The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: posix hand-off decides every marker mutation under the A7 lock (protocol 2)
Tekniuma0f2dc903ea2
diff --git a/scripts/desktop-update/marker.sh b/scripts/desktop-update/marker.shnew file mode 100644index 00000000000..1b9db056236--- /dev/null+++ b/scripts/desktop-update/marker.sh@@ -0,0 +1,502 @@+# marker.sh -- the update marker for posix.sh, which sources it. Bash 3.2+# (macOS /bin/bash) compatible: no associative arrays, no {fd} redirections.+#+# The caller defines MARKER (the marker path), INSTALL_ROOT, DESKTOP_PID,+# HANDOFF_RUN, STARTED_AT and log(). Tests source this file on its own.+#+# Body (every reader parses it the same way; the shared corpus+# tests/fixtures/update_marker_corpus.json is the contract):+#+# <pid>\n<started_at>\nct:<creation time>\n[delegate:<pid> ct:<ct>\n][run:<id>\n]+#+# Each line drops one leading BOM (line 1), one trailing CR and surrounding+# spaces/tabs. Line 1 (a u32 pid) and line 2 (an integer) are required, else+# the marker is MALFORMED. A line 3 that is not `ct:<n>` makes it v1. Lines 4++# are tagged: the first well-formed `delegate:<pid> ct:<n>` and the first+# well-formed `run:<id>` count; anything else is ignored.+#+# Identity: (pid, creation time). Our own pid is ours only at our exact+# creation time (5 ms: the marker rounds to 3 decimals); a no-ct claim naming+# our pid is a previous incarnation. Any other pid matches within 2 s; with no+# recorded or readable creation time it is live only within 20 minutes of+# line 2.+#+# Mutation (A7): every read -> judge -> write/delete of the marker happens+# while holding an exclusive kernel lock on the sidecar "$MARKER.lock" (flock+# on the open file description of fd 9, through flock(1) or perl's Fcntl,+# which ships with macOS). The sidecar is never deleted. Busy for 10 s, or no+# lock tool at all, fails closed.++MARKER_CT_RE='^ct:([0-9]+(\.[0-9]+)?)$'+MARKER_DELEGATE_RE='^delegate:([0-9]+) ct:([0-9]+(\.[0-9]+)?)$'+MARKER_RUN_RE='^run:([A-Za-z0-9._-]{1,128})$'+MARKER_LOCK_TOOL="${MARKER_LOCK_TOOL:-}"+MY_PID="${MY_PID:-$$}"+MY_CT="${MY_CT:-}"++# ── process identity ─────────────────────────────────────────────────────────+proc_ct() { # pid -> creation time (unix seconds, 3 decimals), or nothing+ local pid="$1" stat rest start btime hz lstart secs+ [ "$pid" -gt 0 ] 2>/dev/null || return 0+ if [ -r "/proc/$pid/stat" ]; then+ stat="$(cat "/proc/$pid/stat" 2>/dev/null)" || return 0+ rest="${stat##*) }" # comm may hold spaces/parens; fields resume after the last ") "+ start="$(printf '%s\n' "$rest" | awk '{print $20}')" # field 22 overall+ btime="$(awk '/^btime /{print $2}' /proc/stat 2>/dev/null)"+ hz="$(getconf CLK_TCK 2>/dev/null)"+ [ -n "$start" ] && [ -n "$btime" ] && [ -n "$hz" ] || return 0+ awk -v b="$btime" -v s="$start" -v h="$hz" 'BEGIN{printf "%.3f\n", b + s / h}'+ elif [ "$(uname)" = "Darwin" ]; then+ # ps prints lstart in local time: render AND parse it in UTC so a DST+ # fall-back hour cannot shift the identity by 3600 s.+ lstart="$(TZ=UTC0 LC_ALL=C ps -o lstart= -p "$pid" 2>/dev/null | sed 's/^ *//;s/ *$//')"+ [ -n "$lstart" ] || return 0+ secs="$(TZ=UTC0 LC_ALL=C date -j -f '%a %b %e %T %Y' "$lstart" +%s 2>/dev/null)" || return 0+ [ -n "$secs" ] && printf '%s.000\n' "$secs"+ fi+}++pid_alive() { # pid exists and is not a zombie+ local pid="$1" st+ [ "$pid" -gt 0 ] 2>/dev/null || return 1+ st="$(ps -o stat= -p "$pid" 2>/dev/null | tr -d '[:space:]')"+ [ -n "$st" ] && [ "${st#Z}" = "$st" ]+}++pid_parent() { # pid -> parent pid, or nothing+ ps -o ppid= -p "$1" 2>/dev/null | tr -d '[:space:]'+}++ct_close() { # a b tolerance -> 0 iff |a - b| <= tolerance+ awk -v a="$1" -v b="$2" -v t="$3" 'BEGIN{d=a-b; if (d<0) d=-d; exit !(d<=t)}'+}++marker_now() { date +%s; }++ident_state() { # pid recorded-ct -> 0 same process, 1 gone/reused, 2 alive but a ct is unknown+ local pid="$1" want="${2:-}" have+ pid_alive "$pid" || return 1+ [ -n "$want" ] || return 2+ have="$(proc_ct "$pid")"+ [ -n "$have" ] || return 2+ ct_close "$want" "$have" 2.0+}++ident_alive() { # pid recorded-ct -> 0 iff that process may still be running (unknown counts)+ ident_state "$1" "${2:-}"; [ $? -ne 1 ]+}++marker_identity() { # pid recorded-ct age -> 0 OURS, 1 DEAD, 2 LIVE (another process)+ local pid="$1" want="${2:-}" age="$3" have+ [ "$pid" -gt 0 ] 2>/dev/null || return 1+ if [ "$pid" = "$MY_PID" ]; then+ [ -n "$MY_CT" ] || MY_CT="$(proc_ct "$MY_PID")"+ [ -n "$want" ] && [ -n "$MY_CT" ] && ct_close "$want" "$MY_CT" 0.005 && return 0+ return 1+ fi+ pid_alive "$pid" || return 1+ have=""+ [ -z "$want" ] || have="$(proc_ct "$pid")"+ if [ -z "$want" ] || [ -z "$have" ]; then+ [ "$age" -le 1200 ] && return 2+ return 1+ fi+ ct_close "$want" "$have" 2.0 && return 2+ return 1+}++# ── parsing and judging ──────────────────────────────────────────────────────+marker_u32() { # digits -> U32 (leading zeros dropped) iff it fits an unsigned 32-bit pid+ local n="${1#"${1%%[!0]*}"}"+ n="${n:-0}"+ if [ "${#n}" -gt 10 ] || { [ "${#n}" -eq 10 ] && [[ "$n" > 4294967295 ]]; }; then return 1; fi+ U32="$n"+}++marker_line() { # raw line -> LINE without one trailing CR and surrounding spaces/tabs+ LINE="${1%$'\r'}"+ LINE="${LINE#"${LINE%%[![:blank:]]*}"}"+ LINE="${LINE%"${LINE##*[![:blank:]]}"}"+}++M_PID="" M_STARTED="" M_CT="" M_DPID="" M_DCT="" M_RUN="" M_RUNS=""+marker_parse() { # marker text -> M_* fields. M_PID="" = MALFORMED.+ local raw n=0 l1="" l2="" dpid dct+ M_PID="" M_STARTED="" M_CT="" M_DPID="" M_DCT="" M_RUN="" M_RUNS=""+ while IFS= read -r raw || [ -n "$raw" ]; do+ n=$((n + 1))+ [ "$n" -ne 1 ] || raw="${raw#$'\357\273\277'}"+ marker_line "$raw"+ case "$n" in+ 1) l1="$LINE" ;;+ 2) l2="$LINE" ;;+ 3) if [[ "$LINE" =~ $MARKER_CT_RE ]]; then M_CT="${BASH_REMATCH[1]}"; fi ;;+ *)+ if [ -z "$M_DPID" ] && [[ "$LINE" =~ $MARKER_DELEGATE_RE ]]; then+ dpid="${BASH_REMATCH[1]}" dct="${BASH_REMATCH[2]}"+ if marker_u32 "$dpid"; then M_DPID="$U32" M_DCT="$dct"; fi+ elif [[ "$LINE" =~ $MARKER_RUN_RE ]]; then+ [ -n "$M_RUN" ] || M_RUN="${BASH_REMATCH[1]}"+ M_RUNS="$M_RUNS$LINE"$'\n'+ fi ;;+ esac+ done <<EOF_MARKER+$1+EOF_MARKER+ case "$l1" in ''|*[!0-9]*) return 0 ;; esac+ case "$l2" in ''|*[!0-9]*) return 0 ;; esac+ marker_u32 "$l1" || return 0+ M_STARTED="${l2#"${l2%%[!0]*}"}"+ M_STARTED="${M_STARTED:-0}"+ [ "${#M_STARTED}" -le 18 ] || M_STARTED=999999999999999999 # far future: "young"+ M_PID="$U32"+}++# marker text -> J_VERDICT (malformed|dead|ours|live), J_OWNER (the live owner,+# else the live delegate, else ""), J_OWNER_STATE / J_DELEGATE_STATE (0 ours,+# 1 dead/absent, 2 live), plus the M_* fields.+marker_judge() {+ local age+ marker_parse "$1"+ J_OWNER="" J_OWNER_STATE=1 J_DELEGATE_STATE=1+ if [ -z "$M_PID" ]; then J_VERDICT=malformed; return 0; fi+ age=$(( $(marker_now) - M_STARTED ))+ marker_identity "$M_PID" "$M_CT" "$age"; J_OWNER_STATE=$?+ if [ -n "$M_DPID" ]; then marker_identity "$M_DPID" "$M_DCT" "$age"; J_DELEGATE_STATE=$?; fi+ if [ "$J_OWNER_STATE" -ne 1 ]; then J_OWNER="$M_PID"+ elif [ "$J_DELEGATE_STATE" -ne 1 ]; then J_OWNER="$M_DPID"+ fi+ if [ "$J_OWNER_STATE" -eq 0 ] || [ "$J_DELEGATE_STATE" -eq 0 ]; then J_VERDICT=ours+ elif [ -n "$J_OWNER" ]; then J_VERDICT=live+ else J_VERDICT=dead+ fi+}++marker_live() { # marker text -> 0 iff someone (us included) still owns it+ marker_judge "$1"+ [ "$J_VERDICT" = live ] || [ "$J_VERDICT" = ours ]+}++marker_canonical() { # pid started ct-text [delegate-pid delegate-ct] -> body, run lines kept+ local body="$1"$'\n'"$2"$'\n'+ [ -z "$3" ] || body="${body}ct:$3"$'\n'+ [ -z "${4:-}" ] || body="${body}delegate:$4 ct:$5"$'\n'+ printf '%s%s' "$body" "$M_RUNS"+}++# ── A7: the sidecar kernel lock ──────────────────────────────────────────────+marker_lock_tool() {+ if [ -z "$MARKER_LOCK_TOOL" ]; then+ if command -v flock >/dev/null 2>&1; then MARKER_LOCK_TOOL=flock+ elif command -v perl >/dev/null 2>&1; then MARKER_LOCK_TOOL=perl+ else MARKER_LOCK_TOOL=none+ fi+ fi+}++fd_flock() { # fd wait-seconds -> 0 iff an exclusive flock is now held on that fd's open file+ # description (it outlives the helper process: the shell still holds the fd).+ marker_lock_tool+ case "$MARKER_LOCK_TOOL" in+ flock) if [ "$2" -gt 0 ]; then flock -x -w "$2" "$1"; else flock -x -n "$1"; fi ;;+ perl)+ perl -MFcntl=:flock -e '+ open(my $f, "+<&=", $ARGV[0]) or open($f, "<&=", $ARGV[0]) or exit 2;+ my $tries = $ARGV[1] * 10;+ for (my $i = 0; ; $i++) {+ exit 0 if flock($f, LOCK_EX | LOCK_NB);+ exit 1 if $i >= $tries;+ select(undef, undef, undef, 0.1);+ }' "$1" "$2" ;;+ *) return 1 ;;+ esac+}++marker_locked() { # fn args... -> runs fn holding the A7 lock; 75 when the lock is busy+ local rc+ if ! { exec 9>>"$MARKER.lock"; } 2>/dev/null; then+ log "WARNING: cannot open the update marker lock $MARKER.lock"; return 75+ fi+ if ! fd_flock 9 10; then+ exec 9>&-+ log "update marker lock is busy (or no flock/perl to take it): treating the marker as owned"+ return 75+ fi+ "$@"; rc=$?+ exec 9>&-+ return $rc+}++# ── mutations (call ONLY through marker_locked) ──────────────────────────────+marker_read() { # -> SEEN, return 1 when there is no marker+ [ -e "$MARKER" ] || return 1+ SEEN="$(cat "$MARKER" 2>/dev/null)"+}++marker_replace() { # body -> atomic replace (we hold the lock, so nobody judged in between)+ local tmp="$MARKER.$$.tmp"+ printf '%s' "$1" > "$tmp" 2>/dev/null && mv -f "$tmp" "$MARKER" 2>/dev/null && return 0+ rm -f "$tmp" 2>/dev/null+ return 1+}++marker_publish_new() { # body -> 0 iff we created the marker (never replaces one)+ local tmp="$MARKER.$$.tmp" rc+ printf '%s' "$1" > "$tmp" 2>/dev/null || { rm -f "$tmp" 2>/dev/null; return 2; }+ ln "$tmp" "$MARKER" 2>/dev/null; rc=$? # link(2) is an atomic no-replace create+ rm -f "$tmp" 2>/dev/null+ return $rc+}++marker_young_empty() { # A3 fallback writers create then write: a fresh empty file is a claim in flight+ local mtime+ [ -f "$MARKER" ] && [ ! -s "$MARKER" ] || return 1+ mtime="$(stat -c %Y "$MARKER" 2>/dev/null || stat -f %m "$MARKER" 2>/dev/null)" || return 1+ [ -n "$mtime" ] && [ $(( $(marker_now) - mtime )) -lt 5 ]+}++marker_own_body() { # started -> our canonical claim (run line = the Desktop's hand-off run)+ [ -n "$MY_CT" ] || MY_CT="$(proc_ct "$MY_PID")"+ M_RUNS=""+ [ -z "$HANDOFF_RUN" ] || M_RUNS="run:$HANDOFF_RUN"$'\n'+ MARKER_BODY="$(marker_canonical "$MY_PID" "$1" "$MY_CT")"$'\n'+}++marker_ancestor() { # pid -> 0 iff it is one of our ancestors+ local p="$MY_PID" i+ for i in 1 2 3 4 5 6 7 8; do+ p="$(pid_parent "$p")"+ case "$p" in ''|0|1) return 1 ;; esac+ [ "$p" = "$1" ] && return 0+ done+ return 1+}++marker_old_desktop_bridge() { # an OLD Desktop's bridge: "<launcher pid>\n<started_at>\n"+ # written over the marker right after it spawned the launcher that started us+ # (be3fd671d70 checkout.ts). Proven by lineage, never assumed: the named pid+ # is our parent and the Desktop's child, or -- once it has exited -- the+ # marker carries the hand-off's own HERMES_UPDATE_STARTED_AT (the old+ # Desktop writes the same value to both; a Desktop that already quit leaves+ # its launcher re-parented, so either proof suffices while it is alive).+ local x="$M_PID" same_start=1+ [ "$x" != "$DESKTOP_PID" ] && [ -z "$M_CT" ] && [ -z "$M_DPID" ] || return 1+ [ -n "${HERMES_UPDATE_STARTED_AT:-}" ] \+ && [ "$M_STARTED" = "${HERMES_UPDATE_STARTED_AT#"${HERMES_UPDATE_STARTED_AT%%[!0]*}"}" ] && same_start=0+ if pid_alive "$x"; then+ [ "$x" = "$(pid_parent "$MY_PID")" ] || return 1+ [ "$(pid_parent "$x")" = "$DESKTOP_PID" ] || [ "$same_start" -eq 0 ]+ else+ [ "$same_start" -eq 0 ]+ fi+}++marker_take() { # how started -> replace or create our claim; 0 ok, 2 unwritable+ marker_own_body "$2"+ if [ "$1" = new ]; then+ marker_publish_new "$MARKER_BODY"+ case $? in 0) ;; 2) return 2 ;; *) return 1 ;; esac+ else+ marker_replace "$MARKER_BODY" || return 2+ fi+ MARKER_CLAIMED=1+}++# Claim protocol (hand-off protocol 2, see SPEC in the Round 5 report):+# --handoff-run R adopt ONLY the Desktop's live bridge carrying run:R;+# --desktop-pid P (no run: an older Desktop) adopt its bridge by lineage, or+# claim afresh when the Desktop is our ancestor;+# neither claim: reclaim a dead marker, refuse a live one.+# 0 claimed/adopted, 1 refused (MARKER_REFUSED_PID), 2 claim unwritable.+marker_claim_locked() {+ local verdict=absent+ if marker_read; then+ if [ -z "$SEEN" ] && marker_young_empty; then MARKER_REFUSED_PID=unknown; return 1; fi+ marker_judge "$SEEN"; verdict="$J_VERDICT"+ fi+ if [ -n "$HANDOFF_RUN" ]; then+ if [ "$verdict" = live ] && [ "$M_PID" = "$DESKTOP_PID" ] && [ "$J_OWNER_STATE" -eq 2 ] \+ && [ -n "$M_CT" ] && [ "$M_RUN" = "$HANDOFF_RUN" ] && [ "$J_DELEGATE_STATE" -eq 1 ]; then+ STARTED_AT="$M_STARTED" # one acquisition time for the whole chain+ marker_take replace "$M_STARTED" || return 2+ log "adopted the Desktop's update marker (desktop pid $DESKTOP_PID -> $MY_PID, run $HANDOFF_RUN)"+ return 0+ fi+ log "update marker is not the live bridge of desktop pid $DESKTOP_PID run $HANDOFF_RUN ($verdict): exiting without claiming"+ MARKER_REFUSED_PID="${J_OWNER:-${M_PID:-$DESKTOP_PID}}"+ return 1+ fi+ if [ "$DESKTOP_PID" -gt 0 ] 2>/dev/null; then+ if [ "$verdict" = live ] && [ "$J_OWNER" = "$M_PID" ] && [ "$J_DELEGATE_STATE" -eq 1 ] \+ && { [ "$M_PID" = "$DESKTOP_PID" ] || marker_old_desktop_bridge; }; then+ STARTED_AT="$M_STARTED"+ marker_take replace "$M_STARTED" || return 2+ log "adopted the Desktop's update marker (desktop pid $DESKTOP_PID, bridge pid $M_PID -> $MY_PID)"+ return 0+ fi+ case "$verdict" in+ dead|malformed|absent)+ if [ "$verdict" = dead ] && marker_old_desktop_bridge; then+ STARTED_AT="$M_STARTED"+ marker_take replace "$M_STARTED" || return 2+ log "adopted the Desktop's update marker (exited bridge pid $M_PID -> $MY_PID)"+ return 0+ fi+ if ! marker_ancestor "$DESKTOP_PID"; then+ log "no update marker from desktop pid $DESKTOP_PID and it did not start us: exiting without claiming"+ MARKER_REFUSED_PID="${M_PID:-$DESKTOP_PID}"+ return 1+ fi ;;+ esac+ fi+ case "$verdict" in+ live) MARKER_REFUSED_PID="$J_OWNER"; return 1 ;;+ ours) MARKER_BODY="$SEEN"$'\n'; MARKER_CLAIMED=1; return 0 ;;+ dead|malformed)+ rm -f "$MARKER" 2>/dev/null+ log "reclaimed a dead update marker (pid ${M_PID:-?})" ;;+ esac+ marker_take new "$STARTED_AT"+ case $? in+ 0) log "claimed update marker (pid $MY_PID${MY_CT:+ ct $MY_CT})"; return 0 ;;+ 2) return 2 ;;+ esac+ MARKER_REFUSED_PID=unknown+ return 1+}++marker_claim() { # FIRST action of the daemon. Sets MARKER_BODY/CLAIMED.+ marker_locked marker_claim_locked+ case $? in+ 0) return 0 ;;+ 2) log "WARNING: could not write update marker"; return 0 ;;+ 75) MARKER_REFUSED_PID="${MARKER_REFUSED_PID:-unknown}"; return 1 ;;+ *) return 1 ;;+ esac+}++marker_add_delegate_locked() { # pid ct -> name the update child as line 4 under OUR claim+ marker_read || return 0+ marker_judge "$SEEN"+ if [ "$M_PID" != "$MY_PID" ] || [ "$J_OWNER_STATE" -ne 0 ]; then+ log "update marker is no longer ours; no delegate written"; return 0+ fi+ if [ -n "$M_DPID" ] && [ "$M_DPID" != "$1" ] && [ "$J_DELEGATE_STATE" -eq 2 ]; then return 0; fi+ marker_replace "$(marker_canonical "$M_PID" "$M_STARTED" "$M_CT" "$1" "$2")"$'\n' \+ && log "update marker names update pid $1 (ct $2) as its delegate"+}++marker_add_delegate() { # pid -> line 4 `delegate:<pid> ct:<ct>` (C1 rule 6)+ local ct+ [ "$MARKER_CLAIMED" -eq 1 ] || return 0+ ct="$(proc_ct "$1")"+ [ -n "$ct" ] || { log "WARNING: no creation time for update pid $1; marker names no delegate"; return 0; }+ marker_locked marker_add_delegate_locked "$1" "$ct"+}++marker_refresh_locked() { # old packaged Desktops age a marker on line 2 (20 min) and then+ # DELETE it, live owner or not. While we still own it, keep line 2 young.+ marker_read || return 0+ marker_judge "$SEEN"+ [ "$M_PID" = "$MY_PID" ] && [ "$J_OWNER_STATE" -eq 0 ] || return 0+ if [ "$J_DELEGATE_STATE" -eq 1 ]; then M_DPID="" M_DCT=""; fi+ marker_replace "$(marker_canonical "$M_PID" "$(marker_now)" "$M_CT" "$M_DPID" "$M_DCT")"$'\n'+}++marker_release_locked() { # A7 rule 5 / corpus "release"+ marker_read || return 0+ marker_judge "$SEEN"+ [ -n "$M_PID" ] || return 0+ if [ "$M_PID" = "$MY_PID" ] && [ "$J_OWNER_STATE" -eq 0 ]; then+ if [ -n "$M_DPID" ] && [ "$M_DPID" != "$MY_PID" ] && [ "$J_DELEGATE_STATE" -eq 2 ]; then+ marker_replace "$(marker_canonical "$M_DPID" "$M_STARTED" "$M_DCT")"$'\n'+ log "handed the update marker to its live delegate pid $M_DPID (hermes update)"+ else+ rm -f "$MARKER" 2>/dev/null+ fi+ return 0+ fi+ if [ "$M_DPID" = "$MY_PID" ] && [ "$J_DELEGATE_STATE" -eq 0 ]; then+ if [ "$J_OWNER_STATE" -ne 1 ]; then+ marker_replace "$(marker_canonical "$M_PID" "$M_STARTED" "$M_CT")"$'\n'+ else+ rm -f "$MARKER" 2>/dev/null+ fi+ return 0+ fi+ log "leaving update marker: no longer ours"+}++# ── the checkout lock (hermes_cli/update_lock.py::checkout_lock_path) ────────+checkout_lock_path() {+ local root="$INSTALL_ROOT" dot="$INSTALL_ROOT/.git" gitdir line common+ if [ -d "$dot" ]; then+ gitdir="$dot"+ elif [ -f "$dot" ]; then+ IFS= read -r line < "$dot" || [ -n "$line" ] || { printf '%s\n' "$root/.hermes-update.lock"; return; }+ line="${line#$'\357\273\277'}"; marker_line "$line"; line="$LINE"+ case "$line" in gitdir:*) ;; *) printf '%s\n' "$root/.hermes-update.lock"; return ;; esac+ marker_line "${line#gitdir:}"; gitdir="$LINE"+ case "$gitdir" in /*) ;; *) gitdir="$root/$gitdir" ;; esac+ else+ printf '%s\n' "$root/.hermes-update.lock"; return+ fi+ if [ -f "$gitdir/commondir" ]; then+ IFS= read -r common < "$gitdir/commondir" || [ -n "$common" ]+ common="${common#$'\357\273\277'}"; marker_line "$common"; common="$LINE"+ case "$common" in /*) gitdir="$common" ;; '') ;; *) gitdir="$gitdir/$common" ;; esac+ fi+ printf '%s\n' "$gitdir/hermes-update.lock"+}++checkout_lock_held() { # 0 iff some process holds the checkout kernel lock right now+ local path rc+ path="$(checkout_lock_path)"+ [ -f "$path" ] || return 1+ { exec 8<"$path"; } 2>/dev/null || return 1+ fd_flock 8 0; rc=$?+ exec 8<&- # closing our probe releases it when we did get it+ [ "$rc" -eq 1 ]+}++# ── helper ops for the Desktop (it never mutates the marker itself) ──────────+marker_op_reclaim_locked() {+ marker_read || { echo absent; return 0; }+ if [ -z "$SEEN" ] && marker_young_empty; then echo busy; return 0; fi+ marker_judge "$SEEN"+ case "$J_VERDICT" in+ live|ours) echo "live $J_OWNER" ;;+ *)+ if checkout_lock_held; then echo held; return 0; fi+ rm -f "$MARKER" 2>/dev/null+ log "reclaimed a dead update marker for the Desktop (pid ${M_PID:-?})"+ echo reclaimed ;;+ esac+}++marker_op_withdraw_locked() {+ marker_read || { echo absent; return 0; }+ marker_judge "$SEEN"+ if [ -z "$M_PID" ] || [ "$M_RUN" != "$HANDOFF_RUN" ]; then echo foreign; return 0; fi+ if [ "$M_PID" != "$DESKTOP_PID" ] && [ "$J_OWNER_STATE" -eq 2 ]; then echo "taken $M_PID"; return 0; fi+ if [ "$M_PID" = "$DESKTOP_PID" ] || [ "$J_VERDICT" = dead ]; then+ rm -f "$MARKER" 2>/dev/null+ log "withdrew the Desktop's hand-off marker (run $HANDOFF_RUN)"+ echo withdrawn; return 0+ fi+ echo foreign+}++marker_op() { # reclaim | withdraw -> one verdict line on stdout+ local rc+ case "$1" in+ reclaim) marker_locked marker_op_reclaim_locked ;;+ withdraw)+ [ -n "$HANDOFF_RUN" ] && [ "$DESKTOP_PID" -gt 0 ] 2>/dev/null || { echo "withdraw needs --handoff-run and --desktop-pid" >&2; return 64; }+ marker_locked marker_op_withdraw_locked ;;+ *) echo "unknown --marker-op: $1" >&2; return 64 ;;+ esac+ rc=$?+ [ "$rc" -ne 75 ] || { echo busy; rc=0; }+ return $rc+}diff --git a/scripts/desktop-update/posix.sh b/scripts/desktop-update/posix.shindex 45dc6770268..6e521a46b1d 100755--- a/scripts/desktop-update/posix.sh+++ b/scripts/desktop-update/posix.sh@@ -13,6 +13,10 @@# --install-root <path> repo checkout (HERMES_HOME/hermes-agent)# [--branch <ref> | --channel stable|canary|main] default: branch main# --desktop-pid <pid> the Electron main process to wait out+# [--handoff-run <id>] hand-off protocol 2: adopt ONLY the Desktop's+# bridge marker carrying `run:<id>`+# [--marker-op reclaim|withdraw] the Desktop's marker helper: one verdict+# line on stdout, no update (see marker.sh)# [--relaunch-target <p>] mac: running .app to swap+reopen;# linux: running binary (omit = no relaunch)# [--relaunch-cwd <p>] linux: working directory to restore on relaunch@@ -29,6 +33,9 @@# no renderer exists. No chromium-family browser found = no UI, fine; macOS# never opens one (see find_browser).#+# The Desktop reads the next line to pick the hand-off protocol it speaks.+# hermes-handoff-protocol: 2+## ORDERING (the durable-truth rule): swap and relaunch are DECIDED AND# EXECUTED before the result file is written, the marker is removed, or a# terminal event reaches the shim. Nothing user-visible may claim an outcome@@ -43,7 +50,7 @@ RELAUNCH_CWD="" SANDBOX_FALLBACK=0 RELAUNCH_ARGS=()NO_GATEWAY=0NO_UI=0 NO_MARKER_CLEANUP=0 SELF_TEST_UI=0 SELF_TEST_GATE=0 SELF_TEST_MARKER=0SELF_TEST_TCC_HEAL=0-HANDOFF_DAEMONIZED=0+HANDOFF_DAEMONIZED=0 HANDOFF_RUN="" MARKER_OP=""while [ $# -gt 0 ]; docase "$1" in--install-root) INSTALL_ROOT="$2"; shift 2 ;;@@ -55,6 +62,8 @@ while [ $# -gt 0 ]; doesacshift 2 ;;--desktop-pid) DESKTOP_PID="$2"; shift 2 ;;+ --handoff-run) HANDOFF_RUN="$2"; shift 2 ;;+ --marker-op) MARKER_OP="$2"; NO_UI=1; shift 2 ;;--relaunch-target) RELAUNCH_TARGET="$2"; shift 2 ;;--relaunch-cwd) RELAUNCH_CWD="$2"; shift 2 ;;--sandbox-fallback) SANDBOX_FALLBACK=1; shift ;;@@ -71,6 +80,8 @@ while [ $# -gt 0 ]; doesacdone[ "$SELF_TEST_UI" -eq 1 ] || [ -n "$INSTALL_ROOT" ] || { echo "--install-root is required" >&2; exit 64; }+case "$DESKTOP_PID" in ''|*[!0-9]*) echo "--desktop-pid must be a pid" >&2; exit 64 ;; esac+[ -z "$HANDOFF_RUN" ] || [[ "$HANDOFF_RUN" =~ ^[A-Za-z0-9._-]{1,128}$ ]] || { echo "--handoff-run must match [A-Za-z0-9._-]{1,128}" >&2; exit 64; }[ "$BRANCH_EXPLICIT" -eq 0 ] || [ -z "$CHANNEL" ] || { echo "--branch and --channel are mutually exclusive" >&2; exit 64; }TARGET_ARGS=(--branch "$BRANCH")[ -z "$CHANNEL" ] || TARGET_ARGS=(--channel "$CHANNEL")@@ -93,209 +104,57 @@ DONE_NOTE="" # set when the update succeeded but the app will NOT reopen itself# result stays ok:true (contract C3: ok:false only while still on the previous# version); each entry reaches the Desktop as a warning.WARNINGS=()-MARKER_BODY="" # the exact bytes we published; release compares against them+MARKER_BODY="" # the claim we published (logging; release judges identity, not bytes)MARKER_CLAIMED=0APP_REBUILD_FAILED=0-log() { echo "$(date +%Y-%m-%dT%H:%M:%S%z) $1" | tee -a "$LOG" 2>/dev/null; }--# ── process identity (update marker contract C1) ────────────────────────────-# A pid alone is not an identity: the marker records the owner's creation time-# (`ct:` unix seconds, 3 decimals) so a reused pid never reads as the owner.-proc_ct() { # pid -> creation time, or nothing when it cannot be read- local pid="$1" stat rest start btime hz lstart secs- [ "$pid" -gt 0 ] 2>/dev/null || return 0- if [ -r "/proc/$pid/stat" ]; then- stat="$(cat "/proc/$pid/stat" 2>/dev/null)" || return 0- rest="${stat##*) }" # comm may hold spaces/parens; fields resume after the last ") "- start="$(printf '%s\n' "$rest" | awk '{print $20}')" # field 22 overall- btime="$(awk '/^btime /{print $2}' /proc/stat 2>/dev/null)"- hz="$(getconf CLK_TCK 2>/dev/null)"- [ -n "$start" ] && [ -n "$btime" ] && [ -n "$hz" ] || return 0- awk -v b="$btime" -v s="$start" -v h="$hz" 'BEGIN{printf "%.3f\n", b + s / h}'- elif [ "$(uname)" = "Darwin" ]; then- # ps prints lstart in local time: render AND parse it in UTC so a DST- # fall-back hour cannot shift the identity by 3600 s.- lstart="$(TZ=UTC0 LC_ALL=C ps -o lstart= -p "$pid" 2>/dev/null | sed 's/^ *//;s/ *$//')"- [ -n "$lstart" ] || return 0- secs="$(TZ=UTC0 LC_ALL=C date -j -f '%a %b %e %T %Y' "$lstart" +%s 2>/dev/null)" || return 0- [ -n "$secs" ] && printf '%s.000\n' "$secs"- fi-}--pid_alive() { # pid exists and is not a zombie- local pid="$1" st- [ "$pid" -gt 0 ] 2>/dev/null || return 1- st="$(ps -o stat= -p "$pid" 2>/dev/null | tr -d '[:space:]')"- [ -n "$st" ] && [ "${st#Z}" = "$st" ]-}--ident_state() { # pid recorded-ct -> 0 same process, 1 gone/reused, 2 alive but a ct is unknown- local pid="$1" want="${2:-}" have- pid_alive "$pid" || return 1- [ -n "$want" ] || return 2- have="$(proc_ct "$pid")"- [ -n "$have" ] || return 2- awk -v a="$want" -v b="$have" 'BEGIN{d=a-b; if (d<0) d=-d; exit !(d<=2.0)}'-}--ident_alive() { # pid recorded-ct -> 0 iff that process may still be running (unknown counts)- ident_state "$1" "${2:-}"; [ $? -ne 1 ]-}--M_PID="" M_STARTED="" M_CT="" M_DPID="" M_DCT=""-marker_parse() { # marker text -> M_* fields (contract A2). M_PID="" = malformed = dead.- local l1 l2 l3 l4- { IFS= read -r l1; IFS= read -r l2; IFS= read -r l3; IFS= read -r l4; } <<EOF_MARKER-$1-EOF_MARKER- l1="${l1#$'\357\273\277'}" l1="${l1%$'\r'}" l2="${l2%$'\r'}" l3="${l3%$'\r'}" l4="${l4%$'\r'}"- M_PID="$(printf '%s' "$l1" | tr -d '[:space:]')"- M_STARTED="$(printf '%s' "$l2" | tr -d '[:space:]')"- M_CT="" M_DPID="" M_DCT=""- case "$M_PID" in ''|*[!0-9]*) M_PID="" ;; esac- case "$M_STARTED" in ''|*[!0-9]*) M_PID="" M_STARTED="" ;; esac # line 2 not an integer- [[ "$l3" =~ ^ct:([0-9]+(\.[0-9]+)?)$ ]] && M_CT="${BASH_REMATCH[1]}" # else v1- if [[ "$l4" =~ ^delegate:([0-9]+)\ ct:([0-9]+(\.[0-9]+)?)$ ]]; then # else ignored- M_DPID="${BASH_REMATCH[1]}" M_DCT="${BASH_REMATCH[2]}"- fi-}--marker_ident_live() { # pid ct -> 0 iff LIVE: same process, or alive with an unknown ct- # inside the 20-minute ceiling from line 2 (A1: unknown must never mean forever).- ident_state "$1" "$2"- case $? in- 0) return 0 ;;- 2) [ $(( $(date +%s) - M_STARTED )) -le 1200 ] ;;- *) return 1 ;;- esac-}--marker_live() { # marker text -> 0 iff LIVE (owner OR delegate), per contract C1 rule 3/6- marker_parse "$1"- [ -n "$M_PID" ] || return 1- if [ -n "$M_DPID" ] && marker_ident_live "$M_DPID" "$M_DCT"; then return 0; fi- marker_ident_live "$M_PID" "$M_CT"+log() {+ if [ -n "$MARKER_OP" ]; then echo "$(date +%Y-%m-%dT%H:%M:%S%z) $1" >> "$LOG" 2>/dev/null+ else echo "$(date +%Y-%m-%dT%H:%M:%S%z) $1" | tee -a "$LOG" 2>/dev/null; fi}-marker_young_empty() { # A3 fallback writers create then write: a fresh empty file is a claim in flight- local mtime- [ -f "$MARKER" ] && [ ! -s "$MARKER" ] || return 1- mtime="$(stat -c %Y "$MARKER" 2>/dev/null || stat -f %m "$MARKER" 2>/dev/null)" || return 1- [ -n "$mtime" ] && [ $(( $(date +%s) - mtime )) -lt 5 ]-}--marker_publish_new() { # body -> 0 iff we created the marker (never replaces one)- local tmp="$MARKER.$$.tmp" rc- printf '%s' "$1" > "$tmp" 2>/dev/null || { rm -f "$tmp" 2>/dev/null; return 2; }- ln "$tmp" "$MARKER" 2>/dev/null; rc=$? # link(2) is an atomic no-replace create- rm -f "$tmp" 2>/dev/null- return $rc-}--marker_claim() { # FIRST action of the daemon (contract C2). Sets MARKER_BODY/CLAIMED.- # Started with --desktop-pid it only ADOPTS that Desktop's live bridge claim- # (A4): no bridge, or anyone else's marker, means the Desktop already gave- # up on this hand-off, so the run must not start.- local seen attempt ct started adopt_only=0- [ "$DESKTOP_PID" -gt 0 ] 2>/dev/null && adopt_only=1- ct="$(proc_ct $$)"- for attempt in 1 2; do- started="$STARTED_AT"- MARKER_BODY="$$"$'\n'"$started"$'\n'"${ct:+ct:$ct}"$'\n'- [ -n "$ct" ] || MARKER_BODY="$$"$'\n'"$started"$'\n'- if [ "$adopt_only" -eq 0 ]; then- marker_publish_new "$MARKER_BODY"- case $? in- 0) MARKER_CLAIMED=1; log "claimed update marker (pid $$${ct:+ ct $ct})"; return 0 ;;- 2) log "WARNING: could not write update marker"; return 0 ;;- esac- fi- if ! seen="$(cat "$MARKER" 2>/dev/null)"; then- [ "$adopt_only" -eq 1 ] || continue- log "no update marker from the Desktop (pid $DESKTOP_PID): it gave up on this hand-off; exiting without claiming"- MARKER_REFUSED_PID="$DESKTOP_PID"; return 1- fi- if [ -z "$seen" ] && marker_young_empty; then- MARKER_REFUSED_PID="unknown"; return 1- fi- if [ "$adopt_only" -eq 1 ]; then- if marker_live "$seen" && [ "$M_PID" = "$DESKTOP_PID" ] && [ -z "$M_DPID" ]; then- # The Desktop's bridge claim. One acquisition time for the whole- # chain: keep its line 2.- started="$M_STARTED" STARTED_AT="$M_STARTED"- MARKER_BODY="$$"$'\n'"$started"$'\n'"${ct:+ct:$ct}"$'\n'- [ -n "$ct" ] || MARKER_BODY="$$"$'\n'"$started"$'\n'- printf '%s' "$MARKER_BODY" > "$MARKER.$$.tmp" 2>/dev/null || { rm -f "$MARKER.$$.tmp"; return 0; }- if [ "$(cat "$MARKER" 2>/dev/null)" = "$seen" ] && mv -f "$MARKER.$$.tmp" "$MARKER" 2>/dev/null; then- MARKER_CLAIMED=1; log "adopted the Desktop's update marker (desktop pid $DESKTOP_PID -> $$)"; return 0- fi- rm -f "$MARKER.$$.tmp" 2>/dev/null- continue- fi- log "update marker is not the live bridge claim of desktop pid $DESKTOP_PID: exiting without claiming"- MARKER_REFUSED_PID="${M_DPID:-${M_PID:-unknown}}"- return 1- fi- if marker_live "$seen" && [ "$M_PID" != "$$" ]; then- MARKER_REFUSED_PID="${M_DPID:-$M_PID}"- return 1- fi- # Dead owner: compare-and-delete the exact bytes judged dead, then retry.- if [ "$(cat "$MARKER" 2>/dev/null)" = "$seen" ]; then- rm -f "$MARKER" 2>/dev/null- log "reclaimed a dead update marker (pid ${M_PID:-?})"+# The marker (contract C1/C2 + the A7 lock): parsing, identity, claim, delegate,+# release and the Desktop's helper ops live in marker.sh.+MY_PID=$$ MY_CT=""+# shellcheck source=marker.sh+. "$SCRIPT_DIR/marker.sh"++marker_release() { # A7 rule 5, under the lock. Never while a survivor of the+ # update still holds the checkout lock (R6): the marker would read free while+ # that completion still mutates the checkout. Wait it out; past the bound,+ # leave the marker in place -- dead to every reader, and the Desktop's+ # reclaim helper refuses to delete it while the checkout lock is held.+ local waited=0+ [ "$MARKER_CLAIMED" -eq 1 ] && [ "$NO_MARKER_CLEANUP" -eq 0 ] || return 0+ while checkout_lock_held; do+ [ "$waited" -gt 0 ] || log "a process still holds the checkout update lock; keeping the update marker until it exits"+ if [ "$waited" -ge "$RELEASE_WAIT_S" ]; then+ log "WARNING: checkout update lock still held after ${waited}s; leaving the update marker"+ return 0fi+ sleep 1; waited=$((waited + 1))done- MARKER_REFUSED_PID="${M_PID:-unknown}"- return 1-}--marker_release() { # compare-and-delete; never drops a marker whose delegate is LIVE- local now- [ "$MARKER_CLAIMED" -eq 1 ] && [ "$NO_MARKER_CLEANUP" -eq 0 ] || return 0- now="$(cat "$MARKER" 2>/dev/null)" || return 0- case "$now"$'\n' in "$MARKER_BODY"*) ;; *) log "leaving update marker: no longer ours"; return 0 ;; esac- marker_parse "$now"- if [ -n "$M_DPID" ] && marker_ident_live "$M_DPID" "$M_DCT"; then- log "leaving update marker: delegate pid $M_DPID (hermes update) is still running"- return 0- fi- [ "$(cat "$MARKER" 2>/dev/null)" = "$now" ] && rm -f "$MARKER" 2>/dev/null+ marker_locked marker_release_lockedMARKER_CLAIMED=0}--marker_add_delegate() { # pid -> line 4 `delegate:<pid> ct:<ct>` under our claim (C1 rule 6)- # Written the moment the update child exists: killed in the second before- # that child takes the update lock, this script would otherwise leave a- # marker that reads DEAD while the update goes on. Compare-and-swap on our- # own lines 1-3; a marker with no ct line (v1) gets no delegate.- local pid="$1" ct seen tmp="$MARKER.$$.tmp"- [ "$MARKER_CLAIMED" -eq 1 ] || return 0- case "$MARKER_BODY" in *$'\n'ct:*) ;; *) return 0 ;; esac- ct="$(proc_ct "$pid")"- [ -n "$ct" ] || { log "WARNING: no creation time for update pid $pid; marker names no delegate"; return 0; }- seen="$(cat "$MARKER" 2>/dev/null)" || return 0- case "$seen"$'\n' in "$MARKER_BODY"*) ;; *) log "update marker is no longer ours; no delegate written"; return 0 ;; esac- marker_parse "$seen"- if [ -n "$M_DPID" ] && [ "$M_DPID" != "$pid" ] && marker_ident_live "$M_DPID" "$M_DCT"; then return 0; fi- printf '%sdelegate:%s ct:%s\n' "$MARKER_BODY" "$pid" "$ct" > "$tmp" 2>/dev/null || { rm -f "$tmp" 2>/dev/null; return 0; }- if [ "$(cat "$MARKER" 2>/dev/null)" = "$seen" ] && mv -f "$tmp" "$MARKER" 2>/dev/null; then- log "update marker names update pid $pid (ct $ct) as its delegate"- else- rm -f "$tmp" 2>/dev/null- fi-}+RELEASE_WAIT_S=7200run_bounded() { # seconds cmd... -> cmd's stdout; 124 when it had to be killedlocal secs="$1" out pid i rcshiftout="$(mktemp "${TMPDIR:-/tmp}/hermes-update-probe.$$.XXXXXX")" || return 1- "$@" > "$out" 2>/dev/null < /dev/null &+ # Its own process group (pgid = pid), so a timeout kills the probe's whole+ # tree -- a hung `hermes` launcher's python child included, not just the shell.+ if command -v perl >/dev/null 2>&1; then+ perl -e 'setpgrp(0, 0); exec { $ARGV[0] } @ARGV or exit 127' "$@" > "$out" 2>/dev/null < /dev/null &+ else+ "$@" > "$out" 2>/dev/null < /dev/null &+ fipid=$!for ((i = 0; i < secs * 10; i++)); do kill -0 "$pid" 2>/dev/null || break; sleep 0.1; doneif kill -0 "$pid" 2>/dev/null; then- kill -KILL "$pid" 2>/dev/null; wait "$pid" 2>/dev/null+ kill -KILL -- "-$pid" 2>/dev/null || kill -KILL "$pid" 2>/dev/null+ wait "$pid" 2>/dev/nullrm -f "$out" 2>/dev/nulllog "WARNING: probe timed out after ${secs}s: $*"return 124@@ -961,6 +820,13 @@ if [ "$SELF_TEST_UI" -eq 1 ]; thenexit "$FINAL_CODE"fi+# ── the Desktop's marker helper: verdict on stdout, nothing else ────────────+if [ -n "$MARKER_OP" ]; then+ trap - EXIT HUP INT QUIT TERM+ marker_op "$MARKER_OP"+ exit $?+fi+# ── the actual job ──────────────────────────────────────────────────────────# Everything below is ONE brace group: bash parses a compound command whole# before running it, so `hermes update` rewriting this very file (the script@@ -1056,6 +922,7 @@ ficase "$RELAUNCH_TARGET" in *.app) mac_bundle_recover "$RELAUNCH_TARGET" ;; esacfor _stale in "$INSTALL_ROOT"/venv/bin/*.tcc-heal-old.* "$INSTALL_ROOT"/venv/bin/*.tcc-heal-new.* \"${TMPDIR:-/tmp}"/hermes-update-status.[0-9]* "${TMPDIR:-/tmp}"/hermes-update-probe.[0-9]* \+ "${TMPDIR:-/tmp}"/hermes-update-go.[0-9]* \"${TMPDIR:-/tmp}"/hermes-update-ui-[0-9]*-*; do[ -e "$_stale" ] || [ -L "$_stale" ] || continuecase "$_stale" in@@ -1174,20 +1041,37 @@ run_update() { # streams straight into the log (a killed run keeps its output);# OUT = this run's slice of the log. TERM goes back to default for the child# so neither it nor anything it starts (gateways) inherits our SIG_IGN.# The child runs asynchronously only so its pid can go into the marker- # (marker_add_delegate) before it does anything; a HUP/INT/QUIT that lands- # meanwhile is handled once it exits, exactly like a foreground child.- local offset pid sig+ # (marker_add_delegate) before it does anything: it waits on a go-file that+ # is created only AFTER the delegate line is published, and gives up when+ # this script dies first -- so no instant exists in which the update runs+ # but the marker names neither a live owner nor a live delegate. A+ # HUP/INT/QUIT that lands meanwhile is handled once it exits, exactly like a+ # foreground child.+ local offset pid sig go="${TMPDIR:-/tmp}/hermes-update-go.$$" refresheroffset="$(wc -c < "$LOG" 2>/dev/null | tr -d '[:space:]')"PENDING_SIGNAL=""for sig in HUP INT QUIT; do trap "PENDING_SIGNAL=\${PENDING_SIGNAL:-$sig}" "$sig"; done- ( trap - TERM; exec "${UPDATE_INVOKE[@]}" update --yes $GATEWAY_FLAG $KEEP_STASH "${TARGET_ARGS[@]}" ) >> "$LOG" 2>&1 <&0 &+ rm -f "$go" 2>/dev/null+ ( trap - TERM+ while [ ! -e "$go" ]; do kill -0 "$MY_PID" 2>/dev/null || exit 70; sleep 0.05; done+ exec "${UPDATE_INVOKE[@]}" update --yes $GATEWAY_FLAG $KEEP_STASH "${TARGET_ARGS[@]}" ) >> "$LOG" 2>&1 <&0 &pid=$!marker_add_delegate "$pid"+ : > "$go"+ # An older packaged Desktop judges a marker by line 2 alone and deletes it+ # 20 minutes in, live owner or not: keep line 2 young while we own it.+ ( for _ in $(seq 1 100000); do+ for _ in $(seq 1 60); do sleep 5; kill -0 "$MY_PID" 2>/dev/null || exit 0; done+ marker_locked marker_refresh_locked+ done ) >/dev/null 2>&1 &+ refresher=$!while :; dowait "$pid"; CODE=$?[ "$CODE" -ne 127 ] || break # not our child any morekill -0 "$pid" 2>/dev/null || break # reaped: CODE is its exit statusdone+ kill -KILL "$refresher" 2>/dev/null; wait "$refresher" 2>/dev/null+ rm -f "$go" 2>/dev/nullfor sig in HUP INT QUIT; do trap "on_signal $sig" "$sig"; doneOUT="$(tail -c +"$(( ${offset:-0} + 1 ))" "$LOG" 2>/dev/null)"[ -z "$PENDING_SIGNAL" ] || on_signal "$PENDING_SIGNAL"