Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sources set-pull-strategy <id> <rebase|merge>: per-source pull_strategy for divergenceSafePull; merge mode aborts a conflict with merge --abort and verifies MERGE_HEAD is gone (#5429)

garrytan92d7cb40582e
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index b65c92987b..7d3bae58ca 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -455,9 +455,17 @@ gbrain sources unharden wiki
What hardening guarantees:
- **Pull-first, conflict-safe.** Every pull is a divergence-safe rebase. A
- dirty working tree is skipped (your in-progress edits are never touched); a
- rebase conflict is aborted cleanly and flagged for attention, never left
- half-applied.
+ dirty working tree is skipped (your in-progress edits are never touched; the
+ pull runs with `--no-autostash`, so a `rebase.autoStash` setting never
+ stashes and replays edits under it); a rebase conflict is aborted cleanly and
+ flagged for attention, never left half-applied. A brain whose intermediate
+ snapshot commits conflict under rebase replay while the two tips merge
+ cleanly can record `gbrain sources set-pull-strategy <id> merge`: pulls of
+ that source then fast-forward when possible and otherwise make a merge
+ commit, and a real conflict is aborted with `merge --abort`. The setting
+ lives in the source's config (`sources list --json` shows `pull_strategy`),
+ so a repository or global `pull.rebase` never changes it; `--path` pulls with
+ no source row keep `rebase`.
- **Push is never deferred.** `scripts/brain-commit-push.sh "<msg>" <path>`
commits and pushes, and refuses to report success without a successful push
or confirmation that the exact destination branch at every effective origin
diff --git a/src/commands/sources-harden.ts b/src/commands/sources-harden.ts
index baddcd5240..ec707619fa 100644
--- a/src/commands/sources-harden.ts
+++ b/src/commands/sources-harden.ts
@@ -17,7 +17,8 @@ import {
hardenBrainRepo, unhardenBrainRepo, acceptPat,
type DurabilityReport,
} from '../core/brain-repo-durability.ts';
-import { divergenceSafePull, detectDefaultBranch, isInsideGitRepo } from '../core/git-remote.ts';
+import { divergenceSafePull, detectDefaultBranch, isInsideGitRepo, pullStrategyOf, type PullStrategy } from '../core/git-remote.ts';
+import { parseSourceConfig } from '../core/sources-load.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { invalidateBackupStatus } from '../core/backup/status-file.ts';
import { existsSync } from 'fs';
@@ -110,7 +111,7 @@ export async function runHarden(engine: BrainEngine, args: string[]): Promise<vo
continue;
}
const report = await hardenBrainRepo({
- repoPath: row.local_path, sourceId: row.id, branch,
+ repoPath: row.local_path, sourceId: row.id, branch, pullStrategy: pullStrategyOf(parseSourceConfig(row.config)),
pat: pat?.token, installCron, verify, dryRun,
logger: json ? undefined : (l) => console.error(` ${l}`),
});
@@ -150,6 +151,7 @@ export async function runPull(engine: BrainEngine | null, args: string[]): Promi
const branchFlag = flagVal(args, '--branch');
let repoPath: string;
+ let pullStrategy: PullStrategy = 'rebase';
if (path) {
repoPath = path;
} else {
@@ -164,6 +166,7 @@ export async function runPull(engine: BrainEngine | null, args: string[]): Promi
process.exit(1);
}
repoPath = rows[0].local_path;
+ pullStrategy = pullStrategyOf(parseSourceConfig(rows[0].config));
}
if (!isInsideGitRepo(repoPath)) {
@@ -171,7 +174,7 @@ export async function runPull(engine: BrainEngine | null, args: string[]): Promi
process.exit(1);
}
const branch = branchFlag || detectDefaultBranch(repoPath);
- const outcome = divergenceSafePull(repoPath, branch);
+ const outcome = divergenceSafePull(repoPath, branch, { strategy: pullStrategy });
switch (outcome.status) {
case 'up_to_date': console.log(`up to date (${branch})`); break;
case 'advanced': console.log(`advanced ${outcome.from.slice(0, 7)}→${outcome.to.slice(0, 7)} (${branch})`); break;
diff --git a/src/commands/sources-pull-strategy.ts b/src/commands/sources-pull-strategy.ts
new file mode 100644
index 0000000000..5e2af6d9ec
--- /dev/null
+++ b/src/commands/sources-pull-strategy.ts
@@ -0,0 +1,42 @@
+/**
+ * `gbrain sources set-pull-strategy <id> <rebase|merge>` (#5429): persist
+ * `sources.config.pull_strategy`, how every divergence-safe pull of the source
+ * (`sources pull <id>`, `sources push <id>`, `sources harden <id>`) reconciles
+ * local commits with origin. Unset means `rebase`, the behaviour every brain
+ * had. `merge` is for a brain whose intermediate snapshot commits conflict
+ * under rebase replay while the two tips merge cleanly: a fast-forward when
+ * possible, else a merge commit, and a real conflict is aborted with
+ * `merge --abort`. The brain's own config plane is the single switch: a
+ * repository or global `pull.rebase` setting never changes the contract.
+ * `--path` callers have no source row and keep `rebase`. Follows
+ * `set-strategy`: one writer, `updateSourceConfig`'s single-key merge.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import { isPullStrategy, PULL_STRATEGIES, pullStrategyOf } from '../core/git-remote.ts';
+import { parseSourceConfig } from '../core/sources-load.ts';
+
+export async function runSetPullStrategy(engine: BrainEngine, args: string[]): Promise<void> {
+ const [id, strategy] = args;
+ if (!id || id.startsWith('-') || !strategy) {
+ console.error(`Usage: gbrain sources set-pull-strategy <id> <${PULL_STRATEGIES.join('|')}>`);
+ process.exit(2);
+ }
+ if (!isPullStrategy(strategy)) {
+ console.error(`Error: invalid pull strategy "${strategy}". Valid: ${PULL_STRATEGIES.join(', ')}.`);
+ process.exit(2);
+ }
+ const [src] = await engine.executeRaw<{ config: unknown; local_path: string | null }>('SELECT config, local_path FROM sources WHERE id=$1', [id]);
+ if (!src) {
+ console.error(`Source "${id}" not found. List sources with: gbrain sources list`);
+ process.exit(4);
+ }
+ const config = parseSourceConfig(src.config);
+ if (typeof config.kind === 'string') {
+ console.error(`Source "${id}" is a ${config.kind} connector source; a pull strategy applies to Git-backed sources only.`);
+ process.exit(2);
+ }
+ const previous = pullStrategyOf(config);
+ await engine.updateSourceConfig(id, { pull_strategy: strategy });
+ console.log(`Source "${id}" now pulls with strategy ${strategy}${previous === strategy ? ' (unchanged)' : ` (was ${previous})`}.`);
+ if (strategy === 'merge') console.log(` Divergence now ends in a merge commit when the two tips merge cleanly; a conflict is aborted (merge --abort) and reported as conflict_aborted.`);
+}
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index cb4c931593..96339ace60 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -73,6 +73,7 @@ import { preflightOauthClientColumns } from './auth.ts';
import { deleteSourceRow } from '../core/source-delete.ts';
import { USAGE_EXIT_CODE } from '../core/exit-codes.ts';
import { isSyncStrategy } from '../core/sync.ts';
+import { pullStrategyOf } from '../core/git-remote.ts';
// ── Validation ──────────────────────────────────────────────
@@ -106,6 +107,7 @@ interface SourceListEntry {
federated: boolean;
mirror_read_only: boolean;
strategy: 'markdown' | 'code' | 'auto' | null;
+ pull_strategy: 'rebase' | 'merge';
page_count: number;
last_sync_at: string | null;
}
@@ -615,6 +617,7 @@ async function runPush(engine: BrainEngine, args: string[]): Promise<void> {
}
let dir = path;
+ let pullStrategy: 'rebase' | 'merge' = 'rebase';
if (id) {
const src = await fetchSource(engine, id);
if (!src) {
@@ -626,6 +629,7 @@ async function runPush(engine: BrainEngine, args: string[]): Promise<void> {
process.exit(1);
}
dir = src.local_path;
+ pullStrategy = pullStrategyOf(parseConfig(src.config));
}
const { workspacePush, formatBlockedSecrets } = await import('../core/workspace-push.ts');
@@ -633,6 +637,7 @@ async function runPush(engine: BrainEngine, args: string[]): Promise<void> {
const res = await workspacePush({
dir: dir!,
branch,
+ pullStrategy,
commitMessage: message,
allowUnverifiedRemote: allowUnverified,
logger: (l) => console.error(`[gbrain] ${l}`),
@@ -713,6 +718,7 @@ async function runList(engine: BrainEngine, args: string[]): Promise<void> {
federated: isFederated(r.config),
mirror_read_only: parseConfig(r.config).mirror_read_only === true,
strategy: isSyncStrategy(parseConfig(r.config).strategy) ? parseConfig(r.config).strategy as 'markdown' | 'code' | 'auto' : null,
+ pull_strategy: pullStrategyOf(parseConfig(r.config)),
page_count: pageCount,
last_sync_at: r.last_sync_at ? new Date(r.last_sync_at).toISOString() : null,
});
@@ -1883,6 +1889,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<v
case 'unfederate': return runFederate(engine, rest, false);
case 'mirror-readonly': case 'mirror-writable': return (await import('./sources-mirror.ts')).runMirrorMode(engine, rest, sub === 'mirror-readonly');
case 'set-strategy': return (await import('./sources-strategy.ts')).runSetStrategy(engine, rest);
+ case 'set-pull-strategy': return (await import('./sources-pull-strategy.ts')).runSetPullStrategy(engine, rest);
case 'refresh': return (await import('./sources-refresh.ts')).runSourcesRefresh(engine, rest);
case 'archive': return runArchive(engine, rest);
case 'restore': return runRestore(engine, rest);
@@ -1976,6 +1983,7 @@ Subcommands:
mirror-readonly <id> Read-only mirror (#5409): managed writes never touch its checkout.
mirror-writable <id> Undo mirror-readonly.
set-strategy <id> <markdown|code|auto> Persist the sync strategy every sync of the source uses (PR #5955).
+ set-pull-strategy <id> <rebase|merge> How pulls reconcile local commits with origin (#5429); default rebase.
refresh <id> [--dry-run] [--wait-drain <s>] [--fetch-timeout-ms <ms>] [--resume|--abandon] [--json]
Managed brains: drain writes to the source's worktree, fast-forward
it to its upstream (git merge --ff-only) and sync every source bound
diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.ts
index 78a86bf1a8..8e774b66c0 100644
--- a/src/core/brain-repo-durability.ts
+++ b/src/core/brain-repo-durability.ts
@@ -37,7 +37,7 @@ import { execFileSync, execSync } from './spawn.ts';
import { execFileBounded } from './bounded-child-exec.ts';
import {
GIT_ENV, GIT_ENV_AUTH, divergenceSafePull, detectDefaultBranch, pushProbe,
- type PullOutcome, type PushProbeResult,
+ type PullOutcome, type PullStrategy, type PushProbeResult,
} from './git-remote.ts';
import { findResolverFile, RESOLVER_FILENAMES } from './resolver-filenames.ts';
import { redactSecretsInText } from './minions/handlers/shell-redact.ts';
@@ -81,6 +81,7 @@ export interface HardenOpts {
repoPath: string;
sourceId: string;
branch?: string; // default: detectDefaultBranch
+ pullStrategy?: PullStrategy; // sources.config.pull_strategy (#5429); default rebase
pat?: string; // already-loaded token; never logged
installCron?: boolean; // default true
verify?: boolean; // default true
@@ -1025,10 +1026,10 @@ export async function hardenBrainRepo(opts: HardenOpts): Promise<DurabilityRepor
if (currentBranch(repoPath) === 'HEAD') {
push('pull', { status: 'needs_attention', detail: 'detached HEAD — checkout a branch before hardening' });
} else if (dryRun) {
- push('pull', { status: 'skipped', detail: `dry-run — would fetch + pull --rebase origin/${branch}` });
+ push('pull', { status: 'skipped', detail: `dry-run — would fetch + pull ${opts.pullStrategy === 'merge' ? '--no-rebase' : '--rebase'} origin/${branch}` });
} else {
// 1. pull current state
- try { push('pull', pullDetail(divergenceSafePull(repoPath, branch))); }
+ try { push('pull', pullDetail(divergenceSafePull(repoPath, branch, { strategy: opts.pullStrategy }))); }
catch (e) { push('pull', { status: 'needs_attention', detail: `fetch/pull failed: ${(e as Error).message.slice(0, 140)}` }); }
}
diff --git a/src/core/git-remote.ts b/src/core/git-remote.ts
index 7a1d50a853..9e463cb822 100644
--- a/src/core/git-remote.ts
+++ b/src/core/git-remote.ts
@@ -547,18 +547,19 @@ export function detectDefaultBranch(repoPath: string): string {
return 'main';
}
+/** True if the git-dir entry `name` (a state file or directory) exists; false when git cannot be asked. */
+function gitStateExists(repoPath: string, name: string): boolean {
+ try {
+ const p = execFileSync('git', ['-C', repoPath, 'rev-parse', '--git-path', name], {
+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),
+ }).toString().trim();
+ return existsSync(p.startsWith('/') ? p : join(repoPath, p));
+ } catch { return false; }
+}
+
/** True if a rebase is mid-flight (rebase-merge or rebase-apply state dir exists). */
function rebaseInProgress(repoPath: string): boolean {
- for (const name of ['rebase-merge', 'rebase-apply']) {
- try {
- const p = execFileSync('git', ['-C', repoPath, 'rev-parse', '--git-path', name], {
- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),
- }).toString().trim();
- const abs = p.startsWith('/') ? p : join(repoPath, p);
- if (existsSync(abs)) return true;
- } catch { /* ignore */ }
- }
- return false;
+ return ['rebase-merge', 'rebase-apply'].some(name => gitStateExists(repoPath, name));
}
export type PullOutcome =
@@ -567,8 +568,20 @@ export type PullOutcome =
| { status: 'skipped_dirty' }
| { status: 'conflict_aborted'; detail: string };
+/** How `divergenceSafePull` reconciles local commits with origin (#5429): `sources.config.pull_strategy`, default `rebase`. */
+export const PULL_STRATEGIES = ['rebase', 'merge'] as const;
+export type PullStrategy = (typeof PULL_STRATEGIES)[number];
+export function isPullStrategy(value: unknown): value is PullStrategy {
+ return typeof value === 'string' && (PULL_STRATEGIES as readonly string[]).includes(value);
+}
+/** The strategy a source's parsed `config` records; anything else is the default. */
+export function pullStrategyOf(config: Record<string, unknown> | null | undefined): PullStrategy {
+ return isPullStrategy(config?.pull_strategy) ? config.pull_strategy : 'rebase';
+}
+
/**
- * Divergence-safe pull: `fetch` + `pull --rebase`, never leaving a mid-rebase.
+ * Divergence-safe pull: `fetch` + `pull --rebase` (or `pull --no-rebase` under
+ * `strategy: 'merge'`), never leaving a mid-rebase or a mid-merge.
*
* - Dirty working tree → `skipped_dirty` (NORMAL mid-session state, not an
* error; never auto-stashes, never touches in-progress edits). The pull
@@ -578,6 +591,11 @@ export type PullOutcome =
* - Rebase conflict → `git rebase --abort`, verify no rebase state remains,
* return `conflict_aborted` ("manual attention needed"). Never throws past
* this — the repo is always left clean (possibly un-advanced).
+ * - Merge strategy → fast-forward when possible, else a merge commit
+ * (`--no-edit`); a conflict runs `git merge --abort`, verifies MERGE_HEAD is
+ * gone and returns `conflict_aborted`. For a brain whose intermediate
+ * snapshot commits conflict under rebase replay while the two tips merge
+ * cleanly (#5429); per source via `sources.config.pull_strategy`.
*
* Auth-capable (GIT_ENV_AUTH) so it works against private remotes via the
* repo's configured credential helper. SSRF flags applied on every call.
@@ -585,10 +603,11 @@ export type PullOutcome =
export function divergenceSafePull(
repoPath: string,
branch: string,
- opts: { timeoutMs?: number } = {},
+ opts: { timeoutMs?: number; strategy?: PullStrategy } = {},
): PullOutcome {
assertManagedFilesystemWrite(repoPath);
const timeoutMs = opts.timeoutMs ?? 300_000;
+ const merge = opts.strategy === 'merge';
if (isWorkingTreeDirty(repoPath)) return { status: 'skipped_dirty' };
@@ -599,28 +618,33 @@ export function divergenceSafePull(
timeoutMs, env: { ...GIT_ENV_AUTH },
});
+ const mode = merge ? ['--no-rebase', '--no-edit', '--no-autostash'] : ['--rebase', '--no-autostash'];
try {
- runGit(repoPath, ssrf, 'pull', [...GIT_SSRF_SUBCOMMAND_FLAGS, '--rebase', '--no-autostash', 'origin', branch], 'pull', {
+ runGit(repoPath, ssrf, 'pull', [...GIT_SSRF_SUBCOMMAND_FLAGS, ...mode, 'origin', branch], 'pull', {
timeoutMs, env: { ...GIT_ENV_AUTH },
});
} catch (e) {
- // Abort any half-applied rebase so the tree is never left mid-rebase.
+ // Abort any half-applied rebase or merge so the tree is never left mid-operation.
+ const abort = merge ? ['merge', '--abort'] : ['rebase', '--abort'];
+ const inProgress = () => merge ? gitStateExists(repoPath, 'MERGE_HEAD') : rebaseInProgress(repoPath);
try {
- execFileSync('git', ['-C', repoPath, 'rebase', '--abort'], {
+ execFileSync('git', ['-C', repoPath, ...abort], {
stdio: 'ignore', timeout: 30_000, env: gitChildEnv({ ...GIT_ENV }),
});
} catch { /* best-effort */ }
// If state STILL remains, try once more, then report regardless.
- if (rebaseInProgress(repoPath)) {
+ if (inProgress()) {
try {
- execFileSync('git', ['-C', repoPath, 'rebase', '--abort'], {
+ execFileSync('git', ['-C', repoPath, ...abort], {
stdio: 'ignore', timeout: 30_000, env: gitChildEnv({ ...GIT_ENV }),
});
} catch { /* best-effort */ }
}
return {
status: 'conflict_aborted',
- detail: `pull --rebase on ${branch} conflicted; rebase aborted — manual attention needed (${(e as Error).message.slice(0, 120)})`,
+ detail: merge
+ ? `pull --no-rebase (merge) on ${branch} conflicted; merge aborted — manual attention needed (${(e as Error).message.slice(0, 120)})`
+ : `pull --rebase on ${branch} conflicted; rebase aborted — manual attention needed (${(e as Error).message.slice(0, 120)})`,
};
}
diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.ts
index ae4974116b..ed9420f93e 100644
--- a/src/core/workspace-push.ts
+++ b/src/core/workspace-push.ts
@@ -59,7 +59,7 @@ import {
import { dirname, join, resolve } from 'path';
import { createHash, randomBytes } from 'crypto';
import { execFileSync } from './spawn.ts';
-import { GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS, detectDefaultBranch, divergenceSafePull } from './git-remote.ts';
+import { GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS, detectDefaultBranch, divergenceSafePull, type PullStrategy } from './git-remote.ts';
import { loadConfigFileOnly } from './config.ts';
import { ensureGbrainHome } from './gbrain-home.ts';
import { invalidateBackupStatus, loadBackupStatus } from './backup/status-file.ts';
@@ -150,6 +150,8 @@ export interface WorkspacePushOpts {
dir: string;
/** Branch to pull/push; default `detectDefaultBranch(root)`. */
branch?: string;
+ /** How the pre-push pull reconciles divergence (`sources.config.pull_strategy`, #5429); default rebase. */
+ pullStrategy?: PullStrategy;
/** Escape hatch for self-hosted git: skip the gh privacy verification [G8]. Logged. */
allowUnverifiedRemote?: boolean;
commitMessage?: string;
@@ -991,7 +993,7 @@ export async function workspacePush(opts: WorkspacePushOpts): Promise<WorkspaceP
// 6. pull AFTER commit [CX2-7] — a dirty tree is impossible here short of
// a mid-run writer, and divergenceSafePull handles that as skipped_dirty.
try {
- const pull = divergenceSafePull(root, branch);
+ const pull = divergenceSafePull(root, branch, { strategy: opts.pullStrategy });
if (pull.status === 'conflict_aborted') {
return finish({
ok: false, status: 'pull_conflict', repoRoot: root, branch, committed,
diff --git a/test/divergence-safe-pull-5429.serial.test.ts b/test/divergence-safe-pull-5429.serial.test.ts
index 60a70eb52b..4127cc92e8 100644
--- a/test/divergence-safe-pull-5429.serial.test.ts
+++ b/test/divergence-safe-pull-5429.serial.test.ts
@@ -3,7 +3,10 @@
* but the pull it ran honoured a repository or user `rebase.autoStash=true`,
* so an edit made between the dirty check and the pull was stashed and
* replayed onto the rebased tree. The pull now carries `--no-autostash` in
- * every mode.
+ * every mode. Second half: a per-source `pull_strategy: merge` for brains
+ * whose intermediate snapshot commits conflict under rebase replay while a
+ * merge of the two tips is clean; a merge conflict is aborted with
+ * `merge --abort` and the tree is restored byte for byte.
*
* Local file transport is enabled via GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1 (the
* durable SSRF flags refuse it otherwise); the spy sits on node:child_process,
@@ -11,7 +14,7 @@
*/
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
import * as childProcess from 'node:child_process';
-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { divergenceSafePull } from '../src/core/git-remote.ts';
@@ -54,13 +57,39 @@ function commitFile(work: string, name: string, body: string, message: string):
return git(work, 'rev-parse', 'HEAD');
}
+/** Every tracked and untracked file under the work tree (not .git) with its bytes: the byte-identical witness. */
+function treeBytes(work: string): Record<string, string> {
+ const out: Record<string, string> = {};
+ const walk = (dir: string, rel: string) => {
+ for (const name of readdirSync(dir).sort()) {
+ if (name === '.git') continue;
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) walk(path, `${rel}${name}/`);
+ else out[`${rel}${name}`] = readFileSync(path, 'latin1');
+ }
+ };
+ walk(work, '');
+ return out;
+}
+
+/** The repo in `work` has the origin at A→B (page.md = v2) and a local A→L1 (v1b)→L2 (v2): rebase replays L1 onto B and conflicts; a merge of the tips is clean. */
+function tipEquivalentDivergence(): { work: string; remoteHead: string; localHead: string } {
+ const { bare, work } = makePair();
+ const other = secondClone(bare);
+ const remoteHead = commitFile(other, 'page.md', 'v2\n', 'remote: v2');
+ git(other, 'push', '-q', 'origin', 'main');
+ commitFile(work, 'page.md', 'v1b\n', 'local snapshot');
+ const localHead = commitFile(work, 'page.md', 'v2\n', 'local: v2');
+ return { work, remoteHead, localHead };
+}
+
beforeAll(() => { process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT = '1'; });
afterAll(() => { delete process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT; });
beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'gd-5429-')); });
afterEach(() => { rmSync(root, { recursive: true, force: true }); });
describe('--no-autostash (#5429, bug fix)', () => {
- test('the pull git runs carries --no-autostash', () => {
+ test('the pull git runs carries --no-autostash, in rebase mode and in merge mode', () => {
const { bare, work } = makePair();
const other = secondClone(bare);
commitFile(other, 'remote.txt', 'r\n', 'remote');
@@ -69,6 +98,7 @@ describe('--no-autostash (#5429, bug fix)', () => {
const spy = spyOn(childProcess, 'execFileSync');
try {
divergenceSafePull(work, 'main');
+ divergenceSafePull(work, 'main', { strategy: 'merge' });
} finally {
for (const call of spy.mock.calls) {
const args = call[1] as string[] | undefined;
@@ -76,9 +106,10 @@ describe('--no-autostash (#5429, bug fix)', () => {
}
spy.mockRestore();
}
- expect(pulls).toHaveLength(1);
- expect(pulls[0]!.slice(pulls[0]!.indexOf('pull'))).toContain('--no-autostash');
+ expect(pulls).toHaveLength(2);
+ for (const argv of pulls) expect(argv.slice(argv.indexOf('pull'))).toContain('--no-autostash');
expect(pulls[0]!.slice(pulls[0]!.indexOf('pull'))).toContain('--rebase');
+ expect(pulls[1]!.slice(pulls[1]!.indexOf('pull'))).toContain('--no-rebase');
});
test('git itself: with rebase.autoStash=true the old argv stashes and replays a dirty edit; --no-autostash refuses and leaves the stash list empty', () => {
@@ -106,12 +137,68 @@ describe('--no-autostash (#5429, bug fix)', () => {
}
});
- test('a dirty tree with rebase.autoStash=true is skipped_dirty, nothing stashed', () => {
- const { work } = makePair();
- git(work, 'config', 'rebase.autoStash', 'true');
- writeFileSync(join(work, 'README.md'), 'dirty\n');
- expect(divergenceSafePull(work, 'main')).toEqual({ status: 'skipped_dirty' });
- expect(git(work, 'stash', 'list')).toBe('');
- expect(readFileSync(join(work, 'README.md'), 'utf8')).toBe('dirty\n');
+ test('a dirty tree with rebase.autoStash=true is skipped_dirty in both modes, nothing stashed', () => {
+ for (const strategy of ['rebase', 'merge'] as const) {
+ const { work } = makePair();
+ git(work, 'config', 'rebase.autoStash', 'true');
+ writeFileSync(join(work, 'README.md'), 'dirty\n');
+ expect(divergenceSafePull(work, 'main', { strategy })).toEqual({ status: 'skipped_dirty' });
+ expect(git(work, 'stash', 'list')).toBe('');
+ expect(readFileSync(join(work, 'README.md'), 'utf8')).toBe('dirty\n');
+ }
+ });
+});
+
+describe('pull_strategy: merge (#5429, feature)', () => {
+ test('tip-equivalent divergence: rebase mode conflict_aborted, merge mode advanced with both histories as ancestors', () => {
+ const rebase = tipEquivalentDivergence();
+ const before = treeBytes(rebase.work);
+ const out = divergenceSafePull(rebase.work, 'main');
+ expect(out.status).toBe('conflict_aborted');
+ expect(git(rebase.work, 'rev-parse', 'HEAD')).toBe(rebase.localHead);
+ expect(existsSync(join(rebase.work, '.git', 'rebase-merge'))).toBe(false);
+ expect(treeBytes(rebase.work)).toEqual(before);
+
+ const merge = tipEquivalentDivergence();
+ const merged = divergenceSafePull(merge.work, 'main', { strategy: 'merge' });
+ expect(merged.status).toBe('advanced');
+ if (merged.status !== 'advanced') throw new Error('unreachable');
+ expect(merged.from).toBe(merge.localHead);
+ const head = git(merge.work, 'rev-parse', 'HEAD');
+ expect(merged.to).toBe(head);
+ expect(git(merge.work, 'merge-base', '--is-ancestor', merge.remoteHead, head)).toBe('');
+ expect(git(merge.work, 'merge-base', '--is-ancestor', merge.localHead, head)).toBe('');
+ expect(readFileSync(join(merge.work, 'page.md'), 'utf8')).toBe('v2\n');
+ expect(existsSync(join(merge.work, '.git', 'MERGE_HEAD'))).toBe(false);
+ });
+
+ test('merge mode fast-forwards when the local branch is behind and reports up_to_date when level', () => {
+ const { bare, work } = makePair();
+ const other = secondClone(bare);
+ const remoteHead = commitFile(other, 'remote.txt', 'r\n', 'remote');
+ git(other, 'push', '-q', 'origin', 'main');
+ const out = divergenceSafePull(work, 'main', { strategy: 'merge' });
+ expect(out.status).toBe('advanced');
+ expect(git(work, 'rev-parse', 'HEAD')).toBe(remoteHead);
+ expect(divergenceSafePull(work, 'main', { strategy: 'merge' })).toEqual({ status: 'up_to_date' });
+ });
+
+ test('a real content conflict in merge mode: merge --abort, MERGE_HEAD gone, HEAD and tree byte-identical', () => {
+ const { bare, work } = makePair();
+ const other = secondClone(bare);
+ commitFile(other, 'page.md', 'remote line\n', 'remote');
+ git(other, 'push', '-q', 'origin', 'main');
+ const head = commitFile(work, 'page.md', 'local line\n', 'local');
+ const before = treeBytes(work);
+ const out = divergenceSafePull(work, 'main', { strategy: 'merge' });
+ expect(out.status).toBe('conflict_aborted');
+ if (out.status !== 'conflict_aborted') throw new Error('unreachable');
+ expect(out.detail).toContain('merge');
+ expect(existsSync(join(work, '.git', 'MERGE_HEAD'))).toBe(false);
+ expect(existsSync(join(work, '.git', 'MERGE_MSG'))).toBe(false);
+ expect(existsSync(join(work, '.git', 'rebase-merge'))).toBe(false);
+ expect(git(work, 'rev-parse', 'HEAD')).toBe(head);
+ expect(git(work, 'status', '--porcelain')).toBe('');
+ expect(treeBytes(work)).toEqual(before);
});
});
diff --git a/test/sources-pull-strategy-5429.test.ts b/test/sources-pull-strategy-5429.test.ts
new file mode 100644
index 0000000000..2f0592fb0a
--- /dev/null
+++ b/test/sources-pull-strategy-5429.test.ts
@@ -0,0 +1,75 @@
+/**
+ * `gbrain sources set-pull-strategy <id> <rebase|merge>` (#5429): the one
+ * writer persists `sources.config.pull_strategy` by a single-key merge, the
+ * reader `pullStrategyOf` defaults anything else to `rebase`, and `sources
+ * list --json` reads it back. An invalid value, a missing source and a
+ * connector source are refused without writing.
+ */
+import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { isPullStrategy, PULL_STRATEGIES, pullStrategyOf } from '../src/core/git-remote.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+async function cli(args: string[]): Promise<{ out: string; err: string; exit: number | null }> {
+ const out: string[] = [], err: string[] = [];
+ let exit: number | null = null;
+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => { exit = code ?? 0; throw new Error('EXIT'); }) as never);
+ const logSpy = spyOn(console, 'log').mockImplementation((...parts: unknown[]) => { out.push(parts.map(String).join(' ')); });
+ const errSpy = spyOn(console, 'error').mockImplementation((...parts: unknown[]) => { err.push(parts.map(String).join(' ')); });
+ try { await runSources(engine, args); } catch (error) { if (!(error instanceof Error && error.message === 'EXIT')) throw error; }
+ finally { exitSpy.mockRestore(); logSpy.mockRestore(); errSpy.mockRestore(); }
+ return { out: out.join('\n'), err: err.join('\n'), exit };
+}
+const config = async (id: string) => (await engine.executeRaw<{ config: Record<string, unknown> }>('SELECT config FROM sources WHERE id=$1', [id]))[0]!.config;
+
+test('the pull strategy enum is closed and anything else reads as rebase', () => {
+ expect([...PULL_STRATEGIES]).toEqual(['rebase', 'merge']);
+ expect(isPullStrategy('merge')).toBe(true);
+ expect(isPullStrategy('MERGE')).toBe(false);
+ expect(pullStrategyOf({ pull_strategy: 'merge' })).toBe('merge');
+ expect(pullStrategyOf({ pull_strategy: 'ff-only' })).toBe('rebase');
+ expect(pullStrategyOf({})).toBe('rebase');
+ expect(pullStrategyOf(null)).toBe('rebase');
+});
+
+test('set-pull-strategy persists config.pull_strategy by a single-key merge and sources list --json reads it back', async () => {
+ const id = `pull-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw(`INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,'/tmp/${id}','{"federated":true,"strategy":"code"}')`, [id]);
+ let listed = JSON.parse((await cli(['list', '--json'])).out) as { sources: Array<{ id: string; pull_strategy: string }> };
+ expect(listed.sources.find(source => source.id === id)).toMatchObject({ pull_strategy: 'rebase' });
+
+ const set = await cli(['set-pull-strategy', id, 'merge']);
+ expect(set.exit).toBeNull();
+ expect(set.out).toContain(`Source "${id}" now pulls with strategy merge (was rebase).`);
+ expect(set.out).toContain('merge --abort');
+ expect(await config(id)).toEqual({ federated: true, strategy: 'code', pull_strategy: 'merge' });
+ listed = JSON.parse((await cli(['list', '--json'])).out);
+ expect(listed.sources.find(source => source.id === id)).toMatchObject({ pull_strategy: 'merge', strategy: 'code' });
+
+ const back = await cli(['set-pull-strategy', id, 'rebase']);
+ expect(back.out).toContain('now pulls with strategy rebase (was merge).');
+ expect(back.out).not.toContain('merge --abort');
+ expect(await config(id)).toEqual({ federated: true, strategy: 'code', pull_strategy: 'rebase' });
+});
+
+test('an invalid strategy, a missing source and a connector source are refused without writing', async () => {
+ const id = `pull-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw(`INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,'/tmp/${id}','{}')`, [id]);
+ const invalid = await cli(['set-pull-strategy', id, 'ff-only']);
+ expect(invalid).toMatchObject({ exit: 2 });
+ expect(invalid.err).toContain('invalid pull strategy "ff-only"');
+ expect(await config(id)).toEqual({});
+ expect((await cli(['set-pull-strategy', `missing-${randomUUID().slice(0, 6)}`, 'merge'])).exit).toBe(4);
+ expect((await cli(['set-pull-strategy'])).exit).toBe(2);
+ const connector = `gh-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw(`INSERT INTO sources(id,name,config) VALUES($1,$1,'{"kind":"github"}')`, [connector]);
+ const refused = await cli(['set-pull-strategy', connector, 'merge']);
+ expect(refused.exit).toBe(2);
+ expect(refused.err).toContain('github connector source');
+ expect(await config(connector)).toEqual({ kind: 'github' });
+});