Skip to content

The agent that grows with you

fix(update): hand-offs report a nonzero exit past the commit point as installed with a follow-up

Teknium7a8249f35c53
diff --git a/scripts/desktop-update/posix.sh b/scripts/desktop-update/posix.sh
index caf60052a0e..a913a5b49e7 100755
--- a/scripts/desktop-update/posix.sh
+++ b/scripts/desktop-update/posix.sh
@@ -220,6 +220,14 @@ on_signal() {
return 0
fi
log "SIGNAL: $sig pid=$$ ppid=$PPID pgid=${pgid:-unknown}"
+ if handoff_committed; then
+ # Contract C3: the code is already updated, so the interruption is an owed
+ # follow-up on an ok result, never "the update failed".
+ FINAL_CODE=0
+ DONE_NOTE="Hermes was updated, but the update hand-off was interrupted by $sig before its remaining steps finished. The next launch or hermes update finishes them."
+ add_warning "handoff" "interrupted by $sig after the update was committed"
+ exit 0
+ fi
FINAL_MSG="Update hand-off was interrupted by $sig (pid $$)."
case "$sig" in
HUP) FINAL_CODE=129 ;;
@@ -229,6 +237,36 @@ on_signal() {
esac
exit "$FINAL_CODE"
}
+
+# ── the commit point (contract C3) ──────────────────────────────────────────
+# `hermes update` exits 0 once committed, except an interrupt (130) or a parked
+# autostash (1) after the commit point, and a crash of a committed run. Its
+# receipt says which: the run's own receipt -- matched by the correlation id we
+# hand it, finalized (finished_at set) -- with outcome success | partial (the
+# user still has to act) | interrupted (Ctrl-C after the code moved). A
+# reconciled "interrupted" record keeps finished_at null, so it never matches.
+UPDATE_CORRELATION="${HERMES_UPDATE_CORRELATION_ID:-$RESULT_RUN_ID}"
+UPDATE_COMMITTED=0 RECEIPT_OUTCOME=""
+receipt_json_field() { # file key -> the top-level string value (json.dumps indent=2 layout)
+ sed -n "s/^ \"$2\": \"\([A-Za-z0-9._:+-]*\)\",\{0,1\}\$/\1/p" "$1" 2>/dev/null | head -n 1
+}
+update_committed_after_exit() { # -> 0 iff this run's receipt shows the commit point passed
+ local root="$HERMES_HOME" f outcome
+ # hermes_constants.get_default_hermes_root: a <root>/profiles/<name> home files under <root>
+ [ "$(basename "$(dirname "$root")")" != profiles ] || root="$(dirname "$(dirname "$root")")"
+ f="$root/logs/update_receipts/latest.json"
+ [ -f "$f" ] && [ -n "$UPDATE_CORRELATION" ] || return 1
+ [ "$(receipt_json_field "$f" correlation_id)" = "$UPDATE_CORRELATION" ] || return 1
+ [ -n "$(receipt_json_field "$f" finished_at)" ] || return 1
+ outcome="$(receipt_json_field "$f" outcome)"
+ case "$outcome" in success|partial|interrupted) RECEIPT_OUTCOME="$outcome"; return 0 ;; esac
+ return 1
+}
+handoff_committed() { # -> 0 iff the update itself is committed (whatever happens to us now)
+ [ "$UPDATE_COMMITTED" -eq 0 ] || return 0
+ [ -n "${CODE:-}" ] || return 1
+ [ "$CODE" -eq 0 ] || { [ "$CODE" -ne 2 ] && update_committed_after_exit; }
+}
trap 'on_signal HUP' HUP
trap 'on_signal INT' INT
trap 'on_signal QUIT' QUIT
@@ -1065,6 +1103,9 @@ export PYTHONUNBUFFERED=1
export HERMES_UPDATE_STATUS_FILE="$STATUS"
# `hermes update` runs under OUR marker claim (contract C1 rule 4/6).
export HERMES_UPDATE_HANDOFF_PID="$$"
+# The update's receipt carries this id (update_receipt._launcher_correlation_id),
+# which is how update_committed_after_exit finds THIS run's receipt.
+export HERMES_UPDATE_CORRELATION_ID="$UPDATE_CORRELATION"
# --keep-stash: never re-apply local source edits after the update (they stay
# parked in git stash). Probe --help first: older installed backends don't
# know the flag and argparse would abort with exit 2, which collides with the
@@ -1156,7 +1197,16 @@ if [ "$LEGACY_INSTALL" -eq 1 ] && [ "$CODE" -ne 0 ] && [ "$CODE" -ne 2 ]; then
fi
trap 'on_signal TERM' TERM
-if [ "$CODE" -eq 0 ]; then FINAL_CODE=0 FINAL_MSG="Update complete."
+if [ "$CODE" -eq 0 ]; then FINAL_CODE=0 FINAL_MSG="Update complete." UPDATE_COMMITTED=1
+elif [ "$CODE" -ne 2 ] && update_committed_after_exit; then
+ # Past the commit point: installed, with an owed follow-up (contract C3).
+ FINAL_CODE=0 FINAL_MSG="Update complete." UPDATE_COMMITTED=1
+ case "$RECEIPT_OUTCOME" in
+ partial) DONE_NOTE="Hermes was updated, but one step is left for you: your local source changes may still be parked in git stash. Run hermes update in a terminal for the exact commands." ;;
+ interrupted) DONE_NOTE="Hermes was updated, but its post-update steps were interrupted. The next launch or hermes update finishes them." ;;
+ *) DONE_NOTE="Hermes was updated, but hermes update exited with code $CODE afterwards. Run hermes update in a terminal to finish any remaining steps." ;;
+ esac
+ add_warning "update" "hermes update exited $CODE after the commit point (receipt outcome: $RECEIPT_OUTCOME)"
else
FINAL_CODE="$CODE" FINAL_MSG="Update failed (exit $CODE). Run hermes debug share in a terminal to send a report."
# The bricked-venv class is fixable and must not read as a generic exit 1:
diff --git a/scripts/desktop-update/windows.ps1 b/scripts/desktop-update/windows.ps1
index 288f995c26c..e3cfe2d2c9a 100644
--- a/scripts/desktop-update/windows.ps1
+++ b/scripts/desktop-update/windows.ps1
@@ -1180,6 +1180,29 @@ function Resolve-HermesUpdateOutcome($StepResult) {
return $StepResult
}
+# -- The commit point (contract C3) --------------------------------------------
+# `hermes update` exits 0 once committed, except an interrupt (130) or a parked
+# autostash (1) after the commit point, and a crash of a committed run. Its own
+# receipt says which (same rule as posix.sh::update_committed_after_exit): the
+# run's receipt -- matched by the correlation id handed to it, finalized
+# (finished_at set) -- with outcome success | partial (the user still has to
+# act) | interrupted (Ctrl-C after the code moved). A reconciled "interrupted"
+# record keeps finished_at null, so it never matches.
+function Get-CommittedReceiptOutcome {
+ $root = $HermesHome
+ # hermes_constants.get_default_hermes_root: a <root>\profiles\<name> home files under <root>
+ $parent = Split-Path -Parent $root
+ if ($parent -and (Split-Path -Leaf $parent) -eq 'profiles') { $root = Split-Path -Parent $parent }
+ $path = Join-Path $root 'logs\update_receipts\latest.json'
+ $receipt = $null
+ try { $receipt = [System.IO.File]::ReadAllText($path, [System.Text.Encoding]::UTF8) | ConvertFrom-Json } catch { return $null }
+ if ($null -eq $receipt -or -not $script:UpdateCorrelation) { return $null }
+ if ([string]$receipt.correlation_id -cne $script:UpdateCorrelation -or -not $receipt.finished_at) { return $null }
+ $outcome = [string]$receipt.outcome
+ if ($outcome -cin @('success', 'partial', 'interrupted')) { return $outcome }
+ return $null
+}
+
function Set-InstallRootCurrentDirectory([string]$Root) {
$resolved = [System.IO.Path]::GetFullPath($Root)
[Environment]::CurrentDirectory = $resolved
@@ -1554,6 +1577,10 @@ try {
} catch {
Write-HandoffLog "could not probe update --help; running without --keep-stash"
}
+ # The update's receipt carries this id (update_receipt._launcher_correlation_id):
+ # Get-CommittedReceiptOutcome finds THIS run's receipt by it.
+ $script:UpdateCorrelation = if ($env:HERMES_UPDATE_CORRELATION_ID) { $env:HERMES_UPDATE_CORRELATION_ID } else { $script:ResultRunId }
+ $env:HERMES_UPDATE_CORRELATION_ID = $script:UpdateCorrelation
Write-HandoffLog ("running: python " + ($updateArgs -join " "))
Publish-UiProgress "Updating code and dependencies"
$res = Invoke-HermesStep $pythonExe $updateArgs "update"
@@ -1575,7 +1602,9 @@ try {
$res = Resolve-HermesUpdateOutcome $res
}
- if ($res.Code -ne 0) {
+ $committedAfterExit = $null
+ if ($res.Code -ne 0 -and $res.Code -ne 2) { $committedAfterExit = Get-CommittedReceiptOutcome }
+ if ($res.Code -ne 0 -and -not $committedAfterExit) {
$finalCode = $res.Code
$finalMsg = "Update failed (exit $($res.Code)). Run `hermes debug share` in a terminal to send a report."
exit $finalCode
@@ -1590,6 +1619,15 @@ try {
if ($script:UpdateInterrupted) {
Add-Followup "post-update steps (gateway resume) were interrupted; run hermes update again" "its post-update steps (gateway resume) were interrupted. Run 'hermes update' again to finish them." -Manual
}
+ if ($committedAfterExit) {
+ # Past the commit point with a nonzero exit: installed, with an owed follow-up.
+ $sentence = switch ($committedAfterExit) {
+ 'partial' { "one step is left for you: your local source changes may still be parked in git stash. Run 'hermes update' in a terminal for the exact commands." }
+ 'interrupted' { "its post-update steps were interrupted. The next launch or 'hermes update' finishes them." }
+ default { "'hermes update' exited with code $($res.Code) afterwards. Run 'hermes update' in a terminal to finish any remaining steps." }
+ }
+ Add-Followup "update: hermes update exited $($res.Code) after the commit point (receipt outcome: $committedAfterExit)" $sentence -Manual
+ }
# Pre-PM updates reported a successful exit with a failed build warning.
# Keep that historical transition here only; current failures propagate.
diff --git a/tests/scripts/desktop_update/test_desktop_update_posix_marker.py b/tests/scripts/desktop_update/test_desktop_update_posix_marker.py
index 5f39d75ce00..5f065b09066 100644
--- a/tests/scripts/desktop_update/test_desktop_update_posix_marker.py
+++ b/tests/scripts/desktop_update/test_desktop_update_posix_marker.py
@@ -39,6 +39,17 @@ if completion and sys.argv[1:2] == ['update']: # a survivor that keeps the chec
os.environ['HANDOFF_CHECKOUT_LOCK'], completion], start_new_session=True)
while not Path(completion + '.ready').exists():
__import__('time').sleep(0.02)
+receipt = os.environ.get('HANDOFF_RECEIPT') # outcome[,correlation][,unfinished]: this run's receipt
+if receipt and sys.argv[1:2] == ['update']:
+ import json
+ outcome, correlation, finished = (receipt.split(',') + ['', ''])[:3]
+ path = Path(os.environ['HERMES_HOME']) / 'logs' / 'update_receipts' / 'latest.json'
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps({
+ 'stages': [{'name': 'apply', 'outcome': 'failed'}], # nested keys are never read
+ 'correlation_id': correlation or os.environ.get('HERMES_UPDATE_CORRELATION_ID'),
+ 'outcome': outcome, 'finished_at': None if finished else '2026-10-05T12:00:00.000001+00:00',
+ }, indent=2) + '\\n', encoding='utf-8')
hold = os.environ.get('HANDOFF_HOLD')
if hold: # an update still running: report the pid, then wait to be released
Path(hold + '.pid').write_text(str(os.getpid()), encoding='utf-8')
@@ -230,6 +241,66 @@ def test_committed_update_with_failed_followup_is_ok_with_warnings(tmp_path):
assert not (home / ".hermes-update-in-progress").exists()
[email protected](("outcome", "code"), [("interrupted", "130"), ("partial", "1"), ("success", "1")])
+def test_nonzero_exit_after_the_commit_point_is_installed_with_a_followup(tmp_path, outcome, code):
+ """Contract C3: `hermes update` exits 130 (Ctrl-C after the code moved) or 1 (a parked
+ autostash) AFTER its commit point. Its own receipt says so; the result must report the
+ update installed with an owed follow-up, never ok:false / "still on the previous version"."""
+ home, install = _install(tmp_path)
+
+ result = _run(tmp_path, home, install, HANDOFF_EXIT=code, HANDOFF_RECEIPT=outcome)
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ receipt = json.loads((home / ".hermes-update-result.json").read_text(encoding="utf-8-sig"))
+ assert (receipt["ok"], receipt["exit_code"], receipt["manual"]) == (True, 0, True), receipt
+ assert receipt["message"].startswith("Hermes was updated, but"), receipt
+ assert [w.split(":")[0] for w in receipt["warnings"]] == ["update"], receipt
+ assert f"exited {code} after the commit point" in receipt["warnings"][0]
+
+
+def test_handoff_interrupted_while_a_committed_update_finishes_is_still_installed(tmp_path):
+ """Ctrl-C reaches the hand-off too: it waits for the update child, whose receipt says it
+ passed the commit point. The hand-off's own interruption is then an owed follow-up."""
+ home, install = _install(tmp_path)
+ hold = tmp_path / "release-update"
+ env = {**os.environ, "HOME": str(tmp_path), "TMPDIR": str(tmp_path), "HERMES_HOME": str(home),
+ "HANDOFF_CAPTURE": str(tmp_path / "calls.txt"), "HERMES_RUNTIME_DIR": str(tmp_path / "store"),
+ "HERMES_UPDATE_SHIM_GRACE_SECONDS": "0", "HANDOFF_HOLD": str(hold), "HANDOFF_EXIT": "130",
+ "HANDOFF_RECEIPT": "interrupted"}
+ for key in ("PYTHONPATH", "PYTHONHOME", "HERMES_UPDATE_STARTED_AT"):
+ env.pop(key, None)
+ script = subprocess.Popen(["bash", str(POSIX), "--daemonized", "--no-ui", "--install-root", str(install)],
+ env=env, cwd=tmp_path, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ try:
+ deadline = time.monotonic() + 60
+ while not Path(str(hold) + ".pid").exists():
+ assert time.monotonic() < deadline and script.poll() is None, "update child never started"
+ time.sleep(0.01)
+ script.send_signal(2) # SIGINT, deferred while the update child runs
+ time.sleep(0.3)
+ hold.touch()
+ assert script.wait(timeout=60) == 0
+ finally:
+ hold.touch()
+ if script.poll() is None:
+ script.kill(); script.wait()
+ outcome = json.loads((home / ".hermes-update-result.json").read_text(encoding="utf-8-sig"))
+ assert (outcome["ok"], outcome["exit_code"], outcome["manual"]) == (True, 0, True), outcome
+ assert any(w.startswith("handoff: interrupted by INT") for w in outcome["warnings"]), outcome
+
+
[email protected]("receipt", ["", "failed", "interrupted,another-run", "interrupted,,unfinished"],
+ ids=["no-receipt", "failed", "another-runs-receipt", "reconciled-not-finalized"])
+def test_nonzero_exit_without_this_runs_committed_receipt_still_fails(tmp_path, receipt):
+ home, install = _install(tmp_path)
+
+ result = _run(tmp_path, home, install, HANDOFF_EXIT="130", HANDOFF_RECEIPT=receipt)
+
+ assert result.returncode == 130, result.stdout + result.stderr
+ outcome = json.loads((home / ".hermes-update-result.json").read_text(encoding="utf-8-sig"))
+ assert (outcome["ok"], outcome["exit_code"]) == (False, 130), outcome
+
+
def test_interrupted_app_swap_is_rolled_back_at_the_next_run(tmp_path):
home, install = _install(tmp_path)
app = tmp_path / "Applications" / "Hermes.app"
diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_commit_outcome.py b/tests/scripts/desktop_update/test_desktop_update_windows_commit_outcome.py
index d8fed633549..02cde63ebd0 100644
--- a/tests/scripts/desktop_update/test_desktop_update_windows_commit_outcome.py
+++ b/tests/scripts/desktop_update/test_desktop_update_windows_commit_outcome.py
@@ -58,6 +58,15 @@ def main():
if os.environ.get('HANDOFF_HANG'):
print(os.environ['HANDOFF_HANG'], flush=True)
time.sleep(300)
+ receipt = os.environ.get('HANDOFF_RECEIPT') # this run's finalized receipt: outcome[,correlation]
+ if receipt:
+ outcome, correlation = (receipt.split(',') + [''])[:2]
+ path = Path(os.environ['HERMES_HOME']) / 'logs' / 'update_receipts' / 'latest.json'
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps({'correlation_id': correlation or os.environ.get('HERMES_UPDATE_CORRELATION_ID'),
+ 'outcome': outcome, 'finished_at': '2026-10-05T12:00:00+00:00'}, indent=2),
+ encoding='utf-8')
+ return int(os.environ.get('HANDOFF_EXIT', '0'))
print('Update complete!', flush=True)
return 0
if __name__ == '__main__':
@@ -124,6 +133,25 @@ def test_a_result_that_cannot_be_published_leaves_no_tmp_file(tmp_path: Path) ->
assert not list(home.glob('.hermes-update-result.json.*.tmp')), list(home.iterdir())
[email protected](('receipt', 'ok'), [('interrupted', True), ('partial', True), ('interrupted,another-run', False),
+ ('failed', False)])
+def test_nonzero_exit_after_the_commit_point_is_installed_with_a_followup(tmp_path: Path, receipt: str, ok: bool) -> None:
+ # Contract C3: `hermes update` exits 130 / 1 AFTER its commit point (Ctrl-C after the code
+ # moved, a parked autostash). Its own receipt (matched by the correlation id) says so: the
+ # result must report the update installed with an owed follow-up, never "update failed".
+ code, out, argv, result, _ = _handoff(tmp_path, HANDOFF_RECEIPT=receipt, HANDOFF_EXIT='130')
+ if ok:
+ assert code == 0, out
+ assert (result['ok'], result['exit_code'], result['manual']) == (True, 0, True), result
+ assert result['message'].startswith('Hermes was updated, but'), result
+ assert [w.split(':')[0] for w in result['warnings']] == ['update'], result
+ assert argv[-1] == ['gateway', 'start', '--all'], argv # the post-commit steps still run
+ else:
+ assert code == 130, out
+ assert (result['ok'], result['exit_code']) == (False, 130), result
+
+
_TIMED_CHECKOUT_HOLDER = """
import msvcrt, os, sys, time
fd = os.open(sys.argv[1], os.O_RDWR | os.O_CREAT | os.O_BINARY, 0o644)