Skip to content

The agent that grows with you

fix(update): a conflicted autostash is owed to the user, never a plain success

Teknium630b1bce801a
diff --git a/apps/desktop/e2e/update/build-fail.spec.ts b/apps/desktop/e2e/update/build-fail.spec.ts
index 2db60bdf629..f7aa698a72e 100644
--- a/apps/desktop/e2e/update/build-fail.spec.ts
+++ b/apps/desktop/e2e/update/build-fail.spec.ts
@@ -4,10 +4,15 @@
* #124040: the Desktop build failed inside the update takeover's completion
* stage and the failure was swallowed / kept looping instead of reaching the
* user. Here upstream main carries a Desktop source file that does not
- * compile; the user clicks "Update now". The update must end with the app
- * telling the user the update FAILED (the relaunched app's result dialog is
- * logged as `[updates] detached update FAILED`), never "finished OK", and the
- * updater must not be left running.
+ * compile; the user clicks "Update now".
+ *
+ * The build runs after the code committed, so under contract C3 the update
+ * succeeds with an owed follow-up: Hermes IS on the new code and only this
+ * app was not rebuilt. The relaunched (old-build) app must say exactly that
+ * and what to do — the action-required dialog, logged as `[updates] detached
+ * update finished with manual action` — never "finished OK" (a silent stale
+ * app) and never "FAILED / still on the previous version" (false: the code
+ * moved). The updater must not be left running.
*/
import * as path from 'node:path'
@@ -32,7 +37,7 @@ import {
waitForUpdateOffer
} from './harness'
-test('a Desktop build failure during Update now is reported to the user as a failed update', async () => {
+test('a Desktop build failure during Update now tells the user the app was not rebuilt and how to fix it', async () => {
test.setTimeout(20 * 60_000)
const session = await startInstallSession()
const { facts, env } = session
@@ -52,7 +57,7 @@ test('a Desktop build failure during Update now is reported to the user as a fai
await clickUpdateNowAndExpectHandoff(launched, facts)
})
- await test.step('the failed build reaches the user as a failed update', async () => {
+ await test.step('the failed build reaches the user as an app that still needs rebuilding', async () => {
await waitFor(
'the relaunched app to report the update outcome',
() => /\[updates\] detached update (finished|FAILED)/.test(desktopLog(facts)),
@@ -64,8 +69,15 @@ test('a Desktop build failure during Update now is reported to the user as a fai
.filter(line => /\[updates\] detached update/.test(line))
.join('\n')
- expect(outcome, `the update is reported as FAILED, not finished\n${explain()}`).toMatch(/detached update FAILED/)
+ expect(outcome, `the owed rebuild reaches the user as an action, not a silent OK\n${explain()}`).toMatch(
+ /detached update finished with manual action/
+ )
+ expect(outcome, 'the user is told the Desktop app could not be rebuilt and how to rebuild it').toMatch(
+ /Desktop app could not be rebuilt.*hermes desktop --force-build/
+ )
expect(outcome).not.toMatch(/detached update finished OK/)
+ // The code committed: "FAILED / still on the previous version" would be false.
+ expect(outcome).not.toMatch(/detached update FAILED|previous version/)
// The relaunched app reports the result while posix.sh is still inside launch_app's 1.5 s
// acceptance window, so the updater gets a bounded moment to exit instead of none.
await expect
@@ -77,10 +89,8 @@ test('a Desktop build failure during Update now is reported to the user as a fai
{ timeout: 30_000, message: 'no updater is left running after the failure' }
)
.toEqual([])
- // What the user is left on: record it for triage (the checkout moved; the app bundle did not).
- test
- .info()
- .annotations.push({ type: 'checkout-after-failure', description: git(facts.checkout, 'rev-parse', 'HEAD') })
+ // The checkout moved (that is why it is not "previous version"); the app bundle did not.
+ expect(git(facts.checkout, 'rev-parse', 'HEAD'), 'the code update committed').toBe(target)
})
} finally {
await session.close()
diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.py
index 3cb353f7b5a..3080b3e81ac 100644
--- a/hermes_cli/update_cmd_maint.py
+++ b/hermes_cli/update_cmd_maint.py
@@ -1073,7 +1073,9 @@ def _run_post_update_maintenance(
with _best_effort('Post-update notices failed: %s'):
_print_post_update_notices_and_self_heals()
- if not update_complete:
+ # A non-✓ completion message (parked local changes) withholds success on its own; only a
+ # ✓ message that still came back False is the SQLite verdict.
+ if not update_complete and (completion_message or "✓").startswith("✓"):
record_followup("sqlite_runtime", "the selected Python links an unsafe SQLite runtime",
retry="run the installer again")
return update_complete
diff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.py
index 91325ce8975..d71216038b4 100644
--- a/hermes_cli/update_completion.py
+++ b/hermes_cli/update_completion.py
@@ -158,6 +158,26 @@ def _running_record(request: dict) -> dict | None:
return None
+def _owed_user_action(request: dict) -> str | None:
+ """The unsettled-autostash notice (#122557) when this run parked the user's local changes.
+
+ ``_complete_source_update`` hands it over as the completion message, and a completion message
+ that is not a ``✓`` line is never a success (``_print_verified_update_completion``).
+ """
+ message = request.get("completion_message") or ""
+ return message if message and not message.startswith("✓") else None
+
+
+def _record_owed_user_action(request: dict) -> bool:
+ """Land the parked local changes on the receipt; True when nothing is owed to the user."""
+ from hermes_cli.update_receipt import record_user_action
+
+ notice = _owed_user_action(request)
+ if notice:
+ record_user_action("local_changes", notice)
+ return notice is None
+
+
def _settle_after_commit(request: dict, result_path: Path, step: str, reason: str) -> int:
"""The tree already moved, so a failure here is owed work, never a failed update (C3, A6).
@@ -180,6 +200,8 @@ def _settle_after_commit(request: dict, result_path: Path, step: str, reason: st
update_receipt.record_stage("deps" if step == "dependencies" else "build", "failed")
update_receipt.record_followup(step, reason, retry="dependencies not installed yet — the next launch retries"
if step == "dependencies" else "the next launch or `hermes update` retries it")
+ if not _record_owed_user_action(request):
+ print(_owed_user_action(request)) # the completion child that would print it never ran
update_receipt.finalize_pending_update_receipt(0, f"{step} owed after the code was updated")
receipt = _read_terminal_receipt(request)
code = 0 if receipt is not None and receipt.get("outcome") == "success" else 1
@@ -229,12 +251,14 @@ def _prepare(request: dict, request_path: Path, result_path: Path) -> int:
return code
-def _complete_selected(request: dict) -> None:
- """Everything after the commit point. Nothing here fails the update (contract C3).
+def _complete_selected(request: dict) -> bool:
+ """Everything after the commit point. No step failure fails the update (contract C3).
Each step is independent; a failed one prints ``⚠``, lands on the receipt as a follow-up
and keeps its own obligation armed (``source-completion-pending`` for the tail, the fleet
restart obligation for gateways), so the next launch or ``hermes update`` retries it.
+ Returns False only when the user's local changes were left parked in the stash: nothing
+ retries that, so the run is ``partial`` and exits 1 (#122557), never "Update complete".
"""
from hermes_cli import main, update_cmd, update_cmd_config
from hermes_cli.source_completion import complete_source_checkout
@@ -243,6 +267,7 @@ def _complete_selected(request: dict) -> None:
root = Path(request["source"])
main.PROJECT_ROOT = root
+ complete = _record_owed_user_action(request)
update_cmd_config._LAST_SIBLING_SNAPSHOTS = request["sibling_snapshots"]
plan_data = request["plan"]
plan = None if plan_data is None else UpdatePlan(**{
@@ -269,14 +294,15 @@ def _complete_selected(request: dict) -> None:
from hermes_cli.venv_sync import clear_completion
clear_completion(root)
# systemctl's KillMode=mixed fallback can kill this whole cgroup. Publish the
- # gateway watcher's status BEFORE that operation: the code is committed, so it is 0.
+ # gateway watcher's status BEFORE that operation: the code is committed, so it is 0 unless
+ # the user's own changes are still parked.
if request["gateway_mode"]:
- update_cmd._write_gateway_update_exit_code(True)
+ update_cmd._write_gateway_update_exit_code(complete)
if request.get("no_gateway_restart", False):
record_skip("gateway_restart", "--no-gateway-restart: deferred, marker kept")
record_stage("restart", "skipped")
print("→ Gateway restart deferred (--no-gateway-restart); restart gateways separately.")
- return
+ return complete
skip = update_cmd._fleet_restart_skip_reason(plan)
if skip and update_cmd._pending_fleet_restart_needed():
# A host already stamped "restarted" for this SHA whose fleet is still off the checkout
@@ -287,12 +313,13 @@ def _complete_selected(request: dict) -> None:
record_skip("gateway_restart", skip)
record_stage("restart", "skipped")
print(f" ✓ Gateway restart skipped: {skip}.")
- return
+ return complete
restart = update_cmd._restart_gateway_fleet_after_update(plan, request["gateway_mode"])
record_stage("restart", "failed" if getattr(restart, "incomplete", False) else "success")
update_cmd._resume_windows_gateways_and_merge_outcome(restart, request["windows_resume"], request["gateway_mode"])
update_cmd._verify_fleet_after_update(
restart, _pre_update_plan=plan, _windows_gateway_resume=request["windows_resume"], update_complete=True)
+ return complete
class _ForwardedOutput:
@@ -317,7 +344,8 @@ def _finish(request: dict, result_path: Path) -> int:
update_receipt.record_stage("deps", "success") # only a completed PM preparation reaches --prepared
code, reason = 0, "source update completion"
try:
- _complete_selected(request)
+ if not _complete_selected(request):
+ code, reason = 1, "local changes left in the stash; re-apply them by hand"
except KeyboardInterrupt:
# An operator interrupt is not a step failure, and the code already moved: the run is
# ``interrupted`` (never "failed"), and the armed obligations finish the tail.
diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.py
index 1e5e1a3db40..16c11f7c3d3 100644
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@ -188,6 +188,8 @@ class UpdateReceipt:
self.data["gateway_restart"] = result
def finalize(self, outcome: str) -> None:
+ if outcome == "success" and self.data.get("user_action"):
+ outcome = "partial" # committed, but the user still has to act (record_user_action)
self.data["outcome"] = outcome
self.data["finished_at"] = _utc_now_iso()
self.data["post_update"] = _code_identity(refresh=True)
@@ -332,6 +334,16 @@ def record_followup(step: str, reason: str, *, retry: str = "the next launch or
_persist_running(current.data)
+def record_user_action(step: str, reason: str) -> None:
+ """The code committed, but something only the user can do is still owed. Never raises.
+
+ Unlike a follow-up nothing retries it (a stash whose restore conflicted stays parked until the
+ user re-applies it), so the run can never be a plain success: it finalizes ``partial`` and
+ ``hermes update`` exits 1, as #122557 established for an unrestored autostash.
+ """
+ _record("fact", f"update user action {step}", "user_action", {"step": step, "reason": " ".join(str(reason).split())[:500]})
+
+
def amend_terminal_followup(update_id: str, step: str, reason: str) -> None:
"""A follow-up that failed after the run's receipt was finalized lands on that receipt. Never raises."""
with suppress(Exception):
@@ -557,7 +569,8 @@ def finalize_pending_update_receipt(exit_code: Optional[int] = None, stop_reason
``hermes update`` has many early ``sys.exit`` paths (preflight refusals, venv-holder refusal,
fetch failure) predating the inner finalize calls; finalizing here means refused/failed runs —
where a receipt matters most — leave a record. Exit 0/None → ``success``, exit 2 → ``refused``
- (preflight convention), else → ``failed``.
+ (preflight convention), else → ``failed`` (``partial`` when the run committed and only owes a
+ user action, see ``record_user_action``).
No-op when no receipt is open (the inner paths already finalized — exactly-once via the popped
per-context receipt) or when recording was never started. See #91283.
@@ -565,7 +578,8 @@ def finalize_pending_update_receipt(exit_code: Optional[int] = None, stop_reason
current = _current.get()
if current is None:
return None
- outcome = "success" if exit_code in (0, None) else "refused" if exit_code == 2 else "failed"
+ outcome = ("success" if exit_code in (0, None) else "refused" if exit_code == 2
+ else "partial" if current.data.get("user_action") else "failed")
if exit_code is not None:
with suppress(Exception):
clone = copy.copy(current)
diff --git a/scripts/desktop-update/posix.sh b/scripts/desktop-update/posix.sh
index b1c86d26ed7..84e15ea6335 100755
--- a/scripts/desktop-update/posix.sh
+++ b/scripts/desktop-update/posix.sh
@@ -88,7 +88,8 @@ STARTED_AT="$(date +%s)" # the shim's elapsed clock; see serve-ui.py
UI_SERVER_PID="" UI_BROWSER_PID="" UI_PANEL_PID="" UI_PROFILE_DIR="" FINAL_CODE=1
FINAL_MSG="update did not complete"
-DONE_NOTE="" # set when the update succeeded but the app will NOT reopen itself
+DONE_NOTE="" # set when the update succeeded but the user must act (reopen, reinstall, rebuild)
+APP_REBUILD_FAILED=0 # 1 = the code committed but the Desktop app build is an owed follow-up
log() { echo "$(date +%Y-%m-%dT%H:%M:%S%z) $1" | tee -a "$LOG" 2>/dev/null; }
@@ -400,7 +401,9 @@ mac_swap() {
# Transactional swap: stage a full copy, move the old bundle aside, move
# the copy in. Every step checked; a failed final move ROLLS BACK so the
# user always has a launchable app, and the result file tells the truth.
- if [ "$FINAL_CODE" -eq 0 ] && [ -n "$rebuilt" ] && [ -d "$RELAUNCH_TARGET" ] && [ "$rebuilt" != "$RELAUNCH_TARGET" ]; then
+ # A failed rebuild left release/ holding the OLD build: nothing new to install.
+ if [ "$FINAL_CODE" -eq 0 ] && [ "$APP_REBUILD_FAILED" -eq 0 ] && [ -n "$rebuilt" ] \
+ && [ -d "$RELAUNCH_TARGET" ] && [ "$rebuilt" != "$RELAUNCH_TARGET" ]; then
publish_stage "Installing the new app"
rm -rf "$RELAUNCH_TARGET.new" "$RELAUNCH_TARGET.old" 2>/dev/null || true
if ! /usr/bin/ditto "$rebuilt" "$RELAUNCH_TARGET.new"; then
@@ -434,7 +437,7 @@ deliver_outcome() { # the truth-determining half: swap bundles / gate the relaun
else
linux_gate
if [ "$GATE" != "relaunch" ] && [ "$FINAL_CODE" -eq 0 ]; then
- DONE_NOTE="$GATE_MSG"
+ DONE_NOTE="${DONE_NOTE:+$DONE_NOTE }$GATE_MSG"
log "no relaunch ($GATE): $GATE_MSG"
fi
fi
@@ -505,9 +508,10 @@ finish() {
fi
if [ -n "$DONE_NOTE" ]; then
- if [ "$(uname)" = "Darwin" ]; then
+ if [ "$(uname)" = "Darwin" ] || [ "$GATE" = "relaunch" ]; then
# mac DONE_NOTE = swap failed but the PREVIOUS bundle was kept/rolled
- # back — bring it back up; the note still tells the user to re-run.
+ # back, or (any OS) the Desktop rebuild is owed — bring the kept app
+ # back up; the note still tells the user what to do.
# A gated linux outcome (skew/manual) skips the launch BY DESIGN.
if ! launch_app; then
# Even the kept bundle didn't come back: the durable message must
@@ -885,6 +889,15 @@ if [ "$LEGACY_INSTALL" -eq 1 ] && [ "$CODE" -eq 0 ] && printf '%s' "$OUT" | grep
fi
if [ "$CODE" -eq 0 ]; then FINAL_CODE=0 FINAL_MSG="Update complete."
+ # Contract C3: a Desktop build that fails after the code committed is an owed
+ # follow-up (hermes update exits 0 and prints it). The user is on the new
+ # Hermes, but this app was not rebuilt: say so and say how to fix it, never
+ # "finished OK" and never "still on the previous version".
+ if printf '%s' "$OUT" | grep -Eq "Update follow-up 'build' did not finish: .*(desktop app build|Node dependencies)"; then
+ APP_REBUILD_FAILED=1
+ DONE_NOTE="Hermes was updated, but the Desktop app could not be rebuilt, so it still runs its old build. Run hermes desktop --force-build in a terminal to rebuild it; the update log has the build error."
+ log "desktop app build is an owed follow-up of the committed update"
+ fi
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/tests/e2e/core/upgrade/pm/test_stamps_and_doctor.py b/tests/e2e/core/upgrade/pm/test_stamps_and_doctor.py
index 0edc3e26553..8dd99f0b8a2 100644
--- a/tests/e2e/core/upgrade/pm/test_stamps_and_doctor.py
+++ b/tests/e2e/core/upgrade/pm/test_stamps_and_doctor.py
@@ -13,8 +13,10 @@ is not the installer's. Then:
* real drift is caught and healed: a user uninstalls fastapi (the ``web`` extra the dashboard
imports) from the selected environment. ``hermes doctor`` must say so, and ``hermes pm repair``
must bring the dashboard's import back;
-* a dependency update that cannot resolve fails loudly, ``hermes pm status`` reports it as failed,
- and the previous generation stays selected and working.
+* a dependency update that cannot resolve after the tree moved is an owed follow-up (contract C3,
+ A6): ``hermes update`` exits 0 but says loudly that the dependencies are not installed yet, the
+ receipt names the ``dependencies`` follow-up, the source-update tail stays armed for the next
+ launch, and the previous generation stays selected and working.
"""
from __future__ import annotations
@@ -149,20 +151,29 @@ def test_pm_repair_heals_the_drift(drifted):
f"`hermes pm repair` exited 0 but the dashboard still cannot import: {imports}\n" + P.diagnostics(sb, rp))
-def test_failed_dependency_update_is_reported_as_failed(updated):
- """A release whose uv.lock uv rejects: the update must fail loudly, the receipt must say so, and
- the install must keep running on the generation it had."""
+def test_failed_dependency_update_is_an_owed_followup(updated):
+ """A release whose uv.lock uv rejects, synced after the tree moved: the code is committed, so
+ the update exits 0 (A6) but must say loudly that the dependencies are not installed yet, the
+ receipt must name the owed follow-up, the tail must stay armed, and the install must keep
+ running on the generation it had."""
sb = updated["sb"]
before = P.selected_generation(sb)
origin, scratch = updated["origin"], updated["root"]
lock = I.git("show", "main:uv.lock", cwd=origin) + '\n[[package]]\nname = "e2e-broken"\n'
- I.publish_commit(origin, scratch, "release: e2e broken lockfile", {"uv.lock": lock})
+ target = I.publish_commit(origin, scratch, "release: e2e broken lockfile", {"uv.lock": lock})
up = P.update(sb)
receipt = json.loads(P.ok(sb.cli("pm", "status")).stdout)
- assert up.returncode != 0, "`hermes update` exited 0 on a release whose uv.lock uv rejects\n" + P.diagnostics(sb, up)
- assert receipt.get("outcome") not in ("ok", "success"), (
- f"`hermes pm status` reports the failed update as a success: {receipt}\n" + P.diagnostics(sb, up))
- assert P.selected_generation(sb) == before, "a failed update switched the selected generation"
+ assert up.returncode == 0, (
+ "`hermes update` failed although the code committed; a dependency sync after the tree moved "
+ "is an owed follow-up (A6)\n" + P.diagnostics(sb, up))
+ assert I.git("rev-parse", "HEAD", cwd=sb.checkout) == target, "the code update did not land\n" + P.diagnostics(sb, up)
+ assert re.search(r"⚠ Update follow-up 'dependencies' did not finish: .*dependencies not installed yet",
+ up.stdout + up.stderr), "the owed dependency sync is not reported loudly\n" + P.diagnostics(sb, up)
+ assert receipt.get("outcome") == "success" and "dependencies" in [
+ f.get("step") for f in receipt.get("followups") or []], (
+ f"the receipt does not name the owed dependency sync: {receipt}\n" + P.diagnostics(sb, up))
+ assert P.pending_marker(sb).exists(), "the owed source-update tail is not armed for the next launch"
+ assert P.selected_generation(sb) == before, "a failed dependency sync switched the selected generation"
imports = P.managed_imports(sb, "pydantic", "openai")
assert set(imports.values()) == {"ok"}, f"the install no longer works after a failed update: {imports}"
cp = sb.cli("--version")
diff --git a/tests/hermes_cli/test_update_completion_process.py b/tests/hermes_cli/test_update_completion_process.py
index 747d014f41c..c10009a538f 100644
--- a/tests/hermes_cli/test_update_completion_process.py
+++ b/tests/hermes_cli/test_update_completion_process.py
@@ -162,6 +162,7 @@ def transition(tmp_path):
" r = _current.get()\n"
" if r is not None: r.data.setdefault('followups', []).append({'step': step, 'reason': reason})\n"
"def amend_terminal_followup(*args): pass\n"
+ "def record_user_action(*args): pass\n"
"def _receipt_dir():\n"
" return pathlib.Path(os.environ['HERMES_HOME']) / 'logs/update_receipts'\n"
"def finalize_pending_update_receipt(code, reason):\n"
diff --git a/tests/hermes_cli/test_update_post_commit_followups.py b/tests/hermes_cli/test_update_post_commit_followups.py
index c91576436c5..e928f1b75d1 100644
--- a/tests/hermes_cli/test_update_post_commit_followups.py
+++ b/tests/hermes_cli/test_update_post_commit_followups.py
@@ -37,6 +37,21 @@ def test_open_receipt_is_durably_running_and_finalizes_in_place(tmp_path, monkey
assert list((tmp_path / "logs/update_receipts").glob(f"update_*_{final['update_id']}.json")) == run_files
[email protected]("finish", [lambda: update_receipt.finalize_update_receipt("success"),
+ lambda: update_receipt.finalize_pending_update_receipt(1, "local changes parked")])
+def test_parked_local_changes_never_finalize_as_success(tmp_path, monkeypatch, finish):
+ # A follow-up is retried by the next launch; a stash whose restore conflicted is not, so the
+ # committed run must stay partial (#122557) on both the verify path and the boundary net.
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ update_receipt.begin_update_receipt()
+ update_receipt.record_user_action("local_changes", "⚠ hermes update stashed 1 local modification(s)\n Stash ref: abc")
+ finish()
+ final = _latest(tmp_path)
+ assert final["outcome"] == "partial"
+ assert final["user_action"] == {"step": "local_changes",
+ "reason": "⚠ hermes update stashed 1 local modification(s) Stash ref: abc"}
+
+
def test_dead_running_record_is_reported_interrupted_by_the_next_run(tmp_path, monkeypatch, capsys):
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
dead = subprocess.Popen(["true"])