Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): a --no-pull CLI cost estimate prices local HEAD and never fetches (lane D's run.ts hunk, GBRA-133 2b.3)
garrytan2bdd68300096
diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex 4ff6f4d3d4..dbc2d3a7ef 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -462,7 +462,7 @@ async function runSyncAll(catch (error) { policyFailures.set(source.id, error); }}const embedPlan = await resolveSyncAllEmbedPlan(engine, runnableSources.filter(src => !policyFailures.has(src.id) && !companyPolicies.get(src.id)), {- v2Enabled, serialFlag, noEmbed: noEmbed || !!embeddingCredentialError, noAutoEmbed, dryRun, jsonOut, yesFlag, full, includeGitignored,+ v2Enabled, serialFlag, noEmbed: noEmbed || !!embeddingCredentialError, noAutoEmbed, dryRun, jsonOut, yesFlag, full, includeGitignored, noPull,});if (embedPlan.stop) return;const {@@ -845,7 +845,7 @@ async function runSingleSourceSync(chunker_version: gateRows[0].chunker_version,}, {dryRun: false,- jsonOut, yesFlag, full, includeGitignored, noAutoEmbed,+ jsonOut, yesFlag, full, includeGitignored, noAutoEmbed, noPull,});singleSourceNoWorkerSurface = gate.workerSurface.status === 'no_worker_surface';singleCostGate = gate.costGate;diff --git a/src/core/sync-cost-gate.ts b/src/core/sync-cost-gate.tsindex d271affd98..26b7e54ed7 100644--- a/src/core/sync-cost-gate.ts+++ b/src/core/sync-cost-gate.ts@@ -148,7 +148,7 @@ function estimateDeltaTokens(localPath: string, relPaths: string[]): number {* cost paid a few seconds early — a tighter cap would frequently fall back to* local HEAD and underestimate the remote delta).*/-function resolveEstimateTarget(localPath: string): { target: string; detached: boolean } | null {+function resolveEstimateTarget(localPath: string, noPull = false): { target: string; detached: boolean } | null {let head: string;try {head = git(localPath, ['rev-parse', 'HEAD']);@@ -164,7 +164,9 @@ function resolveEstimateTarget(localPath: string): { target: string; detached: b} catch {branch = null;}- if (branch && branch !== 'HEAD' && hasOriginRemote(localPath)) {+ // GBRA-133 2b.3: a --no-pull run syncs local HEAD and never fetches, so its estimate prices local HEAD and the gate+ // spends no network round trip (a fetch can take the shared 30 s git budget on a slow or unreachable remote).+ if (!noPull && branch && branch !== 'HEAD' && hasOriginRemote(localPath)) {try {// v0.42.42.0 (#2139): route through the SSRF-hardened fetch (same flags +// no-prompt env as pullRepo) — a cost preview / dry-run must NOT hit a@@ -232,7 +234,7 @@ export function estimateInlineNewTokens(chunker_version: string | null;}>,currentChunkerVersion: string,- opts: { forceFullTree?: boolean; chunkerDriftWalks?: boolean } = {},+ opts: { forceFullTree?: boolean; chunkerDriftWalks?: boolean; noPull?: boolean } = {},): InlineEstimate {let tokens = 0;let changedSources = 0;@@ -285,7 +287,7 @@ export function estimateInlineNewTokens(continue;}- const resolved = resolveEstimateTarget(localPath);+ const resolved = resolveEstimateTarget(localPath, opts.noPull === true);if (!resolved) {// HEAD unresolvable (not a git repo / gone) — can't compute a delta. CEILING.ceiling(localPath, strategy, 'git_unavailable');@@ -407,6 +409,8 @@ interface CostGateContext {yesFlag: boolean;full: boolean;includeGitignored?: boolean;+ /** The run will not pull: estimate against local HEAD without fetching. */+ noPull?: boolean;/** Message prefix ('sync --all' | 'sync'). */label: string;/** Public queue capability resolved at the command boundary. */@@ -550,6 +554,7 @@ export async function runInlineCostGate(// ── Inline path ───────────────────────────────────────────────const inline = estimateInlineNewTokens(sources, chunkerStamp(), {forceFullTree: ctx.includeGitignored === true,+ noPull: ctx.noPull === true,chunkerDriftWalks: full === true || !(await readManagedMode(engine).catch(() => false)),});// D7A: `--full` runs `performFullSync` → `runEmbedCore({stale:true})`, whichdiff --git a/src/core/sync-embed-backfill.ts b/src/core/sync-embed-backfill.tsindex 03b2336d4b..0ed145afb7 100644--- a/src/core/sync-embed-backfill.ts+++ b/src/core/sync-embed-backfill.ts@@ -33,6 +33,8 @@ type SyncCostGateFlags = {full: boolean;includeGitignored: boolean;noAutoEmbed: boolean;+ /** GBRA-133 2b.3: the run will not pull, so the inline estimate skips its remote fetch. */+ noPull?: boolean;};export async function resolveSyncAllEmbedPlan(@@ -73,6 +75,7 @@ export async function resolveSyncAllEmbedPlan(yesFlag: opts.yesFlag,full: opts.full,includeGitignored: opts.includeGitignored,+ noPull: opts.noPull,label: 'sync --all',workerSurface,autoSubmitEnabled: !opts.noAutoEmbed,@@ -104,6 +107,7 @@ export async function resolveSingleSyncEmbedPlan(yesFlag: opts.yesFlag,full: opts.full,includeGitignored: opts.includeGitignored,+ noPull: opts.noPull,label: 'sync',workerSurface,autoSubmitEnabled: !opts.noAutoEmbed,diff --git a/test/sync-no-pull-estimate-gbra133.test.ts b/test/sync-no-pull-estimate-gbra133.test.tsnew file mode 100644index 0000000000..35a918a3c0--- /dev/null+++ b/test/sync-no-pull-estimate-gbra133.test.ts@@ -0,0 +1,60 @@+/**+ * GBRA-133 PR 2b (lane D's run.ts hunk): \`gbrain sync --no-pull\` syncs local HEAD, so its inline cost estimate prices+ * local HEAD and runs no git fetch. The control (the same command without --no-pull) fetches, so the check is not+ * vacuous. The sync is stopped right after the cost gate, before it would pull.+ */+import { afterAll, expect, spyOn, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runSync } from '../src/commands/sync.ts';+import * as gitRemote from '../src/core/git-remote.ts';+import * as embedBackfill from '../src/core/sync-embed-backfill.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { withEnv } from './helpers/with-env.ts';+import { chunkerStamp } from '../src/core/chunkers/code.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-no-pull-estimate-'));+afterAll(() => { resetGateway(); rmSync(home, { recursive: true, force: true }); });+const sh = (cwd: string, ...args: string[]) => execFileSync('git', ['-c', 'user.name=Example', '-c', '[email protected]', ...args], { cwd, encoding: 'utf8' }).trim();+const page = (name: string) => '---\ntitle: ' + name + '\n---\nA note about acme-example named ' + name + '.\n';++test('gbrain sync --no-pull runs no git fetch during the cost estimate; without it the estimate fetches', async () => {+ const remote = join(home, 'remote.git'), writer = join(home, 'writer'), local = join(home, 'local');+ sh(home, 'init', '-q', '--bare', '-b', 'main', remote);+ sh(home, 'clone', '-q', remote, writer);+ writeFileSync(join(writer, 'a.md'), page('a')); sh(writer, 'add', '-A'); sh(writer, 'commit', '-qm', 'a'); sh(writer, 'push', '-q', 'origin', 'HEAD:main');+ sh(home, 'clone', '-q', remote, local);+ const base = sh(local, 'rev-parse', 'HEAD');+ writeFileSync(join(writer, 'b.md'), page('b')); sh(writer, 'add', '-A'); sh(writer, 'commit', '-qm', 'b'); sh(writer, 'push', '-q', 'origin', 'HEAD:main');++ const engine = new PGLiteEngine();+ await engine.connect({}); await engine.initSchema();+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config,last_commit,chunker_version) VALUES('estimate','estimate',$1,'{}',$2,$3)", [local, base, chunkerStamp()]);+ const fetches = spyOn(gitRemote, 'fetchRemote');+ const real = embedBackfill.resolveSingleSyncEmbedPlan;+ const gates: Array<Record<string, unknown>> = [];+ const gate = spyOn(embedBackfill, 'resolveSingleSyncEmbedPlan').mockImplementation(async (e, source, opts) => {+ gates.push(opts as unknown as Record<string, unknown>);+ return { ...await real(e, source, opts), stop: true };+ });+ try {+ await withEnv({ GBRAIN_HOME: home, GBRAIN_GIT_ALLOW_FILE_TRANSPORT: '1', OPENAI_API_KEY: 'sk-test-not-a-key', DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test-not-a-key' } } as never);+ await runSync(engine, ['--source', 'estimate', '--no-pull']);+ expect(gates.length).toBe(1);+ expect(fetches).not.toHaveBeenCalled();+ expect(sh(local, 'rev-parse', 'refs/remotes/origin/main')).toBe(base);+ expect(gates[0]!.noPull).toBe(true);+ await runSync(engine, ['--source', 'estimate']);+ expect(gates.length).toBe(2);+ expect(fetches).toHaveBeenCalled();+ expect(sh(local, 'rev-parse', 'refs/remotes/origin/main')).not.toBe(base);+ });+ } finally {+ fetches.mockRestore(); gate.mockRestore();+ await engine.disconnect();+ }+}, 60_000);