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): warn before quota refusal [H5]
Corey Olson3a2d5ad1f335
diff --git a/relay/browser-client.js b/relay/browser-client.jsindex edc3ba00..bb73849a 100644--- a/relay/browser-client.js+++ b/relay/browser-client.js@@ -206,7 +206,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>const phoneWaiting = root.dataset.relayDevice === 'phone' && (!rendered || paired.size === 0);const step = emptyBoardStep({ available, waitingBoards, approvedBoards, loaded: inventoryLoaded, browserPaired, failure });showRelayScreen(root, phoneWaiting || paired.size === 0 ? 'share' : null,- phoneWaiting && (failure || waitingBoards.size || warnings.some(value => value?.code === 'ACCOUNT_STORAGE_LIMIT')) ? lines.join(' ') : '', step);+ phoneWaiting && (failure || waitingBoards.size || warnings.some(value => ['ACCOUNT_STORAGE_WARNING', 'ACCOUNT_STORAGE_LIMIT'].includes(value?.code))) ? lines.join(' ') : '', step);placePhoneApprovals(document);}@@ -236,7 +236,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>/** Retain one warning per board without duplicating it on the next live poll. */function warning(value, boardId) {- if (!value || !['BOARD_INACTIVE', 'ACCOUNT_STORAGE_LIMIT'].includes(value.code)) return;+ if (!value || !['BOARD_INACTIVE', 'ACCOUNT_STORAGE_WARNING', 'ACCOUNT_STORAGE_LIMIT'].includes(value.code)) return;warnings = warnings.filter(entry => entry.board !== boardId || entry.code !== value.code);warnings.push({ ...value, board: boardId });notice();@@ -397,6 +397,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>document = await boardEvents(entry);}warning(document.warning, entry.id);+ for (const value of document.warnings ?? []) warning(value, entry.id);for (const row of document.events) await receive(entry, row, true);}diff --git a/relay/browser-notice.js b/relay/browser-notice.jsindex 94bdf7b8..d05664c7 100644--- a/relay/browser-notice.js+++ b/relay/browser-notice.js@@ -65,7 +65,13 @@ export function noticeLines({ available, paired, ownedRequestIds = new Map(), wafor (const warning of warnings) if (warning?.code === 'BOARD_INACTIVE' && Number.isInteger(warning.daysLeft)) {lines.push('BOARD_INACTIVE: ' + warning.daysLeft + ' days left before this relay board is deleted. Make a board move from a linked machine to keep it.');}- for (const warning of warnings) if (warning?.code === 'ACCOUNT_STORAGE_LIMIT' && typeof warning.message === 'string') lines.push(warning.message);+ const storageAccounts = new Set();+ for (const warning of warnings) if (['ACCOUNT_STORAGE_WARNING', 'ACCOUNT_STORAGE_LIMIT'].includes(warning?.code) && typeof warning.message === 'string') {+ const account = warning.storage?.account?.id;+ if (account && storageAccounts.has(account)) continue;+ if (account) storageAccounts.add(account);+ lines.push(warning.message);+ }if (failure) lines.push(failure);if (!available.length) lines.push('No linked boards are available for this account.');return lines;diff --git a/relay/service.js b/relay/service.jsindex a203b31c..0df41319 100644--- a/relay/service.js+++ b/relay/service.js@@ -303,8 +303,12 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin},boards: (who) => {const boards = who.visible.filter((board) => !retention.expire(board.id));+ const warnedAccounts = new Set();const warnings = boards.flatMap((board) => {const storage = quota?.notice(board.id);+ const accountId = storage?.storage?.account?.id;+ if (accountId && warnedAccounts.has(accountId)) return [retention.notice(board.id)].filter(Boolean);+ if (accountId) warnedAccounts.add(accountId);return [retention.notice(board.id), ...(storage ? [{ board: board.id, ...storage }] : [])].filter(Boolean);});return { boards, ...(warnings.length ? { warnings } : {}) };@@ -321,6 +325,7 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginreturn journal.after(after).map(event);}, false, board.engineVersion),warning: (board) => retention.notice(board.id),+ warnings: (board) => [quota?.notice(board.id)].filter(Boolean),move: append,request: async (board, body, who) => (await append(board, body, who, 'request')).body,}, { pollMs });diff --git a/relay/storage-quota.js b/relay/storage-quota.jsindex f02fa671..8b1ecf8b 100644--- a/relay/storage-quota.js+++ b/relay/storage-quota.js@@ -35,6 +35,11 @@ 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.`;}+/** Warn before the account reaches its quota while naming exact bytes and the available next step. */+function storageWarningMessage(storage) {+ return `Account ${storage.account.login} has used ${storage.usedBytes} of ${storage.limitBytes} bytes of relay storage (over 80%). 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.');@@ -93,9 +98,11 @@ export function createStorageQuota({ directory, auth, limitBytes = ACCOUNT_STORAconst 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 };+ if (saved && current.usedBytes + saved.needed > limitBytes || current.usedBytes >= limitBytes) {+ return { code: 'ACCOUNT_STORAGE_LIMIT', message: storageLimitMessage(current), storage: current };+ }+ if (current.usedBytes / current.limitBytes <= 0.8) return null;+ return { code: 'ACCOUNT_STORAGE_WARNING', message: storageWarningMessage(current), storage: current };}/** A successful checkpoint or explicit unlink clears this board's old refusal notice. */diff --git a/src/api-http.js b/src/api-http.jsindex 78d2554a..e0b315f1 100644--- a/src/api-http.js+++ b/src/api-http.js@@ -129,6 +129,13 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {}}+ /** Preserve the legacy primary warning while carrying additional independent notices. */+ async function warningsFor(board, who) {+ const primary = await adapter.warning?.(board, who);+ const additional = await adapter.warnings?.(board, who);+ return [primary, ...(Array.isArray(additional) ? additional : [])].filter(Boolean);+ }+/*** Replay and follow one or more boards' records on one response, respecting slow clients and* revocation between polls. A tagged stream names each frame's board, and each ordinary@@ -165,11 +172,13 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {for (const follow of follows) {current = follow;follow.who = await adapter.authenticate(req, { board: follow.board.id, write: false });- const warning = await adapter.warning?.(follow.board, follow.who);- const serialized = warning ? frame(follow, { warning }) : null;+ const warnings = await warningsFor(follow.board, follow.who);+ const serialized = warnings.length ? JSON.stringify(warnings) : null;if (serialized !== follow.lastWarning) {follow.lastWarning = serialized;- if (serialized && !res.write('event: warning\ndata: ' + serialized + '\n\n')) { blocked = true; return; }+ for (const warning of warnings) {+ if (!res.write('event: warning\ndata: ' + frame(follow, { warning }) + '\n\n')) { blocked = true; return; }+ }}const records = follow.initial ?? await adapter.events(follow.board, follow.after, follow.who);follow.initial = null;@@ -314,9 +323,10 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {}}const initial = await adapter.events(board, after, who);- const warning = await adapter.warning?.(board, who);+ const warnings = await warningsFor(board, who);const eventLogVersion = await adapter.eventLogVersion?.(board, who);- return json(res, 200, { events: initial, ...(eventLogVersion === undefined ? {} : { eventLogVersion }), ...(warning ? { warning } : {}) });+ return json(res, 200, { events: initial, ...(eventLogVersion === undefined ? {} : { eventLogVersion }),+ ...(warnings.length ? { warning: warnings[0], ...(warnings.length > 1 ? { warnings: warnings.slice(1) } : {}) } : {}) });}if (req.method === 'POST' && route[2] === 'moves') {const moved = await adapter.move(board, await readBody(req), who);diff --git a/src/relay-notices.js b/src/relay-notices.jsnew file mode 100644index 00000000..49efaaad--- /dev/null+++ b/src/relay-notices.js@@ -0,0 +1,17 @@+const WARNED_COMMANDS = new WeakSet();+const STORAGE_WARNED_COMMANDS = new WeakSet();++/** Print relay warnings once per command, keeping account storage notices distinct from refusal behavior. */+export function relayNotices(document, io) {+ const warnings = [document.warning, document.state?.warning, ...(document.warnings ?? [])].filter(Boolean);+ if (!io || typeof io !== 'object' || typeof io.err !== 'function') return;+ for (const warning of warnings) {+ if (warning.code === 'BOARD_INACTIVE' && !WARNED_COMMANDS.has(io)) {+ WARNED_COMMANDS.add(io);+ io.err(`pullboard: [BOARD_INACTIVE] ${warning.daysLeft} days left before this relay board is deleted; ${warning.next || 'make a board move before the deadline to keep it'}`);+ } else if (['ACCOUNT_STORAGE_WARNING', 'ACCOUNT_STORAGE_LIMIT'].includes(warning.code) && !STORAGE_WARNED_COMMANDS.has(io)) {+ STORAGE_WARNED_COMMANDS.add(io);+ io.err(`pullboard: [${warning.code}] ${warning.message}`);+ }+ }+}diff --git a/src/relay.js b/src/relay.jsindex d9593c76..cc0e67a1 100644--- a/src/relay.js+++ b/src/relay.js@@ -87,6 +87,7 @@ import { terminalQr } from './qr.js';import { Refused } from './refused.js';import { refusalFromReceipt } from './recorded-refusal.js';import { relaySenderProblem } from './relay-sender.js';+import { relayNotices } from './relay-notices.js';import {readRelayMachine,removeRecordedDevice,@@ -119,7 +120,6 @@ export { relayStorageLine };export const DEFAULT_RELAY = 'https://app.pullboard.dev';const LINK_FILES = new WeakMap();const STATE_FILES = new WeakMap();-const WARNED_COMMANDS = new WeakSet();const KEY_WARNED_COMMANDS = new WeakSet();const BASELINE_ATTEMPTS = new WeakMap();const BASELINE_NOTICES = new WeakSet();@@ -342,15 +342,6 @@ async function locked(file, work) {} finally { rmSync(lock, { recursive: true, force: true }); }}-/** Surface retention notices on the very command that receives them, without exposing credentials. */-function notices(document, io) {- const warnings = [document.warning, document.state?.warning, ...(document.warnings ?? [])].filter(Boolean);- for (const warning of warnings) if (warning.code === 'BOARD_INACTIVE' && !WARNED_COMMANDS.has(io)) {- WARNED_COMMANDS.add(io);- io.err(`pullboard: [BOARD_INACTIVE] ${warning.daysLeft} days left before this relay board is deleted; ${warning.next || 'make a board move before the deadline to keep it'}`);- }-}-/*** Name how a relay request failed before any response, from the error's own fields only.* Why: a bare "did not answer" hid whether a request timed out, was refused or lost its socket,@@ -410,7 +401,7 @@ async function rawRequest(state, path, { method = 'GET', body, allowMissing = faerror.httpStatus = response.status;throw error;}- notices(document, io);+ relayNotices(document, io);// Only off can forget a link after a supported API reports that the board is gone.if (allowMissing && method === 'DELETE' && response.status === 404 && document.version === 1) return { alreadyDeleted: true };if (!response.ok) {diff --git a/test/relay-storage-quota.test.js b/test/relay-storage-quota.test.jsindex a2561f69..03787d5a 100644--- a/test/relay-storage-quota.test.js+++ b/test/relay-storage-quota.test.js@@ -1,7 +1,9 @@/** 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 { once } from 'node:events';import { mkdtempSync, rmSync } from 'node:fs';+import { createServer } from 'node:http';import { tmpdir } from 'node:os';import { join } from 'node:path';import { DatabaseSync } from 'node:sqlite';@@ -10,7 +12,11 @@ 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 { createRelayHandler } from '../relay/service.js';+import { noticeLines } from '../relay/browser-notice.js';import { boardStorageBytes, createStorageQuota } from '../relay/storage-quota.js';+import { ENGINE_VERSION } from '../src/machine.js';+import { request as relayRequest } from '../src/relay.js';import { githubFixture } from './relay-fixture.js';const A = 'a'.repeat(32);@@ -74,6 +80,61 @@ test('one account quota includes legacy bytes and unfinished pages across its bofinally { reopened.close(); }});+test('an account nearing its storage quota is warned before any write is refused [H5,H15,H17]', async t => {+ const box = await fixture(t, 300);+ const actor = { kind: 'agent', userId: box.signed.user.id, agent: 'fixture' };+ box.journal(A, journal => journal.appendNext(Buffer.alloc(120), 'move', actor));+ box.journal(B, journal => journal.appendNext(Buffer.alloc(120), 'move', actor));+ assert.equal(box.quota.usage(A).usedBytes, 240);+ assert.equal(box.quota.notice(A), null, 'exactly 80 percent does not cross the warning threshold');+ box.journal(B, journal => journal.appendNext(Buffer.alloc(1), 'move', actor));++ const warning = box.quota.notice(A);+ assert.equal(warning.code, 'ACCOUNT_STORAGE_WARNING');+ assert.equal(warning.storage.usedBytes, 241);+ assert.equal(warning.storage.limitBytes, 300);+ assert.match(warning.message, /241 of 300 bytes/u);+ assert.match(warning.message, /Remove unneeded relay copies/u);++ let handler;+ const server = createServer((req, res) => handler(req, res));+ server.listen(0, '127.0.0.1');+ await once(server, 'listening');+ const origin = 'http://127.0.0.1:' + server.address().port;+ handler = createRelayHandler({ directory: box.directory, auth: box.auth, publicOrigin: origin, maintenanceMs: 0, accountStorageBytes: 300 });+ try {+ /** Read a relay document without returning the signed-in test credential in diagnostics. */+ async function call(path) {+ const response = await fetch(origin + path, { headers: { authorization: 'Bearer ' + box.signed.token, 'x-pullboard-engine': String(ENGINE_VERSION) } });+ return { status: response.status, document: await response.json() };+ }+ const listing = await call('/api/v1/boards');+ assert.equal(listing.status, 200);+ const listedWarnings = listing.document.warnings.filter(value => value.code === 'ACCOUNT_STORAGE_WARNING');+ assert.equal(listedWarnings.length, 1, 'the phone inventory names an account warning once across its linked boards');+ assert.equal(listedWarnings[0].storage.usedBytes, 241);++ const events = await call('/api/v1/boards/' + A + '/events?after=0');+ assert.equal(events.document.warning.code, 'ACCOUNT_STORAGE_WARNING', 'the sync/status event read carries the same warning');+ const messages = [];+ const io = { ignoreRelayEnvironmentToken: true, err: value => messages.push(value) };+ const state = { url: origin, board: A, token: box.signed.token };+ await relayRequest(state, '/api/v1/boards/' + A + '/events?after=0', {}, io);+ await relayRequest(state, '/api/v1/boards/' + A + '/events?after=0', {}, io);+ assert.equal(messages.length, 1, 'one command surfaces one account warning even when it reads more than once');+ assert.match(messages[0], /ACCOUNT_STORAGE_WARNING.*241 of 300 bytes/u);++ const duplicateInventory = [listedWarnings[0], { ...listedWarnings[0], board: B }];+ const lines = noticeLines({ available: [{ id: A, repository: 'fixture/repository' }, { id: B, repository: 'fixture/repository' }],+ paired: new Map([[A, { state: {} }], [B, { state: {} }]]), warnings: duplicateInventory });+ assert.equal(lines.filter(value => value.includes('241 of 300 bytes')).length, 1, 'the phone page shows one warning for the shared account');+ } finally {+ server.closeAllConnections();+ await new Promise(resolve => server.close(resolve));+ handler.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;