Skip to content

The agent that grows with you

fix: bash and PowerShell adopt an old Desktop's launcher bridge by one lineage rule

Teknium33cea9a733dc
diff --git a/scripts/desktop-update/marker-claim.ps1 b/scripts/desktop-update/marker-claim.ps1
index 1821ddb61f8..b6db5a5abb6 100644
--- a/scripts/desktop-update/marker-claim.ps1
+++ b/scripts/desktop-update/marker-claim.ps1
@@ -55,6 +55,30 @@ function Invoke-MarkerAdoptRun($Read, [int]$Desktop, [string]$Run) {
return $verdict
}
+# The launcher-lineage rule -- ONE rule, the same in marker.sh
+# (marker_launcher_rule); the shared table is
+# tests/scripts/desktop_update/lineage_rule_cases.py. An OLD Desktop's bridge
+# "<launcher pid>\n<started_at>\n" (v1: no ct, no delegate) names the launcher
+# it spawned (its cmd.exe wrapper) instead of itself. It is adopted iff it does
+# not name the Desktop and
+# the named pid is alive: it is our parent AND (its parent is the Desktop OR
+# line 2 == HERMES_UPDATE_STARTED_AT);
+# the named pid is gone: line 2 == HERMES_UPDATE_STARTED_AT (`start /b`
+# wrappers exit at once).
+function Test-MarkerLauncherRule($Facts) {
+ if (-not $Facts.V1 -or $Facts.NamesDesktop) { return $false }
+ if ($Facts.NamedAlive) { return [bool]($Facts.NamedIsOurParent -and ($Facts.NamedParentIsDesktop -or $Facts.EnvStartedMatches)) }
+ return [bool]$Facts.EnvStartedMatches
+}
+
+function Test-MarkerEnvStartedAt([string]$Line2) {
+ # HERMES_UPDATE_STARTED_AT is plain ASCII digits (no sign, no spaces) of line 2's value.
+ $e = [string]$env:HERMES_UPDATE_STARTED_AT
+ if ($e -cnotmatch '\A[0-9]+\z' -or $Line2 -cnotmatch '\A[0-9]+\z') { return $false }
+ $e = $e.TrimStart('0'); $want = $Line2.TrimStart('0')
+ return $e -ceq $want
+}
+
function Get-MarkerLineage([int]$Desktop, $Info) {
# X = our recorded parent: the old Desktop's cmd.exe wrapper.
$x = Get-ParentProcessId $PID
@@ -64,17 +88,20 @@ function Get-MarkerLineage([int]$Desktop, $Info) {
$xAlive = (Get-LiveProcessCt $x).Alive
if ($xAlive) { $xParent = Get-ParentProcessId $x }
}
- $envStarted = 0L
- $hasEnvStarted = [int64]::TryParse("$env:HERMES_UPDATE_STARTED_AT".Trim(), [ref]$envStarted)
- $namesX = $x -gt 0 -and $Info -and $Info.Pid -eq $x
- $xLineage = $false
- if ($namesX) {
- # Alive: it must still be the Desktop's child. Dead (start /b exits at
- # once): the marker must carry the startedAt the Desktop gave us.
- $xLineage = if ($xAlive) { $xParent -eq $Desktop } else { $hasEnvStarted -and $Info.StartedAt -eq $envStarted }
+ $launcher = $false
+ if ($Info) {
+ $named = [int64]$Info.Pid
+ $namedAlive = if ($named -eq $x) { $xAlive } else { $named -gt 0 -and (Get-LiveProcessCt $named).Alive }
+ $facts = @{
+ V1 = ($null -eq $Info.Ct -and $Info.DelegatePid -le 0); NamesDesktop = ($named -eq $Desktop)
+ NamedAlive = $namedAlive; NamedIsOurParent = ($x -gt 0 -and $named -eq $x)
+ NamedParentIsDesktop = ($namedAlive -and $named -eq $x -and $xParent -eq $Desktop)
+ EnvStartedMatches = (Test-MarkerEnvStartedAt "$($Info.StartedAt)")
+ }
+ $launcher = Test-MarkerLauncherRule $facts
}
return @{
- Parent = $x; ParentAlive = $xAlive; Grandparent = $xParent; LauncherClaim = $xLineage
+ Parent = $x; ParentAlive = $xAlive; Grandparent = $xParent; LauncherClaim = $launcher
Ancestor = ($x -gt 0 -and ($x -eq $Desktop -or ($xAlive -and $xParent -eq $Desktop)))
}
}
diff --git a/scripts/desktop-update/marker.sh b/scripts/desktop-update/marker.sh
index 4bd4efca42c..f5285cbb050 100644
--- a/scripts/desktop-update/marker.sh
+++ b/scripts/desktop-update/marker.sh
@@ -120,10 +120,10 @@ marker_line() { # raw line -> LINE without one trailing CR and surrounding space
LINE="${LINE%"${LINE##*[![:blank:]]}"}"
}
-M_PID="" M_STARTED="" M_CT="" M_DPID="" M_DCT="" M_RUN="" M_RUNS=""
+M_PID="" M_STARTED="" M_STARTED_DIGITS="" 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=""
+ M_PID="" M_STARTED="" M_STARTED_DIGITS="" 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'}"
@@ -149,6 +149,7 @@ EOF_MARKER
marker_u32 "$l1" || return 0
M_STARTED="${l2#"${l2%%[!0]*}"}"
M_STARTED="${M_STARTED:-0}"
+ M_STARTED_DIGITS="$M_STARTED" # exact value (no leading zeros), before the age clamp
[ "${#M_STARTED}" -le 18 ] || M_STARTED=999999999999999999 # far future: "young"
M_PID="$U32"
}
@@ -273,23 +274,47 @@ marker_ancestor() { # pid -> 0 iff it is one of our ancestors
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 ]
+# The launcher-lineage rule -- ONE rule, the same in marker-claim.ps1
+# (Test-MarkerLauncherRule); the shared table is
+# tests/scripts/desktop_update/lineage_rule_cases.py. An OLD Desktop's bridge
+# "<launcher pid>\n<started_at>\n" (v1: no ct, no delegate) names the launcher
+# it spawned (be3fd671d70 checkout.ts) instead of itself. It is adopted iff it
+# does not name the Desktop and
+# the named pid is alive: it is our parent AND (its parent is the Desktop OR
+# line 2 == HERMES_UPDATE_STARTED_AT -- a Desktop
+# that already quit leaves its launcher re-parented);
+# the named pid is gone: line 2 == HERMES_UPDATE_STARTED_AT (the old Desktop
+# hands the launcher the same value it writes).
+# 1/0 facts: v1 names_desktop named_alive named_is_our_parent
+# named_parent_is_desktop env_started_matches -> 0 adopt
+marker_launcher_rule() {
+ [ "$1" = 1 ] && [ "$2" = 0 ] || return 1
+ if [ "$3" = 1 ]; then
+ [ "$4" = 1 ] && { [ "$5" = 1 ] || [ "$6" = 1 ]; }
else
- [ "$same_start" -eq 0 ]
+ [ "$6" = 1 ]
+ fi
+}
+
+marker_env_started_matches() { # line-2 digits -> 0 iff HERMES_UPDATE_STARTED_AT is plain ASCII
+ # digits (no sign, no spaces) of the same value
+ local env="${HERMES_UPDATE_STARTED_AT:-}" want="${1#"${1%%[!0]*}"}"
+ case "$env" in ''|*[!0-9]*) return 1 ;; esac
+ env="${env#"${env%%[!0]*}"}"
+ [ "${env:-0}" = "${want:-0}" ]
+}
+
+marker_old_desktop_bridge() { # the parsed marker is an OLD Desktop's launcher bridge (rule above)
+ local x="$M_PID" v1=0 names_desktop=0 alive=0 is_parent=0 parent_desktop=0 env_match=0
+ [ -n "$M_CT" ] || [ -n "$M_DPID" ] || v1=1
+ [ "$x" != "$DESKTOP_PID" ] || names_desktop=1
+ marker_env_started_matches "$M_STARTED_DIGITS" && env_match=1
+ if pid_alive "$x"; then
+ alive=1
+ [ "$x" != "$(pid_parent "$MY_PID")" ] || is_parent=1
+ [ "$(pid_parent "$x")" != "$DESKTOP_PID" ] || parent_desktop=1
fi
+ marker_launcher_rule "$v1" "$names_desktop" "$alive" "$is_parent" "$parent_desktop" "$env_match"
}
marker_take() { # how started -> replace or create our claim; 0 ok, 2 unwritable
diff --git a/tests/scripts/desktop_update/lineage_rule_cases.py b/tests/scripts/desktop_update/lineage_rule_cases.py
new file mode 100644
index 00000000000..9b7936ec0ed
--- /dev/null
+++ b/tests/scripts/desktop_update/lineage_rule_cases.py
@@ -0,0 +1,65 @@
+"""The launcher-lineage rule shared by marker.sh (marker_launcher_rule) and
+marker-claim.ps1 (Test-MarkerLauncherRule): one table, every consumer runs it.
+
+An OLD packaged Desktop overwrites the marker with a v1 bridge naming the launcher it
+spawned. Adopted iff the bridge is v1, does not name the Desktop, and
+ named pid alive: it is our parent AND (its parent is the Desktop OR env == line 2);
+ named pid gone: env == line 2.
+"""
+from __future__ import annotations
+
+FACTS = ("v1", "names_desktop", "named_alive", "named_is_our_parent", "named_parent_is_desktop", "env_started_matches")
+
+
+def _case(case_id: str, expect: bool, **facts: bool) -> dict:
+ assert set(facts) == set(FACTS), case_id
+ return {"id": case_id, "facts": facts, "expect": expect}
+
+
+RULE_CASES = [
+ # the old Desktop's own shapes
+ _case("alive_launcher_child_of_desktop", True, v1=True, names_desktop=False, named_alive=True,
+ named_is_our_parent=True, named_parent_is_desktop=True, env_started_matches=False),
+ _case("gone_launcher_env_matches", True, v1=True, names_desktop=False, named_alive=False,
+ named_is_our_parent=False, named_parent_is_desktop=False, env_started_matches=True),
+ # D11 (round 5): bash adopted, PowerShell refused -- the Desktop already quit, so its live
+ # launcher was re-parented, but it carries the hand-off's own startedAt.
+ _case("alive_launcher_reparented_env_matches", True, v1=True, names_desktop=False, named_alive=True,
+ named_is_our_parent=True, named_parent_is_desktop=False, env_started_matches=True),
+ # PowerShell also required the gone launcher to be our recorded parent; POSIX cannot know it.
+ _case("gone_named_pid_not_our_recorded_parent_env_matches", True, v1=True, names_desktop=False,
+ named_alive=False, named_is_our_parent=False, named_parent_is_desktop=False, env_started_matches=True),
+ _case("alive_launcher_reparented_env_differs", False, v1=True, names_desktop=False, named_alive=True,
+ named_is_our_parent=True, named_parent_is_desktop=False, env_started_matches=False),
+ _case("gone_launcher_env_differs", False, v1=True, names_desktop=False, named_alive=False,
+ named_is_our_parent=True, named_parent_is_desktop=True, env_started_matches=False),
+ # an unrelated live process is never adopted, whatever the env says
+ _case("alive_not_our_parent_env_matches", False, v1=True, names_desktop=False, named_alive=True,
+ named_is_our_parent=False, named_parent_is_desktop=True, env_started_matches=True),
+ _case("alive_not_our_parent_child_of_desktop", False, v1=True, names_desktop=False, named_alive=True,
+ named_is_our_parent=False, named_parent_is_desktop=True, env_started_matches=False),
+ # only a v1 bridge: a v2 claim (ct line) or one with a delegate is somebody's real claim.
+ # (PowerShell used to accept these when they named its parent.)
+ _case("v2_claim_naming_our_parent", False, v1=False, names_desktop=False, named_alive=True,
+ named_is_our_parent=True, named_parent_is_desktop=True, env_started_matches=True),
+ _case("v2_claim_gone_env_matches", False, v1=False, names_desktop=False, named_alive=False,
+ named_is_our_parent=False, named_parent_is_desktop=False, env_started_matches=True),
+ # the Desktop's own bridge is not a launcher bridge (it has its own adoption path)
+ _case("names_the_desktop", False, v1=True, names_desktop=True, named_alive=True,
+ named_is_our_parent=True, named_parent_is_desktop=False, env_started_matches=True),
+]
+
+# HERMES_UPDATE_STARTED_AT vs line 2 (its digits as parsed): plain ASCII digits of the same value.
+# (PowerShell used to Trim() and Int64.TryParse the env value: spaces and a sign matched.)
+ENV_CASES = [
+ {"id": "equal", "env": "1791079348", "line2": "1791079348", "expect": True},
+ {"id": "leading_zeros_env", "env": "01791079348", "line2": "1791079348", "expect": True},
+ {"id": "leading_zeros_line2", "env": "1791079348", "line2": "0001791079348", "expect": True},
+ {"id": "zero", "env": "00", "line2": "0", "expect": True},
+ {"id": "different", "env": "1791079349", "line2": "1791079348", "expect": False},
+ {"id": "padded_env", "env": " 1791079348", "line2": "1791079348", "expect": False},
+ {"id": "trailing_space_env", "env": "1791079348 ", "line2": "1791079348", "expect": False},
+ {"id": "signed_env", "env": "+1791079348", "line2": "1791079348", "expect": False},
+ {"id": "empty_env", "env": "", "line2": "1791079348", "expect": False},
+ {"id": "garbage_env", "env": "1791079348x", "line2": "1791079348", "expect": False},
+]
diff --git a/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py b/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py
index fe642fed4aa..e8c540ff6fa 100644
--- a/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py
+++ b/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py
@@ -2,11 +2,14 @@
One or two invariant tests per Round 5 finding:
R3 every marker mutation is decided under the sidecar kernel lock (flock(1) and perl);
- R4 an OLD packaged Desktop's bridge (its launcher's pid, v1) is adopted by lineage only;
+ R4 an OLD packaged Desktop's bridge (its launcher's pid, v1) is adopted by lineage only, by
+ the one launcher rule bash and PowerShell share (lineage_rule_cases.py);
R5 with --handoff-run only the Desktop's live bridge carrying that run is adopted;
R6 the marker outlives a survivor still holding the checkout lock; the Desktop's reclaim
helper answers `held` for it;
- plus the pre-publication kill cell, the process-group probe kill and the line-2 refresh.
+ plus the pre-publication kill cell, the process-group probe kill and the line-2 refresh
+ (also through the R6 release wait), and a checkout-lock probe that never makes a concurrent
+ acquire fail (Round 6).
"""
from __future__ import annotations
@@ -22,6 +25,8 @@ import time
import pytest
+from tests.scripts.desktop_update.lineage_rule_cases import ENV_CASES, RULE_CASES
+from tests.scripts.desktop_update.lineage_rule_cases import FACTS as LINEAGE_FACTS
from tests.scripts.desktop_update.test_desktop_update_posix_marker import POSIX, _calls, _ct, _install
pytestmark = pytest.mark.platforms("linux") # /proc ancestry and creation times
@@ -138,6 +143,44 @@ def test_old_desktop_handoff_never_adopts_an_unrelated_live_claim(tmp_path, proc
assert (home / ".hermes-update-in-progress").read_text(encoding="utf-8-sig") == before
+def test_launcher_lineage_rule_matches_the_shared_table(tmp_path):
+ """One lineage rule for bash and PowerShell (round 5 D11): the same table runs in both."""
+ calls = [f"log() {{ :; }}; MARKER=/dev/null INSTALL_ROOT=/dev/null; . {shlex.quote(str(MARKER_SH))}"]
+ for case in RULE_CASES:
+ args = " ".join("1" if case["facts"][name] else "0" for name in LINEAGE_FACTS)
+ calls.append(f"if marker_launcher_rule {args}; then echo {case['id']}=1; else echo {case['id']}=0; fi")
+ for case in ENV_CASES:
+ calls.append(f"if HERMES_UPDATE_STARTED_AT={shlex.quote(case['env'])} marker_env_started_matches {shlex.quote(case['line2'])}; "
+ f"then echo env_{case['id']}=1; else echo env_{case['id']}=0; fi")
+ out = subprocess.run(["bash", "-c", "\n".join(calls)], capture_output=True, text=True, encoding="utf-8", timeout=30, check=True).stdout
+ got = dict(line.split("=") for line in out.split())
+ want = {c["id"]: "1" if c["expect"] else "0" for c in RULE_CASES} | {f"env_{c['id']}": "1" if c["expect"] else "0" for c in ENV_CASES}
+ assert got == want
+
+
[email protected]("env_matches", [True, False], ids=["env-matches", "env-differs"])
+def test_reparented_live_launcher_is_adopted_only_with_the_handoff_started_at(tmp_path, procs, env_matches):
+ """The table's divergent row on real processes: the launcher X is our live parent, but no
+ longer the Desktop's child (the Desktop quit first); line 2 == HERMES_UPDATE_STARTED_AT."""
+ home, install = _install(tmp_path)
+ desktop = subprocess.Popen(["sleep", "60"]); procs.append(desktop) # not X's parent
+ started = int(time.time())
+ marker = home / ".hermes-update-in-progress"
+ report = tmp_path / "launched.txt"
+ launcher = (f'printf "%s\\n{started}\\n" $$ > {shlex.quote(str(marker))}; '
+ f'HERMES_UPDATE_STARTED_AT={started if env_matches else started - 7} bash {shlex.quote(str(POSIX))} --daemonized --no-ui '
+ f'--self-test-marker --install-root {shlex.quote(str(install))} --desktop-pid {desktop.pid}; echo "rc=$?" > {shlex.quote(str(report))}')
+ x = subprocess.run(["bash", "-c", launcher], env=_env(tmp_path, home), timeout=60)
+ assert x.returncode == 0
+ rc = report.read_text(encoding="utf-8-sig").strip()
+ body = marker.read_text(encoding="utf-8-sig").splitlines()
+ if env_matches:
+ assert rc == "rc=0", (home / "logs" / "desktop-update-handoff.log").read_text(encoding="utf-8-sig")
+ assert body[1] == str(started) and body[2].startswith("ct:")
+ else:
+ assert rc == "rc=2" and len(body) == 2 and body[1] == str(started)
+
+
# ── R5: protocol 2 adopts only the Desktop's bridge carrying its run ────────
diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_handoff_lineage.py b/tests/scripts/desktop_update/test_desktop_update_windows_handoff_lineage.py
index 3d0ebac48fe..8c2a5538151 100644
--- a/tests/scripts/desktop_update/test_desktop_update_windows_handoff_lineage.py
+++ b/tests/scripts/desktop_update/test_desktop_update_windows_handoff_lineage.py
@@ -4,6 +4,7 @@
"""
from __future__ import annotations
+import json
import os
from pathlib import Path
import subprocess
@@ -12,9 +13,11 @@ import time
import pytest
+from tests.scripts.desktop_update.lineage_rule_cases import ENV_CASES, RULE_CASES
from tests.scripts.desktop_update.windows_handoff_support import (
SCRIPT,
MARKER,
+ MARKER_PS1,
POWERSHELL,
_creation_time,
_script,
@@ -40,11 +43,12 @@ from pathlib import Path
# same tick overwrite the marker with the WRAPPER's pid as a v1 claim, then
# stay up (the -SelfTestMarker script ends before it would wait us out).
home, script, mode, foreign = Path(sys.argv[1]), sys.argv[2], sys.argv[3], int(sys.argv[4])
+other_desktop, env_skew = int(sys.argv[5]), int(sys.argv[6]) # a Desktop that is NOT the wrapper's parent
started = int(time.time())
-env = dict(os.environ, HERMES_UPDATE_STARTED_AT=str(started))
+env = dict(os.environ, HERMES_UPDATE_STARTED_AT=str(started + env_skew))
ps = [os.environ['POWERSHELL'], '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script,
'-InstallRoot', str(home / 'hermes-agent'), '-NoUi', '-SelfTestMarker', '-NoMarkerCleanup',
- '-DesktopPid', str(os.getpid())]
+ '-DesktopPid', str(other_desktop or os.getpid())]
wrapper = ['cmd.exe', '/d', '/s', '/c'] + (['start', '', '/b'] if mode == 'start-b' else [])
child = subprocess.Popen(wrapper + ps, cwd=home, env=env, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
@@ -55,10 +59,12 @@ time.sleep(600)
"""
-def _old_desktop(home: Path, mode: str, foreign: int = 0) -> tuple[subprocess.Popen, int, int, int]:
+def _old_desktop(home: Path, mode: str, foreign: int = 0, other_desktop: int = 0,
+ env_skew: int = 0) -> tuple[subprocess.Popen, int, int, int]:
program = home.parent / 'old_desktop.py'
program.write_text(OLD_DESKTOP, encoding='utf-8')
- desktop = subprocess.Popen([sys.executable, str(program), str(home), str(SCRIPT), mode, str(foreign)],
+ desktop = subprocess.Popen([sys.executable, str(program), str(home), str(SCRIPT), mode, str(foreign),
+ str(other_desktop), str(env_skew)],
env={**os.environ, 'HERMES_HOME': str(home), 'POWERSHELL': POWERSHELL})
deadline = time.monotonic() + 30
while not (home / 'desktop.json').exists():
@@ -103,6 +109,75 @@ def test_r4_old_desktop_lineage_never_adopts_an_unrelated_live_claim(
assert (home / MARKER).read_bytes().decode() == f'{sleeper.pid}\n{started}\n'
[email protected]('env_matches', [True, False], ids=['env-matches', 'env-differs'])
+def test_r4_live_wrapper_not_the_desktops_child_is_adopted_only_with_the_handoff_started_at(
+ tmp_path: Path, sleeper: subprocess.Popen, env_matches: bool,
+) -> None:
+ """The lineage table's divergent row (round 5 D11) on real processes: the cmd.exe wrapper is
+ our live parent but not the Desktop's child; line 2 == HERMES_UPDATE_STARTED_AT adopts, as
+ in bash. Any other startedAt refuses."""
+ home = tmp_path / 'home'; home.mkdir()
+ desktop, wrapper, started, _ = _old_desktop(home, 'waiting-wrapper', other_desktop=sleeper.pid,
+ env_skew=0 if env_matches else -7)
+ try:
+ log = _wait_for_log(home, 'hand-off start:' if env_matches else 'exiting without claiming')
+ finally:
+ desktop.kill(); desktop.wait()
+ if env_matches:
+ assert 'marker=adopted' in log, log
+ assert f"desktop pid {sleeper.pid}'s launcher pid {wrapper}" in log, log
+ lines = (home / MARKER).read_bytes().decode().split('\n')
+ assert lines[1] == str(started) and lines[2].startswith('ct:'), lines
+ else:
+ assert 'hand-off start:' not in log, log
+ assert (home / MARKER).read_bytes().decode() == f'{wrapper}\n{started}\n'
+
+
+# -- the one launcher-lineage rule, shared with marker.sh ---------------------
+
+_RULE_HARNESS = r"""
+param([string]$MarkerPs1, [string]$Marker, [string]$Cases)
+$MarkerPath = $Marker
+$NoMarkerCleanup = $true
+function Write-HandoffLog([string]$Message) { [Console]::Error.WriteLine($Message) }
+. $MarkerPs1
+$data = [System.IO.File]::ReadAllText($Cases) | ConvertFrom-Json
+foreach ($c in $data.rule) {
+ $facts = @{}
+ foreach ($p in $c.facts.PSObject.Properties) { $facts[$p.Name] = [bool]$p.Value }
+ [Console]::Out.WriteLine("$($c.id)=$([int][bool](Test-MarkerLauncherRule $facts))")
+}
+foreach ($c in $data.env) {
+ $env:HERMES_UPDATE_STARTED_AT = $c.env
+ [Console]::Out.WriteLine("env_$($c.id)=$([int][bool](Test-MarkerEnvStartedAt $c.line2))")
+}
+"""
+
+_PASCAL = {'v1': 'V1', 'names_desktop': 'NamesDesktop', 'named_alive': 'NamedAlive',
+ 'named_is_our_parent': 'NamedIsOurParent', 'named_parent_is_desktop': 'NamedParentIsDesktop',
+ 'env_started_matches': 'EnvStartedMatches'}
+
+
+def test_launcher_lineage_rule_matches_the_shared_table(tmp_path: Path) -> None:
+ cases = tmp_path / 'cases.json'
+ cases.write_text(json.dumps({
+ 'rule': [{'id': c['id'], 'facts': {_PASCAL[k]: v for k, v in c['facts'].items()}} for c in RULE_CASES],
+ 'env': [{'id': c['id'], 'env': c['env'], 'line2': c['line2']} for c in ENV_CASES],
+ }), encoding='utf-8')
+ harness = tmp_path / 'rule.ps1'
+ harness.write_text(_RULE_HARNESS, encoding='utf-8')
+ proc = subprocess.run([POWERSHELL, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(harness),
+ '-MarkerPs1', str(MARKER_PS1), '-Marker', str(tmp_path / MARKER), '-Cases', str(cases)],
+ capture_output=True, text=True, timeout=120)
+ assert proc.returncode == 0, proc.stdout + proc.stderr
+ got = dict(line.split('=') for line in proc.stdout.split())
+ want = {c['id']: '1' if c['expect'] else '0' for c in RULE_CASES}
+ want.update({f"env_{c['id']}": '1' if c['expect'] else '0' for c in ENV_CASES})
+ assert got == want, proc.stderr
+
+
# -- protocol 2: -HandoffRun --------------------------------------------------
@pytest.mark.platforms('windows')