Manipulating documents in agents that bound to input fields are tricky. The XPages runtime isn't really aware what the agent is doing. Quite often you are actually better off converting an agent into a Java bean and call that one. It gives you the opportunity to clean up code and optimize performance. It also removes the performance penalty of loading the agent runtime for an operation. "I want to reuse existing code" is often overrated here...
But you asked... so here we go. The documentation suggest you can use
agent.runWithDocumentContext(document.getDocument(true));
to ensure backend changes are applied. Try that and let us know how it went. I actually would take a slightly different approach and bind the input field to a view variable and write that one only back on the save event. Something like:
<xp:inputText id="inputText1" value="#{viewScope.InMemReturn}"></xp:inputText>
and in your SSJS:
var agent = database.getAgent("test");
var doc = document.getDocument(true);
agent.runWithDocumentContext(doc);
viewScope.InMemReturn = doc.getItemValueString("InMemReturn");
and in a querySave event:
document.getDocument().replaceItemValue("InMemReturn",viewScope.InMemReturn);
Let us know how it goes.