Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(facts): maintenance_backpressure also guards reserved receipt bytes and request ids
time-attack315906ad3dc4
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 72d757a3f0..11e0d4c966 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -23,7 +23,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core PersDerived atom pages may regenerate or retire when their canonical file is already absent, while ordinary page writes retain missing-file refusal.Accepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronological `valid_until` writeback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority. `submitMaintenanceIntent` admits a maintenance request with its own intent kind keyed by the intent; `prepareMaintenanceMutation` also handles `managed_maintenance_phantom_merge` and `managed_maintenance_phantom_delete` (both delegated to `cycle/phantom-redirect-managed.ts`). `publishMaintenancePage` accepts an optional `eventProjection` (Life Chronicle): the event page and its depth-page timeline row commit in the same publication with the depth page key locked. Remote maintenance remains refused.- `src/core/persistence/derived-facts.ts` — `writeDerivedFacts`: the unmanaged conversation fact index commits in one maintenance transaction under the maintenance principal; on a managed brain it refuses with `writer_coordinator_required`, because every managed facts/takes writer publishes a receipted maintenance request (`test/receipt-coverage.test.ts` lists every coordinated write site). Tests: `test/write-attribution-misc.test.ts`.-- `src/core/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` requests (`submitDatabaseMaintenanceIntent`, dispatched from `prepareMaintenanceMutation`). `startConversationGeneration` runs before model work: the generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, `--since`/`--segment-limit`, newest extractor row id) and attempt number make the request id, so an admitted request is replayed (`settled`, zero model calls), a retryable failure resubmits its stored batch (`resubmit`), a deterministic one (`invalid_params`, `permission_denied`, size) or three failed attempts block the generation until the page changes. `buildConversationIntent` freezes the rows (`FrozenExtractedFact` shape without source, page, row number or visibility; vectors only under the brain's facts embedding signature); `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest batch cannot fit before any model call; `assertConversationAdmissionHeadroom` stops the run at 80% of `principalOutstanding` (`maintenance_backpressure`, exit 12) and checks lifetime ids. The preparer rechecks authority, page id, revision and version token (sidecar bytes), the embedding signature and alias merges, and `replaceConversationFacts` deletes the page's extractor rows and inserts the batch numbered above every remaining row, failing on a lost insert. Tests: `test/conversation-facts-managed.test.ts` (+ Postgres arm), managed-connector contract cases `extract_conversation_facts*`.+- `src/core/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` requests (`submitDatabaseMaintenanceIntent`, dispatched from `prepareMaintenanceMutation`). `startConversationGeneration` runs before model work: the generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, `--since`/`--segment-limit`, newest extractor row id) and attempt number make the request id, so an admitted request is replayed (`settled`, zero model calls), a retryable failure resubmits its stored batch (`resubmit`), a deterministic one (`invalid_params`, `permission_denied`, size) or three failed attempts block the generation until the page changes. `buildConversationIntent` freezes the rows (`FrozenExtractedFact` shape without source, page, row number or visibility; vectors only under the brain's facts embedding signature); `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest batch cannot fit before any model call; `assertConversationAdmissionHeadroom` stops admitting at 80% of the writer's outstanding requests, reserved receipt bytes or lifetime ids (`maintenance_backpressure`, exit 12, naming the resource and a `--limit` that fits), up front for the whole planned run and again before each page. The preparer rechecks authority, page id, revision and version token (sidecar bytes), the embedding signature and alias merges, and `replaceConversationFacts` deletes the page's extractor rows and inserts the batch numbered above every remaining row, failing on a lost insert. Tests: `test/conversation-facts-managed.test.ts` (+ Postgres arm), managed-connector contract cases `extract_conversation_facts*`.- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. Fence refusals are typed `invalid_fence` (`fence-repair/refusal.ts`): `compileCanonicalProjections`, the validation-only entry, refuses the first defect `scanCanonicalFences` finds (repeated marker, any strict-parser warning, a row number used twice on the page) with wire `invalid_params`; a new fence row whose number belongs to a database-only take refuses as `stored_row_collision` with wire `take_row_collision`. When the prior takes fence does not parse, the page's stored `takes.row_num` count as prior canonical rows (TE1), so a row Tier 1 normalized updates its take instead of colliding. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres). A write that would drop rows held by a fence quoted in markdown code (readers project nothing from it) is refused as `invalid_fence` / `quoted_fence_rows` instead of deleting them. Pinned by `test/fence-marker-projection.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 80a0413bc5..f57f2e1225 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1466,7 +1466,7 @@ More: [docs/guides/repair.md#legacy-jobs-active](../../docs/guides/repair.md#leg| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| Managed maintenance stopped admitting requests because this writer's outstanding requests reached 80% of its limit; nothing more was submitted. | Each page of a maintenance run publishes as its own request. Stopping well below principalOutstanding leaves room for the writer's other work and keeps a slow consumer from turning the run into refused admissions. | Wait briefly, then retry the same request (writes: reuse the same request_id). Run: gbrain sources writer status --source '{source_id}' --json | agent | `repeat the read that failed` | 12 | yes |+| Managed maintenance stopped admitting requests because this writer's outstanding requests, reserved receipt bytes or permanent request ids would pass 80% of their limit; nothing more was submitted. | Each page of a maintenance run publishes as its own request under the local CLI writer the user's own CLI writes share. Stopping at 80% leaves room for those writes: reserved receipt bytes free only when receipts compact, request ids never. | Wait briefly, then retry the same request (writes: reuse the same request_id). Run: gbrain sources writer status --source '{source_id}' --json | agent | `repeat the read that failed` | 12 | yes |More: [docs/guides/write-refusals.md#maintenance_backpressure](../../docs/guides/write-refusals.md#maintenance_backpressure)diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 0fb57760a4..a620407a07 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -69,7 +69,7 @@ of making a duplicate.| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | `gbrain sources refresh <source>` (the printed `fix` fills in the source). It drains writes to the source's checkout, fast-forwards it to its upstream and runs the managed sync for every source bound to that checkout; see [worktree refresh refusals](#worktree-refresh-refusals) for what it can refuse. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. || <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). || <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |-| <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. Before each page's model work it checks this CLI writer's outstanding requests; at 80% of `persistence.limits.principal_outstanding` it stops admitting, so a slow or absent consumer cannot turn the run into refused admissions. Pages already published keep their facts and nothing is half-written. | Read the pending requests with `gbrain sources writer status --source <id> --json`. A resident `gbrain serve`, or the next CLI run, publishes them; once they settle, rerun the same command. Raising `persistence.limits.principal_outstanding` is the user's call. |+| <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. |### Other error codesdiff --git a/docs/w9f/R.md b/docs/w9f/R.mdindex 36ffd3c633..9cda1a7525 100644--- a/docs/w9f/R.md+++ b/docs/w9f/R.md@@ -16,11 +16,12 @@ lines below when the PR is next to merge.- Managed brains now extract facts from email threads, and record singleemails, prose meeting notes and undated pages as "not extractable" for goodinstead of rescanning them every run.-- `gbrain extract-conversation-facts` on a managed brain stops admitting at- 80% of the writer's outstanding-request limit (`maintenance_backpressure`,- exit 12), skips a page whose largest batch cannot fit one request before any- model call, and refuses up front when the writer's permanent request ids- cannot cover the run.+- `gbrain extract-conversation-facts` on a managed brain stops admitting once+ the writer's outstanding requests, reserved receipt bytes or permanent+ request ids would pass 80% of their limit (`maintenance_backpressure`,+ exit 12; the message names the resource and a `--limit` that fits), checked+ up front for the whole planned run and again before each page, and skips a+ page whose largest batch cannot fit one request before any model call.- The cycle `extract_facts` fence reconcile, its deleted-page fact expiry,`gbrain extract takes --source db` / `gbrain takes rebuild` / the v0.28.0takes backfill, and `gbrain repair take-supersession`'s database branch now@@ -61,18 +62,27 @@ model calls). Script: `~/.capy/work/w9f-r/scratch/measure-d9.test.ts`| Measure | Per request | Per 1k pages | 50k pages | Share of default limit ||---|---|---|---|---|| Permanent request ids | 1 | 1,000 | 50,000 | 20% of `principalLifetimeIds` (250,000) |-| Intent bytes (transient; released when the request settles) | avg 96 KB, max 191 KB | 96 MB (one at a time) | - | per request well under `principalIntentBytes` (32 MiB) |-| Reserved receipt bytes (30-day window) | 16 KiB | 16 MiB | 819 MB | 51% of `principalTerminalBytes` (1,536 MiB) |+| Intent bytes (transient; released when the request settles, stored intent dropped at compaction) | fact batch avg 128 KB (5 rows, 1536-dim vectors), outcome-only 1.5 KB | - | - | per request well under `principalIntentBytes` (32 MiB) |+| Reserved receipt bytes (until compaction, 30-day window) | 16,384 B flat, whatever the payload | 16 MiB | 781 MiB | 51% of `principalTerminalBytes` (1,536 MiB) |+| Retained receipt bytes (after compaction) | about 1.75 KB (1,743 B outcome-only, 1,754 B fact batch) | 1.7 MB | 87 MB | about 5.5% of `principalTerminalBytes`, long-term |++Breakdown (second run, same corpus, receipts force-compacted;+`~/.capy/work/w9f-r/scratch/measure-d9b.test.ts`, output+`~/.capy/work/w9f-r/out/d9-breakdown.json`): 50 of the 200 requests (25%)+were outcome-only (prose; no vectors) and 150 (75%) carried fact batches.+Request ids and reserved receipt bytes are charged per request, not per+payload byte, so each request type's share of the 20% and the 51% equals its+share of requests. Vectors only affect intent bytes.One request id per page per extraction generation (each later page edit addsone). At 50k pages the backfill alone uses 20% of the writer's permanentrequest ids, above Decision 9's 10% switch threshold, and reserves half of-its receipt bytes for the retention window (compacted receipts keep about-4 KiB each, about 13% long term). Per Decision 9 (A) this wave keeps outcomes-as receipted facts rows and reports the number; the threshold is crossed, so-Garry's call on 9B (a non-guarded outcome side table for-non-extractable/terminal outcomes) or batching outcomes across pages is the-follow-up.+its receipt bytes for the retention window. The writer is the local CLI+principal the user's own CLI writes share, and outcome-only pages cost $0, so+no spend cap limits them; `maintenance_backpressure` therefore also stops at+80% of reserved receipt bytes and request ids. Per Decision 9 (A) this wave+keeps outcomes as receipted facts rows; the threshold is crossed, so batching+vs 9B (a non-guarded outcome side table) is Garry's call.## Functions touched in GBRA-52's file (`src/commands/extract-conversation-facts.ts`)diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 83bcc4386d..76df2a0c99 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -215,7 +215,7 @@ export const CODES = {local_conflict: { class: 'caller', summary: "A local file or registration conflicts with the requested change." },lock_busy: { class: 'retryable', summary: "Another process holds the lock this command needs." },managed_pull_skipped: { class: 'retryable', summary: "The managed pull was skipped." },- maintenance_backpressure: { class: 'retryable', summary: "Managed maintenance stopped admitting requests because this writer's outstanding requests reached 80% of its limit; nothing more was submitted.", why: "Each page of a maintenance run publishes as its own request. Stopping well below principalOutstanding leaves room for the writer's other work and keeps a slow consumer from turning the run into refused admissions.", docs: 'docs/guides/write-refusals.md#maintenance_backpressure', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the pending requests holding this writer's capacity, read-only.", requires_exclusive: false }, exit: 12 },+ maintenance_backpressure: { class: 'retryable', summary: "Managed maintenance stopped admitting requests because this writer's outstanding requests, reserved receipt bytes or permanent request ids would pass 80% of their limit; nothing more was submitted.", why: "Each page of a maintenance run publishes as its own request under the local CLI writer the user's own CLI writes share. Stopping at 80% leaves room for those writes: reserved receipt bytes free only when receipts compact, request ids never.", docs: 'docs/guides/write-refusals.md#maintenance_backpressure', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the pending requests holding this writer's capacity, read-only.", requires_exclusive: false }, exit: 12 },membership_inactive: { class: 'caller', summary: "The shared-skills enrollment epoch was left or superseded.", docs: 'docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollment' },membership_not_found: { class: 'caller', summary: "This principal has no shared-skills membership with that installation id.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },method_not_allowed: { class: 'caller', summary: "The HTTP method is not allowed on this endpoint." },diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.tsindex a68dcca96c..8425be7d02 100644--- a/src/core/facts/conversation-publication.ts+++ b/src/core/facts/conversation-publication.ts@@ -46,7 +46,7 @@ import { opError, OperationError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import { authorizeStoredRequest, authorizeWrite } from '../persistence/authority.ts';import { digest, jsonBytes } from '../persistence/digest.ts';-import { assertLifetimeIdHeadroom, getWriteRequest } from '../persistence/journal.ts';+import { getWriteRequest } from '../persistence/journal.ts';import { readJournalLimits } from '../persistence/limits.ts';import { principalKey } from '../persistence/model.ts';import { PERSISTENCE_IPC_MAX_BYTES } from '../persistence/ipc.ts';@@ -57,12 +57,13 @@ import { loadConfig } from '../config.ts';import { waitForWrite, writeResponse } from '../persistence/service.ts';import { catalogueError } from '../error-catalogue.ts';import { CONVERSATION_EXTRACTOR_VERSION, NON_EXTRACTABLE_AUDIT_SOURCE, TERMINAL_AUDIT_SOURCE } from './audit-sources.ts';+import { ALLOWED_TYPES, pageTypesForAllowed, type AllowedType } from './conversation-types.ts';export const CONVERSATION_FACTS_INTENT = 'managed_maintenance_conversation_facts';export const CONVERSATION_FACTS_PROTOCOL = 1;export const CONVERSATION_FACTS_SOURCE_PREFIX = 'cli:extract-conversation-facts';export const MAX_GENERATION_ATTEMPTS = 3;-/** Admission stops once the principal's outstanding requests reach this share of `principalOutstanding`. */+/** Admission stops once the principal's outstanding requests, reserved receipt bytes or request ids reach this share of their limit. */export const OUTSTANDING_ADMISSION_SHARE = 0.8;/** Facts per segment the extractor returns at most (extractFactsFromTurn's default maxFactsPerTurn). */const MAX_FACTS_PER_SEGMENT = 10;@@ -203,22 +204,62 @@ export async function conversationIntentByteLimit(engine: BrainEngine): Promise<}/**- * Before a page's model work: stop the run once this principal's outstanding- * requests reach OUTSTANDING_ADMISSION_SHARE of its limit, and refuse when- * its permanent request ids cannot cover `needed` more admissions.+ * 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 admissions up+ * front, 1 before each page.*/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 }>(- 'SELECT outstanding_count FROM persistence_counters WHERE key=$1', [principalKey(authority.writer.principal)]);+ 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);- const ceiling = Math.max(1, Math.floor(limits.principalOutstanding * OUTSTANDING_ADMISSION_SHARE));- if (outstanding >= ceiling) {+ if (outstanding >= share(limits.principalOutstanding)) {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 ${authority.writer.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.`);+ `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.`);+ }+ const reservation = Math.max(16_384, jsonBytes(authority.writer) + 8192);+ 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);+ if (r.used + needed * r.per <= ceiling) continue;+ const room = Math.max(0, Math.floor((ceiling - r.used) / r.per));+ 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.`);}- await assertLifetimeIdHeadroom(engine, authority.writer.principal, needed);+}++/**+ * The admissions a run plans: the named pages, or every page of the+ * conversation types (`opts.types`, else all) that has no active outcome yet+ * (`--force`: every such page), capped by `--limit`.+ */+async function plannedAdmissions(engine: BrainEngine, sourceId: string,+ opts: { slugs?: string[]; slug?: string; limit?: number; force?: boolean; types?: readonly AllowedType[] }): Promise<number> {+ if (opts.slugs) return opts.slugs.length;+ if (opts.slug) return 1;+ const [row] = await engine.executeRaw<{ n: number | string }>(`SELECT count(*)::int AS n FROM pages p+ WHERE p.source_id=$1 AND p.deleted_at IS NULL AND p.type=ANY($2::text[])+ AND ($3::boolean OR NOT EXISTS (SELECT 1 FROM facts f WHERE f.source_id=p.source_id AND f.source_markdown_slug=p.slug+ AND f.source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%' AND f.source IN ($4,$5) AND f.expired_at IS NULL))`,+ [sourceId, pageTypesForAllowed(opts.types ?? ALLOWED_TYPES), opts.force === true, TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE]);+ const backlog = Number(row?.n ?? 0);+ return Math.max(1, opts.limit ? Math.min(opts.limit, backlog) : backlog);}function freezeRow(row: ConversationFactRow): FrozenConversationFact {@@ -419,11 +460,11 @@ interface PageSnapshot { page: Page; versionToken: string }* admissions fit the writer's request capacity.*/export async function managedConversationPublisher(engine: BrainEngine, sourceId: string,- opts: { dryRun?: boolean; slugs?: string[]; slug?: string; limit?: number }): Promise<ManagedConversationPublisher | null> {+ opts: { dryRun?: boolean; slugs?: string[]; slug?: string; limit?: number; force?: boolean; types?: readonly AllowedType[] }): Promise<ManagedConversationPublisher | null> {if (opts.dryRun || !await managedPersistenceEnabled(engine)) return null;const authority = (await maintenancePreflight(engine, sourceId))!;const config = loadConfig() ?? { engine: engine.kind };- await assertConversationAdmissionHeadroom(engine, authority, opts.slugs?.length ?? (opts.slug ? 1 : opts.limit ?? 1));+ await assertConversationAdmissionHeadroom(engine, authority, await plannedAdmissions(engine, sourceId, opts));return { engine, authority, config, embedding: await resolveManagedFactsEmbedding(engine, config) };}diff --git a/test/conversation-facts-managed.test.ts b/test/conversation-facts-managed.test.tsindex e27e069eb2..75a4057cfc 100644--- a/test/conversation-facts-managed.test.ts+++ b/test/conversation-facts-managed.test.ts@@ -248,7 +248,7 @@ 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('queue_capacity');+ expect(lifetime?.code).toBe('maintenance_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.@@ -270,6 +270,61 @@ for (const backend of testBackends()) {expect(authority.writer.principal.kind).toBe('local_cli');}, { databaseUrl });}, 120_000);++ test(`${backend}: admission stops at 80% of the writer's reserved receipt bytes, before any model call`, async () => {+ await managedBrain(async brain => {+ const { engine } = brain;+ await putPage(brain, transcript());+ const [{ bytes }] = await engine.executeRaw<{ bytes: number }>("SELECT COALESCE(max(terminal_bytes),0)::bigint AS bytes FROM persistence_counters WHERE key LIKE 'principal:local_cli:%'");+ // One more 16 KiB reservation fits under the hard limit but crosses 80% of it.+ 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?.suggestion).toContain('persistence.limits.principal_terminal_bytes');+ 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 () => {+ await managedBrain(async brain => {+ const { engine } = brain;+ await putPage(brain, transcript());+ await maintenancePreflight(engine, 'default');+ const [{ used }] = await engine.executeRaw<{ used: number }>("SELECT COALESCE(max(lifetime_ids),0)::int AS used FROM persistence_counters WHERE key LIKE 'principal:local_cli:%'");+ 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');+ expect(calls.n).toBe(0);+ }, { databaseUrl });+ }, 120_000);++ test(`${backend}: the up-front check counts the whole planned run and names a --limit that fits`, async () => {+ await managedBrain(async brain => {+ const { engine } = brain;+ for (const day of ['28', '29', '30']) await putPage(brain, transcript().replace('Plan sync', `Plan sync ${day}`), `meetings/2026-09-${day}-plan-sync`);+ await maintenancePreflight(engine, 'default');+ const [{ used }] = await engine.executeRaw<{ used: number }>("SELECT COALESCE(max(lifetime_ids),0)::int AS used FROM persistence_counters WHERE key LIKE 'principal:local_cli:%'");+ // 80% of the limit leaves room for one admission, not the three the run plans.+ const limit = Math.ceil((used + 1) / 0.8) + 1;+ await engine.setConfig('persistence.limits.principal_lifetime_ids', String(limit));+ const room = Math.floor(limit * 0.8) - used;+ expect(room).toBeGreaterThanOrEqual(1);+ expect(room).toBeLessThan(3);+ 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?.message).toContain('3 planned');+ expect(error?.suggestion).toContain(`gbrain extract-conversation-facts --source-id default --limit ${room}`);+ expect(calls.n).toBe(0);+ }, { databaseUrl });+ }, 120_000);}test('a lost insert fails the replacement instead of committing a partial batch', async () => {