Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip(#6712 PR 4b lane S): sync.admission set_at, status, doctor check

garrytanc3bc08599ec9
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 26da2f2166..2641c6395d 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -378,6 +378,7 @@ const setLineGrammarConfig = async (engine: BrainEngine, key: string, value: str
async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value: string, force = false): Promise<void> {
if (await setLineGrammarConfig(engine, key, value)) return;
+ if (key === 'sync.admission') return (await import('./config/sync-admission-value.ts')).setSyncAdmissionValue(engine, value);
if (key.startsWith('decide.')) {
const { validateDecideConfigValue } = await import('../core/ai/decide/config.ts');
const err = validateDecideConfigValue(key, value);
diff --git a/src/commands/config/sync-admission-value.ts b/src/commands/config/sync-admission-value.ts
new file mode 100644
index 0000000000..65ab15c84d
--- /dev/null
+++ b/src/commands/config/sync-admission-value.ts
@@ -0,0 +1,21 @@
+/**
+ * #6712 PR 4b: `config set sync.admission`. A value outside `normal | imports_only | classify_only` is refused as a
+ * usage error (exit 2) and nothing is written, `--force` included (the reader would fail it closed to
+ * `classify_only`). A valid value is stored with its `set_at` in one transaction (persistence/sync-admission.ts).
+ * `config` refuses on a thin client and no remote operation writes config, so the switch is set only on the brain host.
+ */
+import type { BrainEngine } from '../../core/engine.ts';
+import { SYNC_ADMISSION_KEY, SYNC_ADMISSION_VALUES, writeSyncAdmission, type SyncAdmission } from '../../core/persistence/sync-admission.ts';
+import { inertText } from '../../core/agent-output.ts';
+import { exitCliError, usageError } from '../../cli/cli-error.ts';
+
+export async function setSyncAdmissionValue(engine: BrainEngine, value: string): Promise<void> {
+ if (!(SYNC_ADMISSION_VALUES as readonly string[]).includes(value)) {
+ exitCliError(usageError(`${SYNC_ADMISSION_KEY} is one of ${SYNC_ADMISSION_VALUES.join(', ')}; "${inertText(value, 40)}" is not. Nothing was written.`,
+ `Re-run with one of them, e.g. gbrain config set ${SYNC_ADMISSION_KEY} normal (the default: managed sync admits everything it classifies).`, {
+ why: 'Managed sync reads any other stored value as classify_only (fail closed), which would stop every write.',
+ fix: { argv: ['gbrain', 'config', 'get', SYNC_ADMISSION_KEY], consent: [], actor: 'agent', why: 'Shows the value in effect and when it was set; nothing was written.', requires_exclusive: false },
+ }), 'config');
+ }
+ await writeSyncAdmission(engine, value as SyncAdmission);
+}
diff --git a/src/commands/doctor/checks/sync-admission.ts b/src/commands/doctor/checks/sync-admission.ts
new file mode 100644
index 0000000000..c7c0a7242b
--- /dev/null
+++ b/src/commands/doctor/checks/sync-admission.ts
@@ -0,0 +1,50 @@
+/**
+ * #6712 PR 4b (design v3.2 §8): `sync_admission_restricted`. While `sync.admission` is not `normal`, managed sync
+ * admits less than it classifies (`imports_only`: no deletes and no keep_db writes; `classify_only`: nothing), so the
+ * check warns with the value, its age (from `set_at`) and the restore command, which only the user runs. A brain that
+ * is not managed has no managed pass to restrict, so the check is ok there. It reads config and one checkpoint row.
+ */
+import type { Check } from '../../doctor.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { checkError, doctorVerify } from '../check-fix.ts';
+import { readManagedMode } from '../../../core/persistence/managed-mode.ts';
+import { SYNC_ADMISSION_KEY, readSyncAdmissionSetting } from '../../../core/persistence/sync-admission.ts';
+
+const NAME = 'sync_admission_restricted';
+const DOCS = 'docs/guides/error-codes.md#sync_admission_restricted';
+const PAUSED = { imports_only: 'admits no deletes and no keep_db writes (those paths wait as paused_deletes and paused_keep_db; imports continue)',
+ classify_only: 'reads and classifies only: it writes and stamps nothing (stop admission_paused)' } as const;
+
+async function runSyncAdmissionCheck(ctx: DoctorContext): Promise<Check[]> {
+ try {
+ const engine = connectedEngine(ctx);
+ const setting = await readSyncAdmissionSetting(engine);
+ const ageSeconds = setting.set_at ? Math.max(0, Math.round((Date.now() - Date.parse(setting.set_at)) / 1000)) : null;
+ const details = { value: setting.value, stored: setting.stored, set_at: setting.set_at, age_seconds: ageSeconds, docs: DOCS };
+ if (setting.value === 'normal') return [{ name: NAME, status: 'ok', message: `${SYNC_ADMISSION_KEY} is normal: managed sync admits everything it classifies.`, details }];
+ if (!await readManagedMode(engine)) {
+ return [{ name: NAME, status: 'ok', severity: 'info', readiness_state: 'not_applicable', details,
+ message: `${SYNC_ADMISSION_KEY} is ${setting.value}, but this brain is not managed, so no managed sync reads it.` }];
+ }
+ const value = setting.value as keyof typeof PAUSED;
+ const stored = setting.stored !== value ? ` (the stored value ${JSON.stringify((setting.stored ?? '').slice(0, 40))} is not a value and reads as ${value}, fail closed)` : '';
+ const age = ageSeconds === null ? 'set at an unknown time' : `set ${formatAge(ageSeconds)} ago (${setting.set_at})`;
+ return [{ name: NAME, status: 'warn', details,
+ message: `${SYNC_ADMISSION_KEY} is ${value}${stored}, ${age}: managed sync ${PAUSED[value]}. Ask the user whether the reason for restricting it still holds; `
+ + `gbrain config set ${SYNC_ADMISSION_KEY} normal restores it, and the next sync admits what waited.`,
+ fix: { argv: ['gbrain', 'config', 'set', SYNC_ADMISSION_KEY, 'normal'], consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify(NAME), docs: DOCS,
+ why: `Restores the default, so managed sync admits deletes and keep_db writes again. The owner chose ${value}; only they restore it, and gbrain never runs this on its own.` } }];
+ } catch (error) {
+ return [checkError(NAME, 'read sync.admission', error, { details: { docs: DOCS } })];
+ }
+}
+
+function formatAge(seconds: number): string {
+ if (seconds < 120) return `${seconds}s`;
+ if (seconds < 7200) return `${Math.round(seconds / 60)}m`;
+ if (seconds < 172_800) return `${Math.round(seconds / 3600)}h`;
+ return `${Math.round(seconds / 86_400)}d`;
+}
+
+/** An ops section: one config read and one checkpoint row, cheap on every engine. */
+export const syncAdmissionEntry: DoctorEntry = { name: NAME, emits: [NAME], tier: 'ops', run: runSyncAdmissionCheck };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 87f1ee3bd5..0ad6bfa328 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -121,6 +121,7 @@ import { missingRecordedFilesEntry } from './checks/missing-recorded-files.ts';
import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';
import { managedSyncConvergenceEntry } from './checks/managed-sync-convergence.ts';
import { managedSyncBlockedEntry } from './checks/managed-sync-blocked.ts';
+import { syncAdmissionEntry } from './checks/sync-admission.ts';
import { atomHeldFailedEntry } from './checks/atom-holds.ts';
import { extractionInputTruncatedEntry } from './checks/extraction-input.ts';
import {
@@ -168,6 +169,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
terminalFailuresEntry,
managedSyncMovementEntry,
managedSyncBlockedEntry,
+ syncAdmissionEntry,
persistenceCompactionEntry,
soakCountersEntry,
serveBuildDriftEntry,
diff --git a/src/core/config.ts b/src/core/config.ts
index 50bfceb191..6452cf24e9 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1720,6 +1720,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'orphans.exclude_prefixes',
'orphans.exclude_slugs',
'sync.cost_gate_min_usd',
+ 'sync.admission', // #6712 PR 4b: normal | imports_only | classify_only, what a managed pass admits (persistence/sync-admission.ts)
'sync.federated_v2',
'sync.include_working_tree',
// #5984: managed Postgres sync publishes pages in bulk groups (on by default; each page keeps its own request).
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 1d08de891b..ef3870895c 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -293,6 +293,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'managed_sync_blocked',
// #6712 PR 4a: the read-only convergence shadow's counts (doctor/checks/managed-sync-convergence.ts).
'managed_sync_convergence',
+ // #6712 PR 4b: sync.admission is not normal, so managed sync admits less than it classifies (doctor/checks/sync-admission.ts).
+ 'sync_admission_restricted',
'persistence_session_timeouts',
// #6317: consumer heartbeat rows and host identity (doctor/checks/persistence-consumers.ts).
'two_consumers_on_host',
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 32b51e6949..ffc68b52e5 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -564,6 +564,13 @@ export const CODES = {
suggestion: 'For persistence_mode_unknown: run gbrain sources writer status --probe --json on the brain host (it reports the malformed state instead of refusing), fix the persistence_brain row it names, then gbrain doctor --json.' },
sync_not_applicable: { class: 'caller', summary: "Sync does not apply to this source: its directory is not a Git checkout.", why: "Sync imports changes between Git commits. A gbrain-owned content directory (created by init) holds files gbrain manages itself and is not a Git repository, so there is nothing to sync; gbrain never initializes Git on its own.", reasons: ['content_directory'] },
// #6712 PR 1: the drain lease (src/core/persistence/sync-lease.ts).
+ sync_admission_restricted: { class: 'host_only', retryable: false, actor: 'user',
+ summary: "`sync.admission` is not `normal`, so managed sync admits less than it classifies: `imports_only` admits no deletes and no keep_db writes (they wait as `paused_deletes` and `paused_keep_db`), and `classify_only` writes and stamps nothing.",
+ why: "The owner sets the switch on the brain host (`gbrain config set`; it is never settable remotely) as the first response to a suspected sync bug. A pass reads it at pin and in every group's admission, and a destructive request re-reads it at publication, so the change applies at the next group; `sync status --json` reports `admission: {value, set_at, effective}`, where `effective` turns true once no pass pinned before `set_at` holds the lease and no delete or keep_db reconcile admitted before it is unpublished. Doctor warns, with the value's age, for as long as it stays restricted.",
+ suggestion: 'Tell the user how long ago the switch was set and ask whether its reason still holds. Only they restore it: gbrain config set sync.admission normal on the brain host; the next sync admits what waited.',
+ fix: { argv: ['gbrain', 'config', 'set', 'sync.admission', 'normal'], consent: [], actor: 'user', requires_exclusive: false,
+ why: 'Restores the default; the owner chose the restriction, so only they lift it, and gbrain never runs this on its own.',
+ verify: { argv: ['gbrain', 'doctor', '--only', 'sync_admission_restricted', '--json'] } } },
sync_drain_lease_held: { class: 'retryable', actor: 'provider',
summary: "Another process holds the source's drain lease and is still committing pages; this run followed it until its own budget ended, or lost the lease mid-pass, and stopped `resumable`.",
why: "One managed drainer per source: two drainers on one cursor raced each other's checkpoints. A follower counts the holder's commits as its own progress, takes the lease when the holder releases it, and stops `drain_stalled` (cause `no_progress`) instead when the holder commits nothing for 5 minutes, so a wedged holder never reads as a clean exit.",
diff --git a/src/core/persistence/sync-admission.ts b/src/core/persistence/sync-admission.ts
index d0eba31d29..9c3a74fbf8 100644
--- a/src/core/persistence/sync-admission.ts
+++ b/src/core/persistence/sync-admission.ts
@@ -7,8 +7,17 @@
*
* The value is read at pin, inside every group's admission transaction, and by the destructive kinds at publication, so
* a change takes effect at the next group. An unrecognized stored value reads as `classify_only` (fail closed).
+ *
+ * `set_at`: the config table has no timestamp, so local `gbrain config set` (`writeSyncAdmission`) records the value
+ * and the database's clock in an `op_checkpoints` row (`op='sync-admission'`, fingerprint `brain`) in the same
+ * transaction as the config row. The row dates the stored value only while it names that value: a value written any
+ * other way (or a row the checkpoint GC dropped) reads `set_at: null`. `syncAdmissionStatus` turns `effective` once
+ * no pass pinned before `set_at` holds the lease and no destructive request admitted before it is unpublished; with
+ * `set_at` unknown, every open pass and every unpublished destructive request counts as earlier.
*/
import type { BrainEngine } from '../engine.ts';
+import { syncLockId } from '../db-lock.ts';
+import { MANAGED_SYNC_PASS_OP, passFingerprint } from './sync-pass-row.ts';
export const SYNC_ADMISSION_KEY = 'sync.admission';
export const SYNC_ADMISSION_VALUES = ['normal', 'imports_only', 'classify_only'] as const;
@@ -31,3 +40,72 @@ export function admissionAllows(admission: SyncAdmission, kind: 'import' | 'dest
if (admission === 'normal') return true;
return admission === 'imports_only' && kind === 'import';
}
+
+/** The `op_checkpoints` row that dates the stored value (see the module comment). */
+export const SYNC_ADMISSION_SET_OP = 'sync-admission';
+const SET_FINGERPRINT = 'brain';
+/** The destructive request kinds (design §8): a managed delete, and the DB-wins reconcile keep_db admits. */
+export const SYNC_ADMISSION_DESTRUCTIVE_KINDS = ['managed_sync_delete', 'canonical_reconcile'] as const;
+
+type Exec = Pick<BrainEngine, 'executeRaw'>;
+const iso = (value: Date | string | null | undefined) => value == null ? null : new Date(value).toISOString();
+
+export interface SyncAdmissionSetting {
+ /** The value in effect (`parseSyncAdmission` of the stored one). */
+ value: SyncAdmission;
+ /** The stored config value, verbatim (null when unset). */
+ stored: string | null;
+ /** When local `config set` wrote the stored value (database clock), or null when unknown or unset. */
+ set_at: string | null;
+}
+
+export interface SyncAdmissionStatus { value: SyncAdmission; set_at: string | null; effective: boolean }
+
+/** The value in effect, the stored value and its `set_at`, in one read. */
+export async function readSyncAdmissionSetting(engine: Exec): Promise<SyncAdmissionSetting> {
+ const { raw_set_at, ...setting } = await readSetting(engine);
+ return { ...setting, set_at: iso(raw_set_at) };
+}
+
+async function readSetting(engine: Exec): Promise<Omit<SyncAdmissionSetting, 'set_at'> & { raw_set_at: string | null }> {
+ const [row] = await engine.executeRaw<{ stored: string | null; row_value: string | null; set_at: string | null }>(
+ `SELECT c.value AS stored, o.completed_keys->0->>'value' AS row_value, o.completed_keys->0->>'set_at' AS set_at
+ FROM (SELECT 1) one LEFT JOIN config c ON c.key=$1 LEFT JOIN op_checkpoints o ON o.op=$2 AND o.fingerprint=$3`,
+ [SYNC_ADMISSION_KEY, SYNC_ADMISSION_SET_OP, SET_FINGERPRINT]);
+ const stored = row?.stored ?? null;
+ return { value: parseSyncAdmission(stored), stored, raw_set_at: stored !== null && row?.row_value === stored ? row.set_at : null };
+}
+
+/** Stores `value` and its `set_at` (database clock) in one transaction; returns `set_at`. The caller validated `value`. */
+export async function writeSyncAdmission(engine: Pick<BrainEngine, 'transaction'>, value: SyncAdmission): Promise<string> {
+ return engine.transaction(async tx => {
+ await tx.setConfig(SYNC_ADMISSION_KEY, value);
+ const [row] = await tx.executeRaw<{ set_at: string }>(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at)
+ VALUES($1,$2,jsonb_build_array(jsonb_build_object('value',$3::text,'set_at',clock_timestamp())),now())
+ ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now()
+ RETURNING completed_keys->0->>'set_at' AS set_at`, [SYNC_ADMISSION_SET_OP, SET_FINGERPRINT, value]);
+ return iso(row!.set_at)!;
+ });
+}
+
+/**
+ * `sync status`'s `admission` of one source incarnation (design §8). `effective` is always true for `normal`; otherwise
+ * it is false while the source's pass row is `open` with `started_at` before `set_at` and its `lease_token` holds the
+ * live drain lease, or while a destructive request of the incarnation admitted before `set_at` is still queued,
+ * running or recovering.
+ */
+export async function syncAdmissionStatus(engine: Exec, sourceId: string, incarnation: string): Promise<SyncAdmissionStatus> {
+ const { value, raw_set_at } = await readSetting(engine);
+ const set_at = iso(raw_set_at);
+ if (value === 'normal') return { value, set_at, effective: true };
+ const [row] = await engine.executeRaw<{ pinned: boolean; destructive: boolean }>(`SELECT
+ EXISTS (SELECT 1 FROM op_checkpoints p JOIN gbrain_cycle_locks l ON l.id=$1 AND l.ttl_expires_at > now()
+ AND l.acquisition_token::text = p.completed_keys->0->>'lease_token'
+ WHERE p.op=$2 AND p.fingerprint=$3 AND p.completed_keys->0->'telemetry'->>'outcome'='open'
+ AND ($4::timestamptz IS NULL OR (p.completed_keys->0->'telemetry'->>'started_at')::timestamptz < $4::timestamptz)) AS pinned,
+ EXISTS (SELECT 1 FROM persistence_requests r WHERE r.source_id=$5 AND r.source_incarnation=$6::uuid
+ AND r.state IN ('queued','running','recovering') AND r.intent->>'kind' = ANY($7::text[])
+ AND ($4::timestamptz IS NULL OR r.created_at < $4::timestamptz)) AS destructive`,
+ [syncLockId(sourceId), MANAGED_SYNC_PASS_OP, passFingerprint(sourceId, incarnation), raw_set_at, sourceId, incarnation, [...SYNC_ADMISSION_DESTRUCTIVE_KINDS]]);
+ return { value, set_at, effective: !row?.pinned && !row?.destructive };
+}
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 9a12742c9a..02f860b2fa 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -136,6 +136,8 @@ export interface SyncStatus {
*/
convergence: import('./sync-convergence.ts').ConvergenceReceipt | { dry_run: true; status: 'unavailable'; code: string; message: string } | null;
convergence_read: SyncStatusRead;
+ /** #6712 PR 4b: `sync.admission` (brain-wide), when it was set, and whether it is in effect for this source (sync-admission.ts). */
+ admission: import('./sync-admission.ts').SyncAdmissionStatus;
}
export type SyncStatusState = 'synced' | 'resumable' | 'blocked';
/** Why the source is in its state; one closed list. */
@@ -313,7 +315,8 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
state, reason: stateReason,
oldest_blocker: oldest, recovery, checkpoint_blockers_read: detail ? { status: 'read' } : notRead('checkpoint blocker list'),
cursors_read: detail ? { status: 'read' } : notRead('live cursor'), terminal_failures_read: detail ? { status: 'read' } : notRead('terminal-failure summary'),
- convergence: detail ? await (await import('./sync-pass.ts')).statusConvergence(engine, sourceId) : null, convergence_read: detail ? { status: 'read' } : notRead('convergence shadow') };
+ convergence: detail ? await (await import('./sync-pass.ts')).statusConvergence(engine, sourceId) : null, convergence_read: detail ? { status: 'read' } : notRead('convergence shadow'),
+ admission: await (await import('./sync-admission.ts')).syncAdmissionStatus(engine, sourceId, source.incarnation) };
}
/** #6712 PR 2: the state and its reason, from what this read saw; a probe that did not answer never yields `synced`. */
diff --git a/src/core/sync-config-keys.ts b/src/core/sync-config-keys.ts
index 4c8526da63..9a4963cb74 100644
--- a/src/core/sync-config-keys.ts
+++ b/src/core/sync-config-keys.ts
@@ -11,9 +11,10 @@
* stored before the upgrade as unapplied.
*/
import { CONFIG_ROLLBACK_WINDOWS, type ConfigRollbackWindow } from './wire-skew.ts';
+import type { BrainEngine } from './engine.ts';
export const SYNC_TUNABLE_KEYS = ['sync.bulk_size', 'sync.lanes', 'sync.exclude', 'sync.include_hidden', 'sync.include_working_tree', 'sync.holds',
- 'sync.write_through', 'sync.cost_gate_min_usd'] as const;
+ 'sync.write_through', 'sync.cost_gate_min_usd', 'sync.admission'] as const;
export interface RetiredSyncKey {
key: string;
@@ -120,8 +121,18 @@ export function syncKeySetNotice(key: string): { writes: boolean; lines: string[
* `gbrain config get|set` of a retired or rollback key. `get` prints the value in effect (stdout) and its origin
* (stderr); `set` prints the key's notice. True when the command is done: every `get`, and the `set` of a retired key,
* which writes nothing. A rollback key's `set` returns false so the write goes ahead; any other key returns false.
+ * #6712 PR 4b: `get sync.admission` prints the value in effect (`normal` when unset) and when it was set.
*/
-export async function handleSyncKeyConfig(engine: { getConfig(key: string): Promise<string | null> }, action: 'get' | 'set', key: string): Promise<boolean> {
+export async function handleSyncKeyConfig(engine: Pick<BrainEngine, 'getConfig' | 'executeRaw'>, action: 'get' | 'set', key: string): Promise<boolean> {
+ if (action === 'get' && key === 'sync.admission') {
+ const { readSyncAdmissionSetting } = await import('./persistence/sync-admission.ts');
+ const setting = await readSyncAdmissionSetting(engine);
+ console.log(setting.value);
+ console.error(`[config] source: ${setting.stored === null ? 'default (unset)'
+ : setting.stored !== setting.value ? `brain config holds ${JSON.stringify(setting.stored.slice(0, 40))}, which is not a value; managed sync reads it as ${setting.value} (fail closed)`
+ : `brain config${setting.set_at ? `, set at ${setting.set_at}` : ' (set_at unknown)'}`}${setting.value === 'normal' ? '' : '. Restore the default with gbrain config set sync.admission normal'}.`);
+ return true;
+ }
if (!retiredSyncKey(key) && !rollbackSyncKey(key)) return false;
if (action === 'set') {
const notice = syncKeySetNotice(key)!;