# Task 1910 — Two-way portal file exchange (design)

Design for [`.tasks/1910-two-way-portal-file-exchange.md`](../../../../.tasks/1910-two-way-portal-file-exchange.md). Operator decision 2026-07-22: the data portal becomes a two-way folder exchange, reversing the one-way scope decisions of Tasks 1831, 1905 and 1906.

## The problem in one line

Today the portal is two stores that never meet: a flat, destination-less R2 upload area the client writes to, and a read-only device folder index the client browses. Neither can reach the other.

## Manifest state machine

Three new columns on `manifest`: `targetPath` (the exposed folder chosen at upload, empty means untargeted), `devicePath` (where the bytes actually landed, written only after a verified device write, so its presence *is* the proof the move happened), and `deleted` (the client asked to withdraw a file that has already moved).

| State | Columns | Bytes live in | Uploads panel |
|---|---|---|---|
| In transit | `ingested=0`, `devicePath=''` | R2 | shown, downloads from R2 |
| Moved | `ingested=1`, `devicePath` set, R2 object gone | device | shown only when the file is not reachable in the folder tree |
| Withdrawn | `deleted=1` | device, pending removal | hidden |

**One listing rule:** the uploads panel shows a row when the bytes are still in R2, or when the moved file is not reachable in the folder tree. A targeted file therefore leaves the panel and appears in its folder; an untargeted file stays in the panel and downloads through the device. No file is ever listed twice, and no file becomes unreachable.

`devicePath` rather than a boolean is deliberate: a boolean would say a move happened without saying where, and the audit's `unpublishedRouted` check needs the path to compare against the published index.

**Withdrawal ends in row deletion, not a tombstone.** Once the device file is confirmed absent the row is removed. A tombstone would grow the manifest without bound and force every listing read to filter it, and the R2 object is already gone, so the row describes nothing.

### Serving a moved untargeted file

A moved untargeted file sits at `uploads/<ownerId>/<filename>`, and `uploads` is deliberately never exposed (`schema-exposed-dirs.mjs:9-14`). `resolveFetchTarget` refuses any path whose top segment is outside the exposed set (`portal-fetch.ts:182`), and the signed message carries `accountId`, `relPath` and an expiry but no owner (`portal-fetch.ts:56`), so as it stands the device would both refuse the path and be unable to tell whose uploads folder was asked for.

Two link types with two distinct signed messages resolve this:

| Link type | Signed message | Device admission rule |
|---|---|---|
| Exposed-folder file | `accountId \n relPath \n exp` (unchanged) | top segment ∈ exposed set |
| Own-upload file | `accountId \n uploads \n ownerId \n relPath \n exp` | path is exactly `uploads/<signed ownerId>/…` |

The owner is inside the HMAC, so a portal cannot mint a link into another person's upload folder, and the device still decides admission itself rather than trusting the path. `uploads/` gains no exposure to the folder tree; only a link naming its own owner reaches it.

Two message shapes rather than one extended shape, because the exposed-folder message is unchanged and an already-deployed portal never mints the second type. Device and portal redeploy at different times (installer publish versus `site-deploy`), so a single extended message would break every existing download in the window between them.

## Upload key

`ownerId/targetPath/filename`, collapsing to `ownerId/filename` when untargeted.

The target must be in the key. With a flat `ownerId/filename` key, the same filename dropped into two different folders collides on `objectKey UNIQUE`: the upsert would overwrite the first object, reset `ingested`, and the first file would never land. `authorizeKey` (`_lib/authorize.ts:22-32`) already admits deeper keys, rejecting only `..` and a leading separator, so the owner-isolation gate is unchanged by this.

Same owner, same folder, same filename still upserts, which is success criterion 7's replace case.

## Target validation, and where the boundary actually is

A target is legal when it passes the person's grant (`grantAllows`, `_lib/session.ts:87`) **and** carries a folder row (`isDir=1`) in the published `directory` index for that account.

This means you can only drop where you can see, which introduces no new permission concept: the set of legal upload targets is exactly the set of folders already rendered to that person. An empty target is always legal.

