Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(#6712 PR 4b K): keep_db becomes a pass admission; retire the consumer keep_db worker
garrytaned08d0f92f8b
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 86f8250ec1..a8c5454cb3 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -76,6 +76,14 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-cMore: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)+### admission_paused++<a id="admission_paused"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| `sync.admission` is not `normal`, so a managed sync's destructive write (a delete or a keep_db DB-wins reconcile) was not admitted, or was cancelled before it published; nothing was written. | `sync.admission` (`imports_only` or `classify_only`) is the brain-wide switch that pauses what managed sync writes. It is read when the pass pins, inside every admission transaction and again when a destructive write publishes, so a change takes effect at the next group and no destructive write lands after it. | Restore admission with `gbrain config set sync.admission normal` when the pause is no longer wanted; the next plain sync admits the paused paths again. Run: gbrain sync status --source '{source_id}' --json | agent | `gbrain doctor --json` | 1 | no |+### ambient_capture_off<a id="ambient_capture_off"></a>diff --git a/src/commands/doctor/checks/maintenance-drift.ts b/src/commands/doctor/checks/maintenance-drift.tsindex 5562a6eb44..ce3053b554 100644--- a/src/commands/doctor/checks/maintenance-drift.ts+++ b/src/commands/doctor/checks/maintenance-drift.ts@@ -67,7 +67,7 @@ export async function maintenanceWriteDriftCheck(engine: BrainEngine, sourceIds?const details = { count, concept_skips: skipCount, sources: rows, window_sequences: WINDOW, repair: 'file-drift', docs, suppressed, ...(policies.length ? { keep_db_policy: policies } : {}) };const policyNote = policies.map(policy => 'error' in policy ? ` storage.keep_db of ${policy.source_id} could not be read: ${policy.error}`: ` storage.keep_db of ${policy.source_id} (${policy.keep_db.join(', ')}) matches ${policy.matched} of them${policy.unchecked ? ` (${policy.unchecked} more not checked here)` : ''}; `- + `the owner host's maintenance worker reconciles them with the database copy, one rate-limited request each (${policy.receipt_cost.lifetime_ids} lifetime id(s), ${policy.receipt_cost.receipt_bytes} receipt bytes).`).join('');+ + `the owner host's managed sync reconciles those whose file is clean and committed with the database copy, one request each (${policy.receipt_cost.lifetime_ids} lifetime id(s), ${policy.receipt_cost.receipt_bytes} receipt bytes).`).join('');if (!count && !skipCount && suppressed.length) {return { name: 'maintenance_write_drift', status: 'warn', details,message: `${suppressed.length} maintenance write(s) are held back after repeated identical refusals (#6696), so they stop adding receipts: `diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 32b51e6949..c7b3a77a93 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -62,6 +62,7 @@ export const CODES = {access_env_missing: { class: 'caller', summary: "Google connect credential error: access env missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },acknowledgment_unavailable: { class: 'unavailable', summary: "This batch is unknown or outside the retained replay window." },admin_policy_enforced: { class: 'host_only', summary: "Google connect credential error: admin policy enforced.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ admission_paused: { class: 'host_only', summary: "`sync.admission` is not `normal`, so a managed sync's destructive write (a delete or a keep_db DB-wins reconcile) was not admitted, or was cancelled before it published; nothing was written.", why: "`sync.admission` (`imports_only` or `classify_only`) is the brain-wide switch that pauses what managed sync writes. It is read when the pass pins, inside every admission transaction and again when a destructive write publishes, so a change takes effect at the next group and no destructive write lands after it.", suggestion: 'Restore admission with `gbrain config set sync.admission normal` when the pause is no longer wanted; the next plain sync admits the paused paths again.', fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Shows the admission switch and what the newest pass paused, read-only.', requires_exclusive: false } },ambient_capture_off: { class: 'caller', summary: "memory.auto_writeback no longer allows this ambient capture lane, so facts extracted from captured session text were dropped before admission.", why: "An explicit off (or an incoherent setting) applies to every capture-lane fact request admitted after the change, including one whose provider call was already in flight; requests admitted earlier still publish.", docs: 'docs/guides/ambient-writeback.md#capture-lanes-and-the-off-switch' },ambiguous_id: { class: 'caller', summary: "The legacy id matches multiple readable pages." },ambiguous_ref: { class: 'caller', summary: "A page reference in a rating matches pages in more than one source of that answer.", docs: 'docs/guides/retrieval-feedback.md#ambiguous_ref' },diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 2d599742e3..f3565f0d14 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -52,8 +52,6 @@ export const DEFAULT_ZOMBIE_CAP = 1;/** An effects drain running this long names itself on stderr (serve), then again at this cadence. */const DRAIN_NOTICE_AFTER_MS = 5_000;const DRAIN_NOTICE_EVERY_MS = 10_000;-/** #6696 C7: at most one storage.keep_db policy pass (KEEP_DB_BATCH requests) per this interval. */-const KEEP_DB_POLICY_INTERVAL_MS = 10 * 60_000;/** #6712 (convergence mode f): how long a pass whose connection died keeps trying to release its unpublished claims. */const CONNECTION_LOSS_RELEASE_MS = 30_000;/** #6650: how often a consumer looks for claims held by an owner it can prove dead. */@@ -209,9 +207,6 @@ export class PersistenceConsumer implements PersistenceConsumerLike {private settleCursor: NoopSettleCursor | undefined;private topologyWorker: Promise<unknown> | undefined;private maintenanceWorker: Promise<unknown> | undefined;- /** #6696 C7: the storage.keep_db policy pass (resident owners only, at most one per KEEP_DB_POLICY_INTERVAL_MS while idle). */- private keepDbWorker: Promise<unknown> | undefined;- private nextKeepDb = 0;private nextMaintenance = 0;private publishedSinceMaintenance = 0;private maintenanceVolume = 50;@@ -252,9 +247,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {/** #6278: abandoned preparations past the ceiling before this process stops claiming (default DEFAULT_ZOMBIE_CAP). */zombieCap?: number;/** Write the long-drain progress line on stderr (serve; never a CLI command that may print --json). */- drainNotice?: boolean;- /** #6696 C7: run the storage.keep_db policy (repair/keep-db-policy.ts) for the sources this host owns while idle. */- keepDbPolicy?: boolean } = {}) {+ drainNotice?: boolean } = {}) {this.hostId = opts.hostId ?? localHostId();this.statements = consumerStatementEngine(engine);}@@ -509,11 +502,6 @@ export class PersistenceConsumer implements PersistenceConsumerLike {this.maintenanceWorker = runCompactionPass(this.engine, { hostId: this.hostId, notice: this.opts.drainNotice }).then(() => maybeRefreshPlannerStats(this.engine, 'idle')).catch(error => this.report(error)).finally(() => { this.maintenanceWorker = undefined; });}- if (this.opts.keepDbPolicy && !this.opts.requestsOnly && !this.keepDbWorker && Date.now() >= this.nextKeepDb) {- this.nextKeepDb = Date.now() + KEEP_DB_POLICY_INTERVAL_MS;- this.keepDbWorker = import('../repair/keep-db-policy.ts').then(({ runKeepDbPolicy }) => runKeepDbPolicy(this.engine, { hostId: this.hostId }))- .catch(error => this.report(error)).finally(() => { this.keepDbWorker = undefined; });- }return;}}@@ -1124,7 +1112,6 @@ export class PersistenceConsumer implements PersistenceConsumerLike {await this.effectsWorker;await this.topologyWorker;await this.maintenanceWorker;- await this.keepDbWorker;this.unobserveCheckout?.();this.unobserveCheckout = undefined;try { this.loopDelay?.disable(); } catch { /* fail-open */ }diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex fe7a20db84..3f55ed2da4 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -157,6 +157,8 @@ function requestError(error: unknown): PublicationFailure {return ownerExceptionFailure(error);}function conflictCode(code: string): boolean { return ['revision_required','revision_conflict','revision_backfill_pending','source_changed','page_identity_changed',SYNC_CURSOR_REPLACED].includes(code); }+/** The terminal state of an unpublished failure: `admission_paused` (#6712 PR 4b, a destructive write `sync.admission` paused at publication) is `cancelled`. */+function failureState(code: string): 'conflict' | 'failed' | 'cancelled' { return code === 'admission_paused' ? 'cancelled' : conflictCode(code) ? 'conflict' : 'failed'; }export function transientDatabaseFailure(error: unknown): boolean {return ['40001','40P01','55P03','57014','53300','57P01','57P02','57P03','08000','08003','08006','08001','08004','ECONNRESET','ECONNREFUSED','ETIMEDOUT','CONNECTION_CLOSED','CONNECTION_ENDED'].includes(String((error as {code?:string})?.code));@@ -217,7 +219,7 @@ export async function finishUnpublishedFailure(engine: BrainEngine, row: WriteReawait releaseUnpublishedClaim(engine, row, transientDatabaseFailure(error) ? 'database_contention' : 'revision_changed_repreparing');return (await getWriteRequestById(engine, row.id))!;}- return engine.transaction(tx => completeWrite(tx, row, conflictCode(failure.code) ? 'conflict' : 'failed', {}, failure));+ return engine.transaction(tx => completeWrite(tx, row, failureState(failure.code), {}, failure));}/**@@ -556,7 +558,7 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostId// Withdrawal is authoritative DB state and is never rolled back here.const failure: PublicationFailure | undefined = terminalError ?? (current.error_code ? {code:current.error_code,message:current.error_message ?? 'Publication failed before database completion.',...(current.error_detail ? { detail: current.error_detail as unknown as PublicationFailureDetail } : {})} : undefined);- if (failure) return completeWrite(tx, current, conflictCode(failure.code) ? 'conflict' : 'failed', {}, failure);+ if (failure) return completeWrite(tx, current, failureState(failure.code), {}, failure);for (const key of ['brain', `worktree:${current.worktree_id}`]) await tx.executeRaw('UPDATE persistence_counters SET recovery_bytes=recovery_bytes-$2 WHERE key=$1', [key, Number(current.recovery_bytes)]);const [queued] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state='queued',execution_token=NULL,claim_expires_at=NULL,recovery=NULL,recovery_bytes=0,publication_started=false,blocked_reason=NULL,updated_at=now()diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.tsindex cbb9e86ffd..24bff51cfd 100644--- a/src/core/persistence/reconcile-prepare.ts+++ b/src/core/persistence/reconcile-prepare.ts@@ -24,6 +24,7 @@ import { stabilizeSafetyAssessments } from './reconcile-safety.ts';import { ABSENT_FILE_HASH, assertReconcilePins, readReconcileState, reconcileFileReading, reconcileReadOptions, staleReconcile, validateReconcileArtifact, type ReconcileState } from './reconcile-state.ts';import { verifyReconcileBackup } from './reconcile-backup.ts';import { assertAutoDecisions } from './reconcile-additive.ts';+import { admissionAllows, readSyncAdmission } from './sync-admission.ts';const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows page ${slug} in source ${sourceId} as stored now, with its revision, read-only.`,{ argv: ['gbrain', 'get', '--source', sourceId, '--', slug] });@@ -115,11 +116,26 @@ export async function prepareReconcileResult(engine: BrainEngine, state: Reconcireturn { ...merged, result: resolved, ready, project };}+/**+ * #6712 PR 4b (design v3.2 §8 fencing point 2): a keep_db reconcile (`intent.keepDb`, admitted by the sync pass) re-reads+ * `sync.admission` at preparation and inside the publication transaction; when it is not `normal` the request completes+ * `cancelled` with `admission_paused` (coordinator.ts) and nothing is written. The path is a candidate again on the next pass.+ */+async function assertKeepDbAdmission(engine: Pick<BrainEngine, 'executeRaw'>, row: WriteRequest): Promise<void> {+ if (!row.intent?.keepDb) return;+ const admission = await readSyncAdmission(engine);+ if (admissionAllows(admission, 'destructive')) return;+ throw opError('admission_paused', `sync.admission is ${admission}, so this keep_db write was cancelled before it published.`,+ `Nothing was written to ${row.slug} in source ${row.source_id}. keep_db writes resume when sync.admission is normal again (gbrain config set sync.admission normal); the next sync pass admits this page again.`,+ { fix: readFix('Shows the sync admission switch and what the newest pass paused, read-only.', { argv: ['gbrain', 'sync', 'status', '--source', row.source_id, '--json'] }) });+}+export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {if (row.operation !== 'put_page' || row.intent?.kind !== 'canonical_reconcile' || row.authority.remote !== false || row.authority.principal.kind !== 'local_cli') {throw trustedCliRequired('Canonical reconciliation requires trusted local administration.');}await authorizeStoredRequest(engine, row);+ await assertKeepDbAdmission(engine, row);const artifact = validateReconcileArtifact(row.intent.preview);const reference = row.intent.backup_reference;if (typeof reference !== 'string') throw opError('storage_error', 'Reconciliation has no retained preimages.',@@ -151,6 +167,7 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRenoop: ready.noop && sha256(content) === state.pins.raw_file_hash && state.origin === 'recorded',validate: async tx => {await authorizeStoredRequest(tx, row, true);+ await assertKeepDbAdmission(tx, row);assertReconcilePins(artifact.preconditions, (await readReconcileState(tx, row.source_id, row.slug, artifact.preconditions.assessment_at, adopt)).pins);verifyReconcileBackup(reference, artifact);await ready.validate(tx);diff --git a/src/core/persistence/reconcile.ts b/src/core/persistence/reconcile.tsindex a8e7518c98..436b7560bc 100644--- a/src/core/persistence/reconcile.ts+++ b/src/core/persistence/reconcile.ts@@ -17,7 +17,7 @@ import { assertReconcilePins, readReconcileState, reconcilePreviewAdopts, reconcimport { prepareReconcileResult } from './reconcile-prepare.ts';import { assertReconcileOutputPath, assertReconcileSize, manageReconcileBackups, retainReconcileBackup } from './reconcile-backup.ts';import type { LocalGrant } from './identity.ts';-import { isTerminal } from './model.ts';+import { isTerminal, type WriteRequest } from './model.ts';import { serializePageToMarkdown } from '../markdown.ts';import { readFix, trustedCliRequired } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';@@ -151,12 +151,27 @@ export async function runReconcileApply(engine: BrainEngine, params: Record<striconst artifact = validateReconcileArtifact(params.preview);artifact.decisions = reconcileDecisions(artifact.decisions);const requestId = requireUuid(params.request_id as string);+ return admitReconcileArtifact(engine, { sourceId, slug, authority, artifact, requestId, keepFileBytes: params.keep_file_bytes === true },+ async (row, replayed) => writeResponse(replayed && isTerminal(row) ? row : await waitForWrite(engine, row, await config(engine))));+}++/**+ * Admits one ready reconcile artifact for an authorized page (`authorizeReconcile`): it re-reads the page and file, checks+ * the preimages, retains the backup and admits the request, replaying a prior request under the same id. `settle` runs on+ * the admitted or replayed row inside the same refusal handling. `intentExtra` rides the stored intent without entering the+ * digest; `transaction` wraps the admission transaction (`admitWrite`). #6712 PR 4b: the sync pass's keep_db admission+ * (repair/keep-db-policy.ts) uses both and settles without waiting for publication.+ */+export async function admitReconcileArtifact<T>(engine: BrainEngine, input: { sourceId: string; slug: string; authority: Awaited<ReturnType<typeof authorizeReconcile>>['authority'];+ artifact: ReconcileArtifact; requestId: string; keepFileBytes?: boolean; intentExtra?: Record<string, unknown>;+ transaction?: <U>(fn: (tx: BrainEngine) => Promise<U>) => Promise<U> }, settle: (row: WriteRequest, replayed: boolean) => Promise<T>): Promise<T> {+ const { sourceId, slug, authority, artifact, requestId } = input;if (artifact.preconditions.source_id !== sourceId || artifact.preconditions.slug !== slug || artifact.status !== 'ready' || artifact.conflicts.length) {throw opError('invalid_params', 'Apply requires a ready preview for this exact source and page.',`Nothing was submitted. Resolve every conflict first (preview with --from and --decisions until status is ready), then apply that resolved preview for ${slug} in '${sourceId}'.`);}// #6643: `gbrain repair file-drift --prefer file` keeps the file's own bytes when they already parse to the resolved result.- const callerIntent = { kind: 'canonical_reconcile', preview: artifact, ...(params.keep_file_bytes === true ? { keep_file_bytes: true } : {}) };+ const callerIntent = { kind: 'canonical_reconcile', preview: artifact, ...(input.keepFileBytes ? { keep_file_bytes: true } : {}) };const expectedDigest = intentDigest({ operation: 'put_page', sourceId, slug, callerIntent });await assertPageRequestIdentity(engine, authority.principal, requestId);const replay = async () => {@@ -164,7 +179,7 @@ export async function runReconcileApply(engine: BrainEngine, params: Record<striif (!prior) return null;assertReplayIntent(prior, expectedDigest);await authorizeStoredRequest(engine, prior);- return writeResponse(isTerminal(prior) ? prior : await waitForWrite(engine, prior, await config(engine)));+ return settle(prior, true);};const prior = await replay();if (prior) return prior;@@ -187,8 +202,8 @@ export async function runReconcileApply(engine: BrainEngine, params: Record<striconst row = await admitWrite(engine, { principal: authority.principal, operation: 'put_page', sourceId,sourceIncarnation: state.pins.source_incarnation, slug, pageId: state.pins.page_id, worktreeId: state.pins.worktree_id,topologyGeneration: state.binding.topology_generation, requestId, authority, callerIntent,- intent: { ...callerIntent, backup_reference: reference } });- return writeResponse(await waitForWrite(engine, row, await config(engine)));+ intent: { ...callerIntent, ...input.intentExtra, backup_reference: reference } }, undefined, input.transaction);+ return await settle(row, false);} catch (error) {const racedReplay = await replay();if (racedReplay) return racedReplay;diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 2f4ad55a24..c48902ca1e 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -113,8 +113,6 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest* `autopilot`, `mcp`) get a `WaiterOnlyConsumer` that probes the host's consumer rows on its first tick and settles to* full or waiter-only (consumer-election.ts). Either way the returned object has the consumer's whole surface.*/-/** #6696 C7: the resident owners whose full consumer runs the storage.keep_db policy (never a short-lived command). */-const KEEP_DB_POLICY_OWNERS = ['serve', 'jobs', 'autopilot'];export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConfig): PersistenceConsumerLike {const prior = services.get(engine);if (prior) {@@ -125,7 +123,7 @@ export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConfreturn prior.consumer;}const full = () => new PersistenceConsumer(engine, config, preparePersistedMutation,- { drainNotice: claimOwnerKind() === 'serve', keepDbPolicy: KEEP_DB_POLICY_OWNERS.includes(claimOwnerKind()), onSettled: row => { recordSettlement(engine); rememberSettled(engine, row.id); for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });+ { drainNotice: claimOwnerKind() === 'serve', onSettled: row => { recordSettlement(engine); rememberSettled(engine, row.id); for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });const kind = claimOwnerKind();const service: Service = kind !== 'serve' && RESIDENT_CONSUMER_KINDS.includes(kind) && engine.kind === 'postgres'? { consumer: new WaiterOnlyConsumer(engine, config, full, { kind, hostId: localHostId(), pool: () => enginePoolStats(engine) }), stopping: false }diff --git a/src/core/repair/keep-db-policy.ts b/src/core/repair/keep-db-policy.tsindex ea04a3eab1..e3b5afc022 100644--- a/src/core/repair/keep-db-policy.ts+++ b/src/core/repair/keep-db-policy.ts@@ -1,67 +1,51 @@/**- * #6696 C7: the opt-in `storage.keep_db` policy (gbrain.yml), consumed only by- * the trusted local maintenance worker on the canonical owner host.+ * #6696 C7: the opt-in `storage.keep_db` policy (gbrain.yml). #6712 PR 4b (design v3.2 §4, d1b option C): the policy is+ * an admission of the managed sync pass itself; the separate maintenance worker is retired.*- * A source whose gbrain.yml declares `keep_db:` prefixes asks that a drifted- * page under them (its canonical file differs from the database copy, so every- * coordinated write refuses `source_changed` / `file_database_drift`) be- * reconciled with the database copy winning, the resolution- * `gbrain repair file-drift --prefer database` previews, inside the same- * reconcile protections. Nothing else reads the policy: remote and caller- * writes to those pages keep refusing until the worker (or an operator)- * reconciles them.+ * A source whose gbrain.yml declares `keep_db:` prefixes asks that a drifted page under them be reconciled with the+ * database copy winning, the resolution `gbrain repair file-drift --prefer database` previews, inside the same reconcile+ * protections. Only the owner host's pass writes it, and only for a path it classified `keep_db` (row 18) or+ * `db_ahead`/`db_only` under a keep_db prefix (row 15) in committed mode with `Dp = clean`:*- * `runKeepDbPolicy` runs only for a source whose active binding this host- * owns. Candidates are the slugs under the prefixes with a drift conflict- * receipt in the newest `CONFLICT_WINDOW_DEFAULT` request sequences, plus the- * recorded concept drift skips; each is checked live before anything is- * prepared. Each drifted page gets one reconcile request (`runReconcileApply`)- * whose id is derived from the page revision and file bytes, so the same drift- * is never submitted twice, whatever its outcome. A run submits at most `limit`- * requests (`KEEP_DB_BATCH`; the consumer runs it at most every 10 minutes) and- * stops before an admission the `admission` gate refuses, or at the first- * `write_capacity_backpressure` refusal (it submits as a background producer).+ * - `freezeKeepDbReconcile` builds the DB-wins artifact (`prepareDriftPage(prefer: database)`) and binds it to the bytes and+ * page revision the pass froze under its lease: an artifact whose own read differs is refused, so its+ * `preconditions.raw_file_hash` is the frozen hash and publication refuses any later edit.+ * - `admitKeepDbReconcile` admits it under this installation's own CLI writer registration (never a caller's grant) with a+ * request id derived from the page revision and frozen bytes, re-reading `sync.admission` and running the pass's+ * `inTx` fence (the drain lease) inside the admission transaction. It does not wait for publication. The publication+ * re-reads `sync.admission` (reconcile-prepare.ts) and completes `cancelled` / `admission_paused` when it is not normal.+ *+ * Concept drift skips stay concept-side records; `releaseMatchedDriftSkips` clears the ones of pages the pass classified+ * `matched`. Doctor `maintenance_write_drift` reads `readKeepDbPolicy` and `keepDbReceiptCost`.*/-import { join } from 'node:path';+import { join, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import { OperationError, type OperationContext } from '../ops/contract.ts';+import { trustedCliRequired } from '../ops/op-fix.ts';import { isKeepDbSlug, loadStorageConfig } from '../storage-config.ts';import { getWorktreeBinding } from '../persistence/ownership.ts';-import { CONFLICT_WINDOW_DEFAULT, FILE_DRIFT_MESSAGE, liveFileDrift, readDriftSkips } from '../persistence/drift-conflicts.ts';-import { readLocalWriter, withVerifiedLocalRegistration } from '../persistence/identity.ts';+import { readDriftSkips, releaseDriftSkip } from '../persistence/drift-conflicts.ts';+import { localHostId, readLocalWriter, withVerifiedLocalRegistration } from '../persistence/identity.ts';import { getWriteRequest } from '../persistence/journal.ts';-import { runReconcileApply } from '../persistence/reconcile.ts';-import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';-import { digest } from '../persistence/digest.ts';+import { admitReconcileArtifact, authorizeReconcile, type ReconcileArtifact } from '../persistence/reconcile.ts';+import { digest, sha256 } from '../persistence/digest.ts';+import type { Principal, WriteRequest } from '../persistence/model.ts';+import { sourceMirrorReadOnly } from '../persistence/mirror-read-only.ts';+import { admissionAllows, readSyncAdmission } from '../persistence/sync-admission.ts';+import type { SyncClassified, SyncDirtiness, SyncPathState } from '../persistence/sync-classify.ts';import { capacity } from './core.ts';import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';import { readBackgroundPauseShare, withAdmissionOrigin } from '../persistence/admission-origin.ts';import { prepareDriftPage } from './file-drift.ts';-/** Reconcile requests one policy run submits at most. */-export const KEEP_DB_BATCH = 10;-/** Candidate slugs one source contributes to a run. */-const CANDIDATE_LIMIT = 1000;-export interface KeepDbPolicy { source_id: string; keep_db: string[] }-export interface KeepDbRun {- submitted: number;- skipped_by_reason: Record<string, number>;- /**- * `rate_limit`: candidates remain past `limit`; `capacity`: the admission gate refused the next request;- * `write_capacity_backpressure`: admission refused this background producer past the pause line, with no receipt.- */- stopped?: 'rate_limit' | 'capacity' | 'write_capacity_backpressure';- sources: Array<KeepDbPolicy & { submitted: number }>;-}-/*** The admission seam for this background producer: a stop reason when it must not admit now. The default stops at* the repair core's 90% stop line on lifetime ids and receipt bytes (`capacity`) and, before that, at the background* pause line (`persistence.capacity.background_pause_pct`, 80%) where admission would refuse this background request* `write_capacity_backpressure`. Checking first keeps a refused attempt from retaining a reconcile backup under the- * page's deterministic request id; an admission-time refusal (another writer crossed the line meanwhile) also stops the run.+ * page's deterministic request id.*/export type KeepDbAdmission = (engine: BrainEngine) => Promise<'capacity' | 'write_capacity_backpressure' | null>;@@ -88,74 +72,131 @@ export async function readKeepDbPolicy(engine: BrainEngine, sourceId: string, horeturn keepDb.length ? { source_id: sourceId, keep_db: keepDb } : null;}-const likeEscape = (value: string) => value.replace(/[\\%_]/g, char => `\\${char}`);+/** What the pass froze for one path under its lease, and how it classified it. */+export interface KeepDbFreeze {+ sourceId: string;+ slug: string;+ pageId: number;+ /** The page revision the pass classified. */+ revision: string;+ /** The source-relative origin `p`, with forward slashes. */+ path: string;+ /** The bytes the pass read: committed mode with `Dp = clean`, so `T[p]`. */+ frozenBytes: Uint8Array;+ classified: Pick<SyncClassified, 'cls' | 'sub' | 'keepDbWrite'>;+ mode: SyncPathState['mode'];+ dirty: SyncDirtiness | null;+}++/** A DB-wins reconcile artifact bound to the frozen bytes and revision (`preview.preconditions`). */+export interface KeepDbArtifact { source_id: string; slug: string; page_id: number; path: string; preview: ReconcileArtifact }++/**+ * Why a frozen path gets no keep_db write: `not_keep_db` (another class), `not_committed_clean` (working mode, or `Dp` not+ * `clean`), `outside_keep_db` (no owner-host policy covers the slug), `storage_config_error`, `mirror_read_only`,+ * `page_changed`, `revision_changed`, `bytes_changed` or `path_changed` (the artifact's own read differs from the freeze),+ * or the code `prepareDriftPage` refused with.+ */+export type KeepDbFreezeResult = { artifact: KeepDbArtifact } | { refused: string };++/**+ * Builds the keep_db DB-wins artifact for one frozen path (design v3.2 §4). Refuses anything but a committed, clean+ * `keep_db` or `db_ahead`/`db_only` keep_db path under this host's policy on a source that is not mirror-read-only, and+ * fails closed when its own read of the page or file differs from what the pass froze.+ */+export async function freezeKeepDbReconcile(engine: BrainEngine, input: KeepDbFreeze): Promise<KeepDbFreezeResult> {+ const { cls, sub, keepDbWrite } = input.classified;+ if (!(cls === 'keep_db' || (cls === 'db_ahead' && sub === 'db_only' && keepDbWrite))) return { refused: 'not_keep_db' };+ if (input.mode !== 'committed' || input.dirty !== 'clean') return { refused: 'not_committed_clean' };+ let policy: KeepDbPolicy | null;+ try { policy = await readKeepDbPolicy(engine, input.sourceId, localHostId()); } catch { return { refused: 'storage_config_error' }; }+ if (!policy || !isKeepDbSlug(input.slug, policy.keep_db)) return { refused: 'outside_keep_db' };+ if (await sourceMirrorReadOnly(engine, input.sourceId)) return { refused: 'mirror_read_only' };+ let preview: ReconcileArtifact;+ try { preview = (await prepareDriftPage(engine, input.sourceId, input.slug, 'database', new Date().toISOString())).preview; }+ catch (error) { if (error instanceof OperationError) return { refused: error.code }; throw error; }+ const pins = preview.preconditions;+ if (pins.page_id !== input.pageId) return { refused: 'page_changed' };+ if (pins.revision !== input.revision) return { refused: 'revision_changed' };+ if (pins.raw_file_hash !== sha256(Buffer.from(input.frozenBytes))) return { refused: 'bytes_changed' };+ if (pins.relative_path.split(sep).join('/') !== input.path) return { refused: 'path_changed' };+ return { artifact: { source_id: input.sourceId, slug: input.slug, page_id: input.pageId, path: input.path, preview } };+}-async function candidates(engine: BrainEngine, policy: KeepDbPolicy): Promise<string[]> {- const [bounds] = await engine.executeRaw<{ top: string | null }>('SELECT max(sequence)::text AS top FROM persistence_requests');- const floor = String(Math.max(0, Number(bounds?.top ?? 0) - CONFLICT_WINDOW_DEFAULT));- const prefixes = policy.keep_db.map(dir => `${likeEscape(dir.toLowerCase())}%`);- const rows = await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT r.slug FROM persistence_requests r- WHERE r.sequence > $2::bigint AND r.source_id=$1 AND r.state='conflict' AND r.error_code='source_changed' AND r.error_message=$3- AND lower(r.slug) LIKE ANY($4::text[]) ORDER BY r.slug LIMIT ${CANDIDATE_LIMIT}`, [policy.source_id, floor, FILE_DRIFT_MESSAGE, prefixes]);- const skipped = Object.keys(await readDriftSkips(engine)).filter(key => key.startsWith(`${policy.source_id}:`)).map(key => key.slice(policy.source_id.length + 1));- return [...new Set([...rows.map(row => row.slug), ...skipped])].filter(slug => isKeepDbSlug(slug, policy.keep_db)).sort();+/**+ * The request id of an artifact: derived from the page revision and the frozen bytes, so one drift is submitted once+ * whatever its outcome, except that a request `sync.admission` cancelled at publication (`admission_paused`) leaves the+ * path a candidate again: the next admission takes the next id in that sequence.+ */+async function keepDbRequestId(engine: BrainEngine, principal: Principal, artifact: KeepDbArtifact): Promise<string> {+ for (let attempt = 0; ; attempt++) {+ const h = digest(['keep-db-policy-v1', artifact.source_id, artifact.slug, artifact.preview.preconditions.revision, artifact.preview.preconditions.raw_file_hash,+ ...(attempt ? [attempt] : [])]);+ const requestId = `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;+ const prior = await getWriteRequest(engine, principal, requestId);+ if (prior?.state !== 'cancelled' || prior.error_code !== 'admission_paused') return requestId;+ }}/**- * One drifted page: submitted, the capacity stop, or the reason it was skipped. It always runs as this- * installation's own CLI writer registration, never as whatever caller context the worker's timer inherited:- * the policy is the owner host's declaration, so no remote caller's grant applies to it or is widened by it.+ * The admitted request (`replayed`: the same drift was admitted before, under the same id), or why nothing was admitted:+ * `admission_paused` (`sync.admission` is not normal inside the admission transaction), `capacity` /+ * `write_capacity_backpressure`, or the code the reconcile admission refused with.*/-async function reconcileWithDatabase(engine: BrainEngine, sourceId: string, slug: string, admission: KeepDbAdmission): Promise<string> {+export type KeepDbAdmitResult = { request: WriteRequest; replayed: boolean } | { refused: string };++/**+ * Admits a frozen keep_db artifact for the sync pass `passId` (`intent.keepDb.passId`). `inTx` runs inside the admission+ * transaction after the request row is inserted (the pass runs `assertDrainLease` there); whatever it throws rolls the+ * admission back and is rethrown as is. Only a trusted local pass (`remote: false`) admits keep_db writes.+ */+export async function admitKeepDbReconcile(engine: BrainEngine, artifact: KeepDbArtifact,+ opts: { passId: string; remote: boolean; inTx: (tx: BrainEngine) => Promise<void>; admission?: KeepDbAdmission }): Promise<KeepDbAdmitResult> {+ if (opts.remote !== false) throw trustedCliRequired("keep_db writes are admitted only by the owner host's own sync pass.");return withVerifiedLocalRegistration(engine, await readLocalWriter(engine, 'cli'), async writer => {- const live = await liveFileDrift(engine, sourceId, slug);- if (live.still_present !== true) return live.still_present === false ? 'no_drift' : live.reason;- let page;- try { page = await prepareDriftPage(engine, sourceId, slug, 'database', new Date().toISOString()); }- catch (error) { if (error instanceof OperationError) return error.code; throw error; }- const h = digest(['keep-db-policy-v1', sourceId, slug, page.preview.preconditions.revision, page.preview.preconditions.raw_file_hash]);- const requestId = `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;- if (await getWriteRequest(engine, writer.principal, requestId)) return 'already_submitted';- const stop = await admission(engine);- if (stop) return stop;+ const requestId = await keepDbRequestId(engine, writer.principal, artifact);+ const prior = await getWriteRequest(engine, writer.principal, requestId);+ if (prior) return { request: prior, replayed: true };+ const stop = await (opts.admission ?? headroom)(engine);+ if (stop) return { refused: stop };+ let fenced: { error: unknown } | undefined;+ let paused = false;+ const transaction = <T>(fn: (tx: BrainEngine) => Promise<T>) => engine.transaction(async tx => {+ const row = await fn(tx);+ if (!admissionAllows(await readSyncAdmission(tx), 'destructive')) {+ paused = true;+ throw new OperationError('admission_paused', 'sync.admission paused keep_db writes.', 'Nothing was admitted; the next pass admits this page once sync.admission is normal.');+ }+ try { await opts.inTx(tx); } catch (error) { fenced = { error }; throw error; }+ return row;+ });try {+ const { authority } = await authorizeReconcile(engine, artifact.source_id, artifact.slug);// #6696 A5: a background producer, so near-cap backpressure refuses it before any receipt and interactive writes keep the rest.- await withAdmissionOrigin('background', () => runReconcileApply(engine, { source_id: sourceId, slug, preview: page.preview, request_id: requestId }));+ return await withAdmissionOrigin('background', () => admitReconcileArtifact(engine, { sourceId: artifact.source_id, slug: artifact.slug, authority,+ artifact: artifact.preview, requestId, intentExtra: { keepDb: { passId: opts.passId } }, transaction },+ async (request, replayed): Promise<KeepDbAdmitResult> => ({ request, replayed })));} catch (error) {- if (acceptedPendingReceipt(error)) return 'submitted';+ if (fenced) throw fenced.error;+ if (paused) return { refused: 'admission_paused' };if (!(error instanceof OperationError)) throw error;- if (error.code === 'write_capacity_backpressure') return error.code;- return await getWriteRequest(engine, writer.principal, requestId) ? 'submitted' : error.code;+ const raced = await getWriteRequest(engine, writer.principal, requestId);+ return raced ? { request: raced, replayed: true } : { refused: error.code };}- return 'submitted';});}/**- * One rate-limited pass of the keep_db policy over `sourceIds` (default: every active source) for the owner host- * `hostId`. Sources this host does not own, or that declare no policy, are skipped without a read of their pages.+ * Releases the concept drift skips (`dream.concepts.drift_skips`) of pages the pass classified `matched` in `sourceId`:+ * one read of the skips, and one release per matched page that has one.*/-export async function runKeepDbPolicy(engine: BrainEngine, opts: { hostId: string; sourceIds?: string[]; limit?: number; admission?: KeepDbAdmission }): Promise<KeepDbRun> {- const limit = opts.limit ?? KEEP_DB_BATCH;- const run: KeepDbRun = { submitted: 0, skipped_by_reason: {}, sources: [] };- const skip = (reason: string) => { run.skipped_by_reason[reason] = (run.skipped_by_reason[reason] ?? 0) + 1; };- const sourceIds = opts.sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);- for (const sourceId of sourceIds) {- let policy: KeepDbPolicy | null;- try { policy = await readKeepDbPolicy(engine, sourceId, opts.hostId); } catch { skip('storage_config_error'); continue; }- if (!policy) continue;- const entry = { ...policy, submitted: 0 };- run.sources.push(entry);- for (const slug of await candidates(engine, policy)) {- if (run.submitted >= limit) { run.stopped = 'rate_limit'; return run; }- let outcome: string;- try { outcome = await reconcileWithDatabase(engine, sourceId, slug, opts.admission ?? headroom); }- catch (error) { if (!(error instanceof OperationError)) throw error; outcome = error.code; }- if (outcome === 'capacity' || outcome === 'write_capacity_backpressure') { run.stopped = outcome; return run; }- if (outcome !== 'submitted') { skip(outcome); continue; }- run.submitted++;- entry.submitted++;- }+export async function releaseMatchedDriftSkips(engine: BrainEngine, sourceId: string, matchedSlugs: Iterable<string>): Promise<number> {+ const skips = await readDriftSkips(engine);+ let released = 0;+ for (const slug of new Set(matchedSlugs)) {+ if (!skips[`${sourceId}:${slug}`]) continue;+ await releaseDriftSkip(engine, sourceId, slug);+ released++;}- return run;+ return released;}