diff --git a/README.md b/README.md index d371aee..6a75e73 100644 --- a/README.md +++ b/README.md @@ -302,6 +302,23 @@ Env var naming rules: | `/sync-sessions-cleanup-git` | Remove deprecated Git session artifacts after migration | | `/sync-resolve` | Auto-resolve uncommitted changes using AI | +### Drift and dry runs + +`status` also compares this machine with the repo: + +- `Local changes:` how many synced files differ from what the repo holds, so unpushed edits show up + even though `Working tree` (the state of the plugin's own clone) says `clean`. +- `Remote:` whether the remote has commits you have not pulled, or you have commits not pushed. + +`pull` and `push` accept `dryRun: true` (for example `{"command":"push","dryRun":true}` on opencode +v2) to list what would change without changing anything. A push dry run stages your local config +into a throwaway clone, so it uses the same logic as a real push and never touches the sync repo, your +config or the overrides file. Real runs now end with the same per-file summary, for example +`2 files: 1 updated, 1 added`. + +Dry runs and `Local changes` cover `config/` and `state/` only; session data and secret files are never +compared or printed. +
Manual sync (without slash commands) diff --git a/src/index.ts b/src/index.ts index 3d93424..365da5a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -82,6 +82,10 @@ export const opencodeConfigSync: Plugin = async (ctx) => { .describe( 'Acknowledge that an explicit non-GitHub remote is private (only after user confirmation)' ), + dryRun: tool.schema + .boolean() + .optional() + .describe('For pull and push: list what would change without changing anything'), setupTurso: tool.schema .boolean() .optional() diff --git a/src/shared.ts b/src/shared.ts index 0003cbf..bae5d9a 100644 --- a/src/shared.ts +++ b/src/shared.ts @@ -150,6 +150,7 @@ export interface SyncToolArgs { acknowledgePrivateRemote?: boolean; setupTurso?: boolean; migrateSessions?: boolean; + dryRun?: boolean; } export function buildSyncToolInputSchema(): Record { @@ -176,6 +177,7 @@ export function buildSyncToolInputSchema(): Record { extraConfigPaths: { type: 'array', items: { type: 'string' } }, localRepoPath: { type: 'string' }, acknowledgePrivateRemote: { type: 'boolean' }, + dryRun: { type: 'boolean' }, setupTurso: { type: 'boolean' }, migrateSessions: { type: 'boolean' }, }, @@ -226,10 +228,10 @@ export async function executeSyncCommand( }); } if (args.command === 'pull') { - return await service.pull(); + return await service.pull({ dryRun: args.dryRun }); } if (args.command === 'push') { - return await service.push(); + return await service.push({ dryRun: args.dryRun }); } if (args.command === 'secrets-pull') { return await service.secretsPull(); diff --git a/src/sync/preview.test.ts b/src/sync/preview.test.ts new file mode 100644 index 0000000..ea7f30e --- /dev/null +++ b/src/sync/preview.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest'; +import { summarizeChanges } from './preview.js'; + +describe('summarizeChanges', () => { + it('returns nothing for no changes', () => { + expect(summarizeChanges([])).toEqual([]); + expect(summarizeChanges(['', ' '])).toEqual([]); + }); + + it('counts actions and lists paths from porcelain and name-status lines', () => { + expect( + summarizeChanges([ + 'M config/opencode.json', + '?? config/agents/lead.md', + 'D\tconfig/commands/old.md', + 'A\tconfig/commands/new.md', + ]) + ).toEqual([ + '4 files: 1 updated, 2 added, 1 deleted', + ' update config/opencode.json', + ' add config/agents/lead.md', + ' delete config/commands/old.md', + ' add config/commands/new.md', + ]); + }); + + it('uses the new path for renames and the singular noun for one file', () => { + expect(summarizeChanges(['R100\tconfig/a.md\tconfig/b.md'])[0]).toBe('1 file: 1 renamed'); + expect(summarizeChanges(['R config/a.md -> config/b.md'])[1]).toBe(' rename config/b.md'); + }); + + it('truncates long lists', () => { + const lines = Array.from({ length: 20 }, (_value, index) => `M config/file-${index}.md`); + const summary = summarizeChanges(lines, 5); + expect(summary).toHaveLength(1 + 5 + 1); + expect(summary.at(-1)).toBe(' ... and 15 more'); + }); +}); diff --git a/src/sync/preview.ts b/src/sync/preview.ts new file mode 100644 index 0000000..9b9a41e --- /dev/null +++ b/src/sync/preview.ts @@ -0,0 +1,127 @@ +import { promises as fs } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import type { PluginInput } from '@opencode-ai/plugin'; + +import { syncLocalToRepo } from './apply.js'; +import type { NormalizedSyncConfig } from './config.js'; +import { canCommitMcpSecrets } from './config.js'; +import { buildSyncPlan, type SyncLocations } from './paths.js'; +import { getStatusLines } from './repo.js'; + +type Shell = PluginInput['$']; + +/** Repo paths the preview reports on. Secrets and session data are never compared or printed. */ +const PREVIEW_ROOTS = ['config/', 'state/'] as const; +const MAX_LISTED_CHANGES = 15; + +const ACTION_BY_CODE: Record = { + M: 'update', + A: 'add', + '??': 'add', + D: 'delete', + R: 'rename', + C: 'add', + T: 'update', +}; + +/** + * Lists what a push would change, without touching the real sync repo, the real config or the + * overrides file. The local config is staged into a throwaway sparse clone with the same code a + * real push uses, and the clone's `git status` is reported. Only paths are returned, never content. + * + * Session and secret items are not compared. Returns null when the preview cannot be computed. + */ +export async function previewLocalChanges( + $: Shell, + config: NormalizedSyncConfig, + locations: SyncLocations, + repoRoot: string, + overrides: Record | null +): Promise { + let scratchRoot: string | null = null; + try { + scratchRoot = await fs.mkdtemp(path.join(tmpdir(), 'opencode-synced-preview-')); + const cloneRoot = path.join(scratchRoot, 'repo'); + await $`git clone --quiet --local --no-checkout ${repoRoot} ${cloneRoot}`.quiet(); + try { + await $`git -C ${cloneRoot} sparse-checkout set --no-cone /config /state`.quiet(); + } catch { + // Older Git without sparse-checkout: fall back to a full checkout. + } + const head = (await $`git -C ${repoRoot} rev-parse HEAD`.quiet().text()).trim(); + await $`git -C ${cloneRoot} checkout --quiet --detach ${head}`.quiet(); + + const plan = buildSyncPlan(config, locations, cloneRoot); + await syncLocalToRepo( + { + ...plan, + items: plan.items.filter( + (item) => !item.isSecret && !item.chunkLargeFiles && !item.preserveWhenMissing + ), + extraSecrets: { ...plan.extraSecrets, allowlist: [], entries: [] }, + }, + overrides, + { allowMcpSecrets: canCommitMcpSecrets(config) } + ); + + const changes = await getStatusLines($, cloneRoot); + return changes.filter((line) => + PREVIEW_ROOTS.some((root) => changePath(line).startsWith(root)) + ); + } catch { + return null; + } finally { + if (scratchRoot) { + await fs.rm(scratchRoot, { recursive: true, force: true }); + } + } +} + +function changePath(line: string): string { + const match = /^\S+\s+(.*)$/u.exec(line); + const rest = match?.[1] ?? line; + const renamed = rest.split(' -> '); + return (renamed[renamed.length - 1] ?? rest).replace(/^"|"$/gu, ''); +} + +function changeAction(line: string): string { + const code = /^(\S+)/u.exec(line)?.[1] ?? ''; + return ACTION_BY_CODE[code] ?? ACTION_BY_CODE[code.charAt(0)] ?? 'update'; +} + +/** + * Turns `git status --porcelain` or `git diff --name-status` lines into a short summary, for + * example `3 files: 2 updated, 1 added` followed by one `action path` line per file. + */ +export function summarizeChanges(lines: string[], limit = MAX_LISTED_CHANGES): string[] { + const entries = lines + .map((line) => line.trim()) + .filter(Boolean) + .map((line) => ({ action: changeAction(line), path: changePath(line) })); + if (entries.length === 0) return []; + + const counts = new Map(); + for (const entry of entries) { + counts.set(entry.action, (counts.get(entry.action) ?? 0) + 1); + } + const past: Record = { + update: 'updated', + add: 'added', + delete: 'deleted', + rename: 'renamed', + }; + const breakdown = [...counts.entries()] + .map(([action, count]) => `${count} ${past[action] ?? action}`) + .join(', '); + + const noun = entries.length === 1 ? 'file' : 'files'; + const summary = [`${entries.length} ${noun}: ${breakdown}`]; + for (const entry of entries.slice(0, limit)) { + summary.push(` ${entry.action} ${entry.path}`); + } + if (entries.length > limit) { + summary.push(` ... and ${entries.length - limit} more`); + } + return summary; +} diff --git a/src/sync/repo.ts b/src/sync/repo.ts index 78600a9..ac6171b 100644 --- a/src/sync/repo.ts +++ b/src/sync/repo.ts @@ -239,6 +239,47 @@ export async function fetchAndFastForward( return { updated: false, branch }; } +export interface RemoteDrift { + /** Commits in the local sync repo that are not on the remote branch. */ + ahead: number; + /** Commits on the remote branch that a pull would bring in. */ + behind: number; + /** `git diff --name-status` lines for what a pull would change. */ + changes: string[]; +} + +/** + * Read-only check of how the local sync repo relates to its remote. Fetches, but never moves the + * branch or the working tree. Returns null when the remote cannot be reached. + */ +export async function inspectRemoteDrift( + $: Shell, + repoDir: string, + branch: string +): Promise { + try { + await $`git -C ${repoDir} fetch --prune`.quiet(); + } catch { + return null; + } + if (!(await hasRemoteBranch($, repoDir, branch))) { + return { ahead: 0, behind: 0, changes: [] }; + } + const remoteRef = `origin/${branch}`; + const { ahead, behind } = await getAheadBehind($, repoDir, remoteRef); + if (behind === 0) return { ahead, behind, changes: [] }; + try { + const output = await $`git -C ${repoDir} diff --name-status HEAD ${remoteRef}`.quiet().text(); + const changes = output + .split('\n') + .map((line) => line.trim()) + .filter(Boolean); + return { ahead, behind, changes }; + } catch { + return { ahead, behind, changes: [] }; + } +} + export async function getRepoStatus($: Shell, repoDir: string): Promise { const branch = await getCurrentBranch($, repoDir); const changes = await getStatusLines($, repoDir); @@ -420,7 +461,7 @@ async function getAheadBehind( } } -async function getStatusLines($: Shell, repoDir: string): Promise { +export async function getStatusLines($: Shell, repoDir: string): Promise { try { const output = await $`git -C ${repoDir} status --porcelain`.quiet().text(); return output diff --git a/src/sync/service.test.ts b/src/sync/service.test.ts index 5d12cb9..c81651f 100644 --- a/src/sync/service.test.ts +++ b/src/sync/service.test.ts @@ -294,6 +294,70 @@ describe('explicit Git remote service flow', () => { }); }, 30_000); + it('reports drift in status and supports dry runs for pull and push', async () => { + await withIsolatedEnvironment(async (root) => { + const testShell = createTestShell(); + const remotePath = path.join(root, 'sync-remote.git'); + await testShell`git init --bare ${remotePath}`.quiet(); + const remoteHead = async (): Promise => + (await testShell`git --git-dir ${remotePath} rev-parse main`.text()).trim(); + + useIsolatedHome(path.join(root, 'machine-a')); + const machineALocations = resolveSyncLocations(); + await fs.mkdir(machineALocations.configRoot, { recursive: true }); + const machineAConfig = path.join(machineALocations.configRoot, 'opencode.json'); + await fs.writeFile(machineAConfig, '{"theme":"one"}\n', 'utf8'); + const machineAService = createSyncService({ client: createClient(), $: testShell }); + await machineAService.init({ repo: remotePath, branch: 'main' }); + + useIsolatedHome(path.join(root, 'machine-b')); + const machineBLocations = resolveSyncLocations(); + const machineBConfig = path.join(machineBLocations.configRoot, 'opencode.json'); + const machineBService = createSyncService({ client: createClient(), $: testShell }); + await machineBService.link({ repo: remotePath, branch: 'main' }); + + const inSync = await machineBService.status(); + expect(inSync).toContain('Local changes: none'); + expect(inSync).toContain('Remote: up to date'); + + await fs.writeFile(machineBConfig, '{"theme":"two"}\n', 'utf8'); + const drifted = await machineBService.status(); + expect(drifted).toContain('Local changes: 1 file(s) differ'); + expect(drifted).toContain('Working tree: clean'); + + const headBeforeDryRun = await remoteHead(); + const pushDryRun = await machineBService.push({ dryRun: true }); + expect(pushDryRun).toContain('Dry run: a push would commit these changes'); + expect(pushDryRun).toContain('update config/opencode.json'); + expect(await remoteHead()).toBe(headBeforeDryRun); + await expect(machineBService.status()).resolves.toContain('Working tree: clean'); + await expect(fs.readFile(machineBConfig, 'utf8')).resolves.toContain('two'); + + const pushed = await machineBService.push(); + expect(pushed).toContain('Pushed changes:'); + expect(pushed).toContain('1 file: 1 updated'); + expect(await remoteHead()).not.toBe(headBeforeDryRun); + await expect(machineBService.push({ dryRun: true })).resolves.toContain( + 'a push would change nothing' + ); + + useIsolatedHome(path.join(root, 'machine-a')); + await expect(machineAService.status()).resolves.toContain( + 'Remote: 1 commit(s) not yet pulled' + ); + const pullDryRun = await machineAService.pull({ dryRun: true }); + expect(pullDryRun).toContain('a pull would apply 1 commit'); + expect(pullDryRun).toContain('update config/opencode.json'); + await expect(fs.readFile(machineAConfig, 'utf8')).resolves.toContain('one'); + + const pulled = await machineAService.pull(); + expect(pulled).toContain('Remote config applied'); + expect(pulled).toContain('1 file: 1 updated'); + await expect(fs.readFile(machineAConfig, 'utf8')).resolves.toContain('two'); + await expect(machineAService.pull({ dryRun: true })).resolves.toContain('already up to date'); + }); + }, 60_000); + it('fails closed with recovery instructions for an oversized unpushed session commit', async () => { await withIsolatedEnvironment(async (root) => { const testShell = createTestShell(); diff --git a/src/sync/service.ts b/src/sync/service.ts index ba27d7a..d6c040c 100644 --- a/src/sync/service.ts +++ b/src/sync/service.ts @@ -28,6 +28,7 @@ import { SyncCommandError, SyncConfigMissingError } from './errors.js'; import type { SyncLockInfo } from './lock.js'; import { withSyncLock } from './lock.js'; import { buildSyncPlan, resolveRepoRoot, resolveSyncLocations } from './paths.js'; +import { previewLocalChanges, summarizeChanges } from './preview.js'; import { commitAll, ensureRepoCloned, @@ -36,10 +37,12 @@ import { findSyncRepo, getAuthenticatedUser, getRepoStatus, + getStatusLines, hasAnyRemoteBranches, hasLocalChanges, hasRemoteBranch, inspectOversizedUnpushedHistory, + inspectRemoteDrift, isExplicitGitRemote, isGitHubRepoConfig, isRepoCloned, @@ -99,14 +102,19 @@ interface LinkOptions { acknowledgePrivateRemote?: boolean; } +export interface DryRunOptions { + /** Report what would change without applying or committing anything. */ + dryRun?: boolean; +} + export interface SyncService { startupSync: () => Promise; handleEvent: (_event: unknown) => Promise; status: () => Promise; init: (_options: InitOptions) => Promise; link: (_options: LinkOptions) => Promise; - pull: () => Promise; - push: () => Promise; + pull: (_options?: DryRunOptions) => Promise; + push: (_options?: DryRunOptions) => Promise; secretsPull: () => Promise; secretsPush: () => Promise; secretsStatus: () => Promise; @@ -723,6 +731,20 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { changesLabel = `${repoStatus.length} pending`; } } + let localChangesLabel = 'unknown (repo not cloned)'; + let remoteLabel = 'unknown (repo not cloned)'; + if (cloned) { + const driftLines = await describeDrift({ + $: ctx.$, + config, + locations, + repoRoot, + branch, + clean: repoStatus.length === 0, + }); + localChangesLabel = driftLines.local; + remoteLabel = driftLines.remote; + } const statusLines = [ `Repo: ${repoIdentifier}`, `Branch: ${branch}`, @@ -740,6 +762,8 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { `Last pull: ${lastPull}`, `Last push: ${lastPush}`, `Working tree: ${changesLabel}`, + `Local changes: ${localChangesLabel}`, + `Remote: ${remoteLabel}`, ]; if (tursoStatusLine) { statusLines.push(tursoStatusLine); @@ -977,7 +1001,7 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { await showToast(ctx.client, 'Config synced. Restart opencode to apply.', 'info'); return lines.join('\n'); }), - pull: () => + pull: (options?: DryRunOptions) => runExclusive(async () => { const config = await getConfigOrThrow(locations); const repoRoot = resolveRepoRoot(config, locations); @@ -994,6 +1018,11 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { ); } + if (options?.dryRun) { + return await describePullDryRun(ctx.$, repoRoot, branch); + } + + const headBeforePull = await readHead(ctx.$, repoRoot); const update = await fetchAndFastForward(ctx.$, repoRoot, branch); if (!update.updated) { const plan = buildSyncPlan(config, locations, repoRoot); @@ -1032,15 +1061,14 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { ensureTursoSyncLoop(config); await showToast(ctx.client, 'Config updated. Restart opencode to apply.', 'info'); - if (tursoSummary) { - return [ - 'Remote config applied. Restart opencode to use new settings.', - tursoSummary, - ].join('\n'); - } - return 'Remote config applied. Restart opencode to use new settings.'; + const appliedChanges = await describeAppliedChanges(ctx.$, repoRoot, headBeforePull); + return [ + 'Remote config applied. Restart opencode to use new settings.', + ...appliedChanges, + ...(tursoSummary ? [tursoSummary] : []), + ].join('\n'); }), - push: () => + push: (options?: DryRunOptions) => runExclusive(async () => { const config = await getConfigOrThrow(locations); const repoRoot = resolveRepoRoot(config, locations); @@ -1057,6 +1085,17 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { } const overrides = await loadOverrides(locations); + if (options?.dryRun) { + return await describePushDryRun({ + $: ctx.$, + config, + locations, + repoRoot, + branch, + overrides, + }); + } + const plan = buildSyncPlan(config, locations, repoRoot); await syncLocalToRepo(plan, overrides, { overridesPath: locations.overridesPath, @@ -1092,6 +1131,7 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { } } + const pushedChanges = summarizeChanges(await getStatusLines(ctx.$, repoRoot)); const message = await generateCommitMessage( { client: ctx.client, $: ctx.$, ai: ctx.ai }, repoRoot @@ -1115,16 +1155,20 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { ensureTursoSyncLoop(config); if (secretsFailure) { - const lines = [`Pushed changes: ${message}. Secrets push failed: ${secretsFailure}`]; + const lines = [ + `Pushed changes: ${message}. Secrets push failed: ${secretsFailure}`, + ...pushedChanges, + ]; if (tursoSummary) { lines.push(tursoSummary); } return lines.join('\n'); } - if (tursoSummary) { - return [`Pushed changes: ${message}`, tursoSummary].join('\n'); - } - return `Pushed changes: ${message}`; + return [ + `Pushed changes: ${message}`, + ...pushedChanges, + ...(tursoSummary ? [tursoSummary] : []), + ].join('\n'); }), secretsPull: () => runExclusive(() => @@ -1419,6 +1463,107 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { }; } +async function readHead($: Shell, repoRoot: string): Promise { + try { + return (await $`git -C ${repoRoot} rev-parse HEAD`.quiet().text()).trim(); + } catch { + return null; + } +} + +async function describeAppliedChanges( + $: Shell, + repoRoot: string, + headBefore: string | null +): Promise { + if (!headBefore) return []; + try { + const output = await $`git -C ${repoRoot} diff --name-status ${headBefore} HEAD`.quiet().text(); + return summarizeChanges(output.split('\n')); + } catch { + return []; + } +} + +async function describePullDryRun($: Shell, repoRoot: string, branch: string): Promise { + const drift = await inspectRemoteDrift($, repoRoot, branch); + if (!drift) return 'Dry run: could not reach the remote, nothing was changed.'; + if (drift.behind === 0) { + return 'Dry run: already up to date, a pull would change nothing.'; + } + const commits = drift.behind === 1 ? '1 commit' : `${drift.behind} commits`; + return [ + `Dry run: a pull would apply ${commits} from the remote. Nothing was changed.`, + 'Paths below are repository paths.', + ...summarizeChanges(drift.changes), + ].join('\n'); +} + +async function describePushDryRun(input: { + $: Shell; + config: NormalizedSyncConfig; + locations: ReturnType; + repoRoot: string; + branch: string; + overrides: Record | null; +}): Promise { + const { $, config, locations, repoRoot, branch, overrides } = input; + const changes = await previewLocalChanges($, config, locations, repoRoot, overrides); + if (!changes) return 'Dry run: could not compute local changes, nothing was changed.'; + + const drift = await inspectRemoteDrift($, repoRoot, branch); + const lines = + changes.length === 0 + ? ['Dry run: a push would change nothing in the config repo.'] + : [ + 'Dry run: a push would commit these changes. Nothing was changed.', + ...summarizeChanges(changes), + ]; + if (drift && drift.behind > 0) { + lines.push( + `Warning: the remote has ${drift.behind} newer commit(s). Pull first, or a push will be rejected.` + ); + } + lines.push('Session and secret files are not compared.'); + return lines.join('\n'); +} + +async function describeDrift(input: { + $: Shell; + config: NormalizedSyncConfig; + locations: ReturnType; + repoRoot: string; + branch: string; + clean: boolean; +}): Promise<{ local: string; remote: string }> { + const { $, config, locations, repoRoot, branch, clean } = input; + let local = 'unknown (sync repo has pending changes)'; + if (clean) { + const overrides = await loadOverrides(locations); + const changes = await previewLocalChanges($, config, locations, repoRoot, overrides); + if (!changes) { + local = 'unknown (could not compare)'; + } else if (changes.length === 0) { + local = 'none (local config matches the repo)'; + } else { + local = `${changes.length} file(s) differ from the repo, use push with dryRun to list them`; + } + } + + const drift = await inspectRemoteDrift($, repoRoot, branch); + let remote = 'unreachable'; + if (drift) { + if (drift.behind > 0) { + remote = `${drift.behind} commit(s) not yet pulled, use pull with dryRun to list them`; + } else if (drift.ahead > 0) { + remote = `${drift.ahead} local commit(s) not yet pushed`; + } else { + remote = 'up to date'; + } + } + return { local, remote }; +} + function assertValidSecretsBackend(config: NormalizedSyncConfig): void { const resolution = resolveSecretsBackendConfig(config); if (resolution.state === 'invalid') {