@@ -95,6 +95,33 @@ async function resetToFetchedRemoteBranch(
9595 }
9696}
9797
98+ async function getCurrentHead ( sandbox : Sandbox ) : Promise < string > {
99+ const headResult = await exec ( sandbox , "git rev-parse HEAD" , 10000 ) ;
100+ if ( ! headResult . success ) {
101+ throw new Error (
102+ `Failed to inspect current HEAD: ${ commandOutput ( headResult ) } ` ,
103+ ) ;
104+ }
105+
106+ return headResult . stdout . trim ( ) ;
107+ }
108+
109+ async function resetToCommit ( sandbox : Sandbox , commit : string ) : Promise < void > {
110+ const resetResult = await exec ( sandbox , `git reset --hard ${ commit } ` , 10000 ) ;
111+ if ( ! resetResult . success ) {
112+ throw new Error (
113+ `Failed to restore original HEAD after sync failure: ${ commandOutput ( resetResult ) } ` ,
114+ ) ;
115+ }
116+
117+ const cleanResult = await exec ( sandbox , "git clean -fd" , 10000 ) ;
118+ if ( ! cleanResult . success ) {
119+ throw new Error (
120+ `Failed to clean worktree after sync failure: ${ commandOutput ( cleanResult ) } ` ,
121+ ) ;
122+ }
123+ }
124+
98125// ---- public functions ----
99126
100127/**
@@ -343,6 +370,8 @@ export async function syncToRemotePreservingChanges(
343370 return ;
344371 }
345372
373+ const originalHead = await getCurrentHead ( sandbox ) ;
374+
346375 const stashResult = await exec (
347376 sandbox ,
348377 "git stash push --include-untracked -m open-agents-pre-commit-sync" ,
@@ -357,12 +386,21 @@ export async function syncToRemotePreservingChanges(
357386 try {
358387 await resetToFetchedRemoteBranch ( sandbox , branch ) ;
359388 } catch ( error ) {
389+ await resetToCommit ( sandbox , originalHead ) ;
360390 await exec ( sandbox , "git stash pop" , 30000 ) . catch ( ( ) => { } ) ;
361391 throw error ;
362392 }
363393
364394 const popResult = await exec ( sandbox , "git stash pop" , 30000 ) ;
365395 if ( ! popResult . success ) {
396+ await resetToCommit ( sandbox , originalHead ) ;
397+ const restoreResult = await exec ( sandbox , "git stash pop" , 30000 ) ;
398+ if ( ! restoreResult . success ) {
399+ throw new Error (
400+ `Failed to restore local changes after rolling back sync failure: ${ commandOutput ( restoreResult ) } ` ,
401+ ) ;
402+ }
403+
366404 throw new Error (
367405 `Failed to restore local changes after syncing remote branch: ${ commandOutput ( popResult ) } ` ,
368406 ) ;
0 commit comments