Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(#6712 PR 4b): contracts — pass row, sync.admission reader
garrytan99b7074cb499
diff --git a/src/core/persistence/sync-admission.ts b/src/core/persistence/sync-admission.tsnew file mode 100644index 0000000000..d0eba31d29--- /dev/null+++ b/src/core/persistence/sync-admission.ts@@ -0,0 +1,33 @@+/**+ * #6712 PR 4b (design v3.2 §8): `sync.admission`, the brain-wide switch that pauses what a managed pass admits.+ *+ * - `normal` (the default): the pass admits everything it classifies.+ * - `imports_only`: no deletes and no keep_db writes; those paths settle as `paused_deletes` / `paused_keep_db`.+ * - `classify_only`: the pass reads and classifies, writes telemetry only, and stamps nothing (stop `admission_paused`).+ *+ * 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).+ */+import type { BrainEngine } from '../engine.ts';++export const SYNC_ADMISSION_KEY = 'sync.admission';+export const SYNC_ADMISSION_VALUES = ['normal', 'imports_only', 'classify_only'] as const;+export type SyncAdmission = typeof SYNC_ADMISSION_VALUES[number];++export function parseSyncAdmission(value: string | null | undefined): SyncAdmission {+ const trimmed = value?.trim();+ if (!trimmed) return 'normal';+ return (SYNC_ADMISSION_VALUES as readonly string[]).includes(trimmed) ? trimmed as SyncAdmission : 'classify_only';+}++/** The value in effect, read in the caller's transaction (`tx`) when given, so admission and publication see one value. */+export async function readSyncAdmission(engine: Pick<BrainEngine, 'executeRaw'>): Promise<SyncAdmission> {+ const [row] = await engine.executeRaw<{ value: string | null }>('SELECT value FROM config WHERE key=$1', [SYNC_ADMISSION_KEY]);+ return parseSyncAdmission(row?.value ?? null);+}++/** Whether a kind of write may be admitted (or published) under `admission`. */+export function admissionAllows(admission: SyncAdmission, kind: 'import' | 'destructive'): boolean {+ if (admission === 'normal') return true;+ return admission === 'imports_only' && kind === 'import';+}diff --git a/src/core/persistence/sync-pass-row.ts b/src/core/persistence/sync-pass-row.tsnew file mode 100644index 0000000000..868f9d05a4--- /dev/null+++ b/src/core/persistence/sync-pass-row.ts@@ -0,0 +1,156 @@+/**+ * #6712 PR 4b (design v3.2 §3.4): the pass row of a managed source and the rows that live beside it. Kept free of heavy+ * imports: doctor, status, the lease, compaction and GC read it without loading the pass.+ *+ * - `managed-sync-pass`, fingerprint `<source>:<incarnation>`: one row per incarnation. `obligations` are what the next+ * pass must honor (baseline, episode, cost, the converged state, mismatch and not-converged streaks, page faults);+ * `telemetry` is the newest pass's progress and ending. Written at pin, per batch and at the stamp, each time under+ * `assertDrainLease`; after the pin only `WHERE lease_token = $token`, so a pass that lost the lease writes nothing.+ * - `sync-origin-deleted`, fingerprint `<source>:<incarnation>:<origin>`: a deletion marker (design §2.5).+ * - `sync-deletes-withheld`, fingerprint `<source>:<incarnation>`: the mass-delete trip (design §2.6).+ * - `sync-pass-cost`, fingerprint `<source>:<incarnation>:<episode_or_pass_id>:<group_id>`: one cost reservation (design §7).+ *+ * Every value carries `source_id` and `incarnation`, so the checkpoint GC (`op-checkpoint.ts`) keeps the rows of a live+ * incarnation with the same join it uses for `sync-hold`.+ */+import type { BrainEngine } from '../engine.ts';++export const MANAGED_SYNC_PASS_OP = 'managed-sync-pass';+export const SYNC_ORIGIN_DELETED_OP = 'sync-origin-deleted';+export const SYNC_DELETES_WITHHELD_OP = 'sync-deletes-withheld';+export const SYNC_PASS_COST_OP = 'sync-pass-cost';+/** The ops of live-incarnation rows the checkpoint GC must keep (design §3.4). */+export const SYNC_PASS_ROW_OPS = [MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP, SYNC_DELETES_WITHHELD_OP, SYNC_PASS_COST_OP] as const;++/** `open` while the pass runs; the rest are its ending (`DrainOutcome` plus the idle `up_to_date`). */+export type PassOutcome = 'open' | 'synced' | 'up_to_date' | 'resumable' | 'blocked';+export type PassKind = 'idle' | 'hold_only' | 'full';++/** What a pass syncs (design §6): an episode stores it, the configured one stamps `last_commit`. */+export interface SyncSelection { exclude: string[]; includeHidden: string[]; strategy: string | null; srcSubpath: string | null; mode: 'committed' | 'working' }++export interface PassEpisode {+ opened_at: string;+ /** The `--full` that opened it (its pass id), absent for an episode a legacy cursor seeded. */+ full_id?: string;+ selection: SyncSelection;+ inherited: { noEmbed: boolean; noExtract: boolean; noSchemaPack: boolean; from: 'flag' | 'legacy_cursor' };+}++export interface PassConverged {+ target: string;+ at: string;+ /** The highest request `sequence` of the worktree the stamp saw (text: a bigint). */+ request_hwm: string;+ /** Requests and Git effects open on settled paths at the stamp (design §2.2), at most `OPEN_AT_STAMP_CAP`; null when the cap overflowed (no idle). */+ open_at_stamp: string[] | null;+ parser_fp: string;+ pack: string | null;+ selection_fp: string;+ last_full_at: string;+ passes_since_full: number;+}++export interface ManagedSyncPassValue {+ source_id: string;+ incarnation: string;+ lease_token: string;+ obligations: {+ baseline_commit: string | null;+ episode?: PassEpisode;+ cost?: { approved_usd: number | null; reserved_usd: number };+ converged?: PassConverged;+ mismatch: Record<string, { level: string | null; streak: number }>;+ not_converged_streak: number;+ faults: Record<string, { level: string | null; class: string; attempts: number }>;+ };+ telemetry: {+ pass_id: string;+ target: string;+ started_at: string;+ ended_at: string | null;+ kind: PassKind;+ round: number;+ outcome: PassOutcome;+ /** A `DrainStopReason` or a status reason (`not_converged`, `admission_paused`, ...); null while open or synced. */+ stop_reason: string | null;+ candidates: number;+ settled: number;+ /** `|C_k| − |S|` of the newest round; what the movement readers count down. */+ remaining: number;+ counts: Record<string, number>;+ duration_ms: number | null;+ timings_ms: Record<string, number>;+ };+}++export const OPEN_AT_STAMP_CAP = 256;+/** A settle mismatch at one `(path, level)` becomes a hold after this many consecutive passes (design §3.1). */+export const SETTLE_MISMATCH_STREAK = 3;+/** Consecutive `not_converged` passes after which `fix.next` becomes `report` (design §3.1, DX R9). */+export const NOT_CONVERGED_REPORT_STREAK = 3;++export const passFingerprint = (sourceId: string, incarnation: string) => `${sourceId}:${incarnation}`;++export interface PassRow { value: ManagedSyncPassValue; updated_at: string }++type Exec = Pick<BrainEngine, 'executeRaw'>;+const iso = (value: Date | string) => new Date(value).toISOString();++/** The pass row of one incarnation, or null when no pass has run on it. */+export async function readPassRow(engine: Exec, sourceId: string, incarnation: string): Promise<PassRow | null> {+ const [row] = await engine.executeRaw<{ value: ManagedSyncPassValue | null; updated_at: Date | string }>(+ 'SELECT completed_keys->0 AS value, updated_at FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [MANAGED_SYNC_PASS_OP, passFingerprint(sourceId, incarnation)]);+ return row?.value ? { value: row.value, updated_at: iso(row.updated_at) } : null;+}++/** The pass rows of the sources' live incarnations (all sources when `sourceIds` is omitted), keyed by source id. */+export async function readLivePassRows(engine: Exec, sourceIds?: readonly string[]): Promise<Map<string, PassRow>> {+ const rows = await engine.executeRaw<{ source_id: string; value: ManagedSyncPassValue; updated_at: Date | string }>(+ `SELECT s.id AS source_id, c.completed_keys->0 AS value, c.updated_at FROM sources s+ JOIN op_checkpoints c ON c.op=$1 AND c.fingerprint=s.id||':'||s.incarnation::text+ WHERE ($2::text[] IS NULL OR s.id=ANY($2::text[]))`, [MANAGED_SYNC_PASS_OP, sourceIds ? [...sourceIds] : null]);+ return new Map(rows.filter(row => row.value).map(row => [row.source_id, { value: row.value, updated_at: iso(row.updated_at) }]));+}++/**+ * Writes the pass row inside `tx` (the caller has run `assertDrainLease` in the same transaction). `pin`: the pass that+ * just took the lease replaces whatever row a former holder left; otherwise the write lands only while the row still+ * carries `leaseToken`. Returns false when it did not land (another pass pinned since).+ */+export async function writePassRow(tx: Exec, value: ManagedSyncPassValue, opts: { pin?: boolean } = {}): Promise<boolean> {+ const rows = await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now())+ ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now()+ WHERE $4::boolean OR op_checkpoints.completed_keys->0->>'lease_token'=$5 RETURNING 1`,+ [MANAGED_SYNC_PASS_OP, passFingerprint(value.source_id, value.incarnation), JSON.stringify(value), opts.pin === true, value.lease_token]);+ return rows.length > 0;+}++/** A pass row's health for the readers of design §3.7 (doctor movement and git-holds, the lease's progress, status). */+export interface PassHealth {+ /** The newest pass ended `blocked`, the not-converged streak is running, a settle mismatch is streaking, or an open pass stopped moving. */+ unhealthy: boolean;+ reason: 'blocked' | 'not_converged' | 'settle_mismatch' | 'open_stalled' | null;+ /** Nothing is left for sync to do at `head`: converged there and the newest pass ended `synced` or `up_to_date`. */+ nothing_pending: boolean;+ remaining: number | null;+ last_progress_at: string;+}++/**+ * One rule for every health reader (design §3.7: a pass that stops `blocked` or `not_converged` on every tick must read+ * unhealthy). `stalledMs`: an open pass whose row has not moved for that long reads `open_stalled`.+ */+export function passHealth(row: PassRow, opts: { head?: string | null; now?: number; stalledMs: number }): PassHealth {+ const { telemetry: t, obligations: o } = row.value;+ const now = opts.now ?? Date.now();+ const mismatch = Object.values(o.mismatch ?? {}).some(entry => entry.streak >= SETTLE_MISMATCH_STREAK - 1);+ const reason: PassHealth['reason'] = t.outcome === 'blocked' ? 'blocked'+ : (o.not_converged_streak ?? 0) > 0 ? 'not_converged'+ : mismatch ? 'settle_mismatch'+ : t.outcome === 'open' && now - Date.parse(row.updated_at) >= opts.stalledMs ? 'open_stalled'+ : null;+ const ended = t.outcome === 'synced' || t.outcome === 'up_to_date';+ return { unhealthy: reason !== null, reason, remaining: ended ? 0 : t.remaining,+ nothing_pending: ended && !!o.converged && (opts.head == null || o.converged.target === opts.head), last_progress_at: row.updated_at };+}diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 21668a6ca1..3246ca7f62 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -37,11 +37,9 @@ import { probeDirtiness, readBlobs, readIndexLevel, readTreeLevel, type GitTreeEimport { classifySyncPath, syncPassKind, type SyncClassified, type SyncIdleBlocker, type SyncPathState } from './sync-classify.ts';import { buildConvergenceReceipt, readOnlySameContentScreen, type ConvergenceReceipt, type ConvergenceScreen } from './sync-convergence.ts';import { readManagedMode } from './ownership.ts';+import { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP } from './sync-pass-row.ts';-/** The deletion marker op PR 4b writes in every page-row deletion (design v3.2 §2.5); PR 4a only reads it. */-export const SYNC_ORIGIN_DELETED_OP = 'sync-origin-deleted';-/** The pass row PR 4b writes (design v3.2 §3.4); PR 4a only reads it, so a shadow pass is always a full round. */-export const MANAGED_SYNC_PASS_OP = 'managed-sync-pass';+export { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP };/** PGLite's keyset page size (design v3.2 §2.1); Postgres reads `I⋈P` in one statement of its snapshot. */const PGLITE_KEYSET_ROWS = 2_000;/** Blob bytes read for adoption by hash and the screen, per blob. */