Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(relay): account for sealed storage across boards [H15,H17]
Corey Olson536cb020967f
diff --git a/relay/auth.js b/relay/auth.jsindex cd494bc7..653c98d6 100644--- a/relay/auth.js+++ b/relay/auth.js@@ -78,6 +78,9 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =if (!db.prepare('PRAGMA table_info(relay_boards)').all().some((column) => column.name === 'linked_at')) {db.exec('ALTER TABLE relay_boards ADD COLUMN linked_at INTEGER');}+ if (!db.prepare('PRAGMA table_info(relay_boards)').all().some((column) => column.name === 'storage_account')) {+ db.exec('ALTER TABLE relay_boards ADD COLUMN storage_account TEXT REFERENCES relay_users(id)');+ }db.prepare('UPDATE relay_boards SET linked_at=? WHERE linked_at IS NULL').run(now());db.prepare('DELETE FROM relay_deleted_credentials WHERE expires<=?').run(now());db.exec('COMMIT');@@ -506,7 +509,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =if (db.prepare('SELECT 1 FROM relay_cleanup WHERE board=?').get(board)) throw new Refused('RELAY_CLEANUP', 'finish pending board cleanup before linking again');const existing = db.prepare('SELECT * FROM relay_boards WHERE id=?').get(board);if (existing && existing.repository_id !== String(repo.id)) throw new Refused('BOARD_LINK_CONFLICT', 'use a new board identifier for a different repository');- db.prepare('INSERT INTO relay_boards (id,repository,repository_id,linked_at) VALUES (?,?,?,?) ON CONFLICT(id) DO UPDATE SET repository=excluded.repository').run(board, repo.name, String(repo.id), now());+ db.prepare('INSERT INTO relay_boards (id,repository,repository_id,linked_at,storage_account) VALUES (?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET repository=excluded.repository,storage_account=COALESCE(relay_boards.storage_account,excluded.storage_account)').run(board, repo.name, String(repo.id), now(), row.user_id);permissions.delete(row.user_id + ':' + board);});return { id: board, repository: repo.name, repositoryID: String(repo.id) };@@ -516,6 +519,25 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =open();return db.prepare('SELECT id,repository,linked_at AS linkedAt FROM relay_boards ORDER BY id').all();},+ /** Resolve a stable storage account; only the service's authenticated writer may assign an older unassigned link. */+ storageAccount(board, authenticatedUserId) {+ identifier(board, 'BAD_BOARD');+ return lifecycle(() => {+ const saved = db.prepare('SELECT storage_account FROM relay_boards WHERE id=?').get(board);+ if (!saved) throw new Refused('BOARD_NOT_LINKED', 'Link this board before using relay storage.');+ if (saved.storage_account === null && authenticatedUserId !== undefined) {+ if (typeof authenticatedUserId !== 'string' || !db.prepare('SELECT 1 FROM relay_users WHERE id=?').get(authenticatedUserId)) throw new Refused('BAD_SENDER', 'Use the authenticated account when assigning existing relay storage.');+ db.prepare('UPDATE relay_boards SET storage_account=? WHERE id=? AND storage_account IS NULL').run(authenticatedUserId, board);+ }+ return db.prepare('SELECT id,login FROM relay_users WHERE id=(SELECT storage_account FROM relay_boards WHERE id=?)').get(board) ?? null;+ });+ },+ /** Internal account inventory for quota checks; repository authorization still governs every public board request. */+ storageBoards(account) {+ open();+ if (typeof account !== 'string' || !account) throw new Refused('BAD_SENDER', 'Name the authenticated storage account.');+ return db.prepare('SELECT id FROM relay_boards WHERE storage_account=? ORDER BY id').all(account).map(row => row.id);+ },/** Hold one shared lifecycle lock through every journal use and expiry decision. */withBoard(board, work) {identifier(board, 'BAD_BOARD');diff --git a/relay/journal.js b/relay/journal.jsindex 415d3aba..ee3e29b1 100644--- a/relay/journal.js+++ b/relay/journal.js@@ -4,7 +4,7 @@ import { closeSync, lstatSync, mkdirSync, openSync } from 'node:fs';import { join, resolve } from 'node:path';import { Refused } from '../src/refused.js';-const FORMAT = 3;+const FORMAT = 4;const DEFAULT_BYTES = 100_000;/** Validate a persistent identity before it can name an internal file. */@@ -44,7 +44,7 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTEif (saved.length === 0) {if (db.prepare('SELECT 1 FROM journal_record LIMIT 1').get()) throw new Refused('RELAY_STORAGE', 'restore the journal with its original identity and format metadata');db.prepare('INSERT INTO journal_meta (key,value) VALUES (?,?), (?,?)').run('board', id, 'format', String(FORMAT));- } else if (saved.length !== 2 || saved[0].key !== 'board' || saved[0].value !== id || saved[1].key !== 'format' || !['2', String(FORMAT)].includes(saved[1].value)) {+ } else if (saved.length !== 2 || saved[0].key !== 'board' || saved[0].value !== id || saved[1].key !== 'format' || !['2', '3', String(FORMAT)].includes(saved[1].value)) {throw new Refused('RELAY_STORAGE', 'open this journal with its original board identity and supported transport format');}db.exec(`CREATE TABLE IF NOT EXISTS journal_head (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL);@@ -71,6 +71,10 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTEDROP TABLE journal_snapshot_v2;UPDATE journal_meta SET value='3' WHERE key='format';`);}+ for (const [column, type] of [['api_version', 'INTEGER NOT NULL DEFAULT 1'], ['page_bytes', 'INTEGER']]) {+ if (!db.prepare('PRAGMA table_info(journal_snapshot)').all().some(row => row.name === column)) db.exec(`ALTER TABLE journal_snapshot ADD COLUMN ${column} ${type}`);+ }+ db.prepare('UPDATE journal_meta SET value=? WHERE key=?').run(String(FORMAT), 'format');// Engine-27 attribution (#579): the relay's policy stamp, the person-set coordinator flag and a// seat receipt. Older records keep these empty, so they replay exactly as they did.for (const [column, type] of [['sender_policy', 'INTEGER'], ['sender_root', 'INTEGER'], ['sender_lineage', 'TEXT'], ['registration', 'TEXT']]) {@@ -102,7 +106,8 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE...(row.sender_kind === 'agent' ? { agent: row.sender_agent } : row.sender_kind === 'machine' ? { machine: row.sender_agent } : {}),...(row.sender_policy ? { policy: row.sender_policy } : {}), ...(row.sender_root ? { root: true } : {}),...(row.sender_lineage ? { lineage: row.sender_lineage } : {}) },- ...(row.registration ? { registration: JSON.parse(row.registration) } : {}), bytes: Buffer.from(row.payload) };+ ...(row.registration ? { registration: JSON.parse(row.registration) } : {}),+ ...(row.api_version === 2 ? { apiVersion: 2, pageBytes: row.page_bytes } : {}), bytes: Buffer.from(row.payload) };}/** Require server-derived attribution, copying only its public identity and never a credential. */@@ -216,9 +221,10 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE}/** Replace a covered snapshot and compact only its acknowledged prefix, keeping the head. */- function saveSnapshot(sequence, bytes, principal, { initialOnly = false } = {}) {+ function saveSnapshot(sequence, bytes, principal, { initialOnly = false, apiVersion = 1, pageBytes = null } = {}) {open();if (!Number.isSafeInteger(sequence) || sequence < 0) throw new Refused('BAD_SEQUENCE', 'name the nonnegative sequence this snapshot covers');+ if (![1, 2].includes(apiVersion) || apiVersion === 2 && (!Number.isSafeInteger(pageBytes) || pageBytes < 1)) throw new Refused('SNAPSHOT_VERSION', 'Publish a supported snapshot transport version and its sealed root length.');const sealed = payload(bytes);const who = sender(principal, true);db.exec('BEGIN IMMEDIATE');@@ -229,7 +235,7 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTEif (previous && sequence < previous.sequence) throw new Refused('SNAPSHOT_STALE', 'use the latest stored snapshot and seal a snapshot that covers at least its sequence');const at = now();if (!(at instanceof Date) || !Number.isFinite(at.getTime())) throw new Refused('RELAY_CONFIG', 'the journal clock must return a valid Date');- db.prepare('INSERT INTO journal_snapshot (slot,sequence,received_at,payload,sender_kind,sender_user,sender_agent) VALUES (1,?,?,?,?,?,?) ON CONFLICT(slot) DO UPDATE SET sequence=excluded.sequence,received_at=excluded.received_at,payload=excluded.payload,sender_kind=excluded.sender_kind,sender_user=excluded.sender_user,sender_agent=excluded.sender_agent').run(sequence, at.toISOString(), sealed, who.kind, who.userId, who.agent);+ db.prepare('INSERT INTO journal_snapshot (slot,sequence,received_at,payload,sender_kind,sender_user,sender_agent,api_version,page_bytes) VALUES (1,?,?,?,?,?,?,?,?) ON CONFLICT(slot) DO UPDATE SET sequence=excluded.sequence,received_at=excluded.received_at,payload=excluded.payload,sender_kind=excluded.sender_kind,sender_user=excluded.sender_user,sender_agent=excluded.sender_agent,api_version=excluded.api_version,page_bytes=excluded.page_bytes').run(sequence, at.toISOString(), sealed, who.kind, who.userId, who.agent, apiVersion, apiVersion === 2 ? pageBytes : null);db.prepare('DELETE FROM journal_record WHERE sequence <= ?').run(sequence);const result = snapshot();db.exec('COMMIT');@@ -237,6 +243,16 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE} catch (error) { db.exec('ROLLBACK'); throw error; }}+ /** Measure the exact retained-byte change of a replacement and its compacted acknowledged prefix. */+ function snapshotDelta(sequence, bytes) {+ open();+ if (!Number.isSafeInteger(sequence) || sequence < 0) throw new Refused('BAD_SEQUENCE', 'Name the snapshot coverage sequence before accounting for storage.');+ const size = payload(bytes).byteLength;+ const previous = db.prepare('SELECT COALESCE(SUM(length(payload)),0) AS bytes FROM journal_snapshot').get().bytes;+ const compacted = db.prepare('SELECT COALESCE(SUM(length(payload)),0) AS bytes FROM journal_record WHERE sequence<=?').get(sequence).bytes;+ return size - previous - compacted;+ }+/** Replay the committed prefix in order, without parsing or executing its payloads. */function after(sequence = 0) {open();@@ -251,5 +267,5 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTEclosed = true;}- return { board: id, latest, activity, append, appendNext, recordAt, registrationFor, after, snapshot, saveSnapshot, close };+ return { board: id, latest, activity, append, appendNext, recordAt, registrationFor, after, snapshot, saveSnapshot, snapshotDelta, close };}diff --git a/relay/storage-quota.js b/relay/storage-quota.jsnew file mode 100644index 00000000..478de2f6--- /dev/null+++ b/relay/storage-quota.js@@ -0,0 +1,99 @@+/** Account-wide logical sealed storage, checked under the same cross-process lifecycle lock as publication [H15,H17,H18]. */+import { closeSync, lstatSync, mkdirSync, openSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { DatabaseSync } from 'node:sqlite';+import { Refused } from '../src/refused.js';++export const ACCOUNT_STORAGE_BYTES = 256_000_000;++/** Read only byte counts from a private relay database; never decode or return stored payloads. */+function storedBytes(file, query) {+ let stat;+ try { stat = lstatSync(file); } catch (error) { if (error.code === 'ENOENT') return 0; throw error; }+ if (!stat.isFile() || stat.isSymbolicLink() || stat.mode & 0o077) throw new Refused('RELAY_STORAGE', 'Keep account storage in private regular relay databases.');+ const db = new DatabaseSync(file, { readOnly: true });+ try { return db.prepare(query).get().bytes; } finally { db.close(); }+}++/** Count committed legacy bytes and every staged or committed opaque page for one linked board. */+export function boardStorageBytes(directory, id) {+ if (!/^[0-9a-f]{32}$/u.test(id ?? '')) throw new Refused('BAD_BOARD', 'Use a persistent board identity for storage accounting.');+ const root = resolve(directory);+ return storedBytes(join(root, id + '.journal.sqlite'), 'SELECT COALESCE((SELECT SUM(length(payload)) FROM journal_record),0)+COALESCE((SELECT SUM(length(payload)) FROM journal_snapshot),0) AS bytes')+ + storedBytes(join(root, id + '.pages.sqlite'), 'SELECT COALESCE(SUM(length(payload)+length(children)),0) AS bytes FROM page_object');+}++/** Format the provisional operator-set account budget without printing a credential or repository path. */+export function storageLimitMessage(storage) {+ return `Account ${storage.account.login} has used ${(storage.usedBytes / 1_000_000).toFixed(1)} MB of its ${(storage.limitBytes / 1_000_000).toFixed(1)} MB relay storage limit. Remove unneeded relay copies or ask the relay operator to increase the account quota.`;+}++/** Enforce a net storage change while authentication's shared lifecycle transaction excludes competing board writes. */+export function createStorageQuota({ directory, auth, limitBytes = ACCOUNT_STORAGE_BYTES }) {+ if (typeof directory !== 'string' || !Number.isSafeInteger(limitBytes) || limitBytes < 1 || !auth?.withBoard) throw new Refused('RELAY_CONFIG', 'Configure a positive account storage quota and the shared relay lifecycle lock.');+ const root = resolve(directory);+ mkdirSync(root, { recursive: true, mode: 0o700 });+ const parent = lstatSync(root);+ if (!parent.isDirectory() || parent.isSymbolicLink() || parent.mode & 0o077) throw new Refused('RELAY_STORAGE', 'Keep quota notices in private relay storage.');+ const file = join(root, 'storage-quota.sqlite');+ try { closeSync(openSync(file, 'wx', 0o600)); } catch (error) { if (error.code !== 'EEXIST') throw error; }+ const stat = lstatSync(file);+ if (!stat.isFile() || stat.isSymbolicLink() || stat.mode & 0o077) throw new Refused('RELAY_STORAGE', 'Keep quota notices in a private regular database.');+ const db = new DatabaseSync(file);+ db.exec('PRAGMA busy_timeout=30000; CREATE TABLE IF NOT EXISTS storage_warning (board TEXT PRIMARY KEY, storage TEXT NOT NULL, needed INTEGER NOT NULL)');+ let closed = false;++ /** Refuse use after shutdown instead of exposing a native database error. */+ function open() { if (closed) throw new Refused('RELAY_CLOSED', 'Open relay quota storage before using it.'); }++ /** Resolve only service-derived identity and count every board charged to that account. */+ function usage(board, principal) {+ open();+ if (!auth.storageAccount || !auth.storageBoards) throw new Refused('RELAY_CONFIG', 'Upgrade the relay authentication adapter for account storage quotas.');+ const account = auth.storageAccount(board, principal?.userId);+ if (!account) return null;+ let usedBytes = 0;+ for (const id of auth.storageBoards(account.id)) {+ usedBytes += boardStorageBytes(root, id);+ if (!Number.isSafeInteger(usedBytes)) throw new Refused('RELAY_STORAGE', 'Restore storage accounting within safe byte counts.');+ }+ return { account: { id: account.id, login: account.login }, usedBytes, limitBytes };+ }++ /** Execute a synchronous authorized write only when its additional retained bytes fit; shrinking writes remain available. */+ function change(board, principal, delta, write) {+ if (!Number.isSafeInteger(delta) || typeof write !== 'function') throw new Refused('RELAY_CONFIG', 'Compute the exact retained byte change before storing opaque data.');+ return auth.withBoard(board, () => {+ const storage = usage(board, principal);+ if (!storage) throw new Refused('RELAY_CONFIG', 'Assign the linked board to its authenticated storage account before uploading.');+ if (delta > 0 && storage.usedBytes + delta > limitBytes) {+ // This small independent notice survives the failed journal transaction, which must roll back its data write.+ db.prepare('INSERT INTO storage_warning VALUES (?,?,?) ON CONFLICT(board) DO UPDATE SET storage=excluded.storage,needed=excluded.needed').run(board, JSON.stringify(storage), delta);+ const error = new Refused('ACCOUNT_STORAGE_LIMIT', storageLimitMessage(storage));+ error.storage = storage;+ throw error;+ }+ const result = write();+ if (result && typeof result.then === 'function') throw new Refused('RELAY_CONFIG', 'Finish storage accounting and its write before awaiting.');+ return result;+ });+ }++ /** Keep the phone informed while a refused upload still lacks space, including after a service restart. */+ function notice(board) {+ open();+ const saved = db.prepare('SELECT storage,needed FROM storage_warning WHERE board=?').get(board);+ const current = usage(board);+ if (!current) return null;+ if (!saved && current.usedBytes < limitBytes) return null;+ if (saved && current.usedBytes + saved.needed <= limitBytes) return null;+ return { code: 'ACCOUNT_STORAGE_LIMIT', message: storageLimitMessage(current), storage: current };+ }++ /** A successful checkpoint or explicit unlink clears this board's old refusal notice. */+ function clear(board) { open(); db.prepare('DELETE FROM storage_warning WHERE board=?').run(board); }++ /** Close this private notice store exactly once. */+ function close() { if (!closed) { db.close(); closed = true; } }+ return { usage, change, notice, clear, close };+}diff --git a/test/relay-machine-journal.test.js b/test/relay-machine-journal.test.jsindex 1a67866f..8c8c6498 100644--- a/test/relay-machine-journal.test.js+++ b/test/relay-machine-journal.test.js@@ -89,7 +89,7 @@ test('[H7,H15] format-2 opaque history migrates to machine attribution without csender: PERSON, bytes: Buffer.from([7, 0, 255, 3]),}, 'the historical person snapshot remains unchanged');const migrated = databaseContents(path);- assert.equal(migrated.tables.journal_meta.find(row => row.key === 'format').value, '3');+ assert.equal(migrated.tables.journal_meta.find(row => row.key === 'format').value, '4');assert.equal(migrated.tables.journal_meta.find(row => row.key === 'board').value, ID);assert.equal(migrated.tables.journal_record.length, legacy.tables.journal_record.length);assert.equal(migrated.tables.journal_snapshot.length, legacy.tables.journal_snapshot.length);diff --git a/test/relay-storage-quota.test.js b/test/relay-storage-quota.test.jsnew file mode 100644index 00000000..a2561f69--- /dev/null+++ b/test/relay-storage-quota.test.js@@ -0,0 +1,116 @@+/** Real account attribution and a shared lifecycle lock protect storage across boards [H15,H17,H18]. */+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { DatabaseSync } from 'node:sqlite';+import { test } from 'node:test';+import { createRelayAuth } from '../relay/auth.js';+import { createGitHubClient } from '../relay/github.js';+import { createRelayJournal } from '../relay/journal.js';+import { createRelayPages } from '../relay/page-store.js';+import { boardStorageBytes, createStorageQuota } from '../relay/storage-quota.js';+import { githubFixture } from './relay-fixture.js';++const A = 'a'.repeat(32);+const B = 'b'.repeat(32);+const C = 'c'.repeat(32);++/** Complete a synthetic OAuth sign-in without returning any credential in a test assertion. */+async function signIn(auth) {+ const flow = auth.beginWeb();+ const redirect = await fetch(flow.authorizationURL, { redirect: 'manual' });+ const url = new URL(redirect.headers.get('location'));+ return auth.finishWeb(url.searchParams.get('state'), url.searchParams.get('code'), flow.binding);+}++/** Create actual private authentication and storage files with no owner data or relay connection. */+async function fixture(t, limitBytes = 300) {+ const provider = await githubFixture(t);+ const root = mkdtempSync(join(tmpdir(), 'pullboard-storage-quota-'));+ const directory = join(root, 'boards');+ const database = join(root, 'auth.sqlite');+ const auth = createRelayAuth({ database, github: createGitHubClient(provider.config) });+ const signed = await signIn(auth);+ await auth.linkBoard(signed.token, A, 'fixture/repository');+ await auth.linkBoard(signed.token, B, 'fixture/repository');+ const principal = { kind: 'machine', userId: signed.user.id, machine: 'fixture-native' };+ const quota = createStorageQuota({ directory, auth, limitBytes });+ const opened = [];+ t.after(() => { for (const store of opened) store.close(); quota.close(); auth.close(); rmSync(root, { recursive: true, force: true }); });+ /** Close each actual journal after one synchronous test operation. */+ function journal(id, work) {+ const store = createRelayJournal({ directory, boardId: id });+ try { return work(store); } finally { store.close(); }+ }+ /** Add real staged opaque bytes while leaving their interpretation on the client. */+ function page(id, size) {+ const store = createRelayPages({ directory, boardId: id }); opened.push(store);+ const upload = store.begin(principal, 0);+ const bytes = Buffer.alloc(size, 5);+ store.put(upload.id, principal, { id: createHash('sha256').update(bytes).digest('hex'), sequence: 0, bytes, children: [] });+ return store;+ }+ return { provider, root, directory, database, auth, signed, principal, quota, journal, page };+}++test('one account quota includes legacy bytes and unfinished pages across its boards [H15,H17]', async t => {+ const box = await fixture(t);+ box.journal(A, journal => journal.appendNext(Buffer.alloc(150), 'move', { kind: 'agent', userId: box.signed.user.id, agent: 'fixture' }));+ box.page(B, 110);+ assert.equal(boardStorageBytes(box.directory, A), 150);+ assert.equal(box.quota.usage(B).usedBytes, 262, 'the staged page and its opaque child index count alongside the other board');+ let wrote = false;+ assert.throws(() => box.quota.change(B, box.principal, 50, () => { wrote = true; }), { code: 'ACCOUNT_STORAGE_LIMIT' });+ assert.equal(wrote, false);+ const notice = box.quota.notice(B);+ assert.equal(notice.storage.account.id, box.signed.user.id);+ assert.equal(notice.storage.usedBytes, 262);+ assert.equal(notice.storage.limitBytes, 300);+ assert.ok(notice.message.includes(box.signed.user.login), 'the public notice names the authenticated account');+ const reopened = createStorageQuota({ directory: box.directory, auth: box.auth, limitBytes: 300 });+ try { assert.equal(reopened.notice(B).code, 'ACCOUNT_STORAGE_LIMIT', 'the warning survives a service restart'); }+ finally { reopened.close(); }+});++test('an existing storage account is stable across a second authorized link and another account has its own budget [H15,H17]', async t => {+ const box = await fixture(t);+ box.provider.state.accountID = 8; box.provider.state.permissionAccountID = 8;+ const other = await signIn(box.auth);+ await box.auth.linkBoard(other.token, A, 'fixture/repository');+ await box.auth.linkBoard(other.token, C, 'fixture/repository');+ assert.equal(box.auth.storageAccount(A, other.user.id).id, box.signed.user.id);+ assert.equal(box.auth.storageAccount(C).id, other.user.id);+ assert.deepEqual(box.auth.storageBoards(box.signed.user.id), [A, B]);+ assert.deepEqual(box.auth.storageBoards(other.user.id), [C]);+ box.page(A, 250);+ assert.equal(box.quota.usage(C).usedBytes, 0);+ box.quota.change(C, { kind: 'person', userId: other.user.id }, 200, () => {+ box.journal(C, journal => journal.saveSnapshot(0, Buffer.alloc(200), { kind: 'person', userId: other.user.id }));+ });+ assert.equal(box.quota.usage(C).usedBytes, 200);+ assert.equal(box.quota.usage(A).usedBytes, 252);+});++test('the quota lock remains held through the write and an over-quota account may still shrink [H15,H17]', async t => {+ const box = await fixture(t, 100);+ box.quota.change(A, box.principal, 90, () => {+ const independent = new DatabaseSync(box.database);+ try {+ independent.exec('PRAGMA busy_timeout=0');+ assert.throws(() => independent.exec('BEGIN IMMEDIATE'), /locked|busy/u, 'another connection cannot spend the same account budget during the write');+ } finally { independent.close(); }+ box.journal(A, journal => journal.saveSnapshot(0, Buffer.alloc(90), { kind: 'person', userId: box.signed.user.id }));+ });+ const lower = createStorageQuota({ directory: box.directory, auth: box.auth, limitBytes: 20 });+ try {+ box.journal(A, journal => {+ const replacement = Buffer.alloc(50);+ const delta = journal.snapshotDelta(0, replacement);+ assert.equal(delta, -40);+ lower.change(A, box.principal, delta, () => journal.saveSnapshot(0, replacement, { kind: 'person', userId: box.signed.user.id }));+ });+ assert.equal(lower.usage(A).usedBytes, 50, 'a reducing write remains possible even before usage falls below the lowered quota');+ } finally { lower.close(); }+});