From 86e35c12ba43b080a07e1b0c0dd991566665ab38 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Mon, 26 Oct 2026 11:04:29 +0000 Subject: [PATCH 01/13] feat(cloud): admit imports against published limits --- e2e/exomem-home/import.spec.ts | 164 +++++++++++ .../design.md | 18 +- .../proposal.md | 2 + .../specs/exomem-tenant-control-plane/spec.md | 25 +- .../tasks.md | 16 +- .../tasks.md | 8 +- .../home/__tests__/home-import.test.tsx | 196 ++++++++++++- src/app/exomem/home/home-import-panels.tsx | 76 ++++- src/app/exomem/home/home-import.tsx | 113 ++++++-- .../cloud-import-browser-api.test.ts | 13 + .../cloud-import-browser-file.test.ts | 24 ++ .../cloud-import-browser-upload.test.ts | 56 +++- .../__tests__/cloud-import-browser.test.ts | 2 +- ...cloud-imports-postgres.integration.test.ts | 262 +++++++++++++++++- .../exomem-hosted/cloud-import-browser-api.ts | 35 ++- .../cloud-import-browser-file.ts | 102 ++++++- .../cloud-import-browser-upload.ts | 19 +- src/lib/exomem-hosted/cloud-import-browser.ts | 14 +- src/lib/exomem-hosted/cloud-import-http.ts | 4 +- .../exomem-hosted/cloud-import-selection.ts | 4 +- src/lib/exomem-hosted/cloud-import-stop.ts | 40 ++- src/lib/exomem-hosted/cloud-imports.ts | 178 ++++++++++-- src/lib/exomem-hosted/errors.ts | 8 + src/lib/exomem-hosted/hosted-browser.ts | 13 +- .../__tests__/cloud-import-contract.test.ts | 91 ++++++ src/lib/exomem/cloud-import-contract.ts | 81 +++++- src/lib/exomem/theme-script.generated.ts | 2 +- 27 files changed, 1453 insertions(+), 113 deletions(-) create mode 100644 src/lib/exomem/__tests__/cloud-import-contract.test.ts diff --git a/e2e/exomem-home/import.spec.ts b/e2e/exomem-home/import.spec.ts index 3f403023..e2bbd091 100644 --- a/e2e/exomem-home/import.spec.ts +++ b/e2e/exomem-home/import.spec.ts @@ -358,3 +358,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: "Import…", exact: true }).click(); + let dialog = page.getByRole("dialog"); + await dialog.getByLabel("Folder to import").setInputFiles(folder); + await expect(dialog.getByText("grows to about", { exact: false })).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: "Import…", 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: "Import…", exact: true }).click(); + await expect( + page.getByRole("dialog").getByText("Staged originals", { exact: true }) + ).toBeVisible(); + await expect( + page.getByRole("dialog").getByText("1 file · 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..6eab2d3c 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/design.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/design.md @@ -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 @@ -101,7 +103,7 @@ The `IMPORT_STORAGE_LIMIT` check uses the unscaled lower bound `space_factor × ### 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. @@ -124,7 +126,7 @@ 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` and `usage_observed_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 @@ -136,7 +138,9 @@ Home's wait for `key_ready` has no bound of its own. It follows the import's obs ### D9. Staged and adopted 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. + +Import replies expose the pair only when the import is `done` with no pending cancellation or discard. Otherwise both fields are null. Home shows recorded counts instead of the declared counts. An import without them shows "not recorded". Missing or malformed reports remain unknown and do not block cleanup. 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. @@ -158,11 +162,11 @@ 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. +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. 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..73a817bc 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/proposal.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/proposal.md @@ -33,4 +33,6 @@ Cellctl publishes each cell's effective limits. Admission grows `storage_gib` wi 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-tenant-control-plane/spec.md b/openspec/changes/admit-cloud-imports-against-published-limits/specs/exomem-tenant-control-plane/spec.md index 6097f6a7..60aba694 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` for each live cell whose storage has passed its rollout gate. It SHALL rewrite the value only when its content changes. Cellctl SHALL inspect the actual claim class and actively write NULL for local claims until authoritative shared capacity accounting and the local rehearsal pass. This SHALL clear any previously published object. Local publication and import growth SHALL remain open work in the paired Exomem task 1.7. 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 @@ -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 `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 authoritative capacity accounting shared by local volume consumers and this behavior pass the local cutover check. Until that gate passes, cellctl SHALL actively publish NULL for local claims. #### 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` and `usage_observed_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 observed capacity covers `required_storage_bytes` and its storage receipt shows no resize pending. 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..ea3805f4 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/tasks.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/tasks.md @@ -8,16 +8,16 @@ The packets P1 to P7 below match the paired Exomem change `publish-cloud-import- ## 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 counts from the Job's report and "not recorded" for older imports. Verify: a component test with and without counts. ## 4. Browser follow-ups (P5) @@ -33,3 +33,5 @@ The follow-ups from the first Home import change live in `make-home-import-visib - [ ] 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. + +- [ ] 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. 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/src/app/exomem/home/__tests__/home-import.test.tsx b/src/app/exomem/home/__tests__/home-import.test.tsx index 03fdd29d..4394db2c 100644 --- a/src/app/exomem/home/__tests__/home-import.test.tsx +++ b/src/app/exomem/home/__tests__/home-import.test.tsx @@ -46,7 +46,11 @@ function folder(name: string, notes: number) { }); } -async function home(options: { quota?: number; api: ReturnType }) { +async function home(options: { + quota?: number; + api: ReturnType; + context?: Record; +}) { const dom = new JSDOM('
', { url: "http://localhost/exomem/home", }); @@ -66,7 +70,15 @@ async function home(options: { quota?: number; api: ReturnType { + 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 }); @@ -142,7 +154,10 @@ it("closing the dialog keeps the import running, and a pause shows how to resume await page.click("Import…"); await page.click("Pause"); await page.until( - () => page.text().includes("Paused. Parts already uploaded from this page are kept."), + () => + page + .text() + .includes("Paused. Confirmed parts are kept in this browser, including after a reload."), "the paused state" ); assert.ok(page.button("Resume upload")); @@ -200,3 +215,178 @@ it("a folder whose encrypted copy cannot fit in this browser is refused before a assert.equal(page.button("Encrypt and upload"), undefined); 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 counts folders as members and refuses a selection above the published maximum", async () => { + const api = importApiDouble("unused"); + const page = await home({ + api, + context: { limits: { ...published, max_members: 3 }, storage: readings }, + }); + await page.click("Import…"); + await page.choose(folder("research", 3)); + await page.until(() => page.text().includes("4 of 3"), "the member limit"); + assert.equal(page.button("Encrypt and upload"), undefined); + assert.equal(api.rows.size, 0); +}); + +it("preflight shows growth, the reserve warning and the measured reading without refusing existing-content pressure", async () => { + const page = await home({ + api: importApiDouble("unused"), + context: { limits: published, storage: readings }, + }); + await page.click("Import…"); + await page.choose(folder("research", 1)); + await page.until(() => page.text().includes("grows to about"), "the storage growth estimate"); + assert.ok(page.text().includes("reserve")); + assert.ok(page.button("Encrypt and upload")); +}); + +it("preflight refuses the unscaled lower bound above the 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("Import…"); + await page.choose(folder("research", 1)); + 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("Import…"); + await page.choose(folder("research", 1)); + await page.until( + () => page.text().includes("Limits not published"), + "the unpublished limit notice" + ); + assert.ok(page.button("Encrypt and upload")); +}); + +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("Import…"); + await page.until(() => page.text().includes("60 minutes"), "the published wait bound"); + assert.ok(page.text().includes("waiting for its encrypted copy")); + 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("Import…"); + 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")); +}); + +it("staged totals use the Job report and older imports say not recorded", async () => { + const api = importApiDouble("unused"); + const id = crypto.randomUUID(); + const row = { + import_id: id, + kind: "adopt", + declared_files: 99, + declared_bytes: 9999, + requested_state: "uploaded", + observed_state: "done", + recipient: null, + part_urls: null, + urls_expire_at: null, + error_code: null, + ciphertext_sha256: "a".repeat(64), + ciphertext_bytes: 999, + staged_files: 2, + staged_bytes: 2048, + created_at: "2026-01-01T00:00:00Z", + updated_at: "2026-01-01T00:00:00Z", + }; + api.rows.set(id, row); + let page = await home({ api }); + await page.click("Import…"); + await page.until(() => page.text().includes("2 files · 2 kB"), "the staged report"); + await cleanup?.(); + cleanup = null; + Object.assign(row, { staged_files: null, staged_bytes: null }); + page = await home({ api }); + await page.click("Import…"); + await page.until(() => page.text().includes("not recorded"), "the unknown staged count"); +}); + +for (const [code, unit, reason] of [ + ["IMPORT_TOO_MANY_FILES", "files", "more members 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("Import…"); + await page.choose(folder("research", 1)); + await page.click("Encrypt and upload"); + await page.until(() => page.text().includes(reason), "the fixed refusal"); + assert.ok(page.text().includes("Requested:")); + assert.ok(page.text().includes("Published limit:")); + assert.ok(!page.text().includes("untrusted wording")); + assert.ok(page.text().includes(code)); + }); +} diff --git a/src/app/exomem/home/home-import-panels.tsx b/src/app/exomem/home/home-import-panels.tsx index e1943c1a..5ec2d1e8 100644 --- a/src/app/exomem/home/home-import-panels.tsx +++ b/src/app/exomem/home/home-import-panels.tsx @@ -11,6 +11,11 @@ import { type IncludeChoices, 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 } from "./home-format"; import styles from "./home.module.css"; @@ -23,10 +28,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, }; } @@ -93,6 +98,8 @@ export function ImportExclusions({ /** The selection beside every limit Home can measure before the upload starts. */ export function ImportLimits({ forecast, + admission, + importStorage, room, others, storage, @@ -101,6 +108,8 @@ export function ImportLimits({ onDiscardOthers, }: { forecast: ImportForecast; + admission: ReturnType; + importStorage: ImportStorage | null; room: BrowserRoom; /** Kept copies outside this account's folder; null when they could not be read. */ others: SelectionTotals | null; @@ -110,10 +119,40 @@ 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); return ( <>
+ {admission && ( + <> +
+
Archive members
+
+ {count(forecast.members)} of {count(admission.limits.max_members)} (files and + folders) +
+
+
+
Storage needed
+
+ {byteSize(admission.need_bytes)} of{" "} + {byteSize(admission.limits.max_storage_gib * IMPORT_GIB)} maximum +
+
+ + )}
Encrypted copy
{byteSize(forecast.ciphertextBytes)}
@@ -144,6 +183,24 @@ export function ImportLimits({ ) )}
+ {!admission && ( +

Limits not published; the cell checks during import.

+ )} + {admission?.refusal && ( + + {admission.refusal.code === "IMPORT_TOO_MANY_FILES" + ? "This folder has more members than the published maximum. Choose a smaller folder." + : "This import cannot fit within the published storage cap. Choose a smaller folder."} + + )} + {admission && + !admission.refusal && + admission.required_storage_gib * IMPORT_GIB > admission.current_storage_bytes && ( +

+ Your vault’s storage grows to about{" "} + {byteSize(admission.required_storage_gib * IMPORT_GIB)} before encryption starts. +

+ )} {others !== null && others.files > 0 && ( <>

@@ -165,7 +222,8 @@ export function ImportLimits({ )} {vault !== null && vault.bytes < forecast.plaintextBytes && ( - 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 folder adds {byteSize(forecast.plaintextBytes)}. Exomem may stop the import while it stages the files. Add storage first, or choose a smaller folder. @@ -290,8 +348,8 @@ export function StagedImportStorage({ storage, now, }: { - stagedBytes: number; - stagedFiles: number; + stagedBytes: number | null; + stagedFiles: number | null; storage: HomeStorage | null; now: number; }) { @@ -300,7 +358,11 @@ export function StagedImportStorage({

Staged originals
-
{totals({ files: stagedFiles, bytes: stagedBytes })}
+
+ {stagedFiles === null || stagedBytes === null + ? "not recorded" + : totals({ files: stagedFiles, bytes: stagedBytes })} +
Your vault
diff --git a/src/app/exomem/home/home-import.tsx b/src/app/exomem/home/home-import.tsx index 36a8f0b5..8b584a4d 100644 --- a/src/app/exomem/home/home-import.tsx +++ b/src/app/exomem/home/home-import.tsx @@ -5,6 +5,10 @@ import { Button } from "@/components/exomem/Button"; import { Modal } from "@/components/exomem/Modal"; import { cloudImportFinished, + calculateImportAdmission, + homeImportLimits, + type CloudImportReply, + type ImportLimit, stagedImportFolder, type CloudImport, } from "@/lib/exomem/cloud-import-contract"; @@ -14,7 +18,7 @@ import { type ImportForecast, } from "@/lib/exomem-hosted/cloud-import-browser"; import { - readBrowserImport, + readBrowserImportContext, requestBrowserImport, } from "@/lib/exomem-hosted/cloud-import-browser-api"; import { @@ -77,7 +81,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.", @@ -86,7 +97,18 @@ const NEXT_STEP: Record = { status: "Check the import’s current status above.", }; +function growthWait(operation: CloudImport): string | null { + return operation.requested_state === "requested" && + operation.observed_state === "pending" && + operation.required_storage_bytes != null && + operation.storage_ready === false + ? `Your vault’s storage is growing to about ${byteSize(operation.required_storage_bytes)}.` + : 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") @@ -145,7 +167,7 @@ function rowProgress(progress: ImportProgress): string { function pausedText(stop: Extract): string { if (stop.unavailable) return "Paused until uploads are available again."; if (stop.phase === "uploading" || stop.phase === "reporting" || stop.phase === "verifying") - return "Paused. Parts already uploaded from this page are kept."; + return "Paused. Confirmed parts are kept in this browser, including after a reload."; return stop.phase === "linking" ? "Paused. This browser keeps the encrypted copy for when you resume." : "Paused. Encryption starts again from the beginning when you resume."; @@ -221,6 +243,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); const [folder, setFolder] = useState(null); @@ -314,8 +337,10 @@ 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); @@ -405,6 +430,16 @@ export function ImportDocuments({ return () => controller.abort(); }, [measuring, resumingId, account, csrfToken, discards]); const measured = preflight && measuring && preflight.selection === measuring ? preflight : null; + const published = homeImportLimits.safeParse(context?.limits); + const admission = + measured && "forecast" in measured && context?.storage && published.success + ? calculateImportAdmission( + context.limits, + context.storage, + measured.forecast.plaintextBytes, + measured.forecast.members + ) + : null; const storedId = open && reported && !holding && !busy ? awaiting.import_id : null; useEffect(() => { @@ -515,12 +550,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 (!selection) return; + if (!selection || admission?.refusal) return; const previous = upload.current; const resumeId = awaiting && !reported ? awaiting.import_id : undefined; upload.current = new BrowserImportUpload({ @@ -625,15 +661,17 @@ export function ImportDocuments({ "forecast" in measured && (browserFree(measured.room) ?? Infinity) < measured.forecast.ciphertextBytes; const rowStatus = - busy && progress - ? rowProgress(progress) - : stop?.kind === "paused" - ? "Import paused. Open it to resume." - : stop - ? "Import stopped. Open it to see why and what to do next." - : awaiting - ? "An upload is waiting to continue." - : null; + operation && growthWait(operation) + ? growthWait(operation) + : busy && progress + ? rowProgress(progress) + : stop?.kind === "paused" + ? "Import paused. Open it to resume." + : stop + ? "Import stopped. Open it to see why and what to do next." + : awaiting + ? "An upload is waiting to continue." + : null; return ( <> {(canStart || operation !== null || readMessage !== null) && ( @@ -690,7 +728,21 @@ export function ImportDocuments({ Status updated {shortDateTime(operation.updated_at)}.

{operation.error_code && ( -

Exomem reported: {operation.error_code}

+ <> +

+ {importStopFrom( + new HostedBrowserError({ code: operation.error_code, message: "" }, 422) + )?.message ?? "Exomem stopped the import."} +

+ + + )} + {growthWait(operation) && published.success && ( +

+ Exomem allows up to{" "} + {count(Math.ceil(published.data.import_growth_deadline_seconds / 60))} minutes + for storage growth. This page keeps checking while the import waits. +

)} )} @@ -701,14 +753,18 @@ export function ImportDocuments({ <> )} - {busy && progress && } + {busy && + progress && + !(progress.phase === "preparing" && operation && growthWait(operation)) && ( + + )} {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 5e35b7a1..f3ddd465 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; other accounts' copies 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 45ca265e..00b6105c 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-import-browser.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-import-browser.test.ts @@ -164,7 +164,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 315d2c3a..544b73c6 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 @@ -188,7 +188,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); @@ -232,6 +235,263 @@ 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 + ); + 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, + false + ); + }); + + 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 89b86b37..6e9a61f2 100644 --- a/src/lib/exomem-hosted/cloud-import-browser-api.ts +++ b/src/lib/exomem-hosted/cloud-import-browser-api.ts @@ -1,9 +1,23 @@ -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()) { @@ -23,10 +37,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; } @@ -43,7 +70,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 4d0d2e13..633a6c51 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 @@ -16,6 +19,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), +}); + /** Origin-private storage exists only in secure contexts of browsers that implement it. */ function privateStorage(): boolean { return typeof navigator !== "undefined" && typeof navigator.storage?.getDirectory === "function"; @@ -50,6 +71,67 @@ async function removeEntry(directory: FileSystemDirectoryHandle, name: string) { } } +async function removeCopy(directory: FileSystemDirectoryHandle, importId: string) { + await removeEntry(directory, ciphertextName(importId)); + await removeEntry(directory, receiptName(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}`; } @@ -94,7 +176,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"); @@ -124,7 +206,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; @@ -134,7 +216,7 @@ export async function storedImportCiphertext( /** Removes this import's copy; the caller holds the import or has checked that no tab does. */ export async function removeImportCiphertext(account: string, importId: string): Promise { if (!privateStorage()) return; - await removeEntry(await accountDirectory(account), ciphertextName(importId)); + await removeCopy(await accountDirectory(account), importId); } /** Removes this import's copy unless another tab holds the import; false when one does. */ @@ -167,10 +249,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); } } @@ -216,9 +300,9 @@ export async function otherKeptCiphertext( export async function discardOtherKeptCiphertext(account: string): Promise<{ kept: number }> { if (!privateStorage()) return { kept: 0 }; let kept = 0; - for (const { directory, name, importId } of await otherCopies(account)) { + for (const { directory, importId } of await otherCopies(account)) { const removed = await whileImportFree(importId, async () => { - await removeEntry(directory, name); + await removeCopy(directory, importId); return true; }).catch(() => false); if (!removed) kept += 1; diff --git a/src/lib/exomem-hosted/cloud-import-browser-upload.ts b/src/lib/exomem-hosted/cloud-import-browser-upload.ts index 8274a18e..05f239d6 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"; @@ -86,7 +88,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; @@ -256,16 +257,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 02b37e29..440accbb 100644 --- a/src/lib/exomem-hosted/cloud-import-browser.ts +++ b/src/lib/exomem-hosted/cloud-import-browser.ts @@ -14,6 +14,7 @@ export type EncryptionProgress = { files: number; plaintextBytes: number; cipher /** The exact sizes one selection produces, before anything is read or written. */ export type ImportForecast = { files: number; + members: number; plaintextBytes: number; tarBytes: number; ciphertextBytes: number; @@ -102,8 +103,16 @@ export async function forecastImport( ): Promise { const archive = await tarBytes(files, signal); const stand = recipient ?? (await identityToRecipient(await generateX25519Identity())); + // The archive's slash-separated parent folders each count as a member beside its files. + const folders = new Set(); + for (const { path } of files) { + const components = path.split("/"); + for (let index = 1; index < components.length; index++) + folders.add(components.slice(0, index).join("/")); + } return { files: files.length, + members: files.length + folders.size, plaintextBytes: files.reduce((total, { file }) => total + file.size, 0), tarBytes: archive, ciphertextBytes: await ageBytes(archive, stand), @@ -208,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()) { @@ -253,11 +263,13 @@ 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"); + await onConfirmed({ part_number: part.part_number, etag }); completed.set(part.part_number, etag); } offset = end; 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 f201d5ee..6fb4138a 100644 --- a/src/lib/exomem-hosted/cloud-import-selection.ts +++ b/src/lib/exomem-hosted/cloud-import-selection.ts @@ -22,9 +22,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 memory. This is -// the Exomem CLI's limit, so both read a folder the same way; keep the two in step until the -// published import limits carry it. +// 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 ca957ded..3e08b238 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: "Choose a folder that contains files." }, @@ -57,6 +58,26 @@ const STOPS = { next: "resume", text: "This import is running in another tab or window.", }, + IMPORT_TOO_MANY_FILES: { + next: "choose", + text: "The folder has more members than this vault accepts. Choose a smaller folder.", + }, + IMPORT_STORAGE_LIMIT: { + next: "choose", + text: "The import cannot fit within this vault’s storage limit. Choose a smaller folder.", + }, + 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 import to try again.", + }, + IMPORT_STORAGE_NO_ROOM: { + next: "choose", + text: "The vault cannot grow its storage right now. Start a new import later.", + }, STOPPED: { next: "resume", text: "The browser stopped the import." }, } satisfies Record; @@ -67,13 +88,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; } } @@ -97,14 +123,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 9488bf1f..1f8cb792 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, @@ -23,6 +28,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; @@ -40,12 +60,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 = () => @@ -131,7 +159,45 @@ 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, + }; +} + +function limits(cell: CellRow) { + return calculateImportAdmission(cell.import_limits, storage(cell), 0, 0) + ? cell.import_limits + : null; +} + +function status(row: ImportRow, cell: CellRow): CloudImport { + const required = row.required_storage_gib === null ? null : row.required_storage_gib * IMPORT_GIB; + // The controller publishes this generation receipt only after resize conditions clear. + const storageReady = + required === null + ? null + : Boolean( + cell.observed_storage_capacity_bytes !== null && + storedCount(cell.observed_storage_capacity_bytes) >= required && + cell.observed_storage_generation === cell.generation && + 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, @@ -145,6 +211,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(), }; @@ -154,25 +224,40 @@ 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 || (!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 @@ -182,6 +267,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( @@ -219,7 +305,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 @@ -233,14 +325,35 @@ 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 + ); + } + if (admission) { + const grown = await tx` + UPDATE exomem_cloud_cells SET storage_gib = GREATEST(storage_gib, ${admission.required_storage_gib}) + WHERE cell_id = ${principal.cellId} RETURNING * + `; + 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) { @@ -251,7 +364,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 ( @@ -262,7 +394,7 @@ export async function mutateCloudImport( ) ) throw conflict(); - return { import: status(row), created: false }; + return reply(row); } if ( row.requested_state !== "requested" || @@ -291,10 +423,10 @@ export async function mutateCloudImport( requested_state = ${parts ? "uploaded" : "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); } 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" && @@ -306,7 +438,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 5087b06f..6cef844d 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 } : {}), }; } } @@ -180,6 +187,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 c226d2ec..2868818a 100644 --- a/src/lib/exomem-hosted/hosted-browser.ts +++ b/src/lib/exomem-hosted/hosted-browser.ts @@ -4,6 +4,7 @@ export type HostedErrorBody = { retryable?: boolean; requestId?: string; remediation?: string; + limit?: unknown; }; export class HostedBrowserError extends Error { @@ -13,6 +14,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."); @@ -21,6 +23,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; } } @@ -39,6 +42,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, }; } } @@ -88,10 +92,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", @@ -107,9 +111,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..df21c0b9 --- /dev/null +++ b/src/lib/exomem/__tests__/cloud-import-contract.test.ts @@ -0,0 +1,91 @@ +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 stale capacity ratio sizes growth but cannot refuse an import that fits an empty vault", () => { + const result = calculateImportAdmission( + limits, + { + ...storage, + storage_gib: 20, + filesystem_bytes: Math.floor(1.9 * GiB), + observed_storage_capacity_bytes: 20 * GiB, + }, + GiB, + 1 + )!; + assert.ok(result.need_bytes > 20 * GiB); + assert.equal(result.required_storage_gib, 20); + assert.equal(result.refusal, null); +}); + +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..993f5ffa 100644 --- a/src/lib/exomem/cloud-import-contract.ts +++ b/src/lib/exomem/cloud-import-contract.ts @@ -1,6 +1,78 @@ 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 }); +export const homeImportLimits = admissionLimits.extend({ + 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(), +}); +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 current = Math.max(storage.storage_gib, storage.grown_storage_gib ?? 0) * IMPORT_GIB; + const ratio = + storage.used_bytes !== null && + storage.filesystem_bytes && + storage.observed_storage_capacity_bytes + ? 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); + const cap = limits.max_storage_gib * 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, + required_storage_gib: Math.min(Math.ceil(need / IMPORT_GIB), limits.max_storage_gib), + refusal, + }; +} /** S3's multipart protocol fixes this maximum number of numbered parts. */ export const MAX_IMPORT_PARTS = 10_000; @@ -25,13 +97,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 d49dc8d8..05881004 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 J=Object.defineProperty;var X=(t,e,n)=>e in t?J(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var h=(t,e,n)=>X(t,typeof e!=\"symbol\"?e+\"\":e,n);function H(t){for(let e of(document.cookie??\"\").split(\";\")){let[n,...r]=e.trim().split(\"=\");if(n===t)return decodeURIComponent(r.join(\"=\"))}return\"\"}function U(){return H(\"exomem_csrf\")}function W(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 r=W(t),o=t?.length,c=e!==void 0;if(!r||c&&o!==e){let i=n&&`\"${n}\" `,s=c?` of length ${e}`:\"\",f=r?`length=${o}`:`type=${typeof t}`,d=i+\"expected Uint8Array\"+s+\", got \"+f;throw r?new RangeError(d):new TypeError(d)}return t}function L(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 K=typeof Uint8Array.from([]).toHex==\"function\"&&typeof Uint8Array.fromHex==\"function\",z=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,\"0\"));function C(t){if(w(t),K)return t.toHex();let e=\"\";for(let n=0;nt(c).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}var F=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 R(t,e,n){return t&e^t&n^e&n}var T=class{constructor(e,n,r,o){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=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=A(this.buffer)}update(e){L(this),w(e);let{view:n,buffer:r,blockLen:o}=this,c=e.length;for(let i=0;io-i&&(this.process(r,0),i=0);for(let a=i;al.length)throw new Error(\"_sha2: outputLen bigger than state\");for(let a=0;a>>3,S=u(b,17)^u(b,19)^b>>>10;m[a]=S+m[a-7]+_+m[a-16]|0}let{A:r,B:o,C:c,D:i,E:s,F:f,G:d,H:l}=this;for(let a=0;a<64;a++){let g=u(s,6)^u(s,11)^u(s,25),b=l+g+M(s,f,d)+q[a]+m[a]|0,S=(u(r,2)^u(r,13)^u(r,22))+R(r,o,c)|0;l=d,d=f,f=s,s=i+b|0,i=c,c=o,o=r,r=b+S|0}r=r+this.A|0,o=o+this.B|0,c=c+this.C|0,i=i+this.D|0,s=s+this.E|0,f=f+this.F|0,d=d+this.G|0,l=l+this.H|0,this.set(r,o,c,i,s,f,d,l)}roundClean(){y(m)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),y(this.buffer)}},v=class extends B{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 I=D(()=>new v,F(1));var Y=\"exomem_theme_v2_\";function Q(t){return C(I(k(`exomem-theme-v2:${C(t)}`)))}function P(t){return t?Q(I(k(t))):\"\"}function G(t){return`${Y}${t}`}function $(t,e){return t===\"auto\"?e?\"light\":\"dark\":t}function Z(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 p={choice:\"exomem-theme-choice\",legacy:\"exomem-theme\",account:\"exomem-theme-account\"};function ee(t){let e=j(),n=null;try{n=Z(H(G(e)))}catch{}e&&n?.binding!==e?n={scope:\"\",binding:e,choice:\"auto\",effective:null,expiresAt:null}:e||(n=null);let r=\"auto\";try{let s=window.localStorage.getItem(p.choice);if(s===null){let f=window.localStorage.getItem(p.legacy);s=f===\"light\"||f===\"dark\"?f:\"auto\",window.localStorage.setItem(p.choice,s),window.localStorage.removeItem(p.legacy)}(s===\"light\"||s===\"dark\")&&(r=s)}catch{}let o=n?n.scope?n.choice??r:\"auto\":r;try{n?.scope?window.localStorage.setItem(p.account,JSON.stringify({scope:n.scope,choice:o})):window.localStorage.removeItem(p.account)}catch{}let c=!1;if(o===\"auto\")try{c=window.matchMedia(\"(prefers-color-scheme: light)\").matches}catch{}let i=$(o,c);return t.setAttribute(\"data-exomem\",\"\"),t.setAttribute(\"data-theme-choice\",o),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 N(t){return t===\"/exomem\"||t.indexOf(\"/exomem/\")===0}var te={status:\"idle\",error:null},E=null,Te=Promise.resolve();function ne(t){return t.getAttribute(\"data-theme\")===\"light\"?\"light\":\"dark\"}function re(t,e){let n=!1;if(e===\"auto\")try{n=window.matchMedia(\"(prefers-color-scheme: light)\").matches}catch{}let r=$(e,n);t.setAttribute(\"data-theme-choice\",e),t.getAttribute(\"data-theme\")!==r&&t.setAttribute(\"data-theme\",r)}function V(t){ee(t);let e=t.getAttribute(\"data-theme-scope\")??\"\";return E?.scope===e&&E.binding===j()?re(t,E.choice):E&&(E=null,te={status:\"idle\",error:null}),ne(t)}function j(){try{return P(U())}catch{return\"\"}}N(location.pathname)&&V(document.documentElement);})();"; + "\"use strict\";(()=>{var J=Object.defineProperty;var X=(t,e,n)=>e in t?J(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var h=(t,e,n)=>X(t,typeof e!=\"symbol\"?e+\"\":e,n);function H(t){for(let e of(document.cookie??\"\").split(\";\")){let[n,...o]=e.trim().split(\"=\");if(n===t)return decodeURIComponent(o.join(\"=\"))}return\"\"}function U(){return H(\"exomem_csrf\")}function W(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=W(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}`,d=i+\"expected Uint8Array\"+s+\", got \"+f;throw o?new RangeError(d):new TypeError(d)}return t}function L(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 K=typeof Uint8Array.from([]).toHex==\"function\"&&typeof Uint8Array.fromHex==\"function\",z=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,\"0\"));function C(t){if(w(t),K)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 F=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 R(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){L(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=u(b,17)^u(b,19)^b>>>10;m[a]=S+m[a-7]+_+m[a-16]|0}let{A:o,B:r,C:c,D:i,E:s,F:f,G:d,H:l}=this;for(let a=0;a<64;a++){let g=u(s,6)^u(s,11)^u(s,25),b=l+g+M(s,f,d)+q[a]+m[a]|0,S=(u(o,2)^u(o,13)^u(o,22))+R(o,r,c)|0;l=d,d=f,f=s,s=i+b|0,i=c,c=r,r=o,o=b+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,d=d+this.G|0,l=l+this.H|0,this.set(o,r,c,i,s,f,d,l)}roundClean(){y(m)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),y(this.buffer)}},v=class extends B{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 I=D(()=>new v,F(1));var Y=\"exomem_theme_v2_\";function Q(t){return C(I(k(`exomem-theme-v2:${C(t)}`)))}function P(t){return t?Q(I(k(t))):\"\"}function G(t){return`${Y}${t}`}function $(t,e){return t===\"auto\"?e?\"light\":\"dark\":t}function Z(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 p={choice:\"exomem-theme-choice\",legacy:\"exomem-theme\",account:\"exomem-theme-account\"};function ee(t){let e=j(),n=null;try{n=Z(H(G(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(p.choice);if(s===null){let f=window.localStorage.getItem(p.legacy);s=f===\"light\"||f===\"dark\"?f:\"auto\",window.localStorage.setItem(p.choice,s),window.localStorage.removeItem(p.legacy)}(s===\"light\"||s===\"dark\")&&(o=s)}catch{}let r=n?n.scope?n.choice??o:\"auto\":o;try{n?.scope?window.localStorage.setItem(p.account,JSON.stringify({scope:n.scope,choice:r})):window.localStorage.removeItem(p.account)}catch{}let c=!1;if(r===\"auto\")try{c=window.matchMedia(\"(prefers-color-scheme: light)\").matches}catch{}let i=$(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 N(t){return t===\"/exomem\"||t.indexOf(\"/exomem/\")===0}var te={status:\"idle\",error:null},E=null,Te=Promise.resolve();function ne(t){return t.getAttribute(\"data-theme\")===\"light\"?\"light\":\"dark\"}function oe(t,e){let n=!1;if(e===\"auto\")try{n=window.matchMedia(\"(prefers-color-scheme: light)\").matches}catch{}let o=$(e,n);t.setAttribute(\"data-theme-choice\",e),t.getAttribute(\"data-theme\")!==o&&t.setAttribute(\"data-theme\",o)}function V(t){ee(t);let e=t.getAttribute(\"data-theme-scope\")??\"\";return E?.scope===e&&E.binding===j()?oe(t,E.choice):E&&(E=null,te={status:\"idle\",error:null}),ne(t)}function j(){try{return P(U())}catch{return\"\"}}N(location.pathname)&&V(document.documentElement);})();"; From 6cc5605f4f7245335a49ee79330f89e3336287d7 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Mon, 26 Oct 2026 11:20:03 +0000 Subject: [PATCH 02/13] fix(exomem): count only written import archive members The browser writes one TAR member per selected file. Count these entries so that implicit folders do not reject imports at the limit. --- .../design.md | 2 +- .../specs/exomem-home/spec.md | 4 ++-- src/app/exomem/home/__tests__/home-import.test.tsx | 10 +++++----- src/lib/exomem-hosted/cloud-import-browser.ts | 10 ++-------- 4 files changed, 10 insertions(+), 16 deletions(-) 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 6eab2d3c..d281f4eb 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/design.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/design.md @@ -130,7 +130,7 @@ The three codes join the closed set of import protocol codes. Their error envelo ### 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 member count against `max_members`, the storage need against the cap, and "grows to about N GB" when the need exceeds the current size. The browser writes one file entry per selected file; implicit parent folders add no TAR members. It refuses to start where admission would refuse. 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. 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..23a66777 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,7 +3,7 @@ ### 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. +When the cell has published its import limits, the dialog SHALL also show the actual archive member count against the published maximum. The browser writes one file entry per selected file; implicit parent folders SHALL NOT add members. 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. @@ -29,7 +29,7 @@ Home SHALL NOT enforce the cell's path or name limits; the cell keeps enforcing #### 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 diff --git a/src/app/exomem/home/__tests__/home-import.test.tsx b/src/app/exomem/home/__tests__/home-import.test.tsx index 4394db2c..eaa3a5e1 100644 --- a/src/app/exomem/home/__tests__/home-import.test.tsx +++ b/src/app/exomem/home/__tests__/home-import.test.tsx @@ -233,16 +233,16 @@ const readings = { usage_observed_at: "2026-01-01T00:00:00Z", }; -it("preflight counts folders as members and refuses a selection above the published maximum", async () => { +it("preflight admits a file at the member limit without counting its parent folder", async () => { const api = importApiDouble("unused"); const page = await home({ api, - context: { limits: { ...published, max_members: 3 }, storage: readings }, + context: { limits: { ...published, max_members: 1 }, storage: readings }, }); await page.click("Import…"); - await page.choose(folder("research", 3)); - await page.until(() => page.text().includes("4 of 3"), "the member limit"); - assert.equal(page.button("Encrypt and upload"), undefined); + await page.choose(folder("research", 1)); + await page.until(() => page.text().includes("1 of 1"), "the archive's actual member count"); + assert.ok(page.button("Encrypt and upload")); assert.equal(api.rows.size, 0); }); diff --git a/src/lib/exomem-hosted/cloud-import-browser.ts b/src/lib/exomem-hosted/cloud-import-browser.ts index 440accbb..5fa4fe5b 100644 --- a/src/lib/exomem-hosted/cloud-import-browser.ts +++ b/src/lib/exomem-hosted/cloud-import-browser.ts @@ -103,16 +103,10 @@ export async function forecastImport( ): Promise { const archive = await tarBytes(files, signal); const stand = recipient ?? (await identityToRecipient(await generateX25519Identity())); - // The archive's slash-separated parent folders each count as a member beside its files. - const folders = new Set(); - for (const { path } of files) { - const components = path.split("/"); - for (let index = 1; index < components.length; index++) - folders.add(components.slice(0, index).join("/")); - } return { files: files.length, - members: files.length + folders.size, + // The writer emits file entries only; parent paths do not add TAR members. + members: files.length, plaintextBytes: files.reduce((total, { file }) => total + file.size, 0), tarBytes: archive, ciphertextBytes: await ageBytes(archive, stand), From da9916caaa358d64abc539eea40064f711fb0d8a Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Mon, 26 Oct 2026 12:48:30 +0000 Subject: [PATCH 03/13] feat(cloud): show distinct filed counts for staged imports --- e2e/exomem-home/fake-cell.ts | 3 + e2e/exomem-home/import.spec.ts | 32 +++- .../home/__tests__/home-import.test.tsx | 7 +- src/app/exomem/home/home-import-panels.tsx | 10 ++ src/app/exomem/home/home-import.tsx | 1 + .../cloud-home-postgres.integration.test.ts | 143 +++++++++++++++++- src/lib/exomem-hosted/cloud-home-mcp.ts | 38 ++++- src/lib/exomem-hosted/cloud-import-http.ts | 6 +- src/lib/exomem-hosted/cloud-imports.ts | 30 +++- .../exomem-hosted/cloud-owner-principal.ts | 9 +- src/lib/exomem/cloud-import-contract.ts | 1 + 11 files changed, 266 insertions(+), 14 deletions(-) diff --git a/e2e/exomem-home/fake-cell.ts b/e2e/exomem-home/fake-cell.ts index 670bbdcd..2df3d894 100644 --- a/e2e/exomem-home/fake-cell.ts +++ b/e2e/exomem-home/fake-cell.ts @@ -36,6 +36,7 @@ export type FakeCellState = { viewerMap?: unknown; viewerSearch?: unknown; viewerNotes?: Record; + adoptionStatus?: Record; }; function initialState(): FakeCellState { @@ -83,6 +84,8 @@ export function startFakeCell(options: { }; function call(state: FakeCellState, name: string, args: Record): unknown { + if (name === "adoption_studio") + return state.adoptionStatus?.[String(args.path)] ?? { runs: [] }; if (name === "viewer_map") return state.viewerMap ?? { available: false }; if (name === "ask_memory") return { result: state.viewerSearch ?? [] }; if (name === "read_memory") return state.viewerNotes?.[String(args.path)] ?? {}; diff --git a/e2e/exomem-home/import.spec.ts b/e2e/exomem-home/import.spec.ts index e2bbd091..e296ad7f 100644 --- a/e2e/exomem-home/import.spec.ts +++ b/e2e/exomem-home/import.spec.ts @@ -5,7 +5,7 @@ import { join } from "node:path"; import { expect, test as base } from "@playwright/test"; import { Decrypter, generateIdentity, identityToRecipient } from "age-encryption"; import { createTarDecoder } from "modern-tar"; -import { createOwner, pool, signIn } from "./seed"; +import { createOwner, pool, setCell, signIn } from "./seed"; import { homeE2eEnvironment } from "./environment"; const test = base.extend({ @@ -18,6 +18,36 @@ const test = base.extend({ ], }); +test("Home shows the cell's complete filing count and keeps an incomplete count unknown after reload", async ({ + page, + context, +}) => { + const owner = await createOwner(); + const result = await pool.query( + `INSERT INTO exomem_cloud_imports (cell_id, kind, declared_bytes, declared_files, + requested_state, observed_state, staged_files, staged_bytes, part_etags, + ciphertext_sha256, ciphertext_bytes) + VALUES ($1, 'adopt', 99, 9, 'uploaded', 'done', 4, 44, + '[{"part_number":1,"etag":"synthetic"}]', repeat('a',64), 77) + RETURNING import_id`, + [owner.cellId] + ); + const path = `_Imports/${result.rows[0].import_id}`; + await setCell(owner, { adoptionStatus: { [path]: { complete: true, adopted_files: 3 } } }); + await signIn(context, owner); + await page.goto("/exomem/home"); + await page.getByRole("button", { name: "Import…", exact: true }).click(); + const dialog = page.getByRole("dialog"); + await expect(dialog.getByText("3 files", { exact: true })).toBeVisible(); + await setCell(owner, { adoptionStatus: { [path]: { complete: false, adopted_files: 2 } } }); + await page.reload(); + await page.getByRole("button", { name: "Import…", exact: true }).click(); + await expect(dialog.getByText("unknown", { exact: true })).toBeVisible(); + const fresh = await page.evaluate(async () => (await fetch("/api/exomem/cloud/imports")).json()); + expect(fresh.import.adopted_files).toBeNull(); + expect(fresh.import.staged_files).toBe(4); +}); + test("Home offers imports only while the cell permits starting one", async ({ page, context }) => { const owner = await createOwner(); await signIn(context, owner); diff --git a/src/app/exomem/home/__tests__/home-import.test.tsx b/src/app/exomem/home/__tests__/home-import.test.tsx index 4394db2c..1f1acfb6 100644 --- a/src/app/exomem/home/__tests__/home-import.test.tsx +++ b/src/app/exomem/home/__tests__/home-import.test.tsx @@ -325,7 +325,7 @@ it("Home shows the published growth wait on its row and dialog, then a fixed gro assert.ok(unavailable.text().includes("IMPORT_STORAGE_NO_ROOM")); }); -it("staged totals use the Job report and older imports say not recorded", async () => { +it("staged and filed counts use their own observations and older imports remain unknown", async () => { const api = importApiDouble("unused"); const id = crypto.randomUUID(); const row = { @@ -343,6 +343,7 @@ it("staged totals use the Job report and older imports say not recorded", async ciphertext_bytes: 999, staged_files: 2, staged_bytes: 2048, + adopted_files: 1, created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z", }; @@ -350,12 +351,14 @@ it("staged totals use the Job report and older imports say not recorded", async let page = await home({ api }); await page.click("Import…"); await page.until(() => page.text().includes("2 files · 2 kB"), "the staged report"); + assert.ok(page.text().includes("Filed1 file")); await cleanup?.(); cleanup = null; - Object.assign(row, { staged_files: null, staged_bytes: null }); + Object.assign(row, { staged_files: null, staged_bytes: null, adopted_files: undefined }); page = await home({ api }); await page.click("Import…"); await page.until(() => page.text().includes("not recorded"), "the unknown staged count"); + assert.ok(page.text().includes("Filedunknown")); }); for (const [code, unit, reason] of [ diff --git a/src/app/exomem/home/home-import-panels.tsx b/src/app/exomem/home/home-import-panels.tsx index 5ec2d1e8..e19c5d0b 100644 --- a/src/app/exomem/home/home-import-panels.tsx +++ b/src/app/exomem/home/home-import-panels.tsx @@ -345,11 +345,13 @@ export function ImportReference({ importId, code }: { importId: string; code?: s export function StagedImportStorage({ stagedBytes, stagedFiles, + adoptedFiles, storage, now, }: { stagedBytes: number | null; stagedFiles: number | null; + adoptedFiles: number | null; storage: HomeStorage | null; now: number; }) { @@ -364,6 +366,14 @@ export function StagedImportStorage({ : totals({ files: stagedFiles, bytes: stagedBytes })}
+
+
Filed
+
+ {adoptedFiles === null + ? "unknown" + : `${adoptedFiles} ${adoptedFiles === 1 ? "file" : "files"}`} +
+
Your vault
diff --git a/src/app/exomem/home/home-import.tsx b/src/app/exomem/home/home-import.tsx index 8b584a4d..2d248c9a 100644 --- a/src/app/exomem/home/home-import.tsx +++ b/src/app/exomem/home/home-import.tsx @@ -755,6 +755,7 @@ export function ImportDocuments({ diff --git a/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts index 859f6ff4..8e08c37b 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts @@ -10,6 +10,7 @@ import { randomCloudCellId } from "../cloud-admission"; import { cloudExportReply } from "../../exomem/cloud-export-contract"; import { handleCloudExportLinkRequest, handleCloudExportsRequest } from "../cloud-exports"; import { handleCloudHomeLevelsRequest, handleCloudHomeLiveRequest } from "../cloud-home-mcp"; +import { handleCloudImportRequest } from "../cloud-import-http"; import { handleCloudViewerRequest } from "../cloud-viewer"; import { findCloudOAuthAccessToken, resolveApprovedCloudOAuthClient } from "../cloud-oauth"; import { getOwnerCloudHomeStatus } from "../cloud-status"; @@ -68,15 +69,15 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function owner( - cell: { desired?: string; ready?: boolean; image?: string | null } = {} + cell: { desired?: string; ready?: boolean; image?: string | null; reviewerPurpose?: boolean } = {} ): Promise { const user = await pool.query("INSERT INTO exomem_users (email) VALUES ($1) RETURNING id", [ `home-${randomUUID()}@example.test`, ]); const userId = user.rows[0].id; const tenant = await pool.query( - "INSERT INTO exomem_tenants (owner_user_id, status, desired_state) VALUES ($1, 'active', 'running') RETURNING id", - [userId] + "INSERT INTO exomem_tenants (owner_user_id, status, desired_state, marketplace_reviewer_purpose) VALUES ($1, 'active', 'running', $2) RETURNING id", + [userId, cell.reviewerPurpose ?? false] ); const tenantId = tenant.rows[0].id; const cellId = randomCloudCellId(); @@ -629,6 +630,142 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database }); describe("Home channel", () => { + it("keeps the browser reviewer's credential on the optional filing observation", async () => { + const prior = process.env.EXOMEM_MARKETPLACE_REVIEWER_ACCESS_ENABLED; + let credentialId: string | undefined; + process.env.EXOMEM_MARKETPLACE_REVIEWER_ACCESS_ENABLED = "true"; + try { + const alice = await owner({ reviewerPurpose: true }); + await pool.query( + `INSERT INTO exomem_entitlements (tenant_id, source, source_state, effective_state) + VALUES ($1, 'complimentary', 'complimentary_active', 'active')`, + [alice.tenantId] + ); + const credential = await pool.query( + `INSERT INTO exomem_marketplace_reviewer_credentials ( + provider, username_digest, password_hash, owner_user_id, tenant_id, fixture_version, + fixture_payload_digest, created_by_principal_digest, expires_at, credential_kind + ) VALUES ('anthropic', $1, '$argon2id$test', $2, $3, 'sample-v1', $4, $5, + now() + interval '1 day', 'cloud_provider_review') RETURNING id`, + [ + digestSecret(randomUUID()), + alice.userId, + alice.tenantId, + "a".repeat(64), + digestSecret(randomUUID()), + ] + ); + credentialId = credential.rows[0].id; + await pool.query( + "UPDATE exomem_sessions SET reviewer_credential_id=$1 WHERE session_digest=$2", + [credentialId, digestSecret(alice.cookie)] + ); + await pool.query( + `INSERT INTO exomem_cloud_imports (cell_id, kind, declared_bytes, declared_files, observed_state) + VALUES ($1, 'adopt', 99, 9, 'done')`, + [alice.cellId] + ); + const cell = fakeCell(() => ({ complete: true, adopted_files: 1 })); + const response = await handleCloudImportRequest( + browserRequest(alice, "GET", "/api/exomem/cloud/imports"), + "status", + undefined, + { fetchCell: cell.fetchCell, env: ENV } + ); + assert.equal(response.status, 200); + assert.equal((await response.json()).import.adopted_files, 1); + const token = await pool.query( + "SELECT reviewer_credential_id FROM exomem_oauth_access_tokens WHERE access_digest=$1", + [digestSecret(cell.calls[0].bearer)] + ); + assert.equal(token.rows[0].reviewer_credential_id, credentialId); + } finally { + if (credentialId) + await pool.query( + "UPDATE exomem_marketplace_reviewer_credentials SET revoked_at=now() WHERE id=$1", + [credentialId] + ); + if (prior === undefined) delete process.env.EXOMEM_MARKETPLACE_REVIEWER_ACCESS_ENABLED; + else process.env.EXOMEM_MARKETPLACE_REVIEWER_ACCESS_ENABLED = prior; + } + }); + + it("reads the filed count through the owner's channel after the owned import lookup", async () => { + const alice = await owner(); + const bob = await owner(); + const importId = randomUUID(); + await pool.query( + `INSERT INTO exomem_cloud_imports (import_id, cell_id, kind, declared_bytes, declared_files, + observed_state, staged_files, staged_bytes) + VALUES ($1, $2, 'adopt', 99, 9, 'done', 4, 44)`, + [importId, alice.cellId] + ); + const cell = fakeCell(() => ({ adopted_files: 3, complete: true })); + const read = (who: Owner, id = importId) => + handleCloudImportRequest( + browserRequest( + who, + "GET", + `/api/exomem/cloud/imports/${id}?path=other&tenant_id=${bob.tenantId}` + ), + "status", + id, + { fetchCell: cell.fetchCell, env: ENV } + ); + assert.equal((await read(bob)).status, 404); + assert.equal(cell.calls.length, 0); + const response = await read(alice); + assert.equal(response.status, 200); + const result = await response.json(); + assert.equal(result.import.adopted_files, 3); + assert.equal(result.import.staged_files, 4); + assert.ok("limits" in result && "storage" in result); + assert.deepEqual(cell.calls[0].arguments, { action: "status", path: `_Imports/${importId}` }); + assert.equal(cell.calls[0].tool, "adoption_studio"); + assert.equal(cell.calls[0].routedTenantId, alice.tenantId); + assert.equal(cell.calls[0].routedCellId, alice.cellId); + assert.equal(cell.calls[0].firstParty, true); + await pool.query( + "UPDATE exomem_cloud_imports SET requested_state='cancelled' WHERE import_id=$1", + [importId] + ); + assert.equal((await (await read(alice)).json()).import.adopted_files, null); + assert.equal(cell.calls.length, 1); + }); + + it("keeps import status available when the filed count is incomplete, old or unavailable", async () => { + const alice = await owner(); + const importId = randomUUID(); + await pool.query( + `INSERT INTO exomem_cloud_imports (import_id, cell_id, kind, declared_bytes, declared_files, + observed_state) VALUES ($1, $2, 'adopt', 99, 9, 'done')`, + [importId, alice.cellId] + ); + for (const answer of [ + { adopted_files: 0, complete: true }, + { adopted_files: 2, complete: false }, + { runs: [] }, + { adopted_files: -1, complete: true }, + { adopted_files: 1.5, complete: true }, + { adopted_files: "2", complete: true }, + { success: false, error: { code: "READ_DENIED" } }, + Response.json({ error: "CELL_NOT_READY" }, { status: 503 }), + ]) { + const cell = fakeCell(() => answer); + const response = await handleCloudImportRequest( + browserRequest(alice, "GET", "/api/exomem/cloud/imports"), + "status", + undefined, + { fetchCell: cell.fetchCell, env: ENV } + ); + assert.equal(response.status, 200); + assert.equal( + (await response.json()).import.adopted_files, + "adopted_files" in answer && answer.adopted_files === 0 ? 0 : null + ); + } + }); + it("mints a token that the gateway routes only to the session's own cell, for 120 seconds", async () => { const alice = await owner(); const bob = await owner(); diff --git a/src/lib/exomem-hosted/cloud-home-mcp.ts b/src/lib/exomem-hosted/cloud-home-mcp.ts index 39291bad..5dfb84e4 100644 --- a/src/lib/exomem-hosted/cloud-home-mcp.ts +++ b/src/lib/exomem-hosted/cloud-home-mcp.ts @@ -8,13 +8,14 @@ * logged. The gateway's own lookup re-checks revocation, account blocks and * deletion when the token arrives (`findCloudOAuthAccessToken`). * - * Home calls only `configure_memory` and the `bootstrap` activity section. + * Home calls `configure_memory`, the `bootstrap` activity section and scoped adoption status. * The viewer reuses the same transport for three fixed read operations. * Browser callers never choose a tool, tenant, gateway or cell. */ import { randomUUID } from "node:crypto"; import { z } from "zod"; +import { stagedImportFolder } from "../exomem/cloud-import-contract"; import { loadExomemCloudResource, type EnvironmentSource } from "./cloud-config"; import { assertPrincipalOwnsCloudCell, CloudPrincipalHasNoCellError } from "./cloud-oauth"; import { executeExomemSql, withExomemTransaction } from "./db"; @@ -54,6 +55,10 @@ const ConfigureMemoryAnswer = z.object({ revision: z.string().min(1).max(128), levels: z.object({ coding: ContextLevel, conversation: ContextLevel }), }); +const AdoptedFilesAnswer = z.object({ + complete: z.literal(true), + adopted_files: z.number().int().nonnegative().safe(), +}); /** * The client families an activity event can name. This is the cell's closed @@ -167,7 +172,8 @@ type HomeToolCall = } | { action: "clear"; context: CloudHomeContext; expected_revision: string }; } - | { name: "bootstrap"; arguments: { profile: "compact"; section: "activity" } }; + | { name: "bootstrap"; arguments: { profile: "compact"; section: "activity" } } + | { name: "adoption_studio"; arguments: { action: "status"; path: string } }; // These names and argument shapes are the existing cell protocol, not a browser-selected proxy. export type CloudViewerToolCall = @@ -471,6 +477,34 @@ export async function callCloudViewerTool( return callHomeTool(principal, call, dependencies); } +/** Read only the server-selected import's complete historical filing count. */ +export async function readCloudImportAdoptedFiles( + principal: CloudHomePrincipal, + importId: string, + dependencies: CloudHomeDependencies = {} +): Promise { + if (!cloudHomeChannelEnabled(dependencies.env)) return null; + try { + const cell = await servingCell(principal); + if (cell.state !== "serving") return null; + const answer = await callHomeTool( + principal, + { + name: "adoption_studio", + arguments: { action: "status", path: stagedImportFolder(importId) }, + }, + dependencies + ); + if (answer.kind !== "result") return null; + const parsed = AdoptedFilesAnswer.safeParse(answer.value); + return parsed.success ? parsed.data.adopted_files : null; + } catch { + // Optional filing observations must not make the import's C5 status unavailable. + logUnavailable("adoption_studio", "CELL_UNREACHABLE"); + return null; + } +} + function liveLevels( value: unknown, desiredState: ServingCell["desiredState"] diff --git a/src/lib/exomem-hosted/cloud-import-http.ts b/src/lib/exomem-hosted/cloud-import-http.ts index 3781c2f9..7fc6c344 100644 --- a/src/lib/exomem-hosted/cloud-import-http.ts +++ b/src/lib/exomem-hosted/cloud-import-http.ts @@ -8,17 +8,19 @@ import { } from "./cloud-imports"; import { ExomemHostedError, safeErrorResponse } from "./errors"; import { readBoundedJsonRequest } from "./http"; +import type { CloudHomeDependencies } from "./cloud-home-mcp"; export async function handleCloudImportRequest( request: Request, action: CloudImportAction, - importId?: string + importId?: string, + dependencies: CloudHomeDependencies = {} ): Promise { const headers = { "cache-control": "no-store", "referrer-policy": "no-referrer" }; try { const principal = await resolveCloudImportPrincipal(request); if (action === "status") - return Response.json(await readCloudImport(principal, importId), { headers }); + return Response.json(await readCloudImport(principal, importId, dependencies), { headers }); const body = action === "cancel" || action === "discard" ? undefined diff --git a/src/lib/exomem-hosted/cloud-imports.ts b/src/lib/exomem-hosted/cloud-imports.ts index 1f8cb792..a61b4c00 100644 --- a/src/lib/exomem-hosted/cloud-imports.ts +++ b/src/lib/exomem-hosted/cloud-imports.ts @@ -12,6 +12,11 @@ import { type UploadPart, } from "../exomem/cloud-import-contract"; import { resolveCloudOwnerPrincipal } from "./cloud-owner-principal"; +import { + readCloudImportAdoptedFiles, + type CloudHomeDependencies, + type CloudHomePrincipal, +} from "./cloud-home-mcp"; import { executeExomemSql, withExomemTransaction, type ExomemSql } from "./db"; import { ExomemHostedError, exomemErrors } from "./errors"; @@ -27,6 +32,7 @@ type CloudImportPrincipal = { tenantId: string; cellId: string; cellDesiredState: string; + homePrincipal?: CloudHomePrincipal; }; type CellRow = { desired_state: string; @@ -93,6 +99,7 @@ export async function resolveCloudImportPrincipal(request: Request): Promise Date: Wed, 2 Dec 2026 08:51:08 +0000 Subject: [PATCH 04/13] Revert "feat(cloud): show distinct filed counts for staged imports" This reverts commit da9916caaa358d64abc539eea40064f711fb0d8a. --- e2e/exomem-home/fake-cell.ts | 3 - e2e/exomem-home/import.spec.ts | 32 +--- .../home/__tests__/home-import.test.tsx | 7 +- src/app/exomem/home/home-import-panels.tsx | 10 -- src/app/exomem/home/home-import.tsx | 1 - .../cloud-home-postgres.integration.test.ts | 143 +----------------- src/lib/exomem-hosted/cloud-home-mcp.ts | 38 +---- src/lib/exomem-hosted/cloud-import-http.ts | 6 +- src/lib/exomem-hosted/cloud-imports.ts | 30 +--- .../exomem-hosted/cloud-owner-principal.ts | 9 +- src/lib/exomem/cloud-import-contract.ts | 1 - 11 files changed, 14 insertions(+), 266 deletions(-) diff --git a/e2e/exomem-home/fake-cell.ts b/e2e/exomem-home/fake-cell.ts index 2df3d894..670bbdcd 100644 --- a/e2e/exomem-home/fake-cell.ts +++ b/e2e/exomem-home/fake-cell.ts @@ -36,7 +36,6 @@ export type FakeCellState = { viewerMap?: unknown; viewerSearch?: unknown; viewerNotes?: Record; - adoptionStatus?: Record; }; function initialState(): FakeCellState { @@ -84,8 +83,6 @@ export function startFakeCell(options: { }; function call(state: FakeCellState, name: string, args: Record): unknown { - if (name === "adoption_studio") - return state.adoptionStatus?.[String(args.path)] ?? { runs: [] }; if (name === "viewer_map") return state.viewerMap ?? { available: false }; if (name === "ask_memory") return { result: state.viewerSearch ?? [] }; if (name === "read_memory") return state.viewerNotes?.[String(args.path)] ?? {}; diff --git a/e2e/exomem-home/import.spec.ts b/e2e/exomem-home/import.spec.ts index e296ad7f..e2bbd091 100644 --- a/e2e/exomem-home/import.spec.ts +++ b/e2e/exomem-home/import.spec.ts @@ -5,7 +5,7 @@ import { join } from "node:path"; import { expect, test as base } from "@playwright/test"; import { Decrypter, generateIdentity, identityToRecipient } from "age-encryption"; import { createTarDecoder } from "modern-tar"; -import { createOwner, pool, setCell, signIn } from "./seed"; +import { createOwner, pool, signIn } from "./seed"; import { homeE2eEnvironment } from "./environment"; const test = base.extend({ @@ -18,36 +18,6 @@ const test = base.extend({ ], }); -test("Home shows the cell's complete filing count and keeps an incomplete count unknown after reload", async ({ - page, - context, -}) => { - const owner = await createOwner(); - const result = await pool.query( - `INSERT INTO exomem_cloud_imports (cell_id, kind, declared_bytes, declared_files, - requested_state, observed_state, staged_files, staged_bytes, part_etags, - ciphertext_sha256, ciphertext_bytes) - VALUES ($1, 'adopt', 99, 9, 'uploaded', 'done', 4, 44, - '[{"part_number":1,"etag":"synthetic"}]', repeat('a',64), 77) - RETURNING import_id`, - [owner.cellId] - ); - const path = `_Imports/${result.rows[0].import_id}`; - await setCell(owner, { adoptionStatus: { [path]: { complete: true, adopted_files: 3 } } }); - await signIn(context, owner); - await page.goto("/exomem/home"); - await page.getByRole("button", { name: "Import…", exact: true }).click(); - const dialog = page.getByRole("dialog"); - await expect(dialog.getByText("3 files", { exact: true })).toBeVisible(); - await setCell(owner, { adoptionStatus: { [path]: { complete: false, adopted_files: 2 } } }); - await page.reload(); - await page.getByRole("button", { name: "Import…", exact: true }).click(); - await expect(dialog.getByText("unknown", { exact: true })).toBeVisible(); - const fresh = await page.evaluate(async () => (await fetch("/api/exomem/cloud/imports")).json()); - expect(fresh.import.adopted_files).toBeNull(); - expect(fresh.import.staged_files).toBe(4); -}); - test("Home offers imports only while the cell permits starting one", async ({ page, context }) => { const owner = await createOwner(); await signIn(context, owner); diff --git a/src/app/exomem/home/__tests__/home-import.test.tsx b/src/app/exomem/home/__tests__/home-import.test.tsx index 69043bea..eaa3a5e1 100644 --- a/src/app/exomem/home/__tests__/home-import.test.tsx +++ b/src/app/exomem/home/__tests__/home-import.test.tsx @@ -325,7 +325,7 @@ it("Home shows the published growth wait on its row and dialog, then a fixed gro assert.ok(unavailable.text().includes("IMPORT_STORAGE_NO_ROOM")); }); -it("staged and filed counts use their own observations and older imports remain unknown", async () => { +it("staged totals use the Job report and older imports say not recorded", async () => { const api = importApiDouble("unused"); const id = crypto.randomUUID(); const row = { @@ -343,7 +343,6 @@ it("staged and filed counts use their own observations and older imports remain ciphertext_bytes: 999, staged_files: 2, staged_bytes: 2048, - adopted_files: 1, created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z", }; @@ -351,14 +350,12 @@ it("staged and filed counts use their own observations and older imports remain let page = await home({ api }); await page.click("Import…"); await page.until(() => page.text().includes("2 files · 2 kB"), "the staged report"); - assert.ok(page.text().includes("Filed1 file")); await cleanup?.(); cleanup = null; - Object.assign(row, { staged_files: null, staged_bytes: null, adopted_files: undefined }); + Object.assign(row, { staged_files: null, staged_bytes: null }); page = await home({ api }); await page.click("Import…"); await page.until(() => page.text().includes("not recorded"), "the unknown staged count"); - assert.ok(page.text().includes("Filedunknown")); }); for (const [code, unit, reason] of [ diff --git a/src/app/exomem/home/home-import-panels.tsx b/src/app/exomem/home/home-import-panels.tsx index e19c5d0b..5ec2d1e8 100644 --- a/src/app/exomem/home/home-import-panels.tsx +++ b/src/app/exomem/home/home-import-panels.tsx @@ -345,13 +345,11 @@ export function ImportReference({ importId, code }: { importId: string; code?: s export function StagedImportStorage({ stagedBytes, stagedFiles, - adoptedFiles, storage, now, }: { stagedBytes: number | null; stagedFiles: number | null; - adoptedFiles: number | null; storage: HomeStorage | null; now: number; }) { @@ -366,14 +364,6 @@ export function StagedImportStorage({ : totals({ files: stagedFiles, bytes: stagedBytes })}
-
-
Filed
-
- {adoptedFiles === null - ? "unknown" - : `${adoptedFiles} ${adoptedFiles === 1 ? "file" : "files"}`} -
-
Your vault
diff --git a/src/app/exomem/home/home-import.tsx b/src/app/exomem/home/home-import.tsx index 2d248c9a..8b584a4d 100644 --- a/src/app/exomem/home/home-import.tsx +++ b/src/app/exomem/home/home-import.tsx @@ -755,7 +755,6 @@ export function ImportDocuments({ diff --git a/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts index 8e08c37b..859f6ff4 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts @@ -10,7 +10,6 @@ import { randomCloudCellId } from "../cloud-admission"; import { cloudExportReply } from "../../exomem/cloud-export-contract"; import { handleCloudExportLinkRequest, handleCloudExportsRequest } from "../cloud-exports"; import { handleCloudHomeLevelsRequest, handleCloudHomeLiveRequest } from "../cloud-home-mcp"; -import { handleCloudImportRequest } from "../cloud-import-http"; import { handleCloudViewerRequest } from "../cloud-viewer"; import { findCloudOAuthAccessToken, resolveApprovedCloudOAuthClient } from "../cloud-oauth"; import { getOwnerCloudHomeStatus } from "../cloud-status"; @@ -69,15 +68,15 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function owner( - cell: { desired?: string; ready?: boolean; image?: string | null; reviewerPurpose?: boolean } = {} + cell: { desired?: string; ready?: boolean; image?: string | null } = {} ): Promise { const user = await pool.query("INSERT INTO exomem_users (email) VALUES ($1) RETURNING id", [ `home-${randomUUID()}@example.test`, ]); const userId = user.rows[0].id; const tenant = await pool.query( - "INSERT INTO exomem_tenants (owner_user_id, status, desired_state, marketplace_reviewer_purpose) VALUES ($1, 'active', 'running', $2) RETURNING id", - [userId, cell.reviewerPurpose ?? false] + "INSERT INTO exomem_tenants (owner_user_id, status, desired_state) VALUES ($1, 'active', 'running') RETURNING id", + [userId] ); const tenantId = tenant.rows[0].id; const cellId = randomCloudCellId(); @@ -630,142 +629,6 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database }); describe("Home channel", () => { - it("keeps the browser reviewer's credential on the optional filing observation", async () => { - const prior = process.env.EXOMEM_MARKETPLACE_REVIEWER_ACCESS_ENABLED; - let credentialId: string | undefined; - process.env.EXOMEM_MARKETPLACE_REVIEWER_ACCESS_ENABLED = "true"; - try { - const alice = await owner({ reviewerPurpose: true }); - await pool.query( - `INSERT INTO exomem_entitlements (tenant_id, source, source_state, effective_state) - VALUES ($1, 'complimentary', 'complimentary_active', 'active')`, - [alice.tenantId] - ); - const credential = await pool.query( - `INSERT INTO exomem_marketplace_reviewer_credentials ( - provider, username_digest, password_hash, owner_user_id, tenant_id, fixture_version, - fixture_payload_digest, created_by_principal_digest, expires_at, credential_kind - ) VALUES ('anthropic', $1, '$argon2id$test', $2, $3, 'sample-v1', $4, $5, - now() + interval '1 day', 'cloud_provider_review') RETURNING id`, - [ - digestSecret(randomUUID()), - alice.userId, - alice.tenantId, - "a".repeat(64), - digestSecret(randomUUID()), - ] - ); - credentialId = credential.rows[0].id; - await pool.query( - "UPDATE exomem_sessions SET reviewer_credential_id=$1 WHERE session_digest=$2", - [credentialId, digestSecret(alice.cookie)] - ); - await pool.query( - `INSERT INTO exomem_cloud_imports (cell_id, kind, declared_bytes, declared_files, observed_state) - VALUES ($1, 'adopt', 99, 9, 'done')`, - [alice.cellId] - ); - const cell = fakeCell(() => ({ complete: true, adopted_files: 1 })); - const response = await handleCloudImportRequest( - browserRequest(alice, "GET", "/api/exomem/cloud/imports"), - "status", - undefined, - { fetchCell: cell.fetchCell, env: ENV } - ); - assert.equal(response.status, 200); - assert.equal((await response.json()).import.adopted_files, 1); - const token = await pool.query( - "SELECT reviewer_credential_id FROM exomem_oauth_access_tokens WHERE access_digest=$1", - [digestSecret(cell.calls[0].bearer)] - ); - assert.equal(token.rows[0].reviewer_credential_id, credentialId); - } finally { - if (credentialId) - await pool.query( - "UPDATE exomem_marketplace_reviewer_credentials SET revoked_at=now() WHERE id=$1", - [credentialId] - ); - if (prior === undefined) delete process.env.EXOMEM_MARKETPLACE_REVIEWER_ACCESS_ENABLED; - else process.env.EXOMEM_MARKETPLACE_REVIEWER_ACCESS_ENABLED = prior; - } - }); - - it("reads the filed count through the owner's channel after the owned import lookup", async () => { - const alice = await owner(); - const bob = await owner(); - const importId = randomUUID(); - await pool.query( - `INSERT INTO exomem_cloud_imports (import_id, cell_id, kind, declared_bytes, declared_files, - observed_state, staged_files, staged_bytes) - VALUES ($1, $2, 'adopt', 99, 9, 'done', 4, 44)`, - [importId, alice.cellId] - ); - const cell = fakeCell(() => ({ adopted_files: 3, complete: true })); - const read = (who: Owner, id = importId) => - handleCloudImportRequest( - browserRequest( - who, - "GET", - `/api/exomem/cloud/imports/${id}?path=other&tenant_id=${bob.tenantId}` - ), - "status", - id, - { fetchCell: cell.fetchCell, env: ENV } - ); - assert.equal((await read(bob)).status, 404); - assert.equal(cell.calls.length, 0); - const response = await read(alice); - assert.equal(response.status, 200); - const result = await response.json(); - assert.equal(result.import.adopted_files, 3); - assert.equal(result.import.staged_files, 4); - assert.ok("limits" in result && "storage" in result); - assert.deepEqual(cell.calls[0].arguments, { action: "status", path: `_Imports/${importId}` }); - assert.equal(cell.calls[0].tool, "adoption_studio"); - assert.equal(cell.calls[0].routedTenantId, alice.tenantId); - assert.equal(cell.calls[0].routedCellId, alice.cellId); - assert.equal(cell.calls[0].firstParty, true); - await pool.query( - "UPDATE exomem_cloud_imports SET requested_state='cancelled' WHERE import_id=$1", - [importId] - ); - assert.equal((await (await read(alice)).json()).import.adopted_files, null); - assert.equal(cell.calls.length, 1); - }); - - it("keeps import status available when the filed count is incomplete, old or unavailable", async () => { - const alice = await owner(); - const importId = randomUUID(); - await pool.query( - `INSERT INTO exomem_cloud_imports (import_id, cell_id, kind, declared_bytes, declared_files, - observed_state) VALUES ($1, $2, 'adopt', 99, 9, 'done')`, - [importId, alice.cellId] - ); - for (const answer of [ - { adopted_files: 0, complete: true }, - { adopted_files: 2, complete: false }, - { runs: [] }, - { adopted_files: -1, complete: true }, - { adopted_files: 1.5, complete: true }, - { adopted_files: "2", complete: true }, - { success: false, error: { code: "READ_DENIED" } }, - Response.json({ error: "CELL_NOT_READY" }, { status: 503 }), - ]) { - const cell = fakeCell(() => answer); - const response = await handleCloudImportRequest( - browserRequest(alice, "GET", "/api/exomem/cloud/imports"), - "status", - undefined, - { fetchCell: cell.fetchCell, env: ENV } - ); - assert.equal(response.status, 200); - assert.equal( - (await response.json()).import.adopted_files, - "adopted_files" in answer && answer.adopted_files === 0 ? 0 : null - ); - } - }); - it("mints a token that the gateway routes only to the session's own cell, for 120 seconds", async () => { const alice = await owner(); const bob = await owner(); diff --git a/src/lib/exomem-hosted/cloud-home-mcp.ts b/src/lib/exomem-hosted/cloud-home-mcp.ts index 5dfb84e4..39291bad 100644 --- a/src/lib/exomem-hosted/cloud-home-mcp.ts +++ b/src/lib/exomem-hosted/cloud-home-mcp.ts @@ -8,14 +8,13 @@ * logged. The gateway's own lookup re-checks revocation, account blocks and * deletion when the token arrives (`findCloudOAuthAccessToken`). * - * Home calls `configure_memory`, the `bootstrap` activity section and scoped adoption status. + * Home calls only `configure_memory` and the `bootstrap` activity section. * The viewer reuses the same transport for three fixed read operations. * Browser callers never choose a tool, tenant, gateway or cell. */ import { randomUUID } from "node:crypto"; import { z } from "zod"; -import { stagedImportFolder } from "../exomem/cloud-import-contract"; import { loadExomemCloudResource, type EnvironmentSource } from "./cloud-config"; import { assertPrincipalOwnsCloudCell, CloudPrincipalHasNoCellError } from "./cloud-oauth"; import { executeExomemSql, withExomemTransaction } from "./db"; @@ -55,10 +54,6 @@ const ConfigureMemoryAnswer = z.object({ revision: z.string().min(1).max(128), levels: z.object({ coding: ContextLevel, conversation: ContextLevel }), }); -const AdoptedFilesAnswer = z.object({ - complete: z.literal(true), - adopted_files: z.number().int().nonnegative().safe(), -}); /** * The client families an activity event can name. This is the cell's closed @@ -172,8 +167,7 @@ type HomeToolCall = } | { action: "clear"; context: CloudHomeContext; expected_revision: string }; } - | { name: "bootstrap"; arguments: { profile: "compact"; section: "activity" } } - | { name: "adoption_studio"; arguments: { action: "status"; path: string } }; + | { name: "bootstrap"; arguments: { profile: "compact"; section: "activity" } }; // These names and argument shapes are the existing cell protocol, not a browser-selected proxy. export type CloudViewerToolCall = @@ -477,34 +471,6 @@ export async function callCloudViewerTool( return callHomeTool(principal, call, dependencies); } -/** Read only the server-selected import's complete historical filing count. */ -export async function readCloudImportAdoptedFiles( - principal: CloudHomePrincipal, - importId: string, - dependencies: CloudHomeDependencies = {} -): Promise { - if (!cloudHomeChannelEnabled(dependencies.env)) return null; - try { - const cell = await servingCell(principal); - if (cell.state !== "serving") return null; - const answer = await callHomeTool( - principal, - { - name: "adoption_studio", - arguments: { action: "status", path: stagedImportFolder(importId) }, - }, - dependencies - ); - if (answer.kind !== "result") return null; - const parsed = AdoptedFilesAnswer.safeParse(answer.value); - return parsed.success ? parsed.data.adopted_files : null; - } catch { - // Optional filing observations must not make the import's C5 status unavailable. - logUnavailable("adoption_studio", "CELL_UNREACHABLE"); - return null; - } -} - function liveLevels( value: unknown, desiredState: ServingCell["desiredState"] diff --git a/src/lib/exomem-hosted/cloud-import-http.ts b/src/lib/exomem-hosted/cloud-import-http.ts index 7fc6c344..3781c2f9 100644 --- a/src/lib/exomem-hosted/cloud-import-http.ts +++ b/src/lib/exomem-hosted/cloud-import-http.ts @@ -8,19 +8,17 @@ import { } from "./cloud-imports"; import { ExomemHostedError, safeErrorResponse } from "./errors"; import { readBoundedJsonRequest } from "./http"; -import type { CloudHomeDependencies } from "./cloud-home-mcp"; export async function handleCloudImportRequest( request: Request, action: CloudImportAction, - importId?: string, - dependencies: CloudHomeDependencies = {} + importId?: string ): Promise { const headers = { "cache-control": "no-store", "referrer-policy": "no-referrer" }; try { const principal = await resolveCloudImportPrincipal(request); if (action === "status") - return Response.json(await readCloudImport(principal, importId, dependencies), { headers }); + return Response.json(await readCloudImport(principal, importId), { headers }); const body = action === "cancel" || action === "discard" ? undefined diff --git a/src/lib/exomem-hosted/cloud-imports.ts b/src/lib/exomem-hosted/cloud-imports.ts index a61b4c00..1f8cb792 100644 --- a/src/lib/exomem-hosted/cloud-imports.ts +++ b/src/lib/exomem-hosted/cloud-imports.ts @@ -12,11 +12,6 @@ import { type UploadPart, } from "../exomem/cloud-import-contract"; import { resolveCloudOwnerPrincipal } from "./cloud-owner-principal"; -import { - readCloudImportAdoptedFiles, - type CloudHomeDependencies, - type CloudHomePrincipal, -} from "./cloud-home-mcp"; import { executeExomemSql, withExomemTransaction, type ExomemSql } from "./db"; import { ExomemHostedError, exomemErrors } from "./errors"; @@ -32,7 +27,6 @@ type CloudImportPrincipal = { tenantId: string; cellId: string; cellDesiredState: string; - homePrincipal?: CloudHomePrincipal; }; type CellRow = { desired_state: string; @@ -99,7 +93,6 @@ export async function resolveCloudImportPrincipal(request: Request): Promise Date: Wed, 2 Dec 2026 09:21:12 +0000 Subject: [PATCH 05/13] fix(cloud): size import growth from same-volume readings and settle the Home preflight Use the capacity ratio only when the usage reading is at least as recent as the capacity reading, never below 1, and clamp against the larger of the published cap and the current size. Home warns about free space only when growth cannot cover the need, refuses an encrypted copy above the multipart ceiling, needs the growth deadline only for the wait text, and says when limits could not be read. The staged size modifies the existing staged-originals requirement; hidden items stay out of the selection. --- e2e/exomem-home/import.spec.ts | 10 ++-- .../design.md | 13 ++--- .../specs/exomem-home/spec.md | 49 +++++++++++-------- .../specs/exomem-tenant-control-plane/spec.md | 14 +++--- .../tasks.md | 11 +++-- .../home/__tests__/home-import.test.tsx | 30 +++++++++++- src/app/exomem/home/home-import-panels.tsx | 27 ++++++++-- src/app/exomem/home/home-import.tsx | 29 ++++++++--- src/lib/exomem-hosted/cloud-imports.ts | 1 + .../__tests__/cloud-import-contract.test.ts | 33 +++++++++++-- src/lib/exomem/cloud-import-contract.ts | 28 +++++++---- 11 files changed, 175 insertions(+), 70 deletions(-) diff --git a/e2e/exomem-home/import.spec.ts b/e2e/exomem-home/import.spec.ts index 726111b8..ea16d306 100644 --- a/e2e/exomem-home/import.spec.ts +++ b/e2e/exomem-home/import.spec.ts @@ -425,9 +425,9 @@ test("admission grows before encryption and a reloaded upload sends only unrecor }); await signIn(context, owner); await page.goto("/exomem/home"); - await page.getByRole("button", { name: "Import…", exact: true }).click(); + await page.getByRole("button", { name: "Add files…", exact: true }).click(); let dialog = page.getByRole("dialog"); - await dialog.getByLabel("Folder to import").setInputFiles(folder); + await dialog.getByLabel("Folder to add").setInputFiles(folder); await expect(dialog.getByText("grows to about", { exact: false })).toBeVisible(); const created = page.waitForResponse( (response) => @@ -498,7 +498,7 @@ test("admission grows before encryption and a reloaded upload sends only unrecor 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: "Import…", exact: true }).click(); + 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") @@ -520,12 +520,12 @@ test("admission grows before encryption and a reloaded upload sends only unrecor [importId, Buffer.byteLength(content)] ); await page.reload(); - await page.getByRole("button", { name: "Import…", exact: true }).click(); + 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("1 file · 16 kB", { exact: true }) + page.getByRole("dialog").getByText("16 kB", { exact: true }) ).toBeVisible(); } finally { await page.close(); 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 53c5e40d..6a30c36c 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/design.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/design.md @@ -93,11 +93,12 @@ 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. @@ -110,7 +111,7 @@ The raise changes the cell's render digest, so it restarts the cell pod once. Ho 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 observed capacity covers `required_storage_bytes` and its storage receipt is current: `observed_storage_generation` equals the cell's generation. This is stricter than paid storage, which accepts any receipt at or after the generation it wrote. An unrelated generation change during the wait, such as an image rollout, therefore shows the import as growing until cellctl observes the storage again. No new observed state exists. `key_ready` keeps its meaning. @@ -159,7 +160,7 @@ Substrate branches on no storage-class name and holds no copy of the cap, the re 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. +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. @@ -167,4 +168,4 @@ Roll out outside the 02:00–05:00 UTC backup window. 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. 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. 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/specs/exomem-home/spec.md b/openspec/changes/admit-cloud-imports-against-published-limits/specs/exomem-home/spec.md index 261779e5..e9eeeb69 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 actual archive member count against the published maximum. The browser writes one file entry per selected file; implicit parent folders SHALL NOT add members. 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 archive's entry count against the published maximum. 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 say that limits are not published and that the cell checks during the import. When Home could not read the import route, it SHALL say that the limits could not be 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,7 +26,8 @@ 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 @@ -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 - **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,17 +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 bytes an import staged - -Home SHALL show the bytes that an import staged 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. The filed counts come from the cell's filing view, which this change does not alter. - -#### Scenario: An import has staged its files - -- **WHEN** an adopt import reaches `done` with a recorded staged count -- **THEN** Home shows the staged bytes from the Job's report - -#### 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 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 60aba694..eaf6dd71 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 whose storage has passed its rollout gate. It SHALL rewrite the value only when its content changes. Cellctl SHALL inspect the actual claim class and actively write NULL for local claims until authoritative shared capacity accounting and the local rehearsal pass. This SHALL clear any previously published object. Local publication and import growth SHALL remain open work in the paired Exomem task 1.7. 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 @@ -67,9 +67,9 @@ Creation SHALL run these steps in order inside its existing transaction, with th 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. -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. 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 @@ -107,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 @@ -119,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 authoritative capacity accounting shared by local volume consumers and this behavior pass the local cutover check. Until that gate passes, cellctl SHALL actively publish NULL for local claims. +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 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 76b5f84a..3707beab 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/tasks.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/tasks.md @@ -2,9 +2,9 @@ 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) @@ -16,8 +16,9 @@ The packets P1 to P7 below match the paired Exomem change `publish-cloud-import- ## 3. Home preflight and states (P4) - [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. +- [ ] 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) @@ -34,4 +35,4 @@ The follow-ups from the first Home import change live in `make-home-import-visib - [ ] 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. -- [ ] 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. +- [ ] 6.4 (Deferred to its own change; it does not hold this archive.) 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. diff --git a/src/app/exomem/home/__tests__/home-import.test.tsx b/src/app/exomem/home/__tests__/home-import.test.tsx index 7066c6f0..f70d6262 100644 --- a/src/app/exomem/home/__tests__/home-import.test.tsx +++ b/src/app/exomem/home/__tests__/home-import.test.tsx @@ -443,7 +443,7 @@ it("preflight refuses a selection with more entries than the limit and leaves no assert.equal(api.rows.size, 0); }); -it("preflight shows growth, the reserve warning and the measured reading without refusing existing-content pressure", async () => { +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 }, @@ -451,10 +451,36 @@ it("preflight shows growth, the reserve warning and the measured reading without await page.click("Add files…"); await page.choose(folder("research", 1), "Folder to add"); await page.until(() => page.text().includes("grows to about"), "the storage growth estimate"); - assert.ok(page.text().includes("reserve")); + 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("grows to about")); + 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("accepts in one upload"), "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({ diff --git a/src/app/exomem/home/home-import-panels.tsx b/src/app/exomem/home/home-import-panels.tsx index c701eca6..d7b422fb 100644 --- a/src/app/exomem/home/home-import-panels.tsx +++ b/src/app/exomem/home/home-import-panels.tsx @@ -39,6 +39,8 @@ export function browserFree(room: BrowserRoom): number | null { export function ImportLimits({ forecast, admission, + limitsRead, + partsCeiling, importStorage, room, others, @@ -50,6 +52,10 @@ export function ImportLimits({ 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; @@ -78,6 +84,12 @@ export function ImportLimits({ 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 ( <>
@@ -92,8 +104,7 @@ export function ImportLimits({
Storage needed
- {byteSize(admission.need_bytes)} of{" "} - {byteSize(admission.limits.max_storage_gib * IMPORT_GIB)} maximum + {byteSize(admission.need_bytes)} of {byteSize(admission.cap_bytes)} maximum
@@ -130,9 +141,17 @@ export function ImportLimits({
{!admission && (

- Limits not published; Evermatter checks them during the upload. + {limitsRead + ? "Limits not published; Evermatter checks them during the upload." + : "Limits could not be read; Evermatter checks them during the upload."}

)} + {partsCeiling !== null && ( + + The encrypted copy needs {byteSize(forecast.ciphertextBytes)}, more than this vault + accepts in one upload ({byteSize(partsCeiling)}). Choose fewer files. + + )} {admission?.refusal && ( {admission.refusal.code === "IMPORT_TOO_MANY_FILES" @@ -165,7 +184,7 @@ 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 {admission ? ` after the ${byteSize(reserve)} reserve` : ""} when it was measured{" "} diff --git a/src/app/exomem/home/home-import.tsx b/src/app/exomem/home/home-import.tsx index 48cbb71a..f4162ff6 100644 --- a/src/app/exomem/home/home-import.tsx +++ b/src/app/exomem/home/home-import.tsx @@ -6,7 +6,8 @@ import { Modal } from "@/components/exomem/Modal"; import { calculateImportAdmission, cloudImportFinished, - homeImportLimits, + importGrowthDeadline, + importPartLimits, type CloudImport, type CloudImportReply, type ImportLimit, @@ -520,9 +521,9 @@ export function ImportDocuments({ return () => controller.abort(); }, [measuring, resumingId, account, csrfToken, discards]); const measured = preflight && measuring && preflight.archive === measuring ? preflight : null; - const published = homeImportLimits.safeParse(context?.limits); + const deadline = importGrowthDeadline.safeParse(context?.limits); const admission = - measured && "forecast" in measured && context?.storage && published.success + measured && "forecast" in measured && context?.storage ? calculateImportAdmission( context.limits, context.storage, @@ -530,6 +531,18 @@ export function ImportDocuments({ 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(() => { @@ -682,7 +695,7 @@ export function ImportDocuments({ } function start() { - if (!archive || admission?.refusal) return; + if (!archive || refused) return; const previous = upload.current; const resumeId = awaiting && !reported ? awaiting.import_id : undefined; upload.current = new BrowserImportUpload({ @@ -881,10 +894,10 @@ export function ImportDocuments({ )} - {growth && published.success && ( + {growth && deadline.success && (

Evermatter allows up to{" "} - {count(Math.ceil(published.data.import_growth_deadline_seconds / 60))} minutes + {count(Math.ceil(deadline.data.import_growth_deadline_seconds / 60))} minutes for storage growth. This page keeps checking while the upload waits.

)} @@ -1014,6 +1027,8 @@ export function ImportDocuments({ void discardOthers()} /> )} - {measured && "forecast" in measured && !browserShort && !admission?.refusal && ( + {measured && "forecast" in measured && !browserShort && !refused && ( diff --git a/src/lib/exomem-hosted/cloud-imports.ts b/src/lib/exomem-hosted/cloud-imports.ts index fe4df4ff..801277be 100644 --- a/src/lib/exomem-hosted/cloud-imports.ts +++ b/src/lib/exomem-hosted/cloud-imports.ts @@ -175,6 +175,7 @@ function storage(cell: CellRow): ImportStorage { ? 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, }; } diff --git a/src/lib/exomem/__tests__/cloud-import-contract.test.ts b/src/lib/exomem/__tests__/cloud-import-contract.test.ts index df21c0b9..ce4d17f6 100644 --- a/src/lib/exomem/__tests__/cloud-import-contract.test.ts +++ b/src/lib/exomem/__tests__/cloud-import-contract.test.ts @@ -28,21 +28,46 @@ test("unknown usage treats the whole current volume as used without a stale rati assert.equal(result.required_storage_gib, 9); }); -test("a stale capacity ratio sizes growth but cannot refuse an import that fits an empty vault", () => { +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, + { ...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.ok(result.need_bytes > 20 * GiB); - assert.equal(result.required_storage_gib, 20); + 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", () => { diff --git a/src/lib/exomem/cloud-import-contract.ts b/src/lib/exomem/cloud-import-contract.ts index 993f5ffa..afa9aeb6 100644 --- a/src/lib/exomem/cloud-import-contract.ts +++ b/src/lib/exomem/cloud-import-contract.ts @@ -12,9 +12,8 @@ const admissionLimits = z.object({ max_storage_gib: positive, }); export const importPartLimits = z.object({ part_bytes: positive, max_parts: positive }); -export const homeImportLimits = admissionLimits.extend({ - import_growth_deadline_seconds: 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, @@ -29,6 +28,7 @@ const importStorage = z.object({ 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; @@ -42,16 +42,23 @@ export function calculateImportAdmission( const parsed = admissionLimits.safeParse(published); if (!parsed.success) return null; const limits = parsed.data; - const current = Math.max(storage.storage_gib, storage.grown_storage_gib ?? 0) * IMPORT_GIB; + 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 = - storage.used_bytes !== null && - storage.filesystem_bytes && - storage.observed_storage_capacity_bytes - ? storage.observed_storage_capacity_bytes / storage.filesystem_bytes + 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); - const cap = limits.max_storage_gib * IMPORT_GIB; + // 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 @@ -69,7 +76,8 @@ export function calculateImportAdmission( limits, need_bytes: need, current_storage_bytes: current, - required_storage_gib: Math.min(Math.ceil(need / IMPORT_GIB), limits.max_storage_gib), + cap_bytes: cap, + required_storage_gib: Math.min(Math.ceil(need / IMPORT_GIB), capGib), refusal, }; } From 29072428ff2b7e99a807a725862eb419f1720103 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 09:23:26 +0000 Subject: [PATCH 06/13] docs(openspec): name observed_storage_at in the import reply and defer the local cutover --- .../admit-cloud-imports-against-published-limits/design.md | 2 +- .../specs/exomem-tenant-control-plane/spec.md | 2 +- .../admit-cloud-imports-against-published-limits/tasks.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) 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 6a30c36c..a081a26b 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/design.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/design.md @@ -127,7 +127,7 @@ 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 reply also carries a nullable `storage` object with the calculator readings: `storage_gib`, `grown_storage_gib`, `observed_storage_capacity_bytes`, `used_bytes`, `filesystem_bytes` and `usage_observed_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. +`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 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 eaf6dd71..ab5ec73f 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 @@ -170,7 +170,7 @@ 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`. The reply SHALL also carry nullable `storage` with `storage_gib`, `grown_storage_gib`, `observed_storage_capacity_bytes`, `used_bytes`, `filesystem_bytes` and `usage_observed_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 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 observed capacity covers `required_storage_bytes` and its storage receipt shows no resize pending. Replies SHALL stay readable to clients that predate these fields. #### Scenario: Cancellation follows successful staging 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 3707beab..f0299cd6 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/tasks.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/tasks.md @@ -35,4 +35,4 @@ The follow-ups from the first Home import change live in `make-home-import-visib - [ ] 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. -- [ ] 6.4 (Deferred to its own change; it does not hold this archive.) 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. +- [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 to its own change: local cutover waits on the paired Exomem task 1.7, and cellctl publishes NULL for local claims until then. From 0c62dfe01a1279729a7d3de72b018767cad9fba0 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 09:31:17 +0000 Subject: [PATCH 07/13] build(exomem): regenerate the theme prepaint script --- src/lib/exomem/theme-script.generated.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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);})();"; From cf8235d85b1def5c2f21b8381fdba9568ea64654 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 09:40:15 +0000 Subject: [PATCH 08/13] fix(home): show the growth wait while an upload waits for the vault to grow --- .../home/__tests__/home-import.test.tsx | 25 +++++++++++++++++++ src/app/exomem/home/home-import.tsx | 22 +++++++++++++--- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/src/app/exomem/home/__tests__/home-import.test.tsx b/src/app/exomem/home/__tests__/home-import.test.tsx index f70d6262..0cab6b35 100644 --- a/src/app/exomem/home/__tests__/home-import.test.tsx +++ b/src/app/exomem/home/__tests__/home-import.test.tsx @@ -505,6 +505,31 @@ it("unpublished limits stay visibly unknown while a selection remains available" 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("Encryption starts when your vault is ready.")); + assert.ok(page.text().includes("60 minutes")); +}); + 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(); diff --git a/src/app/exomem/home/home-import.tsx b/src/app/exomem/home/home-import.tsx index f4162ff6..53316895 100644 --- a/src/app/exomem/home/home-import.tsx +++ b/src/app/exomem/home/home-import.tsx @@ -904,9 +904,25 @@ export function ImportDocuments({ ) )} - {busy && progress && !(progress.phase === "preparing" && growth) && ( - - )} + {busy && + progress && + (progress.phase === "preparing" && growth ? ( + // Encryption waits for the vault to grow; the wait is the upload's state. + <> +

+ {growth} +

+ {deadline.success && ( +

+ Evermatter allows up to{" "} + {count(Math.ceil(deadline.data.import_growth_deadline_seconds / 60))} minutes + for storage growth. Encryption starts when your vault is ready. +

+ )} + + ) : ( + + ))} {busy && progress && ( <>
-
Storage needed
+
Storage needed, estimate
- {byteSize(admission.need_bytes)} of {byteSize(admission.cap_bytes)} maximum + {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)}
@@ -139,32 +155,13 @@ export function ImportLimits({ ) )}
- {!admission && ( -

- {limitsRead - ? "Limits not published; Evermatter checks them during the upload." - : "Limits could not be read; Evermatter checks them during the upload."} -

- )} {partsCeiling !== null && ( - The encrypted copy needs {byteSize(forecast.ciphertextBytes)}, more than this vault - accepts in one upload ({byteSize(partsCeiling)}). Choose fewer files. + The encrypted copy ({byteSize(forecast.ciphertextBytes)}) is above this vault’s upload + limit ({byteSize(partsCeiling)}). Choose fewer files. )} - {admission?.refusal && ( - - {admission.refusal.code === "IMPORT_TOO_MANY_FILES" - ? "This selection has more files than this vault accepts in one upload. Choose fewer files." - : "This selection cannot fit within this vault’s storage limit. Choose fewer files."} - - )} - {grows && ( -

- Your vault’s storage grows to about{" "} - {byteSize(admission.required_storage_gib * IMPORT_GIB)} before encryption starts. -

- )} + {admission?.refusal && {importStopText(admission.refusal.code)}} {others !== null && others.files > 0 && ( <>

diff --git a/src/app/exomem/home/home-import.tsx b/src/app/exomem/home/home-import.tsx index 53316895..47964078 100644 --- a/src/app/exomem/home/home-import.tsx +++ b/src/app/exomem/home/home-import.tsx @@ -51,6 +51,7 @@ import { ImportStop, importPaused, importStopFrom, + importStopText, type ImportStopNext, } from "@/lib/exomem-hosted/cloud-import-stop"; import { friendlyHostedError, HostedBrowserError } from "@/lib/exomem-hosted/hosted-browser"; @@ -119,7 +120,7 @@ function growthWait(operation: CloudImport): string | null { operation.observed_state === "pending" && operation.required_storage_bytes != null && operation.storage_ready === false - ? `Your vault’s storage is growing to about ${byteSize(operation.required_storage_bytes)}.` + ? `Storage growing to about ${byteSize(operation.required_storage_bytes)}` : null; } @@ -339,9 +340,9 @@ export function ImportDocuments({ 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 ( @@ -802,21 +803,22 @@ export function ImportDocuments({ "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 = - growth ?? - (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) && ( @@ -887,19 +889,21 @@ export function ImportDocuments({ {operation.error_code && ( <>

- {importStopFrom( - new HostedBrowserError({ code: operation.error_code, message: "" }, 422) - )?.message ?? "Evermatter stopped the upload."} + {importStopText(operation.error_code) ?? "Evermatter stopped the upload."}

)} {growth && deadline.success && ( -

- Evermatter allows up to{" "} - {count(Math.ceil(deadline.data.import_growth_deadline_seconds / 60))} minutes - for storage growth. This page keeps checking while the upload waits. -

+
+
+
Growth time limit
+
+ {count(Math.ceil(deadline.data.import_growth_deadline_seconds / 60))}{" "} + minutes +
+
+
)} ) @@ -913,11 +917,15 @@ export function ImportDocuments({ {growth}

{deadline.success && ( -

- Evermatter allows up to{" "} - {count(Math.ceil(deadline.data.import_growth_deadline_seconds / 60))} minutes - for storage growth. Encryption starts when your vault is ready. -

+
+
+
Growth time limit
+
+ {count(Math.ceil(deadline.data.import_growth_deadline_seconds / 60))}{" "} + minutes +
+
+
)} ) : ( @@ -942,17 +950,30 @@ export function ImportDocuments({ {stop.text} {NEXT_STEP[stop.next]}

{stop.limit && ( -

- Requested:{" "} - {stop.limit.unit === "files" - ? `${count(stop.limit.requested)} files` - : byteSize(stop.limit.requested)} - . Published limit:{" "} - {stop.limit.unit === "files" - ? `${count(stop.limit.value)} files` - : byteSize(stop.limit.value)} - . -

+
+
+
+ {stop.limit.unit === "files" + ? "Archive entries" + : stop.code === "IMPORT_STORAGE_LIMIT" + ? "Space needed to unpack" + : "Encrypted copy"} +
+
+ {stop.limit.unit === "files" + ? count(stop.limit.requested) + : byteSize(stop.limit.requested)} +
+
+
+
Published limit
+
+ {stop.limit.unit === "files" + ? count(stop.limit.value) + : byteSize(stop.limit.value)} +
+
+
)} @@ -1000,7 +1021,7 @@ export function ImportDocuments({ {awaiting && parts === null && (

{growth - ? "This upload is waiting for its encrypted copy. Choose the same files again; encryption starts on this device when your vault is ready." + ? "Waiting for storage to grow. Choose the same files again to encrypt them." : "Upload stopped before its encrypted copy was finished"}

)} 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 e8be828b..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 @@ -294,12 +294,14 @@ describe("Cloud import API PostgreSQL boundary", { skip: !databaseUrl }, () => { (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, - false + true ); }); diff --git a/src/lib/exomem-hosted/cloud-import-browser-file.ts b/src/lib/exomem-hosted/cloud-import-browser-file.ts index d20b945e..12ae88ea 100644 --- a/src/lib/exomem-hosted/cloud-import-browser-file.ts +++ b/src/lib/exomem-hosted/cloud-import-browser-file.ts @@ -78,8 +78,10 @@ async function removeEntry(directory: FileSystemDirectoryHandle, name: string) { } async function removeCopy(directory: FileSystemDirectoryHandle, importId: string) { - await removeEntry(directory, ciphertextName(importId)); + // 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. */ diff --git a/src/lib/exomem-hosted/cloud-import-browser-upload.ts b/src/lib/exomem-hosted/cloud-import-browser-upload.ts index 05f239d6..19f1f071 100644 --- a/src/lib/exomem-hosted/cloud-import-browser-upload.ts +++ b/src/lib/exomem-hosted/cloud-import-browser-upload.ts @@ -41,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 = () => { @@ -51,7 +55,7 @@ function pauseUntilNextRead(signal: AbortSignal): Promise { const timer = setTimeout(() => { signal.removeEventListener("abort", stop); resolve(); - }, 2500); + }, ms); signal.addEventListener("abort", stop, { once: true }); }); } @@ -185,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"); diff --git a/src/lib/exomem-hosted/cloud-import-stop.ts b/src/lib/exomem-hosted/cloud-import-stop.ts index c100cada..efef58e2 100644 --- a/src/lib/exomem-hosted/cloud-import-stop.ts +++ b/src/lib/exomem-hosted/cloud-import-stop.ts @@ -112,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"; diff --git a/src/lib/exomem-hosted/cloud-imports.ts b/src/lib/exomem-hosted/cloud-imports.ts index 801277be..58dbd4fb 100644 --- a/src/lib/exomem-hosted/cloud-imports.ts +++ b/src/lib/exomem-hosted/cloud-imports.ts @@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto"; import { validate as validUuid } from "uuid"; import { cloudImportAvailable, + admissionLimits, calculateImportAdmission, IMPORT_GIB, importPartLimits, @@ -180,21 +181,19 @@ function storage(cell: CellRow): ImportStorage { } function limits(cell: CellRow) { - return calculateImportAdmission(cell.import_limits, storage(cell), 0, 0) - ? cell.import_limits - : null; + return admissionLimits.safeParse(cell.import_limits).success ? cell.import_limits : null; } function status(row: ImportRow, cell: CellRow): CloudImport { const required = row.required_storage_gib === null ? null : row.required_storage_gib * IMPORT_GIB; - // The controller publishes this generation receipt only after resize conditions clear. + // 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_generation === cell.generation && cell.observed_storage_pvc_uid && cell.observed_storage_pvc_version && cell.observed_storage_at @@ -249,6 +248,7 @@ export async function readCloudImport(principal: CloudImportPrincipal, importId? AND tenant.status NOT IN ('deletion_pending', 'deleted') AND cell.desired_state <> 'deleted' `; 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, @@ -347,7 +347,12 @@ export async function mutateCloudImport( admission.refusal.limit ); } - if (admission) { + // Only a requirement above the current size writes the cell: an equal raise would still + // 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 * diff --git a/src/lib/exomem/cloud-import-contract.ts b/src/lib/exomem/cloud-import-contract.ts index afa9aeb6..5d360865 100644 --- a/src/lib/exomem/cloud-import-contract.ts +++ b/src/lib/exomem/cloud-import-contract.ts @@ -5,7 +5,7 @@ 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({ +export const admissionLimits = z.object({ max_members: positive, reserve_bytes: positive, space_factor: positive, From 1e5a122d0680f360ceedc0fcaeda932e0c0c236d Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 10:04:48 +0000 Subject: [PATCH 10/13] fix(home): count the person's files against the limit and keep sizes on one line The preflight shows the selected files against the published maximum less the series file's entry. The growth row keeps a size and its unit together. The change text gives the real reason for skipping no-op growth writes, and the rendered pass ticks task 3.2. --- .../admit-cloud-imports-against-published-limits/design.md | 4 ++-- .../specs/exomem-home/spec.md | 2 +- .../specs/exomem-tenant-control-plane/spec.md | 2 +- .../admit-cloud-imports-against-published-limits/tasks.md | 2 +- src/app/exomem/home/__tests__/home-import.test.tsx | 4 ++-- src/app/exomem/home/home-import-panels.tsx | 5 +++-- src/app/exomem/home/home-import.tsx | 3 ++- src/lib/exomem-hosted/cloud-imports.ts | 4 ++-- 8 files changed, 14 insertions(+), 12 deletions(-) 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 8a891993..4bf220cc 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/design.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/design.md @@ -112,7 +112,7 @@ 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 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, because an equal raise would still bump the generation and restart the cell. +- 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. @@ -134,7 +134,7 @@ The three codes join the closed set of import protocol codes. Their error envelo 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. The browser writes one file entry per selected file; implicit parent folders add no TAR members. It refuses to start where admission would refuse. 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. 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 820ab7a6..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,7 +3,7 @@ ### 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 the admission limits (`max_members`, `reserve_bytes`, `space_factor` and `max_storage_gib`), the dialog SHALL also show the archive's entry count against the published maximum. 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. +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. 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 f4cc4be6..9820ddd5 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 @@ -65,7 +65,7 @@ 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. 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. 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 5cf7de09..ecbd46db 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/tasks.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/tasks.md @@ -16,7 +16,7 @@ The packets P1 to P7 below match the paired Exomem change `publish-cloud-import- ## 3. Home preflight and states (P4) - [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. -- [ ] 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.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. diff --git a/src/app/exomem/home/__tests__/home-import.test.tsx b/src/app/exomem/home/__tests__/home-import.test.tsx index 3a34389d..afb307e5 100644 --- a/src/app/exomem/home/__tests__/home-import.test.tsx +++ b/src/app/exomem/home/__tests__/home-import.test.tsx @@ -417,7 +417,7 @@ const readings = { usage_observed_at: "2026-01-01T00:00:00Z", }; -it("preflight admits a selection at the entry limit, counting the series entry the upload adds", async () => { +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, @@ -425,7 +425,7 @@ it("preflight admits a selection at the entry limit, counting the series entry t }); await page.click("Add files…"); await page.choose(folder("research", 1), "Folder to add"); - await page.until(() => page.text().includes("2 of 2"), "the archive's entry count"); + 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); }); diff --git a/src/app/exomem/home/home-import-panels.tsx b/src/app/exomem/home/home-import-panels.tsx index 7160d476..a39cb421 100644 --- a/src/app/exomem/home/home-import-panels.tsx +++ b/src/app/exomem/home/home-import-panels.tsx @@ -97,9 +97,10 @@ export function ImportLimits({ {admission && ( <>
-
Archive entries
+ {/* The series file always takes one archive entry, so the person's files get the rest. */} +
Files
- {count(forecast.members)} of {count(admission.limits.max_members)} + {count(forecast.files)} of {count(admission.limits.max_members - 1)}
diff --git a/src/app/exomem/home/home-import.tsx b/src/app/exomem/home/home-import.tsx index 47964078..2cdcac68 100644 --- a/src/app/exomem/home/home-import.tsx +++ b/src/app/exomem/home/home-import.tsx @@ -120,7 +120,8 @@ function growthWait(operation: CloudImport): string | null { operation.observed_state === "pending" && operation.required_storage_bytes != null && operation.storage_ready === false - ? `Storage growing to about ${byteSize(operation.required_storage_bytes)}` + ? // 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; } diff --git a/src/lib/exomem-hosted/cloud-imports.ts b/src/lib/exomem-hosted/cloud-imports.ts index 58dbd4fb..32b44612 100644 --- a/src/lib/exomem-hosted/cloud-imports.ts +++ b/src/lib/exomem-hosted/cloud-imports.ts @@ -347,8 +347,8 @@ export async function mutateCloudImport( admission.refusal.limit ); } - // Only a requirement above the current size writes the cell: an equal raise would still - // bump the generation and restart the cell for nothing. + // 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 From 7236b6f77233eaf6c1cfd5fb13634c760c198950 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 10:31:10 +0000 Subject: [PATCH 11/13] fix(home): fold the review follow-ups into the import admission batch A part receipt the browser cannot write no longer stops the upload. Limit refusals name their next step once, show files against the limit in the same terms as the preflight, and the series entry count lives beside the archive builder. The growth limit is one component that says it counts from the upload's start. The reply passes published limits whole for each reader to check, the growth write returns only the cell columns it reads, and C5 timestamps are measurement times. --- .../design.md | 2 +- .../specs/exomem-tenant-control-plane/spec.md | 2 +- .../home/__tests__/home-import.test.tsx | 1 + src/app/exomem/home/home-import-panels.tsx | 5 +- src/app/exomem/home/home-import.tsx | 47 ++++++++++--------- .../__tests__/cloud-import-browser.test.ts | 29 ++++++++++++ src/lib/exomem-hosted/cloud-import-browser.ts | 7 ++- .../exomem-hosted/cloud-import-envelope.ts | 3 ++ src/lib/exomem-hosted/cloud-imports.ts | 11 +++-- 9 files changed, 76 insertions(+), 31 deletions(-) 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 4bf220cc..93be1949 100644 --- a/openspec/changes/admit-cloud-imports-against-published-limits/design.md +++ b/openspec/changes/admit-cloud-imports-against-published-limits/design.md @@ -132,7 +132,7 @@ The three codes join the closed set of import protocol codes. Their error envelo ### 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. The browser writes one file entry per selected file; implicit parent folders add no TAR members. 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 shows "Import limits: not published", and the cell keeps checking during the import. It substitutes no constant. 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 9820ddd5..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 @@ -67,7 +67,7 @@ Creation SHALL run these steps in order inside its existing transaction, with th 5. When `space_factor × declared_bytes + reserve_bytes` exceeds the cap in bytes, refuse with 422 `IMPORT_STORAGE_LIMIT`. 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. 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. +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. 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. diff --git a/src/app/exomem/home/__tests__/home-import.test.tsx b/src/app/exomem/home/__tests__/home-import.test.tsx index afb307e5..d527dc8e 100644 --- a/src/app/exomem/home/__tests__/home-import.test.tsx +++ b/src/app/exomem/home/__tests__/home-import.test.tsx @@ -634,6 +634,7 @@ for (const [code, unit, reason] of [ 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")); }); } diff --git a/src/app/exomem/home/home-import-panels.tsx b/src/app/exomem/home/home-import-panels.tsx index a39cb421..ad007350 100644 --- a/src/app/exomem/home/home-import-panels.tsx +++ b/src/app/exomem/home/home-import-panels.tsx @@ -97,10 +97,11 @@ export function ImportLimits({ {admission && ( <>
- {/* The series file always takes one archive entry, so the person's files get the rest. */} + {/* 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 - 1)} + {count(forecast.files)} of{" "} + {count(admission.limits.max_members - (forecast.members - forecast.files))}
diff --git a/src/app/exomem/home/home-import.tsx b/src/app/exomem/home/home-import.tsx index 2cdcac68..9de22038 100644 --- a/src/app/exomem/home/home-import.tsx +++ b/src/app/exomem/home/home-import.tsx @@ -37,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, @@ -115,6 +119,18 @@ 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" && @@ -896,15 +912,7 @@ export function ImportDocuments({ )} {growth && deadline.success && ( -
-
-
Growth time limit
-
- {count(Math.ceil(deadline.data.import_growth_deadline_seconds / 60))}{" "} - minutes -
-
-
+ )} ) @@ -918,15 +926,7 @@ export function ImportDocuments({ {growth}

{deadline.success && ( -
-
-
Growth time limit
-
- {count(Math.ceil(deadline.data.import_growth_deadline_seconds / 60))}{" "} - minutes -
-
-
+ )} ) : ( @@ -948,21 +948,22 @@ export function ImportDocuments({ {!busy && stop?.kind === "failed" && ( <>

- {stop.text} {NEXT_STEP[stop.next]} + {/* A limit refusal already names its next step; "choose again" would invite it twice. */} + {stop.text} {stop.limit && stop.next === "choose" ? "" : NEXT_STEP[stop.next]}

{stop.limit && (
{stop.limit.unit === "files" - ? "Archive entries" + ? "Files" : stop.code === "IMPORT_STORAGE_LIMIT" ? "Space needed to unpack" : "Encrypted copy"}
{stop.limit.unit === "files" - ? count(stop.limit.requested) + ? count(stop.limit.requested - SERIES_ENTRIES) : byteSize(stop.limit.requested)}
@@ -970,7 +971,7 @@ export function ImportDocuments({
Published limit
{stop.limit.unit === "files" - ? count(stop.limit.value) + ? count(stop.limit.value - SERIES_ENTRIES) : byteSize(stop.limit.value)}
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 a6436453..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. diff --git a/src/lib/exomem-hosted/cloud-import-browser.ts b/src/lib/exomem-hosted/cloud-import-browser.ts index 1caa204c..70a71380 100644 --- a/src/lib/exomem-hosted/cloud-import-browser.ts +++ b/src/lib/exomem-hosted/cloud-import-browser.ts @@ -269,7 +269,12 @@ export async function uploadImportParts( if (!response.ok) throw new ImportStop("STORAGE_REFUSED"); const etag = response.headers.get("etag"); if (!etag) throw new ImportStop("STORAGE_UNCONFIRMED"); - await onConfirmed({ part_number: part.part_number, etag }); + 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..70d043e6 100644 --- a/src/lib/exomem-hosted/cloud-import-envelope.ts +++ b/src/lib/exomem-hosted/cloud-import-envelope.ts @@ -69,6 +69,9 @@ export function uploadOrigin(identity: BrowserIdentity, label: string): UploadOr * cell to file the import, names the collection of a single folder or zip, and states the * origin. Without such a name the cell names the collection after the import. */ +/** The archive entries every upload adds beside the person's files: its one series file. */ +export const SERIES_ENTRIES = 1; + export function importArchive( selection: ImportSelection, collection: string | null, diff --git a/src/lib/exomem-hosted/cloud-imports.ts b/src/lib/exomem-hosted/cloud-imports.ts index 32b44612..df933177 100644 --- a/src/lib/exomem-hosted/cloud-imports.ts +++ b/src/lib/exomem-hosted/cloud-imports.ts @@ -2,7 +2,6 @@ import { randomUUID } from "node:crypto"; import { validate as validUuid } from "uuid"; import { cloudImportAvailable, - admissionLimits, calculateImportAdmission, IMPORT_GIB, importPartLimits, @@ -180,8 +179,10 @@ function storage(cell: CellRow): ImportStorage { }; } +// Each reader checks the keys it needs (D2), so any published object passes through whole. function limits(cell: CellRow) { - return admissionLimits.safeParse(cell.import_limits).success ? cell.import_limits : null; + const value = cell.import_limits; + return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null; } function status(row: ImportRow, cell: CellRow): CloudImport { @@ -355,7 +356,11 @@ export async function mutateCloudImport( ) { const grown = await tx` UPDATE exomem_cloud_cells SET storage_gib = GREATEST(storage_gib, ${admission.required_storage_gib}) - WHERE cell_id = ${principal.cellId} RETURNING * + 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; } From 932fba527c26d802118994ceb848be807febf8a6 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 10:43:44 +0000 Subject: [PATCH 12/13] refactor(cloud): keep the admission schema private and the archive comment on its function --- src/lib/exomem-hosted/cloud-import-envelope.ts | 6 +++--- src/lib/exomem/cloud-import-contract.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/lib/exomem-hosted/cloud-import-envelope.ts b/src/lib/exomem-hosted/cloud-import-envelope.ts index 70d043e6..7c75caad 100644 --- a/src/lib/exomem-hosted/cloud-import-envelope.ts +++ b/src/lib/exomem-hosted/cloud-import-envelope.ts @@ -64,14 +64,14 @@ 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 * origin. Without such a name the cell names the collection after the import. */ -/** The archive entries every upload adds beside the person's files: its one series file. */ -export const SERIES_ENTRIES = 1; - export function importArchive( selection: ImportSelection, collection: string | null, diff --git a/src/lib/exomem/cloud-import-contract.ts b/src/lib/exomem/cloud-import-contract.ts index 5d360865..afa9aeb6 100644 --- a/src/lib/exomem/cloud-import-contract.ts +++ b/src/lib/exomem/cloud-import-contract.ts @@ -5,7 +5,7 @@ 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. -export const admissionLimits = z.object({ +const admissionLimits = z.object({ max_members: positive, reserve_bytes: positive, space_factor: positive, From 1135681d4794828697ad818d0acf72030037922a Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 10:44:44 +0000 Subject: [PATCH 13/13] fix(home): decide a refusal's next step from its code and keep the pause line true --- src/app/exomem/home/__tests__/home-import.test.tsx | 2 +- src/app/exomem/home/home-import.tsx | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/app/exomem/home/__tests__/home-import.test.tsx b/src/app/exomem/home/__tests__/home-import.test.tsx index d527dc8e..9c30dfef 100644 --- a/src/app/exomem/home/__tests__/home-import.test.tsx +++ b/src/app/exomem/home/__tests__/home-import.test.tsx @@ -237,7 +237,7 @@ it("closing the dialog keeps the import running, and a pause shows how to resume () => page .text() - .includes("Paused. Confirmed parts are kept in this browser, including after a reload."), + .includes("Paused. Parts already uploaded from this page are kept."), "the paused state" ); assert.ok(page.button("Resume upload")); diff --git a/src/app/exomem/home/home-import.tsx b/src/app/exomem/home/home-import.tsx index 9de22038..fd9e8ad9 100644 --- a/src/app/exomem/home/home-import.tsx +++ b/src/app/exomem/home/home-import.tsx @@ -202,7 +202,7 @@ function rowProgress(progress: ImportProgress): string { function pausedText(stop: Extract): string { if (stop.unavailable) return "Paused until uploads are available again."; if (stop.phase === "uploading" || stop.phase === "reporting" || stop.phase === "verifying") - return "Paused. Confirmed parts are kept in this browser, including after a reload."; + return "Paused. Parts already uploaded from this page are kept."; return stop.phase === "linking" ? "Paused. This browser keeps the encrypted copy for when you resume." : "Paused. Encryption starts again from the beginning when you resume."; @@ -949,7 +949,10 @@ export function ImportDocuments({ <>

{/* A limit refusal already names its next step; "choose again" would invite it twice. */} - {stop.text} {stop.limit && stop.next === "choose" ? "" : NEXT_STEP[stop.next]} + {stop.text}{" "} + {stop.code === "IMPORT_TOO_MANY_FILES" || stop.code === "IMPORT_STORAGE_LIMIT" + ? "" + : NEXT_STEP[stop.next]}

{stop.limit && (