Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/capy/sync-feeder-fast-writes' into capy/6278-preparation-deadline
garrytan6f36d507b2b1
diff --cc docs/guides/write-refusals.mdindex 38f13826b5,e6f6b0277d..8dd07c5986--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@@ -71,8 -71,8 +71,9 @@@ of making a duplicate| <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="managed_raw_upload"></a>raw upload on a managed brain | `writer_coordinator_required` | `gbrain files upload-raw` of a small (git-storage) file whose `.raw/` destination is inside a managed canonical worktree. The persistence coordinator does not publish raw files yet, so the worktree refuses writes from outside it; starting a `gbrain serve` owner does not change that. The refusal comes before anything is created: no `.raw/` directory and no `files` row. With no storage backend, `file_upload` for such a page no longer suggests `upload-raw`. | Configure `storage` (supabase, s3 or local) in the gbrain config, then run the printed `gbrain files upload <file> --page <slug>`; check it with `gbrain files list <slug>`. || <a id="timeline_rows_would_be_removed"></a>`timeline_rows_would_be_removed` | `timeline_rows_would_be_removed` | A remote `put_page` (or a `put_pages` entry) has no Timeline section at all — no `<!-- timeline -->` sentinel and no `## Timeline` or `## History` heading — and would delete dated entries the page has, including rows `add_timeline_entry` added. `put_page` content replaces the whole page, so the omission must be explicit. Nothing was written. A section that is present but empty is a deliberate delete and is not refused; a local `gbrain put` without `--expected-revision` keeps the rows instead. | Re-read with `get_page include_content:true`, keep the Timeline section and resubmit with a new `request_id`; to remove every dated entry on purpose, resubmit the same content with `drop_timeline: true` (on put_pages, per entry). A successful write that deletes rows reports `timeline_rows_removed {count, earliest, latest, warning, fix}` (dates only); `get_versions` then `revert_version` restores them as new rows. |+| <a id="preparation_stalled"></a>`preparation_stalled` | `preparation_stalled` | The owner cut this write's preparation off at its deadline `persistence.max_preparation_attempts` times (default 2; `persistence.sync_preparation_ms` for a managed sync member, `persistence.maintenance_preparation_ms` for every other kind, 120 s each; a kill mid-preparation counts too), so instead of claiming it again and holding its root, it finished the request `failed`. The receipt names the last recorded step and what it was waiting on; while it was still running, `gbrain sources writer status --json` showed the same on `claim.stall` (`preparation_overdue`). The rest of the root keeps publishing. The deadlines sit behind `persistence.preparation_deadlines` (`false` restores the old behaviour, where only `remember`/`put_page`/`edit_page` had a 30 s budget). | Run `gbrain sources writer status --source <source> --json` (read-only: the step, its wait cause and the owner process), fix or report the cause, then `gbrain sources retry-held <source>` and the same `gbrain sync` with the same options. A foreground write needs a new `request_id`. || <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. |### Other error codesdiff --cc src/core/behavior-change-notice.tsindex 19eb624410,6ab9552823..2c45e44e71--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -306,11 -306,13 +306,18 @@@ export const BEHAVIOR_CHANGES: Readonly{ since: '0.60.107.0', text: 'Search-hiding and other gate-owned frontmatter keys (`quarantine`, `content_flag`, `embed_skip`, `atoms_scan_hash`, `quarantine_override`) in a local `put_page`, a connector, an ingest event or any other non-owner write are now stripped instead of kept; sync and import of your own files, reindex, repair and `gbrain quarantine clear` keep them.' },{ since: '0.60.107.0', text: 'A quarantined page is no longer offered to automatic fact extraction (`facts_backstop.skipped: quarantined`) and its facts and takes fences are not projected; rows projected before it was quarantined stay.' },{ since: '0.60.107.0', text: '`get_page` and `fetch` of a quarantined page carry `quarantined` (fetch: `metadata.quarantined`) and a `page_quarantined` notice, and remote callers get no body or text unless an admin-scoped caller passes `include_quarantined: true`; a quarantined `put_page` now reports `quarantined: { reason, detail }`.' },+ { since: '0.60.108.0', text: 'Managed brains now extract conversation facts from meetings, transcripts and email threads through receipted batch requests (up to 25 pages each), and record single emails, prose notes and undated pages as not extractable for good. Nothing runs on its own: preview with `gbrain extract-conversation-facts --source-id <id> --dry-run`. A run stops with `maintenance_backpressure` (exit 12) before the writer passes 80% of its request or receipt capacity; `gbrain sources writer status --json` shows it.' },+ { since: '0.60.108.0', text: 'Re-extracting a conversation page now keeps facts that an open loop or a superseding fact references, as expired history, instead of deleting them.' },+ { since: '0.60.108.0', text: 'Take numbers are never reused: `gbrain takes remove` leaves a struck `(removed)` row in the page, and a new take gets one more than every facts or takes row number on the page, so the first take on a page whose facts fence holds rows 1-5 is #6. Deleting the placeholder by hand frees its number again.' },+ { since: '0.60.108.0', text: 'On an unmanaged brain a dream-cycle concept whose file holds an edit the database has not imported is deferred (`revision_conflict`) and published after sync imports it, instead of being overwritten.' },+ { since: '0.60.108.0', text: 'A job error during worker shutdown now records `worker_shutdown: <handler error>` instead of bare `worker_shutdown`, and an `UnrecoverableError` thrown then dead-letters at once instead of running again.' },+ { since: '0.60.108.0', text: '`gbrain jobs supervisor stop` can now report `unverified` (exit 1) and `stale_pid_file` (exit 0, nothing signaled), and on Linux the supervisor PID file has a second line with the process start time; read only its first line.' },+ { since: '0.60.108.0', text: '`thinking: off` calls on native Google and OpenAI routes (eval judges, the synthesize triage judge, fence repair\'s model tier) now send the model\'s thinking switch (`thinkingBudget: 0`, `reasoningEffort: none`) and, where reasoning cannot be turned off (Gemini 2.5 Pro and 3.x, gpt-5/-mini/-nano, o-series), a 32,000-token reply cap; `eval takes-quality --budget-usd` and `eval cross-modal --max-usd` price that cap, so a budget that passed before can refuse earlier.' },+ // #6278 (the integrator restamps `since` to the release that ships it).+ { since: '0.60.107.0', text: 'Managed sync and maintenance writes now have a preparation deadline: a write that cannot finish preparing is released at its budget and retried once, and a second expiry finishes it `failed` with `preparation_stalled`. A managed sync holds such a file (`preparation_stalled`, listed by `gbrain sources status`) and keeps going; held content stays out of the index until `gbrain sources retry-held <id>` and the same sync re-import it. Many such stalls in one run stop it with `preparation_systemic` instead of holding every file.' },+ { since: '0.60.107.0', text: 'A foreground or maintenance write (`put_page`, `remember`, fact-fence adoption) whose preparation stalls twice now gets a terminal `preparation_stalled` receipt instead of staying `running` forever; `gbrain sources writer status` shows the step a stuck write reached (`claim.stall`).' },+ { since: '0.60.107.0', text: 'New keys `persistence.sync_preparation_ms` (120000), `persistence.maintenance_preparation_ms` (120000), `persistence.preparation_ceiling_ms` (600000) and `persistence.max_preparation_attempts` (2) bound write preparation; the `preparation_deadlines` write switch (`gbrain config set persistence.preparation_deadlines false`) turns all of it off. `persistence.max_claim_ms` keeps its doctor meaning.' },+ { since: '0.60.107.0', text: 'Fact-fence adoption (the extract_facts cycle phase and the v0.32.2 backfill) now writes the fence\'s parsed text back into `facts.fact`: a legacy claim with surrounding whitespace or CRLF line endings is adopted with that whitespace trimmed and its line endings folded to LF (the row keeps its id, vectors and provenance), a claim the fence codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or one the page already carries stays a legacy row and is reported as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: …)` and under doctor fence_integrity `unrenderable_legacy_facts`, and only the pages still holding such rows skip destructive fact reconciliation instead of the whole source.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --cc src/core/persistence/consumer.tsindex 9118f4b326,2f28679d44..d739f0c0ac--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@@ -109,12 -92,9 +109,14 @@@ export class PersistenceConsumerprivate active = new Set<Promise<void>>();/** #5373: preparations and renewals that outlived their claim; stop() drains them before the engine closes. */private outlived = new Set<Promise<void>>();+ /** #6278: preparations whose claim the budget (or a lost claim, with the switch on) released; stop() gives them ABANDONED_STOP_GRACE_MS. */+ private abandoned = new Set<Promise<void>>();+ /** #6278: abandoned preparations past the ceiling, by request row id. */+ private zombies = new Map<string, AbandonedPreparation>();+ private policy: EffectivePreparationPolicy = { ...DEFAULT_PREPARATION_POLICY, deadlines: true };private activeRoots = new Set<string>();+ /** #5984 Phase 4.5: active roots whose only task is a foreground write publishing beside this process's lane groups. */+ private besideLanes = new Set<string>();/** #5984 lanes: running lane tasks per worktree. */private laneTasks = new Map<string, number>();private foregroundCounts = new Map<string, number>();@@@ -477,10 -448,10 +479,12 @@@WHERE state='queued' AND blocked_reason IS DISTINCT FROM 'writer_pool_capacity' AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, undefined, { signal }));return;}+ // #6278: at the zombie cap this process claims nothing more; status() says restart_required and the drain ends.+ if (this.restartRequired()) return;const concurrency = this.opts.concurrency ?? 2;- const attemptedRoots = new Set([...this.activeRoots, ...this.laneTasks.keys(), ...this.rootRetryAfter.keys()]);+ // #5984: on a root whose lane groups run here, only a foreground write is claimed, to publish beside them.+ const laneRootKeys = [...this.laneTasks.keys()];+ const attemptedRoots = new Set([...this.activeRoots, ...this.rootRetryAfter.keys()]);while (!this.stopping && this.active.size - this.laneTaskCount() < concurrency) {const claimed = laneClaim();try {diff --cc src/core/persistence/fault-points.tsindex 074b61a0d2,71a3f0706e..f63a266ecc--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@@ -15,13 -15,8 +15,13 @@@ import type { WriteRequest } from './moexport type PublicationBoundary = Parameters<NonNullable<PublicationHooks['boundary']>>[0];export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${EffectKind}:mid`| 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'sync:before_group_admission' | 'sync:mid_waiver_run' | 'consumer:prepared'- | 'consumer:preparing';- | 'lane:applied';-export interface FaultDetail { requestId?: string; effectId?: string | number; sourceId?: string; operation?: string | null }++ | 'consumer:preparing' | 'lane:applied';+/**+ * `signal` (#6278, `consumer:preparing` only): the preparation's abort signal, so+ * a stalling hook can model both the reporter's cases: a preparer that honours+ * cancellation (settle on abort) and one that ignores it (hang on).+ */+export interface FaultDetail { requestId?: string; effectId?: string | number; sourceId?: string; operation?: string | null; signal?: AbortSignal }type FaultHook = (point: FaultPoint, detail: FaultDetail) => Promise<void> | void;/** The mid-effect seam of every effect kind; a new kind without one fails typecheck. */diff --cc src/core/persistence/group-publish.tsindex 17ef15fa08,0406dd94fa..c8304c1247--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@@ -35,15 -35,14 +35,15 @@@ import type { BrainEngine } from '../enimport { OperationError } from '../ops/contract.ts';import { authorizeStoredRequest, storedAuthorizationReads } from './authority.ts';import { localHostId } from './identity.ts';- import { acquireWorktree, acquireWorktreeShared, getWorktreeBinding, guardOwnership } from './ownership.ts';- import { awaitLaneBegin, awaitLaneTurn, LaneAbort, laneApplyBegin, laneClaimed, laneFinished, stepDownLanes, type LaneState } from './sync-lanes.ts';+ import { acquireWorktree, acquireWorktreeShared, getWorktreeBinding, guardOwnership, joinWorktreeLease } from './ownership.ts';+ import { awaitLaneBegin, awaitLaneTurn, LaneAbort, laneApplyBegin, laneClaimed, laneFinished, lanePolicy, stepDownLanes, type LaneState } from './sync-lanes.ts';import { cancelRows, windowPredecessor } from './sync-window.ts';-import { clearResolvedRecoveries, completeWrite, ENSURE_COUNTERS_SQL, getWriteRequestById, LOCK_COUNTERS_SQL, markRecovering, prepareRecoveries,+import { clearResolvedRecoveries, completeWrite, ENSURE_COUNTERS_SQL, getWriteRequestById, LOCK_COUNTERS_SQL, markDispatched, markRecovering, prepareRecoveries,- publicationGroupKey, reclaimReleasedWrite, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';+ foregroundPriority, publicationGroupKey, reclaimReleasedWrite, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';import { principalKey, requestPrincipal, type FileRecoveryRecord, type WriteRequest } from './model.ts';import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';-import { claimPhaseStamp, enterClaimPhase, startClaimPhase } from './claim-phase.ts';+import { claimPhaseStamp, enterClaimPhase, startClaimPhase, type ClaimPhaseClock } from './claim-phase.ts';+import { DEFAULT_PREPARATION_POLICY, preparationBudgetMs, startPreparation, type PreparationPolicy, type PreparationRun } from './preparation-budget.ts';import { setMemberAttribution, withCoordinatedWrite } from './context.ts';import { requestAttribution } from './attribution.ts';import { tryAcquirePublicationCapacity } from './pool-capacity.ts';diff --cc src/core/persistence/prepared-maintenance.tsindex ce6f85972b,bbaf11d911..843df8bfe3--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@@ -360,12 -361,16 +386,18 @@@ export async function applyPreservingTareturn outcome;}-export async function prepareMaintenanceMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {+/** `clock` (#6278): the claim's phase clock, threaded to the page and adoption preparers' step boundaries. */+export async function prepareMaintenanceMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, clock?: ClaimPhaseClock): Promise<PreparedMutation> {if (row.authority.remote) throw trustedCliRequired('Remote maintenance publication is not supported.');+ enterClaimStep(clock, 'maintenance_dispatch');if (row.intent?.kind === 'managed_maintenance_restore_extractor_facts') return (await import('../repair/extractor-facts.ts')).prepareExtractorFactsRestore(engine, row);if (row.intent?.kind === 'managed_maintenance_expire_captured_facts') return (await import('../repair/captured-facts.ts')).prepareCapturedFactsExpiry(engine, row);+ if (row.intent?.kind === 'managed_maintenance_conversation_label_retire') return (await import('../repair/conversation-labels.ts')).prepareConversationLabelRetirement(engine, row);+ if (row.intent?.kind === 'managed_maintenance_conversation_facts') return (await import('../facts/conversation-publication.ts')).prepareConversationFactsPublication(engine, row, config);+ if (row.intent?.kind === 'managed_maintenance_fence_facts') return (await import('../cycle/extract-facts.ts')).prepareFenceFactsReconcile(engine, row, config);+ if (row.intent?.kind === 'managed_maintenance_deleted_page_facts_expire') return (await import('../cycle/extract-facts.ts')).prepareDeletedPageFactsExpiry(engine, row);+ if (row.intent?.kind === 'managed_maintenance_takes_reextract') return (await import('../cycle/extract-takes.ts')).prepareTakesReextract(engine, row);+ if (row.intent?.kind === 'managed_maintenance_take_reproject') return (await import('../repair/take-supersession.ts')).prepareTakeReprojection(engine, row);if (row.intent?.kind === 'managed_maintenance_timeline_extract') return (await import('../../commands/extract-timeline-db.ts')).prepareTimelineExtract(engine, row);if (row.intent?.kind === 'managed_maintenance_page') {const prepared = await preparePageMutation(engine, row.intent.expected_revision === nulldiff --cc src/core/persistence/sync-run.tsindex 519973b7eb,f53e1b891b..0eaa4049c0--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@@ -746,14 -582,19 +749,19 @@@ async function waiveRun(engine: BrainEnassertActive();const run: WaiverRunEntry[] = [{ pending: head, waived: first }];const max = Math.max(1, Math.min(WAIVER_RUN_MAX, limit));+ // Each entry is frozen and screened in its own chain, WAIVER_SCREEN_WIDTH at a time (reads only, so the entries+ // past the first that is not waived are discarded unused).extend: for (let next = cursor.index + 1; run.length < max && next < cursor.entries.length;) {- const batch = Array.from({ length: Math.min(4, max - run.length, cursor.entries.length - next) }, (_, i) => next + i);- const frozen = await Promise.all(batch.map(index => freezeEntry(engine, { ...cursor, index }, key, assertActive, frozenRun).catch(() => null)));- const screened = await Promise.all(frozen.map((entry, i) => entry && !('hold' in entry) && !entry.rebound- ? screenWaiver(engine, { ...cursor, index: batch[i]! }, entry, config, frozenRun.signal).catch(() => null) : null));- for (const [i, waived] of screened.entries()) {- if (!waived) break extend;- run.push({ pending: frozen[i] as Pending, waived });+ const batch = Array.from({ length: Math.min(WAIVER_SCREEN_WIDTH, max - run.length, cursor.entries.length - next) }, (_, i) => next + i);+ const screened = await Promise.all(batch.map(async index => {+ const entry = await freezeEntry(engine, { ...cursor, index }, key, assertActive, frozenRun).catch(() => null);+ if (!entry || 'hold' in entry || entry.rebound) return null;- const waived = await screenWaiver(engine, { ...cursor, index }, entry, config).catch(() => null);++ const waived = await screenWaiver(engine, { ...cursor, index }, entry, config, frozenRun.signal).catch(() => null);+ return waived ? { pending: entry as Pending, waived } : null;+ }));+ for (const member of screened) {+ if (!member) break extend;+ run.push(member);}next += batch.length;}diff --cc src/core/persistence/sync-waivers.tsindex edd9a66362,fec05be6ec..b5bb613454--- a/src/core/persistence/sync-waivers.ts+++ b/src/core/persistence/sync-waivers.ts@@@ -131,14 -76,15 +131,15 @@@ export async function screenWaiver(engiconst intent = pending.intent;if (intent.kind === 'managed_sync_delete') {if (intent.unownedDeletion || intent.renameFrom || intent.rawHash !== null || typeof intent.path !== 'string' || typeof intent.sourcePath !== 'string') return null;- const snapshot = await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });+ // The authority check runs beside the snapshot read; its refusal counts only for an entry that would be waived.+ const [snapshot, denied] = await Promise.all([engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true }), authorityRefusal(engine, cursor, pending)]);if (!softDeletedAt(snapshot, pending)) return null;- await validateSyncAuthority(engine, cursor.authority, pending.slug);+ if (denied) throw denied.error;return { kind: 'delete', kernel: [] };}- const kernel = await unchangedSyncImport(engine, cursor, pending, config, signal);- const [kernel, denied] = await Promise.all([unchangedSyncImport(engine, cursor, pending, config), authorityRefusal(engine, cursor, pending)]);++ const [kernel, denied] = await Promise.all([unchangedSyncImport(engine, cursor, pending, config, signal), authorityRefusal(engine, cursor, pending)]);if (!kernel) return null;- await validateSyncAuthority(engine, cursor.authority, pending.slug);+ if (denied) throw denied.error;return { kind: 'import', kernel };}