**The portal check is convenience; the device check is the boundary.** The pull re-derives the exposed set itself through `resolveExposedDirs`, refusing anything outside it, the same two-ended pattern `portal-fetch.ts` uses for signed downloads. A compromised portal cannot route a file into a folder the device does not expose. The two ends are pinned to agree by a parity test over one shared fixture set, mirroring the existing HMAC parity test.

Refusal fails closed: the file stays pending, the refusal is logged with the exact failing segment, and it is never silently rerouted to the default. A silent reroute would put a client's file somewhere they did not choose and could not find.

## Large uploads

The client slices anything above one part into 25 MiB pieces against an R2 multipart session; files at or below one part keep today's single request. The cap is 1 GiB, checked at session creation against the declared size and again at completion against the summed parts.

Slicing is on the client because the ceiling is the isolate: an upload is read wholly into Function memory (`upload.ts:137`), which is why 25 MiB was chosen in the first place (`upload.ts:8-15`). Parts preserve that bound exactly while removing the total-size limit. Cloudflare's proxied-body cap is not the constraint here; the portal is on Pages, not behind the tunnel that bounds the admin `/data` page (Task 1174).

## Atomic index replace

`directory` gains a `generation` column and a per-account pointer table. The push writes rows at the next generation, flips the pointer in one statement, then deletes superseded rows.

The flip is the atomic point, so a listing racing a push sees the old tree or the new one, never a half-built one. Cleanup afterwards need not be atomic because nothing reads a superseded generation. This supersedes backlog Task 1842, which recorded the delete-then-insert window as an open defect; at 60 second cadence that window would otherwise be hit sixty times more often than at hourly.

## Cadence

The index push becomes a 60 second loop in the admin server's loop registry, beside the pull that already runs there. The scheduling heartbeat's hourly gate and its `auditPortalIndexPush` are retired.

That heartbeat spawn is the path whose own header records it has "never been observed running on a device" (`portal-index-push.mjs:11-13`). Moving the push into the loop registry replaces an unobserved spawn with the mechanism the pull demonstrably uses, and removes the hourly gate that made the client's tree stale by up to two hours. Importing across the tree boundary is precedented: `portal-fetch.ts:22` already imports `schema-exposed-dirs.mjs` from the plugins tree. The script stays runnable standalone.

## Audit

The five-minute `[data-portal-audit]` gains four fields, each answering a failure that emits no event of its own:

- `lastPushAgeSec` — the push stopped running. Healthy under 180.
- `unmovedObjects` — an R2 object survived its own pull, so the move leaked.
- `deletePendingRows` — a withdrawal never reached the device.
- `unpublishedRouted` — a routed file landed somewhere the index never published, so the client cannot see what they uploaded.

Enumeration becomes the union of accounts presenting a config and accounts with a prior push record, reporting `config-absent` rather than falling silent. That is Task 1901's fix, folded in here because this task retires the audit 1901 would have patched.

## Download routing

`/api/download?key=` keeps serving R2 bytes while the row is in transit. Once the row has moved the object is gone, so the same request mints an own-upload signed link and 302s to the device, which is what keeps criterion 5 true without the client learning that the bytes changed home.

## Client

Folder rows and the open listing become drop targets with a drop state. The picker takes multiple files and a multi-file drop uploads each in turn. Upload rows gain `DownloadURL` drag-out, matching what device rows already have (`portal.js:226-233`). Uploads show per-file progress and distinct messages per failure class, replacing today's single "Upload failed." for every status. The page re-reads every 60 seconds while its tab is visible.

Polling was rejected in Tasks 1885 and 1900 on the explicit reasoning that "a poll against an hourly tree is waste". The premise dies with the hourly push: against a 60 second tree the poll is the thing that makes a device-side change visible without the client clicking anything, which is success criterion 4.

## Out of scope

Client deletion or rename of device-authored files the client did not upload; the trust boundary is that a client may withdraw their own file, not destroy a business record. Folder upload and zip download, both directions being files only. Portal-side folder creation, rename and move. The third D1 client (Task 1843). The admin `/data` page and Task 1174. Graph ingestion of pulled files, unchanged from Task 1906.

## Dependency

Live acceptance is blocked until Task 1909 restores the quarantined `data-portal.json` on both sitedesk accounts; the portal has enumerated zero accounts since 2026-07-21T19:16:05Z. Code and unit verification do not depend on it.
