153 Commits

Author SHA1 Message Date
Teknium
1733a4a653 fix(desktop-update): flush the hand-off log on every exit, encode it only when it opens
Three follow-ups to the queued hand-off log (review on #145712):

- Sync-HandoffLog encoded the whole pending queue before it knew the file
  would open, so a log held through a long step re-encoded a growing queue
  on every poll. It opens the file first and encodes only once it can write.
- -SelfTestLogConcurrency skipped the -InstallRoot requirement but still
  claimed the update marker, and its early exit never released it, leaving
  update state in HERMES_HOME. It no longer claims the marker; its test now
  requires HERMES_HOME to hold no update state afterwards.
- The bounded exit-time flush ran only in the main update's finally. The
  marker helper ops (reclaim/withdraw/custody) and the early marker.ps1
  load failure exited with their lines still queued. Each now flushes after
  its marker lock is released; reclaim/withdraw keep the flush short
  because Electron bounds the whole helper and already has its verdict.
2026-10-27 15:58:38 -07:00
Teknium
3d304a2816 fix(desktop-update): a hand-off log line that meets another holder waits instead of vanishing
The named mutex serializes Hermes's own writers, but any other process holding
the log at the moment of an append (a scanner on the just-closed file, a reader
opened without write sharing) still failed it, and the empty catch dropped the
line for good. The stage relay marks a stage seen before it logs it, so a stage
that lost that race was never written: main's Windows-only job lost "process
cwd set", "running: python ...", the relayed stage and the tail of the
update's output in one run (test_handoff_shows_the_stage_the_update_publishes,
x64), while the same commit passed on arm64.

