diff --git a/e2e/exomem-home/import.spec.ts b/e2e/exomem-home/import.spec.ts index bf985906..371c4617 100644 --- a/e2e/exomem-home/import.spec.ts +++ b/e2e/exomem-home/import.spec.ts @@ -368,3 +368,167 @@ test("local ciphertext cleanup failure does not block cancellation or reuse a te await rm(folder, { recursive: true, force: true }); } }); + +test("admission grows before encryption and a reloaded upload sends only unrecorded parts", async ({ + page, + context, +}) => { + const folder = await mkdtemp(join(tmpdir(), "exomem-import-growth-resume-")); + try { + const content = "A synthetic source. ".repeat(800); + await writeFile(join(folder, "source.md"), content); + const owner = await createOwner({ + storage: { + usedBytes: 2 * 1024 ** 3, + filesystemBytes: 2 * 1024 ** 3, + observedAt: new Date().toISOString(), + }, + }); + const GiB = 1024 ** 3; + const limits = { + max_members: 500, + reserve_bytes: GiB / 4, + space_factor: 2, + max_storage_gib: 20, + part_bytes: 8192, + max_parts: 10000, + upload_window_seconds: 86400, + import_deadline_seconds: 7200, + import_growth_deadline_seconds: 3600, + }; + await pool.query( + "UPDATE exomem_cloud_cells SET storage_gib=2, import_limits=$2::jsonb WHERE cell_id=$1", + [owner.cellId, JSON.stringify(limits)] + ); + const sent: number[] = []; + let refuseSecond = true; + await context.route("https://storage.example.test/**", async (route) => { + const number = Number(new URL(route.request().url()).pathname.split("/").at(-1)); + const headers = { + "access-control-allow-origin": homeE2eEnvironment().baseUrl, + "access-control-allow-methods": "PUT, OPTIONS", + "access-control-allow-headers": "content-type", + "access-control-expose-headers": "etag", + etag: `"part-${number}"`, + }; + if (route.request().method() === "OPTIONS") { + await route.fulfill({ status: 200, headers }); + return; + } + sent.push(number); + if (number === 2 && refuseSecond) { + refuseSecond = false; + await route.fulfill({ status: 503, headers }); + return; + } + await route.fulfill({ status: 200, headers }); + }); + await signIn(context, owner); + await page.goto("/exomem/home"); + await page.getByRole("button", { name: "Add files…", exact: true }).click(); + let dialog = page.getByRole("dialog"); + await dialog.getByLabel("Folder to add").setInputFiles(folder); + await expect(dialog.getByText("Storage grows to", { exact: true })).toBeVisible(); + const created = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/exomem/cloud/imports" && + response.request().method() === "POST" + ); + await dialog.getByRole("button", { name: "Encrypt and upload", exact: true }).click(); + const admitted = await (await created).json(); + expect(admitted.import.required_storage_bytes).toBe(3 * GiB); + expect(admitted.import.storage_ready).toBe(false); + await expect(dialog.getByText("growing to about", { exact: false }).first()).toBeVisible(); + const importId = admitted.import.import_id; + const saved = await pool.query( + "SELECT cell.storage_gib, request.required_storage_gib, request.ciphertext_sha256 FROM exomem_cloud_cells cell JOIN exomem_cloud_imports request USING(cell_id) WHERE import_id=$1", + [importId] + ); + expect(saved.rows[0]).toEqual({ + storage_gib: 3, + required_storage_gib: 3, + ciphertext_sha256: null, + }); + const prepared = page.waitForResponse((response) => + new URL(response.url()).pathname.endsWith("/prepare-upload") + ); + // The controller and object store are the external boundaries; the browser/API/DB run unchanged. + await pool.query( + "UPDATE exomem_cloud_cells SET observed_storage_capacity_bytes=$2, observed_storage_generation=generation, observed_storage_pvc_uid='synthetic-claim', observed_storage_pvc_version='2', observed_storage_at=now() WHERE cell_id=$1", + [owner.cellId, 3 * GiB] + ); + await pool.query( + "UPDATE exomem_cloud_imports SET recipient=$2, observed_state='key_ready' WHERE import_id=$1", + [importId, await identityToRecipient(await generateIdentity())] + ); + const transport = (await (await prepared).json()).import; + const parts = []; + for ( + let offset = 0, n = 1; + offset < transport.ciphertext_bytes; + offset += limits.part_bytes, n++ + ) + parts.push({ + part_number: n, + url: `https://storage.example.test/resume/${n}`, + part_size_bytes: Math.min(limits.part_bytes, transport.ciphertext_bytes - offset), + }); + await pool.query( + "UPDATE exomem_cloud_imports SET upload_id='synthetic-resume', part_urls=$2::jsonb, urls_expire_at=now()+interval '1 hour' WHERE import_id=$1", + [importId, JSON.stringify(parts)] + ); + await expect(dialog.getByRole("button", { name: "Resume upload" })).toBeVisible(); + expect(sent).toEqual([1, 2]); + const receipt = await page.evaluate(async (id) => { + const root = await ( + await navigator.storage.getDirectory() + ).getDirectoryHandle("exomem-import-uploads"); + for await (const [, directory] of ( + root as unknown as { entries(): AsyncIterable<[string, FileSystemDirectoryHandle]> } + ).entries()) { + try { + return JSON.parse( + await (await (await directory.getFileHandle(`${id}.parts.json`)).getFile()).text() + ); + } catch {} + } + return null; + }, importId); + expect(receipt.import_id).toBe(importId); + expect(receipt.ciphertext_sha256).toBe(transport.ciphertext_sha256); + expect(receipt.parts).toEqual([{ part_number: 1, etag: '"part-1"' }]); + await page.reload(); + await page.getByRole("button", { name: "Add files…", exact: true }).click(); + dialog = page.getByRole("dialog"); + const completed = page.waitForResponse((response) => + new URL(response.url()).pathname.endsWith("/complete") + ); + await dialog.getByRole("button", { name: "Continue upload", exact: true }).click(); + expect((await completed).ok()).toBe(true); + expect(sent.filter((number) => number === 1)).toHaveLength(1); + expect(sent).toEqual([1, 2, ...parts.slice(1).map((part) => part.part_number)]); + const fresh = await pool.query( + "SELECT requested_state, part_etags FROM exomem_cloud_imports WHERE import_id=$1", + [importId] + ); + expect(fresh.rows[0].requested_state).toBe("uploaded"); + expect(fresh.rows[0].part_etags).toEqual( + parts.map(({ part_number }) => ({ part_number, etag: `"part-${part_number}"` })) + ); + await pool.query( + "UPDATE exomem_cloud_imports SET staged_files=1, staged_bytes=$2, observed_state='done' WHERE import_id=$1", + [importId, Buffer.byteLength(content)] + ); + await page.reload(); + await page.getByRole("button", { name: "Add files…", exact: true }).click(); + await expect( + page.getByRole("dialog").getByText("Staged originals", { exact: true }) + ).toBeVisible(); + await expect( + page.getByRole("dialog").getByText("16 kB", { exact: true }) + ).toBeVisible(); + } finally { + await page.close(); + await rm(folder, { recursive: true, force: true }); + } +}); diff --git a/openspec/changes/admit-cloud-imports-against-published-limits/design.md b/openspec/changes/admit-cloud-imports-against-published-limits/design.md index 2c7a39f5..93be1949 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/design.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/design.md @@ -23,7 +23,7 @@ Current state, read from source on 2026-10-26: **Non-Goals:** - Plan-storage entitlement enforcement and the paid-storage baseline. The operator deferred both on 2026-10-26. The consequence is in the risks below. -- Adopted counts in C5. +- Filed counts. The cell's filing view reports them. - Path and name limits. The cell keeps enforcing them, and Home does not preflight them. - A refusal for a vault that is merely nearly full. A stale reading of `used_bytes` must not refuse an import that the cell can hold. @@ -33,6 +33,8 @@ Current state, read from source on 2026-10-26: Cellctl owns the values: it enforces them and renders them into the import Jobs. It writes them to `exomem_cloud_cells.import_limits`. A copy of any number in Substrate would drift, because the storage cap is operator configuration and a local cell's room depends on its node. Substrate branches on no storage-class name. It reads only `max_storage_gib`. +The first delivery publishes limits for Hetzner claims. Cellctl reads the actual claim class and actively writes NULL for local claims, including clearing an older object. Local publication and import growth stay gated on authoritative capacity accounting shared by the local volume consumers and the local rehearsal. The paired Exomem task 1.7 remains open. Substrate keeps its unpublished-limits path: the requirement stays NULL and neither desired nor grown storage changes. + *Rejected: constants in Substrate.* They need a code change each time the operator changes a cap. ### D2. New C5 fields @@ -69,7 +71,7 @@ The cells touch trigger does not change. A write of `import_limits` bumps no gen | `import_deadline_seconds` | How long the import hold may last | | `import_growth_deadline_seconds` | How long cellctl waits for growth before the key exists | -A reader treats a value as unpublished when it is not an object, or when a key that the reader needs is missing or invalid. Admission needs the first four keys for creation and the two part keys for prepare-upload. Home also needs the two deadline keys. +A reader treats a value as unpublished when it is not an object, or when a key that the reader needs is missing or invalid. Admission needs the first four keys for creation and the two part keys for prepare-upload. Home also needs `import_growth_deadline_seconds` for the growth wait. ### D3. Admission at creation @@ -91,24 +93,26 @@ Prepare-upload keeps its flow. On the first report only, it refuses a `ciphertex A pure function in `src/lib/exomem/cloud-import-contract.ts` parses `import_limits` and computes the need and the target. The API and Home import it. Its parameters come only from `import_limits` and the cell's readings. - The growth estimate is `used + space_factor × declared_bytes + reserve_bytes`, in filesystem bytes. -- The growth estimate is scaled by the ratio of `observed_storage_capacity_bytes` (0071) to `filesystem_bytes` (0066). That ratio estimates overhead but cannot decide refusal. -- `used_bytes` and `filesystem_bytes` come from the cell's 0066 usage reading. Its age alone does not discard it; stale usage sizes growth but cannot alone refuse admission. +- The growth estimate is scaled by the ratio of `observed_storage_capacity_bytes` (0071) to `filesystem_bytes` (0066), at least 1. The ratio applies only when the usage reading is at least as recent as the capacity reading; a usage reading from before growth describes the smaller volume and would inflate growth that cannot be undone. That ratio never decides refusal. +- `used_bytes` and `filesystem_bytes` come from the cell's 0066 usage reading. A stale `used_bytes` can under-size growth; the cell's own per-member free-space check stays authoritative. - When `used_bytes` is unknown, the function sizes the import as if the whole current volume were used, with a ratio of 1. - The current size is `max(storage_gib, grown_storage_gib)`. -- The function returns `required_storage_gib = min(ceil(need / GiB), max_storage_gib)`, where one GiB is 1,073,741,824 bytes. +- The cap is the larger of `max_storage_gib` and the current size, so storage that paid storage raised before cellctl republishes is never refused. +- The function returns `required_storage_gib = min(ceil(need / GiB), cap)`, where one GiB is 1,073,741,824 bytes. The `IMPORT_STORAGE_LIMIT` check uses the unscaled lower bound `space_factor × declared_bytes + reserve_bytes`. A filesystem reading can predate a resize, so its capacity ratio never decides refusal. When existing content alone pushes the need above the cap, both the requested growth and the recorded requirement equal the cap. Growth can therefore reach `key_ready`, and the cell's own per-member free-space check decides. Refusing only when necessary keeps a stale `used_bytes` reading from blocking an import that the cell can hold. ### D5. Growth at creation, and `key_ready` waits for it -Admission writes the growth. Cellctl does not mint the import key until the claim has grown, so the owner never encrypts for a volume that cannot hold the archive. The exact wait, its deadline and its local-storage check belong to the Exomem change `publish-cloud-import-limits`. Before every larger local claim request, cellctl checks room and retains the last accepted request when it cannot grow. That includes cleanup and later ordinary reconciliation after a failed import. Desired `storage_gib` stays raised; no claim shrinks. Unknown room waits, while known insufficient room fails the import. The local cutover check must prove this before local import growth ships. +Admission writes growth only when limits are published. Local limits stay NULL until the capacity accounting and rehearsal gates pass. Cellctl does not mint the import key until the claim has grown, so the owner never encrypts for a volume that cannot hold the archive. The exact wait, its deadline and its local-storage check belong to the Exomem change `publish-cloud-import-limits`. Before every larger local claim request, cellctl checks room and retains the last accepted request when it cannot grow. That includes cleanup and later ordinary reconciliation after a failed import. Desired `storage_gib` stays raised; no claim shrinks. Unknown room waits, while known insufficient room fails the import. The local cutover check must prove this before local import growth ships. The raise changes the cell's render digest, so it restarts the cell pod once. Home shows that wait as the cell preparing the import, not as a fault. Home and the status reply show the wait from two derived fields on the import: - `required_storage_bytes` is `required_storage_gib` in bytes, or null. -- `storage_ready` is true when the cell's observed capacity covers `required_storage_bytes` and its storage receipt shows no resize pending. That is the same receipt that paid storage trusts: `observed_storage_capacity_bytes`, with `observed_storage_generation` equal to the cell's generation. +- `storage_ready` is true when the cell's last observed claim capacity covers `required_storage_bytes`. A claim never shrinks, so an unrelated generation change, such as an image rollout, does not turn a covered requirement back into a wait. The field informs Home only; cellctl's own receipt decides `key_ready`. +- Admission writes the cell only when the target is above the current size, `max(storage_gib, grown_storage_gib)`. Raising `storage_gib` below a larger `grown_storage_gib` would bump the generation and restart the cell without growing the claim. No new observed state exists. `key_ready` keeps its meaning. @@ -124,21 +128,21 @@ The three codes join the closed set of import protocol codes. Their error envelo ### D7. Replies -`GET /api/exomem/cloud/imports` and the create reply gain a top-level `limits`, the cell's published object or null. Each import gains `required_storage_bytes`, `storage_ready`, `staged_files` and `staged_bytes`. The zod schemas stay non-strict, so older clients ignore them. +`GET /api/exomem/cloud/imports` and the create reply gain a top-level `limits`, the cell's published object or null. Each reply also carries a nullable `storage` object with the calculator readings: `storage_gib`, `grown_storage_gib`, `observed_storage_capacity_bytes`, `used_bytes`, `filesystem_bytes`, `usage_observed_at` and `observed_storage_at`. Unknown readings remain null. The same owner-scoped query reads these fields and the limits. Home reads the response once for its import and preflight context. Each import gains `required_storage_bytes`, `storage_ready`, `staged_files` and `staged_bytes`. The fields are optional in the zod schemas, so older replies and clients stay readable. ### D8. Home -Home runs the shared function in its preflight, beside the checks from S1. It shows the member count against `max_members`, the storage need against the cap, and "grows to about N GB" when the need exceeds the current size. It refuses to start where admission would refuse. The vault warning from S1 now subtracts `reserve_bytes` from the free space. +Home runs the shared function in its preflight, beside the checks from S1. It shows the selected files against `max_members` less the upload's own series entry, the growth estimate against the cap, and "Storage grows to about N GB" when the estimate exceeds the current size. The browser writes one file entry per selected file plus the series file; implicit parent folders add no TAR members. It refuses to start where admission would refuse, and also when the encrypted copy exceeds `max_parts × part_bytes`. The vault warning from S1 now subtracts `reserve_bytes` from the free space. -With no published limits, Home says "limits not published; the cell checks during import". It substitutes no constant. +With no published limits, Home shows "Import limits: not published", and the cell keeps checking during the import. It substitutes no constant. Home's wait for `key_ready` has no bound of its own. It follows the import's observed state, and it keeps polling at least as long as `import_growth_deadline_seconds`, which it reads from the limits. The CLI waits 7200 seconds per state, so the 60-minute default growth deadline expires first. -### D9. Staged and adopted counts +### D9. Staged counts -Cellctl writes `staged_files` and `staged_bytes` when the import Job succeeds, from the report that the Job already emits. Home shows them instead of the declared counts. An import without them shows "not recorded". +Cellctl records `staged_files` and `staged_bytes` from a valid successful Job report before cleanup deletes its Pods. This immutable pair records a successful staging observation and survives cleanup retries. A later cancellation, failure or expiry can retain that historical observation in the row. Terminal publication still waits for every phase Job and Pod to disappear. -Filing happens later, after C5 reports `done`, so the Job cannot supply the adopted count. Home calls `adoption_studio(action="status", path="_Imports/")` through the existing owner channel. The scoped status returns `adopted_files`, counted by distinct original path across successful outcomes in all matching runs. Repeated and overlapping runs count each original once. Compact rows still carry `source_root` for grouping; Home never sums their totals. An incomplete status, or an older cell without the aggregate, leaves the adopted count unknown. This stays in P7. +Import replies expose the pair only when the import is `done` with no pending cancellation or discard. Otherwise both fields are null. Home shows the recorded staged bytes instead of the declared size. An import without them shows "not recorded". Missing or malformed reports remain unknown and do not block cleanup. ### D10. C4 and C6 @@ -151,18 +155,20 @@ Substrate branches on no storage-class name and holds no copy of the cap, the re - **The raise restarts the cell pod once.** It changes the render digest that the pod template carries. The wait tolerates the restart. - **Hetzner online expansion has no production record.** Every cell class allows it, but nobody has raised a live volume. The Exomem rehearsal raises one real volume and records the capacity, the claim's conditions and any pod restart. The restart that the raise causes lets an expansion that completes only at mount time finish, so the wait holds in either mode. - **A stale `used_bytes` reading.** Admission refuses only what cannot fit in an empty vault. The cell's per-member check stays authoritative. +- **Growth sized from a guess cannot be undone.** With no usage reading, each import sizes growth as if the whole volume were used, so repeated small imports can ratchet a vault toward the cap. A usage reading of any age also sizes growth. The cap bounds the cost. The deferred entitlement decision should settle whether growth needs a usage reading newer than a published bound. +- **Paid storage after import growth.** A paid-storage quote previewed before an import grows the vault applies `GREATEST(grown, target)`, so the owner can pay for GiB they partly received through growth. This belongs to the same deferred entitlement decision. ## Migration Plan Roll out outside the 02:00–05:00 UTC backup window. 1. Deploy migration 0079 and the grants. Undo: leave the columns. Older code ignores them. -2. Roll out the Exomem controller and image through the ordinary cell rollout. Undo: return to the previous controller. The operator can set `import_limits` to NULL to stop growth. -3. Deploy the admission code and the Home flow. Undo: roll the deployment back. Volumes that grew stay grown, which is harmless. +2. Roll out the Exomem controller and image through the ordinary cell rollout. Undo: set `import_limits` to NULL, then return to the previous controller. Once step 3 is live the NULL write is required, because an older controller would mint keys before growth finishes. +3. Deploy the admission code and the Home flow for the Hetzner delivery. Keep local limits NULL until its separate cutover passes. Undo: roll the deployment back. Volumes that grew stay grown, which is harmless. 4. Release the CLI. Undo: pin the earlier CLI. Its fallback works against older servers. ## Proof Plan -The workflow that changes is an owner importing a folder. One check proves it: Home starts an import that needs growth against a disposable PostgreSQL database and a stub controller, then reaches `key_ready` with the larger `storage_gib`. +The workflow that changes is an owner importing a folder. One check proves it: Home starts an import that needs growth against a disposable PostgreSQL database and a stub controller, then reaches `key_ready` with the larger `storage_gib`. After one part is confirmed, a reload resumes at the next unrecorded part. A fresh database read verifies growth and accepted part receipts. -Disposable PostgreSQL tests cover grants, trigger immutability, the update from a controller that omits the new columns, growth, replay, rollback on a conflict, each refusal, unpublished limits and a paid cell above the cap. Component tests cover the Home states. Chrome DevTools inspects the dialog at desktop and phone widths in both themes. Strict OpenSpec validation precedes review. +Disposable PostgreSQL tests cover grants, trigger immutability, the update from a controller that omits the new columns, growth, replay, rollback on a conflict, each refusal, unpublished limits and a paid cell above the cap. The NULL-limits case verifies that required storage stays NULL and that desired storage, grown storage and generation all stay unchanged. Status tests keep historical staged counts private during cleanup and after cancellation or discard, then publish the pair only for successful completion. Component tests cover the Home states. Chrome DevTools inspects the dialog at desktop and phone widths in both themes, on the rebased Home. Strict OpenSpec validation precedes review. diff --git a/openspec/changes/admit-cloud-imports-against-published-limits/proposal.md b/openspec/changes/admit-cloud-imports-against-published-limits/proposal.md index b9f55ed8..a141274a 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/proposal.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/proposal.md @@ -10,7 +10,7 @@ An import has no admission check. Home encrypts and uploads a folder, and only t - Import creation checks the declaration against the published limits in its existing transaction. It refuses with `IMPORT_TOO_MANY_FILES` or `IMPORT_STORAGE_LIMIT`. Prepare-upload refuses an upload that needs more than the published part ceiling with `IMPORT_PARTS_LIMIT`. Each refusal carries a typed `limit`. - When the import needs more storage, creation raises the cell's `storage_gib` within the published cap and records the requirement on the import. The cell reports `key_ready` only after the volume has grown. - The import row records the staged file and byte counts from the import Job's report. -- Home checks a folder against the published limits before it creates an import. It shows the wait while storage grows, and it shows staged and adopted counts. +- Home checks a folder against the published limits before it creates an import. It shows the wait while storage grows, and it shows the staged size. - The follow-ups from the first Home import change (part receipts, error mapping, lock order, the `.gitignore` reason) go into `make-home-import-visible-and-resumable`. ## Decision @@ -20,17 +20,19 @@ Cellctl publishes each cell's effective limits. Admission grows `storage_gib` wi ## Non-goals - Plan-storage entitlement enforcement and the paid-storage baseline. The operator deferred both on 2026-10-26. Growth on demand can therefore take a vault of any plan up to the published cap. -- Adopted counts in C5. Adoption Studio files the staged notes after C5 reports `done`, so Home reads that count through the existing owner channel. +- Filed counts. The cell's filing view, read through its public tools, reports them. ## Capabilities ### Modified Capabilities - `exomem-tenant-control-plane`: Add the C5 limit, requirement and staged fields, the admission order, the refusal codes, and growth at creation. -- `exomem-home`: Check a folder against the published limits, show the wait for growth, and show staged and adopted counts. +- `exomem-home`: Check a folder against the published limits, show the wait for growth, and show the staged size. ## Impact The change adds migration 0079, the grants script, the C5 types, the import API handlers and the Home import dialog. The paired Exomem change `publish-cloud-import-limits` adds the cellctl, image and CLI side. The Cloud control-plane owner reviews the migration and the C5 text. +The Hetzner delivery remains independent. Cellctl actively publishes NULL for actual local claims until authoritative shared capacity accounting and the local rehearsal pass. Local publication and import growth remain open in paired Exomem task 1.7. NULL limits retain legacy admission without a storage requirement or a change to either storage size or generation. + Archive order: the C5 requirements that this change builds on exist only in the active change `add-cloud-vault-import`. The Home requirement that it modifies exists only in `make-home-import-visible-and-resumable`. Archive both of those first. Then archive this change. diff --git a/openspec/changes/admit-cloud-imports-against-published-limits/specs/exomem-home/spec.md b/openspec/changes/admit-cloud-imports-against-published-limits/specs/exomem-home/spec.md index e31bf229..67125916 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/specs/exomem-home/spec.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/specs/exomem-home/spec.md @@ -3,10 +3,10 @@ ### Requirement: Home checks a folder import before it creates one Before Home creates an import, the dialog SHALL show the selection's file count and bytes beside each limit it can measure. It SHALL show the exact encrypted size, the browser's free space for this site, and the vault's free space with the age of that reading. When other accounts' kept copies use this browser's space, it SHALL show their files and bytes and offer to discard them. -When the cell has published its import limits, the dialog SHALL also show the selection's member count against the published maximum, counting each folder as a member. It SHALL show the storage that the import needs against the published cap, computed by the function that admission uses. When the import needs more than the vault's current size, the dialog SHALL say that the vault's storage grows to about that size. -Home SHALL refuse to start in three cases: the browser reports less free space than the exact encrypted size, the member count exceeds the published maximum, or the unscaled empty-vault lower bound exceeds the published cap. A vault reading whose free space, less the published reserve, is below the selection's bytes SHALL produce a warning only, because the reading can be stale. -When the cell has published no limits, the dialog SHALL say that limits are not published and that the cell checks during the import. It SHALL NOT substitute a built-in value for a limit. -By default, the selection SHALL leave out hidden items and the items that the folder's own `.gitignore` files exclude. The dialog SHALL show the files and bytes left out for each reason and SHALL let the owner bring each reason's items back. When a `.gitignore` file is too large to read as rules, the dialog SHALL say that its rules are not applied. +When the cell has published the admission limits (`max_members`, `reserve_bytes`, `space_factor` and `max_storage_gib`), the dialog SHALL also show the selected file count against the published maximum less one, because the archive holds one entry per selected file plus the series file; implicit parent folders SHALL NOT add entries. It SHALL show the growth estimate, which includes the vault's current content, against the cap, both computed by the function that admission uses. When the estimate needs more than the vault's current size, the dialog SHALL say that the vault's storage grows to about the clamped target. Home SHALL need `import_growth_deadline_seconds` only to state the bound on the wait for growth. +Home SHALL refuse to start in four cases: the browser reports less free space than the exact encrypted size, the entry count exceeds the published maximum, the unscaled empty-vault lower bound exceeds the cap, or the exact encrypted size exceeds the published `max_parts × part_bytes`. A vault reading whose free space, less the published reserve, is below the selection's bytes SHALL produce a warning only, because the reading can be stale. With published limits, Home SHALL give that warning only when the growth estimate is above the clamped target, because otherwise the vault grows for the import. +When the cell has published no limits, the dialog SHALL show the import limits as not published, and the cell keeps checking during the import. When Home could not read the import route, it SHALL show them as not read. It SHALL NOT substitute a built-in value for a limit. +By default, the selection SHALL leave out hidden items and the items that the folder's own `.gitignore` files exclude. The dialog SHALL show the files and bytes left out for each reason. It SHALL let the owner bring back the gitignored items; hidden items SHALL stay out. When a `.gitignore` file is too large to read as rules, the dialog SHALL say that its rules are not applied. Home SHALL NOT enforce the cell's path or name limits; the cell keeps enforcing them. #### Scenario: The encrypted copy cannot fit in the browser @@ -18,6 +18,7 @@ Home SHALL NOT enforce the cell's path or name limits; the cell keeps enforcing #### Scenario: The vault reading shows too little free space - **WHEN** the last vault reading has free space, less the published reserve, below the selection's bytes +- **AND** the limits are unpublished, or the growth estimate is above the clamped target - **THEN** the dialog warns with the free bytes, the reserve and the age of the reading - **AND** the owner can still start the import @@ -25,11 +26,12 @@ Home SHALL NOT enforce the cell's path or name limits; the cell keeps enforcing - **WHEN** the owner chooses a folder with hidden items and items that its `.gitignore` files exclude - **THEN** the dialog shows the files and bytes left out for each reason -- **AND** turning a reason on adds its items to the selection and to the declared totals +- **AND** turning the gitignore reason on adds its items to the selection and to the declared totals +- **AND** the hidden items stay out #### Scenario: The folder has more members than the cell accepts -- **WHEN** the selection's files and folders exceed the published maximum +- **WHEN** the selection's archive entries exceed the published maximum - **THEN** the dialog shows both numbers and offers no start - **AND** no import is created @@ -41,15 +43,36 @@ Home SHALL NOT enforce the cell's path or name limits; the cell keeps enforcing #### Scenario: The import cannot fit within the cap -- **WHEN** the unscaled empty-vault lower bound is above the published cap +- **WHEN** the unscaled empty-vault lower bound is above the cap - **THEN** the dialog shows the need and the cap and offers no start +#### Scenario: The encrypted copy exceeds the upload ceiling + +- **WHEN** the exact encrypted size is above the published `max_parts × part_bytes` +- **THEN** the dialog shows both sizes and offers no start +- **AND** no import is created and the vault does not grow + #### Scenario: The cell has published no limits - **WHEN** the cell's limits are unpublished -- **THEN** the dialog says that limits are not published and that the cell checks during the import +- **THEN** the dialog shows the import limits as not published - **AND** it shows no member or storage limit +### Requirement: Home shows the space that staged originals take + +When an adopt import has staged its files on a cell without the filer, Home SHALL show the staged bytes beside the vault's last reading and its age. The staged bytes SHALL come from the count that the import Job reported to C5. When an import has no recorded count, Home SHALL say that the staged size is not recorded, and it SHALL NOT show the declared size in its place. Home SHALL say that filing makes separate copies, and it SHALL offer the existing removal of the staged originals. On a cell with the filer, the filing view takes this place. + +#### Scenario: An import has staged its files + +- **WHEN** an adopt import on a cell without the filer reaches `done` with a recorded staged count +- **THEN** the dialog shows the staged bytes from the Job's report beside the vault reading +- **AND** it offers to remove the staged originals + +#### Scenario: An older import has no recorded count + +- **WHEN** an import finished before the counts existed +- **THEN** Home says the staged size is not recorded and shows no declared size as staged + ## ADDED Requirements ### Requirement: Home shows the wait while the vault's storage grows @@ -76,32 +99,3 @@ When creation or prepare-upload returns `IMPORT_TOO_MANY_FILES`, `IMPORT_STORAGE - **WHEN** admission returns `IMPORT_TOO_MANY_FILES` because the preflight used a stale limit - **THEN** Home shows the reason with the limit and the requested count - **AND** it offers to choose a smaller folder - -### Requirement: Home shows the files an import staged and the files filed from them - -Home SHALL show an import's staged files and bytes from the counts that the import Job reported to C5. It SHALL say so when an import has no recorded counts, and it SHALL NOT show the declared counts in their place. Home SHALL read the adopted count from the scoped Adoption Studio status through the existing owner channel. The status SHALL count distinct original paths with successful filing outcomes beneath the import's staged folder, across all runs. Repeated and overlapping runs SHALL count an original once. Home SHALL NOT sum per-run totals. When the status is unavailable, incomplete or lacks `adopted_files`, Home SHALL show the adopted count as unknown, never as zero. - -#### Scenario: An import has staged its files - -- **WHEN** an adopt import reaches `done` with recorded staged counts -- **THEN** Home shows the staged files and bytes from the Job's report - -#### Scenario: An older import has no recorded counts - -- **WHEN** an import finished before the counts existed -- **THEN** Home says the staged counts are not recorded and shows no declared count as staged - -#### Scenario: Some staged files are filed - -- **WHEN** the scoped status reports complete adopted counts for the staged folder -- **THEN** Home shows its distinct-original count - -#### Scenario: The same original appears in several runs - -- **WHEN** repeated or overlapping runs successfully file the same staged original -- **THEN** the adopted count includes that original once - -#### Scenario: Adoption Studio cannot be read - -- **WHEN** the status call fails, is incomplete, or carries no `adopted_files` -- **THEN** Home shows the adopted count as unknown diff --git a/openspec/changes/admit-cloud-imports-against-published-limits/specs/exomem-tenant-control-plane/spec.md b/openspec/changes/admit-cloud-imports-against-published-limits/specs/exomem-tenant-control-plane/spec.md index 6097f6a7..ac50f252 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/specs/exomem-tenant-control-plane/spec.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/specs/exomem-tenant-control-plane/spec.md @@ -2,7 +2,7 @@ ### Requirement: Cells publish their import limits in C5 -Cellctl SHALL write `exomem_cloud_cells.import_limits` for each live cell, and SHALL rewrite it only when its content changes. The value SHALL be a JSON object, or NULL when the cell has published nothing. Its keys SHALL be `max_members`, `reserve_bytes`, `space_factor`, `max_storage_gib`, `part_bytes`, `max_parts`, `upload_window_seconds`, `import_deadline_seconds` and `import_growth_deadline_seconds`, each a positive integer. Readers SHALL ignore keys they do not use. A reader SHALL treat the value as unpublished when it is not an object, or when a key that the reader needs is missing or invalid. `max_storage_gib` SHALL be at least the cell's current size, `max(storage_gib, grown_storage_gib)`. Only cellctl SHALL write the column, and a write SHALL NOT change the cell's generation. +Cellctl SHALL write `exomem_cloud_cells.import_limits` only for a live cell whose claim class has passed its import-growth cutover check, and SHALL actively write NULL for every other cell, clearing any previously published object. It SHALL rewrite the value only when its content changes. The value SHALL be a JSON object, or NULL when the cell has published nothing. Its keys SHALL be `max_members`, `reserve_bytes`, `space_factor`, `max_storage_gib`, `part_bytes`, `max_parts`, `upload_window_seconds`, `import_deadline_seconds` and `import_growth_deadline_seconds`, each a positive integer. Readers SHALL ignore keys they do not use. A reader SHALL treat the value as unpublished when it is not an object, or when a key that the reader needs is missing or invalid. `max_storage_gib` SHALL be at least the cell's current size, `max(storage_gib, grown_storage_gib)`. Only cellctl SHALL write the column, and a write SHALL NOT change the cell's generation. #### Scenario: Cellctl publishes a changed limit @@ -26,9 +26,15 @@ Cellctl SHALL write `exomem_cloud_cells.import_limits` for each live cell, and S - **WHEN** `import_limits` is not an object, or lacks a key that the reader needs - **THEN** the reader treats the limits as unpublished and applies no limit of its own +#### Scenario: Local import growth has not passed its cutover + +- **WHEN** the actual claim class is local and authoritative shared capacity accounting or the local rehearsal remains incomplete +- **THEN** cellctl writes `import_limits` NULL, including replacing an earlier object +- **AND** legacy admission leaves `required_storage_gib` NULL, with desired storage, grown storage and generation unchanged + ### Requirement: Import records carry the storage they require and the files they staged -C5 SHALL add `required_storage_gib` (integer greater than 0), `staged_files` and `staged_bytes` (not negative) to `exomem_cloud_imports`. Each column SHALL be nullable, and `staged_files` and `staged_bytes` SHALL be both set or both NULL. Substrate SHALL write `required_storage_gib` at INSERT only. Cellctl SHALL write `staged_files` and `staged_bytes` from the import Job's report when the Job succeeds. The touch trigger SHALL make `required_storage_gib` immutable, and SHALL make each staged column immutable once set. The gateway SHALL have no access to these columns. The migration SHALL be additive, so a deployed cellctl that does not know the columns keeps working. +C5 SHALL add `required_storage_gib` (integer greater than 0), `staged_files` and `staged_bytes` (not negative) to `exomem_cloud_imports`. Each column SHALL be nullable, and `staged_files` and `staged_bytes` SHALL be both set or both NULL. Substrate SHALL write `required_storage_gib` at INSERT only. Cellctl SHALL persist a valid successful Job report's staged counts before cleanup removes the reporting Pods. The pair SHALL remain a historical staging observation if later cancellation, failure or expiry prevents successful completion. Missing or malformed reports SHALL leave both counts unknown without blocking cleanup. The touch trigger SHALL make `required_storage_gib` immutable, and SHALL make each staged column immutable once set. The gateway SHALL have no access to these columns. The migration SHALL be additive, so a deployed cellctl that does not know the columns keeps working. #### Scenario: A role writes outside its columns @@ -59,11 +65,11 @@ Creation SHALL run these steps in order inside its existing transaction, with th 3. When the limits are unpublished, insert the import with `required_storage_gib` NULL and reply `limits: null`. 4. When `declared_files` exceeds `max_members`, refuse with 422 `IMPORT_TOO_MANY_FILES`. 5. When `space_factor × declared_bytes + reserve_bytes` exceeds the cap in bytes, refuse with 422 `IMPORT_STORAGE_LIMIT`. -6. Raise `storage_gib` with `GREATEST(storage_gib, required_storage_gib)`, then insert the import with that requirement. +6. When `required_storage_gib` is above the current size, raise `storage_gib` with `GREATEST(storage_gib, required_storage_gib)`. Then insert the import with that requirement. -The storage need SHALL be `used + space_factor × declared_bytes + reserve_bytes`, scaled by the ratio of `observed_storage_capacity_bytes` to `filesystem_bytes`. The cell's `used_bytes` and `filesystem_bytes` readings come from migration 0066; its observed capacity comes from migration 0071. A recorded usage reading SHALL count regardless of its age. When `used_bytes` is unknown, the need SHALL treat the whole current volume as used with a ratio of 1. The ratio SHALL affect only the growth estimate. The necessary-only refusal SHALL use the unscaled lower bound `space_factor × declared_bytes + reserve_bytes`, so a filesystem reading from before growth cannot refuse an import that fits. +The storage need SHALL be `used + space_factor × declared_bytes + reserve_bytes`, scaled by the ratio of `observed_storage_capacity_bytes` to `filesystem_bytes`. The cell's `used_bytes` and `filesystem_bytes` readings come from migration 0066; its observed capacity comes from migration 0071. Each timestamp SHALL be the time its reading was measured, not the time it was written. The ratio SHALL apply only when the usage reading is at least as recent as the capacity reading (`usage_observed_at` ≥ `observed_storage_at`), and SHALL never be below 1; otherwise the ratio SHALL be 1, because a filesystem reading from before growth describes a smaller volume. When `used_bytes` is unknown, the need SHALL treat the whole current volume as used with a ratio of 1. The ratio SHALL affect only the growth estimate. The necessary-only refusal SHALL use the unscaled lower bound `space_factor × declared_bytes + reserve_bytes`, so a filesystem reading from before growth cannot refuse an import that fits. -One pure function SHALL compute the need and `required_storage_gib = min(ceil(need / GiB), max_storage_gib)`, where one GiB is 1,073,741,824 bytes. The API and Home SHALL both use that function with the cell readings and the published limits. The recorded requirement SHALL be the clamped target, never the unclamped need. +The cap SHALL be the larger of `max_storage_gib` and the cell's current size, because paid storage can raise the size before cellctl republishes. One pure function SHALL compute the need and `required_storage_gib = min(ceil(need / GiB), cap)`, where one GiB is 1,073,741,824 bytes. The API and Home SHALL both use that function with the cell readings and the published limits. The recorded requirement SHALL be the clamped target, never the unclamped need. #### Scenario: A client retries a creation @@ -101,10 +107,10 @@ One pure function SHALL compute the need and `required_storage_gib = min(ceil(ne #### Scenario: Usage was recorded before a resize -- **WHEN** a cell grew from 2 GiB to 20 GiB and still reports its earlier 1.9 GiB filesystem reading +- **WHEN** a cell grew from 2 GiB to 20 GiB under a 100 GiB cap, and its usage reading of 1 GiB used on a 1.9 GiB filesystem is older than its capacity reading - **AND** the import holds 1 GiB, with space factor 2 and reserve 256 MiB -- **THEN** admission compares the unscaled 2.25 GiB lower bound with the 20 GiB cap and accepts -- **AND** the stale ratio can increase only the clamped growth estimate +- **THEN** admission accepts and computes the need with a ratio of 1, about 3.25 GiB +- **AND** `storage_gib` stays at 20 GiB #### Scenario: A concurrent import holds the open slot @@ -113,7 +119,7 @@ One pure function SHALL compute the need and `required_storage_gib = min(ceil(ne ### Requirement: Admission grows storage within the published cap before the key exists -Admission SHALL raise `storage_gib` with `GREATEST(storage_gib, required_storage_gib)`, so it SHALL never lower a size and SHALL never exceed `max_storage_gib`. It SHALL record the clamped target as `required_storage_gib`. Cellctl SHALL NOT write `recipient` or report `key_ready` for an import that has a `required_storage_gib` until the cell's observed capacity covers it with no resize pending. While it waits, cellctl SHALL leave the cell mounted and running. A brief cell restart that the raise causes SHALL count as waiting, not as failure. When the claim has not grown within `import_growth_deadline_seconds` of the import's creation, cellctl SHALL fail the import with `IMPORT_STORAGE_UNAVAILABLE`. For a local-storage cell, cellctl SHALL check the node's room again before it reports `key_ready`. It SHALL fail the import with `IMPORT_STORAGE_NO_ROOM` when the node cannot hold the size. Before any larger local claim request, cellctl SHALL check the node's room. If room is unavailable, it SHALL retain the last accepted claim request, including during cleanup and later reconciliation. The desired `storage_gib` SHALL stay raised, and cellctl SHALL NOT lower a claim. Unknown room SHALL leave growth waiting until its deadline. Known insufficient room SHALL fail the import with `IMPORT_STORAGE_NO_ROOM`. Local import growth SHALL ship only after this behavior passes the local cutover check. +Admission SHALL raise `storage_gib` with `GREATEST(storage_gib, required_storage_gib)`, so it SHALL never lower a size and SHALL never exceed the cap. It SHALL record the clamped target as `required_storage_gib`. Cellctl SHALL NOT write `recipient` or report `key_ready` for an import that has a `required_storage_gib` until the cell's observed capacity covers it with no resize pending. While it waits, cellctl SHALL leave the cell mounted and running. A brief cell restart that the raise causes SHALL count as waiting, not as failure. When the claim has not grown within `import_growth_deadline_seconds` of the import's creation, cellctl SHALL fail the import with `IMPORT_STORAGE_UNAVAILABLE`. For a local-storage cell, cellctl SHALL check the node's room again before it reports `key_ready`. It SHALL fail the import with `IMPORT_STORAGE_NO_ROOM` when the node cannot hold the size. Before any larger local claim request, cellctl SHALL check the node's room. If room is unavailable, it SHALL retain the last accepted claim request, including during cleanup and later reconciliation. The desired `storage_gib` SHALL stay raised, and cellctl SHALL NOT lower a claim. Unknown room SHALL leave growth waiting until its deadline. Known insufficient room SHALL fail the import with `IMPORT_STORAGE_NO_ROOM`. A local claim class SHALL pass its cutover check only when capacity accounting shared by all local volume consumers proves this behavior; until then its cells publish NULL, as the publication requirement states. #### Scenario: The volume grows @@ -164,7 +170,12 @@ The error envelope of `IMPORT_TOO_MANY_FILES`, `IMPORT_STORAGE_LIMIT` and `IMPOR ### Requirement: Import replies carry the limits, the growth state and the staged counts -`GET /api/exomem/cloud/imports` and the creation reply SHALL carry `limits`, the cell's published object or null, beside `import`. Each import SHALL carry `required_storage_bytes` (null when not required), `storage_ready` (null when not required), `staged_files` and `staged_bytes` (null when not recorded). `storage_ready` SHALL be true only when the cell's observed capacity covers `required_storage_bytes` and its storage receipt shows no resize pending. Replies SHALL stay readable to clients that predate these fields. +`GET /api/exomem/cloud/imports` and the creation reply SHALL carry `limits`, the cell's published object or null, beside `import`. The reply SHALL also carry nullable `storage` with `storage_gib`, `grown_storage_gib`, `observed_storage_capacity_bytes`, `used_bytes`, `filesystem_bytes`, `usage_observed_at` and `observed_storage_at`, read through the same owner scope. Unknown readings SHALL remain null. Home SHALL use these readings for the shared calculation. Each import SHALL carry `required_storage_bytes` (null when not required), `storage_ready` (null when not required), `staged_files` and `staged_bytes` (null when not recorded). Replies SHALL expose staged counts only when `observed_state` is `done` without pending cancellation or discard; otherwise both SHALL be null. `storage_ready` SHALL be true only when the cell's last observed claim capacity covers `required_storage_bytes`. A claim never shrinks, so a covering reading SHALL stay valid across later generation changes. `storage_ready` informs Home only; cellctl's own storage receipt decides `key_ready`. Replies SHALL stay readable to clients that predate these fields. + +#### Scenario: Cancellation follows successful staging + +- **WHEN** the row holds staged counts and newer cancellation or discard intent prevents successful completion +- **THEN** the row retains its immutable historical counts, but the import reply returns both counts as null #### Scenario: An import waits for growth @@ -175,3 +186,9 @@ The error envelope of `IMPORT_TOO_MANY_FILES`, `IMPORT_STORAGE_LIMIT` and `IMPOR - **WHEN** a client that predates these fields reads an import - **THEN** it ignores the new fields and reads the others as before + +#### Scenario: Home reads the admission context + +- **WHEN** the owner reads imports before creating one +- **THEN** the reply carries the cell's published limits and calculator readings even when no import exists +- **AND** a reply that omits the new optional fields still parses diff --git a/openspec/changes/admit-cloud-imports-against-published-limits/tasks.md b/openspec/changes/admit-cloud-imports-against-published-limits/tasks.md index a3dbd419..ecbd46db 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/tasks.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/tasks.md @@ -2,22 +2,23 @@ The packets P1 to P7 below match the paired Exomem change `publish-cloud-import- ## 1. C5 columns, grants and trigger (P1) — Control-plane review -- [ ] 1.1 Add migration 0079 with `import_limits`, `required_storage_gib`, `staged_files` and `staged_bytes`, their CHECKs, and the `CREATE OR REPLACE` of `exomem_cloud_imports_touch` for immutability. Add the grants, each guarded on its column, to `scripts/exomem-cloud-grants.sql`. Add the C5 types to `cloud-import-contract.ts`. Verify: disposable PostgreSQL tests for each grant, for each immutability rule and for both-or-neither staged counts. -- [ ] 1.2 Prove that an update from a controller that omits the new columns still passes the trigger. Verify: one integration case that updates `observed_state` and `part_urls` under the cellctl role, and the deployed cellctl's own tests run against the 0079 ref. -- [ ] 1.3 Deliver P1 as its own pull request. Verify: the pull request records the grants and the trigger test output for the control-plane owner. +- [x] 1.1 Add migration 0079 with `import_limits`, `required_storage_gib`, `staged_files` and `staged_bytes`, their CHECKs, and the `CREATE OR REPLACE` of `exomem_cloud_imports_touch` for immutability. Add the grants, each guarded on its column, to `scripts/exomem-cloud-grants.sql`. Add the C5 types to `cloud-import-contract.ts`. Verify: disposable PostgreSQL tests for each grant, for each immutability rule and for both-or-neither staged counts. Merged as Substrate PR #291. +- [ ] 1.2 Prove that an update from a controller that omits the new columns still passes the trigger. The integration case under the cellctl role merged with #291. Verify: the deployed cellctl's own tests run against the 0079 ref. +- [x] 1.3 Deliver P1 as its own pull request (#291). Verify: the pull request records the grants and the trigger test output for the control-plane owner. ## 2. Admission, refusals and replies (P4) -- [ ] 2.1 Add the pure function to `cloud-import-contract.ts`: parse limits, compute the need and clamped `required_storage_gib`, and build each refusal's `limit`. Verify: cases for unpublished or invalid limits, unknown usage, a stale capacity ratio that cannot refuse admission, growth clamped below need, and a cell above the cap. -- [ ] 2.2 Run the admission steps in `cloud-imports.ts` and add `limit` to the error envelope in `errors.ts`. Verify: PostgreSQL integration tests for growth with `GREATEST`, replay with no check and no growth, rollback on an open-slot conflict, each refusal, and unpublished limits. -- [ ] 2.3 Refuse `IMPORT_PARTS_LIMIT` on the first prepare-upload report only. Verify: an integration case for the first report, and one for a replay that returns the stored import. -- [ ] 2.4 Add `limits`, `required_storage_bytes`, `storage_ready`, `staged_files` and `staged_bytes` to the import routes and zod schemas. Verify: a schema test that parses a reply without the new fields, and an integration case for `storage_ready` while the claim is smaller than required. +- [x] 2.1 Add the pure function to `cloud-import-contract.ts`: parse limits, compute the need and clamped `required_storage_gib`, and build each refusal's `limit`. Verify: cases for unpublished or invalid limits, unknown usage, a stale capacity ratio that cannot refuse admission, growth clamped below need, and a cell above the cap. +- [x] 2.2 Run the admission steps in `cloud-imports.ts` and add `limit` to the error envelope in `errors.ts`. Verify: PostgreSQL integration tests for growth with `GREATEST`, replay with no check and no growth, rollback on an open-slot conflict, each refusal, and unpublished limits. +- [x] 2.3 Refuse `IMPORT_PARTS_LIMIT` on the first prepare-upload report only. Verify: an integration case for the first report, and one for a replay that returns the stored import. +- [x] 2.4 Add `limits`, `required_storage_bytes`, `storage_ready`, `staged_files` and `staged_bytes` to the import routes and zod schemas. Verify: a schema test that parses a reply without the new fields, and integration cases for `storage_ready` while the claim is smaller than required, generation receipt changes, and staged counts hidden during cleanup or newer cancellation or discard. ## 3. Home preflight and states (P4) -- [ ] 3.1 Run the shared function in the Home preflight: member count, storage need against the cap, the grows-to notice, the reserve in the vault warning, and the unpublished-limits message. Verify: component tests for each state in the Home requirement. -- [ ] 3.2 Show the wait for growth, read the key-ready bound from `import_growth_deadline_seconds`, and map the three refusal codes and both growth failures to fixed reasons in the `STOPS` table. Verify: component tests; the Home dialog works in Chrome at desktop and phone widths in both themes against a synthetic API. -- [ ] 3.3 Show the staged counts from the Job's report and "not recorded" for older imports. Verify: a component test with and without counts. +- [x] 3.1 Run the shared function in the Home preflight: member count, storage need against the cap, the grows-to notice, the reserve in the vault warning, and the unpublished-limits message. Verify: component tests for each state in the Home requirement. +- [x] 3.2 Show the wait for growth, read the key-ready bound from `import_growth_deadline_seconds`, and map the three refusal codes and both growth failures to fixed reasons in the `STOPS` table. Verify: component tests; the Home dialog works in Chrome at desktop and phone widths in both themes against a synthetic API. +- [x] 3.3 Show the staged bytes from the Job's report, and "not recorded" for older imports. The filing view shows the file counts. Verify: a Home test with and without a recorded count. +- [x] 3.4 Refuse an encrypted copy above the published `max_parts × part_bytes` in the preflight, before the vault grows. Verify: a component test in which no import is created. ## 4. Browser follow-ups (P5) @@ -25,11 +26,13 @@ The follow-ups from the first Home import change live in `make-home-import-visib ## 5. Adopted count (P7) -- [ ] 5.1 Read scoped `adopted_files` through `cloud-home-mcp.ts`; show "unknown" for unavailable, incomplete or older status. Verify: a Home test covers a distinct-original count and an unknown result. -- [ ] 5.2 Wait for the Exomem scoped status aggregate (its task 4.1). Verify: repeated and overlapping runs contribute each original once on a cell running that version. +- [x] 5.1 ~~Read scoped `adopted_files` through `cloud-home-mcp.ts`.~~ Superseded: Home reads each import's filing through the cell's public `inspect_memory` `imports.status`, which reports filed, duplicate and left-out counts, and a cell refuses the private tool this task named. +- [x] 5.2 ~~Wait for the Exomem scoped status aggregate.~~ Superseded with 5.1 by the filing view. ## 6. Delivery - [ ] 6.1 Complete independent review of the integrated pull requests, with the C4 verdict, and the required checks. - [ ] 6.2 Roll out in this order, outside the 02:00–05:00 UTC window: 1. migration 0079 and grants; 2. the Exomem controller and image; 3. P4 and P5; 4. the CLI. Undo: leave the columns; return to the previous controller and set `import_limits` to NULL; roll the Substrate deployment back, because grown volumes stay grown; pin the earlier CLI. - [ ] 6.3 Archive `add-cloud-vault-import` and `make-home-import-visible-and-resumable` first. Then synchronize this change into the canonical specs and archive it with `openspec archive`. Verify: `openspec validate --all --strict` passes before and after the archive. + +- [x] 6.4 ~~Complete the local cutover only after paired Exomem task 1.7 supplies authoritative shared capacity accounting and the local rehearsal passes. Until then, cellctl actively publishes NULL for the actual local claim class. Verify: NULL-limits admission leaves its requirement NULL and both storage sizes and generation unchanged. The Hetzner delivery remains independent.~~ Deferred: the open task 1.7 of the paired Exomem change `publish-cloud-import-limits` owns the local cutover, and cellctl publishes NULL for local claims until then. diff --git a/openspec/changes/make-home-import-visible-and-resumable/tasks.md b/openspec/changes/make-home-import-visible-and-resumable/tasks.md index 2ec5e33b..05101238 100644 --- a/openspec/changes/make-home-import-visible-and-resumable/tasks.md +++ b/openspec/changes/make-home-import-visible-and-resumable/tasks.md @@ -18,8 +18,8 @@ Complete these before the independent review in 2.1 closes, so that it reviews the final change. They ship in the same pull request as `admit-cloud-imports-against-published-limits`. -- [ ] 3.1 Persist the part receipts. Write each part's number and ETag beside the kept copy after a 2xx answer, key the record by import ID and ciphertext SHA-256, and send only unrecorded parts after a reload. Remove a receipt with its copy. Verify: an upload test in which a reload after some parts resumes at the next part and sends no recorded part, and a receipt with another SHA-256 is ignored. -- [ ] 3.2 Move the TypeError to `CONNECTION` mapping from `cloud-import-stop.ts` to the fetch call sites, and map any other TypeError to `STOPPED`. Verify: a test in which a fetch TypeError stops with `CONNECTION` and a TypeError from our own code stops with `STOPPED`. -- [ ] 3.3 Take the import's Web Lock after the status read in the sweep, and hold it only while the copy is removed. Verify: a sweep test in which a tab that resumes during a slow status read is not refused with `OTHER_TAB`, and a copy of an import that still waits for an upload stays. -- [ ] 3.4 Replace the `.gitignore` size cap's comment in `cloud-import-selection.ts` with its own reason, browser memory, and remove "keep in step" with the CLI. Verify: the comment names the memory bound, and the existing selection tests pass. +- [x] 3.1 Persist the part receipts. Write each part's number and ETag beside the kept copy after a 2xx answer, key the record by import ID and ciphertext SHA-256, and send only unrecorded parts after a reload. Remove a receipt with its copy. Verify: an upload test in which a reload after some parts resumes at the next part and sends no recorded part, and a receipt with another SHA-256 is ignored. +- [x] 3.2 Move the TypeError to `CONNECTION` mapping from `cloud-import-stop.ts` to the fetch call sites, and map any other TypeError to `STOPPED`. Verify: a test in which a fetch TypeError stops with `CONNECTION` and a TypeError from our own code stops with `STOPPED`. +- [x] 3.3 Take the import's Web Lock after the status read in the sweep, and hold it only while the copy is removed. Verify: a sweep test in which a tab that resumes during a slow status read is not refused with `OTHER_TAB`, and a copy of an import that still waits for an upload stays. +- [x] 3.4 Replace the `.gitignore` size cap's comment in `cloud-import-selection.ts` with its own reason, browser memory, and remove "keep in step" with the CLI. Verify: the comment names the memory bound, and the existing selection tests pass. diff --git a/openspec/strict-baseline.json b/openspec/strict-baseline.json index 79f0b5f2..2a1cc895 100644 --- a/openspec/strict-baseline.json +++ b/openspec/strict-baseline.json @@ -13,7 +13,6 @@ "too-long change/add-photography-gallery-and-aurora-hero/homepage-hero :: Continuity-led homepage narrative", "too-long change/add-photography-gallery-and-aurora-hero/homepage-hero :: Energy-resolving motion system", "too-long change/add-photography-gallery-and-aurora-hero/photography-gallery :: Accessible full-screen viewer", - "too-long change/admit-cloud-imports-against-published-limits/exomem-home :: Home shows the files an import staged and the files filed from them", "too-long change/admit-cloud-imports-against-published-limits/exomem-home :: Home shows the wait while the vault's storage grows", "too-long change/admit-cloud-imports-against-published-limits/exomem-tenant-control-plane :: Admission grows storage within the published cap before the key exists", "too-long change/admit-cloud-imports-against-published-limits/exomem-tenant-control-plane :: Cells publish their import limits in C5", diff --git a/src/app/exomem/home/__tests__/home-import.test.tsx b/src/app/exomem/home/__tests__/home-import.test.tsx index c2cc9468..9c30dfef 100644 --- a/src/app/exomem/home/__tests__/home-import.test.tsx +++ b/src/app/exomem/home/__tests__/home-import.test.tsx @@ -85,6 +85,8 @@ function staged(api: ReturnType) { error_code: null, ciphertext_sha256: "0".repeat(64), ciphertext_bytes: 4_300_000, + staged_files: 41, + staged_bytes: 4_200_000, created_at: "2026-11-25T09:00:00Z", updated_at: "2026-11-25T09:05:00Z", }); @@ -97,6 +99,8 @@ async function home(options: { labels?: Record; /** The tab starts hidden, as a tab opened in the background does. */ hidden?: boolean; + /** Published limits and storage readings that the import route adds to each reply. */ + context?: Record; }) { const dom = new JSDOM('
', { url: "http://localhost/exomem/home", @@ -127,7 +131,15 @@ async function home(options: { document: dom.window.document, navigator: { userAgent: "synthetic", storage: browser.storage }, IS_REACT_ACT_ENVIRONMENT: true, - fetch: options.api.receive, + fetch: async (input: RequestInfo | URL, init?: RequestInit) => { + const response = await options.api.receive(input, init); + if (!String(input).startsWith("/api/exomem/cloud/imports") || !options.context) + return response; + return Response.json( + { ...(await response.json()), ...options.context }, + { status: response.status } + ); + }, })) { originals.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); @@ -162,8 +174,8 @@ async function home(options: { [...dom.window.document.querySelectorAll("button")].find( (element) => element.textContent === label ); - const until = async (ready: () => unknown, what: string) => { - for (let waited = 0; waited < 5_000; waited += 20) { + const until = async (ready: () => unknown, what: string, timeout = 5_000) => { + for (let waited = 0; waited < timeout; waited += 20) { if (ready()) return; await act(() => new Promise((resolve) => setTimeout(resolve, 20))); } @@ -222,7 +234,10 @@ it("closing the dialog keeps the import running, and a pause shows how to resume await page.click("Add files…"); await page.click("Pause"); await page.until( - () => page.text().includes("Paused. Parts already uploaded from this page are kept."), + () => + page + .text() + .includes("Paused. Parts already uploaded from this page are kept."), "the paused state" ); assert.ok(page.button("Resume upload")); @@ -385,6 +400,244 @@ it("a selection whose encrypted copy cannot fit in this browser is refused befor assert.ok(!api.requests.some(({ body }) => body?.kind === "adopt")); }); +const GiB = 1024 ** 3; +const published = { + max_members: 500, + reserve_bytes: GiB / 4, + space_factor: 2, + max_storage_gib: 20, + import_growth_deadline_seconds: 3600, +}; +const readings = { + storage_gib: 2, + grown_storage_gib: null, + used_bytes: 2 * GiB, + filesystem_bytes: 2 * GiB, + observed_storage_capacity_bytes: 2 * GiB, + usage_observed_at: "2026-01-01T00:00:00Z", +}; + +it("preflight admits a selection at the entry limit, leaving one entry for the series file", async () => { + const api = importApiDouble("unused"); + const page = await home({ + api, + context: { limits: { ...published, max_members: 2 }, storage: readings }, + }); + await page.click("Add files…"); + await page.choose(folder("research", 1), "Folder to add"); + await page.until(() => page.text().includes("Files1 of 1"), "the files against the limit"); + assert.ok(page.button("Encrypt and upload")); + assert.equal(api.rows.size, 0); +}); + +it("preflight refuses a selection with more entries than the limit and leaves no import", async () => { + const api = importApiDouble("unused"); + const page = await home({ + api, + context: { limits: { ...published, max_members: 2 }, storage: readings }, + }); + await page.click("Add files…"); + await page.choose(folder("research", 2), "Folder to add"); + await page.until(() => page.text().includes("more files than this vault accepts"), "the refusal"); + assert.equal(page.button("Encrypt and upload"), undefined); + assert.equal(api.rows.size, 0); +}); + +it("preflight shows the growth that covers the need and no add-storage warning", async () => { + const page = await home({ + api: importApiDouble("unused"), + context: { limits: published, storage: readings }, + }); + await page.click("Add files…"); + await page.choose(folder("research", 1), "Folder to add"); + await page.until(() => page.text().includes("Storage grows to"), "the storage growth estimate"); + assert.ok(!page.text().includes("Add storage first")); + assert.ok(page.button("Encrypt and upload")); +}); + +it("preflight warns after the reserve when growth stops at the cap below the need, without refusing", async () => { + const page = await home({ + api: importApiDouble("unused"), + context: { limits: { ...published, max_storage_gib: 2 }, storage: readings }, + }); + await page.click("Add files…"); + await page.choose(folder("research", 1), "Folder to add"); + await page.until(() => page.text().includes("Add storage first"), "the space warning"); + assert.match(page.text(), /free after the .* reserve/); + assert.ok(!page.text().includes("Storage grows to")); + assert.ok(page.button("Encrypt and upload")); +}); + +it("preflight refuses an encrypted copy above the published multipart ceiling before any growth", async () => { + const api = importApiDouble("unused"); + const page = await home({ + api, + context: { limits: { ...published, part_bytes: 1024, max_parts: 1 }, storage: readings }, + }); + await page.click("Add files…"); + await page.choose(folder("research", 1), "Folder to add"); + await page.until(() => page.text().includes("upload limit"), "the parts refusal"); + assert.equal(page.button("Encrypt and upload"), undefined); + assert.equal(api.rows.size, 0); +}); + +it("preflight refuses a need above the storage cap and leaves no import", async () => { + const api = importApiDouble("unused"); + const page = await home({ + api, + context: { limits: { ...published, space_factor: GiB, max_storage_gib: 1 }, storage: readings }, + }); + await page.click("Add files…"); + await page.choose(folder("research", 1), "Folder to add"); + await page.until(() => page.text().includes("cannot fit within"), "the storage refusal"); + assert.equal(page.button("Encrypt and upload"), undefined); + assert.equal(api.rows.size, 0); +}); + +it("unpublished limits stay visibly unknown while a selection remains available", async () => { + const page = await home({ api: importApiDouble("unused") }); + await page.click("Add files…"); + await page.choose(folder("research", 1), "Folder to add"); + await page.until( + () => page.text().includes("Import limitsnot published"), + "the unpublished limit notice" + ); + assert.ok(page.button("Encrypt and upload")); +}); + +it("an upload that waits for growth shows the wait in the dialog, not a stalled encryption", async () => { + const api = importApiDouble("unused"); + const receive = api.receive; + // The admitted import needs growth, so the cell holds its key until the vault has grown. + api.receive = async (input, init) => { + const response = await receive(input, init); + if (String(input) !== "/api/exomem/cloud/imports" || init?.method !== "POST") return response; + const { import: row } = await response.json(); + Object.assign(api.rows.get(row.import_id)!, { + observed_state: "pending", + recipient: null, + required_storage_bytes: 3 * GiB, + storage_ready: false, + }); + return Response.json({ import: api.rows.get(row.import_id) }); + }; + const page = await home({ api, context: { limits: published, storage: readings } }); + await page.click("Add files…"); + await page.choose(folder("research", 1), "Folder to add"); + await page.click("Encrypt and upload"); + await page.until(() => page.text().includes("growing to about"), "the growth wait"); + assert.ok(page.text().includes("Growth time limit")); + assert.ok(page.text().includes("60 minutes")); +}); + +it("with the dialog closed, the row keeps reading a growth wait until the vault has grown", async () => { + const api = importApiDouble("unused"); + const importId = crypto.randomUUID(); + const row = { + import_id: importId, + kind: "adopt", + declared_files: 2, + declared_bytes: 99, + requested_state: "requested", + observed_state: "pending", + recipient: null, + part_urls: null, + urls_expire_at: null, + error_code: null, + ciphertext_sha256: null, + ciphertext_bytes: null, + required_storage_bytes: 3 * GiB, + storage_ready: false, + created_at: "2026-01-01T00:00:00Z", + updated_at: "2026-01-01T00:00:00Z", + }; + api.rows.set(importId, row); + const page = await home({ api, context: { limits: published, storage: readings } }); + await page.until(() => page.text().includes("growing to about"), "the row's growth wait"); + Object.assign(row, { storage_ready: true, observed_state: "key_ready" }); + await page.until( + () => page.text().includes("An upload is waiting to continue."), + "the row after the vault has grown", + 20_000 + ); +}); + +it("Home shows the published growth wait on its row and dialog, then a fixed growth failure", async () => { + const api = importApiDouble("unused"); + const importId = crypto.randomUUID(); + const row = { + import_id: importId, + kind: "adopt", + declared_files: 1, + declared_bytes: 99, + requested_state: "requested", + observed_state: "pending", + recipient: null, + part_urls: null, + urls_expire_at: null, + error_code: null, + ciphertext_sha256: null, + ciphertext_bytes: null, + required_storage_bytes: 3 * GiB, + storage_ready: false, + created_at: "2026-01-01T00:00:00Z", + updated_at: "2026-01-01T00:00:00Z", + }; + api.rows.set(importId, row); + const page = await home({ api, context: { limits: published, storage: readings } }); + await page.until(() => page.text().includes("growing to about"), "the row's growth wait"); + await page.click("Add files…"); + await page.until(() => page.text().includes("60 minutes"), "the published wait bound"); + assert.ok(page.text().includes("Waiting for storage to grow")); + assert.ok(!page.text().includes("stopped before")); + Object.assign(row, { observed_state: "failed", error_code: "IMPORT_STORAGE_UNAVAILABLE" }); + await page.until(() => page.text().includes("did not grow in time"), "the fixed growth failure"); + assert.ok(page.text().includes(importId)); + await cleanup?.(); + cleanup = null; + Object.assign(row, { error_code: "IMPORT_STORAGE_NO_ROOM" }); + const unavailable = await home({ api, context: { limits: published, storage: readings } }); + await unavailable.click("Add files…"); + await unavailable.until( + () => unavailable.text().includes("cannot grow its storage right now"), + "the local growth refusal" + ); + assert.ok(unavailable.text().includes("IMPORT_STORAGE_NO_ROOM")); +}); + +for (const [code, unit, reason] of [ + ["IMPORT_TOO_MANY_FILES", "files", "more files than this vault accepts"], + ["IMPORT_STORAGE_LIMIT", "bytes", "cannot fit within this vault’s storage limit"], + ["IMPORT_PARTS_LIMIT", "bytes", "exceeds this vault’s upload limit"], +] as const) { + it(`Home shows the fixed ${code} reason and typed limit from a stale preflight refusal`, async () => { + const api = importApiDouble("unused"); + const receive = api.receive; + api.receive = async (input, init) => + String(input) === "/api/exomem/cloud/imports" && init?.method === "POST" + ? Response.json( + { + error: { + code, + message: "untrusted wording", + limit: { unit, value: 2, requested: 3 }, + }, + }, + { status: 422 } + ) + : receive(input, init); + const page = await home({ api }); + await page.click("Add files…"); + await page.choose(folder("research", 1), "Folder to add"); + await page.click("Encrypt and upload"); + await page.until(() => page.text().includes(reason), "the fixed refusal"); + assert.ok(page.text().includes("Published limit")); + assert.ok(!page.text().includes("untrusted wording")); + assert.ok(page.text().includes(code)); + if (code !== "IMPORT_PARTS_LIMIT") assert.ok(!page.text().includes("Choose the files again")); + }); +} + // Records as Home's filing route passes them on, in the shape settled with the cell. const working = { state: "working", @@ -515,6 +768,17 @@ for (const { name, answer, shows, hides } of filingCases) { }); } +it("an import whose Job reported no staged size says so, and never shows its declared size as staged", async () => { + const api = importApiDouble(await identityToRecipient(await generateIdentity())); + staged(api); + Object.assign(api.rows.get(STAGED_ID)!, { staged_files: null, staged_bytes: null }); + api.answerFiling(() => ({ state: "not_offered" })); + const page = await home({ api }); + await page.click("Add files…"); + await page.until(() => page.text().includes("Staged originalsnot recorded"), "the unknown size"); + assert.ok(!page.text().includes("4.2 MB")); +}); + const wakes = (api: ReturnType) => api.requests.filter(({ body }) => body?.call === "wake").length; diff --git a/src/app/exomem/home/home-import-filing.tsx b/src/app/exomem/home/home-import-filing.tsx index 5699c9b0..b42e3892 100644 --- a/src/app/exomem/home/home-import-filing.tsx +++ b/src/app/exomem/home/home-import-filing.tsx @@ -398,7 +398,7 @@ export function ImportFiling({ }: { read: FilingRead | null; /** The import's declared bytes: what the staging folder holds. */ - staged: { bytes: number }; + staged: { bytes: number | null }; storage: HomeStorage | null; now: number; }) { diff --git a/src/app/exomem/home/home-import-panels.tsx b/src/app/exomem/home/home-import-panels.tsx index 1265ae96..ad007350 100644 --- a/src/app/exomem/home/home-import-panels.tsx +++ b/src/app/exomem/home/home-import-panels.tsx @@ -4,7 +4,13 @@ import { Button } from "@/components/exomem/Button"; import { Notice } from "@/components/exomem/Notice"; import type { ImportForecast } from "@/lib/exomem-hosted/cloud-import-browser"; import type { ImportProgress } from "@/lib/exomem-hosted/cloud-import-browser-upload"; +import { importStopText } from "@/lib/exomem-hosted/cloud-import-stop"; import type { SelectionTotals } from "@/lib/exomem-hosted/cloud-import-selection"; +import { + IMPORT_GIB, + type calculateImportAdmission, + type ImportStorage, +} from "@/lib/exomem/cloud-import-contract"; import type { HomeStorage } from "./home-api"; import { ago, byteSize, count, filesWord } from "./home-format"; import styles from "./home.module.css"; @@ -17,10 +23,10 @@ function totals({ files, bytes }: SelectionTotals): string { } /** Free bytes in the vault from the last disk reading, or null when none is known. */ -function vaultFree(storage: HomeStorage | null) { +function vaultFree(storage: HomeStorage | null, reserve: number) { if (storage?.state !== "known") return null; return { - bytes: Math.max(0, storage.filesystem_bytes - storage.used_bytes), + bytes: Math.max(0, storage.filesystem_bytes - storage.used_bytes - reserve), observedAt: storage.observed_at, }; } @@ -33,6 +39,10 @@ export function browserFree(room: BrowserRoom): number | null { /** The selection beside every limit Home can measure before the upload starts. */ export function ImportLimits({ forecast, + admission, + limitsRead, + partsCeiling, + importStorage, room, others, storage, @@ -41,6 +51,14 @@ export function ImportLimits({ onDiscardOthers, }: { forecast: ImportForecast; + /** The published limits applied to this selection; null when the cell published none. */ + admission: ReturnType | null; + /** False while Home has no answer from the import route, so it cannot say what was published. */ + limitsRead: boolean; + /** The published multipart ceiling when this selection's encrypted copy exceeds it. */ + partsCeiling: number | null; + /** The import route's own vault reading, which wins over Home's when it has one. */ + importStorage: ImportStorage | null; room: BrowserRoom; /** Kept copies outside this account's folder; null when they could not be read. */ others: SelectionTotals | null; @@ -50,10 +68,65 @@ export function ImportLimits({ onDiscardOthers: () => void; }) { const browser = browserFree(room); - const vault = vaultFree(storage); + const reserve = admission?.limits.reserve_bytes ?? 0; + const vaultReading: HomeStorage | null = + importStorage?.used_bytes != null && + importStorage.filesystem_bytes != null && + importStorage.usage_observed_at + ? { + state: "known", + used_bytes: importStorage.used_bytes, + filesystem_bytes: importStorage.filesystem_bytes, + observed_at: importStorage.usage_observed_at, + } + : storage; + const vault = vaultFree(vaultReading, reserve); + const grows = + admission !== null && + !admission.refusal && + admission.required_storage_gib * IMPORT_GIB > admission.current_storage_bytes; + // With published limits the vault grows for the import, so free space alone is no reason to + // warn; only a need above what growth can reach can still stop it. + const short = + vault !== null && + vault.bytes < forecast.plaintextBytes && + (admission === null || admission.need_bytes > admission.required_storage_gib * IMPORT_GIB); return ( <>
+ {admission && ( + <> +
+ {/* The upload's own entries take part of the limit; the person's files get the rest. */} +
Files
+
+ {count(forecast.files)} of{" "} + {count(admission.limits.max_members - (forecast.members - forecast.files))} +
+
+
+
Storage needed, estimate
+
+ {byteSize(admission.need_bytes)} of {byteSize(admission.cap_bytes)} maximum,{" "} + {importStorage?.used_bytes != null && importStorage.usage_observed_at + ? `usage measured ${ago(importStorage.usage_observed_at, now)}` + : "usage not measured"} +
+
+ {grows && ( +
+
Storage grows to
+
about {byteSize(admission.required_storage_gib * IMPORT_GIB)}
+
+ )} + + )} + {!admission && ( +
+
Import limits
+
{limitsRead ? "not published" : "not read"}
+
+ )}
Encrypted copy
{byteSize(forecast.ciphertextBytes)}
@@ -84,6 +157,13 @@ export function ImportLimits({ ) )}
+ {partsCeiling !== null && ( + + The encrypted copy ({byteSize(forecast.ciphertextBytes)}) is above this vault’s upload + limit ({byteSize(partsCeiling)}). Choose fewer files. + + )} + {admission?.refusal && {importStopText(admission.refusal.code)}} {others !== null && others.files > 0 && ( <>

@@ -103,9 +183,10 @@ export function ImportLimits({ more room, then choose the files again. )} - {vault !== null && vault.bytes < forecast.plaintextBytes && ( + {short && vault !== null && ( - Your vault had {byteSize(vault.bytes)} free when it was measured{" "} + Your vault had {byteSize(vault.bytes)} free + {admission ? ` after the ${byteSize(reserve)} reserve` : ""} when it was measured{" "} {ago(vault.observedAt, now)}, and this selection adds {byteSize(forecast.plaintextBytes)}. Evermatter may stop the import while it stages the files. Add storage first, or choose fewer files. @@ -229,7 +310,8 @@ export function StagedImportStorage({ storage, now, }: { - stagedBytes: number; + /** The bytes the import Job reported staging; null when it recorded none. */ + stagedBytes: number | null; storage: HomeStorage | null; now: number; }) { @@ -238,7 +320,7 @@ export function StagedImportStorage({

Staged originals
-
{byteSize(stagedBytes)}
+
{stagedBytes === null ? "not recorded" : byteSize(stagedBytes)}
Your vault
diff --git a/src/app/exomem/home/home-import.tsx b/src/app/exomem/home/home-import.tsx index 2f253d4b..fd9e8ad9 100644 --- a/src/app/exomem/home/home-import.tsx +++ b/src/app/exomem/home/home-import.tsx @@ -3,14 +3,22 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Button } from "@/components/exomem/Button"; import { Modal } from "@/components/exomem/Modal"; -import { cloudImportFinished, type CloudImport } from "@/lib/exomem/cloud-import-contract"; +import { + calculateImportAdmission, + cloudImportFinished, + importGrowthDeadline, + importPartLimits, + type CloudImport, + type CloudImportReply, + type ImportLimit, +} from "@/lib/exomem/cloud-import-contract"; import { forecastImport, type ImportFile, type ImportForecast, } from "@/lib/exomem-hosted/cloud-import-browser"; import { - readBrowserImport, + readBrowserImportContext, readImportFiling, wakeImportFiling, requestBrowserImport, @@ -29,7 +37,11 @@ import { keptCopyRetired, type ImportProgress, } from "@/lib/exomem-hosted/cloud-import-browser-upload"; -import { importArchive, uploadOrigin } from "@/lib/exomem-hosted/cloud-import-envelope"; +import { + importArchive, + SERIES_ENTRIES, + uploadOrigin, +} from "@/lib/exomem-hosted/cloud-import-envelope"; import { addToSelection, selectImportFiles, @@ -43,6 +55,7 @@ import { ImportStop, importPaused, importStopFrom, + importStopText, type ImportStopNext, } from "@/lib/exomem-hosted/cloud-import-stop"; import { friendlyHostedError, HostedBrowserError } from "@/lib/exomem-hosted/hosted-browser"; @@ -90,7 +103,14 @@ type Preflight = { /** Why this page's upload is not running, shown until the person acts on it. */ type Stop = | { kind: "paused"; unavailable: boolean; phase: ImportProgress["phase"] | null } - | { kind: "failed"; importId: string; code: string | null; text: string; next: ImportStopNext }; + | { + kind: "failed"; + importId: string; + code: string | null; + text: string; + next: ImportStopNext; + limit?: ImportLimit; + }; const NEXT_STEP: Record = { resume: "Resume to try again, or cancel the import.", @@ -99,7 +119,31 @@ const NEXT_STEP: Record = { status: "Check the import’s current status above.", }; +/** The published bound on the wait for growth, which counts from the upload's start. */ +function GrowthLimit({ seconds }: { seconds: number }) { + return ( +
+
+
Growth time limit
+
{count(Math.ceil(seconds / 60))} minutes from the upload’s start
+
+
+ ); +} + +function growthWait(operation: CloudImport): string | null { + return operation.requested_state === "requested" && + operation.observed_state === "pending" && + operation.required_storage_bytes != null && + operation.storage_ready === false + ? // A no-break space keeps the size and its unit on one line in a narrow row. + `Storage growing to about ${byteSize(operation.required_storage_bytes).replace(" ", "\u00a0")}` + : null; +} + function observation(operation: CloudImport): string { + const growth = growthWait(operation); + if (growth) return growth; if ( operation.requested_state === "uploaded" && (operation.observed_state === "pending" || operation.observed_state === "key_ready") @@ -182,6 +226,7 @@ export function ImportDocuments({ const [open, setOpen] = useState(false); const [checked, setChecked] = useState(false); const [operation, setOperation] = useState(null); + const [context, setContext] = useState(null); // When this page last heard about the import: "measured N minutes ago" is read against it. const [heardAt, setHeardAt] = useState(0); // What the person chose so far, each pick under its own top-level name; null before any. @@ -303,16 +348,18 @@ export function ImportDocuments({ let timer: ReturnType; const read = async () => { try { - const value = await readBrowserImport(csrfToken, readImportId, controller.signal); + const response = await readBrowserImportContext(csrfToken, readImportId, controller.signal); if (controller.signal.aborted) return; + const value = response.import; + setContext(response); setOperation(value); setHeardAt(Date.now()); setChecked(true); setReadMessage(null); if (!value || cloudImportFinished(value)) return; - // With the dialog closed, only an accepted upload is followed, so the row can say when - // it is staged and filing starts. - if (discover && value.requested_state !== "uploaded") return; + // With the dialog closed, only an accepted upload or a growth wait is followed, so the + // row can say when it is staged, or when the vault has grown and the upload can go on. + if (discover && value.requested_state !== "uploaded" && !growthWait(value)) return; } catch (error) { if (controller.signal.aborted) return; if ( @@ -492,6 +539,28 @@ export function ImportDocuments({ return () => controller.abort(); }, [measuring, resumingId, account, csrfToken, discards]); const measured = preflight && measuring && preflight.archive === measuring ? preflight : null; + const deadline = importGrowthDeadline.safeParse(context?.limits); + const admission = + measured && "forecast" in measured && context?.storage + ? calculateImportAdmission( + context.limits, + context.storage, + measured.forecast.plaintextBytes, + measured.forecast.members + ) + : null; + // The exact ciphertext size is known here, so an upload above the multipart ceiling is + // refused before the vault grows for it or this device encrypts it. + const partLimits = importPartLimits.safeParse(context?.limits); + const partsCeiling = partLimits.success + ? partLimits.data.max_parts * partLimits.data.part_bytes + : null; + const partsRefused = + partsCeiling !== null && + measured !== null && + "forecast" in measured && + measured.forecast.ciphertextBytes > partsCeiling; + const refused = Boolean(admission?.refusal) || partsRefused; const storedId = open && reported && !holding && !busy ? awaiting.import_id : null; useEffect(() => { @@ -638,12 +707,13 @@ export function ImportDocuments({ code: reason?.code ?? (error instanceof HostedBrowserError ? error.code : null), text: reason?.message ?? friendlyHostedError(error), next: reason?.next ?? "resume", + limit: reason?.limit, }); if (reason?.cleanupFailed) failCleanup(); } function start() { - if (!archive) return; + if (!archive || refused) return; const previous = upload.current; const resumeId = awaiting && !reported ? awaiting.import_id : undefined; upload.current = new BrowserImportUpload({ @@ -749,20 +819,23 @@ export function ImportDocuments({ measured !== null && "forecast" in measured && (browserFree(measured.room) ?? Infinity) < measured.forecast.ciphertextBytes; + const growth = operation ? growthWait(operation) : null; + // A paused or stopped upload needs the person, so it wins over the growth wait. const rowStatus = - busy && progress - ? rowProgress(progress) - : stop?.kind === "paused" - ? "Upload paused. Open it to resume." - : stop - ? "Upload stopped. Open it for the next step." - : awaiting - ? "An upload is waiting to continue." - : openImport?.requested_state === "uploaded" - ? "Uploaded · checking the files" - : stagedId - ? filingRowText(filingRead) - : null; + stop?.kind === "paused" + ? "Upload paused. Open it to resume." + : stop + ? "Upload stopped. Open it for the next step." + : (growth ?? + (busy && progress + ? rowProgress(progress) + : awaiting + ? "An upload is waiting to continue." + : openImport?.requested_state === "uploaded" + ? "Uploaded · checking the files" + : stagedId + ? filingRowText(filingRead) + : null)); return ( <> {(canStart || operation !== null || readMessage !== null) && ( @@ -806,7 +879,7 @@ export function ImportDocuments({ {earlier &&

Earlier upload

} @@ -831,12 +904,34 @@ export function ImportDocuments({
{operation.error_code && ( -

Evermatter reported: {operation.error_code}

+ <> +

+ {importStopText(operation.error_code) ?? "Evermatter stopped the upload."} +

+ + + )} + {growth && deadline.success && ( + )} ) )} - {busy && progress && } + {busy && + progress && + (progress.phase === "preparing" && growth ? ( + // Encryption waits for the vault to grow; the wait is the upload's state. + <> +

+ {growth} +

+ {deadline.success && ( + + )} + + ) : ( + + ))} {busy && progress && ( <> diff --git a/src/lib/exomem-hosted/__tests__/cloud-import-browser-api.test.ts b/src/lib/exomem-hosted/__tests__/cloud-import-browser-api.test.ts index 8dc953b9..342302c4 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-import-browser-api.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-import-browser-api.test.ts @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { afterEach, beforeEach, mock, test } from "node:test"; import { readBrowserImport, requestBrowserImport } from "../cloud-import-browser-api"; import { HostedBrowserError } from "../hosted-browser"; +import { importStopFrom } from "../cloud-import-stop"; const importId = "2495eb8e-01ba-445f-ac61-e481c51b68b5"; const csrfToken = "synthetic-csrf"; @@ -34,6 +35,18 @@ const status = { updated_at: "2026-01-01T00:01:00.000Z", }; +test("only a fetch TypeError reads as a dropped connection", async () => { + const network = mock.method(globalThis, "fetch", async () => { + throw new TypeError("network failure"); + }); + try { + await assert.rejects(readBrowserImport(csrfToken), { code: "CONNECTION" }); + assert.equal(importStopFrom(new TypeError("application defect"))?.code, "STOPPED"); + } finally { + network.mock.restore(); + } +}); + test("an accepted upload remains importing and retains the controller observation", async () => { const receive: typeof fetch = async (_input, init) => { assert.equal(init?.credentials, "same-origin"); diff --git a/src/lib/exomem-hosted/__tests__/cloud-import-browser-file.test.ts b/src/lib/exomem-hosted/__tests__/cloud-import-browser-file.test.ts index 41822736..6a282e40 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-import-browser-file.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-import-browser-file.test.ts @@ -4,6 +4,7 @@ import { discardOtherKeptCiphertext, otherKeptCiphertext, sweepKeptCiphertext, + holdImport, } from "../cloud-import-browser-file"; import { browserStorageDouble, webLocksDouble } from "./browser-import-doubles"; @@ -19,6 +20,29 @@ afterEach(() => { const id = (digit: string) => `${digit.repeat(8)}-${digit.repeat(4)}-4${digit.repeat(3)}-8${digit.repeat(3)}-${digit.repeat(12)}`; +test("a slow sweep status read leaves the import lock free for a resuming tab", async () => { + const browser = browserStorageDouble(); + const tabs = webLocksDouble(); + Object.defineProperty(globalThis, "navigator", { + configurable: true, + value: { storage: browser.storage, locks: tabs.locks }, + }); + const importId = id("1"); + const mine = browser.files("exomem-import-uploads", "account-MINE"); + mine.set(`${importId}.age`, [new Uint8Array(10)]); + let finishRead!: (retired: boolean) => void; + const read = new Promise((resolve) => { + finishRead = resolve; + }); + const sweeping = sweepKeptCiphertext("MINE", null, () => read); + await new Promise((resolve) => setTimeout(resolve, 0)); + await holdImport(importId, async () => { + finishRead(false); + await sweeping; + }); + assert.ok(mine.has(`${importId}.age`)); +}); + test("a sweep removes only this account's ended, unheld copies and labels; other accounts' wait for a discard", async () => { const browser = browserStorageDouble(); const tabs = webLocksDouble(); diff --git a/src/lib/exomem-hosted/__tests__/cloud-import-browser-upload.test.ts b/src/lib/exomem-hosted/__tests__/cloud-import-browser-upload.test.ts index a5dee3ec..b15be052 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-import-browser-upload.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-import-browser-upload.test.ts @@ -6,7 +6,7 @@ import { keptCopyRetired, type ImportProgress, } from "../cloud-import-browser-upload"; -import { encryptImportToBrowserFile } from "../cloud-import-browser-file"; +import { encryptImportToBrowserFile, writeImportPartReceipts } from "../cloud-import-browser-file"; import { browserStorageDouble, importApiDouble, webLocksDouble } from "./browser-import-doubles"; const ACCOUNT = "SYNTH1"; @@ -64,7 +64,7 @@ test("an interrupted part upload resumes the same ciphertext and receipts, then ), { code: "STORAGE_REFUSED" } ); - assert.equal(browser.kept().size, 1); + assert.equal([...browser.kept().keys()].filter((name) => name.endsWith(".age")).length, 1); await upload.resume( (value) => observations.push(value.observed_state), (value) => progress.push(value) @@ -88,6 +88,58 @@ test("an interrupted part upload resumes the same ciphertext and receipts, then assert.equal(encrypted.totalCiphertextBytes, row.ciphertext_bytes); }); +test("a reload resumes at the next unrecorded part and removes the durable receipt with the copy", async () => { + const browser = useBrowserStorage(); + const api = importApiDouble(await identityToRecipient(await generateIdentity())); + mock.method(globalThis, "fetch", api.receive); + const first = browserUpload(folder()); + api.refusePartOnce(2); + await assert.rejects( + first.resume( + () => {}, + () => {} + ), + { code: "STORAGE_REFUSED" } + ); + const receipt = browser.kept().get(`${first.id}.parts.json`)!; + assert.ok(receipt); + assert.deepEqual(JSON.parse(new TextDecoder().decode(receipt[0])).parts, [ + { part_number: 1, etag: '"1"' }, + ]); + const prior = api.parts.length; + await browserUpload(null, first.id).resume( + () => {}, + () => {} + ); + assert.ok(api.parts.slice(prior).every(({ url }) => !url.endsWith("/1"))); + assert.equal(api.parts.filter(({ url }) => url.endsWith("/1")).length, 1); + assert.equal(browser.kept().size, 0); +}); + +test("a receipt for different ciphertext never skips a part of the verified copy", async () => { + const browser = useBrowserStorage(); + const api = importApiDouble(await identityToRecipient(await generateIdentity())); + mock.method(globalThis, "fetch", api.receive); + const first = browserUpload(folder()); + api.refusePartOnce(2); + await assert.rejects( + first.resume( + () => {}, + () => {} + ), + { code: "STORAGE_REFUSED" } + ); + await writeImportPartReceipts(ACCOUNT, first.id, "f".repeat(64), [ + { part_number: 1, etag: "unrelated" }, + ]); + await browserUpload(null, first.id).resume( + () => {}, + () => {} + ); + assert.equal(api.parts.filter(({ url }) => url.endsWith("/1")).length, 2); + assert.equal(browser.kept().size, 0); +}); + test("a browser storage refusal leaves no ciphertext entry behind", async () => { const browser = browserStorageDouble(); Object.defineProperty(globalThis, "navigator", { diff --git a/src/lib/exomem-hosted/__tests__/cloud-import-browser.test.ts b/src/lib/exomem-hosted/__tests__/cloud-import-browser.test.ts index cbbc8be3..3beabcc0 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-import-browser.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-import-browser.test.ts @@ -142,6 +142,35 @@ test("failed storage parts retry the same bytes without forwarding session crede } }); +test("a part receipt the browser is too full to write does not stop the upload", async () => { + const ciphertext = new Blob([new Uint8Array([11, 22, 33, 44])]); + const parts = [ + { part_number: 1, url: "https://storage.example.test/part1", part_size_bytes: 2 }, + { part_number: 2, url: "https://storage.example.test/part2", part_size_bytes: 2 }, + ]; + const storage = mock.method(globalThis, "fetch", async (input: RequestInfo | URL) => { + return new Response(null, { headers: { etag: `"${String(input).slice(-1)}"` } }); + }); + try { + const uploaded = await uploadImportParts( + ciphertext, + parts, + new Map(), + () => {}, + undefined, + async () => { + throw new DOMException("full", "QuotaExceededError"); + } + ); + assert.deepEqual(uploaded, [ + { part_number: 1, etag: '"1"' }, + { part_number: 2, etag: '"2"' }, + ]); + } finally { + storage.mock.restore(); + } +}); + test("a part whose encrypted copy can no longer be read stops as a lost copy, not as a dropped connection", async () => { const parts = [{ part_number: 1, url: "https://storage.example.test/part1", part_size_bytes: 4 }]; // Fetch reports a body it cannot read, like a dropped connection, as a TypeError. @@ -166,7 +195,7 @@ test("a part whose encrypted copy can no longer be read stops as a lost copy, no ); await assert.rejects( uploadImportParts(new Blob([new Uint8Array(4)]), parts, new Map(), () => {}), - TypeError + { code: "CONNECTION" } ); } finally { storage.mock.restore(); diff --git a/src/lib/exomem-hosted/__tests__/cloud-imports-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-imports-postgres.integration.test.ts index 930a5706..55bf2b97 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-imports-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-imports-postgres.integration.test.ts @@ -189,7 +189,10 @@ describe("Cloud import API PostgreSQL boundary", { skip: !databaseUrl }, () => { it("reports pending, protects another tenant's transport, and rejects caller-selected authority", async () => { const alice = await owner(); const bob = await owner(); - assert.deepEqual(await (await call(alice, "status")).json(), { import: null }); + const empty = await (await call(alice, "status")).json(); + assert.equal(empty.import, null); + assert.equal(empty.limits, null); + assert.equal(empty.storage.used_bytes, null); const pending = await create(alice); assert.equal(pending.observed_state, "pending"); assert.equal(pending.part_urls, null); @@ -233,6 +236,265 @@ describe("Cloud import API PostgreSQL boundary", { skip: !databaseUrl }, () => { assert.equal((await call(alice, "status", undefined, pending.import_id)).status, 200); }); + it("admits growth atomically, returns its receipt wait, and replays before changed limits", async () => { + const alice = await owner(); + const GiB = 1024 ** 3; + const limits = { + max_members: 500, + reserve_bytes: GiB / 4, + space_factor: 2, + max_storage_gib: 20, + part_bytes: 128, + max_parts: 10, + }; + await pool.query( + "UPDATE exomem_cloud_cells SET storage_gib=2, import_limits=$2::jsonb, used_bytes=$3, filesystem_bytes=$4, usage_observed_at=now()-interval '1 year' WHERE cell_id=$1", + [alice.cellId, JSON.stringify(limits), GiB, 2 * GiB] + ); + const id = randomUUID(); + const body = { import_id: id, kind: "adopt", declared_files: 2, declared_bytes: 2 * GiB }; + const response = await call(alice, "create", body); + assert.equal(response.status, 201); + const admitted = await response.json(); + assert.equal(admitted.import.required_storage_bytes, 6 * GiB); + assert.equal(admitted.import.storage_ready, false); + assert.equal(admitted.storage.storage_gib, 6); + assert.deepEqual(admitted.limits, limits); + const grown = await pool.query( + "SELECT storage_gib, generation FROM exomem_cloud_cells WHERE cell_id=$1", + [alice.cellId] + ); + await pool.query("UPDATE exomem_cloud_cells SET import_limits=$2::jsonb WHERE cell_id=$1", [ + alice.cellId, + JSON.stringify({ ...limits, max_members: 1, max_storage_gib: 1 }), + ]); + assert.equal((await call(alice, "create", body)).status, 200); + assert.deepEqual( + ( + await pool.query( + "SELECT storage_gib, generation FROM exomem_cloud_cells WHERE cell_id=$1", + [alice.cellId] + ) + ).rows, + grown.rows + ); + await pool.query( + "UPDATE exomem_cloud_cells SET observed_storage_capacity_bytes=$2, observed_storage_generation=generation, observed_storage_pvc_uid='synthetic-pvc', observed_storage_pvc_version='1', observed_storage_at=now() WHERE cell_id=$1", + [alice.cellId, 5 * GiB] + ); + assert.equal( + (await (await call(alice, "status", undefined, id)).json()).import.storage_ready, + false + ); + await pool.query( + "UPDATE exomem_cloud_cells SET observed_storage_capacity_bytes=$2 WHERE cell_id=$1", + [alice.cellId, 6 * GiB] + ); + assert.equal( + (await (await call(alice, "status", undefined, id)).json()).import.storage_ready, + true + ); + // An unrelated change that bumps the generation cannot shrink the volume, so the + // requirement it already covers stays ready. + await pool.query("UPDATE exomem_cloud_cells SET storage_gib=7 WHERE cell_id=$1", [ + alice.cellId, + ]); + assert.equal( + (await (await call(alice, "status", undefined, id)).json()).import.storage_ready, + true + ); + }); + + it("rolls back growth when the open slot conflicts, and never lowers existing storage", async () => { + const alice = await owner(); + const GiB = 1024 ** 3; + const limits = { + max_members: 500, + reserve_bytes: GiB / 4, + space_factor: 2, + max_storage_gib: 20, + }; + await create(alice); + await pool.query( + "UPDATE exomem_cloud_cells SET storage_gib=2, import_limits=$2::jsonb WHERE cell_id=$1", + [alice.cellId, JSON.stringify(limits)] + ); + const before = ( + await pool.query("SELECT storage_gib, generation FROM exomem_cloud_cells WHERE cell_id=$1", [ + alice.cellId, + ]) + ).rows; + const response = await call(alice, "create", { + kind: "adopt", + declared_files: 1, + declared_bytes: 4 * GiB, + }); + assert.equal(response.status, 409); + assert.deepEqual( + ( + await pool.query( + "SELECT storage_gib, generation FROM exomem_cloud_cells WHERE cell_id=$1", + [alice.cellId] + ) + ).rows, + before + ); + await pool.query("UPDATE exomem_cloud_imports SET observed_state='done' WHERE cell_id=$1", [ + alice.cellId, + ]); + await pool.query( + "UPDATE exomem_cloud_cells SET storage_gib=20, used_bytes=0, filesystem_bytes=21474836480, usage_observed_at=now() WHERE cell_id=$1", + [alice.cellId] + ); + assert.equal( + (await call(alice, "create", { kind: "adopt", declared_files: 1, declared_bytes: 1 })).status, + 201 + ); + assert.equal( + ( + await pool.query("SELECT storage_gib FROM exomem_cloud_cells WHERE cell_id=$1", [ + alice.cellId, + ]) + ).rows[0].storage_gib, + 20 + ); + }); + + it("returns typed refusals without creating an import or freezing a rejected report", async () => { + const alice = await owner(); + const GiB = 1024 ** 3; + const limits = { + max_members: 2, + reserve_bytes: GiB / 4, + space_factor: 2, + max_storage_gib: 20, + part_bytes: 128, + max_parts: 2, + }; + await pool.query("UPDATE exomem_cloud_cells SET import_limits=$2::jsonb WHERE cell_id=$1", [ + alice.cellId, + JSON.stringify(limits), + ]); + for (const [declaration, code, limit] of [ + [ + { declared_files: 3, declared_bytes: 1 }, + "IMPORT_TOO_MANY_FILES", + { unit: "files", value: 2, requested: 3 }, + ], + [ + { declared_files: 1, declared_bytes: 10 * GiB }, + "IMPORT_STORAGE_LIMIT", + { unit: "bytes", value: 20 * GiB, requested: 20.25 * GiB }, + ], + ] as const) { + const response = await call(alice, "create", { kind: "adopt", ...declaration }); + assert.equal(response.status, 422); + const failure = await response.json(); + assert.equal(failure.error.code, code); + assert.deepEqual(failure.error.limit, limit); + } + assert.equal( + ( + await pool.query("SELECT count(*) FROM exomem_cloud_imports WHERE cell_id=$1", [ + alice.cellId, + ]) + ).rows[0].count, + "0" + ); + const pending = await create(alice); + await pool.query( + "UPDATE exomem_cloud_imports SET recipient='age1synthetic', observed_state='key_ready' WHERE import_id=$1", + [pending.import_id] + ); + const report = { ciphertext_sha256: "a".repeat(64), ciphertext_bytes: 257 }; + const refused = await call(alice, "prepare-upload", report, pending.import_id); + assert.equal(refused.status, 422); + assert.deepEqual((await refused.json()).error.limit, { + unit: "bytes", + value: 256, + requested: 257, + }); + assert.equal( + ( + await pool.query("SELECT ciphertext_sha256 FROM exomem_cloud_imports WHERE import_id=$1", [ + pending.import_id, + ]) + ).rows[0].ciphertext_sha256, + null + ); + report.ciphertext_bytes = 256; + assert.equal((await call(alice, "prepare-upload", report, pending.import_id)).status, 200); + await pool.query("UPDATE exomem_cloud_cells SET import_limits=$2::jsonb WHERE cell_id=$1", [ + alice.cellId, + JSON.stringify({ ...limits, max_parts: 1 }), + ]); + assert.equal((await call(alice, "prepare-upload", report, pending.import_id)).status, 200); + }); + + it("keeps unpublished admission compatible and publishes staged counts only for successful completion", async () => { + const alice = await owner(); + await pool.query( + "UPDATE exomem_cloud_cells SET storage_gib=2, grown_storage_gib=4, import_limits=NULL WHERE cell_id=$1", + [alice.cellId] + ); + const before = ( + await pool.query( + "SELECT storage_gib, grown_storage_gib, generation FROM exomem_cloud_cells WHERE cell_id=$1", + [alice.cellId] + ) + ).rows; + const row = await create(alice); + assert.equal(row.required_storage_bytes, null); + assert.equal(row.storage_ready, null); + assert.equal( + ( + await pool.query( + "SELECT required_storage_gib FROM exomem_cloud_imports WHERE import_id=$1", + [row.import_id] + ) + ).rows[0].required_storage_gib, + null + ); + assert.deepEqual( + ( + await pool.query( + "SELECT storage_gib, grown_storage_gib, generation FROM exomem_cloud_cells WHERE cell_id=$1", + [alice.cellId] + ) + ).rows, + before + ); + await pool.query( + "UPDATE exomem_cloud_imports SET staged_files=1, staged_bytes=77, observed_state='cleanup_running' WHERE import_id=$1", + [row.import_id] + ); + const read = async () => + (await (await call(alice, "status", undefined, row.import_id)).json()).import; + assert.equal((await read()).staged_files, null); + await pool.query("UPDATE exomem_cloud_imports SET observed_state='done' WHERE import_id=$1", [ + row.import_id, + ]); + assert.equal((await read()).staged_files, 1); + assert.equal((await read()).staged_bytes, 77); + await pool.query( + "UPDATE exomem_cloud_imports SET requested_state='cancelled' WHERE import_id=$1", + [row.import_id] + ); + assert.equal((await read()).staged_files, null); + assert.equal((await read()).staged_bytes, null); + await call(alice, "discard", undefined, row.import_id); + assert.equal((await read()).staged_files, null); + assert.equal((await read()).staged_bytes, null); + assert.equal( + ( + await pool.query("SELECT staged_files FROM exomem_cloud_imports WHERE import_id=$1", [ + row.import_id, + ]) + ).rows[0].staged_files, + "1" + ); + }); + it("freezes required storage at insertion, including an unpublished requirement", async () => { const alice = await owner(); await assert.rejects( diff --git a/src/lib/exomem-hosted/cloud-import-browser-api.ts b/src/lib/exomem-hosted/cloud-import-browser-api.ts index 8c342093..22cb6114 100644 --- a/src/lib/exomem-hosted/cloud-import-browser-api.ts +++ b/src/lib/exomem-hosted/cloud-import-browser-api.ts @@ -1,10 +1,24 @@ import { filingViewReply, type FilingView } from "../exomem/cloud-filing-contract"; -import { cloudImportReply, type CloudImport } from "../exomem/cloud-import-contract"; +import { + cloudImportReply, + type CloudImport, + type CloudImportReply, +} from "../exomem/cloud-import-contract"; import { ImportStop } from "./cloud-import-stop"; import { csrfCookie, getPrivateJson, HostedBrowserError, postPrivateJson } from "./hosted-browser"; const path = "/api/exomem/cloud/imports"; +/** Fetch alone reports network failures as TypeError; parsing and application errors keep their identity. */ +const fetchImport: typeof fetch = async (input, init) => { + try { + return await fetch(input, init); + } catch (error) { + if (error instanceof TypeError) throw new ImportStop("CONNECTION"); + throw error; + } +}; + /** A stale page must not send its selected files under another tab's new account. */ export function assertImportAccount(csrfToken: string) { if (!csrfToken || csrfToken !== csrfCookie()) { @@ -24,10 +38,23 @@ export async function readBrowserImport( importId?: string, signal?: AbortSignal ): Promise { + return (await readBrowserImportContext(csrfToken, importId, signal)).import; +} + +/** Home reads the same owner-scoped response once for the import and its admission readings. */ +export async function readBrowserImportContext( + csrfToken: string, + importId?: string, + signal?: AbortSignal +): Promise { assertImportAccount(csrfToken); const result = cloudImportReply.parse( - await getPrivateJson(importId ? `${path}/${encodeURIComponent(importId)}` : path, signal) - ).import; + await getPrivateJson( + importId ? `${path}/${encodeURIComponent(importId)}` : path, + signal, + fetchImport + ) + ); assertImportAccount(csrfToken); return result; } @@ -44,7 +71,7 @@ export async function requestBrowserImport( action === "create" ? path : `${path}/${encodeURIComponent(importId)}/${action}`, action === "create" ? { ...body, import_id: importId } : body, "POST", - { csrfToken, signal } + { csrfToken, signal, fetcher: fetchImport } ); assertImportAccount(csrfToken); const result = cloudImportReply.parse(response).import; diff --git a/src/lib/exomem-hosted/cloud-import-browser-file.ts b/src/lib/exomem-hosted/cloud-import-browser-file.ts index 707b696d..12ae88ea 100644 --- a/src/lib/exomem-hosted/cloud-import-browser-file.ts +++ b/src/lib/exomem-hosted/cloud-import-browser-file.ts @@ -5,6 +5,9 @@ import { type ImportFile, } from "./cloud-import-browser"; import { ImportStop } from "./cloud-import-stop"; +import { z } from "zod"; +import { MAX_IMPORT_PARTS } from "../exomem/cloud-import-contract"; +import type { UploadedPart } from "./cloud-import-browser"; const ROOT = "exomem-import-uploads"; // Checks the shape of our own file names (an import UUID plus ".age"). Anything else, such as a @@ -18,6 +21,24 @@ function ciphertextName(importId: string): string { return `${importId}.age`; } +function receiptName(importId: string): string { + return `${importId}.parts.json`; +} + +// The receipt is our closed multipart wire shape; the digest expression checks SHA-256 format. +const receipt = z.object({ + import_id: z.uuid(), + ciphertext_sha256: z.string().regex(/^[a-f0-9]{64}$/), + parts: z + .array( + z.object({ + part_number: z.number().int().min(1).max(MAX_IMPORT_PARTS), + etag: z.string().min(1).max(1024), + }) + ) + .max(MAX_IMPORT_PARTS), +}); + function labelName(importId: string): string { return `${importId}.label`; } @@ -56,6 +77,69 @@ async function removeEntry(directory: FileSystemDirectoryHandle, name: string) { } } +async function removeCopy(directory: FileSystemDirectoryHandle, importId: string) { + // The receipt goes first: the sweep finds copies by their ciphertext, so a receipt left + // behind after its ciphertext would never be found again. + await removeEntry(directory, receiptName(importId)); + await removeEntry(directory, ciphertextName(importId)); +} + +/** Receipts belong only to this import and verified ciphertext; stale or malformed ones go. */ +export async function readImportPartReceipts( + account: string, + importId: string, + sha256: string +): Promise> { + const directory = await accountDirectory(account); + let value: unknown; + try { + const file = await (await directory.getFileHandle(receiptName(importId))).getFile(); + try { + value = JSON.parse(await file.text()); + } catch { + value = null; + } + } catch (error) { + if (error instanceof DOMException && error.name === "NotFoundError") return new Map(); + throw error; + } + const parsed = receipt.safeParse(value); + if ( + !parsed.success || + parsed.data.import_id !== importId || + parsed.data.ciphertext_sha256 !== sha256 + ) { + await removeEntry(directory, receiptName(importId)); + return new Map(); + } + return new Map(parsed.data.parts.map(({ part_number, etag }) => [part_number, etag])); +} + +/** Commit a confirmed part beside its ciphertext before the upload continues to the next part. */ +export async function writeImportPartReceipts( + account: string, + importId: string, + sha256: string, + parts: UploadedPart[] +): Promise { + const directory = await accountDirectory(account); + const handle = await directory.getFileHandle(receiptName(importId), { create: true }); + const writer = (await handle.createWritable()).getWriter(); + try { + await writer.write( + new TextEncoder().encode( + JSON.stringify({ import_id: importId, ciphertext_sha256: sha256, parts }) + ) + ); + await writer.close(); + } catch (error) { + await writer.abort(error).catch(() => {}); + throw error; + } finally { + writer.releaseLock(); + } +} + function lockName(importId: string): string { return `exomem-import:${importId}`; } @@ -100,7 +184,7 @@ export async function encryptImportToBrowserFile( if (!privateStorage()) throw new ImportStop("BROWSER_UNSUPPORTED"); const directory = await accountDirectory(account); const name = ciphertextName(importId); - const remove = () => removeEntry(directory, name); + const remove = () => removeCopy(directory, importId); const handle = await directory.getFileHandle(name, { create: true }); try { if (typeof handle.createWritable !== "function") throw new ImportStop("BROWSER_UNSUPPORTED"); @@ -130,7 +214,7 @@ export async function storedImportCiphertext( const name = ciphertextName(importId); try { const handle = await directory.getFileHandle(name); - return { ciphertext: await handle.getFile(), remove: () => removeEntry(directory, name) }; + return { ciphertext: await handle.getFile(), remove: () => removeCopy(directory, importId) }; } catch (error) { if (error instanceof DOMException && error.name === "NotFoundError") return null; throw error; @@ -141,7 +225,7 @@ export async function storedImportCiphertext( export async function removeImportCiphertext(account: string, importId: string): Promise { if (!privateStorage()) return; const directory = await accountDirectory(account); - await removeEntry(directory, ciphertextName(importId)); + await removeCopy(directory, importId); await removeEntry(directory, labelName(importId)); } @@ -207,10 +291,12 @@ export async function sweepKeptCiphertext( } for (const importId of candidates) { // One copy that cannot be removed now stays counted as used; the next sweep tries again. - await whileImportFree(importId, async () => { - if (await retired(importId)) await removeImportCiphertext(account, importId); - return true; - }).catch(() => false); + // An import that stops waiting never waits again, so the read stays valid until removal. + if (await retired(importId).catch(() => false)) + await whileImportFree(importId, async () => { + await removeImportCiphertext(account, importId); + return true; + }).catch(() => false); } } @@ -261,14 +347,16 @@ export async function otherKeptCiphertext( */ export async function discardOtherKeptCiphertext(account: string): Promise<{ kept: number }> { if (!privateStorage()) return { kept: 0 }; - const remove = ({ directory, name, importId }: KeptCopy) => + const remove = (importId: string, drop: () => Promise) => whileImportFree(importId, async () => { - await removeEntry(directory, name); + await drop(); return true; }).catch(() => false); let kept = 0; - for (const copy of await otherCopies(account)) if (!(await remove(copy))) kept += 1; - for (const label of await otherCopies(account, LABEL_NAME)) await remove(label); + for (const { directory, importId } of await otherCopies(account)) + if (!(await remove(importId, () => removeCopy(directory, importId)))) kept += 1; + for (const { directory, name, importId } of await otherCopies(account, LABEL_NAME)) + await remove(importId, () => removeEntry(directory, name)); return { kept }; } diff --git a/src/lib/exomem-hosted/cloud-import-browser-upload.ts b/src/lib/exomem-hosted/cloud-import-browser-upload.ts index 8274a18e..19f1f071 100644 --- a/src/lib/exomem-hosted/cloud-import-browser-upload.ts +++ b/src/lib/exomem-hosted/cloud-import-browser-upload.ts @@ -12,6 +12,8 @@ import { removeFreeImportCiphertext, removeImportCiphertext, storedImportCiphertext, + readImportPartReceipts, + writeImportPartReceipts, sweepKeptCiphertext, type StoredCiphertext, } from "./cloud-import-browser-file"; @@ -39,7 +41,11 @@ export type ImportProgress = } | { phase: "verifying" | "uploading"; bytes: number; total: number }; -function pauseUntilNextRead(signal: AbortSignal): Promise { +/** A key read is cheap and soon; growth takes minutes, so its wait reads less often. */ +const KEY_READ_MS = 2500; +const GROWTH_READ_MS = 15_000; + +function pauseUntilNextRead(signal: AbortSignal, ms: number): Promise { return new Promise((resolve, reject) => { signal.throwIfAborted(); const stop = () => { @@ -49,7 +55,7 @@ function pauseUntilNextRead(signal: AbortSignal): Promise { const timer = setTimeout(() => { signal.removeEventListener("abort", stop); resolve(); - }, 2500); + }, ms); signal.addEventListener("abort", stop, { once: true }); }); } @@ -86,7 +92,6 @@ function keptCopyLost(error: unknown): boolean { export class BrowserImportUpload { readonly id: string; private encrypted: StoredCiphertext | null = null; - private readonly completed = new Map(); private active: Promise | null = null; private controller: AbortController | null = null; @@ -184,7 +189,10 @@ export class BrowserImportUpload { throw new ImportStop("NOT_WAITING"); } if (ready(operation)) return; - await pauseUntilNextRead(signal); + await pauseUntilNextRead( + signal, + operation.storage_ready === false ? GROWTH_READ_MS : KEY_READ_MS + ); const next = await readBrowserImport(this.csrfToken, this.id, signal); signal.throwIfAborted(); if (!next) throw new ImportStop("UNAVAILABLE"); @@ -256,16 +264,28 @@ export class BrowserImportUpload { throw new ImportStop("LINKS_EXPIRED"); } assertImportAccount(this.csrfToken); + const completed = await readImportPartReceipts( + this.account, + this.id, + encrypted.report.ciphertext_sha256 + ); progress({ phase: "uploading", bytes: 0, total: encrypted.report.ciphertext_bytes }); const part_etags = await uploadImportParts( encrypted.ciphertext, operation.part_urls, - this.completed, + completed, (bytes) => { assertImportAccount(this.csrfToken); progress({ phase: "uploading", bytes, total: encrypted.report.ciphertext_bytes }); }, - signal + signal, + (part) => + writeImportPartReceipts( + this.account, + this.id, + encrypted.report.ciphertext_sha256, + [...completed].map(([part_number, etag]) => ({ part_number, etag })).concat(part) + ) ).catch((error: unknown) => { // This page's copy can no longer serve the import; a later attempt looks for it afresh. if (error instanceof ImportStop && error.code === "LOCAL_COPY_MISSING") this.encrypted = null; diff --git a/src/lib/exomem-hosted/cloud-import-browser.ts b/src/lib/exomem-hosted/cloud-import-browser.ts index e1997558..70a71380 100644 --- a/src/lib/exomem-hosted/cloud-import-browser.ts +++ b/src/lib/exomem-hosted/cloud-import-browser.ts @@ -26,6 +26,7 @@ export type EncryptionProgress = { files: number; plaintextBytes: number; cipher export type ImportForecast = { /** The person's files; the series file is counted in the bytes, not here. */ files: number; + members: number; plaintextBytes: number; tarBytes: number; ciphertextBytes: number; @@ -109,6 +110,8 @@ export async function forecastImport( const stand = recipient ?? (await identityToRecipient(await generateX25519Identity())); return { files: files.filter(({ reserved }) => !reserved).length, + // Every entry, the reserved series file included, is one TAR member; parent paths add none. + members: files.length, plaintextBytes: files.reduce((total, { file }) => total + file.size, 0), tarBytes: archive, ciphertextBytes: await ageBytes(archive, stand), @@ -214,7 +217,8 @@ export async function uploadImportParts( parts: UploadPart[], completed: Map, onProgress: (uploadedBytes: number) => void, - signal?: AbortSignal + signal?: AbortSignal, + onConfirmed: (part: UploadedPart) => Promise = async () => {} ): Promise { let total = 0; for (const [index, part] of parts.entries()) { @@ -259,11 +263,18 @@ export async function uploadImportParts( // the part tells a lost encrypted copy from a dropped connection. if (error instanceof TypeError && !(await readable(body))) throw new ImportStop("LOCAL_COPY_MISSING"); + if (error instanceof TypeError) throw new ImportStop("CONNECTION"); throw error; } if (!response.ok) throw new ImportStop("STORAGE_REFUSED"); const etag = response.headers.get("etag"); if (!etag) throw new ImportStop("STORAGE_UNCONFIRMED"); + try { + await onConfirmed({ part_number: part.part_number, etag }); + } catch { + // The receipt only saves a resend after a reload; a browser too full to write it must + // not stop the upload, which carries on from the parts confirmed in memory. + } completed.set(part.part_number, etag); } offset = end; diff --git a/src/lib/exomem-hosted/cloud-import-envelope.ts b/src/lib/exomem-hosted/cloud-import-envelope.ts index e200f401..7c75caad 100644 --- a/src/lib/exomem-hosted/cloud-import-envelope.ts +++ b/src/lib/exomem-hosted/cloud-import-envelope.ts @@ -64,6 +64,9 @@ export function uploadOrigin(identity: BrowserIdentity, label: string): UploadOr }; } +/** The archive entries every upload adds beside the person's files: its one series file. */ +export const SERIES_ENTRIES = 1; + /** * The archive's members: the series file first, then the selection. The series file asks the * cell to file the import, names the collection of a single folder or zip, and states the diff --git a/src/lib/exomem-hosted/cloud-import-http.ts b/src/lib/exomem-hosted/cloud-import-http.ts index a6a379b8..3781c2f9 100644 --- a/src/lib/exomem-hosted/cloud-import-http.ts +++ b/src/lib/exomem-hosted/cloud-import-http.ts @@ -18,14 +18,14 @@ export async function handleCloudImportRequest( try { const principal = await resolveCloudImportPrincipal(request); if (action === "status") - return Response.json({ import: await readCloudImport(principal, importId) }, { headers }); + return Response.json(await readCloudImport(principal, importId), { headers }); const body = action === "cancel" || action === "discard" ? undefined : await readBoundedJsonRequest(request, 2 * 1024 * 1024); const result = await mutateCloudImport(principal, action, body, importId); return Response.json( - { import: result.import }, + { import: result.import, limits: result.limits, storage: result.storage }, { status: result.created ? 201 : 200, headers } ); } catch (error) { diff --git a/src/lib/exomem-hosted/cloud-import-selection.ts b/src/lib/exomem-hosted/cloud-import-selection.ts index 689bbf81..f7498667 100644 --- a/src/lib/exomem-hosted/cloud-import-selection.ts +++ b/src/lib/exomem-hosted/cloud-import-selection.ts @@ -50,7 +50,7 @@ export type ImportSelection = { // git's per-directory exclude file, a name git itself fixes. const GITIGNORE = ".gitignore"; -// A larger .gitignore is not a rules file, and reading it whole could exhaust browser memory. +// Home reads each rules file whole into browser memory; this cap bounds that allocation. export const GITIGNORE_MAX_BYTES = 4 * 1024 * 1024; function gitignoreFile(path: string): boolean { diff --git a/src/lib/exomem-hosted/cloud-import-stop.ts b/src/lib/exomem-hosted/cloud-import-stop.ts index b83d6758..efef58e2 100644 --- a/src/lib/exomem-hosted/cloud-import-stop.ts +++ b/src/lib/exomem-hosted/cloud-import-stop.ts @@ -1,4 +1,5 @@ import { HostedBrowserError } from "./hosted-browser"; +import { importLimit, type ImportLimit } from "../exomem/cloud-import-contract"; /** * The route that can still finish a stopped import: resume it, choose the folder again, cancel @@ -6,7 +7,7 @@ import { HostedBrowserError } from "./hosted-browser"; */ export type ImportStopNext = "resume" | "choose" | "cancel" | "status"; -// Our own reasons for stopping a browser import. The text never carries a file name, a path +// These are closed browser and C5 protocol codes. The text never carries a file name, a path // or a browser's message, because those can name private folder content. const STOPS = { FOLDER_EMPTY: { next: "choose", text: "The selection holds no files. Choose files or a folder." }, @@ -56,6 +57,26 @@ const STOPS = { next: "resume", text: "This import is running in another tab or window.", }, + IMPORT_TOO_MANY_FILES: { + next: "choose", + text: "The selection has more files than this vault accepts in one upload. Choose fewer files.", + }, + IMPORT_STORAGE_LIMIT: { + next: "choose", + text: "The upload cannot fit within this vault’s storage limit. Choose fewer files.", + }, + IMPORT_PARTS_LIMIT: { + next: "cancel", + text: "The encrypted copy exceeds this vault’s upload limit.", + }, + IMPORT_STORAGE_UNAVAILABLE: { + next: "choose", + text: "The vault’s storage did not grow in time. Start a new upload to try again.", + }, + IMPORT_STORAGE_NO_ROOM: { + next: "choose", + text: "The vault cannot grow its storage right now. Start a new upload later.", + }, STOPPED: { next: "resume", text: "The browser stopped the import." }, } satisfies Record; @@ -66,13 +87,18 @@ export class ImportStop extends Error { readonly next: ImportStopNext; /** The temporary encrypted file could not be removed after this stop. */ readonly cleanupFailed: boolean; + readonly limit?: ImportLimit; - constructor(code: ImportStopCode, options: { cleanupFailed?: boolean } = {}) { + constructor( + code: ImportStopCode, + options: { cleanupFailed?: boolean; limit?: ImportLimit } = {} + ) { super(STOPS[code].text); this.name = "ImportStop"; this.code = code; this.next = STOPS[code].next; this.cleanupFailed = options.cleanupFailed ?? false; + this.limit = options.limit; } } @@ -86,6 +112,11 @@ const DOM_STOPS: Partial> = { NotFoundError: "FILE_UNREADABLE", }; +/** The fixed reason for a stop code, or null for a code this table does not hold. */ +export function importStopText(code: string): string | null { + return Object.hasOwn(STOPS, code) ? STOPS[code as ImportStopCode].text : null; +} + /** Whether the error is the pause signal rather than a failure. */ export function importPaused(error: unknown): boolean { return error instanceof DOMException && error.name === "AbortError"; @@ -96,14 +127,18 @@ export function importPaused(error: unknown): boolean { * keep their own content-free codes and wording. */ export function importStopFrom(error: unknown): ImportStop | null { - if (importPaused(error) || error instanceof HostedBrowserError) return null; + if (importPaused(error)) return null; + if (error instanceof HostedBrowserError) + return Object.hasOwn(STOPS, error.code) + ? new ImportStop(error.code as ImportStopCode, { + limit: importLimit.safeParse(error.limit).data, + }) + : null; if (error instanceof ImportStop) return error; if (error instanceof AggregateError) { const cause = importStopFrom(error.errors[0]); return new ImportStop(cause?.code ?? "STOPPED", { cleanupFailed: true }); } if (error instanceof DOMException) return new ImportStop(DOM_STOPS[error.name] ?? "STOPPED"); - // Fetch reports a network failure as a TypeError (Fetch standard, "network error"). - if (error instanceof TypeError) return new ImportStop("CONNECTION"); return new ImportStop("STOPPED"); } diff --git a/src/lib/exomem-hosted/cloud-imports.ts b/src/lib/exomem-hosted/cloud-imports.ts index 9a3c1505..df933177 100644 --- a/src/lib/exomem-hosted/cloud-imports.ts +++ b/src/lib/exomem-hosted/cloud-imports.ts @@ -2,6 +2,11 @@ import { randomUUID } from "node:crypto"; import { validate as validUuid } from "uuid"; import { cloudImportAvailable, + calculateImportAdmission, + IMPORT_GIB, + importPartLimits, + type ImportStorage, + type ImportLimit, MAX_IMPORT_PARTS, type CloudImport, type UploadPart, @@ -24,6 +29,21 @@ type CloudImportPrincipal = { cellId: string; cellDesiredState: string; }; +type CellRow = { + desired_state: string; + import_limits: unknown; + storage_gib: number; + grown_storage_gib: number | null; + used_bytes: string | null; + filesystem_bytes: string | null; + usage_observed_at: Date | null; + generation: string; + observed_storage_capacity_bytes: string | null; + observed_storage_generation: string | null; + observed_storage_pvc_uid: string | null; + observed_storage_pvc_version: string | null; + observed_storage_at: Date | null; +}; type PartETag = { part_number: number; etag: string }; type ImportRow = { import_id: string; @@ -41,12 +61,20 @@ type ImportRow = { urls_expire_at: Date | null; observed_state: string | null; error_code: string | null; + required_storage_gib: number | null; + staged_files: string | null; + staged_bytes: string | null; created_at: Date; updated_at: Date; }; -function importError(code: string, status: number, message: string): ExomemHostedError { - return new ExomemHostedError({ code, status, message }); +function importError( + code: string, + status: number, + message: string, + limit?: ImportLimit +): ExomemHostedError { + return new ExomemHostedError({ code, status, message, limit }); } const notFound = () => importError("IMPORT_NOT_FOUND", 404, "the import is unavailable"); const conflict = () => @@ -136,7 +164,46 @@ function storedCount(value: string): number { return parsed; } -function status(row: ImportRow): CloudImport { +function storage(cell: CellRow): ImportStorage { + return { + storage_gib: cell.storage_gib, + grown_storage_gib: cell.grown_storage_gib, + used_bytes: cell.used_bytes === null ? null : storedCount(cell.used_bytes), + filesystem_bytes: cell.filesystem_bytes === null ? null : storedCount(cell.filesystem_bytes), + observed_storage_capacity_bytes: + cell.observed_storage_capacity_bytes === null + ? null + : storedCount(cell.observed_storage_capacity_bytes), + usage_observed_at: cell.usage_observed_at?.toISOString() ?? null, + observed_storage_at: cell.observed_storage_at?.toISOString() ?? null, + }; +} + +// Each reader checks the keys it needs (D2), so any published object passes through whole. +function limits(cell: CellRow) { + const value = cell.import_limits; + return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null; +} + +function status(row: ImportRow, cell: CellRow): CloudImport { + const required = row.required_storage_gib === null ? null : row.required_storage_gib * IMPORT_GIB; + // Volumes never shrink, so an observed capacity that covers the requirement stays true even + // after an unrelated generation change. This is Home's display; cellctl's key wait decides. + const storageReady = + required === null + ? null + : Boolean( + cell.observed_storage_capacity_bytes !== null && + storedCount(cell.observed_storage_capacity_bytes) >= required && + cell.observed_storage_pvc_uid && + cell.observed_storage_pvc_version && + cell.observed_storage_at + ); + const staged = + row.observed_state === "done" && + row.requested_state !== "cancelled" && + row.requested_state !== "discard_requested"; + return { import_id: row.import_id, kind: row.kind, @@ -150,6 +217,10 @@ function status(row: ImportRow): CloudImport { error_code: row.error_code, ciphertext_sha256: row.ciphertext_sha256, ciphertext_bytes: row.ciphertext_bytes === null ? null : storedCount(row.ciphertext_bytes), + required_storage_bytes: required, + storage_ready: storageReady, + staged_files: staged && row.staged_files !== null ? storedCount(row.staged_files) : null, + staged_bytes: staged && row.staged_bytes !== null ? storedCount(row.staged_bytes) : null, created_at: row.created_at.toISOString(), updated_at: row.updated_at.toISOString(), }; @@ -159,25 +230,41 @@ export async function readCloudImport(principal: CloudImportPrincipal, importId? const id = importId === undefined ? null : uuid(importId); // Migration 0061 fixes the open predicate; default status prefers unfinished work over history. const { rows } = await executeExomemSql` - SELECT request.* FROM exomem_cloud_imports AS request - JOIN exomem_cloud_cells AS cell ON cell.cell_id = request.cell_id + SELECT request.*, cell.import_limits, cell.storage_gib, cell.grown_storage_gib, + cell.used_bytes, cell.filesystem_bytes, cell.usage_observed_at, cell.generation, + cell.observed_storage_capacity_bytes, cell.observed_storage_generation, + cell.observed_storage_pvc_uid, cell.observed_storage_pvc_version, cell.observed_storage_at + FROM exomem_cloud_cells AS cell JOIN exomem_tenants AS tenant ON tenant.id = cell.tenant_id + LEFT JOIN LATERAL ( + SELECT * FROM exomem_cloud_imports AS request + WHERE request.cell_id = cell.cell_id AND (${id}::uuid IS NULL OR request.import_id = ${id}::uuid) + ORDER BY (request.observed_state IS NULL + OR request.observed_state IN ('key_ready', 'importing', 'cleanup_running', 'cleanup_stopping', 'cleanup_discard_stopping', 'cleanup_pending') + OR (request.requested_state = 'discard_requested' AND request.observed_state IS DISTINCT FROM 'discarded')) DESC, + request.created_at DESC, request.import_id DESC LIMIT 1 + ) AS request ON true WHERE cell.cell_id = ${principal.cellId} AND cell.tenant_id = ${principal.tenantId}::uuid AND tenant.owner_user_id = ${principal.userId}::uuid AND tenant.status NOT IN ('deletion_pending', 'deleted') AND cell.desired_state <> 'deleted' - AND (${id}::uuid IS NULL OR request.import_id = ${id}::uuid) - ORDER BY (request.observed_state IS NULL - OR request.observed_state IN ('key_ready', 'importing', 'cleanup_running', 'cleanup_stopping', 'cleanup_discard_stopping', 'cleanup_pending') - OR (request.requested_state = 'discard_requested' AND request.observed_state IS DISTINCT FROM 'discarded')) DESC, - request.created_at DESC, request.import_id DESC LIMIT 1 `; - if (!rows[0] && id) throw notFound(); - return rows[0] ? status(rows[0] as ImportRow) : null; + const row = rows[0] as (ImportRow & CellRow) | undefined; + if (!row && !id) return { import: null, limits: null, storage: null }; + if (!row || (!row.import_id && id)) throw notFound(); + return { + import: row.import_id ? status(row, row) : null, + limits: limits(row), + storage: storage(row), + }; } async function lockCell(tx: ExomemSql, principal: CloudImportPrincipal, writable: boolean) { const { rows } = await tx` - SELECT cell.desired_state FROM exomem_cloud_cells AS cell + SELECT cell.desired_state, cell.import_limits, cell.storage_gib, cell.grown_storage_gib, + cell.used_bytes, cell.filesystem_bytes, cell.usage_observed_at, cell.generation, + cell.observed_storage_capacity_bytes, cell.observed_storage_generation, + cell.observed_storage_pvc_uid, cell.observed_storage_pvc_version, cell.observed_storage_at + FROM exomem_cloud_cells AS cell JOIN exomem_tenants AS tenant ON tenant.id = cell.tenant_id WHERE cell.cell_id = ${principal.cellId} AND cell.tenant_id = ${principal.tenantId}::uuid AND tenant.owner_user_id = ${principal.userId}::uuid @@ -187,6 +274,7 @@ async function lockCell(tx: ExomemSql, principal: CloudImportPrincipal, writable if (!rows[0]) throw notFound(); if (writable && !cloudImportAvailable(rows[0].desired_state)) throw exomemErrors.entitlementDenied(); + return rows[0] as CellRow; } export async function mutateCloudImport( @@ -224,7 +312,13 @@ export async function mutateCloudImport( const parts = action === "complete" ? partETags(body.part_etags) : null; try { return await withExomemTransaction(async (tx) => { - await lockCell(tx, principal, action === "create" || prepared !== null); + let cell = await lockCell(tx, principal, action === "create" || prepared !== null); + const reply = (row: ImportRow, created = false) => ({ + import: status(row, cell), + created, + limits: limits(cell), + storage: storage(cell), + }); const existing = await tx` SELECT * FROM exomem_cloud_imports WHERE import_id = ${id}::uuid AND cell_id = ${principal.cellId} FOR UPDATE @@ -238,14 +332,44 @@ export async function mutateCloudImport( storedCount(row.declared_files) !== creation.declared_files ) throw conflict(); - return { import: status(row), created: false }; + return reply(row); + } + const admission = calculateImportAdmission( + cell.import_limits, + storage(cell), + creation.declared_bytes, + creation.declared_files + ); + if (admission?.refusal) { + throw importError( + admission.refusal.code, + 422, + "the import exceeds a published limit", + admission.refusal.limit + ); + } + // Only a requirement above the current size writes the cell: raising storage_gib below a + // larger grown_storage_gib would bump the generation and restart the cell for nothing. + if ( + admission && + admission.required_storage_gib * IMPORT_GIB > admission.current_storage_bytes + ) { + const grown = await tx` + UPDATE exomem_cloud_cells SET storage_gib = GREATEST(storage_gib, ${admission.required_storage_gib}) + WHERE cell_id = ${principal.cellId} + RETURNING desired_state, import_limits, storage_gib, grown_storage_gib, used_bytes, + filesystem_bytes, usage_observed_at, generation, observed_storage_capacity_bytes, + observed_storage_generation, observed_storage_pvc_uid, observed_storage_pvc_version, + observed_storage_at + `; + cell = grown.rows[0] as CellRow; } const inserted = await tx` - INSERT INTO exomem_cloud_imports (import_id, cell_id, kind, declared_bytes, declared_files) - VALUES (${id}::uuid, ${principal.cellId}, ${creation.kind}, ${creation.declared_bytes}, ${creation.declared_files}) + INSERT INTO exomem_cloud_imports (import_id, cell_id, kind, declared_bytes, declared_files, required_storage_gib) + VALUES (${id}::uuid, ${principal.cellId}, ${creation.kind}, ${creation.declared_bytes}, ${creation.declared_files}, ${admission?.required_storage_gib ?? null}) RETURNING * `; - return { import: status(inserted.rows[0] as ImportRow), created: true }; + return reply(inserted.rows[0] as ImportRow, true); } if (!row) throw notFound(); if (prepared) { @@ -256,7 +380,26 @@ export async function mutateCloudImport( ) throw conflict(); if (action === "prepare-upload" && row.ciphertext_sha256 !== null) { - return { import: status(row), created: false }; + return reply(row); + } + if (action === "prepare-upload" && row.ciphertext_sha256 === null) { + const parsed = importPartLimits.safeParse(cell.import_limits); + // A wrong refusal costs a valid upload; only the published multipart ceiling prevents wasted transfer. + if ( + parsed.success && + prepared.ciphertext_bytes > parsed.data.max_parts * parsed.data.part_bytes + ) { + throw importError( + "IMPORT_PARTS_LIMIT", + 422, + "the encrypted upload exceeds a published limit", + { + unit: "bytes", + value: parsed.data.max_parts * parsed.data.part_bytes, + requested: prepared.ciphertext_bytes, + } + ); + } } if (parts && row.part_etags !== null) { if ( @@ -267,7 +410,7 @@ export async function mutateCloudImport( ) ) throw conflict(); - return { import: status(row), created: false }; + return reply(row); } if ( row.requested_state !== "requested" || @@ -310,10 +453,10 @@ export async function mutateCloudImport( operation_grant = ${operationGrant} WHERE import_id = ${id}::uuid AND cell_id = ${principal.cellId} RETURNING * `; - return { import: status(updated.rows[0] as ImportRow), created: false }; + return reply(updated.rows[0] as ImportRow); } const requested = action === "cancel" ? "cancelled" : "discard_requested"; - if (row.requested_state === requested) return { import: status(row), created: false }; + if (row.requested_state === requested) return reply(row); // C5 fixes terminal observations; cancellation must never invent one. if ( action === "cancel" && @@ -325,7 +468,7 @@ export async function mutateCloudImport( UPDATE exomem_cloud_imports SET requested_state = ${requested} WHERE import_id = ${id}::uuid AND cell_id = ${principal.cellId} RETURNING * `; - return { import: status(updated.rows[0] as ImportRow), created: false }; + return reply(updated.rows[0] as ImportRow); }); } catch (error) { if (error && typeof error === "object" && "code" in error && error.code === "23505") diff --git a/src/lib/exomem-hosted/errors.ts b/src/lib/exomem-hosted/errors.ts index 88e5f2bd..4d265db9 100644 --- a/src/lib/exomem-hosted/errors.ts +++ b/src/lib/exomem-hosted/errors.ts @@ -1,3 +1,5 @@ +import type { ImportLimit } from "../exomem/cloud-import-contract"; + export type ExomemHostedErrorEnvelope = { success: false; error: { @@ -7,6 +9,7 @@ export type ExomemHostedErrorEnvelope = { retryable: boolean; retryAfterMs?: number; remediation?: string; + limit?: ImportLimit; }; }; @@ -16,6 +19,7 @@ export class ExomemHostedError extends Error { readonly retryable: boolean; readonly retryAfterMs?: number; readonly remediation?: string; + readonly limit?: ImportLimit; constructor(params: { code: string; @@ -24,6 +28,7 @@ export class ExomemHostedError extends Error { retryable?: boolean; retryAfterMs?: number; remediation?: string; + limit?: ImportLimit; }) { super(params.message); this.name = "ExomemHostedError"; @@ -32,6 +37,7 @@ export class ExomemHostedError extends Error { this.retryable = params.retryable ?? false; this.retryAfterMs = params.retryAfterMs; this.remediation = params.remediation; + this.limit = params.limit; } toJSON(): ExomemHostedErrorEnvelope["error"] { @@ -41,6 +47,7 @@ export class ExomemHostedError extends Error { retryable: this.retryable, ...(this.retryAfterMs ? { retryAfterMs: this.retryAfterMs } : {}), ...(this.remediation ? { remediation: this.remediation } : {}), + ...(this.limit ? { limit: this.limit } : {}), }; } } @@ -198,6 +205,7 @@ export function safeErrorEnvelope(error: unknown, requestId?: string): ExomemHos retryable: safe.retryable, ...(safe.retryAfterMs ? { retryAfterMs: safe.retryAfterMs } : {}), ...(safe.remediation ? { remediation: safe.remediation } : {}), + ...(safe.limit ? { limit: safe.limit } : {}), }, }; } diff --git a/src/lib/exomem-hosted/hosted-browser.ts b/src/lib/exomem-hosted/hosted-browser.ts index fe203056..d6cae487 100644 --- a/src/lib/exomem-hosted/hosted-browser.ts +++ b/src/lib/exomem-hosted/hosted-browser.ts @@ -6,6 +6,7 @@ export type HostedErrorBody = { retryable?: boolean; requestId?: string; remediation?: string; + limit?: unknown; }; export class HostedBrowserError extends Error { @@ -15,6 +16,7 @@ export class HostedBrowserError extends Error { // The cell computes a remediation for refusals a person can act on. It was // being dropped here, so a fixable refusal read as an unexplained failure. readonly remediation?: string; + readonly limit?: unknown; constructor(error: HostedErrorBody, status: number) { super(error.message || "That did not work. Please try again."); @@ -23,6 +25,7 @@ export class HostedBrowserError extends Error { this.retryable = Boolean(error.retryable); this.status = status; if (error.remediation) this.remediation = error.remediation; + if (error.limit) this.limit = error.limit; } } @@ -41,6 +44,7 @@ function errorFrom(value: unknown): HostedErrorBody { retryable: error.retryable === true, requestId: typeof error.requestId === "string" ? error.requestId : undefined, remediation: typeof error.remediation === "string" ? error.remediation : undefined, + limit: error.limit, }; } } @@ -90,10 +94,10 @@ export async function postPrivateJson( path: string, body: Record, method: "POST" | "PUT" = "POST", - options: { csrfToken?: string; signal?: AbortSignal } = {} + options: { csrfToken?: string; signal?: AbortSignal; fetcher?: typeof fetch } = {} ): Promise> { const csrf = options.csrfToken === undefined ? csrfCookie() : options.csrfToken; - const response = await fetch(path, { + const response = await (options.fetcher ?? fetch)(path, { method, headers: { "content-type": "application/json", @@ -109,9 +113,10 @@ export async function postPrivateJson( export async function getPrivateJson( path: string, - signal?: AbortSignal + signal?: AbortSignal, + fetcher: typeof fetch = fetch ): Promise> { - const response = await fetch(path, { + const response = await fetcher(path, { method: "GET", credentials: "same-origin", cache: "no-store", diff --git a/src/lib/exomem/__tests__/cloud-import-contract.test.ts b/src/lib/exomem/__tests__/cloud-import-contract.test.ts new file mode 100644 index 00000000..ce4d17f6 --- /dev/null +++ b/src/lib/exomem/__tests__/cloud-import-contract.test.ts @@ -0,0 +1,116 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { calculateImportAdmission, cloudImportReply } from "../cloud-import-contract"; + +const GiB = 1024 ** 3; +const limits = { max_members: 500, reserve_bytes: GiB / 4, space_factor: 2, max_storage_gib: 20 }; +const storage = { + storage_gib: 4, + grown_storage_gib: null, + used_bytes: GiB, + filesystem_bytes: 4 * GiB, + observed_storage_capacity_bytes: 4 * GiB, +}; + +test("unpublished or invalid creation limits never invent an admission limit", () => { + for (const value of [null, [], {}, { ...limits, max_members: 0 }]) + assert.equal(calculateImportAdmission(value, storage, 1, 1), null); +}); + +test("unknown usage treats the whole current volume as used without a stale ratio", () => { + const result = calculateImportAdmission( + limits, + { ...storage, grown_storage_gib: 6, used_bytes: null, filesystem_bytes: GiB }, + GiB, + 1 + )!; + assert.equal(result.need_bytes, 8.25 * GiB); + assert.equal(result.required_storage_gib, 9); +}); + +test("a usage reading older than the last capacity reading cannot inflate growth", () => { + // After growth to 20 GiB the filesystem reading still describes the old 1.9 GiB volume. + const result = calculateImportAdmission( + { ...limits, max_storage_gib: 100 }, + { + ...storage, + storage_gib: 20, + filesystem_bytes: Math.floor(1.9 * GiB), + observed_storage_capacity_bytes: 20 * GiB, + usage_observed_at: "2026-01-01T00:00:00Z", + observed_storage_at: "2026-01-02T00:00:00Z", + }, + GiB, + 1 + )!; + assert.equal(result.need_bytes, 3.25 * GiB); + assert.ok(result.required_storage_gib <= 20); + assert.equal(result.refusal, null); +}); + +test("a usage reading of the current volume scales the need by its filesystem overhead", () => { + const result = calculateImportAdmission( + limits, + { + ...storage, + filesystem_bytes: 3.5 * GiB, + usage_observed_at: "2026-01-02T00:00:00Z", + observed_storage_at: "2026-01-01T00:00:00Z", + }, + GiB, + 1 + )!; + assert.equal(result.need_bytes, Math.ceil(3.25 * GiB * (4 / 3.5))); +}); + +test("storage raised above the published cap admits against the larger current size", () => { + const result = calculateImportAdmission(limits, { ...storage, storage_gib: 30 }, 12 * GiB, 1)!; + assert.equal(result.refusal, null); + assert.equal(result.cap_bytes, 30 * GiB); + assert.ok(result.required_storage_gib <= 30); +}); + +test("admission returns content-free member and unscaled storage limits", () => { + assert.deepEqual(calculateImportAdmission(limits, storage, 1, 501)!.refusal, { + code: "IMPORT_TOO_MANY_FILES", + limit: { unit: "files", value: 500, requested: 501 }, + }); + assert.deepEqual(calculateImportAdmission(limits, storage, 10 * GiB, 1)!.refusal, { + code: "IMPORT_STORAGE_LIMIT", + limit: { unit: "bytes", value: 20 * GiB, requested: 20.25 * GiB }, + }); +}); + +test("an above-cap cell admits against its larger published cap", () => { + const result = calculateImportAdmission( + { ...limits, max_storage_gib: 30 }, + { ...storage, storage_gib: 30 }, + 12 * GiB, + 1 + )!; + assert.equal(result.current_storage_bytes, 30 * GiB); + assert.equal(result.required_storage_gib, 26); + assert.equal(result.refusal, null); +}); + +test("an older import reply parses without any new optional fields", () => { + const older = { + import: { + import_id: "11111111-1111-4111-8111-111111111111", + kind: "adopt", + declared_bytes: 1, + declared_files: 1, + requested_state: "requested", + observed_state: "pending", + recipient: null, + part_urls: null, + urls_expire_at: null, + error_code: null, + ciphertext_sha256: null, + ciphertext_bytes: null, + created_at: "2026-01-01T00:00:00Z", + updated_at: "2026-01-01T00:00:00Z", + }, + }; + assert.deepEqual(cloudImportReply.parse(older), older); +}); diff --git a/src/lib/exomem/cloud-import-contract.ts b/src/lib/exomem/cloud-import-contract.ts index e63ab6a6..afa9aeb6 100644 --- a/src/lib/exomem/cloud-import-contract.ts +++ b/src/lib/exomem/cloud-import-contract.ts @@ -1,6 +1,86 @@ import { z } from "zod"; const count = z.number().int().nonnegative().safe(); +const positive = z.number().int().positive().safe(); +export const IMPORT_GIB = 1024 ** 3; + +// These keys and units are the additive C5 protocol, not tenant vocabulary. +const admissionLimits = z.object({ + max_members: positive, + reserve_bytes: positive, + space_factor: positive, + max_storage_gib: positive, +}); +export const importPartLimits = z.object({ part_bytes: positive, max_parts: positive }); +/** Home needs this key only to bound its wait for growth, not to apply the other limits. */ +export const importGrowthDeadline = z.object({ import_growth_deadline_seconds: positive }); +export const importLimit = z.object({ + unit: z.enum(["files", "bytes"]), + value: count, + requested: count, +}); +export type ImportLimit = z.infer; + +const importStorage = z.object({ + storage_gib: positive, + grown_storage_gib: positive.nullable(), + used_bytes: count.nullable(), + filesystem_bytes: positive.nullable(), + observed_storage_capacity_bytes: positive.nullable(), + usage_observed_at: z.iso.datetime({ offset: true }).nullable().optional(), + observed_storage_at: z.iso.datetime({ offset: true }).nullable().optional(), +}); +export type ImportStorage = z.infer; + +/** Shared admission: stale usage can size growth, but only an empty-vault lower bound refuses. */ +export function calculateImportAdmission( + published: unknown, + storage: ImportStorage, + declaredBytes: number, + members: number +) { + const parsed = admissionLimits.safeParse(published); + if (!parsed.success) return null; + const limits = parsed.data; + const currentGib = Math.max(storage.storage_gib, storage.grown_storage_gib ?? 0); + const current = currentGib * IMPORT_GIB; + // The capacity-to-filesystem ratio is only valid when both readings describe the same volume: + // a usage reading older than the last capacity reading predates growth and would inflate it. + const sameVolume = + storage.usage_observed_at != null && + storage.observed_storage_at != null && + Date.parse(storage.usage_observed_at) >= Date.parse(storage.observed_storage_at); + const ratio = + sameVolume && storage.filesystem_bytes && storage.observed_storage_capacity_bytes + ? Math.max(1, storage.observed_storage_capacity_bytes / storage.filesystem_bytes) + : 1; + const lowerBound = limits.space_factor * declaredBytes + limits.reserve_bytes; + const need = Math.ceil(((storage.used_bytes ?? current) + lowerBound) * ratio); + // Paid storage can raise the volume before cellctl republishes its cap; the larger one holds. + const capGib = Math.max(limits.max_storage_gib, currentGib); + const cap = capGib * IMPORT_GIB; + // Wrong refusals cost owners a valid import; only necessary limits may prevent wasted transfer. + const refusal = + members > limits.max_members + ? { + code: "IMPORT_TOO_MANY_FILES" as const, + limit: { unit: "files" as const, value: limits.max_members, requested: members }, + } + : lowerBound > cap + ? { + code: "IMPORT_STORAGE_LIMIT" as const, + limit: { unit: "bytes" as const, value: cap, requested: lowerBound }, + } + : null; + return { + limits, + need_bytes: need, + current_storage_bytes: current, + cap_bytes: cap, + required_storage_gib: Math.min(Math.ceil(need / IMPORT_GIB), capGib), + refusal, + }; +} /** S3's multipart protocol fixes this maximum number of numbered parts. */ export const MAX_IMPORT_PARTS = 10_000; @@ -25,13 +105,20 @@ const cloudImport = z.object({ error_code: z.string().nullable(), ciphertext_sha256: z.string().nullable(), ciphertext_bytes: count.nullable(), + required_storage_bytes: count.nullable().optional(), + storage_ready: z.boolean().nullable().optional(), staged_files: count.nullable().optional(), staged_bytes: count.nullable().optional(), created_at: z.iso.datetime({ offset: true }), updated_at: z.iso.datetime({ offset: true }), }); -export const cloudImportReply = z.object({ import: cloudImport.nullable() }); +export const cloudImportReply = z.object({ + import: cloudImport.nullable(), + limits: z.record(z.string(), z.unknown()).nullable().optional(), + storage: importStorage.nullable().optional(), +}); +export type CloudImportReply = z.infer; export type CloudImport = z.infer; export type UploadPart = z.infer; diff --git a/src/lib/exomem/theme-script.generated.ts b/src/lib/exomem/theme-script.generated.ts index 5b5a1bb8..931fdef5 100644 --- a/src/lib/exomem/theme-script.generated.ts +++ b/src/lib/exomem/theme-script.generated.ts @@ -1,4 +1,4 @@ // Generated from theme-prepaint.ts by scripts/build-exomem-theme.mjs. // prettier-ignore export const exomemThemeScript = - "\"use strict\";(()=>{var z=Object.defineProperty;var K=(t,e,n)=>e in t?z(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var h=(t,e,n)=>K(t,typeof e!=\"symbol\"?e+\"\":e,n);var q=[\"docs\",\"benchmarks\",\"privacy\",\"terms\",\"support\"],Y=[\"access-log\",\"authorize\",\"delete\",\"design-system\",\"email-change\",\"email-preview\",\"home\",\"invite\",\"operator\",\"setup\",\"sign-in\",\"unsubscribe\",\"viewer\"];function Q(t){return Y.includes(t.split(\"/\")[1]??\"\")}function H(t){return t===\"/\"||q.includes(t.slice(1))||Q(t)}function L(t){for(let e of(document.cookie??\"\").split(\";\")){let[n,...o]=e.trim().split(\"=\");if(n===t)return decodeURIComponent(o.join(\"=\"))}return\"\"}function P(){return L(\"exomem_csrf\")}function Z(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name===\"Uint8Array\"&&\"BYTES_PER_ELEMENT\"in t&&t.BYTES_PER_ELEMENT===1}function w(t,e,n=\"\"){let o=Z(t),r=t?.length,c=e!==void 0;if(!o||c&&r!==e){let s=n&&`\"${n}\" `,i=c?` of length ${e}`:\"\",f=o?`length=${r}`:`type=${typeof t}`,u=s+\"expected Uint8Array\"+i+\", got \"+f;throw o?new RangeError(u):new TypeError(u)}return t}function C(t,e=!0){if(t.destroyed)throw new Error(\"Hash instance has been destroyed\");if(e&&t.finished)throw new Error(\"Hash#digest() has already been called\")}function O(t,e){w(t,void 0,\"digestInto() output\");let n=e.outputLen;if(t.length='+n)}function y(...t){for(let e=0;e>>e}var ee=typeof Uint8Array.from([]).toHex==\"function\"&&typeof Uint8Array.fromHex==\"function\",te=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,\"0\"));function k(t){if(w(t),ee)return t.toHex();let e=\"\";for(let n=0;nt(c).update(r).digest(),o=t(void 0);return n.outputLen=o.outputLen,n.blockLen=o.blockLen,n.canXOF=o.canXOF,n.create=r=>t(r),Object.assign(n,e),Object.freeze(n)}var R=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function M(t,e,n){return t&e^~t&n}function F(t,e,n){return t&e^t&n^e&n}var T=class{constructor(e,n,o,r){h(this,\"blockLen\");h(this,\"outputLen\");h(this,\"canXOF\",!1);h(this,\"padOffset\");h(this,\"isLE\");h(this,\"buffer\");h(this,\"view\");h(this,\"finished\",!1);h(this,\"length\",0);h(this,\"pos\",0);h(this,\"destroyed\",!1);this.blockLen=e,this.outputLen=n,this.padOffset=o,this.isLE=r,this.buffer=new Uint8Array(e),this.view=A(this.buffer)}update(e){C(this),w(e);let{view:n,buffer:o,blockLen:r}=this,c=e.length;for(let s=0;sr-s&&(this.process(o,0),s=0);for(let a=s;al.length)throw new Error(\"_sha2: outputLen bigger than state\");for(let a=0;a>>3,S=d(p,17)^d(p,19)^p>>>10;m[a]=S+m[a-7]+U+m[a-16]|0}let{A:o,B:r,C:c,D:s,E:i,F:f,G:u,H:l}=this;for(let a=0;a<64;a++){let g=d(i,6)^d(i,11)^d(i,25),p=l+g+M(i,f,u)+ne[a]+m[a]|0,S=(d(o,2)^d(o,13)^d(o,22))+F(o,r,c)|0;l=u,u=f,f=i,i=s+p|0,s=c,c=r,r=o,o=p+S|0}o=o+this.A|0,r=r+this.B|0,c=c+this.C|0,s=s+this.D|0,i=i+this.E|0,f=f+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(o,r,c,s,i,f,u,l)}roundClean(){y(m)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),y(this.buffer)}},I=class extends v{constructor(){super(32);h(this,\"A\",x[0]|0);h(this,\"B\",x[1]|0);h(this,\"C\",x[2]|0);h(this,\"D\",x[3]|0);h(this,\"E\",x[4]|0);h(this,\"F\",x[5]|0);h(this,\"G\",x[6]|0);h(this,\"H\",x[7]|0)}};var _=D(()=>new I,R(1));var oe=\"exomem_theme_v2_\";function re(t){return k(_(B(`exomem-theme-v2:${k(t)}`)))}function G(t){return t?re(_(B(t))):\"\"}function $(t){return`${oe}${t}`}function N(t,e){return t===\"auto\"?e?\"light\":\"dark\":t}function se(t){if(typeof t!=\"string\"||t.length>2048)return null;try{let e=JSON.parse(t);return!e||typeof e!=\"object\"||Array.isArray(e)||typeof e.scope!=\"string\"||e.scope.length>128||typeof e.binding!=\"string\"||e.binding.length>128||e.choice!==null&&e.choice!==\"auto\"&&e.choice!==\"light\"&&e.choice!==\"dark\"||e.effective!==null&&e.effective!==\"light\"&&e.effective!==\"dark\"||e.expiresAt!==null&&(typeof e.expiresAt!=\"string\"||!Number.isFinite(Date.parse(e.expiresAt))||Date.parse(e.expiresAt)<=Date.now())?null:e}catch{return null}}var b={choice:\"exomem-theme-choice\",legacy:\"exomem-theme\",account:\"exomem-theme-account\"};function ie(t){let e=X(),n=null;try{n=se(L($(e)))}catch{}e&&n?.binding!==e?n={scope:\"\",binding:e,choice:\"auto\",effective:null,expiresAt:null}:e||(n=null);let o=\"auto\";try{let i=window.localStorage.getItem(b.choice);if(i===null){let f=window.localStorage.getItem(b.legacy);i=f===\"light\"||f===\"dark\"?f:\"auto\",window.localStorage.setItem(b.choice,i),window.localStorage.removeItem(b.legacy)}(i===\"light\"||i===\"dark\")&&(o=i)}catch{}let r=n?n.scope?n.choice??o:\"auto\":o;try{n?.scope?window.localStorage.setItem(b.account,JSON.stringify({scope:n.scope,choice:r})):window.localStorage.removeItem(b.account)}catch{}let c=!1;if(r===\"auto\")try{c=window.matchMedia(\"(prefers-color-scheme: light)\").matches}catch{}let s=N(r,c);return t.setAttribute(\"data-exomem\",\"\"),t.setAttribute(\"data-theme-choice\",r),t.setAttribute(\"data-theme-scope\",n?.scope??\"\"),t.setAttribute(\"data-theme-initialized\",n?.scope&&n.choice===null?\"false\":\"true\"),t.getAttribute(\"data-theme\")!==s&&t.setAttribute(\"data-theme\",s),s}function V(t,e=!1){return t===\"/exomem\"||t.indexOf(\"/exomem/\")===0||e&&H(t)}function j(t,e){let n=t.getAttribute(\"data-exomem-product-host\");return!!n&&n===e}var ce={status:\"idle\",error:null},E=null,_e=Promise.resolve();function ae(t){return t.getAttribute(\"data-theme\")===\"light\"?\"light\":\"dark\"}function fe(t,e){let n=!1;if(e===\"auto\")try{n=window.matchMedia(\"(prefers-color-scheme: light)\").matches}catch{}let o=N(e,n);t.setAttribute(\"data-theme-choice\",e),t.getAttribute(\"data-theme\")!==o&&t.setAttribute(\"data-theme\",o)}function J(t){ie(t);let e=t.getAttribute(\"data-theme-scope\")??\"\";return E?.scope===e&&E.binding===X()?fe(t,E.choice):E&&(E=null,ce={status:\"idle\",error:null}),ae(t)}function X(){try{return G(P())}catch{return\"\"}}var W=document.documentElement;V(location.pathname,j(W,location.hostname))&&J(W);})();"; + "\"use strict\";(()=>{var z=Object.defineProperty;var K=(t,e,n)=>e in t?z(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var h=(t,e,n)=>K(t,typeof e!=\"symbol\"?e+\"\":e,n);var q=[\"docs\",\"benchmarks\",\"privacy\",\"terms\",\"support\"],Y=[\"access-log\",\"authorize\",\"delete\",\"design-system\",\"email-change\",\"email-preview\",\"home\",\"invite\",\"operator\",\"setup\",\"sign-in\",\"unsubscribe\",\"viewer\"];function Q(t){return Y.includes(t.split(\"/\")[1]??\"\")}function H(t){return t===\"/\"||q.includes(t.slice(1))||Q(t)}function L(t){for(let e of(document.cookie??\"\").split(\";\")){let[n,...o]=e.trim().split(\"=\");if(n===t)return decodeURIComponent(o.join(\"=\"))}return\"\"}function P(){return L(\"exomem_csrf\")}function Z(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name===\"Uint8Array\"&&\"BYTES_PER_ELEMENT\"in t&&t.BYTES_PER_ELEMENT===1}function w(t,e,n=\"\"){let o=Z(t),r=t?.length,c=e!==void 0;if(!o||c&&r!==e){let i=n&&`\"${n}\" `,s=c?` of length ${e}`:\"\",f=o?`length=${r}`:`type=${typeof t}`,u=i+\"expected Uint8Array\"+s+\", got \"+f;throw o?new RangeError(u):new TypeError(u)}return t}function C(t,e=!0){if(t.destroyed)throw new Error(\"Hash instance has been destroyed\");if(e&&t.finished)throw new Error(\"Hash#digest() has already been called\")}function O(t,e){w(t,void 0,\"digestInto() output\");let n=e.outputLen;if(t.length='+n)}function y(...t){for(let e=0;e>>e}var ee=typeof Uint8Array.from([]).toHex==\"function\"&&typeof Uint8Array.fromHex==\"function\",te=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,\"0\"));function k(t){if(w(t),ee)return t.toHex();let e=\"\";for(let n=0;nt(c).update(r).digest(),o=t(void 0);return n.outputLen=o.outputLen,n.blockLen=o.blockLen,n.canXOF=o.canXOF,n.create=r=>t(r),Object.assign(n,e),Object.freeze(n)}var R=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function M(t,e,n){return t&e^~t&n}function F(t,e,n){return t&e^t&n^e&n}var T=class{constructor(e,n,o,r){h(this,\"blockLen\");h(this,\"outputLen\");h(this,\"canXOF\",!1);h(this,\"padOffset\");h(this,\"isLE\");h(this,\"buffer\");h(this,\"view\");h(this,\"finished\",!1);h(this,\"length\",0);h(this,\"pos\",0);h(this,\"destroyed\",!1);this.blockLen=e,this.outputLen=n,this.padOffset=o,this.isLE=r,this.buffer=new Uint8Array(e),this.view=A(this.buffer)}update(e){C(this),w(e);let{view:n,buffer:o,blockLen:r}=this,c=e.length;for(let i=0;ir-i&&(this.process(o,0),i=0);for(let a=i;al.length)throw new Error(\"_sha2: outputLen bigger than state\");for(let a=0;a>>3,S=d(p,17)^d(p,19)^p>>>10;m[a]=S+m[a-7]+U+m[a-16]|0}let{A:o,B:r,C:c,D:i,E:s,F:f,G:u,H:l}=this;for(let a=0;a<64;a++){let g=d(s,6)^d(s,11)^d(s,25),p=l+g+M(s,f,u)+ne[a]+m[a]|0,S=(d(o,2)^d(o,13)^d(o,22))+F(o,r,c)|0;l=u,u=f,f=s,s=i+p|0,i=c,c=r,r=o,o=p+S|0}o=o+this.A|0,r=r+this.B|0,c=c+this.C|0,i=i+this.D|0,s=s+this.E|0,f=f+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(o,r,c,i,s,f,u,l)}roundClean(){y(m)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),y(this.buffer)}},I=class extends v{constructor(){super(32);h(this,\"A\",x[0]|0);h(this,\"B\",x[1]|0);h(this,\"C\",x[2]|0);h(this,\"D\",x[3]|0);h(this,\"E\",x[4]|0);h(this,\"F\",x[5]|0);h(this,\"G\",x[6]|0);h(this,\"H\",x[7]|0)}};var _=D(()=>new I,R(1));var oe=\"exomem_theme_v2_\";function re(t){return k(_(B(`exomem-theme-v2:${k(t)}`)))}function G(t){return t?re(_(B(t))):\"\"}function $(t){return`${oe}${t}`}function N(t,e){return t===\"auto\"?e?\"light\":\"dark\":t}function ie(t){if(typeof t!=\"string\"||t.length>2048)return null;try{let e=JSON.parse(t);return!e||typeof e!=\"object\"||Array.isArray(e)||typeof e.scope!=\"string\"||e.scope.length>128||typeof e.binding!=\"string\"||e.binding.length>128||e.choice!==null&&e.choice!==\"auto\"&&e.choice!==\"light\"&&e.choice!==\"dark\"||e.effective!==null&&e.effective!==\"light\"&&e.effective!==\"dark\"||e.expiresAt!==null&&(typeof e.expiresAt!=\"string\"||!Number.isFinite(Date.parse(e.expiresAt))||Date.parse(e.expiresAt)<=Date.now())?null:e}catch{return null}}var b={choice:\"exomem-theme-choice\",legacy:\"exomem-theme\",account:\"exomem-theme-account\"};function se(t){let e=X(),n=null;try{n=ie(L($(e)))}catch{}e&&n?.binding!==e?n={scope:\"\",binding:e,choice:\"auto\",effective:null,expiresAt:null}:e||(n=null);let o=\"auto\";try{let s=window.localStorage.getItem(b.choice);if(s===null){let f=window.localStorage.getItem(b.legacy);s=f===\"light\"||f===\"dark\"?f:\"auto\",window.localStorage.setItem(b.choice,s),window.localStorage.removeItem(b.legacy)}(s===\"light\"||s===\"dark\")&&(o=s)}catch{}let r=n?n.scope?n.choice??o:\"auto\":o;try{n?.scope?window.localStorage.setItem(b.account,JSON.stringify({scope:n.scope,choice:r})):window.localStorage.removeItem(b.account)}catch{}let c=!1;if(r===\"auto\")try{c=window.matchMedia(\"(prefers-color-scheme: light)\").matches}catch{}let i=N(r,c);return t.setAttribute(\"data-exomem\",\"\"),t.setAttribute(\"data-theme-choice\",r),t.setAttribute(\"data-theme-scope\",n?.scope??\"\"),t.setAttribute(\"data-theme-initialized\",n?.scope&&n.choice===null?\"false\":\"true\"),t.getAttribute(\"data-theme\")!==i&&t.setAttribute(\"data-theme\",i),i}function V(t,e=!1){return t===\"/exomem\"||t.indexOf(\"/exomem/\")===0||e&&H(t)}function j(t,e){let n=t.getAttribute(\"data-exomem-product-host\");return!!n&&n===e}var ce={status:\"idle\",error:null},E=null,_e=Promise.resolve();function ae(t){return t.getAttribute(\"data-theme\")===\"light\"?\"light\":\"dark\"}function fe(t,e){let n=!1;if(e===\"auto\")try{n=window.matchMedia(\"(prefers-color-scheme: light)\").matches}catch{}let o=N(e,n);t.setAttribute(\"data-theme-choice\",e),t.getAttribute(\"data-theme\")!==o&&t.setAttribute(\"data-theme\",o)}function J(t){se(t);let e=t.getAttribute(\"data-theme-scope\")??\"\";return E?.scope===e&&E.binding===X()?fe(t,E.choice):E&&(E=null,ce={status:\"idle\",error:null}),ae(t)}function X(){try{return G(P())}catch{return\"\"}}var W=document.documentElement;V(location.pathname,j(W,location.hostname))&&J(W);})();";