Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(persistence): push capacity warnings from a 60 s snapshot (#6696 A4)
garrytan3b2c5e43acad
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.mdindex 68501aee0b..52934e7ea4 100644--- a/docs/guides/concurrent-writes.md+++ b/docs/guides/concurrent-writes.md@@ -943,3 +943,40 @@ When `persistence_capacity` warns or fails, or a write is refused withRaising a receipt-bytes cap is safe: the counter tracks bytes that are reallystored, and compaction frees the window's reservations as receipts age out.++**Warnings before the wall.** A cap at or past 80%, or one that runs out+within `persistence.capacity.warn_days` (default 30), adds the+`[gbrain notice write_capacity_low]` notice (kind `info`) with the same+`gbrain config set` command. Write and sync receipts carry it at most once an+hour per process per scope (a remote client sees only the brain and its own+principal); `gbrain sync status`, doctor and autopilot cycle output carry it+every time. `gbrain notices mute write_capacity_low` mutes it on receipts;+doctor still reports it. When a cap passes+`persistence.capacity.background_pause_pct` (default 80) background+producers pause and `[gbrain notice write_capacity_backpressure]` (kind+`degraded`) fires once when the pause starts. Every notice reads a capacity+snapshot that refreshes at most once a minute; no write computes a forecast.++**Alerting (hosted operators).** The admin `/metrics` endpoint exports+`gbrain_write_capacity_used`, `gbrain_write_capacity_limit` and+`gbrain_write_capacity_days_to_exhaustion`, labelled `scope` and `resource`+(`lifetime_ids` or `terminal_bytes`), from the same snapshot. The public+`/health` probe is unchanged. A Prometheus rule that pages before the+background pause and before the wall:++```yaml+groups:+ - name: gbrain-write-capacity+ rules:+ - alert: GbrainWriteCapacityLow+ expr: gbrain_write_capacity_used / gbrain_write_capacity_limit >= 0.8 or gbrain_write_capacity_days_to_exhaustion < 30+ for: 15m+ labels: { severity: warning }+ annotations:+ summary: "{{ $labels.scope }} {{ $labels.resource }} write cap near exhaustion"+ runbook: docs/guides/concurrent-writes.md#quota-near-exhaustion+ - alert: GbrainWriteCapacityCritical+ expr: gbrain_write_capacity_used / gbrain_write_capacity_limit >= 0.95 or gbrain_write_capacity_days_to_exhaustion < 7+ for: 5m+ labels: { severity: critical }+```diff --git a/src/cli/main.ts b/src/cli/main.tsindex cde338e12f..253a93b1e4 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -688,6 +688,8 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C}} else {rawResult = await op.handler(ctx, params);+ // #6696 (A4): a local write's output carries the capacity notices (60 s snapshot, hourly per scope).+ if (op.mutating) for (const notice of await (await import('../core/persistence/capacity-snapshot.ts')).capacityNotices(engine).catch(() => [])) captureOpNotice(notice);}// ENG-2 (renderer parity by data shape): JSON-round-trip the local-engine// path's return value so renderers see the same shape they'd see on thediff --git a/src/commands/serve-http-metrics.ts b/src/commands/serve-http-metrics.tsindex 8b029c5a5d..2f83812b14 100644--- a/src/commands/serve-http-metrics.ts+++ b/src/commands/serve-http-metrics.ts@@ -18,6 +18,7 @@* `mountHealth` serves the public liveness probe; `probeHealth` backs the* admin-only full-stats endpoint.*/+import { cachedCapacitySnapshot, type CapacitySnapshot } from '../core/persistence/capacity-snapshot.ts';import type { Express, NextFunction, Request, RequestHandler, Response } from 'express';import type { BrainEngine } from '../core/engine.ts';import { resolveInflightTimeoutSeconds, resolveSessionTimeouts } from '../core/db.ts';@@ -121,6 +122,30 @@ export function cachedTerminalSummary(engine: BrainEngine, now: number = Date.noreturn summary;}+/**+ * #6696 (A4): cumulative write-cap gauges from the 60 s capacity snapshot (never a forecast per scrape): use, cap and+ * days left per scope and resource. Alert rule: docs/guides/concurrent-writes.md#quota-near-exhaustion.+ */+export function renderCapacityMetrics(snapshot: CapacitySnapshot): string {+ if (snapshot.status !== 'ok' || !snapshot.rows.length) return '';+ const label = (value: string) => value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('\n', '\\n');+ const lines: string[] = [];+ const series: Array<[string, string, (row: CapacitySnapshot['rows'][number]) => number | null]> = [+ ['used', 'Cumulative managed-write use (request ids or reserved receipt bytes).', row => row.used],+ ['limit', 'The configured cumulative cap.', row => row.limit],+ ['days_to_exhaustion', 'Days until admission refuses at the 7-day rate (absent when the rate is zero or beyond ten years).', row => row.days_to_exhaustion],+ ];+ for (const [name, help, value] of series) {+ lines.push(`# HELP gbrain_write_capacity_${name} ${help}`, `# TYPE gbrain_write_capacity_${name} gauge`);+ for (const row of snapshot.rows) {+ const v = value(row);+ if (v !== null) lines.push(`gbrain_write_capacity_${name}{scope="${label(row.scope)}",resource="${row.resource}"} ${v}`);+ }+ lines.push('');+ }+ return lines.join('\n');+}+export function renderPrometheusMetrics(counters: MetricsCounters,now: number = Date.now(),@@ -367,7 +392,8 @@ export function mountMetrics(app: Express, ctx: ServeHttpContext): void {// is not a public surface (the original PR served it unauthenticated).app.get('/metrics', requireAdmin, async (_req: Request, res: Response) => {const summary = await cachedTerminalSummary(ctx.engine);+ const capacity = await cachedCapacitySnapshot(ctx.engine);res.set('Content-Type', 'text/plain; version=0.0.4');- res.send(renderPrometheusMetrics(metricsCounters) + renderTerminalFailureMetrics(summary));+ res.send(renderPrometheusMetrics(metricsCounters) + renderTerminalFailureMetrics(summary) + renderCapacityMetrics(capacity));});}diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.tsindex bb7e7692bc..2afe131647 100644--- a/src/commands/sync/operator.ts+++ b/src/commands/sync/operator.ts@@ -82,7 +82,13 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promisconst sourceId = sourceOf(args);const status = await readSyncStatus(engine, sourceId);const ctx = cliRenderContext();- const rendered = { ...status, holds: status.holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })), next: status.next ? renderAction(status.next, ctx) : null };+ // #6696 (A4): the capacity picture rides every status read (unthrottled), from the 60 s snapshot.+ const { cachedCapacitySnapshot, capacityNotices } = await import('../../core/persistence/capacity-snapshot.ts');+ const { renderNotice } = await import('../../core/agent-output.ts');+ const snapshot = await cachedCapacitySnapshot(engine);+ const notices = (await capacityNotices(engine, { throttle: false })).map(notice => renderNotice(notice, ctx));+ const rendered = { ...status, holds: status.holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })), next: status.next ? renderAction(status.next, ctx) : null,+ capacity: { status: snapshot.status, pause_pct: snapshot.pause_pct, low: snapshot.low, paused: snapshot.paused }, ...(notices.length ? { notices } : {}) };if (args.includes('--json')) return writeJsonDocument(JSON.stringify(rendered, null, 2));const c = status.cursor;console.log(`Source ${sourceId}: ${c ? c.done ? `last run finished at ${c.index}/${c.total} (pinned ${c.pinned_target?.slice(0, 8) ?? '?'})` : `cursor ${c.index}/${c.total} at pinned target ${c.pinned_target?.slice(0, 8) ?? '?'}`@@ -100,6 +106,7 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promisfor (const b of t.active_blockers) console.log(` BLOCKING ${b.kind}: request ${b.request_id}${b.slug ? ` (${b.slug})` : ''} [${b.category}]`);if (t.active_blockers.length || t.unresolved.rows) console.log(` drill down: ${t.drill_down.join(' ')}`);}+ for (const notice of notices) console.log(` [gbrain notice ${notice.code}] ${notice.why}`);if (rendered.next) console.log(` Next: ${rendered.next.command ?? rendered.next.argv?.join(' ')}\n Why: ${rendered.next.why}`);else console.log(' Next: nothing; the source is synced and holds nothing.');}diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex 1da04b3652..638ef21d7b 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -57,6 +57,18 @@ type PerSourceResult = {localPath?: string;};+/**+ * #6696 (A4): a sync receipt carries the capacity notices (60 s snapshot, at most once an hour per process per+ * scope): under `--json` as rendered `notices`, otherwise as stderr lines.+ */+async function syncCapacityNotices(engine: BrainEngine, json: boolean): Promise<{ notices?: unknown[] }> {+ const { capacityNotices } = await import('../../core/persistence/capacity-snapshot.ts');+ const { cliRenderContext, renderNotice } = await import('../../core/agent-output.ts');+ const notices = (await capacityNotices(engine).catch(() => [])).map(notice => renderNotice(notice, cliRenderContext()));+ if (!json) for (const notice of notices) process.stderr.write(`[gbrain notice ${notice.code}] ${notice.why}\n`);+ return notices.length ? { notices } : {};+}+export async function runSyncInner(engine: BrainEngine, args: string[]) {// v0.40 Federated Sync v2: `gbrain sync trigger` subcommand// Routes to runSyncTrigger which queues a 'sync' minion job with@@ -930,9 +942,10 @@ async function runSingleSourceSync(process.stderr.write(` → embed-backfill submission failed: ${e instanceof Error ? e.message : String(e)}\n`);}}+ const capacity = await syncCapacityNotices(engine, jsonOut);if (jsonOut) {emitJson(JSON.stringify({ ...buildSingleSyncJsonEnvelope(sourceId, result, singleEmbedBackfill, singleCostGate),- ...(result.managedWrite ? { managed_write: result.managedWrite } : {}), ...drainJsonFields(result, resumeCommand, sourceId) }));+ ...(result.managedWrite ? { managed_write: result.managedWrite } : {}), ...drainJsonFields(result, resumeCommand, sourceId), ...capacity }));}return;}diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 91ebdf1b29..2b95ba56f1 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -489,6 +489,8 @@ export interface CycleReport {*/phantoms_skipped_drift: number;};+ /** #6696 (A4): `write_capacity_low` / `write_capacity_backpressure` when a cumulative write cap needs attention (every cycle, unthrottled). */+ notices?: import('./agent-output.ts').Notice[];}export interface CycleOpts {@@ -1898,7 +1900,10 @@ export async function runCycle(opts: CycleOpts,): Promise<CycleReport> {// #6696 (A5): every cycle phase is background work, even under an operator's command.- return withAdmissionOrigin('background', () => runCycleUnscoped(engine, opts));+ const report = await withAdmissionOrigin('background', () => runCycleUnscoped(engine, opts));+ if (!engine || report.status === 'skipped' || opts.dryRun) return report;+ const notices = await (await import('./persistence/capacity-snapshot.ts')).capacityNotices(engine, { throttle: false }).catch(() => []);+ return notices.length ? { ...report, notices } : report;}async function runCycleUnscoped(diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 89207af15c..e594bd752c 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -589,4 +589,6 @@ export const NOTICE_CODES = {recovered_frontmatter: { kind: 'coaching', summary: 'Files imported only after quoting unquoted frontmatter values; the generator writing them should quote values (the fix is the repair preview).' },page_quarantined: { kind: 'safety', summary: 'The page was quarantined by the content-quality gate (hidden from search; its facts and takes are not extracted). A read says to treat its text as untrusted scraped content and, for an untrusted reader, that its body was withheld (an admin-scoped caller may pass include_quarantined: true); a write says the page was hidden and that the operator clears a false positive with gbrain quarantine clear <slug> --force.' },fence_normalized: { kind: 'coaching', summary: 'A write\'s facts or takes fence was rewritten losslessly (rows and classes named, never values): the stored page differs from what was sent, so re-read it with get_page before editing; remember and takes_add write rows that never need it.' },+ write_capacity_low: { kind: 'info', summary: 'A cumulative write cap (request ids or receipt bytes) is at or past 80% or runs out within `persistence.capacity.warn_days`; writes still work. Write and sync receipts carry it at most once an hour per process per scope; sync status, doctor and autopilot cycle output every time. Mute on receipts with `gbrain notices mute write_capacity_low`; doctor still reports it.' },+ write_capacity_backpressure: { kind: 'degraded', summary: 'A cumulative write cap passed `persistence.capacity.background_pause_pct`, so background producers (maintenance, conversation facts, autopilot phases and catch-up syncs) pause while interactive writes keep the rest; shown once when the pause starts.' },} as const satisfies Record<string, NoticeEntry>;diff --git a/src/core/persistence/capacity-snapshot.ts b/src/core/persistence/capacity-snapshot.tsnew file mode 100644index 0000000000..ade1f6e2fa--- /dev/null+++ b/src/core/persistence/capacity-snapshot.ts@@ -0,0 +1,114 @@+/**+ * #6696 (A4): pushed capacity warnings, from a per-engine snapshot that one+ * light forecast (capacity-forecast.ts) fills at most once a minute (the+ * #6650 `cachedTerminalSummary` pattern); a write never computes a forecast.+ *+ * `write_capacity_low` (notice kind `info`, so `gbrain notices mute+ * write_capacity_low` mutes it on receipts) names every cumulative cap at or+ * past 80% or out within `persistence.capacity.warn_days`. Write and sync+ * receipts carry it at most once an hour per process per scope and resource;+ * `gbrain sync status`, doctor and autopilot cycle output carry it every time.+ * `write_capacity_backpressure` (kind `degraded`, never muted) fires once+ * when a scope passes the background pause line (A5), again only after it+ * clears and passes it anew.+ */+import type { Notice } from '../agent-output.ts';+import type { SqlEngine } from './model.ts';+import { BACKGROUND_PRODUCERS, readBackgroundPauseShare } from './admission-origin.ts';+import { readCapacityForecast } from './capacity-forecast.ts';++export const CAPACITY_SNAPSHOT_TTL_MS = 60_000;+export const CAPACITY_NOTICE_INTERVAL_MS = 60 * 60_000;++export interface CapacityAttention {+ scope: string; resource: 'lifetime_ids' | 'terminal_bytes'; used: number; limit: number; pct: number;+ days_to_exhaustion: number | null; config_key: string; recommended_limit: number; command: string;+}+export interface CapacitySnapshot {+ /** Every cumulative cap of every scope (the /metrics gauges). */+ rows: CapacityAttention[];+ /** Caps at or past the warn percentage or out within the warn days. */+ low: CapacityAttention[];+ /** Caps past the background pause line: background producers refuse there. */+ paused: CapacityAttention[];+ pause_pct: number;+ status: 'ok' | 'unknown';+}++const snapshots = new WeakMap<object, { at: number; value: Promise<CapacitySnapshot> }>();+const lowShownAt = new Map<string, number>();+const pausedShown = new Set<string>();++/** The snapshot for `engine`, shared by every caller within CAPACITY_SNAPSHOT_TTL_MS (in flight included); a failed read is cached as `unknown`. */+export function cachedCapacitySnapshot(engine: SqlEngine, now: number = Date.now()): Promise<CapacitySnapshot> {+ const hit = snapshots.get(engine);+ if (hit && now - hit.at < CAPACITY_SNAPSHOT_TTL_MS) return hit.value;+ const value = Promise.all([readCapacityForecast(engine, { light: true }), readBackgroundPauseShare(engine)]).then(([forecast, share]): CapacitySnapshot => {+ const attention = (row: typeof forecast.rows[number]): CapacityAttention => ({ scope: row.scope, resource: row.resource, used: row.used, limit: row.limit,+ pct: row.pct, days_to_exhaustion: row.days_to_exhaustion, config_key: row.config_key, recommended_limit: row.recommended_limit,+ command: `gbrain config set ${row.config_key} ${row.recommended_limit}` });+ return { rows: forecast.rows.map(attention), low: forecast.rows.filter(row => row.status !== 'ok').map(attention),+ paused: forecast.rows.filter(row => row.used >= Math.floor(row.limit * share)).map(attention), pause_pct: Math.round(share * 100), status: 'ok' };+ }).catch((): CapacitySnapshot => ({ rows: [], low: [], paused: [], pause_pct: 0, status: 'unknown' }));+ snapshots.set(engine, { at: now, value });+ return value;+}++const key = (row: CapacityAttention) => `${row.scope}|${row.resource}`;+const describe = (row: CapacityAttention) => `${row.scope} ${row.resource} ${row.used}/${row.limit} (${row.pct}%`+ + `${row.days_to_exhaustion !== null ? `, about ${row.days_to_exhaustion} day(s) left` : ''})`;+const VERIFY = { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'] };++function lowNotice(rows: CapacityAttention[]): Notice {+ const [first] = rows;+ return { code: 'write_capacity_low', kind: 'info',+ why: `Write capacity is running low: ${rows.map(describe).join('; ')}. Writes still work; admission refuses at the cap. `+ + `The brain host raises it with ${rows.map(row => row.command).join('; ')} (each covers about one more year; reversible).`,+ fix: { argv: ['gbrain', 'config', 'set', first!.config_key, String(first!.recommended_limit)], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: 'Raises the cap that runs out first to a value that covers about one more year; undo with gbrain config unset.', verify: VERIFY,+ docs: 'docs/guides/concurrent-writes.md#quota-near-exhaustion' } };+}++function pausedNotice(rows: CapacityAttention[], pausePct: number): Notice {+ const [first] = rows;+ return { code: 'write_capacity_backpressure', kind: 'degraded',+ why: `Background writes are paused: ${rows.map(describe).join('; ')} passed the ${pausePct}% pause line (persistence.capacity.background_pause_pct). `+ + `Paused: ${BACKGROUND_PRODUCERS.join(', ')}. Interactive writes keep the rest of the cap.`,+ fix: { argv: ['gbrain', 'config', 'set', first!.config_key, String(first!.recommended_limit)], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: 'Moves the pause line by raising the cap; request ids never free, receipt bytes free as receipts compact.', verify: VERIFY,+ docs: 'docs/guides/write-refusals.md#write_capacity_backpressure' } };+}++/**+ * The capacity notices one output carries. `throttle` (write and sync+ * receipts) shows `write_capacity_low` at most once an hour per process per+ * scope and resource; unthrottled (sync status, doctor, cycle output) shows it+ * whenever a cap needs attention. The pause notice fires on each transition+ * into the pause, in either mode. `scopes` limits both to the scopes a+ * caller may see (a remote client: the brain and its own principal).+ */+export async function capacityNotices(engine: SqlEngine, opts: { throttle: boolean; now?: number; scopes?: string[] } = { throttle: true }): Promise<Notice[]> {+ const now = opts.now ?? Date.now();+ const snapshot = await cachedCapacitySnapshot(engine, now);+ const visible = (row: CapacityAttention) => !opts.scopes || opts.scopes.includes(row.scope);+ const notices: Notice[] = [];+ const candidates = snapshot.low.filter(visible);+ const low = opts.throttle ? candidates.filter(row => now - (lowShownAt.get(key(row)) ?? -Infinity) >= CAPACITY_NOTICE_INTERVAL_MS) : candidates;+ if (low.length) {+ if (opts.throttle) for (const row of low) lowShownAt.set(key(row), now);+ notices.push(lowNotice(low));+ }+ const pausedNow = new Set(snapshot.paused.map(key));+ for (const shown of pausedShown) if (!pausedNow.has(shown)) pausedShown.delete(shown);+ const started = snapshot.paused.filter(row => visible(row) && !pausedShown.has(key(row)));+ if (started.length) {+ for (const row of started) pausedShown.add(key(row));+ notices.push(pausedNotice(started, snapshot.pause_pct));+ }+ return notices;+}++export function __resetCapacityNoticesForTests(): void {+ lowShownAt.clear();+ pausedShown.clear();+}diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex efa6b9478b..28193836b9 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -6,6 +6,8 @@* + missing-context bugs; this module exists to prevent that recurring.*/+import { capacityNotices } from '../core/persistence/capacity-snapshot.ts';+import { principalKey } from '../core/persistence/model.ts';import { affectsRecall } from '../core/types.ts';import type { BrainEngine } from '../core/engine.ts';import { operations, OperationError, enforceBoundClientOpAllowList, opError } from '../core/operations.ts';@@ -1060,6 +1062,9 @@ export async function dispatchToolCall(: await op.handler(ctx, safeParams);// Hot memory built before a write (forget, remember, …) is never served after it, on every transport.if (op.mutating) invalidateHotMemoryForEngine(engine);+ // #6696 (A4): a write's receipt carries the capacity notices, from the 60 s snapshot and at most once an hour per scope.+ if (op.mutating) notices.push(...await capacityNotices(engine, { throttle: true,+ scopes: ctx.remote === false ? undefined : ['brain', ...(ctx.auth?.principal ? [principalKey(ctx.auth.principal)] : [])] }).catch(() => []));// [E4] verb success metrics: budget drops + entity hit/miss when present.{const r = result as { dropped_count?: number; found?: boolean; status?: string } | null;diff --git a/test/persistence-capacity-notices.test.ts b/test/persistence-capacity-notices.test.tsnew file mode 100644index 0000000000..4b7a987411--- /dev/null+++ b/test/persistence-capacity-notices.test.ts@@ -0,0 +1,119 @@+/**+ * #6696 (A4): pushed capacity warnings read a per-engine snapshot (at most+ * one light forecast a minute); `write_capacity_low` fires at 80% or under the+ * warn days, at most once an hour per process per scope on receipts and every+ * time unthrottled; the pause notice fires when a scope passes the background+ * pause line and again only after it clears. Both backends.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { __resetCapacityNoticesForTests, cachedCapacitySnapshot, CAPACITY_NOTICE_INTERVAL_MS, CAPACITY_SNAPSHOT_TTL_MS,+ capacityNotices } from '../src/core/persistence/capacity-snapshot.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { renderCapacityMetrics } from '../src/commands/serve-http-metrics.ts';+import { NOTICE_CODES } from '../src/core/error-registry.ts';+import { freshBrainFactory, requestFixture } from './helpers/persistence-request-fixture.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const databaseUrl = process.env.DATABASE_URL;+const setIds = (engine: BrainEngine, used: number) => engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw("UPDATE persistence_counters SET lifetime_ids=$1 WHERE key LIKE 'principal:%'", [used]);+});+const codes = (notices: Array<{ code: string }>) => notices.map(n => n.code);++test('the notice kinds follow the mute convention: low is muteable info, the pause is degraded', () => {+ expect(NOTICE_CODES.write_capacity_low.kind).toBe('info');+ expect(NOTICE_CODES.write_capacity_backpressure.kind).toBe('degraded');+});++for (const kind of testBackends()) {+ describe(`capacity notices ${kind}`, () => {+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;+ let scratch: string;+ beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), 'gbrain-capacity-notices-'));+ factory = await freshBrainFactory(kind, databaseUrl);+ }, 120_000);+ afterAll(async () => {+ await factory?.dispose();+ if (scratch) rmSync(scratch, { recursive: true, force: true });+ });+ beforeEach(() => __resetCapacityNoticesForTests());+ const check = (name: string, fn: (engine: BrainEngine) => Promise<void>) => test(name, async () => {+ const engine = await factory.fresh();+ await withEnv({ GBRAIN_HOME: scratch, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, () => fn(engine));+ }, 120_000);++ check('a fresh brain carries no capacity notice', async engine => {+ await requestFixture(engine).then(r => r.admit('one'));+ expect(await capacityNotices(engine, { throttle: false })).toEqual([]);+ });++ check('at 80% the receipt notice shows once an hour per scope; unthrottled outputs show it every time', async engine => {+ await requestFixture(engine).then(r => r.admit('one'));+ await engine.setConfig('persistence.limits.principal_lifetime_ids', '1000');+ await engine.setConfig('persistence.capacity.background_pause_pct', '1');+ await setIds(engine, 810);+ const t0 = Date.now() + 100 * CAPACITY_SNAPSHOT_TTL_MS; // past any snapshot an earlier case left on a reused engine+ const first = await capacityNotices(engine, { throttle: true, now: t0 });+ expect(codes(first)).toEqual(['write_capacity_low']);+ expect(first[0]).toMatchObject({ kind: 'info', fix: { actor: 'host_admin', argv: ['gbrain', 'config', 'set', 'persistence.limits.principal_lifetime_ids', expect.stringMatching(/^\d+$/)] } });+ expect(first[0]!.why).toContain('81%');+ expect(await capacityNotices(engine, { throttle: true, now: t0 + 1000 })).toEqual([]);+ expect(codes(await capacityNotices(engine, { throttle: false, now: t0 + 1000 }))).toEqual(['write_capacity_low']);+ expect(codes(await capacityNotices(engine, { throttle: true, now: t0 + CAPACITY_NOTICE_INTERVAL_MS }))).toEqual(['write_capacity_low']);+ });++ check('the pause notice fires when the pause starts, and again only after it clears', async engine => {+ await requestFixture(engine).then(r => r.admit('one'));+ await engine.setConfig('persistence.limits.principal_lifetime_ids', '1000');+ await engine.setConfig('persistence.capacity.warn_days', '0'); await engine.setConfig('persistence.capacity.fail_days', '0');+ let now = 2_000_000_000_000;+ const step = () => (now += CAPACITY_SNAPSHOT_TTL_MS);+ await setIds(engine, 500);+ expect(await capacityNotices(engine, { throttle: true, now: step() })).toEqual([]);+ await setIds(engine, 820);+ const started = await capacityNotices(engine, { throttle: true, now: step() });+ expect(codes(started)).toEqual(['write_capacity_low', 'write_capacity_backpressure']);+ expect(started[1]).toMatchObject({ kind: 'degraded' });+ expect(started[1]!.why).toContain('80% pause line');+ expect(codes(await capacityNotices(engine, { throttle: false, now: step() }))).toEqual(['write_capacity_low']);+ await setIds(engine, 500);+ expect(await capacityNotices(engine, { throttle: false, now: step() })).toEqual([]);+ await setIds(engine, 820);+ expect(codes(await capacityNotices(engine, { throttle: false, now: step() }))).toContain('write_capacity_backpressure');+ });++ check('a remote caller sees only the brain and its own principal, and a hidden scope is not marked shown', async engine => {+ await requestFixture(engine).then(r => r.admit('one'));+ await engine.setConfig('persistence.limits.principal_lifetime_ids', '1000');+ await setIds(engine, 900);+ const now = 2_500_000_000_000; // between the cases around it, so neither reads the other's snapshot+ expect(await capacityNotices(engine, { throttle: true, now, scopes: ['brain', 'principal:oauth_client:other-example'] })).toEqual([]);+ const own = await capacityNotices(engine, { throttle: true, now });+ expect(codes(own)).toEqual(['write_capacity_low', 'write_capacity_backpressure']);+ expect(own[0]!.why).toMatch(/principal:local_cli:/);+ });++ check('writes within a minute share one snapshot; the next minute reads again', async engine => {+ await requestFixture(engine).then(r => r.admit('one'));+ await engine.setConfig('persistence.limits.principal_lifetime_ids', '1000');+ const t0 = 3_000_000_000_000;+ const before = await cachedCapacitySnapshot(engine, t0);+ expect(before.low).toEqual([]);+ await setIds(engine, 900);+ expect(await cachedCapacitySnapshot(engine, t0 + CAPACITY_SNAPSHOT_TTL_MS - 1)).toBe(before);+ const after = await cachedCapacitySnapshot(engine, t0 + CAPACITY_SNAPSHOT_TTL_MS);+ expect(after.low.map(row => row.resource)).toEqual(['lifetime_ids']);+ const metrics = renderCapacityMetrics(after);+ expect(metrics).toContain('# TYPE gbrain_write_capacity_used gauge');+ expect(metrics).toMatch(/gbrain_write_capacity_used\{scope="principal:[^"]+",resource="lifetime_ids"\} 900/);+ expect(metrics).toMatch(/gbrain_write_capacity_limit\{scope="principal:[^"]+",resource="lifetime_ids"\} 1000/);+ });+ });+}