A line that cannot be appended now waits in a queue and lands, in order, with
the next append that succeeds; the step loop retries every pass and the run
retries for up to 10 s before it exits. Appends use AppendData with
ReadWrite|Delete sharing, so a reader never blocks them and they land at
end-of-file atomically even beside a writer whose mutex wait timed out.
2026-10-27 15:58:38 -07:00
liuhao1024
0b62510eb3 fix(desktop-update): serialize hand-off log appends across concurrent writers
Write-HandoffLog appended with Add-Content, which is unsafe once a second
writer is live: PowerShell caches a content writer per path, so the second
writer receives a handle the first already consumed. On Windows PowerShell
5.1 that surfaces as a "stream is not readable" error flood; on PowerShell
7 it silently loses lines (58% measured on the issue's 8-writer shape,
#126152). The hand-off log is the only record of why a Desktop update
failed, and overlapping hand-off processes are a real event: the marker
claim is a plain write with no mutual exclusion and its failure path logs
a warning and continues.

Serialize the append behind a named, per-log-path mutex plus one FileStream
per write. The mutex instance is created lazily so any runspace or process
writer joins the same OS object; the bounded wait and the empty catch keep
the "logging must never break the update" contract; an abandoned mutex is
still released so a killed writer cannot leak the hold.

Adds a -SelfTestLogConcurrency fixture (8 runspaces x 100 lines through the
real function, holding the file to the exact count with no torn lines) and
a Windows-lane regression test driving it. Measured with Add-Content
restored: 1026-1157 lines present for 800 written, plus torn lines; with
the fix: 800/800 intact across repeated runs.

Co-authored-by: ZCode <agent@zcode.local>
2026-10-27 15:58:38 -07:00
Teknium
6c4e73376a fix(update): failure tail keeps a progress line's final state; fix proxy env comment
posix.sh stripped CRs, merging a CR-overwritten progress line into one
string whose first 120 chars were its EARLIEST state; it now keeps the last
CR segment, what the terminal showed. checkout-source's comment said the
proxy env comes last, but buildDesktopBackendEnv is spread after it.
(itsflownium review on #144894, small items.)
2026-10-27 13:23:31 -07:00
Teknium
20e892f81a fix(desktop): the system proxy reaches only the update's children
Review round on the system-proxy hand-off (#123387):

- The resolved proxy leaked into the relaunched Desktop and everything it
  starts. posix.sh relaunched with the update env scrubbed but the proxy
  env kept, the Windows Start-Process rung and the staged updater pass
  their env on, and gateways `hermes update` restarts inherit it. With a
  NO_PROXY of only localhost, every LAN or internal host the PAC sends
  direct went through the proxy, and the next update read the stale proxy
  as an explicit user setting and never re-resolved it.
  The Desktop now names each variable it adds in HERMES_UPDATE_SYSTEM_PROXY
  and saves a NO_PROXY of the user's it extends as
  HERMES_UPDATE_USER_<KEY>. The Desktop restores its own env at entry (every
  relaunch rung), posix.sh restores it in the relaunch subshells (Linux
  and macOS), windows.ps1 before the tethered Start-Process rung, and the
  gateway and serve/dashboard at start. A marked value is never taken
  for the user's own on the next update.
- NO_PROXY gains 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16
  and .local, and a user NO_PROXY is extended instead of replaced. The
  user's value previously also overrode the extended one, because
  process.env was spread after the proxy env.
- Each update host is resolved on its own, and the env proxy is exported
  only when every host is either that one plain PROXY or DIRECT. A PAC
  that sends hosts to different proxies gets a logged note and no env.
- SOCKS and HTTPS answers are no longer exported. Chromium's "SOCKS" is
  SOCKS4 and was mapped to socks5h. Beyond that, Python's urllib sends a
  plaintext CONNECT to any proxy URL, npm reads no SOCKS env, httpx refuses
  socks4, and the update's own git calls drop injected git config. They
  get a logged note instead.

Live (Electron 44.9.3 on Xvnc :95):
- Before: the built Desktop launched with a marked proxy env gave its
  Python backend all six proxy variables. After: only the user's
  NO_PROXY=corp.internal.
- The real posix.sh --relaunch-target: `hermes update` still gets the
  proxy, and the relaunched app gets none (before: all six).
- A PAC resolving LAN and corp hosts DIRECT keeps them direct, and so do
  the update's localhost calls.
2026-10-27 13:23:31 -07:00
liuhao1024
e241405cd1 fix(desktop-update): name the failing updater output in the hand-off failure
当 hermes update 在 Desktop hand-off 里失败时,shim 与下次启动的结果
弹窗只显示 "Update failed (exit N)",从不携带 updater 自己的输出,
用户没有任何可达途径看到真实失败原因(#137327)。

从本轮 log 切片(OUT)提取 updater 最后 3 行非空输出(剥离 ANSI/CR、
过滤 hand-off 自身的时间戳日志行、每行限 120 字符)附加到失败文案;
输出为空时保持原文案不变。
2026-10-27 13:23:31 -07:00
PRATHAMESH75
52223a33d2 fix(desktop-update): read macOS creation times with /bin/date under GNU coreutils
proc_ct() parses `ps -o lstart=` with `date -j -f`, a BSD-only flag. The
Desktop hand-off inherits the login-shell PATH, so with Homebrew's coreutils
gnubin first `date` is GNU date: `-j` fails, `2>/dev/null || return 0`
swallows it, proc_ct prints nothing, ident_state returns 2 for the Desktop's
pid, the bridge-marker claim is refused and posix.sh exits 2 on every update.

Pin /bin/date, as the scripts already do for /usr/bin/python3 and xattr.

Fixes #137925
2026-10-27 13:23:31 -07:00
Akloenx123
5a9d72f341 fix(update): compare creation times under LC_ALL=C in ct_close too
ct_close parses two dotted creation times via awk -v. mawk, gawk (also
--posix and --use-lc-numeric) and BusyBox awk all read -v assignments
with a dot under a comma-decimal locale today, so this is no behaviour
change; pinning LC_ALL=C makes the comparison locale-proof by
construction instead of by an awk implementation detail, matching the
write side in proc_ct (#135183).
2026-10-27 13:23:31 -07:00
Akloenx123
7da84c65d4 fix(update): write the hand-off's creation time with a dot under any locale
proc_ct rendered the POSIX hand-off's creation time with awk's printf, and
mawk (the default awk on Debian and Ubuntu) formats %f with LC_NUMERIC's
decimal separator. Under a comma-decimal locale the marker got
ct:1791471938,040, which MARKER_CT_RE and both readers reject, so the
hand-off judged its own claim a previous incarnation, refused to publish
the update child and every Desktop update aborted with exit 3.

Pin that awk to LC_ALL=C, as the ps/date calls beside it already are.

Fixes #135183
2026-10-27 13:23:31 -07:00
Teknium
c0016c3cb5 fix(desktop-update): a Close-and-retry runs under its own hand-off run, not an inherited one
Review round on #101789 (R-890-1). A Desktop that the hand-off's tethered
Start-Process rung relaunched inherited that run's HERMES_UPDATE_CORRELATION_ID.
Its next hand-off passed `-HandoffRun Y`, but windows.ps1 kept the inherited id X
for `hermes update`, so take_consent(release, X) dropped the consent bound to Y:
every "Close <program> and retry" in that Desktop session closed nothing and the
dialog came back (fail-safe, but a dead button).

- windows.ps1: -HandoffRun beats an inherited id; an id from the environment is
  kept only when no run was given (older Desktops, other callers).
- windows.ps1: the run's id is removed from the environment before any relaunch
  rung, so the relaunched Desktop never carries it.
- checkout.ts: the Windows script hand-off sets HERMES_UPDATE_CORRELATION_ID to
  the run its consent is bound to (dropped when the script predates protocol 2).
2026-10-27 11:51:03 -07:00
Teknium
4d854d033b fix(desktop-update): offer the Desktop close only when a holder can be closed
With every holder unreadable (a protected process) the result message no longer points the user
at a close button the dialog does not show.
2026-10-27 11:51:03 -07:00
Teknium
719b4c3220 fix(desktop-update): a close-holder consent covers exactly the retry it started
Review round on #101789. The Desktop's "Close <program> and retry" consent stayed valid for an
hour: when the retry failed before the swap (build error, refused apply), the next swap from any
source (gateway /update, cron, another Desktop) closed the program without asking.

- The consent is bound to the retry's hand-off run id (checkout.ts binds it once the run id
  exists; windows.ps1 already exports it to `hermes update` as HERMES_UPDATE_CORRELATION_ID) and
  to the exact processes the user saw (pid + start time + program).
- Every swap attempt consumes the file at its start, matching or not; only the run it was given
  for acts on it. An apply that does not hand off removes it, and the hand-off script removes one
  its run never used.
- A holder whose program path cannot be read (a protected process) is named for the user to close:
  no Close button in the Desktop dialog and no y/N for it at the terminal, since closing it from
  here can never work.
2026-10-27 11:51:03 -07:00
Teknium
b03699fca5 fix(desktop-update): relaunch the Desktop and point its shortcuts at the user home
The Windows hand-off relaunched Hermes.exe (WMI and Start-Process rungs)
with release\win-unpacked as its working directory, and install.ps1 wrote
the Start menu and desktop shortcuts the same way. Every child the Desktop
starts without its own cwd inherits it, and Windows refuses to rename a
directory that is a live process's cwd, so one helper that outlives the app
blocked every later swap of that folder (#101789). Both now use the user
profile, matching the Electron entry point's own relocation.
2026-10-27 11:51:03 -07:00
Teknium
21ead66c56 fix(desktop-update): windows.ps1 keeps release holders in a plain array (PS 5.1 @() over List[object]) 2026-10-27 11:51:03 -07:00
Teknium
ef47d951bd fix(desktop): name the program holding release/ and close it only with consent (#101789)
Windows refuses to rename a directory that any live process uses as its
working directory. A resident helper spawned from a Hermes window (Sogou
IME's SogouCloud.exe in the report) inherits that window's cwd inside
release/win-unpacked and keeps it after the app exits, so every Desktop
stage-and-swap failed with an opaque "Could not publish the desktop build"
although the build succeeded.

The previous commit stopped such processes automatically. A program that is
not part of Hermes is the user's, so this keeps its cwd detection
(hermes_cli/desktop_release_holders.py) and drops the kill:

- When the first swap rename is refused on Windows, every process whose cwd
  is inside release/ is named, one "Desktop app folder held by: NAME (pid N,
  EXE)" line each, and the update failure names it too.
- It is closed only with consent: a yes at an interactive terminal prompt, or
  the Desktop's "Close NAME and retry" choice, which leaves a one-retry consent
  file in release/ naming the programs. Each one is re-checked right before
  (same pid and creation time, cwd still inside, not our ancestor). A hidden
  hand-off or piped run with no consent never closes anything.
- windows.ps1 turns the holder lines into a structured release_holders list
  and a message naming the program; the relaunched Desktop shows it and offers
  the consented close-and-retry (default button: Not now), which runs the
  update hand-off again so the owed app is rebuilt and promoted.

Same goal as #101793 (name the holder instead of failing opaquely), plus the
consented retry.

main.ts: fileExists/directoryExists/isGitCheckout move to electron/fs-probes.ts
to offset the two new lines.

Fixes #101789
2026-10-27 11:51:03 -07:00
Teknium
121393e1e7 fix(desktop-update): the tethered Windows relaunch does not inherit the stage relay
windows.ps1 exports HERMES_UPDATE_STATUS_FILE for `hermes update`'s stage
relay. The WMI and explorer relaunch rungs start the Desktop with a fresh
environment, but the Start-Process fallback inherits this script's, so the
relaunched app (and the gateways it spawns) carried the update's status file.
Clear it on that rung, as posix.sh does on its relaunch.
2026-10-27 07:53:07 -07:00
Teknium
c9b55ea26d fix(desktop-update): the update window names the stage it is in, on Windows too
The hand-off window showed "Updating code and dependencies" plus a clock for
the whole 20-60 minute update (#139952, #135363, #130460). On Windows the
hermes update child could not publish anything: windows.ps1 never told it
where (posix.sh exports HERMES_UPDATE_STATUS_FILE), and the pipeline's own
stage marks named nothing.

- windows.ps1 exports HERMES_UPDATE_STATUS_FILE and relays what the child
  writes there to the window once a second while the step runs, logging each
  stage to the hand-off log so its timestamps localize the slow one.
- Each pipeline stage mark (snapshot, apply, deps, build) publishes the next
  stage: Downloading updates, Updating dependencies, Building the apps,
  Restarting Hermes services. The desktop build adds "Packaging the desktop
  app" before electron-builder runs.
2026-10-27 07:53:07 -07:00
kshitijk4poor
3752497cc4 refactor(update): one deferral core, shared reason prefix, per-line Desktop hint; review folds
Folds the final-head review and /simplify-code pass on #141070:

- update_serve_obligations: defer_manual_serve and defer_unit_serve share
  _defer_identified (pid/create-time guard, dead-pid discharge, reminder
  write) instead of two copies; a unit row's failed-write warning says
  "unit restart reminder", not "manual".
- update_cmd_fleet: a positive _is_serve_or_dashboard_unit name gate,
  composed into _is_hermes_gateway_unit; _is_serve_unit uses it rather
  than "gateway gate minus SIGUSR1 support". _SERVE_SKIP_REASON names
  hermes-dashboard* units too.
- update_cmd_fleet_verify: SERVE_ONLY_REASON_PREFIX and the gateway
  sentence are module constants, so the producer and the Desktop
  predicate share one spelling; the test now feeds the producer's own
  reasons to both scripts.
- Desktop hand-offs (posix.sh, windows.ps1): drop the gateway hint only
  when EVERY gateway_restart line is serve/dashboard-only, so a serve-only
  line next to a raw restart-phase error keeps it; case-sensitive in
  PowerShell (-cmatch) like grep.
- main_dashboard._format_restart_commands replaces three copies of the
  backticked " or " join.
- Docstrings: already_restarted_units covers declined and failed units.
2026-10-19 02:48:18 +05:30
kshitijk4poor
3c23e52ae3 fix(desktop-update): add the gateway hint only when the follow-up blames gateways
posix.sh and windows.ps1 appended "Run hermes gateway restart" whenever
the gateway_restart step was owed. Since this PR, that step can be owed
for a serve/dashboard unit alone (a system hermes-dashboard the updater had
no root for), and the hint then sends the user to a command that never
touches that unit. Both hand-offs now drop the hint only when the owed
reason is serve/dashboard-only: it starts with "serve/dashboard" and does
not mention `hermes gateway restart`. Every other gateway_restart reason
keeps the hint, including the raw exception text update_finish owes when
the restart phase itself crashes and reasons from older CLIs. A
dashboard-only owed restart points to the update log, which names the
unit's own command. The step id and owed-step parsing are unchanged.

Fixes #141071
Refs #141021
2026-10-19 02:48:18 +05:30
elvindu
013e94b38a fix(install): name the marker owner as the Desktop hand-off pid
The posix hand-off hands marker line 1 to a custodian subshell
(marker_refresher_start) and then exported HERMES_UPDATE_HANDOFF_PID="$$" —
the hand-off script's own pid.

`hermes update` adopts a live claim only when the owner is its own pid, the
HERMES_UPDATE_HANDOFF_PID value, or an ancestor
(update_lock.UpdateLock._is_partner). The custodian is a *sibling* of the
hand-off script, so it is none of the three and the ancestry walk can never
reach it: every desktop-initiated update refused the claim its own script had
just made and exited 2 ("Another Hermes update is already running ...
process <custodian>"), leaving the Desktop to relaunch and retry forever.

Export $MY_PID instead: the custodian once the handover succeeded, and the
script's own pid when it did not.

Fixes #134268
2026-10-10 10:44:34 -07:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
Teknium
808520532c test(desktop-update): kill the macOS app swap at every step and prove recovery
Nothing tested mac_bundle_recover(), the start-of-run repair that finishes or
rolls back a Hermes.app swap a killed hand-off left half done.

posix.sh --self-test-swap-interrupt (body in swap-selftest.sh) runs the REAL
mac_swap on a fixture bundle tree in its own process group. mac_swap now
names its step boundaries (swap_checkpoint start/staged/aside/installed); the
self-test makes the swapper SIGSTOP itself at one of them and SIGKILLs the
whole group there, or resumes it and SIGKILLs it mid-ditto / mid-cleanup rm.
It checks the wreck has the expected shape, runs the REAL mac_bundle_recover,
and asserts the target is the complete old or complete new bundle (whole-tree
checksum, version marker included), no .old/.new/.hermes-update-* is left,
and a second recovery changes and logs nothing. Seven cells: before-stage,
mid-stage, staged, aside, installed, mid-cleanup, complete (control).

The seams are inert in a real run: SWAP_PAUSE_AT is set only inside the
self-test, and MAC_DITTO stays /usr/bin/ditto unless the self-test runs where
ditto is absent (Linux: cp -R).

test_desktop_update_mac_swap_interrupt.py drives the arm under
platforms("posix"): the Linux suite and the macOS lanes of tests-os.yml
(real /usr/bin/ditto, macOS /bin/bash 3.2).
2026-10-07 04:11:50 -07:00
Teknium
d95d5bca1f fix(desktop-update): updater window opens in the Windows 11 25H2 default browser
Get-DefaultBrowserExe read only the legacy UserChoice ProgId, which Windows
11 25H2 Settings no longer updates, so the update hand-off fell back to the
WinForms card (or a stale browser) on machines whose real default is
Chrome/Edge. Read UserChoiceLatest\ProgId first, legacy UserChoice second.

Fixes #108051. Follows #108062 / #108064.

Co-authored-by: KoNit-K <konit.block@protonmail.com>
Co-authored-by: Konstantin Khlopkov <konstantin.khlopkov93@gmail.com>
2026-10-07 02:29:54 -07:00
Teknium
b3f2f9d18d fix(update): owed follow-ups reach the Desktop result through the commit-safe hand-offs
While this branch was in review, #132386 landed on main: a committed
`hermes update` that still owes work prints one whole "Desktop app build
owed:" line and one "Update follow-up '<step>' did not finish:" line per
owed step, and both Desktop hand-offs turn those into a manual outcome
naming the step (never a plain "Update complete."). This branch rewrites
both hand-off scripts, so the rebuild took its versions whole and this
commit carries main's behaviour into them, through this branch's own
post-commit design:

- posix.sh: owed_followup_steps() (unchanged from main: the parser contract
  test runs it), the build-owed and owed-steps checks on a zero exit, each
  setting DONE_NOTE (finish() makes it manual) and an add_warning entry so
  the step also reaches the result's warnings; the Linux relaunch gate now
  appends to DONE_NOTE instead of replacing an owed-step note.
- windows.ps1: the same two checks as Add-Followup -Manual calls before the
  runtime verify, with main's exact [regex]::Matches expression.

Already equivalent here: the mac swap is skipped when the rebuild failed,
and finish() relaunches the kept app for a manual note unless the Linux
gate says skew/manual.

Before: 6 of main's contract tests fail on the rebuilt branch
(test_every_owed_followup_reaches_the_desktop_result x4, the truncated
build-owed case, the parser contract). After: tests/scripts/desktop_update/
plus test_update_post_commit_followups.py pass, 113 passed, 0 failed.
2026-10-06 05:44:21 -07:00
Teknium
299fcf1c69 fix: the POSIX launcher counts the custodian its daemon forked as a started hand-off
Within moments of its claim the daemon hands marker line 1 to the custodian it
forked (fdab580431e). The launcher's start check (contract C2) still waited for
the daemon's own pid, so on a host where the handover beat its next 0.1 s poll
it never matched, and once the daemon finished it reported a running update as
a failed launch (exit 70). `marker_names_handoff` now accepts line 1 naming the
daemon or a process the daemon forked; a grandchild or an unrelated pid still
does not count.

Sabotage A/B (daemon held alive 2 s after the custodian takeover, real
hand-off via the shim-progress harness): old acceptance exits 70, new exits 0
and publishes the stage. Test: the predicate over custodian/daemon/grandchild/
unrelated, red on the previous marker.sh.
2026-10-06 05:44:21 -07:00
Teknium
b2678712f5 fix: an old Desktop never reads a dead owner while the Windows hand-off dies
Same gap as the POSIX hand-off: the -MarkerOp custody watcher took line 1
over only after windows.ps1 exited (WaitForExit, then the marker lock), so
an old packaged Desktop reading in between (lines 1 and 2 only) deleted the
marker while the resumed `hermes update` or a completion survivor still
held the checkout.

Start-MarkerCustodian now names the watcher on line 1 under the marker lock
right after starting it, before any update work, and the hand-off judges
its claim as that watcher from then on ($script:MarkerOwner in
New-MarkerContext): delegate publication, heartbeat and release keep
working. Invoke-MarkerRelease stops the watcher only after the release, so
line 1 stays live until then. Invoke-MarkerCustody keeps a claim that
already names it (judged by the creation time the hand-off recorded) and
falls back to the old takeover only when the handover failed.

Tests (Windows CI lane): the kill cell holds the marker lock across
taskkill /F and runs the shipped legacy reader at once; the pre-publication
kill cell and the A7 race expect the custodian on line 1.
2026-10-06 05:44:21 -07:00
Teknium
4a7c363c0b fix: an old Desktop never reads a dead owner while the POSIX hand-off dies
The previous fix let the line-2 refresher take the marker over only AFTER
the hand-off died: it polls once a second and then waits for the A7 lock,
and until it rewrote line 1 the marker named the dead hand-off. An old
packaged Desktop (judges lines 1 and 2 alone, ignores A7 and the delegate)
reading in that gap deleted the marker and booted its backend while the
`hermes update` the hand-off started, or a completion survivor, still held
the checkout lock -- and the custodian then found no marker to keep.

Now the custodian is named on line 1 BEFORE any update work starts:
marker_refresher_start forks the refresher, then, under A7, rewrites the
claim's line 1 to the refresher's exact pid + creation time and adopts that
identity (MY_PID/MY_CT) for every later marker mutation (delegate, refresh,
release). posix.sh checks its own liveness with $$. The refresher keeps
line 2 young; if the hand-off dies it keeps the marker until the delegate
and the checkout lock are gone, then releases it. The hand-off releases the
marker before it stops the custodian, so line 1 stays live until the
release. If the handover fails (A7 busy), the old takeover-on-death path
still applies.

Test: the orchestrator-killed cell now holds the A7 lock across the SIGKILL
and runs the shipped legacy reader at once (no takeover is possible), then
keeps the post-takeover phases. Red on 5f855a2392c: {'live': None,
'kept': False}. Tests that asserted line 1 == the hand-off pid now expect
the custodian (that assertion encoded the vulnerable state).
2026-10-06 05:44:21 -07:00
Teknium
e8dc3cd63c fix: the hand-off scripts read an unopenable checkout lock as held
marker.sh::checkout_lock_held and marker.ps1::Test-CheckoutLockHeld answered
"not held" when the lock file exists but cannot be opened (root-owned after
`sudo hermes update`, or held open without sharing on Windows), while the
Desktop's own probes (checkout_held / WINDOWS_CHECKOUT_LOCK_PS) answer "held".
The script helper's reclaim then deleted a dead marker the Desktop's probe
keeps. Both scripts now fail closed on every open/probe error except a
missing file: reclaim needs a provably free checkout. Parity tests: the
POSIX probe with perl, python3 and flock(1), plus an end-to-end reclaim; the
Windows reclaim against a lock file held with no sharing (Windows CI lane).
2026-10-06 05:44:21 -07:00
Teknium
d899d5a74b fix: an old Desktop stays parked when the Windows hand-off dies mid-update
Same shape as the POSIX hand-off: windows.ps1 heartbeats line 2 from its
own process, so `taskkill /F` (no finally runs) left line 1 naming a dead
pid while the resumed `hermes update` (the line-4 delegate) or a completion
survivor still held the checkout, and an old packaged Desktop - which judges
lines 1 and 2 alone - deleted the marker and booted its backend.

After its claim the hand-off starts a hidden watcher (-MarkerOp custody
-CustodyOf <pid>, Start-MarkerCustodian). Once the hand-off exits with its
claim still published and the delegate running or the checkout lock held,
the watcher names itself on line 1 under the marker lock, heartbeats line 2
and releases the marker when both end (bounded like the R6 wait).
Invoke-MarkerRelease stops the watcher once the hand-off's own release is
decided. The Windows kill-cell test now also runs the reader be3fd671d70
shipped; that reader runner moves to a helper shared with the POSIX test.
2026-10-06 05:44:21 -07:00
Teknium
e410ffc941 fix: an old Desktop stays parked when the POSIX hand-off dies mid-update
An older packaged Desktop judges the update marker by line 1 (pid alive) and
line 2 (under 20 minutes) alone and unlinks it otherwise, never consulting
the protocol-2 delegate line or the marker helper. The line-2 refresher
exited with the hand-off script, so a SIGKILLed hand-off left line 1 naming
a dead pid while the `hermes update` it started, or a completion survivor,
still held the checkout lock: the old Desktop deleted the marker and booted
its backend into a checkout still being mutated.

The refresher now outlives the hand-off as its custodian (marker_custody):
once the hand-off is gone, if its claim is still published and the delegate
runs or the checkout lock is held, it names itself on line 1 (exact pid +
creation time, under the A7 lock), keeps line 2 young, and releases the
marker only after both are gone (bounded like the R6 wait). The test runs
the reader be3fd671d70 shipped (vendored verbatim under tests/fixtures).
2026-10-06 05:44:21 -07:00
Teknium
ed17c1cea3 fix(desktop): the hand-off waits long enough for a Desktop quit that joins a managed update
The hand-off scripts gave the Desktop a fixed 30 s (windows.ps1) or 60 s
(posix.sh) to exit, but the Desktop's quit can first join a managed SSH update
it is running, which legitimately takes longer. The hand-off then recorded a
failed update although the Desktop exited safely moments later (review H2).

Both twins now share one 150 s ceiling, measured on the clock rather than as a
loop count, and still refuse with "Nothing was changed" if the Desktop is alive
at the ceiling, so nothing is ever replaced under a live Desktop. The ceiling is
overridable through HERMES_UPDATE_DESKTOP_EXIT_SECONDS only so the self-tests
need not sit it out, like the existing pipe-drain and step-idle overrides.

Tests: a Desktop still alive at the ceiling refuses with exit 4 and never runs
the update (red on the start sha, which waited out its hardcoded 60 s); a
Desktop that exits inside the ceiling lets the update run (control).
2026-10-06 05:44:21 -07:00
Teknium
d8b3d565fd refactor(update): update-job.ps1 compiles its job helper in Initialize-HermesUpdateJob
update-job.ps1 was one top-level `if (-not type) { Add-Type ... }` block.
It is now a named function, Initialize-HermesUpdateJob, that returns early
when the type already exists and is called once at the end of the file, so
the dot-source in windows.ps1 behaves exactly as before. The C# body is
unchanged byte for byte.

Checked with PowerShell 7.4 on Linux: dot-sourcing the file twice compiles
the type once and HermesUpdateJob::ProcessIds(0) answers; windows.ps1 still
parses with zero errors. Windows PowerShell 5.1 itself was not run here.

Review 5411223284 (shape: update-job.ps1 top-level code).
2026-10-06 05:44:21 -07:00
Teknium
e13fb204e9 fix(update): with no marker the Desktop gate still asks whether the checkout lock is held
The script helper's `reclaim` answered `absent` the moment the marker file
was missing, before the checkout lock was looked at, and the Desktop gate
(update-marker-gate.ts liveMarkerProbe) returned "nothing runs" for a
missing marker without asking the helper at all. An update that holds the
checkout lock before it publishes its marker, or after it retired it (the
CLI paths of the stacked PRs do both), therefore let the Desktop boot a
backend into a checkout still being written.

- marker.sh marker_op_reclaim_locked / marker-claim.ps1 Invoke-MarkerOp:
  no marker -> `held` when the checkout lock (owner byte + lease bytes on
  Windows) is held, else `absent`, under the same marker lock.
- update-marker-gate.ts (gate-lane file, additive): a missing marker is also
  routed through the helper; only its positive `held` keeps the gate shut
  (blocked screen, Retry, Start anyway as for a dead marker). Any other
  answer, `error` included, proceeds as before, so a broken script never
  blocks a markerless boot.

The gate test "a live owner never reaches the helper; an absent marker
neither" pinned the missing check for the absent half; that half is now the
new "no marker: only held keeps the gate shut" case.

Review 5411223284 (open thread: update-marker-gate.ts ~193 / helper absent).
2026-10-06 05:44:21 -07:00
Teknium
7a8249f35c fix(update): hand-offs report a nonzero exit past the commit point as installed with a follow-up
Both hand-off scripts treated ANY nonzero `hermes update` exit as ok:false
"Update failed". After the commit point `hermes update` can still exit
nonzero by design -- 130 (Ctrl-C after the code moved: receipt outcome
`interrupted`) and 1 (a parked autostash: `partial`) -- or crash after a
committed run (`success`). The Desktop then said the update failed while the
new code was installed (contract C3 / invariant 3).

The scripts now hand the update a correlation id (HERMES_UPDATE_CORRELATION_ID,
already honoured by update_receipt._launcher_correlation_id; a caller's own id
is kept) and, on a nonzero exit other than 2 (refused), read the root's
logs/update_receipts/latest.json. Only THIS run's finalized receipt counts
(matching correlation_id, finished_at set, outcome success|partial|
interrupted); a record reconciled as interrupted keeps finished_at null and
never matches. Then the result is ok:true, manual, with an `update` warning
naming the exit and outcome, and the post-commit steps (Windows: verify,
gateway start --all) still run.

posix.sh also routes its own signal handler through the same judgement: a
HUP/INT/QUIT/TERM that lands after the update committed (exit 0, or a
committed receipt) is an owed `handoff` follow-up, exit 0, not
"hand-off was interrupted".

Tests: posix live cells (RED at start) for interrupted/130, partial/1,
success/1 and an INT delivered while the committed child finishes, plus
negative controls (no receipt, failed, another run's receipt, a reconciled
unfinished record); the Windows twin cells.

review S5
2026-10-06 05:44:21 -07:00
Teknium
98d6720885 fix(update): hand-off results carry the real finish time after the R6 release wait
posix.sh::finish and windows.ps1's finally write the result (finished_at =
now) BEFORE the R6 release wait, which lasts up to 7200 s while a survivor
holds the checkout lock, and before the relaunch. The relaunched Desktop has
no expected run id and handoff-result.ts drops a non-manual result older than
30 min, so a failure or warnings result was silently discarded after a long
wait.

The early write stays (a kill during the wait still leaves a result); when the
wait actually ran, the result is published again after it with the real
finish time, unless something already consumed it. The release records that
it waited (RELEASE_WAITED / $script:MarkerReleaseWaited).

Tests: posix live cell (RED at start: finished_at 3 s before the survivor
let go) and the Windows twin with a timed checkout-lock holder.

review S2
2026-10-06 05:44:21 -07:00
Teknium
6b97fee9c2 fix(update): the Windows hand-off removes its result tmp when publishing fails
Write-Result writes <result>.<pid>.tmp and then Moves/Replaces it over the
result. When both fail (result path locked, a directory, ACLs) the catch only
logged, leaving one tmp file per hand-off beside the result. The tmp is now
removed in a finally (it is gone already after a successful publish), the
same as posix.sh's write_result.

Test (Windows live cell): with the result path occupied by a directory the
hand-off still exits 0 and leaves no .hermes-update-result.json.*.tmp.

review S4
2026-10-06 05:44:21 -07:00
Teknium
684e7d713f fix(update): posix hand-off results stay valid JSON for any control character
json_escape escaped only \ " \n \r \t. Every result/status string it builds
(FINAL_MSG, branch, channel, warnings) can carry text from git/ps/hermes
output; a raw ESC, BEL or any other char below 0x20 made the whole
.hermes-update-result.json invalid, and the Desktop dropped the outcome.

The remaining control chars are now written as \u00XX. Bash 3.2 compatible:
printf -v, no forks; the loop runs only when the string holds a control char.

Test (RED at start): json_escape over chars 1..127 plus UTF-8 and an ANSI
colour sequence round-trips through json.loads, in the C and C.UTF-8 locales.

review S7
2026-10-06 05:44:21 -07:00
Teknium
58512c1671 fix(update): posix marker ops fail closed like marker-claim.ps1 on identity and removal
Two parity gaps between marker.sh and marker-claim.ps1:

- adopt-run (--handoff-run), withdraw's `withdrawn` and `taken` accepted
  J_OWNER_STATE==2, which also covers "alive, creation time unreadable, line 2
  younger than 20 min". marker-claim.ps1 requires Test-ProcessIdentityExact
  (both creation times known, within 2 s). An unreadable ct is no proof the
  pid is still that process; these three now require ident_state 0, and
  `taken` skips our own pid like the ps1.
- reclaim / withdraw printed `reclaimed` / `withdrawn` after an `rm -f` that
  exits 0 even when it cannot unlink; the Desktop then proceeded as if the
  marker were gone. marker_remove checks the marker is gone; else `busy`, the
  ps1's answer when Remove-MarkerLocked fails.

Tests (RED at start): the three identity cases with every foreign ct
unreadable (and the readable control), and a reclaim inside a read-only
home that must answer `busy` and keep the marker.

review S3
2026-10-06 05:44:21 -07:00
Teknium
c8ac525cbf fix(update): Windows marker decisions re-read creation times instead of a pid's cached one
Get-LiveProcessCt caches a pid's creation time for the script's lifetime and
forgets it only when a probe SEES the pid dead. A delegate (the `hermes update`
child) that exits and whose pid is reused between two probes keeps the old
incarnation's time, so the release judged the unrelated new process live and
handed the marker to it (A7 rule 5), parking every later update behind it.

Every judgement made through New-MarkerContext (claim, delegate, heartbeat,
release) and the delegate line Add-MarkerDelegate writes now pass -Fresh,
which re-reads the time. Pollers that only ask "still alive?" (Wait-DesktopExit)
keep the cache.

Test (Windows live cell): a release with the delegate's pid cached at the
recorded ct but really owned by another incarnation deletes the marker instead
of handing it over. marker.sh reads /proc or ps on every call: no cache.

review S6
2026-10-06 05:44:21 -07:00
Teknium
a041e18255 fix(update): the Windows hand-off judges the checkout busy while a leased child holds it
marker.ps1::Test-CheckoutLockHeld probed only the owner byte at 1 MiB. Since R5b
every joiner the kill-on-close job refused also locks one of the 16 lease bytes
after it, and hermes_cli/update_lock.py::_try_lock treats any held lease as a
held lock. With the owner dead and a leased completion child still running, the
hand-off read the checkout as free, so the R6 release wait ended and the
Desktop's reclaim deleted the marker next to a live mutator.

Lock/Unlock now cover 1+16 bytes in one LockFile (it fails if any byte is held).
marker.sh needs no change: POSIX takes the checkout lock with flock on the whole
file and the lease bytes exist only on win32 (_take_lease).

Tests: a live Windows cell holds only a lease byte (1 and 16) and expects
`held`; a static cell, runnable on Linux, pins the probed range (RED at start:
(1048576, 1)).

review S1
2026-10-06 05:44:21 -07:00
Teknium
d549d5fb5c fix(update): a timed-out probe on a host without perl is killed with its whole tree (review desk-noperl-timeout-leak)
What: run_bounded's no-perl branch starts the probe under bash job control (set -m), so it gets its own process group and the timeout's kill -KILL -- -pid reaches its children.
Why: without perl the probe stayed in the caller's group, the group kill failed, and a hung hermes --version / update --help left its python child running.
Red: pre-fix posix.sh fails test_timed_out_probe_is_killed_with_its_whole_process_tree[absent] (grandchild alive after rc=124). Green: both [present] and [absent] pass.
2026-10-06 05:44:21 -07:00
Teknium
3bb4e87775 test(update): runtime unicode docstring matches the ProcessStartInfo UTF-8 capture
Review R8 m7: after the merge with main's 732b63d61a8 the probe decodes launcher
stdout as UTF-8 through ProcessStartInfo.StandardOutputEncoding and never touches
[Console]::OutputEncoding, so the test docstrings no longer claim the call sites
scope and restore it. runtime.ps1 keeps a one-line #124526 pointer at the
encoding line. Behaviour and assertions are unchanged.
2026-10-06 05:44:21 -07:00
Teknium
450b53fab1 fix(update): require delegate publication before releasing handoff child
(cherry picked from commit c41f84ddffcc36a3a59a975d7f85bf8c5b2f19b3)
(cherry picked from commit c85844ceaca472d1260e9883f3268c01c0c6010f)
2026-10-06 05:44:21 -07:00
Teknium
b5852b3187 fix(desktop): correlate handoff receipts with stable run identity
(cherry picked from commit 87c67de3778735837b73de8d2955f83624b2b449)
(cherry picked from commit bf3ca9f63cead72e51f22d4376abe5b3504d4bf2)
2026-10-06 05:44:21 -07:00
Teknium
b17bcfc704 fix: bash and PowerShell marker readers take the oversized-number corpus cases
The corpus now pins line 2 to digits that fit u64 (any count) and a pid to
digits that fit u32 after leading zeros. bash took a line 2 past u64 as a
far-future start (live); PowerShell rejected any line 2 over 18 digits
(so u64::MAX was malformed) and any pid over 10 characters (so a
zero-padded pid was malformed), and Windows PowerShell's [double]::Parse
throws on a creation time past double's range.

bash compares a 20-digit line 2 as two 10-digit halves (never in signed
shell arithmetic); PowerShell strips leading zeros before the width checks,
compares 20 digits as a decimal, and reads an out-of-range ct as +Infinity,
which never matches a live process. Rewrites carry line 2's exact digits;
only the age arithmetic clamps.

(cherry picked from commit 7208aa4af3c9e355dadee970dddb730fcfeb0301)
2026-10-06 05:44:21 -07:00
Teknium
33cea9a733 fix: bash and PowerShell adopt an old Desktop's launcher bridge by one lineage rule
The two scripts disagreed on an old packaged Desktop's v1 bridge (round 5
D11): bash adopted a live launcher that is our parent but no longer the
Desktop's child when line 2 equals HERMES_UPDATE_STARTED_AT (the Desktop
quit first and the launcher was re-parented); PowerShell refused it, also
accepted a v2/delegate claim naming its parent, required a gone launcher to
be its recorded parent, and Trim()/TryParse'd the env value.

One rule now, as a pure function in both (marker_launcher_rule /
Test-MarkerLauncherRule) over the same facts, plus one env comparison
(plain ASCII digits of line 2's value). tests/scripts/desktop_update/
lineage_rule_cases.py is the shared table; the posix and Windows suites run
it, and a real-process cell per platform covers the divergent row.

(cherry picked from commit aa4b8ce704bc474d539690235c191edee3b637f2)
2026-10-06 05:44:21 -07:00
Teknium
b493b91a33 fix: hand-off probes the checkout lock for two syscalls and refreshes line 2 through the R6 wait
checkout_lock_held took the real checkout lock through flock(1) on a shell
fd and released it only when the shell closed that fd: the hold spanned
flock(1)'s exit, the wait and the close, so a concurrent `hermes update`
acquiring non-blocking was refused 223 of 3157 times in the reviewer's
tight-loop probe (round 5 D17). Now one process (perl, else python3) opens
the file, tries LOCK_EX|LOCK_NB and drops it in the next syscall: 0 of
3387. flock(1) stays the last-resort fallback; no tool still means held.

The old-Electron line-2 refresher ran only while `hermes update` ran, so
an old packaged Desktop could age-delete the marker 20 minutes into the R6
release wait (round 5 D18). The refresher now lives from the claim until
the release is decided (posix.sh), and the Windows heartbeat ticks inside
Invoke-MarkerRelease's wait. Tests shorten the cadence with the test-only
--self-test-refresh-every argument.

(cherry picked from commit 8339b25e9cfbd13f9f3e8f606e703d994b8b5410)
2026-10-06 05:44:21 -07:00
Teknium
b802f677b5 fix: windows hand-off keeps the marker while the checkout lock is held (R6)
Release waits (bounded) while any process still holds the checkout lock's
byte (hermes_cli/update_lock.py takes it with msvcrt.locking at 1 MiB), and
-MarkerOp reclaim answers `held` instead of freeing a dead marker in that
state, so a Desktop gate never opens over a surviving completion. posix.sh
withdraw now keeps a dead adopter's claim (`foreign`), like marker.ps1.

(cherry picked from commit 8a5525d26f036a3c4b5176f11ee4a590c746e2db)
2026-10-06 05:44:21 -07:00
Teknium
a9f8800511 fix(desktop-update): probe .cmd launchers through cmd.exe /d /s /c
Invoke-HermesProbe handed a .cmd launcher to Process.Start with
UseShellExecute=false, letting CreateProcess pick the interpreter and
re-parse the arguments. Run it through ComSpec explicitly like the update
step does, and refuse arguments cmd.exe cannot be made to take literally.

(cherry picked from commit 0b24aab96962535268d71711c0ef564e01ac6e11)
2026-10-06 05:44:21 -07:00
Teknium
8fb5c3b536 fix(desktop-update): A7 marker lock and hand-off protocol 2 on Windows
Every marker mutation (reclaim, adopt, delegate, release/hand-over,
withdraw, line-2 refresh) now happens inside one hold of
[IO.File]::Open("<marker>.lock", OpenOrCreate, ReadWrite, None), retried
for 10 s then BUSY (claim refused). Read->judge->mutate all inside the
hold; the sidecar is never deleted. Replaces the compare-then-replace /
compare-then-delete helpers.

- parser/judge per tests/fixtures/update_marker_corpus.json (trimming,
  BOM/CR, u32 pids, pid 0 dead, delegate/run on any line >= 4, own-pid
  exact incarnation, 2 s tolerance, v1 1200 s ceiling)
- release per corpus: owner deletes or hands the claim to a live
  delegate; a delegate releaser drops its line
- -HandoffRun <id>: adopt only the Desktop bridge carrying run:<id>
- -DesktopPid alone (old packaged Desktop): accept its cmd.exe wrapper's
  v1 overwrite by lineage, never by dropping the check
- -MarkerOp reclaim|withdraw: one verdict line, exit 0 (64 usage)
- `# hermes-handoff-protocol: 2`
- the update child is created suspended in a kill-on-close job, named as
  the delegate under the lock, then resumed: no update instruction runs
  before (or without) the delegate line
- line 2 refreshed every 5 min while the child runs (old readers)
- the job helper moves to update-job.ps1 (windows.ps1 < 2000 lines)

(cherry picked from commit 8bdf467c768da314ce7817f114a6b1b154e11154)
2026-10-06 05:44:21 -07:00