Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): write_quota_exhausted at the cumulative wall, background pause near it (#6696 A6, A5)
garrytan82ca63ba60c8
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 5c145491d9..97f149f8e5 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3269,6 +3269,26 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-cMore: [docs/guides/write-refusals.md#worktree_dirty](../../docs/guides/write-refusals.md#worktree_dirty)+### write_capacity_backpressure++<a id="write_capacity_backpressure"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A background producer (maintenance, conversation facts, an autopilot phase or an autopilot catch-up sync) stopped admitting writes because a cumulative write cap is past `persistence.capacity.background_pause_pct` (0.8); interactive writes keep the rest. Nothing was submitted and no receipt was written. | Near a cumulative cap the remaining request ids and receipt bytes are kept for the user's own writes (remember, put_page, edit_page, operator sync, approved repair). Request ids are never freed, so past the line on ids only the brain host's config raise resumes background work; receipt bytes also free as receipts compact. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. Run: gbrain doctor --only persistence_capacity --json | agent | `gbrain doctor --json` | 12 | no |++More: [docs/guides/write-refusals.md#write_capacity_backpressure](../../docs/guides/write-refusals.md#write_capacity_backpressure)++### write_capacity_low++<a id="write_capacity_low"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A cumulative write cap is at or past 80% or runs out within `persistence.capacity.warn_days` (30) days at its 7-day rate; writes still work. | Request ids are permanent and receipt bytes free only as receipts compact, so the cap is raised before admission refuses. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. Run: gbrain doctor --only persistence_capacity --json | agent | `gbrain doctor --json` | 1 | no |++More: [docs/guides/write-refusals.md#write_capacity_low](../../docs/guides/write-refusals.md#write_capacity_low)+### write_claim_lost<a id="write_claim_lost"></a>@@ -3315,6 +3335,30 @@ More: [docs/guides/write-refusals.md#write_outcome_unknown](../../docs/guides/wr|---|---|---|---|---|---|---|| The write was accepted and is still pending; it may commit later. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 10 | yes |+### write_quota_exhausted++<a id="write_quota_exhausted"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A cumulative write cap (permanent request ids or reserved receipt bytes, for the principal or the brain) is full, so the write was not admitted and nothing changed. | Request ids are permanent replay protection and a receipt keeps its bytes until it compacts, so waiting does not free the cap; the brain host raises it with gbrain config set (reversible). | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. Run: gbrain doctor --only persistence_capacity --json | agent | `gbrain doctor --json` | 12 | no |++Reasons: `lifetime_ids`, `terminal_bytes`.++More: [docs/guides/write-refusals.md#write_quota_exhausted](../../docs/guides/write-refusals.md#write_quota_exhausted)++### write_quota_insufficient++<a id="write_quota_insufficient"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A bulk run (managed sync catch-up, reclone or a repair) estimated more new receipts than the remaining write capacity allows before its producer's pause line, so it did not start; other writes still work. | Starting a run that the cap would stop part way leaves a long tail of pending pages; the preflight refuses up front with the config raise that covers the run. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. Run: gbrain doctor --only persistence_capacity --json | agent | `gbrain doctor --json` | 12 | no |++Reasons: `lifetime_ids`, `terminal_bytes`.++More: [docs/guides/write-refusals.md#write_quota_insufficient](../../docs/guides/write-refusals.md#write_quota_insufficient)+### writer_admin_intent_required<a id="writer_admin_intent_required"></a>diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex 40f390debb..5eb106888d 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -106,6 +106,7 @@ Every hold and error has three fields, from one table| `connection_lost` | connection | retry | no | three reruns in a row end connection_lost (the database is unreachable from this host) || `database_contention` | connection | retry | no | three reruns in a row stop on it || `write_capacity` | connection | retry | no | writer status shows the cap held by requests that never settle |+| `write_capacity_backpressure` | connection | retry | no | reason lifetime_ids (request ids never free, so only the host raise lifts it), or the pause outlasts a day || `storage_error` | connection | retry | no | the same error after a rerun (then it is not a dropped connection) || `graduation_in_progress` | connection | retry | no | gbrain migrate --status --json reports no running move and the fence still refuses || `preparation_systemic` | systemic | upgrade, retry | yes | always |@@ -114,6 +115,8 @@ Every hold and error has three fields, from one table| `owner_unavailable` | systemic | none | yes | always || `writer_coordinator_required` | systemic | none | yes | always || `permission_denied` | systemic | none | yes | always |+| `write_quota_exhausted` | systemic | none | yes | always |+| `write_quota_insufficient` | systemic | none | yes | always || `plan_stale` | systemic | none | yes | always || `invalid_params` | systemic | none | yes | always || `cursor_incarnation_retired` | systemic | repair | no | the repair preview lists nothing to retire, or the same code returns after the apply |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex b92e854ea5..8af2af794a 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -87,6 +87,10 @@ of making a duplicate.| <a id="fence_unrenderable"></a>`fence_unrenderable` | `fence_unrenderable` | A legacy fact row (an active `facts` row with no fence row number) was not adopted into its page's `## Facts` fence because the fence codec reads the rendered row back as something other than the stored fact: a whitespace-only claim comes back empty, `~~x~~` comes back struck, a literal `<br>` comes back as a line break, or another column changes. Surrounding whitespace and CRLF line endings are the one accepted difference: such a row is adopted and `facts.fact` takes the fence's text. A second legacy row whose normalized claim, source and visibility the page already carries is left too (`duplicate_claim`; a private and a world row with one text are two facts and both adopt). The cycle and the v0.32.2 migration print `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)`; doctor `fence_integrity` lists the pages, fact ids and reason classes under `unrenderable_legacy_facts` (never the claim text). The same code refuses a planned adoption whose rendered fence does not read back as its facts; that is a gbrain planning defect, not caller input. The planner runs the publisher's own read-back check on the whole rendered fence first, so such a page is reported as unadoptable (class `whole_fence`) instead of being submitted. A managed adoption refused in the last day is not resubmitted: the cycle reports it as class `prior_refusal` with the refused request id (`gbrain write-request -- <id>` reads it), and a direct `submitFactFenceAdoption` call refuses with `The same fact-fence adoption was already refused.`. It is retried a day after the refusal, or at once by a build whose adoption planner revision changed. Unadopted rows hold only their own page: the phantom-redirect pass skips a phantom that owns one and redirects the others. To count what an older build left in the writer table, run the read-only `scripts/diagnose/fence-adoption-census.sql` on the brain host against the brain's Postgres database (its header shows the `psql` command). | Nothing to fix in the page: the rows stay active and searchable, nothing is lost, and their pages skip destructive fact reconciliation until the rows are adopted. Report the pages and reason classes with the gbrain version. Never `forget_fact` a row to clear the count. || <a id="reconcile-private-facts"></a>reconcile private facts | `permission_denied` | `gbrain sources reconcile --apply` (and its preview) found a `## Facts` row that would edit, renumber or change the visibility of a stored private fact, copy a stored private claim into a row under another visibility, or copy a stored private row's context (24 characters or longer) verbatim into a world row. A row is identified by its row number and claim, so a world row that only shares a private row's claim is not a private row and publishes. The refusal names the row number, never its text. It guards against verbatim copies only; reworded text is not detected, so it is not a confidentiality proof. Sources are not compared, because rows share provenance such as "Slack import". Nothing was written. | Read the stored page with the printed `gbrain get --source <id> -- <slug>`, keep the named row as stored in the file (or remove the copied text), then run a fresh `gbrain sources reconcile <id> <slug> --preview` and apply it. Change private facts with `remember` and `forget`. || <a id="maintenance_backpressure"></a>`maintenance_backpressure` (exit 12) | `maintenance_backpressure` | A managed maintenance run (`gbrain extract-conversation-facts`, its cycle phase or job) publishes each page as its own request, under the same local CLI writer your own CLI writes use. Before the run it counts the requests the whole run plans; before each page's model work it checks again. It stops admitting once the writer's outstanding requests, reserved receipt bytes (`persistence.limits.principal_terminal_bytes`; each request reserves 16 KiB until its receipt compacts after the retention window) or permanent request ids (`persistence.limits.principal_lifetime_ids`; never freed) would pass 80% of their limit, so the last 20% stays free for your other writes. The message names the resource. Pages already published keep their facts and nothing is half-written. | Outstanding requests: read them with `gbrain sources writer status --source <id> --json`; a resident `gbrain serve`, or the next CLI run, publishes them, then rerun the same command. Receipt bytes or request ids: run the smaller batch the message prints (`gbrain extract-conversation-facts --source-id <id> --limit <n>`), or wait for receipts to compact; raising the named `persistence.limits.*` key is the user's call. |+| <a id="write_quota_exhausted"></a>`write_quota_exhausted` (exit 12) | `write_quota_exhausted` | A cumulative write cap is full: permanent request ids (`persistence.limits.principal_lifetime_ids` or `brain_lifetime_ids`, `reason: lifetime_ids`) or reserved receipt bytes (`principal_terminal_bytes` or `brain_terminal_bytes`, `reason: terminal_bytes`). `detail` names the limit key. Waiting does not help: ids are permanent and receipt bytes free only as receipts compact. Nothing changed. | Run the `fix` on the brain host: `gbrain config set <key> <value>` (the value covers about one more year at the current rate; undo with `gbrain config unset <key>`), then retry with the same `request_id`. For receipt bytes with reclaimable slack, `gbrain repair receipt-compaction` second previews the retained bytes compaction would free (ids: only the raise helps). Verify with `gbrain doctor --only persistence_capacity --json`. [Runbook](concurrent-writes.md#quota-near-exhaustion). |+| <a id="write_quota_insufficient"></a>`write_quota_insufficient` (exit 12) | `write_quota_insufficient` | A bulk run (a managed sync catch-up, a reclone, a repair) estimated from its manifest more new receipts (ids and 16 KiB reservations) than the capacity left before its producer's pause line, so it did not start. Other writes still work. | Run the `gbrain config set <key> <value>` the message prints on the brain host, then rerun the same command. Verify with `gbrain doctor --only persistence_capacity --json`. |+| <a id="write_capacity_low"></a>`write_capacity_low` (notice) | `write_capacity_low` | Not a refusal: a `[gbrain notice]` on write receipts, `sync` receipts, `gbrain sync status` and autopilot cycle output when a cumulative cap is at or past 80% or would run out within `persistence.capacity.warn_days` (30) days at its 7-day rate. Receipts carry it at most once an hour per process and scope; `sync status` and doctor carry it every time. The structured `capacity` object names the scope, resource, days left and the config command. | Follow the [runbook](concurrent-writes.md#quota-near-exhaustion): raise the cap it names with the printed `gbrain config set`, then verify with `gbrain doctor --only persistence_capacity --json`. |+| <a id="write_capacity_backpressure"></a>`write_capacity_backpressure` (exit 12) | `write_capacity_backpressure` | A background producer (managed maintenance, conversation facts, an autopilot cycle phase, an autopilot catch-up sync) stopped admitting because a cumulative cap of its writer or the brain is past `persistence.capacity.background_pause_pct` (default 0.8). Interactive writes (`remember`, `put_page`, `edit_page`, an operator's `gbrain sync`, an approved `gbrain repair`) keep the remainder. No receipt was written. `reason` names the resource. Doctor `persistence_capacity` names the paused producers. | Depends on `reason`. `lifetime_ids`: ids are never freed, so only the brain host's `gbrain config set <key> <value>` from the `fix` resumes background work; waiting does not. `terminal_bytes`: the same reversible raise resumes it at once, or it resumes by itself as retained receipts compact. Verify with `gbrain doctor --only persistence_capacity --json`. |### Other error codesdiff --git a/src/cli/commands/sync.ts b/src/cli/commands/sync.tsindex 26adc1d328..2f299ce46e 100644--- a/src/cli/commands/sync.ts+++ b/src/cli/commands/sync.ts@@ -13,11 +13,13 @@ import type { BrainEngine } from '../../core/engine.ts';import { OperationError, opError } from '../../core/ops/contract.ts';import { setCliExitVerdict } from '../../core/cli-force-exit.ts';import { writeCliError } from '../cli-error.ts';+import { withAdmissionOrigin } from '../../core/persistence/admission-origin.ts';export async function run(engine: BrainEngine, args: string[]): Promise<void> {const { runSync, SyncLockBusyError } = await import('../../commands/sync.ts');try {- await runSync(engine, args);+ // #6696 (A5): an operator's sync is interactive; autopilot's sync jobs run outside this command, as background.+ await withAdmissionOrigin('interactive', () => runSync(engine, args));} catch (err) {// D1/D2: a busy sync lock is a retryable sync_in_progress refusal (its// message names the holder and the --break-lock recovery), not andiff --git a/src/cli/main.ts b/src/cli/main.tsindex 48e61b67cc..cde338e12f 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -1515,6 +1515,7 @@ export async function makeContext(engine: BrainEngine, params: Record<string, un// Local CLI invocation — the user owns the machine; do not apply remote-caller// confinement (e.g., cwd-locked file_upload).remote: false,+ admissionOrigin: 'interactive', // #6696 (A5): the user's own CLI writescliOpts: getCliOptions(),writeWaitMs: currentCliWriteWait().waitMs, // #5232// v0.34 D4: sourceId is REQUIRED at the type level. Fall back to 'default'diff --git a/src/commands/doctor/checks/persistence-capacity.ts b/src/commands/doctor/checks/persistence-capacity.tsindex 141f489e79..52ad65369e 100644--- a/src/commands/doctor/checks/persistence-capacity.ts+++ b/src/commands/doctor/checks/persistence-capacity.ts@@ -4,6 +4,7 @@ import { capacityDiagnostics } from '../../../core/persistence/diagnostics.ts';import { oneYearCapacity, readJournalLimits } from '../../../core/persistence/limits.ts';import { readCapacityForecast, type CapacityForecast } from '../../../core/persistence/capacity-forecast.ts';import { doctorVerify } from '../check-fix.ts';+import { BACKGROUND_PRODUCERS, readBackgroundPauseShare } from '../../../core/persistence/admission-origin.ts';const VERIFY = 'gbrain doctor --only persistence_capacity --json';const DOCS = 'docs/guides/concurrent-writes.md#quota-near-exhaustion';@@ -15,6 +16,7 @@ const DOCS = 'docs/guides/concurrent-writes.md#quota-near-exhaustion';* failure at 95% or within `persistence.capacity.fail_days` (7). The rate is* the full 7-day aggregate (capacity-forecast.ts); receipt bytes forecast at* their compacted (net) size. Each key gets the one value that covers a year.+ * A scope past the background pause line (A5) names the producers it pauses.*/export async function checkPersistenceCapacity(engine: BrainEngine): Promise<Check> {try {@@ -23,27 +25,32 @@ export async function checkPersistenceCapacity(engine: BrainEngine): Promise<Cheterminal_bytes::text,recovery_bytes::text FROM persistence_counters WHERE key='brain' OR key LIKE 'principal:%' ORDER BY key`);const limits = await readJournalLimits(engine);const forecast: CapacityForecast | null = await readCapacityForecast(engine, { limits }).catch(() => null);+ const pause = await readBackgroundPauseShare(engine);const cumulative = capacityDiagnostics(counters, limits).filter(row => row.resource === 'lifetime_ids' || row.resource === 'terminal_bytes');const resources = [];const needed = new Map<string, number>();let worst: 'ok' | 'warn' | 'fail' = 'ok';for (const row of cumulative) {const predicted = forecast?.rows.find(f => f.scope === row.scope && f.resource === row.resource);- const status = predicted?.status ?? (row.approaching_capacity ? 'warn' : 'ok');+ const paused = row.used >= Math.floor(row.limit * pause);+ const predictedStatus = predicted?.status ?? (row.approaching_capacity ? 'warn' : 'ok');+ const status = paused && predictedStatus === 'ok' ? 'warn' : predictedStatus;if (status === 'ok') continue;if (status === 'fail' || worst === 'ok') worst = status;// No admission inside the window: the latest admissions, however old, size the year instead.const value = predicted && predicted.per_day_7d > 0 ? predicted.recommended_limit: await oneYearCapacity(engine, row.scope, row.resource === 'lifetime_ids' ? 'LifetimeIds' : 'TerminalBytes', row.used, row.limit);- resources.push({ scope: row.scope, resource: row.resource, used: row.used, limit: row.limit, config_key: row.config_key, status,+ resources.push({ scope: row.scope, resource: row.resource, used: row.used, limit: row.limit, config_key: row.config_key, status, background_paused: paused,...(predicted ? { pct: predicted.pct, days_to_exhaustion: predicted.days_to_exhaustion, exhaustion_date: predicted.exhaustion_date, basis: predicted.basis,per_day_7d: predicted.per_day_7d, ...(predicted.net_per_day_7d !== undefined ? { net_per_day_7d: predicted.net_per_day_7d } : {}),...(predicted.reclaimable_bytes !== undefined ? { reclaimable_bytes: predicted.reclaimable_bytes } : {}) } : {}) });// Every principal shares one brain-wide key, so each key gets the largest value any scope needs.needed.set(row.config_key, Math.max(needed.get(row.config_key) ?? 0, value));}+ const anyPaused = resources.some(r => r.background_paused);const commands = [...needed].map(([key, value]) => `gbrain config set ${key} ${value}`);const details = { exact: true, inspected: counters.length, truncated: false, resources, commands, verify: VERIFY, docs: DOCS,+ background_pause_pct: Math.round(pause * 100), paused_producers: anyPaused ? [...BACKGROUND_PRODUCERS] : [],forecast: forecast ? { thresholds: forecast.thresholds, window_days: forecast.window_days, retention_days: forecast.retention_days,table_bytes: forecast.table_bytes, rows: forecast.rows } : { health: 'unknown' } };const thresholds = forecast?.thresholds;@@ -58,7 +65,8 @@ export async function checkPersistenceCapacity(engine: BrainEngine): Promise<Chemessage: `${resources.length} managed write limit(s) near exhaustion: ${resources.map(r => `${r.scope} ${r.resource} ${r.used}/${r.limit}`+ ('days_to_exhaustion' in r && r.days_to_exhaustion !== null ? ` (about ${r.days_to_exhaustion} day(s) left at the 7-day rate, ${r.basis})` : '')).join('; ')}. `+ `Admission refuses at the limit. Run on the brain host: ${commands.join('; ')} (each covers about one more year at the current admission rate), `- + `then verify with ${VERIFY}. Permanent request IDs are never evicted.` };+ + `then verify with ${VERIFY}. Permanent request IDs are never evicted.`+ + (anyPaused ? ` Background writes are paused past ${Math.round(pause * 100)}% (write_capacity_backpressure): ${BACKGROUND_PRODUCERS.join(', ')}; interactive writes keep the rest.` : '') };} catch (error) {return { name: 'persistence_capacity', status: 'warn',message: `Managed write capacity could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,diff --git a/src/commands/migrations/v0_13_1.ts b/src/commands/migrations/v0_13_1.tsindex 0fad9d4000..78bb84869e 100644--- a/src/commands/migrations/v0_13_1.ts+++ b/src/commands/migrations/v0_13_1.ts@@ -160,8 +160,8 @@ export async function phaseCGrandfather(AND NOT (COALESCE(p.source_path,'') ~ '\\.[^./]+$' AND COALESCE(p.source_path,'') !~* '\\.mdx?$')`, [ids]);try { await assertGrandfatherCapacity(engine, Number(admissible)); }catch (error) {- if (!(error instanceof OperationError) || error.code !== 'queue_capacity') throw error;- return { result: { name: 'grandfather', status: 'failed', detail: `queue_capacity: ${error.message} ${error.suggestion ?? ''}`.trim() }, detail: gf };+ if (!(error instanceof OperationError) || !['queue_capacity', 'write_quota_exhausted', 'write_quota_insufficient'].includes(error.code)) throw error;+ return { result: { name: 'grandfather', status: 'failed', detail: `${error.code}: ${error.message} ${error.suggestion ?? ''}`.trim() }, detail: gf };}}diff --git a/src/commands/migrations/v0_32_2.ts b/src/commands/migrations/v0_32_2.tsindex 5ffa08f8f1..3b32426417 100644--- a/src/commands/migrations/v0_32_2.ts+++ b/src/commands/migrations/v0_32_2.ts@@ -177,8 +177,8 @@ async function phaseBFenceFacts(try { await fenceUnfencedFacts(engine, plan); }catch (error) {- if (!(error instanceof OperationError) || error.code !== 'queue_capacity') throw error;- return { name: 'fence_facts', status: 'failed', detail: `queue_capacity: ${error.message} ${error.suggestion ?? ''}`.trim() };+ if (!(error instanceof OperationError) || !['queue_capacity', 'write_quota_exhausted', 'write_quota_insufficient'].includes(error.code)) throw error;+ return { name: 'fence_facts', status: 'failed', detail: `${error.code}: ${error.message} ${error.suggestion ?? ''}`.trim() };}return fenceFactsResult(outcome);} catch (e) {diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex 8d031edf6c..6652feeb29 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -387,6 +387,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, requestry {toolResult = await dispatchToolCall(engine, name, params as Record<string, unknown> | undefined, {remote: true,+ admissionOrigin: 'interactive',// WP1/D7: network transport — the dispatch-layer localOnly// backstop keys off this marker.transport: 'http',diff --git a/src/commands/sync-delegate.ts b/src/commands/sync-delegate.tsindex c78caf37b1..7a86262056 100644--- a/src/commands/sync-delegate.ts+++ b/src/commands/sync-delegate.ts@@ -577,7 +577,8 @@ export async function maybeDelegateManagedSyncToServe(engine: BrainEngine, args:const hard = await deriveDelegatedTimeoutSeconds(args, { env });const timeoutSeconds = soft && soft > 0 ? (hard > 0 ? Math.min(soft, hard) : soft) : hard;const options: DelegatedSyncOptions = {- sourceId, timeoutSeconds,+ // #6696 (A5): an operator's sync keeps the capacity background producers leave free.+ sourceId, timeoutSeconds, origin: 'interactive',...pick(opts, ['dryRun', 'full', 'noPull', 'noEmbed', 'noExtract', 'noSchemaPack', 'skipFailed', 'retryFailed', 'includeGitignored', 'noBulk'] as const),...(opts.lanes !== undefined ? { lanes: opts.lanes } : {}),...(opts.explicitProcessing?.length ? { explicitProcessing: [...opts.explicitProcessing] } : {}),diff --git a/src/core/connectors/item-holds.ts b/src/core/connectors/item-holds.tsindex be9b6f4aa6..d8318a49e2 100644--- a/src/core/connectors/item-holds.ts+++ b/src/core/connectors/item-holds.ts@@ -95,7 +95,7 @@ export interface ItemHoldsState {const SOURCE_CODES = new Set(['writer_coordinator_required', 'owner_unavailable', 'database_contention', 'writer_lock_unavailable', 'writer_pool_capacity',- 'queue_capacity', 'recovery_required', 'write_pending', 'source_changed', 'permission_denied', 'scope_denied',+ 'queue_capacity', 'write_quota_exhausted', 'write_capacity_backpressure', 'recovery_required', 'write_pending', 'source_changed', 'permission_denied', 'scope_denied','writer_registration_required', 'writer_identity_invalid', 'writer_not_initialized', 'writer_upgrade_required','writer_not_quiesced', 'writer_admin_locked', 'connector_account_changed', 'connector_intent_outdated','unsupported_mutation_protocol', 'cancelled', 'write_claim_lost', 'lock_stolen', 'statement_timeout', 'lock_timeout',diff --git a/src/core/context/sync-ipc.ts b/src/core/context/sync-ipc.tsindex d16d8e41b3..198b9fef7d 100644--- a/src/core/context/sync-ipc.ts+++ b/src/core/context/sync-ipc.ts@@ -55,6 +55,7 @@ export const DELEGATED_SYNC_OPTION_FIELDS = {lanes: 'number',explicitProcessing: 'string[]',timeoutSeconds: 'number',+ origin: 'string',} as const;/** `--lanes N` bounds (`src/commands/sync/args.ts`). */@@ -84,6 +85,8 @@ export interface DelegatedSyncOptions {noBulk?: boolean;/** #6317: `--lanes N` / `--no-lanes` (1..DELEGATED_SYNC_LANES_MAX) for the managed catch-up. */lanes?: number;+ /** #6696 (A5): who the run's writes are for; the operator's CLI sends `interactive`, absent is `background`. */+ origin?: 'interactive' | 'background';/** #6317: the processing options the caller set itself; the managed cursor supplies the rest. */explicitProcessing?: Array<typeof DELEGATED_SYNC_PROCESSING_KEYS[number]>;/**@@ -137,6 +140,9 @@ export function validateDelegatedSyncOptions(raw: unknown): DelegatedSyncValidatreturn { ok: false, error: 'invalid_options:explicitProcessing' };}}+ if (out.origin !== undefined && out.origin !== 'interactive' && out.origin !== 'background') {+ return { ok: false, error: 'invalid_options:origin' };+ }const timeout = out.timeoutSeconds;if (typeof timeout !== 'number' || !Number.isInteger(timeout) || timeout < 0) {return { ok: false, error: 'invalid_options:timeoutSeconds' };diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 1784f1a3d6..91ebdf1b29 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -43,6 +43,7 @@* trigger lock acquisition.*/+import { withAdmissionOrigin } from './persistence/admission-origin.ts';import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync, statSync, realpathSync } from 'fs';import { join } from 'path';import { gbrainPath, loadConfig } from './config.ts';@@ -1895,6 +1896,14 @@ async function runRepairLanePhase(phase: typeof REPAIR_LANE_PHASES[number], engiexport async function runCycle(engine: BrainEngine | null,opts: CycleOpts,+): Promise<CycleReport> {+ // #6696 (A5): every cycle phase is background work, even under an operator's command.+ return withAdmissionOrigin('background', () => runCycleUnscoped(engine, opts));+}++async function runCycleUnscoped(+ engine: BrainEngine | null,+ opts: CycleOpts,): Promise<CycleReport> {const start = performance.now();const requestedPhases = opts.phases ?? ALL_PHASES;diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 3bdb65f48d..fc0fe626f2 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -62,6 +62,11 @@ export const ERROR_CATALOGUE = {timeline_rows_would_be_removed: { code: 'timeline_rows_would_be_removed', docs: 'docs/guides/write-refusals.md#timeline_rows_would_be_removed' },reconcile_private_facts: { code: 'permission_denied', docs: 'docs/guides/write-refusals.md#reconcile-private-facts' },maintenance_backpressure: { code: 'maintenance_backpressure', docs: 'docs/guides/write-refusals.md#maintenance_backpressure' },+ // #6696: cumulative write caps (A5 background pause, A6 refusal at the cap, A7 bulk-run preflight).+ write_capacity_backpressure: { code: 'write_capacity_backpressure', docs: 'docs/guides/write-refusals.md#write_capacity_backpressure' },+ write_quota_exhausted: { code: 'write_quota_exhausted', docs: 'docs/guides/write-refusals.md#write_quota_exhausted' },+ write_quota_insufficient: { code: 'write_quota_insufficient', docs: 'docs/guides/write-refusals.md#write_quota_insufficient' },+ write_capacity_low: { code: 'write_capacity_low', docs: 'docs/guides/write-refusals.md#write_capacity_low' },// F0 `gbrain sources refresh` (worktree-wide coordinated ff-only refresh).refresh_not_managed: { code: 'refresh_not_managed', docs: 'docs/guides/write-refusals.md#refresh_not_managed' },refresh_not_owner: { code: 'refresh_not_owner', docs: 'docs/guides/write-refusals.md#refresh_not_owner' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 68ecadaa30..89207af15c 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -486,6 +486,8 @@ export const CODES = {verification_failed: { class: 'server', summary: "Source content or relationships changed during verification." },withdrawal_capacity: { class: 'caller', summary: "Withdrawal capacity." },withdrawal_provenance: { class: 'server', summary: "The withdrawal target manifest is invalid." },+ write_capacity_backpressure: { class: 'host_only', retryable: false, summary: "A background producer (maintenance, conversation facts, an autopilot phase or an autopilot catch-up sync) stopped admitting writes because a cumulative write cap is past `persistence.capacity.background_pause_pct` (0.8); interactive writes keep the rest. Nothing was submitted and no receipt was written.", why: "Near a cumulative cap the remaining request ids and receipt bytes are kept for the user's own writes (remember, put_page, edit_page, operator sync, approved repair). Request ids are never freed, so past the line on ids only the brain host's config raise resumes background work; receipt bytes also free as receipts compact.", docs: 'docs/guides/write-refusals.md#write_capacity_backpressure', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Names the cap past the pause line, its days left and the reversible config raise, read-only.", requires_exclusive: false }, exit: 12 },+ write_capacity_low: { class: 'host_only', retryable: false, summary: "A cumulative write cap is at or past 80% or runs out within `persistence.capacity.warn_days` (30) days at its 7-day rate; writes still work.", why: "Request ids are permanent and receipt bytes free only as receipts compact, so the cap is raised before admission refuses.", docs: 'docs/guides/write-refusals.md#write_capacity_low', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Reads the forecast and the one-year config value, read-only.", requires_exclusive: false } },write_claim_lost: { class: 'retryable', summary: "Execution claim changed before publication." },write_gate_rejected: { class: 'caller', summary: "The write gate refused external instruction-like content because the operator set `write_gate.external_mode` to `reject`.", why: "Text from an untrusted source that reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request) is refused instead of held under that setting, so nothing was written. The same content refuses on every retry.", reasons: ['override', 'standing_instruction', 'exfiltration', 'credential', 'detector_error'], suggestion: 'Tell the user the content was refused; whether to accept it or switch `write_gate.external_mode` back to `quarantine` is their decision.' },write_held: { class: 'consent', summary: "The write gate held this content for the owner's review instead of saving it as memory.", why: "Content from an untrusted source read like an instruction to an agent, so it was quarantined in the write-gate holding table. It is not searchable or recalled until the owner releases it; retrying the same write only re-opens the same hold.", reasons: ['override', 'standing_instruction', 'exfiltration', 'credential', 'detector_error'], actor: 'user', exit: 3, suggestion: 'Do not retry. Tell the user what was held and give them the release command from the fix; releasing is their decision.' },@@ -495,6 +497,8 @@ export const CODES = {docs: 'docs/guides/write-refusals.md#write_outcome_unknown',suggestion: 'Read the request first (the fix names it): a committed or pending row means the write was accepted, replay the same request_id to wait for it; no row means it was not, submit it again with the same request_id. Never resubmit under a new request_id without that read.' },write_pending: { class: 'retryable', summary: "The write was accepted and is still pending; it may commit later.", exit: 10 },+ write_quota_exhausted: { class: 'host_only', retryable: false, reasons: ['lifetime_ids', 'terminal_bytes'], summary: "A cumulative write cap (permanent request ids or reserved receipt bytes, for the principal or the brain) is full, so the write was not admitted and nothing changed.", why: "Request ids are permanent replay protection and a receipt keeps its bytes until it compacts, so waiting does not free the cap; the brain host raises it with gbrain config set (reversible).", docs: 'docs/guides/write-refusals.md#write_quota_exhausted', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Reads which cap is full and the config value that covers one more year, read-only.", requires_exclusive: false }, exit: 12 },+ write_quota_insufficient: { class: 'host_only', retryable: false, reasons: ['lifetime_ids', 'terminal_bytes'], summary: "A bulk run (managed sync catch-up, reclone or a repair) estimated more new receipts than the remaining write capacity allows before its producer's pause line, so it did not start; other writes still work.", why: "Starting a run that the cap would stop part way leaves a long tail of pending pages; the preflight refuses up front with the config raise that covers the run.", docs: 'docs/guides/write-refusals.md#write_quota_insufficient', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Reads the remaining capacity and the one-year config value, read-only.", requires_exclusive: false }, exit: 12 },worktree_dirty: { class: 'caller', retryable: false, actor: 'agent',summary: "A managed sync held a file whose uncommitted working-tree bytes match neither the pinned commit nor the current page; the rest of the source synced and the local edit was not overwritten.",why: "On a live checkout an agent may be mid-edit on a file the catch-up reaches. The bytes are not committed at HEAD, so sync cannot tell a deliberate local change from a stray one, and importing the pinned version would discard the edit; before #6340 this refusal stopped the whole run.",diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.tsindex c6a97e9561..e825788252 100644--- a/src/core/facts/conversation-publication.ts+++ b/src/core/facts/conversation-publication.ts@@ -47,6 +47,7 @@* row numbers under the page lock, and fails the request when an insert is* lost.*/+import { backgroundPaused, readBackgroundPauseShare } from '../persistence/admission-origin.ts';import type { BrainEngine, NewFact } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import type { Page } from '../types.ts';@@ -62,7 +63,7 @@ import { authorizeStoredRequest, authorizeWrite } from '../persistence/authorityimport { digest, jsonBytes } from '../persistence/digest.ts';import { receiptReservation } from '../persistence/receipt-bytes.ts';import { getWriteRequestById } from '../persistence/journal.ts';-import { readJournalLimits } from '../persistence/limits.ts';+import { journalLimitKey, oneYearCapacity, readJournalLimits } from '../persistence/limits.ts';import { principalKey } from '../persistence/model.ts';import { PERSISTENCE_IPC_MAX_BYTES } from '../persistence/ipc.ts';import { resolveManagedFactsEmbedding } from '../persistence/facts-maintenance.ts';@@ -243,43 +244,42 @@ export async function conversationIntentByteLimit(engine: BrainEngine): Promise<}/**- * Before model work: stop admitting once this writer's outstanding requests,- * reserved receipt bytes or permanent request ids would pass- * OUTSTANDING_ADMISSION_SHARE of their limit. The writer is the local CLI- * principal the user's own CLI writes share, so the last 20% stays theirs:- * reserved receipt bytes free only when receipts compact (after the retention- * window), request ids never. `needed` is the run's planned batch requests- * up front, 1 before each new batch; the suggested `--limit` is in pages.+ * Before model work: stop admitting once this writer's outstanding requests+ * pass OUTSTANDING_ADMISSION_SHARE of their limit (`maintenance_backpressure`,+ * retryable: they settle), or its reserved receipt bytes or permanent request+ * ids would pass the background pause line (`write_capacity_backpressure`,+ * host-only, A5): the writer is the local CLI principal the user's own CLI+ * writes share, so the rest stays theirs. Reserved receipt bytes free only+ * when receipts compact, request ids never. `needed` is the run's planned+ * batch requests up front, 1 before each new batch.*/export async function assertConversationAdmissionHeadroom(engine: BrainEngine, authority: MaintenanceAuthority, needed = 1): Promise<void> {const limits = await readJournalLimits(engine);const [counter] = await engine.executeRaw<{ outstanding_count: number | string; terminal_bytes: number | string; lifetime_ids: number | string }>('SELECT outstanding_count, terminal_bytes, lifetime_ids FROM persistence_counters WHERE key=$1', [principalKey(authority.writer.principal)]);const sourceId = authority.writer.sourceId;- const share = (limit: number) => Math.max(1, Math.floor(limit * OUTSTANDING_ADMISSION_SHARE));const outstanding = Number(counter?.outstanding_count ?? 0);- if (outstanding >= share(limits.principalOutstanding)) {+ if (outstanding >= Math.max(1, Math.floor(limits.principalOutstanding * OUTSTANDING_ADMISSION_SHARE))) {throw catalogueError('maintenance_backpressure',`Conversation fact extraction stopped admitting: ${outstanding} of this writer's ${limits.principalOutstanding} outstanding requests are still pending.`,`Let the pending requests settle (gbrain sources writer status --source ${sourceId} --json shows them; a resident gbrain serve or the next CLI run publishes them), then rerun the same command. Pages already published keep their facts.`);}+ // #6696 (A5): the cumulative caps follow the background pause, with the host-only, resource-specific fix: waiting frees no request id.+ const pause = await readBackgroundPauseShare(engine);const reservation = receiptReservation(authority.writer);- const cumulative = [- { resource: 'reserved receipt bytes', key: 'persistence.limits.principal_terminal_bytes', used: Number(counter?.terminal_bytes ?? 0),- limit: limits.principalTerminalBytes, per: reservation,- why: 'each request reserves its receipt for the retention window (persistence.receipt_retention_days), and the reservation frees only when receipts compact' },- { resource: 'permanent request ids', key: 'persistence.limits.principal_lifetime_ids', used: Number(counter?.lifetime_ids ?? 0),- limit: limits.principalLifetimeIds, per: 1, why: 'request ids are never reused or freed' },- ];- for (const r of cumulative) {- const ceiling = share(r.limit);+ const key = principalKey(authority.writer.principal);+ for (const r of [+ { resource: 'terminal_bytes' as const, setting: 'principalTerminalBytes' as const, used: Number(counter?.terminal_bytes ?? 0), per: reservation },+ { resource: 'lifetime_ids' as const, setting: 'principalLifetimeIds' as const, used: Number(counter?.lifetime_ids ?? 0), per: 1 },+ ]) {+ const limit = limits[r.setting];+ const ceiling = Math.floor(limit * pause);if (r.used + needed * r.per <= ceiling) continue;const room = Math.max(0, Math.floor((ceiling - r.used) / r.per)) * batchCaps.factPages;- const planned = needed > 1 ? `${needed} planned` : 'the next';- throw catalogueError('maintenance_backpressure',- `Conversation fact extraction stopped before admitting ${planned} request(s): this writer's ${r.resource} would pass 80% of its limit (${r.used} used of ${r.limit}).`,- `The last 20% stays free for this CLI writer's other writes; ${r.why}. ${room > 0 ? `Run a smaller batch that fits: gbrain extract-conversation-facts --source-id ${sourceId} --limit ${room}. ` : ''}`- + `Check the writer with gbrain sources writer status --source ${sourceId} --json; raising ${r.key} (gbrain config set ${r.key} <n>) is the user's call.`);+ throw backgroundPaused(key, r.resource, r.used, limit, pause, journalLimitKey(r.setting),+ await oneYearCapacity(engine, key, r.resource === 'lifetime_ids' ? 'LifetimeIds' : 'TerminalBytes', r.used, limit), {+ what: `Conversation fact extraction stopped before admitting ${needed > 1 ? `${needed} planned` : 'the next'} request(s)`,+ hint: room > 0 ? `A smaller batch fits: gbrain extract-conversation-facts --source-id ${authority.writer.sourceId} --limit ${room}.` : undefined });}}@@ -757,5 +757,5 @@ export async function flushManagedBatch(state: ManagedRunState, opts: { afterErr/** Managed admission backpressure and exhausted request ids stop the whole run, not one page. */export function stopsRun(err: unknown): boolean {return (!!err && typeof err === 'object' && RUN_STOPPING.has(err))- || (err instanceof OperationError && (err.code === 'maintenance_backpressure' || err.code === 'queue_capacity'));+ || (err instanceof OperationError && (err.code === 'maintenance_backpressure' || err.code === 'queue_capacity' || err.code === 'write_quota_exhausted' || err.code === 'write_capacity_backpressure'));}diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.tsindex 4572b89cd2..057dad1cec 100644--- a/src/core/facts/unfenced-facts.ts+++ b/src/core/facts/unfenced-facts.ts@@ -422,7 +422,7 @@ async function fenceManaged(engine: BrainEngine, plan: UnfencedFactsPlan): Promi// older than its own read (the facts-changed-since-planning guard keeps its short window).const [first] = authorities.values();if (first) await assertLifetimeIdHeadroom(engine, first.writer.principal, groups.size).catch(async (error: unknown) => {- if (!(error instanceof OperationError) || error.code !== 'queue_capacity') throw error;+ if (!(error instanceof OperationError) || !['write_quota_exhausted', 'write_quota_insufficient'].includes(error.code)) throw error;let submitting = 0;for (const [key, group] of groups) {const [sourceId, entitySlug] = key.split('\0');diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 88c38e2341..c50553e4a0 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -441,6 +441,11 @@ export interface OperationContext {* remote/untrusted (defense in depth in case the type is bypassed via cast).*/remote: boolean;+ /**+ * #6696 (A5): who this caller's writes are for, set only by trusted host-side entry points (the CLI, the MCP+ * transports). Unset is `background`; it is never derived from `remote` (persistence/admission-origin.ts).+ */+ admissionOrigin?: import('../persistence/admission-origin.ts').AdmissionOrigin;/*** Transport marker for auth-less remote surfaces (#1061). The stdio MCP* dispatch sets 'stdio' — it is deliberately `remote: true` (agent-facing,diff --git a/src/core/persistence/admission-origin.ts b/src/core/persistence/admission-origin.tsnew file mode 100644index 0000000000..3ed7ace913--- /dev/null+++ b/src/core/persistence/admission-origin.ts@@ -0,0 +1,73 @@+/**+ * #6696 (A5): who a write is for. `interactive` writes are the user's own+ * (`remember`, `put_page`, `edit_page` from the CLI or an MCP client, an+ * operator's `gbrain sync`, an approved `gbrain repair`); everything else is+ * `background` (maintenance, conversation facts, autopilot cycle phases,+ * autopilot catch-up syncs, minion jobs). Trusted host-side callers set the+ * origin explicitly: `OperationContext.admissionOrigin` at the CLI and MCP+ * entry points and the persistence owner's verified IPC dispatch, or a+ * `withAdmissionOrigin` scope around a command (`gbrain sync`, its delegated+ * run on the owner, `gbrain repair`; `runCycle` scopes itself background).+ * A caller that sets nothing is background. It is never inferred from+ * `ctx.remote`: an autopilot phase writes with `remote: true` too.+ *+ * Near a cumulative cap (`persistence.capacity.background_pause_pct`, default+ * 0.8, of a principal's or the brain's request ids or receipt bytes) a+ * background admission refuses `write_capacity_backpressure` before any+ * receipt exists, so the rest stays free for interactive writes.+ */+import { AsyncLocalStorage } from 'node:async_hooks';+import { opError, type OperationError } from '../ops/contract.ts';+import type { SqlEngine } from './model.ts';++export type AdmissionOrigin = 'interactive' | 'background';+export const ADMISSION_ORIGINS: readonly AdmissionOrigin[] = ['interactive', 'background'];+export const BACKGROUND_PAUSE_KEY = 'persistence.capacity.background_pause_pct';+export const DEFAULT_BACKGROUND_PAUSE_SHARE = 0.8;+/** What a paused admission's doctor finding names as paused. */+export const BACKGROUND_PRODUCERS = ['managed maintenance', 'conversation facts', 'autopilot cycle phases', 'autopilot catch-up sync', 'minion jobs'] as const;++const scope = new AsyncLocalStorage<AdmissionOrigin>();++/** Runs `fn` with every admission inside it attributed to `origin` (a background scope wins over an inner interactive caller). */+export function withAdmissionOrigin<T>(origin: AdmissionOrigin, fn: () => T): T {+ return scope.run(scope.getStore() === 'background' ? 'background' : origin, fn);+}++/** The origin an admission is charged to: a surrounding background scope, else the explicit origin, else the scope, else background. */+export function resolveAdmissionOrigin(explicit?: AdmissionOrigin): AdmissionOrigin {+ const surrounding = scope.getStore();+ if (surrounding === 'background') return 'background';+ return explicit ?? surrounding ?? 'background';+}++export function isAdmissionOrigin(value: unknown): value is AdmissionOrigin {+ return value === 'interactive' || value === 'background';+}++/** The pause line as a share of each cumulative cap (0 < share <= 1). */+export async function readBackgroundPauseShare(engine: SqlEngine): Promise<number> {+ const [row] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key=$1', [BACKGROUND_PAUSE_KEY]);+ const value = row ? Number(row.value) : DEFAULT_BACKGROUND_PAUSE_SHARE;+ return Number.isFinite(value) && value > 0 && value <= 1 ? value : DEFAULT_BACKGROUND_PAUSE_SHARE;+}++/**+ * The refusal of a background admission past the pause line; nothing was+ * submitted. Request ids are never freed, so past the line on ids the only fix+ * is the host's config raise; receipt bytes also free as receipts compact.+ */+export function backgroundPaused(scopeKey: string, resource: 'lifetime_ids' | 'terminal_bytes', used: number, limit: number, share: number,+ configKey: string, value: number, context: { what?: string; hint?: string } = {}): OperationError {+ const raise = `gbrain config set ${configKey} ${value}`;+ return opError('write_capacity_backpressure',+ `${context.what ?? 'Background writes are paused'}: ${scopeKey} ${resource} is at ${used} of ${limit}, past the ${Math.round(share * 100)}% pause line (${BACKGROUND_PAUSE_KEY}).`,+ `Nothing was submitted; interactive writes keep the rest of ${configKey}. ${context.hint ? `${context.hint} ` : ''}${resource === 'lifetime_ids'+ ? `Request ids are never freed, so background work resumes only after the brain host runs ${raise} (covers about one more year; undo with gbrain config unset ${configKey}).`+ : `Background work resumes as retained receipts compact, or at once after the brain host runs ${raise} (covers about one more year; undo with gbrain config unset ${configKey}).`}`,+ { reason: resource, detail: configKey.slice('persistence.limits.'.length), docs: 'docs/guides/write-refusals.md#write_capacity_backpressure',+ fix: { argv: ['gbrain', 'config', 'set', configKey, String(value)], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: resource === 'lifetime_ids' ? 'Request ids are permanent, so only a larger cap moves the pause line; the raise is reversible.'+ : 'The raise moves the pause line at once and is reversible; compaction frees reserved bytes only as receipts age out of the retention window.',+ verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'] }, docs: 'docs/guides/concurrent-writes.md#quota-near-exhaustion' } });+}diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.tsindex 2efaa4f9d8..4c241fce5f 100644--- a/src/core/persistence/diagnostics.ts+++ b/src/core/persistence/diagnostics.ts@@ -29,6 +29,7 @@ export const WRITER_NEXT_ACTIONS: Record<string, string> = {recovery_required: 'Inspect the recorded publication fingerprints on the designated owner and settle recovery before publishing this worktree.',recovery_capacity: 'Allow recovery to settle or increase the applicable persistence.limits recovery byte cap. Do not remove recovery records.',queue_capacity: 'Let outstanding requests finish or increase the applicable persistence.limits cap. Accepted request IDs are never evicted.',+ write_quota_exhausted: 'Raise the cumulative cap the refusal names with gbrain config set on the brain host (gbrain doctor --only persistence_capacity --json prints the value), then retry with the same request_id. Accepted request IDs are never evicted.',consumer_stopping: 'Restart the resident owner and inspect the same request_id before resubmitting.',source_changed: 'Inspect the source incarnation and worktree binding; queued requests cannot follow a recreated source.',permission_denied: 'Inspect the durable principal and current source, operation, and namespace grants.',diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex f5bc0c6dc9..8b347fc31e 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -465,7 +465,7 @@ async function recordFailure(engine: BrainEngine, effect: PersistenceEffect, err/** Waits that say nothing about the target never count toward parking. */const CONTENTION_CODES = ['projection_pending', 'revision_conflict', 'writer_busy', 'writer_pool_capacity', 'git_index_locked'];// #6305: writer_lock_unavailable is this process failing to open the lock file, not the effect failing; it never parks the effect.-const DEPENDENCY_CODES = ['recovery_required', 'owner_unavailable', 'write_claim_lost', 'queue_capacity', 'writer_lock_unavailable'];+const DEPENDENCY_CODES = ['recovery_required', 'owner_unavailable', 'write_claim_lost', 'queue_capacity', 'write_quota_exhausted', 'write_capacity_backpressure', 'writer_lock_unavailable'];/*** A scan sets its failing target aside and moves on; a single-target effect,diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 43e65edd48..9012c6aaff 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -11,7 +11,8 @@ import { journalLimitKey, oneYearCapacity, readJournalLimits, readReceiptRetentiimport { outstandingCapacityDetail, retryWriteAdmission } from './admission-retry.ts';import { PreadmitBrainChanged } from './preadmit-cache.ts';import { pipelined } from '../page-state/transactions.ts';-import { EFFECT_BYTES_SQL, receiptReservation, retainedReceiptBytes, TRUE_UP_CLAMP_SQL } from './receipt-bytes.ts';+import { backgroundPaused, readBackgroundPauseShare, resolveAdmissionOrigin, type AdmissionOrigin } from './admission-origin.ts';+import { EFFECT_BYTES_SQL, RECEIPT_RESERVATION_FLOOR, receiptReservation, retainedReceiptBytes, TRUE_UP_CLAMP_SQL } from './receipt-bytes.ts';import { writeHealth, type WriteHealthFacts } from './health.ts';import { writerStamp } from './writer-versions.ts';import { intentCarriesContent, intentCarriesPurgedContent, PURGE_PRESENCE_COLUMNS } from './purged-intent.ts';@@ -47,6 +48,8 @@ export interface WriteAdmission {intent: Record<string, unknown>;authority: WriteAuthority;terminalReservation?: number;+ /** #6696 (A5): who the write is for; unset is background unless a surrounding `withAdmissionOrigin` scope says otherwise. */+ origin?: AdmissionOrigin;/** Phase 4.2: the brain the cached pre-admission reads came from; admission under another brain throws PreadmitBrainChanged. */brainId?: string;}@@ -66,6 +69,20 @@ function ownerStatusFix(sourceId: string): Action {}const lifecycleIdConflict = (requestId: string) => opError('idempotency_conflict', 'This request_id belongs to a source lifecycle operation.',`Request ID ${requestId} is already recorded for a source lifecycle change of this CLI writer, so this page write was not admitted and nothing changed. Submit the page write with a new request_id.`);+/** #6696 (A5): a background admission of `ids` requests and `bytes` reservation refuses past the pause line of any locked counter. */+async function assertBackgroundRoom(tx: SqlEngine, counters: Counter[], limits: JournalLimits, ids: number, bytes: number): Promise<void> {+ const share = await readBackgroundPauseShare(tx);+ for (const row of counters) {+ const scope = row.key === 'brain' ? 'brain' : 'principal';+ for (const [resource, setting, used, need] of [['lifetime_ids', `${scope}LifetimeIds`, Number(row.lifetime_ids), ids],+ ['terminal_bytes', `${scope}TerminalBytes`, Number(row.terminal_bytes), bytes]] as const) {+ const limit = limits[setting];+ if (used + need <= Math.floor(limit * share)) continue;+ throw backgroundPaused(row.key, resource, used, limit, share, journalLimitKey(setting),+ await oneYearCapacity(tx, row.key, resource === 'lifetime_ids' ? 'LifetimeIds' : 'TerminalBytes', used, limit));+ }+ }+}/*** `outstanding` (#6278): the outstanding-request cap carries its counts on `detail`* (`outstandingCapacityDetail`), so a caller that can wait for the other@@ -77,15 +94,30 @@ export function capacityError(resource: string, outstanding?: { used: number; liif (outstanding) error.detail = outstandingCapacityDetail(outstanding.used, outstanding.limit);return error;}-/** Cumulative caps name their config key and a value that covers one more year at the current admission rate. */+/**+ * #6696 (A6): a cumulative cap refusal is `write_quota_exhausted` (host only;+ * waiting does not free a permanent id, and receipt bytes free only as+ * receipts compact). It names the config key and a value that covers one more+ * year at the current admission rate; `detail` keeps the limit key, `reason`+ * the resource.+ */async function cumulativeCapacityError(tx: SqlEngine, resource: string, scope: string, setting: keyof JournalLimits, used: number, limit: number): Promise<OperationError> {const key = journalLimitKey(setting);- const value = await oneYearCapacity(tx, scope, setting.endsWith('LifetimeIds') ? 'LifetimeIds' : 'TerminalBytes', used, limit);- const error = new OperationError('queue_capacity', `Write capacity exhausted: ${resource} (${used} used of ${limit}).`,- `Run on the brain host: gbrain config set ${key} ${value} (covers about one more year at the current admission rate). ` +- 'Keep the same request_id and retry after the change. Accepted request IDs and retained receipts are never evicted.');- error.detail = key.slice('persistence.limits.'.length);- return error;+ const ids = setting.endsWith('LifetimeIds');+ const value = await oneYearCapacity(tx, scope, ids ? 'LifetimeIds' : 'TerminalBytes', used, limit);+ return quotaExhausted(resource, key, value, used, limit, ids ? 'lifetime_ids' : 'terminal_bytes');+}+/** The `write_quota_exhausted` refusal for config key `key`; the fix is the reversible raise, verified by the capacity check. */+export function quotaExhausted(resource: string, key: string, value: number, used: number, limit: number, reason: 'lifetime_ids' | 'terminal_bytes'): OperationError {+ return opError('write_quota_exhausted', `Write capacity exhausted: ${resource} (${used} used of ${limit}).`,+ `Run on the brain host: gbrain config set ${key} ${value} (covers about one more year at the current admission rate; undo with gbrain config unset ${key}). ` ++ `Keep the same request_id and retry after the change. Accepted request IDs and retained receipts are never evicted.${reason === 'terminal_bytes'+ ? ' Then gbrain repair receipt-compaction previews the retained receipt bytes compaction would free.' : ''}`,+ { reason, detail: key.slice('persistence.limits.'.length), docs: 'docs/guides/write-refusals.md#write_quota_exhausted',+ fix: { argv: ['gbrain', 'config', 'set', key, String(value)], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: reason === 'lifetime_ids' ? 'Request ids are permanent, so only a larger cap admits more writes; the raise is reversible.'+ : 'The raise unblocks writes at once and is reversible; compaction frees reserved bytes only over time.',+ verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'] }, docs: 'docs/guides/concurrent-writes.md#quota-near-exhaustion' } });}/*** Up-front refusal for a backfill that will admit `needed` new requests: when@@ -94,16 +126,41 @@ async function cumulativeCapacityError(tx: SqlEngine, resource: string, scope: s* the caller mutates anything.*/export async function assertLifetimeIdHeadroom(engine: SqlEngine, principal: Principal, needed: number): Promise<void> {- if (needed <= 0) return;+ await assertWriteHeadroom(engine, principal, { ids: needed });+}+/**+ * #6696 (A7): a bulk run's preflight. `needed` is the run's estimate (new+ * request ids, and receipt bytes at `receiptReservation` each); `share` is the+ * producer's pause line (`backgroundPauseShare`) or 1 for an interactive run.+ * A cap already full refuses `write_quota_exhausted`; a cap that still admits+ * writes but cannot cover the run refuses `write_quota_insufficient`, both+ * with the config value that covers the run and one more year.+ */+export async function assertWriteHeadroom(engine: SqlEngine, principal: Principal, needed: { ids: number; bytes?: number }, share = 1): Promise<void> {+ if (needed.ids <= 0 && !needed.bytes) return;const limits = await readJournalLimits(engine);const keys = ['brain', principalKey(principal)];- const rows = await engine.executeRaw<{ key: string; lifetime_ids: number | string }>(- 'SELECT key,lifetime_ids FROM persistence_counters WHERE key=ANY($1::text[])', [keys]);+ const rows = await engine.executeRaw<{ key: string; lifetime_ids: number | string; terminal_bytes: number | string }>(+ 'SELECT key,lifetime_ids,terminal_bytes FROM persistence_counters WHERE key=ANY($1::text[])', [keys]);for (const key of keys) {const scope = key === 'brain' ? 'brain' : 'principal';- const used = Number(rows.find(row => row.key === key)?.lifetime_ids ?? 0);- const limit = limits[`${scope}LifetimeIds`];- if (used + needed > limit) throw await cumulativeCapacityError(engine, `${scope} permanent request IDs`, key, `${scope}LifetimeIds`, used, limit);+ for (const [resource, setting, need, label] of [['lifetime_ids', `${scope}LifetimeIds`, needed.ids, 'permanent request IDs'],+ ['terminal_bytes', `${scope}TerminalBytes`, needed.bytes ?? 0, 'reserved receipt bytes']] as const) {+ if (need <= 0) continue;+ const used = Number(rows.find(row => row.key === key)?.[resource] ?? 0);+ const limit = limits[setting];+ if (used + need <= Math.floor(limit * share)) continue;+ if (used + (resource === 'lifetime_ids' ? 1 : RECEIPT_RESERVATION_FLOOR) > limit) {+ throw await cumulativeCapacityError(engine, `${scope} ${label}`, key, setting, used, limit);+ }+ const configKey = journalLimitKey(setting);+ const value = Math.max(Math.ceil((used + need) / share) + 1, await oneYearCapacity(engine, key, resource === 'lifetime_ids' ? 'LifetimeIds' : 'TerminalBytes', used, limit));+ throw opError('write_quota_insufficient', `This run needs ${need} more ${scope} ${label} than the ${Math.floor(limit * share) - used} left before its limit (${used} used of ${limit}${share < 1 ? `, pausing at ${Math.round(share * 100)}%` : ''}).`,+ `Nothing was started and other writes still work. Run on the brain host: gbrain config set ${configKey} ${value} (undo with gbrain config unset ${configKey}), then rerun the same command.`,+ { reason: resource, detail: configKey.slice('persistence.limits.'.length), docs: 'docs/guides/write-refusals.md#write_quota_insufficient',+ fix: { argv: ['gbrain', 'config', 'set', configKey, String(value)], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: 'Covers this run and about one more year at the current rate; reversible.', verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'] } } });+ }}}/** Creates and locks the counter rows in key order: two statements for any number of keys (#5984 round-trip diet). */@@ -179,6 +236,7 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, overconst terminalBytes = input.terminalReservation ?? receiptReservation(input.authority);if (!Number.isSafeInteger(terminalBytes) || terminalBytes < 1024) throw new TypeError('Invalid terminal receipt reservation.');const stamp = writerStamp();+ const origin = resolveAdmissionOrigin(input.origin);return { requestId, apply: async (tx: BrainEngine): Promise<WriteRequest> => {await declarePersistenceProtocol(tx);// The guards are sent together in lock order (worktree, source, writer, counters) and judged in@@ -223,6 +281,7 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, overif (Number(row.terminal_bytes) + terminalBytes > limits[`${scope}TerminalBytes`]) throw await cumulativeCapacityError(tx, `${scope} reserved receipt bytes`,row.key, `${scope}TerminalBytes`, Number(row.terminal_bytes), limits[`${scope}TerminalBytes`]);}+ if (origin === 'background') await assertBackgroundRoom(tx, counters, limits, 1, terminalBytes);// The request row and its counter reservation in one statement; the counters are already locked.const [row] = await tx.executeRaw<WriteRequest>(`WITH reserved AS (UPDATE persistence_counters SET outstanding_count=outstanding_count+1,intent_bytes=intent_bytes+$14,lifetime_ids=lifetime_ids+1,terminal_bytes=terminal_bytes+$15 WHERE key=ANY($20::text[]))@@ -302,6 +361,7 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: Writif (Number(row.terminal_bytes) + terminalBytes > limits[`${scope}TerminalBytes`]) throw await cumulativeCapacityError(tx, `${scope} reserved receipt bytes`,row.key, `${scope}TerminalBytes`, Number(row.terminal_bytes), limits[`${scope}TerminalBytes`]);}+ if (resolveAdmissionOrigin(first.origin) === 'background') await assertBackgroundRoom(tx, counters, limits, fresh.length, terminalBytes);const [rows] = await pipelined(tx, [() => tx.executeRaw<WriteRequest>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,page_id,slug,worktree_id,topology_generation,digest,intent,authority,intent_bytes,terminal_reservation,target_kind,protocol_version,diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 32b4df4274..234792aa36 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -173,7 +173,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco{ pageSlug: slug, remote: ctx.remote !== false, excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote), slugPrefixes: authority.slugPrefixes });}await assertFactNotWithdrawn(ctx.engine, sourceId, factIntent, { excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote) });- const row = await admitWrite(ctx.engine, { principal, operation: 'remember', sourceId, sourceIncarnation: source.incarnation,+ const row = await admitWrite(ctx.engine, { origin: ctx.admissionOrigin, principal, operation: 'remember', sourceId, sourceIncarnation: source.incarnation,slug, pageId: snapshot?.page.id ?? null, requestId, clientRequestId, callerIntent,// The transport's session (MCP `_meta.session_id`) is recorded on the fact, as extract_facts records// it, so recall's session_id filter finds single facts too. Identity only — never a trust surface.@@ -267,7 +267,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'foconst slug = fact.source_markdown_slug ?? fact.entity_slug ?? 'memory/unattributed';enforceClientSlugFence(ctx, slug, operation); enforceSubagentSlugFence(ctx, slug, operation);const authority = await submissionAuthority({ ...ctx, engine: tx }, operation, sourceId, source.incarnation, slug);- const row = await admitWriteInTransaction(tx, { principal, operation, sourceId, sourceIncarnation: source.incarnation,+ const row = await admitWriteInTransaction(tx, { origin: ctx.admissionOrigin, principal, operation, sourceId, sourceIncarnation: source.incarnation,slug, requestId, clientRequestId, callerIntent, intent: { ...callerIntent, reason }, authority });if (isTerminal(row)) return row;return withCoordinatedWrite(tx, [sourceId], async () => {diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 57fcfdc917..aeb608e897 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -390,7 +390,7 @@ export async function preparePageAdmission(ctx: OperationContext,&& !publishesDatabaseOnly(join(binding.local_path, binding.relative_path), slug, snapshot)) {throw colonSlugWindowsRefusal(slug, sourceId);}- return { typeWarning, slugAdvisory, admission: { principal, operation: input.operation, sourceId, sourceIncarnation: source.incarnation,+ return { typeWarning, slugAdvisory, admission: { origin: ctx.admissionOrigin, principal, operation: input.operation, sourceId, sourceIncarnation: source.incarnation,slug, pageId: snapshot?.page.id ?? null, requestId, clientRequestId: input.batch ? undefined : clientRequestIdOf(params.request_id), callerIntent, intent, authority,...(input.operation === 'edit_page' ? { terminalReservation: receiptReservation(authority, (await import('./page-edit.ts')).EDIT_PAGE_RECEIPT_RESERVE) } : {}),worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null } };diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.tsindex e51e12f256..422744c9d1 100644--- a/src/core/persistence/provider.ts+++ b/src/core/persistence/provider.ts@@ -81,6 +81,8 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:const localCliLocalOnly = !verified.remote && verified.principal.kind === 'local_cli' && LOCAL_CLI_LOCAL_ONLY_OPS.has(request.operation);const writeWaitMs = boundedWriteWaitMs(request.write_wait_ms);const result = await dispatchToolCall(engine, request.operation, params, {+ // #6696 (A5): a verified local registration is the user's CLI or agent, as on the in-process entry points.+ admissionOrigin: 'interactive',config, remote: verified.remote, transport: verified.remote || localSkillAdministration || localCliLocalOnly ? 'stdio' : undefined, sourceId, auth,...(writeWaitMs !== undefined ? { writeWaitMs } : {}),...(unrestricted ? {} : { localFederatedSourceIds: verified.grant.sourceIds }),diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.tsindex b632d79583..57bd97d3ef 100644--- a/src/core/persistence/sync-fault-class.ts+++ b/src/core/persistence/sync-fault-class.ts@@ -77,6 +77,9 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [{ code: 'connection_lost', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'three reruns in a row end connection_lost (the database is unreachable from this host)' },{ code: 'database_contention', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'three reruns in a row stop on it' },{ code: 'write_capacity', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'writer status shows the cap held by requests that never settle' },+ // #6696 (A5): a background sync paused near a cumulative cap; interactive writes keep the rest and the pause lifts as capacity returns.+ { code: 'write_capacity_backpressure', class: 'connection', safe_actions: ['retry'], needs_human: false,+ escalate: 'reason lifetime_ids (request ids never free, so only the host raise lifts it), or the pause outlasts a day' },{ code: 'storage_error', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'the same error after a rerun (then it is not a dropped connection)' },// #6513: the engine-graduation fence (SQLSTATE 55000) refuses every write until the move finishes; the cursor and manifest stand.{ code: 'graduation_in_progress', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'gbrain migrate --status --json reports no running move and the fence still refuses' },@@ -87,6 +90,11 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [{ code: 'owner_unavailable', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The write owner is gone; start or restart it on the brain host.' },{ code: 'writer_coordinator_required', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'Managed persistence is not active for this source; activate it or sync unmanaged.' },{ code: 'permission_denied', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'This principal may not sync the source; the owner grants it.' },+ // #6696 (A6/A7): a cumulative cap is full, or too small for the run; only the brain host's reversible config raise clears it.+ { code: 'write_quota_exhausted', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always',+ human_reason: 'A cumulative write cap is full; the brain host runs the gbrain config set the error prints (gbrain doctor --only persistence_capacity --json names the value), then the same sync resumes.' },+ { code: 'write_quota_insufficient', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always',+ human_reason: 'The run needs more write capacity than is left; the brain host runs the gbrain config set the error prints, then reruns the same sync.' },{ code: 'plan_stale', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The approved company-brain manifest changed; inspect and approve the repository again.' },{ code: 'invalid_params', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The resume options conflict with the stored cursor; use the resume command the error prints.' },// #6518: bookkeeping of an incarnation the source no longer has; a retry selects a different key, so only the repair clears it.diff --git a/src/core/persistence/topology-receipts.ts b/src/core/persistence/topology-receipts.tsindex 3366c17485..6d8a372d34 100644--- a/src/core/persistence/topology-receipts.ts+++ b/src/core/persistence/topology-receipts.ts@@ -1,8 +1,8 @@import type { BrainEngine } from '../engine.ts';import { opError } from '../ops/contract.ts';import { digest, jsonBytes } from './digest.ts';-import { lockCounters } from './journal.ts';-import { journalLimitKey, readJournalLimits } from './limits.ts';+import { lockCounters, quotaExhausted } from './journal.ts';+import { journalLimitKey, oneYearCapacity, readJournalLimits } from './limits.ts';import { principalKey } from './model.ts';import { receiptReservation, retainedReceiptBytes } from './receipt-bytes.ts';@@ -41,8 +41,13 @@ export async function recordTopologyChange(tx:BrainEngine, input:{principal:stri`Too much lifecycle work is still pending, so the ${input.operation} of source ${input.sourceId} was not accepted. Let the pending work settle, then submit it again; raising ${journalLimitKey(brain?'brainOutstanding':'principalOutstanding')} is the user's call.`, { fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', input.sourceId, '--json'], consent: [], actor: 'agent', why: 'Shows the pending lifecycle and recovery work that holds this capacity.', requires_exclusive: false } });if(Number(counter.lifetime_ids)+1>(brain?limits.brainLifetimeIds:limits.principalLifetimeIds)||Number(counter.terminal_bytes)+terminalBytes>(brain?limits.brainTerminalBytes:limits.principalTerminalBytes))- throw opError('queue_capacity','Permanent lifecycle receipts reached the configured capacity. Increase the quota; existing IDs are retained.',- `Retained lifecycle receipts reached ${journalLimitKey(brain?'brainLifetimeIds':'principalLifetimeIds')} or ${journalLimitKey(brain?'brainTerminalBytes':'principalTerminalBytes')}, so the ${input.operation} of source ${input.sourceId} was not accepted. Ask the user whether to raise the quota with gbrain config set; receipts are never evicted.`);+ {+ const ids=Number(counter.lifetime_ids)+1>(brain?limits.brainLifetimeIds:limits.principalLifetimeIds);+ const setting=`${brain?'brain':'principal'}${ids?'LifetimeIds':'TerminalBytes'}` as const;+ const used=Number(ids?counter.lifetime_ids:counter.terminal_bytes);+ throw quotaExhausted(`${brain?'brain':'principal'} ${ids?'permanent request IDs':'reserved receipt bytes'} (lifecycle ${input.operation} of source ${input.sourceId})`,+ journalLimitKey(setting),await oneYearCapacity(tx,counter.key,ids?'LifetimeIds':'TerminalBytes',used,limits[setting]),used,limits[setting],ids?'lifetime_ids':'terminal_bytes');+ }}if(recoveryBytes && counter.key!==key && Number(counter.recovery_bytes)+recoveryBytes>(brain?limits.brainRecoveryBytes:limits.worktreeRecoveryBytes))throw opError('queue_capacity','The lifecycle recovery exceeds available brain/worktree capacity.',diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.tsindex 6efb2ea358..2524c8f336 100644--- a/src/core/persistence/types.ts+++ b/src/core/persistence/types.ts@@ -7,7 +7,7 @@ export type WriteRequestState = typeof WRITE_REQUEST_STATES[number];export const WRITE_ERROR_CODES = ['writer_lock_unavailable', 'writer_pool_capacity', 'owner_unavailable',- 'recovery_required', 'queue_capacity', 'revision_required', 'revision_conflict',+ 'recovery_required', 'queue_capacity', 'write_quota_exhausted', 'write_quota_insufficient', 'write_capacity_backpressure', 'revision_required', 'revision_conflict','idempotency_conflict', 'source_changed', 'write_pending', 'storage_error', 'cancelled','permission_denied', 'scope_denied', 'invalid_params', 'not_found', 'page_not_found','page_identity_changed', 'write_claim_lost', 'request_too_large', 'response_too_large',diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 4f5b841e6a..8b10af682b 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -19,6 +19,7 @@* full scan (a run with no stored cursor, which every completed run leaves* behind) does, the same way a `revision_conflict` item is retried.*/+import { withAdmissionOrigin } from '../persistence/admission-origin.ts';import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../engine.ts';import type { OperationContext } from '../ops/contract.ts';@@ -275,6 +276,12 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sspec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;/** Test seam: who publishes this run's admissions (default: this process's consumer, else a live full one on this host). */publicationOwner?: () => Promise<{ alive: boolean; owner: string }> }): Promise<RepairResult> {+ // #6696 (A5): an approved local repair is the operator's own write; a maintenance cycle's background scope still wins.+ return withAdmissionOrigin('interactive', () => runRepairScoped(ctx, handler, scope, opts));+}++async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, scope: RepairScope,+ opts: Parameters<typeof runRepair>[3]): Promise<RepairResult> {const { repairSpec, explicitKindRequired } = await import('./registry.ts');const spec = opts.spec ?? repairSpec(handler.kind);if (spec?.explicit_only && opts.explicit !== true) throw explicitKindRequired(handler.kind);diff --git a/src/core/serve-sync-runner.ts b/src/core/serve-sync-runner.tsindex 7d421e9ef9..a904154c28 100644--- a/src/core/serve-sync-runner.ts+++ b/src/core/serve-sync-runner.ts@@ -54,6 +54,7 @@* CLI's effective flags (the managed cursor owns processing options).*/+import { isAdmissionOrigin, withAdmissionOrigin } from './persistence/admission-origin.ts';import { randomUUID } from 'node:crypto';import { withLegacySyncDelegation } from './persistence/sync-authority.ts';import { verifyLocalWriter, withVerifiedLocalRegistration } from './persistence/identity.ts';@@ -159,6 +160,17 @@ export function startDelegatedSync(rawOptions: unknown,clientToken: string,opts: { boundSourceId?: string; registration?: unknown } = {},+): SyncStartResponse | Promise<SyncStartResponse> {+ // #6696 (A5): the client's admission origin scopes every write of the job (validated below; a client that sends none is background).+ const origin = (rawOptions as { origin?: unknown } | null)?.origin;+ return withAdmissionOrigin(isAdmissionOrigin(origin) ? origin : 'background', () => startDelegatedSyncScoped(engine, rawOptions, clientToken, opts));+}++function startDelegatedSyncScoped(+ engine: BrainEngine,+ rawOptions: unknown,+ clientToken: string,+ opts: { boundSourceId?: string; registration?: unknown },): SyncStartResponse | Promise<SyncStartResponse> {if (typeof clientToken !== 'string' || clientToken.length === 0 || clientToken.length > 128) {return { ok: false, protocol: 2, error: 'invalid_options:clientToken' };diff --git a/src/core/shared-skills/publication.ts b/src/core/shared-skills/publication.tsindex 59351af109..50c4c0c626 100644--- a/src/core/shared-skills/publication.ts+++ b/src/core/shared-skills/publication.ts@@ -411,7 +411,7 @@ export async function submitSharedSkillMutation(ctx: OperationContext, operationconst intent: PublicationIntent = { pack_id: packId, name, expected_revision: expected, policy_epoch: policy.epoch,affected: affected.map(r => ({ name: r.name, revision: r.revision ?? null })), expected_pack_revision: pack?.revision ?? null,manifest_before_hash: manifestBytes ? sha256(manifestBytes) : null, original_manifest: manifestMetadata, before_hashes: beforeHashes, proposals, extra_files: extraFiles };- const row = await admitWrite(ctx.engine, { principal, operation, sourceId, sourceIncarnation: source.incarnation, slug, requestId,+ const row = await admitWrite(ctx.engine, { origin: ctx.admissionOrigin, principal, operation, sourceId, sourceIncarnation: source.incarnation, slug, requestId,targetKind: 'skill_bundle', protocolVersion: 2, callerIntent, intent: intent as unknown as Record<string, unknown>, authority,worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });return writeResponse(await waitForWrite(ctx.engine, row, ctx.config, ctx.writeWaitMs));diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex bff79d4f45..efa6b9478b 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -158,6 +158,8 @@ export interface ToolResult {}export interface DispatchOpts {+ /** #6696 (A5): set by the trusted transport for the user's own agent calls; never from wire params. */+ admissionOrigin?: OperationContext['admissionOrigin'];/** Configuration selected by the resident transport, never populated from wire params. */config?: OperationContext['config'];/** Defaults to true (remote/untrusted). Local CLI callers (`gbrain call`) pass false. */@@ -840,6 +842,7 @@ export function buildOperationContext(...(opts.stdioSurface ? { stdioSurface: opts.stdioSurface } : {}),...(opts.revealTools ? { revealTools: opts.revealTools } : {}),...(opts.writeWaitMs !== undefined ? { writeWaitMs: opts.writeWaitMs } : {}),+ ...(opts.admissionOrigin ? { admissionOrigin: opts.admissionOrigin } : {}),...(opts.resultRows ? { resultRows: opts.resultRows } : {}),isCallable: (opName: string) => (render ??= dispatchRenderContext(opts)).isCallable(opName),auth: opts.auth,diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex 0057903ad0..5b03eecf58 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -535,6 +535,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {}const result = await dispatchToolCall(engine, toolName, args, {remote: true,+ admissionOrigin: 'interactive',// WP1/D7: network transport — the dispatch-layer localOnly// backstop keys off this marker.transport: 'http',diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex d954bcc592..1be2e3ebbd 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -460,6 +460,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS);return finishResult(await dispatchToolCall(engine, name, params, {remote: true,+ admissionOrigin: 'interactive',// #1061: mark the transport so whoami can report {transport: 'stdio'}// instead of throwing unknown_transport. Trust posture unchanged —// stdio stays remote/untrusted.@@ -622,6 +623,7 @@ export async function handleToolCall(const ctx = buildOperationContext(engine, params, {remote: false,+ admissionOrigin: 'interactive',logger: { info: console.log, warn: console.warn, error: console.error },...(opts?.sourceId ? { sourceId: opts.sourceId } : {}),...(opts?.writeWaitMs !== undefined ? { writeWaitMs: opts.writeWaitMs } : {}),diff --git a/test/connector-item-holds.test.ts b/test/connector-item-holds.test.tsindex d38c8400b8..8d89240e91 100644--- a/test/connector-item-holds.test.ts+++ b/test/connector-item-holds.test.ts@@ -37,6 +37,9 @@ describe('classifyConnectorError (the one classification table)', () => {[new OperationError('writer_coordinator_required', 'x'), 'writer_coordinator_required', 'source'],[new OperationError('owner_unavailable', 'x'), 'owner_unavailable', 'source'],[new OperationError('queue_capacity', 'x'), 'queue_capacity', 'source'],+ // #6696 (A5/A6): the cumulative wall and the background pause hold the source, never the item.+ [new OperationError('write_quota_exhausted', 'x'), 'write_quota_exhausted', 'source'],+ [new OperationError('write_capacity_backpressure', 'x'), 'write_capacity_backpressure', 'source'],[new OperationError('write_pending', 'x'), 'write_pending', 'source'],[new OperationError('connector_account_changed', 'x'), 'connector_account_changed', 'source'],[new LockStolenError('lock'), 'lock_stolen', 'source'],diff --git a/test/context/sync-ipc-validation.test.ts b/test/context/sync-ipc-validation.test.tsindex 341ea178cc..dfa2f77c52 100644--- a/test/context/sync-ipc-validation.test.ts+++ b/test/context/sync-ipc-validation.test.ts@@ -123,6 +123,13 @@ describe('validateDelegatedSyncOptions', () => {expect(validateDelegatedSyncOptions({ sourceId: 'ok-source', timeoutSeconds: 60 }).ok).toBe(true);});+ test('#6696 (A5): origin carries the admission origin and rejects anything else', () => {+ expect(validateDelegatedSyncOptions({ timeoutSeconds: 0, origin: 'interactive' })).toEqual({ ok: true, options: { timeoutSeconds: 0, origin: 'interactive' } });+ expect(validateDelegatedSyncOptions({ timeoutSeconds: 0, origin: 'background' })).toMatchObject({ ok: true });+ expect(validateDelegatedSyncOptions({ timeoutSeconds: 0, origin: 'admin' })).toEqual({ ok: false, error: 'invalid_options:origin' });+ expect(validateDelegatedSyncOptions({ timeoutSeconds: 0, origin: true })).toEqual({ ok: false, error: 'invalid_options:origin' });+ });+test('field table and options interface stay in lockstep', () => {// The validator iterates the table; if a field is added to the interface// but not the table it becomes unreachable from the wire — this pin makes@@ -138,6 +145,7 @@ describe('validateDelegatedSyncOptions', () => {'noExtract','noPull','noSchemaPack',+ 'origin','retryFailed','skipFailed','sourceId',diff --git a/test/conversation-facts-managed.test.ts b/test/conversation-facts-managed.test.tsindex e5391b6795..f548e8ce00 100644--- a/test/conversation-facts-managed.test.ts+++ b/test/conversation-facts-managed.test.ts@@ -398,7 +398,8 @@ for (const backend of testBackends()) {const [used] = await engine.executeRaw<{ n: number }>("SELECT COALESCE(max(lifetime_ids),0)::int AS n FROM persistence_counters WHERE key LIKE 'principal:%'");await engine.setConfig('persistence.limits.principal_lifetime_ids', String(used!.n));const lifetime = await extract(engine, calls).then(() => null, (e: Error & { code?: string }) => e);- expect(lifetime?.code).toBe('maintenance_backpressure');+ // #6696 (A5): a cumulative cap is the host-only pause, not a retryable wait.+ expect(lifetime?.code).toBe('write_capacity_backpressure');expect(calls.n).toBe(0);await engine.executeRaw("DELETE FROM config WHERE key='persistence.limits.principal_lifetime_ids'");// Outstanding: with one request pending, a limit of 2 (80% = 1) stops admitting the next page.@@ -421,7 +422,7 @@ for (const backend of testBackends()) {}, { databaseUrl });}, 120_000);- test(`${backend}: admission stops at 80% of the writer's reserved receipt bytes, before any model call`, async () => {+ test(`${backend}: admission stops at 80% of the writer's reserved receipt bytes, before any model call, with the host's raise or compaction`, async () => {await managedBrain(async brain => {const { engine } = brain;await putPage(brain, transcript());@@ -430,15 +431,18 @@ for (const backend of testBackends()) {await engine.setConfig('persistence.limits.principal_terminal_bytes', String(Number(bytes) + 20_000));const calls = { n: 0 };const error = await extract(engine, calls).then(() => null, (e: Error & { code?: string; suggestion?: string }) => e);- expect(error?.code).toBe('maintenance_backpressure');- expect(error?.message).toContain('reserved receipt bytes');+ expect(error?.code).toBe('write_capacity_backpressure');+ expect(error).toMatchObject({ reason: 'terminal_bytes', fix: { actor: 'host_admin',+ argv: ['gbrain', 'config', 'set', 'persistence.limits.principal_terminal_bytes', expect.stringMatching(/^\d+$/)] } });+ expect(error?.message).toContain('terminal_bytes');expect(error?.suggestion).toContain('persistence.limits.principal_terminal_bytes');+ expect(error?.suggestion).toContain('as retained receipts compact');expect(calls.n).toBe(0);expect(await extractorRows(engine)).toEqual([]);}, { databaseUrl });}, 120_000);- test(`${backend}: admission stops at 80% of the writer's permanent request ids, before any model call`, async () => {+ test(`${backend}: admission stops at 80% of the writer's permanent request ids, before any model call, and asks for host action, never a wait`, async () => {await managedBrain(async brain => {const { engine } = brain;await putPage(brain, transcript());@@ -447,9 +451,13 @@ for (const backend of testBackends()) {await engine.setConfig('persistence.limits.principal_lifetime_ids', String(used + 1)); // fits one admission, but past 80%const calls = { n: 0 };const error = await extract(engine, calls).then(() => null, (e: Error & { code?: string; suggestion?: string }) => e);- expect(error?.code).toBe('maintenance_backpressure');- expect(error?.message).toContain('permanent request ids');- expect(error?.suggestion).toContain('persistence.limits.principal_lifetime_ids');+ // #6696 (A5, DX round 3): above the pause line, below the hard cap; ids never free, so the fix is the host's raise.+ expect(error?.code).toBe('write_capacity_backpressure');+ expect(error).toMatchObject({ reason: 'lifetime_ids', fix: { actor: 'host_admin',+ argv: ['gbrain', 'config', 'set', 'persistence.limits.principal_lifetime_ids', expect.stringMatching(/^\d+$/)] } });+ expect(error?.message).toContain('lifetime_ids');+ expect(error?.suggestion).toContain('never freed');+ expect(error?.suggestion).not.toMatch(/\b(wait|retry|settle)\b/i);expect(calls.n).toBe(0);}, { databaseUrl });}, 120_000);@@ -470,7 +478,7 @@ for (const backend of testBackends()) {const calls = { n: 0 };const error = await runExtractConversationFactsCore(engine, { sourceId: 'default', sleepMs: 0, overrideDisabled: true,extractor: async () => { calls.n++; return []; } }).then(() => null, (e: Error & { code?: string; suggestion?: string }) => e);- expect(error?.code).toBe('maintenance_backpressure');+ expect(error?.code).toBe('write_capacity_backpressure');expect(error?.message).toContain('3 planned');expect(error?.suggestion).toContain(`gbrain extract-conversation-facts --source-id default --limit ${room}`);expect(calls.n).toBe(0);diff --git a/test/fact-fence-adoption-exits.test.ts b/test/fact-fence-adoption-exits.test.tsindex 459b6731b1..08e174a0bf 100644--- a/test/fact-fence-adoption-exits.test.ts+++ b/test/fact-fence-adoption-exits.test.ts@@ -163,7 +163,7 @@ for (const backend of testBackends()) {await declarePersistenceProtocol(tx);await tx.executeRaw(`UPDATE persistence_requests SET completed_at=now()-interval '25 hours' WHERE request_id=$1::uuid`, [planned.requestId]);});- await expect(fenceUnfencedFacts(engine, await planUnfencedFacts(engine, { sourceId: 'default' }))).rejects.toMatchObject({ code: 'queue_capacity' });+ await expect(fenceUnfencedFacts(engine, await planUnfencedFacts(engine, { sourceId: 'default' }))).rejects.toMatchObject({ code: 'write_quota_exhausted' });}, { databaseUrl, setup: async ({ engine, root }) => { await seedLegacyManagedContent(engine, root); } });}, 120_000);diff --git a/test/grandfather-capacity.test.ts b/test/grandfather-capacity.test.tsindex fadd62fb94..af1b4483f0 100644--- a/test/grandfather-capacity.test.ts+++ b/test/grandfather-capacity.test.ts@@ -31,7 +31,7 @@ test('one admissible page refuses up front with the capacity command', async ()const before = await engine.executeRaw('SELECT slug, frontmatter, knowledge_revision FROM pages ORDER BY slug');const { result } = await phaseCGrandfather(engine, OPTS);expect(result.status).toBe('failed');- expect(result.detail).toStartWith('queue_capacity: Write capacity exhausted: principal permanent request IDs (0 used of 0).');+ expect(result.detail).toStartWith('write_quota_exhausted: Write capacity exhausted: principal permanent request IDs (0 used of 0).');expect(result.detail).toContain(`gbrain config set ${EXHAUSTED} `);expect(await engine.executeRaw('SELECT slug, frontmatter, knowledge_revision FROM pages ORDER BY slug')).toEqual(before);}, { setup: async brain => {diff --git a/test/helpers/managed-migration-chain-contract.ts b/test/helpers/managed-migration-chain-contract.tsindex 0ff22404eb..3310841e31 100644--- a/test/helpers/managed-migration-chain-contract.ts+++ b/test/helpers/managed-migration-chain-contract.ts@@ -90,7 +90,7 @@ export async function runManagedMigrationChain(databaseUrl: string | undefined,/*** Eng capacity split: with the migration writer's permanent request IDs* exhausted, schema migrations still complete (they admit nothing), the- * first admission-requiring backfill refuses up front with queue_capacity+ * first admission-requiring backfill refuses up front with write_quota_exhausted* and the filled capacity command before it mutates anything, and after the* limit is raised the same runner completes the chain.*/@@ -108,7 +108,7 @@ export async function runExhaustedCapacityChain(databaseUrl: string | undefined,const ledger = fixture.ledger();expect(ledger.filter(e => e.status !== 'complete').map(e => e.version)).toEqual(['0.13.1']);const detail = phaseDetail(ledger, '0.13.1', 'grandfather');- expect(detail).toStartWith('queue_capacity: Write capacity exhausted: principal permanent request IDs (0 used of 0).');+ expect(detail).toStartWith('write_quota_exhausted: Write capacity exhausted: principal permanent request IDs (0 used of 0).');expect(detail).toContain(`gbrain config set ${key} `);engine = await fixture.open();diff --git a/test/helpers/w5-scenarios.ts b/test/helpers/w5-scenarios.tsindex b1f82604fe..d28b2a3ae4 100644--- a/test/helpers/w5-scenarios.ts+++ b/test/helpers/w5-scenarios.ts@@ -26,6 +26,7 @@ import { LINK_EXTRACTOR_VERSION_TS } from '../../src/core/link-extraction.ts';import { checkParkedEffects } from '../../src/commands/doctor/checks/parked-effects.ts';import { checkPersistenceCapacity } from '../../src/commands/doctor/checks/persistence-capacity.ts';import { managedBrain } from './managed-brain.ts';+import { CODES } from '../../src/core/error-registry.ts';import { durableGitRepo, git } from './git-publication.ts';const put = (ctx: OperationContext, slug: string, body: string, type = 'note') => submitPageMutation(ctx, { operation: 'put_page',@@ -190,9 +191,19 @@ export async function capacityWarnsAndRefusalNamesTheKey(databaseUrl?: string) {expect(value).toBeGreaterThanOrEqual(20);expect(warning.message).toContain(details.commands[0]);- await put(ctx, 'notes/cap-8', 'Cap 8.'); await put(ctx, 'notes/cap-9', 'Cap 9.');- const refusal = await put(ctx, 'notes/cap-10', 'Cap 10.').then(() => null, error => error);- expect(refusal).toMatchObject({ code: 'queue_capacity', detail: 'principal_lifetime_ids' });+ // #6696 (A5): past the 80% pause line a background write refuses before any receipt; the user's own writes keep the rest.+ const paused = await put(ctx, 'notes/cap-8', 'Cap 8.').then(() => null, error => error);+ expect(paused).toMatchObject({ code: 'write_capacity_backpressure', reason: 'lifetime_ids', detail: 'principal_lifetime_ids' });+ expect(CODES[paused.code as keyof typeof CODES]).toMatchObject({ class: 'host_only', retryable: false });+ expect(await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE slug='notes/cap-8'")).toEqual([]);+ const interactive = { ...ctx, admissionOrigin: 'interactive' as const };+ await put(interactive, 'notes/cap-8', 'Cap 8.'); await put(interactive, 'notes/cap-9', 'Cap 9.');+ const refusal = await put(interactive, 'notes/cap-10', 'Cap 10.').then(() => null, error => error);+ // #6696 (A6): the cumulative wall has its own host-only code, and the fix is the reversible raise, verified by the capacity check.+ expect(refusal).toMatchObject({ code: 'write_quota_exhausted', reason: 'lifetime_ids', detail: 'principal_lifetime_ids',+ fix: { argv: ['gbrain', 'config', 'set', 'persistence.limits.principal_lifetime_ids', expect.stringMatching(/^\d+$/)], actor: 'host_admin',+ verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'] } } });+ expect(CODES[refusal.code as keyof typeof CODES]).toMatchObject({ class: 'host_only', retryable: false });expect(refusal.message).toContain('10 used of 10');expect(refusal.suggestion).toMatch(/gbrain config set persistence\.limits\.principal_lifetime_ids \d+/);}, { databaseUrl });diff --git a/test/migrations-v0_32_2-managed.test.ts b/test/migrations-v0_32_2-managed.test.tsindex b22a04b497..9b25620b3d 100644--- a/test/migrations-v0_32_2-managed.test.ts+++ b/test/migrations-v0_32_2-managed.test.ts@@ -206,7 +206,7 @@ for (const backend of testBackends()) {const file = readFileSync(join(root, `${LEGACY_FILE_SLUG}.md`), 'utf8');const phase = await __testing.phaseBFenceFacts(engine, OPTS);expect(phase).toMatchObject({ name: 'fence_facts', status: 'failed' });- expect(phase.detail).toStartWith('queue_capacity: Write capacity exhausted: principal permanent request IDs (0 used of 0).');+ expect(phase.detail).toStartWith('write_quota_exhausted: Write capacity exhausted: principal permanent request IDs (0 used of 0).');expect(phase.detail).toContain('gbrain config set persistence.limits.principal_lifetime_ids ');expect(await factRows(engine, [...seed.legacyFactIds, ...seed.dbOnlyFactIds])).toEqual(before);expect(readFileSync(join(root, `${LEGACY_FILE_SLUG}.md`), 'utf8')).toBe(file);diff --git a/test/persistence-background-pause.test.ts b/test/persistence-background-pause.test.tsnew file mode 100644index 0000000000..cf0f93a645--- /dev/null+++ b/test/persistence-background-pause.test.ts@@ -0,0 +1,112 @@+/**+ * #6696 (A5): near a cumulative cap a background admission refuses+ * `write_capacity_backpressure` before any receipt exists, while an+ * interactive admission keeps the rest; a surrounding background scope wins+ * over an inner interactive caller; one config key sets the line; doctor+ * names the paused producers. Both backends.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+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 { submissionAuthority } from '../src/core/persistence/authority.ts';+import { admitWriteGroupInTransaction } from '../src/core/persistence/journal.ts';+import { BACKGROUND_PAUSE_KEY, BACKGROUND_PRODUCERS, resolveAdmissionOrigin, withAdmissionOrigin } from '../src/core/persistence/admission-origin.ts';+import { checkPersistenceCapacity } from '../src/commands/doctor/checks/persistence-capacity.ts';+import { 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 count = async (engine: BrainEngine) => Number((await engine.executeRaw<{ n: string }>('SELECT count(*)::text AS n FROM persistence_requests'))[0]!.n);+const lifetime = async (engine: BrainEngine) => Number((await engine.executeRaw<{ n: string }>(+ "SELECT lifetime_ids::text AS n FROM persistence_counters WHERE key LIKE 'principal:%'"))[0]!.n);++test('a surrounding background scope wins; unset is background', () => {+ expect(resolveAdmissionOrigin()).toBe('background');+ expect(resolveAdmissionOrigin('interactive')).toBe('interactive');+ expect(withAdmissionOrigin('interactive', () => resolveAdmissionOrigin())).toBe('interactive');+ expect(withAdmissionOrigin('background', () => resolveAdmissionOrigin('interactive'))).toBe('background');+ expect(withAdmissionOrigin('background', () => withAdmissionOrigin('interactive', () => resolveAdmissionOrigin('interactive')))).toBe('background');+});++for (const kind of testBackends()) {+ describe(`background pause ${kind}`, () => {+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;+ let scratch: string;+ beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), 'gbrain-pause-'));+ factory = await freshBrainFactory(kind, databaseUrl);+ }, 120_000);+ afterAll(async () => {+ await factory?.dispose();+ if (scratch) rmSync(scratch, { recursive: true, force: true });+ });+ 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 background admission past the line refuses with no receipt; an interactive one is admitted', async engine => {+ const requests = await requestFixture(engine);+ for (let i = 0; i < 3; i++) await requests.admit(`p${i}`);+ await engine.setConfig('persistence.limits.principal_lifetime_ids', '5');+ await engine.setConfig(BACKGROUND_PAUSE_KEY, '0.6');+ const before = await count(engine);+ const refusal = await requests.admit('p3').then(() => null, error => error);+ expect(refusal).toMatchObject({ code: 'write_capacity_backpressure', reason: 'lifetime_ids', detail: 'principal_lifetime_ids' });+ expect(CODES.write_capacity_backpressure).toMatchObject({ class: 'host_only', retryable: false });+ expect(refusal.message).toContain('60% pause line');+ expect(await count(engine)).toBe(before);+ expect(await lifetime(engine)).toBe(3);+ // The same admission under the user's own origin keeps the rest.+ const admitted = await withAdmissionOrigin('interactive', () => requests.admit('p3'));+ expect(admitted.slug).toBe('p3');+ expect(await lifetime(engine)).toBe(4);+ // An interactive caller inside a background scope stays background.+ const scoped = await withAdmissionOrigin('background', () => withAdmissionOrigin('interactive', () => requests.admit('p4'))).then(() => null, error => error);+ expect(scoped).toMatchObject({ code: 'write_capacity_backpressure' });+ // Raising the line to the cap lifts the pause; the cap itself still answers write_quota_exhausted.+ await engine.setConfig(BACKGROUND_PAUSE_KEY, '1');+ await requests.admit('p4');+ expect(await requests.admit('p5').then(() => null, error => error)).toMatchObject({ code: 'write_quota_exhausted' });+ });++ check('a background group admission counts every fresh member against the line', async engine => {+ const requests = await requestFixture(engine);+ await requests.admit('g0');+ await engine.setConfig('persistence.limits.principal_lifetime_ids', '10');+ await engine.setConfig(BACKGROUND_PAUSE_KEY, '0.5');+ const members = async (n: number) => Promise.all(Array.from({ length: n }, async (_, i) => {+ const slug = `g-${i}-${randomUUID()}`;+ const authority = await submissionAuthority(requests.ctx, 'put_page', requests.sourceId, requests.incarnation, slug);+ return { principal: authority.principal, authority, operation: 'put_page', sourceId: requests.sourceId, sourceIncarnation: requests.incarnation,+ slug, requestId: randomUUID(), callerIntent: { body: slug }, intent: { body: slug } };+ }));+ const five = await members(5), four = await members(4);+ const refusal = await engine.transaction(tx => admitWriteGroupInTransaction(tx, five)).then(() => null, error => error);+ expect(refusal).toMatchObject({ code: 'write_capacity_backpressure', reason: 'lifetime_ids' });+ expect(await lifetime(engine)).toBe(1);+ const admitted = await engine.transaction(tx => admitWriteGroupInTransaction(tx, four));+ expect(admitted).toHaveLength(4);+ expect(await lifetime(engine)).toBe(5);+ });++ check('doctor names the paused producers once a scope passes the line, and a fresh brain stays ok', async engine => {+ expect(await checkPersistenceCapacity(engine)).toMatchObject({ status: 'ok', details: { paused_producers: [] } });+ const requests = await requestFixture(engine);+ for (let i = 0; i < 4; i++) await requests.admit(`d${i}`);+ await engine.setConfig('persistence.capacity.warn_days', '0'); await engine.setConfig('persistence.capacity.fail_days', '0');+ await engine.setConfig('persistence.limits.principal_lifetime_ids', '100');+ await engine.setConfig(BACKGROUND_PAUSE_KEY, '0.03');+ const paused = await checkPersistenceCapacity(engine);+ expect(paused.status).toBe('warn');+ expect(paused.details).toMatchObject({ background_pause_pct: 3, paused_producers: [...BACKGROUND_PRODUCERS] });+ expect(paused.message).toContain('Background writes are paused past 3%');+ expect(paused.message).toContain('write_capacity_backpressure');+ });+ });+}diff --git a/test/persistence-topology-quotas.test.ts b/test/persistence-topology-quotas.test.tsindex b78c96ad9c..8a82a7915a 100644--- a/test/persistence-topology-quotas.test.ts+++ b/test/persistence-topology-quotas.test.ts@@ -77,6 +77,17 @@ test('recovering clones share principal and brain outstanding quotas with ordinaexpect((await counters(engine, 'brain')).outstanding_count).toBe(0);}), 120_000);+test('#6696 (A6): a lifecycle receipt past a cumulative cap refuses write_quota_exhausted with the host raise', () => fixture(async (engine, _home, principal, worktree) => {+ await engine.setConfig('persistence.limits.brain_lifetime_ids', '0');+ await expect(record(engine, principal, worktree, { operation: 'reclone', sourceId: 'quota-source' })).rejects.toMatchObject({ code: 'write_quota_exhausted',+ reason: 'lifetime_ids', detail: 'brain_lifetime_ids', fix: { actor: 'host_admin', argv: ['gbrain', 'config', 'set', 'persistence.limits.brain_lifetime_ids', expect.stringMatching(/^\d+$/)] } });+ await engine.setConfig('persistence.limits.brain_lifetime_ids', '10');+ await engine.setConfig('persistence.limits.principal_terminal_bytes', '100');+ await expect(record(engine, principal, worktree, { operation: 'reclone', sourceId: 'quota-source' })).rejects.toMatchObject({ code: 'write_quota_exhausted',+ reason: 'terminal_bytes', detail: 'principal_terminal_bytes' });+ expect(await engine.executeRaw('SELECT id FROM persistence_topology_changes')).toHaveLength(0);+}), 120_000);+test('normalized intent bytes are exact and release once even after principal revocation', () => fixture(async (engine, _home, principal, worktree) => {const intent = { operation: 'reclone', sourceId: 'quota-source', ignored: undefined, config: { note: 'Example café' } };const bytes = jsonBytes(intent);diff --git a/test/put-pages-batch.test.ts b/test/put-pages-batch.test.tsindex 29aa28b0f2..f8b775f915 100644--- a/test/put-pages-batch.test.ts+++ b/test/put-pages-batch.test.ts@@ -130,6 +130,20 @@ describe('put_pages', () => {}});+ test('#6696 (A6): a batch past a cumulative cap refuses write_quota_exhausted with the host raise, not the outstanding wait', async () => {+ const [{ used }] = await engine.executeRaw<{ used: number }>("SELECT COALESCE(max(lifetime_ids),0)::int AS used FROM persistence_counters WHERE key LIKE 'principal:%'");+ await engine.setConfig(journalLimitKey('principalLifetimeIds'), String(used + 2));+ try {+ const refusal = await putPages.handler({ ...ctx(), admissionOrigin: 'interactive' }, { request_id: randomUUID(), wait_ms: 0,+ pages: [page('notes/w1'), page('notes/w2'), page('notes/w3')] }).then(() => null, error => error);+ expect(refusal).toMatchObject({ code: 'write_quota_exhausted', reason: 'lifetime_ids', fix: { actor: 'host_admin' } });+ expect(refusal.suggestion).not.toContain('Wait for this connection');+ expect(await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE slug LIKE 'notes/w%'")).toEqual([]);+ } finally {+ await engine.unsetConfig(journalLimitKey('principalLifetimeIds'));+ }+ });+test('every page needs put_page permission', async () => {const clientId = 'put-pages-batch-only';await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,scope,source_id,allowed_operations)diff --git a/test/serve-sync-handoff.serial.test.ts b/test/serve-sync-handoff.serial.test.tsindex 59ed0e8bb4..e3b149579a 100644--- a/test/serve-sync-handoff.serial.test.ts+++ b/test/serve-sync-handoff.serial.test.ts@@ -322,6 +322,19 @@ describe('maybeDelegateManagedSyncToServe (the Postgres ladder, client half)', (expect(n).toBe(0);}), 120_000);+ test('#6696 (A5): the CLI sends origin interactive in the delegation payload', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const f = await fixture(1);+ const origins: unknown[] = [];+ captureStderr();+ const result = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ sock: await serveSocket({ sync_start: (req) => {+ origins.push((req.options as { origin?: unknown }).origin);+ return { ok: false, protocol: 2 as const, error: 'busy' };+ } }) }));+ releaseStderr();+ expect(origins).toEqual(['interactive']);+ expect(result).toMatchObject({ kind: 'own_consumer', reason: 'serve_refused' });+ }), 120_000);+test('a wrong IPC secret (unauthorized) falls back; the serve bound to another source (source_mismatch) falls back', async () => withEnv({ GBRAIN_HOME: home }, async () => {const f = await fixture(1);captureStderr();diff --git a/test/sync-runbook-table.test.ts b/test/sync-runbook-table.test.tsindex bacce9056c..42901e8638 100644--- a/test/sync-runbook-table.test.ts+++ b/test/sync-runbook-table.test.ts@@ -22,3 +22,12 @@ test('docs/guides/sync-unblock-runbook.md renders SYNC_FAULT_TABLE verbatim', ()const expected = SYNC_FAULT_TABLE.map(rule => ({ code: rule.code, class: rule.class, safe_actions: [...rule.safe_actions], needs_human: rule.needs_human, escalate: rule.escalate }));expect(rows).toEqual(expected);});++test('#6696 (A5/A6): the background pause is a wait; the full or too-small cap needs the host', async () => {+ const { classifySyncFault } = await import('../src/core/persistence/sync-fault-class.ts');+ expect(classifySyncFault({ code: 'write_capacity_backpressure', detail: 'principal_terminal_bytes' })).toEqual({ class: 'connection', safe_actions: ['retry'], needs_human: false });+ for (const code of ['write_quota_exhausted', 'write_quota_insufficient']) {+ expect(classifySyncFault({ code, detail: 'brain_lifetime_ids' })).toMatchObject({ class: 'systemic', safe_actions: ['none'], needs_human: true,+ human_reason: expect.stringContaining('gbrain config set') });+ }+});