Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(#6712 PR 4b lane B): episode closure by inclusion or configured selection; cost reservation rows
garrytan4be53d4f7645
diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex eec0436fbd..78686a759a 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -171,6 +171,8 @@ export {} from '../core/sync-cost-gate.ts';export interface SyncOpts {+ /** #6712 PR 4b (design §7): the owner approved this sync's paid work (`--yes`); an unknown pass cost no longer defers it. */+ costApproved?: boolean;repoPath?: string;dryRun?: boolean;full?: boolean;diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex 7597ef2713..974959a828 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -816,6 +816,7 @@ async function runSingleSourceSync(includeHidden: includeHiddenPatterns.length > 0 ? includeHiddenPatterns : undefined,signal: composeAbortSignals(singleSourceInterrupt.signal, singleSourceController?.signal),drain: true, noBulk, lanes, followDrainLease: true, drainHolder: { kind: 'cli', id: null },+ ...(yesFlag ? { costApproved: true } : {}),};// v0.42.42.0 (#2139, Step 4b): single-source `gbrain sync` gets the SAMEdiff --git a/src/core/persistence/sync-pass-batch.ts b/src/core/persistence/sync-pass-batch.tsindex a01c7900bc..097df4546f 100644--- a/src/core/persistence/sync-pass-batch.ts+++ b/src/core/persistence/sync-pass-batch.ts@@ -7,6 +7,7 @@ import type { BrainEngine } from '../engine.ts';import type { SyncEntry } from './sync-discovery.ts';import { assertDrainLease } from './sync-lease.ts';import { admissionAllows, readSyncAdmission, type SyncAdmission } from './sync-admission.ts';+import { reservePassCost, type PricedIntent } from './sync-pass-episode.ts';/*** #6712 PR 4b (design v3.2 §3.1): a live pass admits each round batch through the cursor machinery of sync-run.ts with no@@ -83,10 +84,12 @@ export class SyncAdmissionPaused extends Error {* Fencing 1 (design v3.2 §8): a pass's admission transaction re-reads `sync.admission` and admits nothing it no longer* allows (a delete needs `normal`; an import or the stamp needs `normal` or `imports_only`). Cursor intents are unaffected.*/-export async function assertPassAdmission(tx: Pick<BrainEngine, 'executeRaw'>, intents: ReadonlyArray<{ passId?: string; kind: string }>): Promise<void> {+export async function assertPassAdmission(tx: Pick<BrainEngine, 'executeRaw'>, intents: ReadonlyArray<PricedIntent>): Promise<void> {if (!intents.some(intent => intent.passId)) return;const admission = await readSyncAdmission(tx);for (const intent of intents) {if (intent.passId && !admissionAllows(admission, intent.kind === 'managed_sync_delete' ? 'destructive' : 'import')) throw new SyncAdmissionPaused(admission);}+ // Design v3.2 §7: the group's cost reservation commits with its admission.+ await reservePassCost(tx, intents);}diff --git a/src/core/persistence/sync-pass-episode.ts b/src/core/persistence/sync-pass-episode.tsnew file mode 100644index 0000000000..c57843366f--- /dev/null+++ b/src/core/persistence/sync-pass-episode.ts@@ -0,0 +1,128 @@+/**+ * #6712 PR 4b (design v3.2 §6, §7): a live pass's episode closure and its cost reservations.+ *+ * **Closure** (§6, dx-outside-1, eng-outside-2). An episode stores its selection, so its universe is `U_E = eligible_E(T)`.+ * A converged round closes it in the pass's checkpoint when either (a) `U_E ⊆ U_pass`, a set inclusion over the paths+ * of `T`, or (b) the pass is at the configured selection, which releases the paths of `U_E` the source does not sync.+ * `chunker_version` is stamped only when (b) holds and `U_E ⊇ U_config`. So a scoped `--full --exclude X` closes its own+ * episode by (a) without advancing `last_commit`; a plain sync closes any episode by (b); a narrower takeover satisfies+ * neither and leaves it open. There is no abandon command: the plain sync (`resume_argv`) always terminates.+ *+ * **Cost** (§7). Each admitted group reserves its priced embedding spend in its own row, `op='sync-pass-cost'`,+ * fingerprint `<source>:<incarnation>:<episode_or_pass_id>:<group_id>`, value `{source_id, incarnation, usd}`, inserted+ * `ON CONFLICT DO NOTHING` inside the group's admission transaction (`reservePassCost`, from `assertPassAdmission`), so a+ * kill after the admission keeps the reservation and a replay adds nothing. `reserved_usd` is a range read. A pass row+ * lost while reservations exist makes the cost `unknown`: paid work defers until the owner approves again (`--yes`).+ */+import { realpathSync } from 'node:fs';+import { relative, sep } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { estimateCostFromChars } from '../embedding-pricing.ts';+import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';+import { isSyncable, matchesAnyGlob } from '../sync.ts';+import { parseUsdLimit } from '../spend-posture.ts';+import { digest } from './digest.ts';+import { readTreeLevel } from './sync-git-stream.ts';+import { SYNC_PASS_COST_OP, type PassEpisode, type SyncSelection } from './sync-pass-row.ts';++type Exec = Pick<BrainEngine, 'executeRaw'>;++/** Whether a Git-root path is in the universe of `selection` (the eligibility of sync-pass.ts `readShadowLevel`). */+export function selectionEligible(selection: SyncSelection, scope: string, slugMode: 'git-root' | 'source-root'): (gitPath: string) => boolean {+ const sub = selection.srcSubpath ? selection.srcSubpath.replace(/^\/+|\/+$/g, '') : scope;+ const includeHidden = selection.includeHidden.map(v => v.endsWith('/') ? `${v}**` : v);+ return gitPath => {+ if (sub && !gitPath.startsWith(`${sub}/`)) return false;+ const sourceRelative = sub ? gitPath.slice(sub.length + 1) : gitPath;+ return !matchesAnyGlob(sourceRelative, selection.exclude) && !isReservedSkillBundlePath(slugMode === 'source-root' ? sourceRelative : gitPath)+ && isSyncable(gitPath, { strategy: (selection.strategy ?? 'markdown') as 'markdown', includeHidden });+ };+}++export interface EpisodeClosure {+ closes: boolean;+ by: 'inclusion' | 'configured' | null;+ /** (b) and `U_E ⊇ U_config`. */+ stampChunker: boolean;+ /** Paths of `U_E` outside the configured universe that a closure by (b) releases. */+ released: number;+}++/** Design §6's closure test over the paths of `T` (the module header). */+export function episodeClosure(input: { treePaths: Iterable<string>; episode: SyncSelection; pass: SyncSelection; configuredSelection: SyncSelection; configured: boolean;+ scope: string; slugMode: 'git-root' | 'source-root' }): EpisodeClosure {+ const inE = selectionEligible(input.episode, input.scope, input.slugMode);+ const inPass = selectionEligible(input.pass, input.scope, input.slugMode);+ const inConfig = selectionEligible(input.configuredSelection, input.scope, input.slugMode);+ let included = true, covers = true, released = 0;+ for (const path of input.treePaths) {+ const e = inE(path), c = inConfig(path);+ if (e && !inPass(path)) included = false;+ if (c && !e) covers = false;+ if (e && !c) released++;+ }+ if (input.configured) return { closes: true, by: 'configured', stampChunker: covers, released };+ return included ? { closes: true, by: 'inclusion', stampChunker: false, released: 0 } : { closes: false, by: null, stampChunker: false, released: 0 };+}++/** The closure of an open episode at the pinned target `head` (one `ls-tree` of the whole commit). */+export async function passEpisodeClosure(input: { gitRoot: string; root: string; head: string; slugMode: 'git-root' | 'source-root'; episode: PassEpisode; pass: SyncSelection;+ configuredSelection: SyncSelection; configured: boolean }): Promise<EpisodeClosure> {+ const scope = relative(realpathSync.native(input.gitRoot), realpathSync.native(input.root)).split(sep).join('/');+ const tree = await readTreeLevel(input.gitRoot, input.head, '');+ return episodeClosure({ treePaths: tree.keys(), episode: input.episode.selection, pass: input.pass, configuredSelection: input.configuredSelection, configured: input.configured, scope, slugMode: input.slugMode });+}++/** What a pass's admissions reserve under (registered at pin, dropped at the pass's end). */+interface PassCostScope { sourceId: string; incarnation: string; scope: string; pricePerMTok: number }+const passCostScopes = new Map<string, PassCostScope>();++export function registerPassCost(passId: string, scope: PassCostScope): void { passCostScopes.set(passId, scope); }+export function unregisterPassCost(passId: string): void { passCostScopes.delete(passId); }++const costPrefix = (sourceId: string, incarnation: string, scope?: string) => `${sourceId}:${incarnation}:${scope === undefined ? '' : `${scope}:`}`;++/** The intent fields a reservation prices: imports whose embeddings are not opted out, by their content's length. */+export interface PricedIntent { passId?: string; kind: string; path?: string | null; level?: string | null; content?: string | null; processingOptions?: { noEmbed?: boolean } | null }++/**+ * Inside a group's admission transaction: reserves the group's priced embedding spend as one `sync-pass-cost` row,+ * `ON CONFLICT DO NOTHING` (a replay of the same group reserves nothing more). A group with no paid import reserves nothing.+ */+export async function reservePassCost(tx: Exec, intents: ReadonlyArray<PricedIntent>): Promise<void> {+ const passId = intents.find(intent => intent.passId)?.passId;+ const scope = passId ? passCostScopes.get(passId) : undefined;+ if (!scope) return;+ const paid = intents.filter(intent => intent.passId === passId && intent.kind === 'managed_sync_import' && intent.processingOptions?.noEmbed !== true && typeof intent.content === 'string');+ if (!paid.length) return;+ const chars = paid.reduce((sum, intent) => sum + intent.content!.length, 0);+ const groupId = digest(['sync-pass-cost-v1', passId!, ...paid.map(intent => `${intent.path ?? ''}\0${intent.level ?? ''}`).sort()]).slice(0, 32);+ 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 NOTHING`,+ [SYNC_PASS_COST_OP, `${costPrefix(scope.sourceId, scope.incarnation, scope.scope)}${groupId}`,+ JSON.stringify({ source_id: scope.sourceId, incarnation: scope.incarnation, usd: estimateCostFromChars(chars, scope.pricePerMTok) })]);+}++/** `reserved_usd`: the reservations of one episode (or pass) scope, or of the whole incarnation; a range read. */+export async function readReservedUsd(exec: Exec, sourceId: string, incarnation: string, scope?: string): Promise<{ usd: number; rows: number }> {+ const [row] = await exec.executeRaw<{ usd: number | string | null; rows: number | string }>(+ `SELECT COALESCE(sum((completed_keys->0->>'usd')::numeric),0)::float8 AS usd, count(*) AS rows FROM op_checkpoints WHERE op=$1 AND starts_with(fingerprint, $2)`,+ [SYNC_PASS_COST_OP, costPrefix(sourceId, incarnation, scope)]);+ return { usd: Number(row?.usd ?? 0), rows: Number(row?.rows ?? 0) };+}++/**+ * The pass's cost decision at pin (design §7, v3 §7): `approved_usd` is the owner's approval (the prior row's, an explicit+ * `--yes`, else the `sync.cost_gate_min_usd` floor); null (`unknown`) when the pass row is missing while reservations of+ * the incarnation exist. `defer`: paid work (embeddings) defers for this pass, because the cost is unknown or the scope's+ * reservations already reached the approval.+ */+export async function passCostDecision(engine: BrainEngine, input: { sourceId: string; incarnation: string; scope: string; priorRow: boolean;+ prior: { approved_usd: number | null; reserved_usd: number } | undefined; approved: boolean }): Promise<{ cost: { approved_usd: number | null; reserved_usd: number }; defer: 'cost_unknown' | 'cost_reserved' | null }> {+ const reserved = await readReservedUsd(engine, input.sourceId, input.incarnation, input.scope);+ const floor = parseUsdLimit(await engine.getConfig('sync.cost_gate_min_usd').catch(() => null), 0.5, { allowZero: true });+ if (input.approved) return { cost: { approved_usd: Number.isFinite(floor) ? Math.max(floor, reserved.usd + floor) : null, reserved_usd: reserved.usd }, defer: null };+ const lost = !input.priorRow && (await readReservedUsd(engine, input.sourceId, input.incarnation)).rows > 0;+ if (lost || (input.priorRow && input.prior && input.prior.approved_usd === null)) return { cost: { approved_usd: null, reserved_usd: reserved.usd }, defer: 'cost_unknown' };+ const approved = input.prior?.approved_usd ?? (Number.isFinite(floor) ? floor : null);+ return { cost: { approved_usd: approved, reserved_usd: reserved.usd }, defer: approved !== null && reserved.usd >= approved && reserved.usd > 0 ? 'cost_reserved' : null };+}diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex b89ed8c2f0..53f48af04a 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -41,6 +41,8 @@ import { syncOriginPath } from './sync-origin.ts';import { originMarkerFingerprint } from './sync-markers.ts';import { passResumeArgs } from './sync-pass-readers.ts';import { applyPassRound, finishPassApply, newPassApplyState, passApplyCounts } from './sync-pass-apply.ts';+import { passCostDecision, passEpisodeClosure, readReservedUsd, registerPassCost, unregisterPassCost } from './sync-pass-episode.ts';+import { currentEmbeddingPricePerMTok } from '../embedding.ts';/** Rounds a pass runs before it stops `not_converged` (design §3.1). */export const PASS_MAX_ROUNDS = 4;@@ -271,10 +273,17 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prawait clearPassFailures(engine, sourceId, incarnation);return { ...empty('up_to_date'), toCommit: remote ? '' : head, ...(inherited.length ? { inherited_options: inherited } : {}) };}+ // Design §7: the cost decision at pin; an unknown or spent envelope defers embeddings for this pass (never inherited).+ const costScope = episode?.full_id ?? passId;+ const costDecision = await passCostDecision(engine, { sourceId, incarnation, scope: costScope, priorRow: !!prior, prior: obligations.cost, approved: opts.costApproved === true });+ obligations.cost = costDecision.cost;+ let costDeferred: string | null = null;+ if (costDecision.defer && !processingOptions.noEmbed) { processingOptions.noEmbed = true; costDeferred = costDecision.defer; }await engine.transaction(async tx => { await assertDrainLease(tx, sourceId); await writePassRow(tx, value, { pin: true }); });assertActive();+ registerPassCost(passId, { sourceId, incarnation, scope: costScope, pricePerMTok: currentEmbeddingPricePerMTok() });- const counts = { added: 0, modified: 0, deleted: 0, renamed: 0, chunks: 0, waivedImports: 0, waivedDeletes: 0, held: 0, pausedDeletes: 0, collisions: 0 };+ const counts = { added: 0, modified: 0, deleted: 0, renamed: 0, chunks: 0, waivedImports: 0, waivedDeletes: 0, held: 0, pausedDeletes: 0, collisions: 0, episodeReleased: 0, costDeferred: costDeferred ? 1 : 0 };const collisions: SyncSlugCollision[] = [];const S = new Map<string, string>();const settledKey = (path: string, level: string | null) => `${path}\0${level ?? ''}`;@@ -396,8 +405,12 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prawait finishPassApply(engine, sourceId, applied);return { ...result('up_to_date'), fromCommit: remote ? null : head };}- const closesEpisode = !!episode && configured;- const stamp: PassStamp = { leaseToken: lease.token, incarnation, configured, stampChunker: configured && (context.source.last_commit === null || (closesEpisode && !!episode?.full_id)),+ // Design §6: an open episode closes by inclusion (a) or at the configured selection (b); chunker_version only by (b) over U_config.+ const closure = episode ? await passEpisodeClosure({ gitRoot: context.gitRoot, root: context.root, head, slugMode: levelSlugMode, episode, pass: selection, configured,+ configuredSelection: await passSelection(engine, { sourceId } as SyncOpts, context, mode) }) : null;+ const closesEpisode = closure?.closes === true;+ if (closure?.released) counts.episodeReleased = closure.released;+ const stamp: PassStamp = { leaseToken: lease.token, incarnation, configured, stampChunker: configured && (context.source.last_commit === null || (closesEpisode && !!episode?.full_id && closure!.stampChunker)),closesEpisode, retryTaken: [...retry], releasedHolds: [], selectionFp, parserFp, pack, full: kind === 'full',changed: counts.added + counts.modified + counts.deleted + counts.renamed, extract: !processingOptions.noExtract };await save('open', null);@@ -420,6 +433,12 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prconst stopped = await drain(chunk);if (stopped) return stop(stopped);value.telemetry.remaining = Math.max(0, built.entries.length - i - chunk.length) + inFlight.length + owed.length + mismatch.length;+ // Design §7 (v3 §7): crossing the approved envelope defers embeddings for the rest of the pass.+ const envelope = value.obligations.cost;+ if (envelope) {+ envelope.reserved_usd = (await readReservedUsd(engine, sourceId, incarnation, costScope)).usd;+ if (!processingOptions.noEmbed && envelope.approved_usd !== null && envelope.reserved_usd > 0 && envelope.reserved_usd >= envelope.approved_usd) { processingOptions.noEmbed = true; counts.costDeferred = 1; }+ }await save('open', null);}// Every candidate of the round settled: committed, waived, held, deferred to a hold, a collision, or (a rename's@@ -436,12 +455,15 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prreturn [entry.path, { level: entry.state.level, streak: seen && seen.level === entry.state.level ? seen.streak + 1 : 1 }];}));value.obligations.not_converged_streak = (value.obligations.not_converged_streak ?? 0) + 1;+ await finishPassApply(engine, sourceId, applied);await save('resumable', 'not_converged');return result('partial', 'not_converged');} catch (error) {if (error instanceof SyncAdmissionPaused) { await save('resumable', 'admission_paused').catch(() => undefined); return result('partial', 'admission_paused'); }if (input.signal?.aborted && error instanceof Error && error.name === 'AbortError') { await save('resumable', 'timeout').catch(() => undefined); return result('partial', 'timeout'); }throw error;+ } finally {+ unregisterPassCost(passId);}}