Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): one-shot housekeeping runs after the reply, a turn counts only once done, per-request identity memo (GBRA-156)
garrytanf7f7151e53b5
diff --git a/src/cli/main.ts b/src/cli/main.tsindex 1c48044609..a2275a2dce 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -644,6 +644,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: Ctry {const { withTimeout, OperationTimeoutError } = await import('../core/timeout.ts');+ const { withRequestIdentityMemo } = await import('../core/persistence/identity.ts');const wallclockMs = getCliOptions().timeoutMs ?? READ_OP_TIMEOUT_MS;const onWallclockTimeout = (e: InstanceType<typeof OperationTimeoutError>) => {const hint = getCliOptions().timeoutMs@@ -678,7 +679,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: Cif (op.scope === 'read') {try {rawResult = await withTimeout(- op.handler(ctx, params).catch(async (e: unknown) => { // large pages: a segmented page streams to stdout+ withRequestIdentityMemo(() => op.handler(ctx, params)).catch(async (e: unknown) => { // large pages: a segmented page streams to stdoutif (op.name === 'get_page' && await streamSegmentedGet(engine, params, e, writeStdoutFinal)) return SEGMENTED_STREAMED;throw e;}),@@ -693,7 +694,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: Cthrow e;}} else {- rawResult = await op.handler(ctx, params);+ rawResult = await withRequestIdentityMemo(() => op.handler(ctx, params));if (op.mutating) await captureCapacityNotices(engine); // #6696 (A4)}if (rawResult === SEGMENTED_STREAMED) return;diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex a25a168bc4..f06a960133 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -20,7 +20,7 @@ import { laneClaim, laneOf, laneRoots, laneTask } from './sync-lanes.ts';import { runPersistenceEffects } from './effects.ts';import { settleNoopEmbeddingEffects, type NoopSettleCursor } from './embedding-noop-settle.ts';import { runCompactionPass } from './compaction-pass.ts';-import { claimHousekeepingTurn, housekeepingIntervalMs } from './housekeeping-turn.ts';+import { claimHousekeepingTurn, completeHousekeepingTurn, housekeepingIntervalMs } from './housekeeping-turn.ts';import { currentEmbeddingSignature } from '../embedding.ts';import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { isWriteErrorCode } from './types.ts';@@ -49,6 +49,8 @@ export type EffectivePreparationPolicy = PreparationPolicy & { deadlines: booleaexport interface AbandonedPreparation { request_id: string; operation: string; step: string | null; waiting_on: WaitingOn; claimed_at: string; abandoned_at: string; outlived_ceiling_at: string }/** #6278: how long stop() waits on abandoned preparations after their abort before closing the engine. */export const ABANDONED_STOP_GRACE_MS = 5_000;+/** GBRA-156: how long a one-shot command's shutdown waits for its housekeeping tick (`runOneShotHousekeeping`). */+export const ONE_SHOT_HOUSEKEEPING_BOUND_MS = 5_000;/** #6278: abandoned preparations past the ceiling this process tolerates before it stops claiming and reports `restart_required`. */export const DEFAULT_ZOMBIE_CAP = 1;/** An effects drain running this long names itself on stderr (serve), then again at this cadence. */@@ -240,6 +242,13 @@ export class PersistenceConsumer implements PersistenceConsumerLike {/** GBRA-156: when this one-shot consumer last asked for the host's housekeeping turn, and whether it holds the turn now. */private housekeepingAskedAt = -Infinity;private housekeepingTurn = false;+ /** GBRA-156: this tick took the host's turn from the database; it is marked done once the upkeep it started settles. */+ private turnClaimed = false;+ private turnDone: Promise<void> | undefined;+ /** GBRA-156: the one-shot shutdown tick runs housekeeping only and claims no write. */+ private housekeepingOnly = false;+ /** GBRA-156: ends the effect drain where `stop()` would have, before the one-shot shutdown's housekeeping tick. */+ private effectsStop = new AbortController();/** #6317: the engine the tick's own statements run through (the direct route when the engine has one; consumer-lane.ts). */private readonly statements: BrainEngine;private routeLogged = false;@@ -274,7 +283,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {return typeof engine.onCheckout === 'function' ? (engine.onCheckout as (listener: () => void) => () => void).bind(this.engine) : undefined;}start(): void {- this.stopping = false; this.abort = new AbortController(); this.fullTickRequested = true; this.idleDelayMs = this.pollMs;+ this.stopping = false; this.abort = new AbortController(); this.effectsStop = new AbortController(); this.fullTickRequested = true; this.idleDelayMs = this.pollMs;// #6317: one loud line when every round-trip of this consumer goes through a transaction-mode pooler with no direct route.const exposure = poolerExposureLine(consumerConnectionRoute(this.engine));if (exposure && !this.routeLogged && !this.opts.onError) { this.routeLogged = true; process.stderr.write(`${exposure}\n`); }@@ -330,9 +339,50 @@ export class PersistenceConsumer implements PersistenceConsumerLike {if (interval === 0) return true;if (Date.now() - this.housekeepingAskedAt < interval) return false;this.housekeepingAskedAt = Date.now();- this.housekeepingTurn = await this.phase('housekeeping_turn', signal => claimHousekeepingTurn(this.statements, this.hostId, interval, signal)).catch(() => true);+ const claimed = await this.phase('housekeeping_turn', signal => claimHousekeepingTurn(this.statements, this.hostId, interval, signal)).catch(() => null);+ this.turnClaimed ||= claimed === true;+ this.housekeepingTurn = claimed !== false;return this.housekeepingTurn;}+ /**+ * GBRA-156: a turn this tick took is marked done once the upkeep it started (compaction, projection, topology recovery)+ * settles; a tick that failed, or a stop that aborted that upkeep, leaves the turn to its lease.+ */+ private settleTurn(): void {+ if (!this.turnClaimed) return;+ this.turnClaimed = false;+ const upkeep = [this.maintenanceWorker, this.projectionWorker, this.topologyWorker];+ this.turnDone = Promise.allSettled(upkeep).then(async () => {+ if (!this.stopping) await completeHousekeepingTurn(this.statements, this.hostId);+ }).catch(error => this.report(error));+ }+ /**+ * GBRA-156: a one-shot command's consumer, at shutdown (after the command's reply), runs one housekeeping tick when no+ * write is awaited and the host's turn is this process's (taken now when it is due): the scans, compaction and the+ * projection pass, no write claim and no effect drain. It waits up to `boundMs` for that upkeep, so a brain with no+ * resident process still compacts and recovers; without the turn it returns at once.+ */+ async runOneShotHousekeeping(boundMs = ONE_SHOT_HOUSEKEEPING_BOUND_MS): Promise<void> {+ if (!this.opts.oneShot || this.stopping || this.opts.oneShot.waiting()) return;+ this.effectsStop.abort();+ this.housekeepingOnly = true;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const bound = new Promise<void>(resolve => { timer = setTimeout(resolve, boundMs); });+ try {+ await Promise.race([(async () => {+ await this.tickPromise;+ if (this.timer) { clearTimeout(this.timer); this.timer = undefined; }+ if (this.stopping || !await this.upkeepAllowed()) return;+ this.fullTickRequested = true;+ this.nextMaintenance = 0;+ await this.tick(false);+ await Promise.allSettled([this.maintenanceWorker, this.projectionWorker, this.topologyWorker]);+ await this.turnDone;+ })(), bound]);+ } finally {+ clearTimeout(timer);+ }+ }private backoff(): number {this.idleDelayMs = Math.min(Math.max(this.idleDelayMs, this.pollMs) * 2, this.idleMaxMs);return this.idleDelayMs;@@ -526,7 +576,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {*/async tick(afterProgress = false): Promise<void> {if (this.tickPromise) return this.tickPromise;- this.tickPromise = this.doTick(afterProgress).catch(error => { this.report(error); }).finally(() => {+ this.tickPromise = this.doTick(afterProgress).then(() => this.settleTurn(), error => { this.turnClaimed = false; this.report(error); }).finally(() => {this.tickPromise = undefined;if (this.wakeRequested) { this.wakeRequested = false; this.schedule(0); }});@@ -534,7 +584,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {}private async doTick(afterProgress: boolean): Promise<void> {if (this.stopping) return;- this.housekeepingTurn = false;+ if (!this.housekeepingOnly) this.housekeepingTurn = false;const requested = this.fullTickRequested;this.fullTickRequested = false;if (!requested) {@@ -589,7 +639,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {.then(({ recoverSourceTopologies }) => recoverSourceTopologies(this.engine, { hostId: this.hostId, limit: 2,onAttempt: (id, recovered) => { if (recovered) this.topologyRetryAfter.delete(id); else this.topologyRetryAfter.set(id, Date.now() + 30_000); } })).catch(error => this.report(error)).finally(() => { this.topologyWorker = undefined; });- if (!this.effectsWorker) this.effectsWorker = this.drainEffects().catch(error => this.report(error))+ if (!this.effectsWorker && !this.housekeepingOnly) this.effectsWorker = this.drainEffects().catch(error => this.report(error)).finally(() => { this.effectsWorker = undefined; });// Queue upkeep also follows publication volume, like autovacuum's scale// factor, so a busy owner never plans against a much smaller queue.@@ -654,6 +704,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {preparation_attempts=r.preparation_attempts+CASE WHEN $2::boolean THEN ${EXPIRED_PREPARING_CHARGE_SQL('r')} ELSE 0 ENDFROM expired WHERE r.id=expired.id`, [this.hostId, this.policy.deadlines, deadOwners], { signal }));}+ if (this.housekeepingOnly) return;if (publicationConcurrency(this.engine) === 0) {await this.phase('capacity', signal => this.statements.executeRaw(`UPDATE persistence_requests SET blocked_reason='writer_pool_capacity'WHERE state='queued' AND blocked_reason IS DISTINCT FROM 'writer_pool_capacity' AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, undefined, { signal }));@@ -770,7 +821,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {const signature = currentEmbeddingSignature();const drain = this.draining = { since: Date.now(), settled: 0, ran: 0, noticedAt: 0 };try {- for (let done = !signature; !done && !this.stopping;) {+ const signal = AbortSignal.any([this.abort.signal, this.effectsStop.signal]);+ for (let done = !signature; !done && !signal.aborted;) {const pass = await settleNoopEmbeddingEffects(this.engine, this.hostId, signature!, this.settleCursor);this.settleCursor = pass.cursor;done = pass.done;@@ -778,8 +830,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {this.drainNotice(drain);if (!done) await yieldToEventLoop();}- for (let ran = limit; ran >= limit && !this.stopping;) {- ran = await runPersistenceEffects(this.engine, this.config, { hostId: this.hostId, limit, signal: this.abort.signal });+ for (let ran = limit; ran >= limit && !signal.aborted;) {+ ran = await runPersistenceEffects(this.engine, this.config, { hostId: this.hostId, limit, signal });drain.ran += ran;this.drainNotice(drain);if (ran >= limit) await yieldToEventLoop();@@ -1197,6 +1249,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {await this.effectsWorker;await this.topologyWorker;await this.maintenanceWorker;+ await this.turnDone;this.unobserveCheckout?.();this.unobserveCheckout = undefined;try { this.loopDelay?.disable(); } catch { /* fail-open */ }diff --git a/src/core/persistence/housekeeping-turn.ts b/src/core/persistence/housekeeping-turn.tsindex 1401867642..519bed34ea 100644--- a/src/core/persistence/housekeeping-turn.ts+++ b/src/core/persistence/housekeeping-turn.ts@@ -3,19 +3,22 @@** A one-shot command (`gbrain put`, `gbrain remember`, any shared operation the CLI runs once and exits) starts a full* consumer to publish its own write. The consumer's housekeeping (recovery and expired-claim scans, dead-owner and topology- * recovery, compaction and queue upkeep, the resident projection pass) is not what that write waits on, and it held the- * process open after the reply on every command. Many brains have no resident process, so these commands are also the only- * thing that runs it: it is rationed, not removed. After no caller in the process awaits a write, the consumer asks for the- * host's turn; the turn is granted at most once per `GBRAIN_ONESHOT_HOUSEKEEPING_INTERVAL_MS` (default 5 minutes) across- * this host's processes (an atomic claim on one op_checkpoints row, op `consumer-housekeeping`, fingerprint the host id),- * and never while a resident full consumer on the host is live, because that one already runs the same scans. The scans a- * waiting write may be blocked behind still run at once (consumer.ts `sweepAllowed`).+ * recovery, compaction and queue upkeep, the resident projection pass) is not what that write waits on. Many brains have no+ * resident process, so these commands are also the only thing that runs it: it is rationed, not removed, and it runs after+ * the reply (consumer.ts `runOneShotHousekeeping`, from the consumer's shutdown). The turn is granted at most once per+ * `GBRAIN_ONESHOT_HOUSEKEEPING_INTERVAL_MS` (default 5 minutes) across this host's processes, judged from the last turn that+ * finished, and never while a resident full consumer on the host is live, because that one already runs the same scans.+ * The op_checkpoints row (op `consumer-housekeeping`, fingerprint the host id) holds the state: `["leased"]` while a+ * process holds the turn (a lease of HOUSEKEEPING_LEASE_MS, so a turn cut short by an exit or an abort is free again+ * after it) and `["done"]` once one finished, `updated_at` stamping either. The scans a waiting write may be blocked+ * behind still run at once (consumer.ts `sweepAllowed`).*/import type { SqlEngine } from './model.ts';import { CONSUMER_LIVE_MS, RESIDENT_CONSUMER_KINDS } from './consumer-heartbeat.ts';export const HOUSEKEEPING_TURN_OP = 'consumer-housekeeping';export const HOUSEKEEPING_INTERVAL_MS_DEFAULT = 300_000;+export const HOUSEKEEPING_LEASE_MS = 60_000;export function housekeepingIntervalMs(env: Record<string, string | undefined> = process.env): number {const raw = env.GBRAIN_ONESHOT_HOUSEKEEPING_INTERVAL_MS;@@ -23,14 +26,24 @@ export function housekeepingIntervalMs(env: Record<string, string | undefined> =return Number.isFinite(value) && value >= 0 ? Math.floor(value) : HOUSEKEEPING_INTERVAL_MS_DEFAULT;}-/** Claims the host's housekeeping turn: true when no turn was taken within `intervalMs` and no resident full consumer of the host is live. */+/**+ * Claims the host's housekeeping turn: true when the last finished turn is older than `intervalMs`, no other process holds+ * an unexpired lease on it, and no resident full consumer of the host is live.+ */export async function claimHousekeepingTurn(engine: SqlEngine, hostId: string, intervalMs: number, signal?: AbortSignal): Promise<boolean> {const [row] = await engine.executeRaw<{ claimed: boolean }>(`WITH claim AS (INSERT INTO op_checkpoints (op, fingerprint, completed_keys, updated_at)- SELECT $1::text, $2::text, '[]'::jsonb, now() WHERE NOT EXISTS (SELECT 1 FROM persistence_consumers WHERE host_id=$2::text::uuid+ SELECT $1::text, $2::text, '["leased"]'::jsonb, now() WHERE NOT EXISTS (SELECT 1 FROM persistence_consumers WHERE host_id=$2::text::uuidAND kind=ANY($4::text[]) AND mode IN ('full','promoted') AND renewed_at > now() - ($5::integer * interval '1 millisecond'))- ON CONFLICT (op, fingerprint) DO UPDATE SET updated_at=now()- WHERE op_checkpoints.updated_at <= now() - ($3::bigint * interval '1 millisecond') RETURNING 1)- SELECT EXISTS (SELECT 1 FROM claim) AS claimed`, [HOUSEKEEPING_TURN_OP, hostId, intervalMs, [...RESIDENT_CONSUMER_KINDS], CONSUMER_LIVE_MS], { signal });+ ON CONFLICT (op, fingerprint) DO UPDATE SET updated_at=now(), completed_keys='["leased"]'::jsonb+ WHERE op_checkpoints.updated_at <= now() - (CASE WHEN op_checkpoints.completed_keys='["done"]'::jsonb THEN $3::bigint ELSE $6::bigint END+ * interval '1 millisecond') RETURNING 1)+ SELECT EXISTS (SELECT 1 FROM claim) AS claimed`, [HOUSEKEEPING_TURN_OP, hostId, intervalMs, [...RESIDENT_CONSUMER_KINDS], CONSUMER_LIVE_MS, HOUSEKEEPING_LEASE_MS], { signal });return row?.claimed === true;}++/** Marks the host's leased turn finished: the next one is due `intervalMs` from now. */+export async function completeHousekeepingTurn(engine: SqlEngine, hostId: string): Promise<void> {+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys='["done"]'::jsonb, updated_at=now()+ WHERE op=$1 AND fingerprint=$2 AND completed_keys='["leased"]'::jsonb`, [HOUSEKEEPING_TURN_OP, hostId]);+}diff --git a/src/core/persistence/identity.ts b/src/core/persistence/identity.tsindex 2a807ff08f..70803edb05 100644--- a/src/core/persistence/identity.ts+++ b/src/core/persistence/identity.ts@@ -115,7 +115,37 @@ export function localHostIdentity(): LocalHostIdentity {export function existingLocalHostId(): string | null {return readHostIdentity(join(persistenceHome(), 'host.json'), false)?.id ?? null;}-async function brainIdentity(engine: SqlEngine): Promise<string> {+/**+ * GBRA-156: one operation invocation (a CLI shared operation, an MCP tool call) reads the brain identity and verifies each+ * local writer credential once for its pre-submission checks; `withRequestIdentityMemo` scopes those reads to that one+ * invocation, so the next request reads both again and a credential revoked in between is refused there. A locking+ * verification (`verifyLocalWriter(..., true)`) is never memoized, and the admission transaction keeps its own fence.+ */+const requestIdentity = new AsyncLocalStorage<{ reads: WeakMap<object, Map<string, Promise<unknown>>> }>();+export function withRequestIdentityMemo<T>(run: () => Promise<T>): Promise<T> {+ return requestIdentity.getStore() ? run() : requestIdentity.run({ reads: new WeakMap() }, run);+}+/** A registration, rotation or revocation inside the request: its later checks read again. */+export function forgetRequestIdentity(): void {+ const store = requestIdentity.getStore();+ if (store) store.reads = new WeakMap();+}+function requestMemo<T>(engine: object, key: string, read: () => Promise<T>): Promise<T> {+ const store = requestIdentity.getStore();+ if (!store) return read();+ let reads = store.reads.get(engine);+ if (!reads) store.reads.set(engine, reads = new Map());+ const held = reads.get(key);+ if (held) return held as Promise<T>;+ const value = read();+ reads.set(key, value);+ value.catch(() => { if (reads!.get(key) === value) reads!.delete(key); });+ return value;+}+function brainIdentity(engine: SqlEngine): Promise<string> {+ return requestMemo(engine, 'brain', () => readBrainIdentity(engine));+}+async function readBrainIdentity(engine: SqlEngine): Promise<string> {const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');if (!brain) throw opError('writer_not_initialized', 'Persistence metadata has not been initialized.','This brain\'s database has no persistence metadata row, which the schema migrations create, so no local writer can be registered or verified; nothing changed. Run gbrain doctor --json on the brain host; if it reports pending migrations, bring the schema current with gbrain apply-migrations, then run the command again.',@@ -148,8 +178,11 @@ async function ensureLocalWriterRow(engine: BrainEngine, lane: 'cli' | 'stdio',if (existing?.revoked_at != null) throw new OperationError('permission_denied', 'This local writer registration was revoked.', 'Explicitly register a new writer to authorize future work.');if (existing && (existing.lane !== lane || existing.credential_hash !== sha256(local.credential))) throw credentialMismatch(path, local.id, lane);// A registered writer is left as it is (the insert would conflict and do nothing).- if (!existing) await engine.executeRaw(`INSERT INTO persistence_local_writers(id,lane,credential_hash,grant_ceiling)+ if (!existing) {+ await engine.executeRaw(`INSERT INTO persistence_local_writers(id,lane,credential_hash,grant_ceiling)VALUES($1::uuid,$2,$3,$4::text::jsonb) ON CONFLICT(id) DO NOTHING`, [local.id, lane, sha256(local.credential), JSON.stringify(grant)]);+ forgetRequestIdentity();+ }return { local, ...(existing ? { existing } : {}) };}/**@@ -196,6 +229,7 @@ async function rotateLocalWriter(engine: BrainEngine, lane: 'cli' | 'stdio', graVALUES($1::uuid,$2,$3,$4::text::jsonb)`, [next.id, lane, sha256(next.credential), JSON.stringify(grant)]);await tx.executeRaw('UPDATE persistence_local_writers SET revoked_at=COALESCE(revoked_at,now()) WHERE id=$1::uuid', [old.id]);});+ forgetRequestIdentity();durable = true;linkSync(path, `${path}.revoked.${next.id}`);renameSync(pending, path); // readers always see one complete credential document@@ -217,8 +251,9 @@ export async function readLocalWriter(engine: SqlEngine, lane: 'cli' | 'stdio'):return local;}export async function verifyLocalWriter(engine: SqlEngine, local: LocalRegistration, lock = false): Promise<{ principal: Principal; grant: LocalGrant; remote: boolean }> {- const [row] = await engine.executeRaw<LocalWriterRow>(+ const read = () => engine.executeRaw<LocalWriterRow>(`SELECT lane,credential_hash,grant_ceiling,revoked_at FROM persistence_local_writers WHERE id=$1::uuid${lock ? ' FOR SHARE' : ''}`, [local.id]);+ const [row] = lock ? await read() : await requestMemo(engine, `writer:${local.id}`, read);return verifiedFromRow(local, row);}export interface LocalWriterRow { lane: string; credential_hash: string; grant_ceiling: LocalGrant; revoked_at: unknown }@@ -233,6 +268,7 @@ function verifiedFromRow(local: LocalRegistration, row: LocalWriterRow | undefinreturn { principal: { kind: row.lane === 'cli' ? 'local_cli' : 'local_stdio', id: local.id }, grant: row.grant_ceiling, remote: row.lane !== 'cli' };}export async function revokeLocalWriter(engine: BrainEngine, id: string): Promise<boolean> {+ forgetRequestIdentity();const rows = await engine.executeRaw('UPDATE persistence_local_writers SET revoked_at=COALESCE(revoked_at,now()) WHERE id=$1::uuid RETURNING id', [id]);return rows.length === 1;}diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex d164d3aed9..898b1554de 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -152,6 +152,8 @@ export async function stopPersistenceConsumer(engine: BrainEngine): Promise<voidservice.stopping = true;const pending = [...(receiptReads.get(engine)?.values() ?? [])];for (const entry of pending) entry.abort.abort();+ // GBRA-156: a one-shot command's housekeeping runs here, after its reply and before its consumer stops.+ if (service.consumer instanceof PersistenceConsumer) await service.consumer.runOneShotHousekeeping();await service.consumer.stop();await service.heartbeat?.stop();await Promise.all(pending.map(entry => entry.read));diff --git a/src/core/shared-skills/restore.ts b/src/core/shared-skills/restore.tsindex 791d2a55f0..fb5bed79c5 100644--- a/src/core/shared-skills/restore.ts+++ b/src/core/shared-skills/restore.ts@@ -4,6 +4,7 @@ import { AgentInstallError } from '../agent-install/state.ts';import { completeWrite } from '../persistence/journal.ts';import type { WriteRequest } from '../persistence/model.ts';import { declarePersistenceProtocol } from '../persistence/protocol.ts';+import { forgetRequestIdentity } from '../persistence/identity.ts';export interface SharedSkillRestoreOptions {mode?: 'new_brain' | 'recovery';@@ -77,6 +78,7 @@ export async function quarantineSharedSkillRestore(tx: BrainEngine, restoreId: sawait tx.executeRaw('UPDATE oauth_tokens SET expires_at=0');await tx.executeRaw('UPDATE oauth_codes SET expires_at=0');await tx.executeRaw('UPDATE persistence_local_writers SET revoked_at=COALESCE(revoked_at,now())');+ forgetRequestIdentity();await tx.executeRaw('DELETE FROM persistence_writer_protocols');await tx.executeRaw('DELETE FROM persistence_host_bindings');await tx.executeRaw('DELETE FROM persistence_source_bindings');diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 68cf105c84..87c1072e94 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -48,7 +48,7 @@ import { operationScopesAllowed } from '../core/scope.ts';import { enforceReadTrustFloor } from '../core/eligibility/registry.ts';import { invalidateHotMemoryForEngine } from '../core/facts/meta-hook.ts';import { admittedPendingReceipt, type WriteReceipt } from '../core/persistence/types.ts';-import { currentVerifiedLocalWriter, readLocalWriter, verifyLocalWriter, withVerifiedLocalRegistration } from '../core/persistence/identity.ts';+import { currentVerifiedLocalWriter, readLocalWriter, verifyLocalWriter, withRequestIdentityMemo, withVerifiedLocalRegistration } from '../core/persistence/identity.ts';import { frameOverCap, resultTooLargeError } from '../core/egress-budget.ts';// WP3: normalization + validation moved to validate-params.ts (direct unit@@ -872,7 +872,8 @@ export async function dispatchToolCall(): Promise<ToolResult> {// #6721: a read op answers every config read from one snapshot of the table// (config-snapshot.ts); a write reads config live, so it sees its own writes.- const run = () => dispatchResolvedCall(engine, name, params, opts);+ // GBRA-156: and reads the brain identity and each local writer's credential once for its pre-submission checks.+ const run = () => withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, params, opts));return operations.find(o => o.name === name)?.mutating === false? withRequestConfigSnapshot(engine, run): withoutRequestConfigSnapshot(run);diff --git a/test/oneshot-housekeeping-cli.test.ts b/test/oneshot-housekeeping-cli.test.tsnew file mode 100644index 0000000000..1837c887d5--- /dev/null+++ b/test/oneshot-housekeeping-cli.test.ts@@ -0,0 +1,76 @@+/**+ * GBRA-156: a one-shot CLI write (`gbrain put`) on a brain with no resident process runs the consumer's housekeeping after+ * its reply: the compaction pass records its run and compacts the receipts past retention. Runs the real CLI as+ * subprocesses on PGLite and on Postgres.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';++const CLI = join(import.meta.dir, '../src/cli.ts');++for (const backend of testBackends()) {+ describe(`one-shot CLI housekeeping (${backend})`, () => {+ let home: string;+ let close: (() => Promise<void>) | undefined;+ let pg: BrainEngine | undefined;+ const pglite = new PGLiteEngine();++ async function cli(args: string[], stdin?: string, env: Record<string, string> = {}) {+ const child = Bun.spawn([process.execPath, '--no-env-file', CLI, ...args], {+ cwd: home, stdout: 'pipe', stderr: 'pipe', stdin: stdin === undefined ? 'ignore' : new Blob([stdin]),+ env: { PATH: process.env.PATH, HOME: home, GBRAIN_HOME: home, GBRAIN_DISABLE_UPDATE_CHECK: '1', GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0', ...env },+ });+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);+ return { stdout, stderr, code };+ }+ async function sql<T>(text: string, params: unknown[] = []): Promise<T[]> {+ if (pg) return pg.executeRaw<T>(text, params);+ const { database_path } = JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf8'));+ await pglite.connect({ database_path });+ try { return await pglite.executeRaw<T>(text, params); } finally { await pglite.disconnect(); }+ }+ const lastCompaction = async () => (await sql<{ value: string }>("SELECT value FROM config WHERE key='persistence.maintenance.last_compaction'"))[0]?.value;+ const compacted = async () => (await sql<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE compacted'))[0]!.n;++ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), `gbrain-oneshot-housekeeping-${backend}-`));+ if (backend === 'postgres') {+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ close = isolated.close;+ pg = isolated.engine;+ const [database] = await pg.executeRaw<{ name: string }>('SELECT current_database() AS name');+ const url = new URL(process.env.DATABASE_URL!); url.pathname = `/${database!.name}`;+ const init = await cli(['init', '--url', url.toString(), '--non-interactive', '--no-embedding']);+ expect(init.code, init.stderr).toBe(0);+ } else {+ const init = await cli(['init', '--pglite', '--no-embedding']);+ expect(init.code, init.stderr).toBe(0);+ }+ }, 180_000);+ afterAll(async () => {+ await close?.();+ rmSync(home, { recursive: true, force: true });+ });++ test('each put runs the compaction pass after its reply, compacting the receipts past retention', async () => {+ await sql("INSERT INTO config(key,value) VALUES ('persistence.receipt_retention_days','0') ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value");+ const records: string[] = [];+ for (let i = 0; i < 3; i++) {+ const put = await cli(['put', `notes/housekeeping-${i}`, '--content-origin', 'user_said'], `# Housekeeping ${i}\n\nbody ${i}\n`,+ { GBRAIN_ONESHOT_HOUSEKEEPING_INTERVAL_MS: '0' });+ expect(put.code, put.stderr).toBe(0);+ const record = await lastCompaction();+ expect(record).toBeDefined();+ records.push(record!);+ }+ expect(new Set(records.map(record => JSON.parse(record).at)).size).toBe(3);+ expect(await compacted()).toBeGreaterThanOrEqual(2);+ }, 300_000);+ });+}diff --git a/test/write-roundtrips-gbra156.test.ts b/test/write-roundtrips-gbra156.test.tsindex a4033c1ff5..0c81e5ec0f 100644--- a/test/write-roundtrips-gbra156.test.ts+++ b/test/write-roundtrips-gbra156.test.ts@@ -8,13 +8,17 @@ import { readCapacityForecast } from '../src/core/persistence/capacity-forecast.import { cachedCapacitySnapshot } from '../src/core/persistence/capacity-snapshot.ts';import { randomUUID } from 'node:crypto';import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';-import { claimHousekeepingTurn, HOUSEKEEPING_TURN_OP } from '../src/core/persistence/housekeeping-turn.ts';+import { claimHousekeepingTurn, completeHousekeepingTurn, HOUSEKEEPING_TURN_OP } from '../src/core/persistence/housekeeping-turn.ts';import { markOneShotCommand } from '../src/core/persistence/claim-phase.ts';import { disposePersistenceConsumer, startPersistenceConsumer } from '../src/core/persistence/service.ts';import { readWriteSwitchSnapshot, resetWriteSwitches } from '../src/core/persistence/switches.ts';import { commandStartupConfig, keepCommandStartupConfig, requestConfigValue, withRequestConfigSnapshot } from '../src/core/config-snapshot.ts';import { mergeDbPlaneConfig } from '../src/cli/db-plane-config.ts';import { withEnv } from './helpers/with-env.ts';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { readLocalWriter, registerLocalWriter, revokeLocalWriter, verifyLocalWriter, withRequestIdentityMemo } from '../src/core/persistence/identity.ts';import { freshBrainFactory, requestFixture } from './helpers/persistence-request-fixture.ts';import { testBackends } from './helpers/test-backends.ts';@@ -39,7 +43,10 @@ async function recordStatements<T>(engine: BrainEngine, fn: () => Promise<T>): Pconst configReads = (statements: string[]) => statements.filter(s => /FROM config\b/.test(s));-type Gate = { upkeepAllowed(): Promise<boolean>; sweepAllowed(direct: boolean): Promise<boolean>; housekeepingTurn: boolean };+type Gate = { upkeepAllowed(): Promise<boolean>; sweepAllowed(direct: boolean): Promise<boolean>; housekeepingTurn: boolean;+ settleTurn(): void; turnDone?: Promise<void>; stopping: boolean };+const turnState = async (engine: BrainEngine, hostId: string) => (await engine.executeRaw<{ state: string[] }>(+ 'SELECT completed_keys AS state FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [HOUSEKEEPING_TURN_OP, hostId]))[0]?.state;const oneShotConsumer = (engine: BrainEngine, hostId: string, waiting: () => boolean) => new PersistenceConsumer(engine, { engine: engine.kind } as never,async () => { throw new Error('unused'); }, { hostId, oneShot: { waiting } }) as unknown as Gate;const turns = async (engine: BrainEngine, hostId: string) => (await engine.executeRaw<{ n: number }>(@@ -105,6 +112,39 @@ for (const kind of testBackends()) {expect(await claimHousekeepingTurn(engine, host, 60_000)).toBe(true);}, 120_000);+ test('a finished turn holds the host for the interval, judged from when it finished', async () => {+ const engine = await factory.fresh();+ const host = randomUUID();+ expect(await claimHousekeepingTurn(engine, host, 60_000)).toBe(true);+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '2 minutes' WHERE op=$1 AND fingerprint=$2", [HOUSEKEEPING_TURN_OP, host]);+ await completeHousekeepingTurn(engine, host);+ expect(await turnState(engine, host)).toEqual(['done']);+ expect(await claimHousekeepingTurn(engine, host, 600_000)).toBe(false);+ expect(await claimHousekeepingTurn(engine, host, 0)).toBe(true);+ }, 120_000);++ test('a turn cut short is not counted as done: the next process takes it once the lease runs out, not after the interval', async () => {+ const engine = await factory.fresh();+ const host = randomUUID();+ expect(await claimHousekeepingTurn(engine, host, 600_000)).toBe(true);+ expect(await claimHousekeepingTurn(engine, host, 600_000)).toBe(false);+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '2 minutes' WHERE op=$1 AND fingerprint=$2", [HOUSEKEEPING_TURN_OP, host]);+ expect(await claimHousekeepingTurn(engine, host, 600_000)).toBe(true);+ }, 120_000);++ test('a consumer marks its turn done when its upkeep settles, and leaves it leased when a stop aborted that upkeep', async () => {+ const engine = await factory.fresh();+ for (const aborted of [false, true]) {+ const host = randomUUID();+ const consumer = oneShotConsumer(engine, host, () => false);+ expect(await consumer.upkeepAllowed()).toBe(true);+ consumer.stopping = aborted;+ consumer.settleTurn();+ await consumer.turnDone;+ expect(await turnState(engine, host)).toEqual([aborted ? 'leased' : 'done']);+ }+ }, 120_000);+test('no housekeeping turn while a resident full consumer of the host is live', async () => {const engine = await factory.fresh();const host = randomUUID();@@ -159,6 +199,50 @@ for (const kind of testBackends()) {}}, 120_000);+ const identity = (statements: string[]) => ({+ brain: statements.filter(s => s.startsWith('SELECT brain_id FROM persistence_brain')).length,+ writer: statements.filter(s => s.startsWith('SELECT lane,credential_hash,grant_ceiling,revoked_at FROM persistence_local_writers')).length });++ test('one request reads the brain identity and verifies a local writer once for its pre-submission checks', async () => {+ const engine = await factory.fresh();+ await withEnv({ GBRAIN_HOME: mkdtempSync(join(tmpdir(), 'gbra156-identity-')) }, async () => {+ await registerLocalWriter(engine, 'cli');+ const { statements } = await recordStatements(engine, () => withRequestIdentityMemo(async () => {+ const local = await readLocalWriter(engine, 'cli');+ await verifyLocalWriter(engine, await readLocalWriter(engine, 'cli'));+ await verifyLocalWriter(engine, local);+ }));+ expect(identity(statements)).toEqual({ brain: 1, writer: 1 });+ const locked = await recordStatements(engine, () => withRequestIdentityMemo(async () => {+ const local = await readLocalWriter(engine, 'cli');+ await verifyLocalWriter(engine, local, true);+ }));+ expect(locked.statements.filter(s => /persistence_local_writers WHERE id=\$1::uuid FOR SHARE$/.test(s))).toHaveLength(1);+ });+ }, 120_000);++ test('a credential revoked between two requests in the same process is refused on the second', async () => {+ const engine = await factory.fresh();+ await withEnv({ GBRAIN_HOME: mkdtempSync(join(tmpdir(), 'gbra156-revoke-')) }, async () => {+ const local = await registerLocalWriter(engine, 'cli');+ expect((await withRequestIdentityMemo(() => readLocalWriter(engine, 'cli'))).id).toBe(local.id);+ expect(await revokeLocalWriter(engine, local.id)).toBe(true);+ await expect(withRequestIdentityMemo(() => readLocalWriter(engine, 'cli'))).rejects.toMatchObject({ code: 'permission_denied' });+ });+ }, 120_000);++ test('a revocation inside a request is seen by that request\'s later checks', async () => {+ const engine = await factory.fresh();+ await withEnv({ GBRAIN_HOME: mkdtempSync(join(tmpdir(), 'gbra156-revoke-in-')) }, async () => {+ const local = await registerLocalWriter(engine, 'cli');+ await withRequestIdentityMemo(async () => {+ await verifyLocalWriter(engine, local);+ await revokeLocalWriter(engine, local.id);+ await expect(verifyLocalWriter(engine, local)).rejects.toMatchObject({ code: 'permission_denied' });+ });+ });+ }, 120_000);+test('an unreadable retention setting still falls back to the default, and bad thresholds to theirs', async () => {const engine = await factory.fresh();await engine.executeRaw(`INSERT INTO config(key,value) VALUES ('persistence.capacity.warn_days','-1'),('persistence.receipt_retention_days','soon')