Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<details>
<summary>Manual sync (without slash commands)</summary>

Expand Down
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
6 changes: 4 additions & 2 deletions src/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ export interface SyncToolArgs {
acknowledgePrivateRemote?: boolean;
setupTurso?: boolean;
migrateSessions?: boolean;
dryRun?: boolean;
}

export function buildSyncToolInputSchema(): Record<string, unknown> {
Expand All @@ -176,6 +177,7 @@ export function buildSyncToolInputSchema(): Record<string, unknown> {
extraConfigPaths: { type: 'array', items: { type: 'string' } },
localRepoPath: { type: 'string' },
acknowledgePrivateRemote: { type: 'boolean' },
dryRun: { type: 'boolean' },
setupTurso: { type: 'boolean' },
migrateSessions: { type: 'boolean' },
},
Expand Down Expand Up @@ -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();
Expand Down
38 changes: 38 additions & 0 deletions src/sync/preview.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
127 changes: 127 additions & 0 deletions src/sync/preview.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> = {
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<string, unknown> | null
): Promise<string[] | null> {
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<string, number>();
for (const entry of entries) {
counts.set(entry.action, (counts.get(entry.action) ?? 0) + 1);
}
const past: Record<string, string> = {
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;
}
43 changes: 42 additions & 1 deletion src/sync/repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<RemoteDrift | null> {
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<RepoStatus> {
const branch = await getCurrentBranch($, repoDir);
const changes = await getStatusLines($, repoDir);
Expand Down Expand Up @@ -420,7 +461,7 @@ async function getAheadBehind(
}
}

async function getStatusLines($: Shell, repoDir: string): Promise<string[]> {
export async function getStatusLines($: Shell, repoDir: string): Promise<string[]> {
try {
const output = await $`git -C ${repoDir} status --porcelain`.quiet().text();
return output
Expand Down
64 changes: 64 additions & 0 deletions src/sync/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> =>
(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();
Expand Down
Loading
Loading