Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): classify upstream force-push and divergence on classic pull; add sources reset-upstream (GBRA-133 S-58/S-59)

garrytan5ea24768aac9
diff --git a/src/commands/doctor/checks/sync-failures.ts b/src/commands/doctor/checks/sync-failures.ts
index d209324371..2044d719ec 100644
--- a/src/commands/doctor/checks/sync-failures.ts
+++ b/src/commands/doctor/checks/sync-failures.ts
@@ -9,12 +9,25 @@ import { readManagedMode } from '../../../core/persistence/ownership.ts';
import { legacyLedgerNote } from '../../../core/persistence/legacy-sync-failures.ts';
import { classifyRecordedFault } from '../../../core/persistence/terminal-classify.ts';
import { agentFix } from '../check-fix.ts';
+import { readUpstreamDivergences } from '../../../core/sync-upstream-rewrite.ts';
/** #6518 [R18 vi]: the fast check cannot verify a mirror row; a warning there is uncertainty, never recovery. */
const MIRROR_UNVERIFIED = (count: number) => `${count} mirrored managed sync failure(s) could not be verified without a database connection: `
+ 'a better fast score means less certainty, not that sync recovered. Run gbrain doctor --only sync_failures with the brain reachable.';
export async function checkSyncFailures(engine: BrainEngine | null, opts: { sourceIds?: string[]; remote?: boolean } = {}): Promise<Check | null> {
+ const check = await checkRecordedSyncFailures(engine, opts);
+ const upstream = engine ? await readUpstreamDivergences(engine, opts.sourceIds) : [];
+ if (!upstream.length) return check;
+ const local = opts.remote === false;
+ const note = local ? upstream.map(report => `${report.message} Next${report.fix.ask_user ? ' (ask the user first)' : ''}: ${report.fix.argv!.join(' ')}.`).join(' ')
+ : `${upstream.length} source(s) cannot pull because the checkout and its upstream diverged (${[...new Set(upstream.map(report => report.code))].join(', ')}); local HEAD keeps syncing. Ask the host operator to run gbrain doctor --only sync_failures.`;
+ return { ...check, name: 'sync_failures', status: check?.status === 'fail' ? 'fail' : 'warn', message: check && check.status !== 'ok' ? `${check.message} ${note}` : note,
+ ...(local ? { details: { ...check?.details, upstream } } : {}),
+ ...(check?.fix ? {} : local ? { fix: upstream[0]!.fix } : { fix_unavailable_reason: 'operator_judgement' as const }) };
+}
+
+async function checkRecordedSyncFailures(engine: BrainEngine | null, opts: { sourceIds?: string[]; remote?: boolean }): Promise<Check | null> {
// #5452: sync refuses an archived source, so its failures cannot be cleared and are not a live health signal.
const archived = new Set(engine ? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived = true')).map(row => row.id) : []);
const allManaged = engine ? await readManagedSyncFailures(engine, opts.sourceIds) : [];
diff --git a/src/commands/sources-reset-upstream.ts b/src/commands/sources-reset-upstream.ts
new file mode 100644
index 0000000000..5985b085e9
--- /dev/null
+++ b/src/commands/sources-reset-upstream.ts
@@ -0,0 +1,183 @@
+/**
+ * `gbrain sources reset-upstream <id> --expect-local <sha> --expect-upstream <sha> [--dry-run] [--json]`
+ * (GBRA-133 S-58/S-59): the fix for `upstream_rewritten` and `upstream_unknown`.
+ * A classic source whose upstream was force-pushed cannot fast-forward, and
+ * merging would bring back the commits the force-push removed, so the checkout
+ * is moved to the new upstream instead, after the user agrees.
+ *
+ * Under the checkout's commit lock (the lock `gbrain git commit-push` and
+ * scripts/brain-commit-push.sh take) it refuses a git operation in progress,
+ * a HEAD or upstream that moved since the observation (`--expect-local` /
+ * `--expect-upstream`), a dirty tracked tree, and local commits that were never
+ * on the upstream (not reachable from the new upstream, the recorded upstream
+ * baseline or the tracking ref's reflog), naming them and the backup ref it
+ * would create. Otherwise it records the old HEAD under
+ * `refs/gbrain/backup/<UTC stamp>-<sha>`, runs `git reset --keep <upstream>`,
+ * verifies HEAD is the expected upstream, records it as the source's upstream
+ * baseline and clears the upstream observation. It never fetches; the next
+ * `gbrain sync --source <id>` imports the upstream commits. `--dry-run` runs
+ * every check, takes no lock and changes nothing.
+ */
+import { existsSync, readFileSync } from 'node:fs';
+import type { Action } from '../core/agent-output.ts';
+import type { BrainEngine } from '../core/engine.ts';
+import { acquireCommitLock, assertNoOperationInProgress, checkoutRoot } from '../core/git/commit-push.ts';
+import { gitChildEnv } from '../core/git-env.ts';
+import { GIT_ENV } from '../core/git-transport.ts';
+import { OperationError, opError } from '../core/ops/contract.ts';
+import { assertLegacyFilesystemWriter } from '../core/persistence/filesystem-guard.ts';
+import { execFileSync } from '../core/spawn.ts';
+import {
+ clearUpstreamDivergence, gitRead, hasCommit, readCheckoutUpstream, readUpstreamBaseline, writeUpstreamBaseline, UPSTREAM_DOCS,
+} from '../core/sync-upstream-rewrite.ts';
+
+const USAGE = 'Usage: gbrain sources reset-upstream <id> --expect-local <sha> --expect-upstream <sha> [--dry-run] [--json]';
+const LIST_CAP = 20;
+const REFLOG_CAP = 500;
+
+export interface ResetUpstreamReceipt {
+ status: 'reset' | 'would_reset' | 'already_at_upstream';
+ source_id: string;
+ repo: string;
+ branch: string | null;
+ tracking_ref: string;
+ dry_run: boolean;
+ from: string;
+ to: string;
+ /** The ref holding the old HEAD (null when nothing moved). */
+ backup_ref: string | null;
+ /** Commits that leave the branch (all were on the upstream before it was rewritten), newest first, capped. */
+ dropped: string[];
+ dropped_count: number;
+ next: Action;
+}
+
+interface Parsed { id?: string; expectLocal?: string; expectUpstream?: string; dryRun: boolean; json: boolean }
+
+function parse(args: string[]): Parsed {
+ const p: Parsed = { dryRun: false, json: false };
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i]!;
+ const value = (name: string): string => {
+ const eq = a.indexOf('=');
+ const v = eq !== -1 ? a.slice(eq + 1) : args[++i];
+ if (!v) throw new OperationError('invalid_params', `${name} needs a value.`, USAGE);
+ return v;
+ };
+ if (a === '--dry-run') p.dryRun = true;
+ else if (a === '--json') p.json = true;
+ else if (a === '--expect-local' || a.startsWith('--expect-local=')) p.expectLocal = value('--expect-local');
+ else if (a === '--expect-upstream' || a.startsWith('--expect-upstream=')) p.expectUpstream = value('--expect-upstream');
+ else if (a.startsWith('-')) throw new OperationError('invalid_params', `Unknown option: ${a}.`, USAGE);
+ else if (!p.id) p.id = a;
+ else throw new OperationError('invalid_params', 'Name one source.', USAGE);
+ }
+ if (!p.id || !p.expectLocal || !p.expectUpstream) throw new OperationError('invalid_params', 'reset-upstream needs a source id, --expect-local and --expect-upstream.', USAGE);
+ for (const sha of [p.expectLocal, p.expectUpstream]) {
+ if (!/^[0-9a-f]{7,64}$/i.test(sha)) throw new OperationError('invalid_params', `${sha} is not a commit sha.`, USAGE);
+ }
+ return p;
+}
+
+const lines = (out: string | null) => (out ? out.split('\n').filter(Boolean) : []);
+
+function refused(reason: 'expect_mismatch' | 'dirty_tree' | 'local_commits' | 'no_upstream', message: string, suggestion: string, fix: Action, detail?: unknown): OperationError {
+ return opError('reset_upstream_refused', message, suggestion, { reason, fix, docs: UPSTREAM_DOCS, ...(detail === undefined ? {} : { detail: JSON.stringify(detail) }) });
+}
+
+/** Every commit the tracking ref ever pointed at, old and new values of its reflog (a forced fetch logs the rewritten tip as the old value). */
+function trackingRefHistory(root: string, trackingRef: string): string[] {
+ const path = gitRead(root, ['rev-parse', '--path-format=absolute', '--git-path', `logs/${trackingRef}`]);
+ if (!path || !existsSync(path)) return [];
+ return readFileSync(path, 'utf8').split('\n').slice(-REFLOG_CAP).flatMap(line => line.split(' ', 2)).filter(sha => /^[0-9a-f]{40,64}$/.test(sha) && !/^0+$/.test(sha));
+}
+
+/** Run the checks and, unless dry-run, the reset; returns the receipt. */
+export async function resetUpstream(engine: BrainEngine, opts: { sourceId: string; expectLocal: string; expectUpstream: string; dryRun?: boolean }): Promise<ResetUpstreamReceipt> {
+ const { sourceId } = opts;
+ const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id = $1 AND archived IS NOT TRUE', [sourceId]);
+ if (!source) throw opError('unknown_source', `Source ${sourceId} is not registered (or is archived).`, 'List the sources with gbrain sources list --json.');
+ if (!source.local_path) throw opError('unknown_source', `Source ${sourceId} has no local checkout.`, 'reset-upstream applies to a Git source with a local_path.');
+ const root = checkoutRoot(source.local_path);
+ await assertLegacyFilesystemWriter(engine, root);
+ const preview = ['gbrain', 'sources', 'reset-upstream', sourceId, '--expect-local', opts.expectLocal, '--expect-upstream', opts.expectUpstream, '--dry-run'];
+ const sync: Action = { argv: ['gbrain', 'sync', '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false,
+ verify: { argv: ['gbrain', 'doctor', '--only', 'sync_failures', '--json'] },
+ why: 'Pulls the upstream (now a fast-forward or up to date) and imports its commits; the upstream report clears.' };
+ const lock = opts.dryRun ? null : acquireCommitLock(root);
+ try {
+ assertNoOperationInProgress(root);
+ const state = readCheckoutUpstream(root);
+ if (!state) {
+ throw refused('no_upstream', `The checkout ${root} has no commit or no upstream branch, so there is nothing to reset to.`,
+ 'Set the branch upstream (git branch --set-upstream-to <remote>/<branch>), run gbrain sync --source <id>, then follow the doctor fix.', sync);
+ }
+ const resolved = (sha: string) => gitRead(root, ['rev-parse', '--verify', '-q', `${sha}^{commit}`]);
+ if (resolved(opts.expectLocal) !== state.head || resolved(opts.expectUpstream) !== state.upstream) {
+ throw refused('expect_mismatch', `The checkout moved since the reset was proposed: HEAD is ${state.head} and ${state.tracking_ref} is ${state.upstream} (expected ${opts.expectLocal} and ${opts.expectUpstream}). Nothing was changed.`,
+ 'Run gbrain sync --source <id> to observe the checkout again; gbrain doctor --only sync_failures then names the current reset command.', sync,
+ { local: state.head, upstream: state.upstream });
+ }
+ const dirty = lines(gitRead(root, ['diff', '--name-only', 'HEAD', '--']));
+ const askAgain: Action = { ask_user: true, consent: [], actor: 'user', requires_exclusive: false, docs: UPSTREAM_DOCS, verify: { argv: preview },
+ why: 'Only the user can decide what happens to work that is not on the upstream.' };
+ if (dirty.length) {
+ const paths = dirty.slice(0, LIST_CAP);
+ throw refused('dirty_tree', `The checkout ${root} has uncommitted changes to tracked files (${paths.join(', ')}${dirty.length > LIST_CAP ? `, and ${dirty.length - LIST_CAP} more` : ''}); nothing was changed.`,
+ 'Commit the edits (gbrain git commit-push -m <msg> -- <paths>) or discard them, then run the same reset-upstream command again.',
+ { ...askAgain, user_message: `The checkout of source ${sourceId} has uncommitted edits to ${paths.join(', ')}. Commit or discard them before resetting to the upstream?` }, { paths });
+ }
+ const baseline = (await readUpstreamBaseline(engine, sourceId))?.sha;
+ const published = [...new Set([...(baseline ? [baseline] : []), ...trackingRefHistory(root, state.tracking_ref)])].filter(sha => hasCommit(root, sha));
+ const localOnly = lines(gitRead(root, ['rev-list', state.head, '--not', state.upstream, ...published]));
+ const backupRef = `refs/gbrain/backup/${new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')}-${state.head.slice(0, 12)}`;
+ if (localOnly.length) {
+ const named = localOnly.slice(0, LIST_CAP).map(sha => gitRead(root, ['log', '-1', '--format=%h %s', sha]) ?? sha.slice(0, 12));
+ throw refused('local_commits', `${localOnly.length} local commit(s) were never on the upstream and a reset would drop them: ${named.join('; ')}. Nothing was changed; a reset would keep them under ${backupRef}.`,
+ `Push or re-apply them after the reset (git cherry-pick from the backup ref), or, if they should go, back them up and reset by hand: git update-ref ${backupRef} ${state.head} && git reset --keep ${state.upstream}.`,
+ { ...askAgain, user_message: `Source ${sourceId}'s checkout has ${localOnly.length} commit(s) that were never pushed (${named.join('; ')}). Keep them (push or re-apply after the reset) or drop them?` },
+ { local_commits: localOnly.slice(0, LIST_CAP), backup_ref: backupRef });
+ }
+ const base = { source_id: sourceId, repo: root, branch: state.branch, tracking_ref: state.tracking_ref, dry_run: !!opts.dryRun, from: state.head, to: state.upstream, next: sync };
+ if (state.head === state.upstream) {
+ if (!opts.dryRun) await clearUpstreamDivergence(engine, sourceId);
+ return { ...base, status: 'already_at_upstream', backup_ref: null, dropped: [], dropped_count: 0 };
+ }
+ const dropped = lines(gitRead(root, ['rev-list', state.head, '--not', state.upstream]));
+ const receipt = { ...base, backup_ref: backupRef, dropped: dropped.slice(0, LIST_CAP), dropped_count: dropped.length };
+ if (opts.dryRun) return { ...receipt, status: 'would_reset' };
+ const write = (args: string[]) => execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'pipe'], timeout: 60_000, env: gitChildEnv({ ...GIT_ENV, LC_ALL: 'C' }) });
+ write(['update-ref', '-m', 'gbrain sources reset-upstream backup', backupRef, state.head, '']);
+ try { write(['reset', '--keep', state.upstream]); } catch (e) {
+ throw opError('git_unavailable', `git reset --keep ${state.upstream} failed in ${root}: ${String((e as { stderr?: unknown }).stderr ?? (e as Error).message).trim().slice(0, 300)}`,
+ `The old HEAD is kept under ${backupRef}. Run git status in ${root}, fix what git reports, then rerun the same reset-upstream command.`);
+ }
+ const after = gitRead(root, ['rev-parse', 'HEAD']);
+ if (after !== state.upstream) {
+ throw opError('git_unavailable', `After the reset HEAD is ${after ?? 'unreadable'}, not ${state.upstream}.`, `The old HEAD is kept under ${backupRef}. Inspect git status and git log in ${root}.`);
+ }
+ await writeUpstreamBaseline(engine, sourceId, root, { ...state, head: after });
+ await clearUpstreamDivergence(engine, sourceId);
+ return { ...receipt, status: 'reset' };
+ } finally {
+ lock?.release();
+ }
+}
+
+export async function runResetUpstream(engine: BrainEngine, args: string[]): Promise<void> {
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`${USAGE}\n\nAfter an upstream force-push (doctor sync_failures: upstream_rewritten or upstream_unknown): keep the\n`
+ + 'current history under refs/gbrain/backup/<stamp>-<sha> and move the checkout to its upstream, under the commit lock.\n'
+ + 'Refuses a moved HEAD or upstream, a dirty tree and local commits that were never on the upstream (it names them).\n'
+ + ` --dry-run run every check and print what would happen; change nothing\n --json print the receipt as JSON\nGuide: ${UPSTREAM_DOCS}`);
+ return;
+ }
+ const p = parse(args);
+ const receipt = await resetUpstream(engine, { sourceId: p.id!, expectLocal: p.expectLocal!, expectUpstream: p.expectUpstream!, dryRun: p.dryRun });
+ if (p.json) { console.log(JSON.stringify(receipt, null, 2)); return; }
+ const to = receipt.to.slice(0, 12);
+ if (receipt.status === 'already_at_upstream') console.log(`${receipt.source_id}: HEAD is already the upstream ${to}; nothing to reset.`);
+ else console.log(`${receipt.source_id}: ${receipt.dry_run ? 'would reset' : 'reset'} ${receipt.repo} from ${receipt.from.slice(0, 12)} to ${receipt.tracking_ref} ${to}; `
+ + `${receipt.dropped_count} commit(s) leave the branch, kept under ${receipt.backup_ref}.`);
+ console.log(`Next: ${receipt.next.argv!.join(' ')}`);
+}
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 6e752b2fd0..eee0e81d57 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1247,6 +1247,7 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
// #6317 (B4): whether managed sync data moves, beside sync_running (a live lock is not progress); the writer-status command rides along.
const movementView = await import('../core/persistence/sync-movement.ts');
const movement = new Map((await movementView.readSourceMovement(engine, { sourceIds: sources.map(source => source.id) }).catch(() => [])).map(m => [m.source_id, m]));
+ const upstreamView = await import('../core/sync-upstream-rewrite.ts'), upstream = new Map((await upstreamView.readUpstreamDivergences(engine, sources.map(source => source.id))).map(u => [u.source_id, upstreamView.renderUpstreamDivergence(u)]));
if (json) {
const enriched = metrics.map((m) => ({
...m,
@@ -1257,7 +1258,7 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
...(backlog.get(m.source_id) ? { managed_backlog: backlog.get(m.source_id) } : {}),
...(movement.get(m.source_id) ? { data_moving: movement.get(m.source_id)!.data_moving, not_moving_since: movement.get(m.source_id)!.not_moving_since,
movement_state: movement.get(m.source_id)!.movement_state, movement: movement.get(m.source_id) } : {}),
- ...(gitHolds.get(m.source_id) ? { git_holds: gitHolds.get(m.source_id) } : {}),
+ ...(gitHolds.get(m.source_id) ? { git_holds: gitHolds.get(m.source_id) } : {}), ...(upstream.get(m.source_id) ? { upstream: upstream.get(m.source_id) } : {}),
...(sharedSkills.get(m.source_id) ? { shared_skills: sharedSkills.get(m.source_id) } : {}),
...(uncommitted.get(m.source_id) ? { fence_repairs_uncommitted: uncommitted.get(m.source_id) } : {}),
}));
@@ -1916,6 +1917,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<v
case 'set-path': { const { runSetPath } = await import('./sources-set-path.ts'); return runSetPath(engine, rest); }
case 'shared-skills': { const { runSourcesSharedSkills } = await import('./sources-shared-skills.ts'); return runSourcesSharedSkills(engine, rest); }
case 'retry-held': { const { runRetryHeld } = await import('./sources-retry-held.ts'); return runRetryHeld(engine, rest); }
+ case 'reset-upstream': { const { runResetUpstream } = await import('./sources-reset-upstream.ts'); return runResetUpstream(engine, rest); }
case 'audit': return runAudit(engine, rest);
// v0.46 github-source demo (offline, privacy-clean fixtures)
case 'demo': { const { runSourcesDemo } = await import('./sources-demo.ts'); return runSourcesDemo(engine, rest); }
@@ -2010,6 +2012,7 @@ Subcommands:
Runs nothing now. Most Git holds re-screen by themselves (file changed or deleted, newer gbrain); fix
frontmatter holds with gbrain repair frontmatter --source <id>; preview fence holds (invalid_fence) with gbrain repair fences --source <id>.
--unindexed instead schedules committed files with no page and no hold (doctor unindexed_files).
+ reset-upstream <id> --expect-local <sha> --expect-upstream <sha> [--dry-run] [--json] After an upstream force-push (upstream_rewritten): back up HEAD, reset to upstream.
shared-skills <id> on|off|status [--json]
Opt a source out of (or back into) shared-skills adoption; status explains its effective policy.
set-path <id> --clear Clear a connector source's (google, github)
diff --git a/src/commands/sync/incremental.ts b/src/commands/sync/incremental.ts
index 5966e69356..92da35b19c 100644
--- a/src/commands/sync/incremental.ts
+++ b/src/commands/sync/incremental.ts
@@ -16,13 +16,15 @@ import { legacyHoldFields, openLegacyHolds, type LegacyHolds } from './holds.ts'
import { runImportsPhase } from './imports.ts';
import { preflightIncrementalSync } from './preflight.ts';
import { runRenamesPhase } from './renames.ts';
+import { readUpstreamDivergence, type UpstreamResultField } from '../../core/sync-upstream-rewrite.ts';
import { createSyncRun, abortUnpersistedPin, registerCheckpointCleanup } from './sync-run.ts';
-export async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<SyncResult> {
+export async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<SyncResult & UpstreamResultField> {
// #5988: content refusals are held, not failed; every exit reports the holds.
const holds = await openLegacyHolds(engine, opts.sourceId);
const result = await runSyncPhases(engine, opts, holds);
- return holds ? { ...result, ...(await legacyHoldFields(engine, holds)) } : result;
+ const upstream = opts.sourceId ? await readUpstreamDivergence(engine, opts.sourceId) : null;
+ return { ...result, ...(holds ? await legacyHoldFields(engine, holds) : {}), ...(upstream ? { upstream } : {}) };
}
async function runSyncPhases(engine: BrainEngine, opts: SyncOpts, holds: LegacyHolds | null): Promise<SyncResult> {
diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.ts
index 81d9ff729a..2c231369e2 100644
--- a/src/commands/sync/preflight.ts
+++ b/src/commands/sync/preflight.ts
@@ -54,6 +54,7 @@ import { sweepOrphanedRenameSentinels } from './rename-reconcile.ts';
import type { SyncPlan, SyncActivePack } from './sync-run.ts';
import { holdUnsupportedPaths, NO_BYTE_PATHS, selectBytePaths, type BytePaths } from './unsupported-paths.ts';
import { formatUrlClonePullBlock, urlClonePullBlock } from '../../core/url-clone.ts';
+import { formatUpstreamNotice, recordUpstreamBeforeFetch, settleUpstreamAfterPull } from '../../core/sync-upstream-rewrite.ts';
export type PreflightOutcome = { readonly done: SyncResult } | { readonly plan: SyncPlan };
@@ -617,6 +618,7 @@ async function pullAndResolveHead(
// process exits could fast-forward the tree behind a released lock.
const { pullRepo, isStoppedGitPull } = await import('../../core/git-remote.ts');
const shutdown = abortOnCleanupPass('sync-git-pull');
+ if (opts.sourceId) await recordUpstreamBeforeFetch(engine, opts.sourceId, gitContextRoot);
try {
// v0.41.13.0 (T3 / D-V4-mech-7): the pull is bounded by the operator's
// --timeout through opts.signal, and by pullRepo's own 300s default
@@ -624,6 +626,7 @@ async function pullAndResolveHead(
// (gitContextRoot), not just the sync scope — git has no per-subdir pull.
await pullRepo(gitContextRoot, { signal: composeAbortSignals(opts.signal, shutdown.signal) });
serr(`[gbrain phase] sync.git_pull done ${Date.now() - _t0}ms`);
+ if (opts.sourceId) await settleUpstreamAfterPull(engine, opts.sourceId, gitContextRoot, true);
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : String(e);
serr(`[gbrain phase] sync.git_pull error ${Date.now() - _t0}ms (${msg.slice(0, 200)})`);
@@ -646,6 +649,8 @@ async function pullAndResolveHead(
} else {
serr(`Warning: git pull failed: ${msg.slice(0, 200)}`); // #1315 stderr-first
}
+ const upstream = opts.sourceId ? await settleUpstreamAfterPull(engine, opts.sourceId, gitContextRoot, false) : null;
+ if (upstream) serr(formatUpstreamNotice(upstream));
// #6946: an owned clone's own checkout blocks it; name the files and the preview-first repair.
const block = opts.sourceId ? await urlClonePullBlock(engine, opts.sourceId) : null;
if (block) serr(formatUrlClonePullBlock(block));
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index fa5d240cbe..c230fe6f34 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -48,7 +48,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -77,7 +77,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--catch-up', '--chat-model', '--check', '--clear-never-installed', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--install', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--since', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--type', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
@@ -111,7 +111,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'repair': ['--acknowledge-managed', '--all', '--all-drifted', '--apply', '--brain', '--break-lock', '--class', '--client', '--close', '--diff', '--expect', '--ff-only', '--force', '--force-break-lock', '--from', '--full', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--scopes', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--url', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-pushes', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
@@ -125,11 +125,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-pushes', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--quiet', '--raw', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--query', '--question', '--queue', '--quiet', '--raw', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 4b4153a1d7..3d8c094577 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -541,6 +541,7 @@ export const CODES = {
request_too_large: { class: 'caller', summary: "The request exceeds a configured capacity; narrow it." },
requirements_changed: { class: 'caller', summary: "The runtime requirements exceed the owner-approved publication policy." },
requires_local_engine: { class: 'host_only', summary: "This command needs the brain's local database, and this install is a thin client of a remote brain." },
+ reset_upstream_refused: { class: 'caller', summary: "gbrain sources reset-upstream changed nothing: the checkout moved since the reset was proposed, has no upstream, has uncommitted tracked edits, or has local commits that were never on the upstream (named, with the backup ref a reset would create).", why: "The reset is bound to the HEAD and upstream the user agreed to and drops only commits the upstream once had; anything else needs the user's decision first.", reasons: ['expect_mismatch', 'no_upstream', 'dirty_tree', 'local_commits'], reason_overrides: { dirty_tree: { class: 'consent' }, local_commits: { class: 'consent' } }, docs: 'docs/guides/troubleshooting.md#upstream-rewritten' },
response_too_large: { class: 'caller', summary: "Persistence response exceeds the local transport limit." },
resume_spec_mismatch: { class: 'caller', summary: "Resume spec mismatch." },
result_too_large: { class: 'caller', summary: "The tool's result is larger than this connection can carry in one response, so it was replaced by this error; nothing was cut.", why: "Results are measured as the complete encoded JSON-RPC frame (every block, notice and escape). A frame over the connection's cap (mcp.max_result_bytes_stdio, 4 MiB; mcp.max_result_bytes_http, 1 MiB) would be rejected or silently cut by the client.", docs: 'docs/guides/windowed-reads.md#result_too_large', legacy_error: 'invalid_params', suggestion: "Ask for less in one call: a window (get_page body: 'window'), a page of rows (limit / from_index), or metadata only (get_versions include_body: false).", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'outline' } }, consent: [], actor: 'agent', why: "Returns the page's size and outline, which name the windows to read.", requires_exclusive: false } },
@@ -659,6 +660,9 @@ export const CODES = {
unsupported_path: { class: 'caller', reasons: ['not_utf8', 'control_character'], summary: "Classic sync held a file whose name is not valid UTF-8 or contains a control character, so it cannot be a page path; the rest of the source synced.", why: "Git stores a name as bytes and a page path is text, so importing a lossy decoding would store a path no file has. The hold key spells the exact bytes (`/gbrain-bytes/` plus %XX escapes), the message names an item id bound to them, and the hold re-screens on every sync and clears once the name leaves the tree.", docs: 'docs/guides/write-refusals.md#unsupported_path', suggestion: 'Rename the file to a valid UTF-8 name without control characters (the hold\'s fix spells the old name with printf escapes, never raw bytes), commit, then run gbrain sync --source <source> --no-pull.' },
unsupported_mutation_protocol: { class: 'unavailable', summary: "Prepared mutation does not match its accepted target." },
upstream: { class: 'retryable', summary: "Google connect credential error: upstream.", docs: 'docs/guides/google-connect.md#troubleshooting' },
+ upstream_diverged: { class: 'caller', actor: 'agent', summary: "A classic source's pull cannot fast-forward: the checkout has commits that are not on the upstream and the upstream moved forward; local HEAD keeps syncing.", why: "The upstream still contains the commit this checkout last pulled, so nothing was force-pushed: bringing the upstream in beside the local commits loses nothing.", docs: 'docs/guides/troubleshooting.md#upstream-rewritten', suggestion: 'Run gbrain git commit-push --pull --path <checkout>, then gbrain sync --source <id>.' },
+ upstream_rewritten: { class: 'consent', actor: 'user', summary: "A classic source's upstream was force-pushed: the upstream commit the checkout last contained is not in the new upstream history, so the pull cannot fast-forward; local HEAD keeps syncing.", why: "Merging would bring back the commits the force-push removed, so the fix resets the checkout to the new upstream after the user agrees, keeping the old history under a backup ref.", docs: 'docs/guides/troubleshooting.md#upstream-rewritten', suggestion: 'Ask the user, then run the gbrain sources reset-upstream <id> --expect-local <sha> --expect-upstream <sha> command doctor sync_failures prints (preview with --dry-run), then gbrain sync --source <id>.' },
+ upstream_unknown: { class: 'consent', actor: 'user', summary: "A classic source's checkout and upstream diverged and gbrain has no record of the upstream before the fetch (first pull after an upgrade, or the recorded commit is gone), so it cannot tell a force-push from local commits; local HEAD keeps syncing.", why: "Merging could bring back commits a force-push removed; the reset preview names any local commit that was never on the upstream before anything moves.", docs: 'docs/guides/troubleshooting.md#upstream-rewritten', suggestion: 'Ask the user, then preview the gbrain sources reset-upstream command doctor sync_failures prints with --dry-run.' },
verification_failed: { class: 'server', summary: "Source content or relationships changed during verification." },
withdrawal_capacity: { class: 'caller', summary: "Withdrawal capacity." },
withdrawal_mirror_failed: { class: 'unavailable', summary: "A page's Git or embedding work is withheld because its withdrawal mirror failed before rewriting the page's file; the file may still hold the withdrawn text.", why: "A withdrawal's Git and embedding effects touch only the pages whose file its mirror recorded rewriting (GBRA-130 A-12); Git never commits a page the mirror passed without rewriting its file. Retrying the request's effects reruns the mirror for this page; once the mirror commits, the withheld work is re-armed automatically.", suggestion: 'Read the parked effects with gbrain doctor --only parked_effects, fix the cause the mirror recorded, then preview gbrain sources writer retry-effects <source> --request-id <id> --dry-run and run it without --dry-run.' },
diff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.ts
index bfd1fdf83e..d2fdff3720 100644
--- a/src/core/git/commit-push.ts
+++ b/src/core/git/commit-push.ts
@@ -209,9 +209,12 @@ function withBranch(ctx: Ctx, branch: string | undefined): Ctx {
return { ...ctx, mergeRef: `refs/heads/${short}`, trackingRef: `refs/remotes/${ctx.remote}/${short}` };
}
+/** The git-dir entries a rebase, merge, cherry-pick or revert leaves while it is in progress. */
+export const GIT_OPERATION_MARKERS = ['rebase-merge', 'rebase-apply', 'MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'sequencer'] as const;
+
/** Refuse while another git operation is mid-flight; never abort it for the user. */
-function assertNoOperationInProgress(root: string): void {
- for (const marker of ['rebase-merge', 'rebase-apply', 'MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'sequencer']) {
+export function assertNoOperationInProgress(root: string): void {
+ for (const marker of GIT_OPERATION_MARKERS) {
if (existsSync(absGitPath(root, marker))) {
throw opError('git_operation_in_progress', `A git ${marker.startsWith('rebase') ? 'rebase' : marker.toLowerCase().replace(/_head$/, '')} is in progress in ${root}.`,
`Finish or abort it first. A stuck rebase may hold another writer's autostash: save it with git stash store <sha from .git/${marker}/autostash> before deleting anything. See docs/guides/shared-checkout-git.md#stuck-rebase.`,
diff --git a/src/core/sync-embed-backfill.ts b/src/core/sync-embed-backfill.ts
index c8a606721a..a2151e299c 100644
--- a/src/core/sync-embed-backfill.ts
+++ b/src/core/sync-embed-backfill.ts
@@ -15,6 +15,7 @@ import {
type EmbedBackfillWorkerSurface,
} from './minions/embed-backfill-admission.ts';
import { runInlineCostGate } from './sync-cost-gate.ts';
+import { renderUpstreamDivergence, type UpstreamDivergenceReport } from './sync-upstream-rewrite.ts';
type SyncCostGateSource = {
id: string;
@@ -220,6 +221,7 @@ export function buildSingleSyncJsonEnvelope(
fromCommit?: string | null;
toCommit?: string;
bankedFiles?: number;
+ upstream?: UpstreamDivergenceReport;
},
embedBackfill?: SyncEmbedBackfillOutcome,
costGate?: Record<string, unknown>,
@@ -231,6 +233,7 @@ export function buildSingleSyncJsonEnvelope(
...syncFailureJsonFields(result),
...syncHoldJsonFields(result),
...(result.reason ? { reason: result.reason } : {}),
+ ...(result.upstream ? { upstream: renderUpstreamDivergence(result.upstream) } : {}),
added: result.added,
modified: result.modified,
deleted: result.deleted,
diff --git a/src/core/sync-upstream-rewrite.ts b/src/core/sync-upstream-rewrite.ts
new file mode 100644
index 0000000000..4f8607022e
--- /dev/null
+++ b/src/core/sync-upstream-rewrite.ts
@@ -0,0 +1,243 @@
+/**
+ * Classic sync's upstream watch (GBRA-133 S-58/S-59). A classic source that
+ * syncs with pull fast-forwards to its upstream; after an upstream force-push
+ * (or local commits beside a moving upstream) that fast-forward fails on every
+ * run. This module tells the cases apart and keeps the answer where doctor and
+ * the sync result can read it, without ever blocking the sync (sync-upstream.ts
+ * keeps the separate freshness observation in the sources.upstream_* columns):
+ *
+ * - `upstream_baseline` (sources.config): the last upstream commit the local
+ * checkout contained, recorded before every fetch and after every pull
+ * that fast-forwarded or was already up to date. Only an upstream commit
+ * that is an ancestor of HEAD is recorded, so a rewritten upstream fetched
+ * by an earlier run never replaces the commit it rewrote.
+ * - `upstream_divergence` (sources.config): set when the pull cannot
+ * fast-forward because HEAD and upstream diverged, cleared by the next pull
+ * that fast-forwards or finds nothing to do. Never a sync-failure ledger
+ * row, so it never gates the bookmark; local HEAD keeps syncing.
+ *
+ * Codes: `upstream_rewritten` (the baseline is not an ancestor of the new
+ * upstream: a force-push removed commits) and `upstream_unknown` (no usable
+ * baseline, so a force-push cannot be told from local commits) are fixed by
+ * `gbrain sources reset-upstream` after the user agrees (a merge would bring
+ * back the commits a force-push removed); `upstream_diverged` (local commits
+ * beside an upstream that moved forward normally) is fixed by
+ * `gbrain git commit-push --pull`. Nothing is classified while a rebase,
+ * merge, cherry-pick or revert is in progress in the checkout.
+ */
+import { existsSync } from 'node:fs';
+import { isAbsolute, resolve } from 'node:path';
+import { cliRenderContext, renderAction, type Action, type RenderedAction } from './agent-output.ts';
+import type { BrainEngine } from './engine.ts';
+import { GIT_OPERATION_MARKERS } from './git/commit-push.ts';
+import { gitChildEnv } from './git-env.ts';
+import { GIT_ENV } from './git-transport.ts';
+import { execFileSync } from './spawn.ts';
+
+export const UPSTREAM_BASELINE_KEY = 'upstream_baseline';
+export const UPSTREAM_DIVERGENCE_KEY = 'upstream_divergence';
+export const UPSTREAM_DOCS = 'docs/guides/troubleshooting.md#upstream-rewritten';
+
+export type UpstreamCode = 'upstream_rewritten' | 'upstream_unknown' | 'upstream_diverged';
+
+export interface UpstreamBaseline { sha: string; tracking_ref: string; recorded_at: string }
+
+/** What the checkout looked like when the pull could not fast-forward. */
+export interface UpstreamDivergence {
+ code: UpstreamCode;
+ source_id: string;
+ repo: string;
+ branch: string | null;
+ tracking_ref: string;
+ local: string;
+ upstream: string;
+ /** The recorded baseline (null for upstream_unknown). */
+ previous_upstream: string | null;
+ first_seen: string;
+ observed_at: string;
+}
+
+/** An observation as doctor, sync and sources status report it. */
+export interface UpstreamDivergenceReport extends UpstreamDivergence { message: string; fix: Action }
+
+/** The classic sync result with the source's standing upstream report. */
+export interface UpstreamResultField { upstream?: UpstreamDivergenceReport }
+
+export interface CheckoutUpstream { head: string; upstream: string; tracking_ref: string; branch: string | null }
+
+const readEnv = () => gitChildEnv({ ...GIT_ENV, GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' });
+
+/** Runs git read-only (no optional locks); null when git exits non-zero. */
+export function gitRead(root: string, args: string[]): string | null {
+ try {
+ return execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'pipe'], timeout: 30_000, env: readEnv() }).toString().trim();
+ } catch {
+ return null;
+ }
+}
+
+/** `a` is an ancestor of (or equal to) `b`; null when git cannot tell (a missing object). */
+export function isAncestor(root: string, a: string, b: string): boolean | null {
+ try {
+ execFileSync('git', ['-C', root, 'merge-base', '--is-ancestor', a, b], { stdio: ['ignore', 'pipe', 'pipe'], timeout: 30_000, env: readEnv() });
+ return true;
+ } catch (e) {
+ return (e as { status?: unknown }).status === 1 ? false : null;
+ }
+}
+
+export function hasCommit(root: string, sha: string): boolean {
+ return gitRead(root, ['cat-file', '-e', `${sha}^{commit}`]) !== null;
+}
+
+/** HEAD, the branch's upstream commit and tracking ref; null when HEAD is unborn or the branch has no upstream. */
+export function readCheckoutUpstream(root: string): CheckoutUpstream | null {
+ const head = gitRead(root, ['rev-parse', '--verify', '-q', 'HEAD^{commit}']);
+ const trackingRef = gitRead(root, ['rev-parse', '--symbolic-full-name', '@{upstream}']);
+ const upstream = trackingRef ? gitRead(root, ['rev-parse', '--verify', '-q', `${trackingRef}^{commit}`]) : null;
+ if (!head || !trackingRef || !upstream) return null;
+ return { head, upstream, tracking_ref: trackingRef, branch: gitRead(root, ['symbolic-ref', '--short', '-q', 'HEAD']) || null };
+}
+
+/** The in-progress git operation marker (rebase-merge, MERGE_HEAD, ...), or null. */
+export function gitOperationInProgress(root: string): string | null {
+ const paths = gitRead(root, ['rev-parse', ...GIT_OPERATION_MARKERS.flatMap(marker => ['--git-path', marker])])?.split('\n');
+ if (!paths) return null;
+ return GIT_OPERATION_MARKERS.find((_, i) => paths[i] && existsSync(isAbsolute(paths[i]!) ? paths[i]! : resolve(root, paths[i]!))) ?? null;
+}
+
+function parseConfig(raw: unknown): Record<string, unknown> {
+ let value = raw;
+ if (typeof raw === 'string') try { value = JSON.parse(raw); } catch { value = null; }
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
+}
+
+async function readSourceConfig(engine: BrainEngine, sourceId: string): Promise<Record<string, unknown>> {
+ const [row] = await engine.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id = $1', [sourceId]);
+ return parseConfig(row?.config);
+}
+
+const asDivergence = (value: unknown): UpstreamDivergence | null =>
+ value && typeof value === 'object' && typeof (value as UpstreamDivergence).code === 'string' && typeof (value as UpstreamDivergence).local === 'string'
+ ? value as UpstreamDivergence : null;
+
+export async function readUpstreamBaseline(engine: BrainEngine, sourceId: string): Promise<UpstreamBaseline | null> {
+ const value = (await readSourceConfig(engine, sourceId))[UPSTREAM_BASELINE_KEY] as UpstreamBaseline | null | undefined;
+ return value && typeof value.sha === 'string' ? value : null;
+}
+
+/** Record the checkout's upstream commit as the baseline, only when HEAD contains it. */
+export async function writeUpstreamBaseline(engine: BrainEngine, sourceId: string, root: string, state: CheckoutUpstream): Promise<void> {
+ if (state.upstream !== state.head && isAncestor(root, state.upstream, state.head) !== true) return;
+ if ((await readUpstreamBaseline(engine, sourceId))?.sha === state.upstream) return;
+ await engine.updateSourceConfig(sourceId, { [UPSTREAM_BASELINE_KEY]: { sha: state.upstream, tracking_ref: state.tracking_ref, recorded_at: new Date().toISOString() } });
+}
+
+export async function clearUpstreamDivergence(engine: BrainEngine, sourceId: string): Promise<void> {
+ if ((await readSourceConfig(engine, sourceId))[UPSTREAM_DIVERGENCE_KEY]) await engine.updateSourceConfig(sourceId, { [UPSTREAM_DIVERGENCE_KEY]: null });
+}
+
+/** Before a classic sync's fetch: remember the upstream commit the checkout already contains. Best effort; never throws. */
+export async function recordUpstreamBeforeFetch(engine: BrainEngine, sourceId: string, root: string): Promise<void> {
+ try {
+ const state = readCheckoutUpstream(root);
+ if (state) await writeUpstreamBaseline(engine, sourceId, root, state);
+ } catch { /* the watch never blocks a sync */ }
+}
+
+/**
+ * After a classic sync's pull. A pull that fast-forwarded or was up to date
+ * records the new baseline and clears the observation; a failed pull whose
+ * HEAD and upstream diverged is classified and stored. Best effort; never throws.
+ */
+export async function settleUpstreamAfterPull(engine: BrainEngine, sourceId: string, root: string, pulled: boolean): Promise<UpstreamDivergenceReport | null> {
+ try {
+ if (pulled) {
+ const state = readCheckoutUpstream(root);
+ if (state) await writeUpstreamBaseline(engine, sourceId, root, state);
+ await clearUpstreamDivergence(engine, sourceId);
+ return null;
+ }
+ if (gitOperationInProgress(root)) return null;
+ const state = readCheckoutUpstream(root);
+ if (!state || isAncestor(root, state.upstream, state.head) !== false || isAncestor(root, state.head, state.upstream) !== false) return null;
+ const config = await readSourceConfig(engine, sourceId);
+ const baseline = (config[UPSTREAM_BASELINE_KEY] as UpstreamBaseline | null | undefined)?.sha;
+ const known = baseline && hasCommit(root, baseline) ? baseline : null;
+ const contained = known ? isAncestor(root, known, state.upstream) : null;
+ const code: UpstreamCode = contained === true ? 'upstream_diverged' : contained === false ? 'upstream_rewritten' : 'upstream_unknown';
+ const prior = asDivergence(config[UPSTREAM_DIVERGENCE_KEY]);
+ const now = new Date().toISOString();
+ const same = prior && prior.code === code && prior.local === state.head && prior.upstream === state.upstream;
+ const observation: UpstreamDivergence = { code, source_id: sourceId, repo: root, branch: state.branch, tracking_ref: state.tracking_ref,
+ local: state.head, upstream: state.upstream, previous_upstream: code === 'upstream_unknown' ? null : known, first_seen: same ? prior.first_seen : now, observed_at: now };
+ await engine.updateSourceConfig(sourceId, { [UPSTREAM_DIVERGENCE_KEY]: observation });
+ return divergenceReport(observation);
+ } catch {
+ return null;
+ }
+}
+
+/** The standing upstream reports of the given (or every) non-archived source. */
+export async function readUpstreamDivergences(engine: BrainEngine, sourceIds?: string[]): Promise<UpstreamDivergenceReport[]> {
+ const rows = await engine.executeRaw<{ id: string; config: unknown }>('SELECT id, config FROM sources WHERE archived IS NOT TRUE ORDER BY id');
+ return rows.filter(row => !sourceIds || sourceIds.includes(row.id))
+ .map(row => asDivergence(parseConfig(row.config)[UPSTREAM_DIVERGENCE_KEY]))
+ .filter((o): o is UpstreamDivergence => o !== null)
+ .map(divergenceReport);
+}
+
+export async function readUpstreamDivergence(engine: BrainEngine, sourceId: string): Promise<UpstreamDivergenceReport | null> {
+ const observation = asDivergence((await readSourceConfig(engine, sourceId))[UPSTREAM_DIVERGENCE_KEY]);
+ return observation ? divergenceReport(observation) : null;
+}
+
+const short = (sha: string | null) => (sha ?? '').slice(0, 12);
+
+export function divergenceReport(o: UpstreamDivergence): UpstreamDivergenceReport {
+ const where = `Source ${o.source_id} (${o.tracking_ref})`;
+ const keeps = `Local HEAD ${short(o.local)} keeps syncing; upstream commits are not imported until this is resolved.`;
+ const message = o.code === 'upstream_rewritten'
+ ? `${where}: the upstream was rewritten (force-pushed): ${short(o.previous_upstream)}, the upstream commit this checkout last contained, is not in the new upstream ${short(o.upstream)}, so the pull cannot fast-forward. ${keeps}`
+ : o.code === 'upstream_unknown'
+ ? `${where}: local HEAD ${short(o.local)} and upstream ${short(o.upstream)} have diverged and gbrain has no record of the upstream before this fetch, so it cannot tell a force-push from local commits. ${keeps}`
+ : `${where}: this checkout has commits that are not on the upstream, and the upstream moved forward to ${short(o.upstream)}, so the pull cannot fast-forward. ${keeps}`;
+ return { ...o, message, fix: upstreamFix(o) };
+}
+
+const doctorVerify = { argv: ['gbrain', 'doctor', '--only', 'sync_failures', '--json'] };
+
+function followUpSync(o: UpstreamDivergence): Action {
+ return { argv: ['gbrain', 'sync', '--source', o.source_id], consent: [], actor: 'agent', requires_exclusive: false, verify: doctorVerify,
+ why: 'The next sync pulls the upstream (now a fast-forward or already up to date), imports its commits and clears the upstream report.' };
+}
+
+/** The typed next step: a reset bound to the observed commits (ask the user first), or the shared-checkout pull for plain divergence. */
+export function upstreamFix(o: UpstreamDivergence): Action {
+ if (o.code === 'upstream_diverged') {
+ return { argv: ['gbrain', 'git', 'commit-push', '--pull', '--path', o.repo], consent: [], actor: 'agent', requires_exclusive: false, verify: doctorVerify,
+ why: 'Brings the upstream commits in beside the local ones (fast-forward or an in-memory merge under the commit lock); nothing is pushed and no commit is dropped.',
+ docs: UPSTREAM_DOCS, then: followUpSync(o) };
+ }
+ const reset = ['gbrain', 'sources', 'reset-upstream', o.source_id, '--expect-local', o.local, '--expect-upstream', o.upstream];
+ return {
+ ask_user: true, argv: reset, preview_argv: [...reset, '--dry-run'], consent: ['destructive'], actor: 'agent', requires_exclusive: true, verify: doctorVerify, docs: UPSTREAM_DOCS,
+ why: o.code === 'upstream_rewritten'
+ ? 'A merge would bring back the commits the force-push removed, so the checkout is reset to the new upstream instead; the reset keeps the old history under a backup ref and refuses local commits that were never on the upstream.'
+ : 'Without a record of the old upstream gbrain cannot tell whether the local-only commits were removed by a force-push or never pushed; the reset preview names any commit that was never on the upstream before anything moves.',
+ user_message: o.code === 'upstream_rewritten'
+ ? `The upstream of source ${o.source_id} was force-pushed. Reset the local checkout to the new upstream ${short(o.upstream)}? The current history (${short(o.local)}) is kept under a backup ref.`
+ : `Source ${o.source_id}'s checkout and its upstream have diverged and gbrain cannot tell why. Preview resetting it to the upstream ${short(o.upstream)}? The current history is kept under a backup ref.`,
+ then: followUpSync(o),
+ };
+}
+
+/** The wire form for local CLI JSON (sync --json, sources status --json): the fix rendered with its next step and command. */
+export function renderUpstreamDivergence(report: UpstreamDivergenceReport): Omit<UpstreamDivergenceReport, 'fix'> & { fix: RenderedAction } {
+ return { ...report, fix: renderAction(report.fix, cliRenderContext()) };
+}
+
+/** The stderr line a classic sync prints when it records an observation. */
+export function formatUpstreamNotice(report: UpstreamDivergenceReport): string {
+ return `Warning [${report.code}]: ${report.message} Next${report.fix.ask_user ? ' (ask the user first)' : ''}: ${report.fix.argv!.join(' ')}. See ${UPSTREAM_DOCS}.`;
+}
diff --git a/test/e2e/s-58-upstream-rewrite-postgres.test.ts b/test/e2e/s-58-upstream-rewrite-postgres.test.ts
new file mode 100644
index 0000000000..3910aba4ef
--- /dev/null
+++ b/test/e2e/s-58-upstream-rewrite-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../pathological/s-58-upstream-rewrite.test.ts'));
diff --git a/test/pathological/s-58-upstream-rewrite.test.ts b/test/pathological/s-58-upstream-rewrite.test.ts
new file mode 100644
index 0000000000..77e41f2cac
--- /dev/null
+++ b/test/pathological/s-58-upstream-rewrite.test.ts
@@ -0,0 +1,278 @@
+/**
+ * S-58/S-59 (GBRA-133): an upstream force-push under a classic clone that
+ * syncs with pull. The fast-forward fails on every run; before this fix every
+ * run returned partial/pull_failed, --skip-failed changed nothing and doctor
+ * sync_failures said nothing.
+ *
+ * Protects: classic preflight records the upstream commit the checkout contains
+ * before every fetch, classifies a pull that cannot fast-forward
+ * (upstream_rewritten, upstream_unknown when nothing usable was recorded,
+ * upstream_diverged for local commits beside a normally moving upstream) as a
+ * non-blocking source observation (never a sync-failure ledger row), names it
+ * in the sync result and doctor sync_failures with its typed fix, and clears it
+ * on the next pull that fast-forwards or is up to date. Nothing is classified
+ * while a merge is in progress. gbrain sources reset-upstream refuses a moved
+ * HEAD or upstream, a dirty tree and never-pushed local commits (naming them),
+ * and otherwise keeps the old HEAD under a backup ref, resets, verifies, and the
+ * next sync catches up with the upstream.
+ * Fails when: the pull failure stays an anonymous partial, the classification
+ * lands in the ledger, the fix for a force-push is a merge, or the reset moves
+ * a checkout it was not bound to. PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { pullShared } from '../../src/core/git/commit-push.ts';
+import { loadSyncFailures } from '../../src/core/sync-failure-ledger.ts';
+import { checkSyncFailures } from '../../src/commands/doctor/checks/sync-failures.ts';
+import { runSources } from '../../src/commands/sources.ts';
+import { buildSingleSyncJsonEnvelope } from '../../src/core/sync-embed-backfill.ts';
+import { pathologicalArms } from './harness.ts';
+import { CASES } from './s-blockers-cases.ts';
+import { gitIn, md, withProbeEngine, withProbeRepo, type ProbeRepo } from './s-blockers-fixture.ts';
+
+interface UpstreamField { code: string; local: string; upstream: string; previous_upstream: string | null; message: string;
+ fix: { ask_user?: boolean; argv?: string[]; consent: string[]; then?: { argv?: string[] } } }
+
+const E = ['-c', 'user.name=E', '-c', '[email protected]'];
+const upOf = (r: ProbeRepo) => r.root.replace(/-clone$/, '');
+const commitUp = (up: string, msg: string) => { gitIn(up, 'add', '-A'); gitIn(up, ...E, 'commit', '-qm', msg); };
+const ledgerRows = (sourceId: string) => loadSyncFailures().filter(row => row.source_id === sourceId);
+const page = async (r: ProbeRepo, slug: string) =>
+ (await r.engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [r.sourceId, slug])).length > 0;
+const doctor = (r: ProbeRepo) => checkSyncFailures(r.engine, { sourceIds: [r.sourceId], remote: false });
+const upstreamOf = (result: unknown) => (result as { upstream?: UpstreamField }).upstream;
+const resetModule = () => import('../../src/commands/sources-reset-upstream.ts');
+
+/** A clone of a fresh upstream (seed.md, plus second.md for a non-root rewrite), registered as a classic source. */
+function makeClone(home: string, opts: { second?: boolean } = {}): string {
+ const up = join(home, 'up-' + Math.random().toString(36).slice(2, 8)); mkdirSync(up);
+ gitIn(up, 'init', '-q', '-b', 'main'); gitIn(up, 'config', 'receive.denyCurrentBranch', 'ignore');
+ writeFileSync(join(up, 'seed.md'), md('seed')); commitUp(up, 'seed');
+ if (opts.second) { writeFileSync(join(up, 'second.md'), md('second')); commitUp(up, 'second'); }
+ const root = up + '-clone';
+ execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', 'file://' + up, root]);
+ gitIn(root, 'config', 'user.name', 'Example'); gitIn(root, 'config', 'user.email', '[email protected]');
+ return root;
+}
+
+async function withClone(engine: BrainEngine, home: string, root: string, run: (r: ProbeRepo) => Promise<void>): Promise<void> {
+ await withProbeRepo(engine, 'classic', home, run, { root, initRepo: false, seed: false });
+}
+
+/** The S-58/S-59 probe flow up to the rewritten upstream: first sync with pull, ok/healthy-1.md, then the case's force-push. */
+async function rewrite(r: ProbeRepo, id: 'S-58' | 'S-59'): Promise<void> {
+ const first = await r.sync({ pull: true });
+ expect(first.status).toBe('first_sync');
+ r.write('ok/healthy-1.md', md('healthy 1'));
+ await CASES.find(c => c.id === id)!.mutate(r);
+}
+
+/** Every observation names the code with its typed fix and is never a ledger row. */
+async function expectObserved(r: ProbeRepo, result: unknown, code: string): Promise<UpstreamField> {
+ const upstream = upstreamOf(result);
+ expect({ code: upstream?.code }).toEqual({ code });
+ expect(ledgerRows(r.sourceId)).toEqual([]);
+ const check = await doctor(r);
+ expect({ status: check?.status, code: (check?.details?.upstream as UpstreamField[] | undefined)?.[0]?.code }).toEqual({ status: 'warn', code });
+ expect(check!.message).toContain(upstream!.fix.argv!.join(' '));
+ expect(check!.fix).toEqual(upstream!.fix as never);
+ return upstream!;
+}
+
+function expectResetFix(r: ProbeRepo, upstream: UpstreamField): void {
+ const head = r.head(), tip = gitIn(r.root, 'rev-parse', '@{upstream}');
+ expect(upstream.fix.ask_user).toBe(true);
+ expect(upstream.fix.consent).toEqual(['destructive']);
+ expect(upstream.fix.argv).toEqual(['gbrain', 'sources', 'reset-upstream', r.sourceId, '--expect-local', head, '--expect-upstream', tip]);
+ expect(upstream.fix.argv!.join(' ')).not.toContain('commit-push');
+ expect(upstream.fix.then?.argv).toEqual(['gbrain', 'sync', '--source', r.sourceId]);
+}
+
+async function stdoutOf(run: () => Promise<unknown>): Promise<string> {
+ const lines: string[] = [];
+ const log = console.log;
+ console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };
+ try { await run(); } finally { console.log = log; }
+ return lines.join('\n');
+}
+
+async function refusal(run: () => Promise<unknown>): Promise<{ code?: string; reason?: string; message: string }> {
+ try { await run(); } catch (e) { return { code: (e as { code?: string }).code, reason: (e as { reason?: string }).reason, message: (e as Error).message }; }
+ throw new Error('expected a refusal');
+}
+
+for (const arm of pathologicalArms()) {
+ describe(`S-58/S-59 upstream rewrite under classic sync with pull (${arm.backend})`, () => {
+ for (const id of ['S-58', 'S-59'] as const) {
+ test(`${id}: upstream_rewritten is reported with the reset fix, local HEAD keeps syncing, and the reset catches up`, async () => {
+ await withProbeEngine(arm.databaseUrl, async (engine, home) => {
+ await withClone(engine, home, CASES.find(c => c.id === id)!.makeRoot!(home), async r => {
+ await rewrite(r, id);
+ const result = await r.sync({ pull: true });
+ expect({ status: result.status, reason: result.reason }).toEqual({ status: 'partial', reason: 'pull_failed' });
+ expect(await r.lastCommit()).toBe(r.head());
+ expect(await page(r, 'seed')).toBe(true);
+ const upstream = await expectObserved(r, result, 'upstream_rewritten');
+ expectResetFix(r, upstream);
+ expect(upstream.previous_upstream).toBe(r.head());
+ const envelope = buildSingleSyncJsonEnvelope(r.sourceId, result) as { upstream?: { code: string; fix: { next: string; command?: string } } };
+ expect({ code: envelope.upstream?.code, next: envelope.upstream?.fix.next }).toEqual({ code: 'upstream_rewritten', next: 'ask_user' });
+ const status = JSON.parse(await stdoutOf(() => runSources(engine, ['status', r.sourceId, '--json']))) as { sources: Array<{ source_id: string; upstream?: { code: string; fix: { next: string } } }> };
+ expect(status.sources.map(s => ({ id: s.source_id, code: s.upstream?.code, next: s.upstream?.fix.next })))
+ .toEqual([{ id: r.sourceId, code: 'upstream_rewritten', next: 'ask_user' }]);
+
+ const again = await r.sync({ pull: true, skipFailed: true });
+ expect(upstreamOf(again)?.code).toBe('upstream_rewritten');
+ expect(ledgerRows(r.sourceId)).toEqual([]);
+
+ const { resetUpstream } = await resetModule();
+ const head = r.head(), tip = gitIn(r.root, 'rev-parse', '@{upstream}');
+ const preview = await resetUpstream(engine, { sourceId: r.sourceId, expectLocal: head, expectUpstream: tip, dryRun: true });
+ expect({ status: preview.status, head: r.head() }).toEqual({ status: 'would_reset', head });
+ expect(gitIn(r.root, 'for-each-ref', 'refs/gbrain/backup')).toBe('');
+ const done = await resetUpstream(engine, { sourceId: r.sourceId, expectLocal: head, expectUpstream: tip });
+ expect({ status: done.status, from: done.from, to: done.to, head: r.head() }).toEqual({ status: 'reset', from: head, to: tip, head: tip });
+ expect(done.backup_ref).toMatch(/^refs\/gbrain\/backup\/\d{8}T\d{6}Z-[0-9a-f]{12}$/);
+ expect(gitIn(r.root, 'rev-parse', done.backup_ref!)).toBe(head);
+ expect(done.dropped).toContain(head);
+ expect(await doctor(r)).toBeNull();
+
+ const up = upOf(r);
+ mkdirSync(join(up, 'ok'), { recursive: true });
+ writeFileSync(join(up, 'ok/healthy-2.md'), md('healthy 2')); commitUp(up, 'healthy 2');
+ const caughtUp = await r.sync({ pull: true });
+ expect({ status: caughtUp.status, upstream: upstreamOf(caughtUp) ?? null }).toEqual({ status: 'synced', upstream: null });
+ expect({ h1: await page(r, 'ok/healthy-1'), h2: await page(r, 'ok/healthy-2'), atHead: (await r.lastCommit()) === r.head() })
+ .toEqual({ h1: true, h2: true, atHead: true });
+ expect(r.head()).toBe(gitIn(up, 'rev-parse', 'HEAD'));
+ expect(await doctor(r)).toBeNull();
+ });
+ });
+ }, 180_000);
+ }
+
+ test('upstream_unknown: a rewrite already fetched before anything was recorded (an upgrade) asks for the reset, never a merge', async () => {
+ await withProbeEngine(arm.databaseUrl, async (engine, home) => {
+ await withClone(engine, home, CASES.find(c => c.id === 'S-58')!.makeRoot!(home), async r => {
+ await rewrite(r, 'S-58');
+ await engine.executeRaw("UPDATE sources SET config = config - 'upstream_baseline' WHERE id = $1", [r.sourceId]);
+ gitIn(r.root, 'fetch', '-q');
+ const result = await r.sync({ pull: true });
+ expect(await r.lastCommit()).toBe(r.head());
+ const upstream = await expectObserved(r, result, 'upstream_unknown');
+ expectResetFix(r, upstream);
+ expect(upstream.previous_upstream).toBeNull();
+ const { resetUpstream } = await resetModule();
+ const done = await resetUpstream(engine, { sourceId: r.sourceId, expectLocal: r.head(), expectUpstream: gitIn(r.root, 'rev-parse', '@{upstream}') });
+ expect(done.status).toBe('reset');
+ const caughtUp = await r.sync({ pull: true });
+ expect({ upstream: upstreamOf(caughtUp) ?? null, h1: await page(r, 'ok/healthy-1') }).toEqual({ upstream: null, h1: true });
+ });
+ });
+ }, 180_000);
+
+ test('a rewrite on the first pull after an upgrade is still upstream_rewritten when the old upstream is the tracking ref', async () => {
+ await withProbeEngine(arm.databaseUrl, async (engine, home) => {
+ await withClone(engine, home, makeClone(home), async r => {
+ expect((await r.sync()).status).toBe('first_sync');
+ const up = upOf(r);
+ writeFileSync(join(up, 'seed.md'), md('seed rewritten')); gitIn(up, 'add', '-A'); gitIn(up, ...E, 'commit', '-q', '--amend', '-m', 'seed rewritten');
+ await expectObserved(r, await r.sync({ pull: true }), 'upstream_rewritten');
+ });
+ });
+ }, 180_000);
+
+ test('upstream_diverged: local commits beside a normally moving upstream get the commit-push --pull fix; the next advancing pull clears it', async () => {
+ await withProbeEngine(arm.databaseUrl, async (engine, home) => {
+ await withClone(engine, home, makeClone(home), async r => {
+ expect((await r.sync({ pull: true })).status).toBe('first_sync');
+ r.write('notes/local.md', md('local')); r.commitAll('local note');
+ const up = upOf(r);
+ mkdirSync(join(up, 'ok'), { recursive: true }); writeFileSync(join(up, 'ok/healthy-1.md'), md('healthy 1')); commitUp(up, 'healthy 1');
+ const result = await r.sync({ pull: true });
+ expect({ local: await page(r, 'notes/local'), atHead: (await r.lastCommit()) === r.head() }).toEqual({ local: true, atHead: true });
+ const upstream = await expectObserved(r, result, 'upstream_diverged');
+ expect(upstream.fix.ask_user).toBeUndefined();
+ expect(upstream.fix.argv).toEqual(['gbrain', 'git', 'commit-push', '--pull', '--path', r.root]);
+ expect(pullShared(r.root).status).toBe('advanced');
+ const cleared = await r.sync({ pull: true });
+ expect({ upstream: upstreamOf(cleared) ?? null, h1: await page(r, 'ok/healthy-1') }).toEqual({ upstream: null, h1: true });
+ expect(await doctor(r)).toBeNull();
+ });
+ });
+ }, 180_000);
+
+ test('nothing is classified while a merge is in progress', async () => {
+ await withProbeEngine(arm.databaseUrl, async (engine, home) => {
+ await withClone(engine, home, makeClone(home), async r => {
+ expect((await r.sync({ pull: true })).status).toBe('first_sync');
+ r.write('seed.md', md('seed edited here')); r.commitAll('local edit');
+ const up = upOf(r);
+ writeFileSync(join(up, 'seed.md'), md('seed edited upstream')); commitUp(up, 'upstream edit');
+ gitIn(r.root, 'fetch', '-q');
+ expect(() => gitIn(r.root, 'merge', '--no-edit', '@{upstream}')).toThrow();
+ expect(gitIn(r.root, 'rev-parse', '-q', '--verify', 'MERGE_HEAD')).not.toBe('');
+ const result = await r.sync({ pull: true });
+ expect(upstreamOf(result) ?? null).toBeNull();
+ expect(await doctor(r)).toBeNull();
+ expect(ledgerRows(r.sourceId)).toEqual([]);
+ });
+ });
+ }, 180_000);
+
+ test('a merge in progress leaves a standing observation as it was (no re-classification)', async () => {
+ await withProbeEngine(arm.databaseUrl, async (engine, home) => {
+ await withClone(engine, home, makeClone(home), async r => {
+ expect((await r.sync({ pull: true })).status).toBe('first_sync');
+ r.write('seed.md', md('seed edited here')); r.commitAll('local edit');
+ const up = upOf(r);
+ writeFileSync(join(up, 'seed.md'), md('seed edited upstream')); commitUp(up, 'upstream edit');
+ const first = await expectObserved(r, await r.sync({ pull: true }), 'upstream_diverged') as UpstreamField & { observed_at: string };
+ expect(() => gitIn(r.root, 'merge', '--no-edit', '@{upstream}')).toThrow();
+ const during = upstreamOf(await r.sync({ pull: true })) as (UpstreamField & { observed_at: string }) | undefined;
+ expect({ code: during?.code, observed_at: during?.observed_at }).toEqual({ code: 'upstream_diverged', observed_at: first.observed_at });
+ expect(ledgerRows(r.sourceId)).toEqual([]);
+ });
+ });
+ }, 180_000);
+
+ test('reset-upstream refuses a moved checkout, a dirty tree and never-pushed local commits, and changes nothing', async () => {
+ await withProbeEngine(arm.databaseUrl, async (engine, home) => {
+ await withClone(engine, home, makeClone(home), async r => {
+ expect((await r.sync({ pull: true })).status).toBe('first_sync');
+ r.write('notes/unpushed.md', md('unpushed')); r.commitAll('unpushed alice-example note');
+ const up = upOf(r);
+ writeFileSync(join(up, 'seed.md'), md('seed rewritten')); gitIn(up, 'add', '-A'); gitIn(up, ...E, 'commit', '-q', '--amend', '-m', 'seed rewritten');
+ const upstream = await expectObserved(r, await r.sync({ pull: true }), 'upstream_rewritten');
+ const { resetUpstream, runResetUpstream } = await resetModule();
+ const head = r.head(), tip = gitIn(r.root, 'rev-parse', '@{upstream}');
+ const reset = (o: { expectLocal?: string; expectUpstream?: string } = {}) =>
+ resetUpstream(engine, { sourceId: r.sourceId, expectLocal: o.expectLocal ?? head, expectUpstream: o.expectUpstream ?? tip });
+
+ const moved = await refusal(() => reset({ expectLocal: tip }));
+ expect({ code: moved.code, reason: moved.reason }).toEqual({ code: 'reset_upstream_refused', reason: 'expect_mismatch' });
+
+ writeFileSync(join(r.root, 'seed.md'), md('uncommitted'));
+ const dirty = await refusal(() => reset());
+ expect({ code: dirty.code, reason: dirty.reason }).toEqual({ code: 'reset_upstream_refused', reason: 'dirty_tree' });
+ expect(dirty.message).toContain('seed.md');
+ gitIn(r.root, 'checkout', '--', 'seed.md');
+
+ const local = await refusal(() => reset());
+ expect({ code: local.code, reason: local.reason }).toEqual({ code: 'reset_upstream_refused', reason: 'local_commits' });
+ expect(local.message).toContain('unpushed alice-example note');
+ expect(local.message).toMatch(/refs\/gbrain\/backup\/\d{8}T\d{6}Z-/);
+ expect({ head: r.head(), backups: gitIn(r.root, 'for-each-ref', 'refs/gbrain/backup') }).toEqual({ head, backups: '' });
+ expect(upstream.fix.argv).toContain(head);
+
+ await expect(runResetUpstream(engine, [r.sourceId, '--expect-local', head, '--expect-upstream', tip, '--dry-run', '--json'])).rejects.toMatchObject({ code: 'reset_upstream_refused', reason: 'local_commits' });
+ await expect(runResetUpstream(engine, [r.sourceId, '--expect-local', head])).rejects.toMatchObject({ code: 'invalid_params' });
+ expect(r.head()).toBe(head);
+ });
+ });
+ }, 180_000);
+ });
+}