From b4f95f148eb15c97a9abb2e1f56a3a964becccc3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 01:08:29 -0600 Subject: [PATCH 01/14] account-availability -Mark writes and parses timestamps in the invariant culture The marker's stamps were formatted with the current culture. Measured: under th-TH marked_at and effective_from came out in Buddhist year 2569, so an account marked unavailable now read PENDING; fi-FI wrote '.' for ':'; ar-SA refused the documented -EffectiveFrom 2026-10-01. Format with InvariantCulture and parse -EffectiveFrom with InvariantCulture and AssumeUniversal, so a bare date is UTC midnight. A failed write or rename no longer leaves the .tmp file behind. New-Item -Path was measured not to expand wildcards; a test pins it. BACKLOG #7557 --- scripts/coord/account-availability.ps1 | 29 +++++-- tests/test_coord_usage.py | 101 +++++++++++++++++++++++++ 2 files changed, 125 insertions(+), 5 deletions(-) diff --git a/scripts/coord/account-availability.ps1 b/scripts/coord/account-availability.ps1 index 43a76ac346..2795f58299 100644 --- a/scripts/coord/account-availability.ps1 +++ b/scripts/coord/account-availability.ps1 @@ -127,9 +127,21 @@ switch ($PSCmdlet.ParameterSetName) { exit 1 } + # THE INVARIANT CULTURE, BOTH WAYS, OR THE MARKER IS NOT THE ISO TEXT ITS READERS PARSE. Under + # th-TH the current culture's Thai Buddhist calendar wrote marked_at in year 2569, so an account + # marked dead NOW read PENDING for 543 years; under fi-FI the time separator became '.'; under + # ar-SA the Um Al Qura calendar refused '2026-10-01' outright. ConvertTo-UtcDateTime parses with + # the current culture, so -EffectiveFrom is parsed here instead. A date with no offset is UTC, + # as every timestamp this codebase writes is, which makes 2026-10-01 and 2026-10-01T00:00:00Z + # the same instant, as the refusal text below says they are. + $inv = [cultureinfo]::InvariantCulture + $iso = "yyyy-MM-dd'T'HH:mm:ss'Z'" $eff = $null if ($EffectiveFrom) { - $eff = ConvertTo-UtcDateTime $EffectiveFrom + $parsed = [System.DateTimeOffset]::MinValue + if ([System.DateTimeOffset]::TryParse($EffectiveFrom, $inv, [System.Globalization.DateTimeStyles]::AssumeUniversal, [ref]$parsed)) { + $eff = $parsed.UtcDateTime + } if ($null -eq $eff) { Write-Host "REFUSED -- -EffectiveFrom is not a date I can read: $EffectiveFrom" -ForegroundColor Red Write-Host " Use an ISO-8601 date, for example 2026-10-01 or 2026-10-01T00:00:00Z." -ForegroundColor DarkGray @@ -143,9 +155,9 @@ switch ($PSCmdlet.ParameterSetName) { $doc = [ordered]@{ unavailable = $true reason = $Reason - marked_at = $now.ToString('yyyy-MM-ddTHH:mm:ssZ') + marked_at = $now.ToString($iso, $inv) marked_by = $By - effective_from = $(if ($eff) { $eff.ToString('yyyy-MM-ddTHH:mm:ssZ') } else { $now.ToString('yyyy-MM-ddTHH:mm:ssZ') }) + effective_from = $(if ($eff) { $eff } else { $now }).ToString($iso, $inv) } $sd = Get-UsageStateDir $ConfigDir @@ -154,9 +166,16 @@ switch ($PSCmdlet.ParameterSetName) { # Temp-then-rename, the same discipline the collector uses: a reader must never observe a # half-written marker, and a half-written marker reads as MALFORMED, which fails closed on a # live account. + # The finally removes the temp file a failed write or rename would otherwise leave beside the + # marker; after a successful rename it no longer exists, so it removes nothing. $tmp = "$path.$PID.tmp" - [System.IO.File]::WriteAllText($tmp, ($doc | ConvertTo-Json -Depth 4), [System.Text.Encoding]::UTF8) - [System.IO.File]::Move($tmp, $path, $true) + try { + [System.IO.File]::WriteAllText($tmp, ($doc | ConvertTo-Json -Depth 4), [System.Text.Encoding]::UTF8) + [System.IO.File]::Move($tmp, $path, $true) + } + finally { + if (Test-Path -LiteralPath $tmp) { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue } + } $pending = $eff -and $eff -gt $now Write-Host "" diff --git a/tests/test_coord_usage.py b/tests/test_coord_usage.py index 2d7d2045f8..69b90bbea2 100644 --- a/tests/test_coord_usage.py +++ b/tests/test_coord_usage.py @@ -3709,6 +3709,107 @@ def test_marking_is_reversible_and_clearing_nothing_is_not_an_error(tmp_path: Pa assert "NOTHING TO CLEAR" in again.stdout +_ISO_UTC = re.compile(r"\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z\Z") + + +def avail_in_culture(culture: str, *args: str) -> subprocess.CompletedProcess[str]: + """Run the script with the current culture set to ``culture`` in the same process. + + The culture line is printed first, with its calendar, so the test can prove the culture TOOK: a + host that silently ignored it would run the Gregorian arm and pass for the wrong reason. + """ + # A parameter name stays bare: quoted, '-Mark' binds as a positional string. + quoted = " ".join( + a if a.startswith("-") else "'" + a.replace("'", "''") + "'" for a in (str(AVAIL), *args) + ) + command = ( + f"[cultureinfo]::CurrentCulture = '{culture}'; " + "$c = [cultureinfo]::CurrentCulture; " + "Write-Output ('CULTURE ' + $c.Name + ' ' + $c.Calendar.GetType().Name); " + f"& {quoted}; if (-not $?) {{ exit 1 }}; exit $LASTEXITCODE" + ) + return run_single( + ["pwsh", "-NoProfile", "-NonInteractive", "-Command", command], + capture_output=True, + text=True, + timeout=TIMEOUT, + check=False, + env=_env(None), + ) + + +@pytest.mark.parametrize( + ("culture", "calendar"), + [ + ("th-TH", "ThaiBuddhistCalendar"), + ("fa-IR", "PersianCalendar"), + ("ar-SA", "UmAlQuraCalendar"), + ("fi-FI", "GregorianCalendar"), + ], +) +def test_a_marker_written_under_any_culture_is_iso_utc_text( + tmp_path: Path, culture: str, calendar: str +) -> None: + """BACKLOG #7557. The stamps were formatted with the CURRENT culture. Under th-TH that wrote + marked_at in Buddhist year 2569, so an account marked dead NOW read PENDING for 543 years; fi-FI + wrote '.' for ':'; ar-SA refused the documented ``-EffectiveFrom 2026-10-01`` outright. + """ + root = tmp_path / ".claude-account-9" + root.mkdir() + state = root / "mefor-usage" + state.mkdir() + tempting(state) + marker = state / "unavailable.json" + + now = avail_in_culture(culture, "-Mark", "-ConfigDir", str(root), "-Reason", "cancelled") + assert f"CULTURE {culture} {calendar}" in now.stdout, now.stdout + now.stderr + assert now.returncode == 0, now.stdout + now.stderr + doc = json.loads(marker.read_text(encoding="utf-8-sig")) + year = datetime.now(UTC).year + for key in ("marked_at", "effective_from"): + assert _ISO_UTC.match(doc[key]), (key, doc[key]) + assert abs(int(doc[key][:4]) - year) <= 1, (key, doc[key]) + # The reader, in the default culture, must take a mark made NOW as live now, not PENDING. + assert read(state)[0] == UNAVAILABLE + + # A date with no offset is UTC midnight, the same instant the refusal text equates it with. + later = avail_in_culture( + culture, + "-Mark", + "-ConfigDir", + str(root), + "-Reason", + "cancelled", + "-EffectiveFrom", + "2099-01-01", + ) + assert later.returncode == 0, later.stdout + later.stderr + doc = json.loads(marker.read_text(encoding="utf-8-sig")) + assert doc["effective_from"] == "2099-01-01T00:00:00Z" + assert _ISO_UTC.match(doc["marked_at"]), doc["marked_at"] + + +def test_a_failed_marker_write_leaves_no_temp_file_behind(tmp_path: Path) -> None: + """BACKLOG #7557. A throw from the rename left ``unavailable.json..tmp`` beside the marker. + A directory at the marker path makes the write fail, whichever line refuses it.""" + root = tmp_path / ".claude-account-9" + (root / "mefor-usage" / "unavailable.json").mkdir(parents=True) + out = avail("-Mark", "-ConfigDir", str(root), "-Reason", "cancelled") + assert out.returncode != 0, out.stdout + assert not list((root / "mefor-usage").glob("*.tmp")) + + +def test_a_root_whose_name_holds_wildcard_characters_is_marked_literally(tmp_path: Path) -> None: + """Pins the reviewed not-a-bug half of BACKLOG #7557: ``New-Item -Path`` was said to expand + wildcards. Measured, it does not; a sibling the pattern would match stays untouched.""" + root = tmp_path / "acct[1]" + root.mkdir() + (tmp_path / "acct1").mkdir() + assert avail("-Mark", "-ConfigDir", str(root), "-Reason", "cancelled").returncode == 0 + assert (root / "mefor-usage" / "unavailable.json").is_file() + assert not (tmp_path / "acct1" / "mefor-usage").exists() + + def test_an_unmarked_root_is_untouched_by_any_of_this(tmp_path: Path) -> None: """The absent-marker arm is the only silent one, and it is the overwhelmingly normal case. If it ever stopped meaning AVAILABLE, every root on the box would go dark at once. From 07d475998829ae57a5ae8d8a87234e7029dad198 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 01:16:27 -0600 Subject: [PATCH 02/14] account-availability -Clear and -Status refuse a missing root; a directory marker is refused Only -Mark refused a -ConfigDir that does not exist. Measured: -Clear on a typo'd root printed NOTHING TO CLEAR and -Status printed AVAILABLE, both exit 0, while the real root's marker stayed in force. Both now refuse with exit 1. A directory at the marker path, which the reader takes as MALFORMED, made -Clear print NOTHING TO CLEAR and -Mark die in File.Move; both now refuse by name and leave it for removal by hand. BACKLOG #7558, including its added items 1 and 2. Proposed PR title: account-availability: invariant-culture stamps, and -Clear/-Status refuse a missing root (BACKLOG #7557, #7558) Proposed banners: #7557 CLOSED: culture-invariant format and parse fixed with tests; the New-Item wildcard sub-claim reviewed not-a-bug and pinned. #7558 CLOSED: -Clear and single-root -Status refuse a missing root; added items 1 and 2 fixed (directory marker refused by -Clear and -Mark). --- scripts/coord/account-availability.ps1 | 36 ++++++++++++++++++----- tests/test_coord_usage.py | 40 ++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 7 deletions(-) diff --git a/scripts/coord/account-availability.ps1 b/scripts/coord/account-availability.ps1 index 2795f58299..8232d112e9 100644 --- a/scripts/coord/account-availability.ps1 +++ b/scripts/coord/account-availability.ps1 @@ -107,6 +107,22 @@ function Show-One([string]$Root) { } } +function Assert-ConfigRoot { + if (-not (Test-Path -LiteralPath $ConfigDir -PathType Container)) { + Write-Host "REFUSED -- no such config root: $ConfigDir" -ForegroundColor Red + Write-Host " This script will not create one, and reads nothing from one. Check the path." -ForegroundColor DarkGray + exit 1 + } +} + +function Assert-MarkerNotDirectory([string]$MarkerPath) { + if (Test-Path -LiteralPath $MarkerPath -PathType Container) { + Write-Host "REFUSED -- the availability marker path is a directory: $MarkerPath" -ForegroundColor Red + Write-Host " The reader treats this account as UNAVAILABLE (MALFORMED). Remove the directory by hand." -ForegroundColor DarkGray + exit 1 + } +} + switch ($PSCmdlet.ParameterSetName) { 'Mark' { @@ -121,11 +137,10 @@ switch ($PSCmdlet.ParameterSetName) { # -Force builds every missing ancestor, so a typo'd -ConfigDir would have this command # MANUFACTURE a config root nothing can launch from and then declare it cancelled -- a wholly # fictional account, recorded as fact, with nothing anywhere reporting a problem. - if (-not (Test-Path -LiteralPath $ConfigDir -PathType Container)) { - Write-Host "REFUSED -- no such config root: $ConfigDir" -ForegroundColor Red - Write-Host " This script will not create one. Check the path." -ForegroundColor DarkGray - exit 1 - } + Assert-ConfigRoot + $sd = Get-UsageStateDir $ConfigDir + $path = Join-Path $sd $script:UsageUnavailableMarker + Assert-MarkerNotDirectory $path # THE INVARIANT CULTURE, BOTH WAYS, OR THE MARKER IS NOT THE ISO TEXT ITS READERS PARSE. Under # th-TH the current culture's Thai Buddhist calendar wrote marked_at in year 2569, so an account @@ -160,9 +175,7 @@ switch ($PSCmdlet.ParameterSetName) { effective_from = $(if ($eff) { $eff } else { $now }).ToString($iso, $inv) } - $sd = Get-UsageStateDir $ConfigDir New-Item -ItemType Directory -Force -Path $sd | Out-Null - $path = Join-Path $sd $script:UsageUnavailableMarker # Temp-then-rename, the same discipline the collector uses: a reader must never observe a # half-written marker, and a half-written marker reads as MALFORMED, which fails closed on a # live account. @@ -199,8 +212,14 @@ switch ($PSCmdlet.ParameterSetName) { } 'Clear' { + # A typo'd root carries no marker, so without this a clear of a fictional account reported + # NOTHING TO CLEAR and exit 0, and the real marker stayed in force. BACKLOG #7558. + Assert-ConfigRoot $sd = Get-UsageStateDir $ConfigDir $path = Join-Path $sd $script:UsageUnavailableMarker + # A directory at the marker path is not "no marker": the reader takes it as MALFORMED and the + # account as UNAVAILABLE, so NOTHING TO CLEAR there was false. + Assert-MarkerNotDirectory $path Write-Host "" if (Test-Path -LiteralPath $path -PathType Leaf) { Remove-Item -LiteralPath $path -Force @@ -239,6 +258,9 @@ switch ($PSCmdlet.ParameterSetName) { } } else { + # A typo'd root has no marker and so read AVAILABLE, an all-clear for an account that + # does not exist. BACKLOG #7558. + Assert-ConfigRoot Show-One $ConfigDir } Write-Host "" diff --git a/tests/test_coord_usage.py b/tests/test_coord_usage.py index 69b90bbea2..062f572fa5 100644 --- a/tests/test_coord_usage.py +++ b/tests/test_coord_usage.py @@ -3810,6 +3810,46 @@ def test_a_root_whose_name_holds_wildcard_characters_is_marked_literally(tmp_pat assert not (tmp_path / "acct1" / "mefor-usage").exists() +@pytest.mark.parametrize("action", ["-Clear", "-Status"]) +def test_clear_and_status_refuse_a_config_root_that_does_not_exist( + tmp_path: Path, action: str +) -> None: + """BACKLOG #7558. Only -Mark refused a typo'd root. -Clear reported NOTHING TO CLEAR and -Status + reported AVAILABLE, both exit 0, for an account that does not exist, while the real root's marker + stayed in force. Neither may create the root it refuses.""" + ghost = tmp_path / ".claude-account-99" + out = avail(action, "-ConfigDir", str(ghost)) + assert out.returncode == 1, out.stdout + assert "REFUSED" in out.stdout + assert "AVAILABLE" not in out.stdout + assert "NOTHING TO CLEAR" not in out.stdout + assert not ghost.exists(), "the refusal created the root it refused" + + # CONTROL: the same action on a root that exists still succeeds. + real = tmp_path / ".claude-account-9" + real.mkdir() + ok = avail(action, "-ConfigDir", str(real)) + assert ok.returncode == 0, ok.stdout + + +@pytest.mark.parametrize("action", ["-Clear", "-Mark"]) +def test_a_directory_at_the_marker_path_is_refused_by_name(tmp_path: Path, action: str) -> None: + """BACKLOG #7558 added items 1 and 2. The reader takes a directory at the marker path as MALFORMED + and the account as UNAVAILABLE, yet -Clear printed NOTHING TO CLEAR and -Mark died in File.Move. + Both now refuse and say to remove it by hand; neither removes it.""" + root = tmp_path / ".claude-account-9" + marker = root / "mefor-usage" / "unavailable.json" + marker.mkdir(parents=True) + args = [action, "-ConfigDir", str(root)] + if action == "-Mark": + args += ["-Reason", "cancelled"] + out = avail(*args) + assert out.returncode == 1, out.stdout + assert "REFUSED" in out.stdout and "is a directory" in out.stdout, out.stdout + assert "NOTHING TO CLEAR" not in out.stdout + assert marker.is_dir() + + def test_an_unmarked_root_is_untouched_by_any_of_this(tmp_path: Path) -> None: """The absent-marker arm is the only silent one, and it is the overwhelmingly normal case. If it ever stopped meaning AVAILABLE, every root on the box would go dark at once. From 5399ad3d33a40140e7f2d19db6ae63da123996fd Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 01:34:05 -0600 Subject: [PATCH 03/14] account-availability: ISO-only -EffectiveFrom, and the reader formats invariantly Review round 1 repairs. -EffectiveFrom is parsed with TryParseExact against the ISO-8601 forms only, so 'Jan 5' or an en-GB '01/10/2026' is refused rather than read as a past date; an explicit empty value is refused rather than read as "now"; a form with no offset keeps its old meaning, local time. Get-RootUnavailability formats marked_at and effective_from with the invariant culture, so -Status under ar-SA no longer throws on a year past 2077 and th-TH no longer prints Buddhist years. Assert-ConfigRoot takes the root as a parameter. The temp-file test now fails inside the write (a read-only marker), not before it. BACKLOG #7557, #7558 Proposed PR title: account-availability: invariant-culture stamps, and -Clear/-Status refuse a missing root (BACKLOG #7557, #7558) Proposed banners: #7557 CLOSED: culture-invariant format and ISO-only parse, writer and reader, with tests; the New-Item wildcard sub-claim reviewed not-a-bug and pinned. Same-pattern stamps elsewhere in scripts/coord are open. #7558 CLOSED: -Clear and single-root -Status refuse a missing root; added items 1 and 2 fixed (directory marker refused by -Clear and -Mark). --- scripts/coord/account-availability.ps1 | 30 ++++++---- scripts/coord/config-roots.ps1 | 4 +- tests/test_coord_usage.py | 76 +++++++++++++++++++------- 3 files changed, 78 insertions(+), 32 deletions(-) diff --git a/scripts/coord/account-availability.ps1 b/scripts/coord/account-availability.ps1 index 8232d112e9..fd429d956c 100644 --- a/scripts/coord/account-availability.ps1 +++ b/scripts/coord/account-availability.ps1 @@ -107,9 +107,9 @@ function Show-One([string]$Root) { } } -function Assert-ConfigRoot { - if (-not (Test-Path -LiteralPath $ConfigDir -PathType Container)) { - Write-Host "REFUSED -- no such config root: $ConfigDir" -ForegroundColor Red +function Assert-ConfigRoot([string]$Root) { + if (-not (Test-Path -LiteralPath $Root -PathType Container)) { + Write-Host "REFUSED -- no such config root: $Root" -ForegroundColor Red Write-Host " This script will not create one, and reads nothing from one. Check the path." -ForegroundColor DarkGray exit 1 } @@ -137,7 +137,7 @@ switch ($PSCmdlet.ParameterSetName) { # -Force builds every missing ancestor, so a typo'd -ConfigDir would have this command # MANUFACTURE a config root nothing can launch from and then declare it cancelled -- a wholly # fictional account, recorded as fact, with nothing anywhere reporting a problem. - Assert-ConfigRoot + Assert-ConfigRoot $ConfigDir $sd = Get-UsageStateDir $ConfigDir $path = Join-Path $sd $script:UsageUnavailableMarker Assert-MarkerNotDirectory $path @@ -146,15 +146,23 @@ switch ($PSCmdlet.ParameterSetName) { # th-TH the current culture's Thai Buddhist calendar wrote marked_at in year 2569, so an account # marked dead NOW read PENDING for 543 years; under fi-FI the time separator became '.'; under # ar-SA the Um Al Qura calendar refused '2026-10-01' outright. ConvertTo-UtcDateTime parses with - # the current culture, so -EffectiveFrom is parsed here instead. A date with no offset is UTC, - # as every timestamp this codebase writes is, which makes 2026-10-01 and 2026-10-01T00:00:00Z - # the same instant, as the refusal text below says they are. + # the current culture, so -EffectiveFrom is parsed here instead, and ONLY as ISO-8601: a lenient + # parse took 'Jan 5' as a date already past and an en-GB '01/10/2026' as 10 January, marking a + # live account dead now. A form with no offset keeps its old meaning, the operator's LOCAL time. $inv = [cultureinfo]::InvariantCulture $iso = "yyyy-MM-dd'T'HH:mm:ss'Z'" $eff = $null - if ($EffectiveFrom) { + # BOUND, NOT TRUTHY: an explicit -EffectiveFrom '' (a wrapper passing an unset variable) must be + # refused, not read as omitted and so as "now". + if ($PSBoundParameters.ContainsKey('EffectiveFrom')) { $parsed = [System.DateTimeOffset]::MinValue - if ([System.DateTimeOffset]::TryParse($EffectiveFrom, $inv, [System.Globalization.DateTimeStyles]::AssumeUniversal, [ref]$parsed)) { + $forms = [string[]]@( + 'yyyy-MM-dd', + "yyyy-MM-dd'T'HH:mm", "yyyy-MM-dd'T'HH:mmK", + "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssK", + "yyyy-MM-dd'T'HH:mm:ss.FFFFFFF", "yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK" + ) + if ([System.DateTimeOffset]::TryParseExact([string]$EffectiveFrom, $forms, $inv, [System.Globalization.DateTimeStyles]::AssumeLocal, [ref]$parsed)) { $eff = $parsed.UtcDateTime } if ($null -eq $eff) { @@ -214,7 +222,7 @@ switch ($PSCmdlet.ParameterSetName) { 'Clear' { # A typo'd root carries no marker, so without this a clear of a fictional account reported # NOTHING TO CLEAR and exit 0, and the real marker stayed in force. BACKLOG #7558. - Assert-ConfigRoot + Assert-ConfigRoot $ConfigDir $sd = Get-UsageStateDir $ConfigDir $path = Join-Path $sd $script:UsageUnavailableMarker # A directory at the marker path is not "no marker": the reader takes it as MALFORMED and the @@ -260,7 +268,7 @@ switch ($PSCmdlet.ParameterSetName) { else { # A typo'd root has no marker and so read AVAILABLE, an all-clear for an account that # does not exist. BACKLOG #7558. - Assert-ConfigRoot + Assert-ConfigRoot $ConfigDir Show-One $ConfigDir } Write-Host "" diff --git a/scripts/coord/config-roots.ps1 b/scripts/coord/config-roots.ps1 index e5cbd5eb3f..cf436ecc96 100644 --- a/scripts/coord/config-roots.ps1 +++ b/scripts/coord/config-roots.ps1 @@ -403,11 +403,11 @@ function Get-RootUnavailability { # written rather than blanked, because a hand-edited marker saying "last Tuesday" should show what # it says instead of vanishing. $mk = ConvertTo-UtcDateTime $doc.marked_at - $o.marked_at = if ($mk) { $mk.ToString('yyyy-MM-ddTHH:mm:ssZ') } else { [string]$doc.marked_at } + $o.marked_at = if ($mk) { $mk.ToString('yyyy-MM-ddTHH:mm:ssZ', [cultureinfo]::InvariantCulture) } else { [string]$doc.marked_at } $o.marked_by = [string]$doc.marked_by $eff = ConvertTo-UtcDateTime $doc.effective_from if ($eff) { - $o.effective_from = $eff.ToString('yyyy-MM-ddTHH:mm:ssZ') + $o.effective_from = $eff.ToString('yyyy-MM-ddTHH:mm:ssZ', [cultureinfo]::InvariantCulture) if ($eff -gt (Get-Date).ToUniversalTime()) { $o.state = 'PENDING' return $o diff --git a/tests/test_coord_usage.py b/tests/test_coord_usage.py index 062f572fa5..7a5ed1e830 100644 --- a/tests/test_coord_usage.py +++ b/tests/test_coord_usage.py @@ -3772,31 +3772,69 @@ def test_a_marker_written_under_any_culture_is_iso_utc_text( # The reader, in the default culture, must take a mark made NOW as live now, not PENDING. assert read(state)[0] == UNAVAILABLE - # A date with no offset is UTC midnight, the same instant the refusal text equates it with. - later = avail_in_culture( - culture, - "-Mark", - "-ConfigDir", - str(root), - "-Reason", - "cancelled", - "-EffectiveFrom", - "2099-01-01", - ) - assert later.returncode == 0, later.stdout + later.stderr - doc = json.loads(marker.read_text(encoding="utf-8-sig")) - assert doc["effective_from"] == "2099-01-01T00:00:00Z" - assert _ISO_UTC.match(doc["marked_at"]), doc["marked_at"] + # The same culture reads it back: -Status formatted the stamps with the current calendar too, + # and under ar-SA a year past 2077 threw. + status = avail_in_culture(culture, "-Status", "-ConfigDir", str(root)) + assert status.returncode == 0, status.stdout + status.stderr + assert re.search(rf"marked {year}-\d\d-\d\dT\d\d:\d\d:\d\dZ", status.stdout), status.stdout + + # The documented ISO forms parse under every culture; the date-only one was refused under ar-SA. + for given, written in ( + ("2099-01-01T00:00:00Z", "2099-01-01T00:00:00Z"), + ("2099-01-01", None), + ): + later = avail_in_culture( + culture, + "-Mark", + "-ConfigDir", + str(root), + "-Reason", + "cancelled", + "-EffectiveFrom", + given, + ) + assert later.returncode == 0, later.stdout + later.stderr + doc = json.loads(marker.read_text(encoding="utf-8-sig")) + assert _ISO_UTC.match(doc["effective_from"]), doc["effective_from"] + assert doc["effective_from"][:4] in ("2098", "2099"), doc["effective_from"] + if written is not None: + assert doc["effective_from"] == written + status = avail_in_culture(culture, "-Status", "-ConfigDir", str(root)) + assert status.returncode == 0, status.stdout + status.stderr + assert "effective from 209" in status.stdout, status.stdout + + +@pytest.mark.parametrize("given", ["Jan 5", "01/10/2026", "10/1/2026 3pm", "", "next Tuesday"]) +def test_an_effective_from_that_is_not_iso_is_refused(tmp_path: Path, given: str) -> None: + """BACKLOG #7557 review. A lenient parse read 'Jan 5' as a date already past and '01/10/2026' by + US order, marking a live account dead now; an explicit '' was read as omitted, so as "now".""" + root = tmp_path / ".claude-account-9" + root.mkdir() + out = avail("-Mark", "-ConfigDir", str(root), "-Reason", "x", "-EffectiveFrom", given) + assert out.returncode == 1, out.stdout + assert "REFUSED" in out.stdout + assert not (root / "mefor-usage" / "unavailable.json").exists() +@pytest.mark.skipif( + os.name != "nt", reason="a read-only target blocks an overwrite only on Windows" +) def test_a_failed_marker_write_leaves_no_temp_file_behind(tmp_path: Path) -> None: """BACKLOG #7557. A throw from the rename left ``unavailable.json..tmp`` beside the marker. - A directory at the marker path makes the write fail, whichever line refuses it.""" + A read-only marker makes the overwriting File.Move throw, after the temp file is written.""" root = tmp_path / ".claude-account-9" - (root / "mefor-usage" / "unavailable.json").mkdir(parents=True) - out = avail("-Mark", "-ConfigDir", str(root), "-Reason", "cancelled") + state = root / "mefor-usage" + state.mkdir(parents=True) + marker = state / "unavailable.json" + marker.write_text('{"unavailable": false}', encoding="utf-8") + marker.chmod(stat.S_IREAD) + try: + out = avail("-Mark", "-ConfigDir", str(root), "-Reason", "cancelled") + finally: + marker.chmod(stat.S_IREAD | stat.S_IWRITE) assert out.returncode != 0, out.stdout - assert not list((root / "mefor-usage").glob("*.tmp")) + assert json.loads(marker.read_text(encoding="utf-8")) == {"unavailable": False} + assert not list(state.glob("*.tmp")) def test_a_root_whose_name_holds_wildcard_characters_is_marked_literally(tmp_path: Path) -> None: From 9e9ec1c2469c3197126c11aa7c8a8ebd8e7d1de3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 03:00:07 -0600 Subject: [PATCH 04/14] install-gate refuses to overwrite a gate that does not match its receipt The installer overwrote the machine-global worktree gate unconditionally, so an unexplained write to it was replaced in silence and the .bak was the only evidence left. It now refuses, before the allowlist write, when the installed gate's content hash differs from its receipt's, when the receipt cannot be read or records no hash, or when a gate has no receipt at all (the receipt is unprotected, so deleting it must not silence the check). The refusal names the file and both hashes. -OverwriteUnexplained proceeds and records the overwritten hash in the new receipt, which now also carries replacedSha256. A box with no installed gate installs as before. BACKLOG #1247 --- docs/WORKTREE-GATE.md | 10 ++ scripts/worktree/install-gate.ps1 | 84 ++++++++++- .../test_install_gate_records_the_install.py | 140 +++++++++++++++++- 3 files changed, 229 insertions(+), 5 deletions(-) diff --git a/docs/WORKTREE-GATE.md b/docs/WORKTREE-GATE.md index 7a3aeb238a..5b6fdacf9d 100644 --- a/docs/WORKTREE-GATE.md +++ b/docs/WORKTREE-GATE.md @@ -239,6 +239,16 @@ position, so a checkout many commits behind with an unchanged gate still passes. `-UpstreamRef` names a different yardstick. +Every install leaves `worktree_gate.ps1.receipt.json` beside the installed gate, with the hash it wrote, +and keeps the replaced gate as `worktree_gate.ps1.bak`. The installer **refuses to overwrite an +installed gate that does not match its own receipt** (BACKLOG #1247): one whose content hash differs +from the receipt's, one whose receipt cannot be read or records no hash, and one with no receipt at all. +Each means something other than the installer may have written it. The refusal names the file and both +hashes, and changes nothing. A missing receipt refuses too, because the receipt is not protected by +the gate and deleting it must not silence the check; a box with no installed gate installs as before. +Find out who wrote the gate, then pass `-OverwriteUnexplained`; the new receipt records the +overwritten hash under `overwroteUnexplained`. The receipt is a convenience record, never attestation. + Two structural choices worth understanding: - **Every config dir, not just `~/.claude`.** The hook is registered into `~/.claude/settings.json` **and** diff --git a/scripts/worktree/install-gate.ps1 b/scripts/worktree/install-gate.ps1 index 6a0474e970..335432e945 100644 --- a/scripts/worktree/install-gate.ps1 +++ b/scripts/worktree/install-gate.ps1 @@ -53,6 +53,15 @@ gate against the same ref, so a stale install run from a stale tree no longer reads IN SYNC. The script never fetches: the ref is as fresh as this checkout's last fetch. + THE INSTALLED GATE MUST MATCH ITS OWN RECEIPT BEFORE IT IS OVERWRITTEN (BACKLOG #1247). Every + install leaves worktree_gate.ps1.receipt.json beside the gate, carrying the hash it installed. A + later install REFUSES when the installed gate's content differs from that hash, when the receipt + cannot be read or records no hash, or when a gate is installed with no receipt at all: each means + something other than this installer may have written the machine-global gate, and overwriting it + would erase the only evidence. Nothing on the box changes on a refusal. Find out who wrote it, then + pass -OverwriteUnexplained; the new receipt records the hash that was overwritten. A box with no + installed gate installs as before. + Run from a PLAIN TERMINAL, not from inside Claude Code -- a session that can install its own gate can uninstall it. The script refuses when $env:CLAUDECODE is set. @@ -64,6 +73,7 @@ pwsh -NoProfile -File scripts\worktree\install-gate.ps1 -Uninstall -Repo C:\Users\me\Code\Probe # stop governing ONE pwsh -NoProfile -File scripts\worktree\install-gate.ps1 -Status pwsh -NoProfile -File scripts\worktree\install-gate.ps1 -AllowStaleSource # deliberately install a gate not on origin/main + pwsh -NoProfile -File scripts\worktree\install-gate.ps1 -OverwriteUnexplained # replace a gate that does not match its receipt #> [CmdletBinding()] param( @@ -102,7 +112,11 @@ param( # Install this checkout's gate even though it differs from -UpstreamRef's, or -UpstreamRef cannot # be read. For a deliberate offline install, a rollback to an older gate, or a test of an unmerged # gate change. Nothing else. - [switch]$AllowStaleSource + [switch]$AllowStaleSource, + # Overwrite an installed gate whose content does not match its own receipt, whose receipt cannot + # be read, or which has no receipt (BACKLOG #1247). Only after finding out who wrote it: the new + # receipt records the overwritten hash, and the .bak keeps its bytes. + [switch]$OverwriteUnexplained ) $ErrorActionPreference = "Stop" @@ -276,6 +290,49 @@ function Get-GateHash([string]$Path) { } } +# WHY AN INSTALLED GATE MAY NOT BE OVERWRITTEN, OR $null WHEN IT MAY (BACKLOG #1247). The receipt each +# install leaves records the hash it wrote, so an installed gate that no longer matches it was written +# by something other than this installer, and overwriting it erases the only evidence of that write. +# +# NO RECEIPT AT ALL ALSO REFUSES, while no GATE at all installs. The receipt is NOT protected by gate +# rule 1a (see the receipt write below), so treating a missing receipt as "nothing to check" would let +# anyone silence this check by deleting one unprotected file. A refusal on a missing receipt costs a +# box that still carries a pre-receipt install one deliberate -OverwriteUnexplained; it is the +# stricter reading, and the receipt is still a convenience record, never attestation. +function Get-UnexplainedGate([string]$Path) { + if (-not (Test-Path -LiteralPath $Path)) { return $null } + $installedSha = Get-GateHash $Path + $receiptPath = "$Path.receipt.json" + $recordedSha = $null + $problem = $null + if (-not (Test-Path -LiteralPath $receiptPath)) { + $problem = "it has no receipt at $receiptPath, so nothing records that this installer wrote it" + } else { + try { + $raw = Get-Content -LiteralPath $receiptPath -Raw -ErrorAction Stop + $parsed = if ($raw) { $raw | ConvertFrom-Json -ErrorAction Stop } else { $null } + $field = if ($null -ne $parsed) { $parsed.PSObject.Properties['gateSha256'] } else { $null } + if ($field -and $field.Value -is [string] -and $field.Value -match '\A[0-9A-Fa-f]{64}\z') { + $recordedSha = $field.Value.ToUpperInvariant() + } else { + $problem = "its receipt at $receiptPath records no gate hash" + } + } catch [System.Management.Automation.RuntimeException], [System.IO.IOException], [System.UnauthorizedAccessException], [System.ArgumentException] { + $problem = "its receipt at $receiptPath cannot be read: $($_.Exception.Message)" + } + if (-not $problem -and $recordedSha -ne $installedSha) { + $problem = "its content does not match the hash its own receipt at $receiptPath records" + } + } + if (-not $problem) { return $null } + [pscustomobject]@{ + Path = $Path + InstalledSha = $installedSha + ReceiptSha = $recordedSha + Problem = $problem + } +} + # Every tool a gate script branches on. -Status calls this on the INSTALLED copy, deliberately: the # question it answers is "which rules does the gate that is RUNNING have, and are they all wired", and the # source's rule set is not evidence for either. That is the whole point of the audit -- rule 4 was in the @@ -1098,6 +1155,24 @@ if ($dispatchRefusal) { New-Item -ItemType Directory -Force -Path $HooksDir | Out-Null +# REFUSE TO OVERWRITE A GATE THAT DOES NOT MATCH ITS OWN RECEIPT (BACKLOG #1247), before the allowlist +# write, so a refusal leaves the box as it was. An unexplained write to this machine-global file was +# once overwritten in silence, and the .bak was the only evidence left afterwards. +$unexplained = Get-UnexplainedGate $GateDst +if ($unexplained) { + $why = @( + "Refusing to overwrite the installed gate at $($unexplained.Path): $($unexplained.Problem)." + " installed gate sha256 : $($unexplained.InstalledSha)" + " receipt records : $(if ($unexplained.ReceiptSha) { $unexplained.ReceiptSha } else { '(no hash)' })" + "Something other than this installer may have written it. Nothing on this box has been changed." + "Find out who wrote it first: compare it with scripts\hooks\worktree_gate.ps1 and keep a copy if you need one." + "Then re-run with -OverwriteUnexplained. The new receipt records the overwritten hash, and the .bak keeps its bytes." + ) -join [Environment]::NewLine + if (-not $OverwriteUnexplained) { throw $why } + Write-Host "WARNING: overwriting an installed gate that does not match its receipt, because -OverwriteUnexplained was given." -ForegroundColor Yellow + Write-Host " $($unexplained.Problem). Installed sha256 $($unexplained.InstalledSha) is recorded in the new receipt." -ForegroundColor Yellow +} + # READ AND MERGE BEFORE ANYTHING ON THIS BOX CHANGES. An allowlist this run cannot read must stop the # install while the machine is still exactly as it was -- reading after the gate copy below would leave a # refreshed gate sitting behind a refusal. @@ -1124,6 +1199,7 @@ $bak = Write-GovernedRoots -Path $ReposFile -Lines $result.Lines # same file. $GateSrc = Join-Path $RepoRoot "scripts\hooks\worktree_gate.ps1" $gateBak = $null +$replacedSha = Get-GateHash $GateDst if (Test-Path -LiteralPath $GateDst) { $gateBak = "$GateDst.bak" Copy-Item -LiteralPath $GateDst -Destination $gateBak -Force @@ -1170,6 +1246,12 @@ $receipt = [ordered]@{ upstreamGateSha256 = $upstream.Sha dispatchSha256 = (Get-GateHash $DispatchDst) allowStaleSource = [bool]$AllowStaleSource + # BACKLOG #1247: the hash this install replaced, and, when it did not match its own receipt, what + # -OverwriteUnexplained overrode. + replacedSha256 = $replacedSha + overwroteUnexplained = $(if ($unexplained -and $OverwriteUnexplained) { + [ordered]@{ installedSha256 = $unexplained.InstalledSha; receiptSha256 = $unexplained.ReceiptSha; problem = $unexplained.Problem } + } else { $null }) note ='Convenience record written by install-gate.ps1. NOT protected by the gate and NOT attestation.' } | ConvertTo-Json -Depth 4 Set-Content -LiteralPath "$GateDst.receipt.json" -Value $receipt -Encoding utf8 diff --git a/tests/test_install_gate_records_the_install.py b/tests/test_install_gate_records_the_install.py index 7d48957552..6ea5806cd8 100644 --- a/tests/test_install_gate_records_the_install.py +++ b/tests/test_install_gate_records_the_install.py @@ -45,6 +45,13 @@ _START = "$GateSrc = Join-Path $RepoRoot" _END = 'Set-Content -LiteralPath "$GateDst.receipt.json" -Value $receipt -Encoding utf8' +# The receipt guard that precedes the allowlist write (BACKLOG #1247's last limb): from the check to +# the comment that opens the allowlist read below it. +_GUARD_START = "$unexplained = Get-UnexplainedGate $GateDst" +_GUARD_END = "# READ AND MERGE BEFORE ANYTHING ON THIS BOX CHANGES" + +_INSTALLED_GATE = "# THE GATE THAT WAS ALREADY INSTALLED\n" + def _region() -> str: text = INSTALLER.read_text(encoding="utf-8") @@ -53,6 +60,17 @@ def _region() -> str: return text[i:j] +def _guard() -> str: + text = INSTALLER.read_text(encoding="utf-8") + assert text.count(_GUARD_START) == 1, "the receipt guard must appear exactly once" + return text[text.index(_GUARD_START) : text.index(_GUARD_END)] + + +def _content_sha(data: bytes) -> str: + """Get-GateHash's basis: SHA-256 over the bytes with each CRLF folded to LF, upper-case hex.""" + return hashlib.sha256(data.replace(b"\r\n", b"\n")).hexdigest().upper() + + def _function(name: str) -> str: """The source of one helper the region calls, so the fixture runs the REAL implementation.""" text = INSTALLER.read_text(encoding="utf-8") @@ -68,8 +86,20 @@ def _function(name: str) -> str: raise AssertionError(f"unbalanced braces reading {name}") -def _run(home: Path, source_age_days: int = 6) -> dict[str, Any]: - """Run the real region against a fixture and read the consequences off disk.""" +def _run( + home: Path, + source_age_days: int = 6, + *, + receipt: str = "match", + override: bool = False, + expect_ok: bool = True, +) -> dict[str, Any]: + """Run the real guard and region against a fixture and read the consequences off disk. + + ``receipt`` is the state of the installed gate's receipt: ``match`` (what this installer leaves), + ``mismatch`` (the gate changed after its install), ``garbage`` (unreadable JSON), ``nohash`` (JSON + with no gate hash), ``none`` (a gate with no receipt) or ``nogate`` (nothing installed at all). + """ if shutil.which("pwsh") is None: pytest.skip("SKIP (nothing run): pwsh not on PATH") @@ -84,7 +114,21 @@ def _run(home: Path, source_age_days: int = 6) -> dict[str, Any]: hooks = home / ".claude" / "hooks" hooks.mkdir(parents=True) dst = hooks / "worktree_gate.ps1" - dst.write_text("# THE GATE THAT WAS ALREADY INSTALLED\n", encoding="utf-8") + receipt_path = Path(f"{dst}.receipt.json") + if receipt != "nogate": + dst.write_bytes(_INSTALLED_GATE.encode("utf-8")) + recorded = { + "match": _content_sha(dst.read_bytes()) if receipt != "nogate" else "", + "mismatch": _content_sha(b"# some other gate\n"), + } + if receipt in recorded: + receipt_path.write_text(json.dumps({"gateSha256": recorded[receipt]}), encoding="utf-8") + elif receipt == "garbage": + receipt_path.write_text("{ not json", encoding="utf-8") + elif receipt == "nohash": + receipt_path.write_text(json.dumps({"note": "no hash"}), encoding="utf-8") + if receipt == "nogate": + receipt_path.unlink(missing_ok=True) script = "\n".join( [ @@ -94,8 +138,11 @@ def _run(home: Path, source_age_days: int = 6) -> dict[str, Any]: f"$sourceDispatch = '{dispatch_src.as_posix()}'", f"$DispatchDst = '{(hooks / 'shell-guard-dispatch.ps1').as_posix()}'", "$ConfigDir = @('c:/fixture/.claude')", + f"$OverwriteUnexplained = ${'true' if override else 'false'}", _function("Get-GateVersion"), _function("Get-GateHash"), + _function("Get-UnexplainedGate"), + _guard(), # Back-date the SOURCE, which is what a checkout does. Copy-Item carries this forward. f"(Get-Item -LiteralPath (Join-Path $RepoRoot 'scripts/hooks/worktree_gate.ps1'))" f".LastWriteTimeUtc = (Get-Date).ToUniversalTime().AddDays(-{source_age_days})", @@ -111,8 +158,10 @@ def _run(home: Path, source_age_days: int = 6) -> dict[str, Any]: encoding="utf-8", errors="replace", ) - assert proc.returncode == 0, f"the region failed to run:\n{proc.stdout}\n{proc.stderr}" + if expect_ok: + assert proc.returncode == 0, f"the region failed to run:\n{proc.stdout}\n{proc.stderr}" return { + "proc": proc, "src": src, "dst": dst, "bak": Path(f"{dst}.bak"), @@ -208,3 +257,86 @@ def test_the_receipt_says_it_is_not_attestation(tmp_path: Path) -> None: data = json.loads(Path(_run(tmp_path)["receipt"]).read_text(encoding="utf-8")) note = str(data.get("note", "")).lower() assert "not attestation" in note and "not protected" in note, data.get("note") + + +# ------------------------------------------------------------- the installed gate matches its receipt + + +def _refused(r: dict[str, Any]) -> str: + proc = r["proc"] + both = str(proc.stdout) + str(proc.stderr) + assert proc.returncode != 0, f"the install was not refused:\n{both}" + assert "Refusing to overwrite the installed gate" in both, both + assert "-OverwriteUnexplained" in both, "the refusal must name the override" + # Nothing on the box changed: the gate is byte-identical, and no backup or new receipt appeared. + assert r["dst"].read_bytes() == _INSTALLED_GATE.encode("utf-8") + assert not r["bak"].exists(), "a refusal must not have reached the backup" + assert not r["dispatch_dst"].exists(), "a refusal must not have reached the copy" + return both + + +def test_a_gate_that_matches_its_receipt_installs(tmp_path: Path) -> None: + """Control: the refusals below are a reading of the fixture, not of every install.""" + r = _run(tmp_path, receipt="match") + assert r["dst"].read_bytes() == r["src"].read_bytes() + data = json.loads(r["receipt"].read_text(encoding="utf-8-sig")) + assert data["replacedSha256"] == _content_sha(_INSTALLED_GATE.encode("utf-8")), data + assert data["overwroteUnexplained"] is None, data + + +def test_a_first_install_with_no_gate_installs(tmp_path: Path) -> None: + r = _run(tmp_path, receipt="nogate") + assert r["dst"].read_bytes() == r["src"].read_bytes() + data = json.loads(r["receipt"].read_text(encoding="utf-8-sig")) + assert data["replacedSha256"] is None, data + + +def test_a_gate_that_does_not_match_its_receipt_is_not_overwritten(tmp_path: Path) -> None: + r = _run(tmp_path, receipt="mismatch", expect_ok=False) + both = _refused(r) + # Name the file and both hashes, so the operator can tell what changed. + assert str(r["dst"].as_posix()) in both.replace("\\", "/"), both + assert _content_sha(_INSTALLED_GATE.encode("utf-8")) in both, both + assert _content_sha(b"# some other gate\n") in both, both + + +def test_an_unreadable_receipt_refuses(tmp_path: Path) -> None: + both = _refused(_run(tmp_path, receipt="garbage", expect_ok=False)) + assert "cannot be read" in both, both + + +def test_a_receipt_with_no_hash_refuses(tmp_path: Path) -> None: + both = _refused(_run(tmp_path, receipt="nohash", expect_ok=False)) + assert "records no gate hash" in both, both + + +def test_a_gate_with_no_receipt_refuses(tmp_path: Path) -> None: + """The receipt is not protected by gate rule 1a, so deleting it must not silence the check.""" + both = _refused(_run(tmp_path, receipt="none", expect_ok=False)) + assert "has no receipt" in both, both + + +def test_the_override_installs_and_records_what_it_overwrote(tmp_path: Path) -> None: + r = _run(tmp_path, receipt="mismatch", override=True) + assert r["dst"].read_bytes() == r["src"].read_bytes() + assert r["bak"].read_bytes() == _INSTALLED_GATE.encode("utf-8") + assert "WARNING" in r["proc"].stdout, r["proc"].stdout + data = json.loads(r["receipt"].read_text(encoding="utf-8-sig")) + over = data["overwroteUnexplained"] + assert over["installedSha256"] == _content_sha(_INSTALLED_GATE.encode("utf-8")), over + assert over["receiptSha256"] == _content_sha(b"# some other gate\n"), over + assert data["replacedSha256"] == over["installedSha256"], data + + +def test_the_receipt_guard_runs_before_anything_on_the_box_changes() -> None: + """A refusal says nothing was changed, so the guard must precede every install-path write.""" + text = INSTALLER.read_text(encoding="utf-8") + install = text.index("# " + "-" * 89 + " install\n") + guard = text.index(_GUARD_START) + assert install < guard, "the receipt guard is not on the install path" + for write in ( + "$bak = Write-GovernedRoots -Path $ReposFile", + "Copy-Item -LiteralPath $GateDst -Destination $gateBak", + "Copy-Item -LiteralPath $GateSrc -Destination $GateDst", + ): + assert guard < text.index(write, install), f"the receipt guard runs after {write!r}" From c63f1a7940d95b4487df3f4f6c69c011d4886321 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 03:20:21 -0600 Subject: [PATCH 05/14] install-gate receipt guard: review repairs Refusal detail goes to Write-Host so the error view cannot re-wrap the two hashes; an unreadable receipt prints (unreadable). The copy refuses if the gate changed between the guard and the backup. An overridden gate's bytes are kept as worktree_gate.ps1.unexplained-, which no later install reuses. -Status reports the same receipt check. The refusal notes when the installed gate matches this checkout's (an interrupted earlier install). Tests: typed fixture states, receipt unchanged on refusal, one hash helper. Doc and comments point to one statement of the rule. BACKLOG #1247 Proposed PR title: install-gate refuses to overwrite a gate that does not match its receipt (BACKLOG #1247) Proposed ledger banner, #1247: CLOSED. The last limb shipped: install-gate.ps1 refuses to overwrite an installed gate that does not match its own receipt, has an unreadable receipt, or has none, behind -OverwriteUnexplained, which records the overwritten hash and keeps its bytes. Open findings (receipt not covered by gate rule 1a, -Uninstall and the pinned dispatcher unguarded, partial-install false refusal) are listed in the PR. --- docs/WORKTREE-GATE.md | 4 +- scripts/worktree/install-gate.ps1 | 70 +++++++++++++------ .../test_install_gate_records_the_install.py | 27 ++++--- 3 files changed, 68 insertions(+), 33 deletions(-) diff --git a/docs/WORKTREE-GATE.md b/docs/WORKTREE-GATE.md index 5b6fdacf9d..ddb9f7aaa7 100644 --- a/docs/WORKTREE-GATE.md +++ b/docs/WORKTREE-GATE.md @@ -247,7 +247,9 @@ Each means something other than the installer may have written it. The refusal n hashes, and changes nothing. A missing receipt refuses too, because the receipt is not protected by the gate and deleting it must not silence the check; a box with no installed gate installs as before. Find out who wrote the gate, then pass `-OverwriteUnexplained`; the new receipt records the -overwritten hash under `overwroteUnexplained`. The receipt is a convenience record, never attestation. +overwritten hash under `overwroteUnexplained`, and its bytes are kept as +`worktree_gate.ps1.unexplained-`. `-Status` reports the same check. The receipt is a +convenience record, never attestation, and the gate does not protect it from an edit. Two structural choices worth understanding: diff --git a/scripts/worktree/install-gate.ps1 b/scripts/worktree/install-gate.ps1 index 335432e945..1c6693d433 100644 --- a/scripts/worktree/install-gate.ps1 +++ b/scripts/worktree/install-gate.ps1 @@ -59,8 +59,9 @@ cannot be read or records no hash, or when a gate is installed with no receipt at all: each means something other than this installer may have written the machine-global gate, and overwriting it would erase the only evidence. Nothing on the box changes on a refusal. Find out who wrote it, then - pass -OverwriteUnexplained; the new receipt records the hash that was overwritten. A box with no - installed gate installs as before. + pass -OverwriteUnexplained; the new receipt records the hash that was overwritten, and its bytes + are kept as worktree_gate.ps1.unexplained-, which no later install reuses. A box with no + installed gate installs as before. -Status reports the same check. -Uninstall does not run it. Run from a PLAIN TERMINAL, not from inside Claude Code -- a session that can install its own gate can uninstall it. The script refuses when $env:CLAUDECODE is set. @@ -113,9 +114,8 @@ param( # be read. For a deliberate offline install, a rollback to an older gate, or a test of an unmerged # gate change. Nothing else. [switch]$AllowStaleSource, - # Overwrite an installed gate whose content does not match its own receipt, whose receipt cannot - # be read, or which has no receipt (BACKLOG #1247). Only after finding out who wrote it: the new - # receipt records the overwritten hash, and the .bak keeps its bytes. + # Overwrite an installed gate that does not match its own receipt (BACKLOG #1247). The cases and + # what the override records are stated once, in .DESCRIPTION above. [switch]$OverwriteUnexplained ) @@ -290,20 +290,21 @@ function Get-GateHash([string]$Path) { } } -# WHY AN INSTALLED GATE MAY NOT BE OVERWRITTEN, OR $null WHEN IT MAY (BACKLOG #1247). The receipt each -# install leaves records the hash it wrote, so an installed gate that no longer matches it was written -# by something other than this installer, and overwriting it erases the only evidence of that write. +# WHY AN INSTALLED GATE MAY NOT BE OVERWRITTEN, OR $null WHEN IT MAY (BACKLOG #1247; the rule is in +# .DESCRIPTION above). # # NO RECEIPT AT ALL ALSO REFUSES, while no GATE at all installs. The receipt is NOT protected by gate # rule 1a (see the receipt write below), so treating a missing receipt as "nothing to check" would let # anyone silence this check by deleting one unprotected file. A refusal on a missing receipt costs a # box that still carries a pre-receipt install one deliberate -OverwriteUnexplained; it is the -# stricter reading, and the receipt is still a convenience record, never attestation. +# stricter reading, and the receipt is still a convenience record, never attestation. Editing the +# receipt silences the check as well as deleting it would; rule 1a does not cover that either. function Get-UnexplainedGate([string]$Path) { if (-not (Test-Path -LiteralPath $Path)) { return $null } $installedSha = Get-GateHash $Path $receiptPath = "$Path.receipt.json" $recordedSha = $null + $unreadable = $false $problem = $null if (-not (Test-Path -LiteralPath $receiptPath)) { $problem = "it has no receipt at $receiptPath, so nothing records that this installer wrote it" @@ -319,6 +320,7 @@ function Get-UnexplainedGate([string]$Path) { } } catch [System.Management.Automation.RuntimeException], [System.IO.IOException], [System.UnauthorizedAccessException], [System.ArgumentException] { $problem = "its receipt at $receiptPath cannot be read: $($_.Exception.Message)" + $unreadable = $true } if (-not $problem -and $recordedSha -ne $installedSha) { $problem = "its content does not match the hash its own receipt at $receiptPath records" @@ -329,6 +331,7 @@ function Get-UnexplainedGate([string]$Path) { Path = $Path InstalledSha = $installedSha ReceiptSha = $recordedSha + Unreadable = $unreadable Problem = $problem } } @@ -847,6 +850,15 @@ if ($Status) { $shortSha = { param($h) if ($h) { " sha $($h.Substring(0, 12).ToLowerInvariant())" } else { "" } } Write-Host "installed : $(if ($iSha) { "$GateDst v$iVer$(& $shortSha $iSha)" } else { 'NOT installed' })" Write-Host "source : $(if ($sSha) { "$srcGate v$sVer$(& $shortSha $sSha)" } else { 'NOT FOUND' })" + # BACKLOG #1247: the audit reports what the install would refuse on, so it is found before then. + if ($iSha) { + $receiptCheck = Get-UnexplainedGate $GateDst + if ($receiptCheck) { + Write-Host "receipt : DOES NOT EXPLAIN THE INSTALLED GATE -- $($receiptCheck.Problem). An install will refuse." -ForegroundColor Yellow + } else { + Write-Host "receipt : matches the installed gate" + } + } # THE THIRD READING, AND THE ONLY ONE NOT TAKEN FROM THIS CHECKOUT (BACKLOG #1878). The two lines # above both came from wherever this script was invoked, so a stale install run from a stale tree @@ -1159,18 +1171,25 @@ New-Item -ItemType Directory -Force -Path $HooksDir | Out-Null # write, so a refusal leaves the box as it was. An unexplained write to this machine-global file was # once overwritten in silence, and the .bak was the only evidence left afterwards. $unexplained = Get-UnexplainedGate $GateDst +# What the guard saw, so a write between here and the copy below cannot pass as explained. +$guardSha = Get-GateHash $GateDst if ($unexplained) { - $why = @( - "Refusing to overwrite the installed gate at $($unexplained.Path): $($unexplained.Problem)." - " installed gate sha256 : $($unexplained.InstalledSha)" - " receipt records : $(if ($unexplained.ReceiptSha) { $unexplained.ReceiptSha } else { '(no hash)' })" - "Something other than this installer may have written it. Nothing on this box has been changed." - "Find out who wrote it first: compare it with scripts\hooks\worktree_gate.ps1 and keep a copy if you need one." - "Then re-run with -OverwriteUnexplained. The new receipt records the overwritten hash, and the .bak keeps its bytes." - ) -join [Environment]::NewLine - if (-not $OverwriteUnexplained) { throw $why } - Write-Host "WARNING: overwriting an installed gate that does not match its receipt, because -OverwriteUnexplained was given." -ForegroundColor Yellow - Write-Host " $($unexplained.Problem). Installed sha256 $($unexplained.InstalledSha) is recorded in the new receipt." -ForegroundColor Yellow + # Detail on Write-Host, not in the throw: the error view re-wraps a thrown message and joins its + # lines, which put the two hashes on one run-on line. + $recorded = if ($unexplained.ReceiptSha) { $unexplained.ReceiptSha } elseif ($unexplained.Unreadable) { '(unreadable)' } else { '(no hash)' } + $color = if ($OverwriteUnexplained) { 'Yellow' } else { 'Red' } + Write-Host "The installed gate at $($unexplained.Path) does not match its receipt: $($unexplained.Problem)." -ForegroundColor $color + Write-Host " installed gate sha256 : $($unexplained.InstalledSha)" -ForegroundColor $color + Write-Host " receipt records : $recorded" -ForegroundColor $color + if ($unexplained.InstalledSha -eq $checkedSha) { + Write-Host " It matches this checkout's gate, so an interrupted earlier install from here may explain it." -ForegroundColor $color + } + if (-not $OverwriteUnexplained) { + Write-Host "Something other than this installer may have written it. Nothing on this box has been changed." -ForegroundColor $color + Write-Host "Find out who wrote it first, then re-run with -OverwriteUnexplained, which keeps its bytes and records its hash." -ForegroundColor $color + throw "Refusing to overwrite the installed gate at $($unexplained.Path), which does not match its receipt. Pass -OverwriteUnexplained once you know who wrote it." + } + Write-Host "WARNING: overwriting it, because -OverwriteUnexplained was given. Its hash goes in the new receipt." -ForegroundColor Yellow } # READ AND MERGE BEFORE ANYTHING ON THIS BOX CHANGES. An allowlist this run cannot read must stop the @@ -1200,10 +1219,19 @@ $bak = Write-GovernedRoots -Path $ReposFile -Lines $result.Lines $GateSrc = Join-Path $RepoRoot "scripts\hooks\worktree_gate.ps1" $gateBak = $null $replacedSha = Get-GateHash $GateDst +if ($replacedSha -ne $guardSha) { + throw "Refusing to overwrite the installed gate at ${GateDst}: it changed during this install (guard saw $guardSha, now $replacedSha). Re-run." +} if (Test-Path -LiteralPath $GateDst) { $gateBak = "$GateDst.bak" Copy-Item -LiteralPath $GateDst -Destination $gateBak -Force } +# An overridden gate's bytes outlive the next routine install, which overwrites the .bak: keep them +# under a name no later install reuses. +if ($unexplained) { + $gateKept = "$GateDst.unexplained-$($replacedSha.Substring(0, 12).ToLowerInvariant())" + Copy-Item -LiteralPath $GateDst -Destination $gateKept -Force +} Copy-Item -LiteralPath $GateSrc -Destination $GateDst -Force Copy-Item -LiteralPath $sourceDispatch -Destination $DispatchDst -Force @@ -1249,7 +1277,7 @@ $receipt = [ordered]@{ # BACKLOG #1247: the hash this install replaced, and, when it did not match its own receipt, what # -OverwriteUnexplained overrode. replacedSha256 = $replacedSha - overwroteUnexplained = $(if ($unexplained -and $OverwriteUnexplained) { + overwroteUnexplained = $(if ($unexplained) { [ordered]@{ installedSha256 = $unexplained.InstalledSha; receiptSha256 = $unexplained.ReceiptSha; problem = $unexplained.Problem } } else { $null }) note ='Convenience record written by install-gate.ps1. NOT protected by the gate and NOT attestation.' diff --git a/tests/test_install_gate_records_the_install.py b/tests/test_install_gate_records_the_install.py index 6ea5806cd8..10a1af7126 100644 --- a/tests/test_install_gate_records_the_install.py +++ b/tests/test_install_gate_records_the_install.py @@ -34,7 +34,7 @@ import time from datetime import UTC, datetime from pathlib import Path -from typing import Any +from typing import Any, Literal import pytest @@ -90,7 +90,7 @@ def _run( home: Path, source_age_days: int = 6, *, - receipt: str = "match", + receipt: Literal["match", "mismatch", "garbage", "nohash", "none", "nogate"] = "match", override: bool = False, expect_ok: bool = True, ) -> dict[str, Any]: @@ -127,8 +127,6 @@ def _run( receipt_path.write_text("{ not json", encoding="utf-8") elif receipt == "nohash": receipt_path.write_text(json.dumps({"note": "no hash"}), encoding="utf-8") - if receipt == "nogate": - receipt_path.unlink(missing_ok=True) script = "\n".join( [ @@ -139,6 +137,7 @@ def _run( f"$DispatchDst = '{(hooks / 'shell-guard-dispatch.ps1').as_posix()}'", "$ConfigDir = @('c:/fixture/.claude')", f"$OverwriteUnexplained = ${'true' if override else 'false'}", + f"$checkedSha = '{_content_sha(src.read_bytes())}'", _function("Get-GateVersion"), _function("Get-GateHash"), _function("Get-UnexplainedGate"), @@ -240,9 +239,7 @@ def test_the_install_leaves_a_receipt_whose_hash_matches_what_was_installed(tmp_ # each CRLF pair before hashing. That is deliberate -- git's clean filter stores LF while # core.autocrlf checks out CRLF, and Copy-Item translates nothing, so a byte hash made every # Windows checkout read as STALE. Hashing raw bytes here would fail against correct code. - folded = Path(r["dst"]).read_bytes().replace(b"\r\n", b"\n") - on_disk = hashlib.sha256(folded).hexdigest() - assert str(data["gateSha256"]).lower() == on_disk.lower(), ( + assert str(data["gateSha256"]).upper() == _content_sha(Path(r["dst"]).read_bytes()), ( "the receipt's hash does not match the file it claims to describe, so it is not checkable" ) @@ -262,7 +259,7 @@ def test_the_receipt_says_it_is_not_attestation(tmp_path: Path) -> None: # ------------------------------------------------------------- the installed gate matches its receipt -def _refused(r: dict[str, Any]) -> str: +def _refused(r: dict[str, Any], receipt_before: bytes | None = None) -> str: proc = r["proc"] both = str(proc.stdout) + str(proc.stderr) assert proc.returncode != 0, f"the install was not refused:\n{both}" @@ -272,6 +269,8 @@ def _refused(r: dict[str, Any]) -> str: assert r["dst"].read_bytes() == _INSTALLED_GATE.encode("utf-8") assert not r["bak"].exists(), "a refusal must not have reached the backup" assert not r["dispatch_dst"].exists(), "a refusal must not have reached the copy" + if receipt_before is not None: + assert r["receipt"].read_bytes() == receipt_before, "a refusal must not rewrite the receipt" return both @@ -293,7 +292,8 @@ def test_a_first_install_with_no_gate_installs(tmp_path: Path) -> None: def test_a_gate_that_does_not_match_its_receipt_is_not_overwritten(tmp_path: Path) -> None: r = _run(tmp_path, receipt="mismatch", expect_ok=False) - both = _refused(r) + expected = json.dumps({"gateSha256": _content_sha(b"# some other gate\n")}).encode("utf-8") + both = _refused(r, receipt_before=expected) # Name the file and both hashes, so the operator can tell what changed. assert str(r["dst"].as_posix()) in both.replace("\\", "/"), both assert _content_sha(_INSTALLED_GATE.encode("utf-8")) in both, both @@ -301,8 +301,8 @@ def test_a_gate_that_does_not_match_its_receipt_is_not_overwritten(tmp_path: Pat def test_an_unreadable_receipt_refuses(tmp_path: Path) -> None: - both = _refused(_run(tmp_path, receipt="garbage", expect_ok=False)) - assert "cannot be read" in both, both + both = _refused(_run(tmp_path, receipt="garbage", expect_ok=False), b"{ not json") + assert "cannot be read" in both and "(unreadable)" in both, both def test_a_receipt_with_no_hash_refuses(tmp_path: Path) -> None: @@ -320,6 +320,11 @@ def test_the_override_installs_and_records_what_it_overwrote(tmp_path: Path) -> r = _run(tmp_path, receipt="mismatch", override=True) assert r["dst"].read_bytes() == r["src"].read_bytes() assert r["bak"].read_bytes() == _INSTALLED_GATE.encode("utf-8") + sha12 = _content_sha(_INSTALLED_GATE.encode("utf-8"))[:12].lower() + kept = Path(f"{r['dst']}.unexplained-{sha12}") + assert kept.read_bytes() == _INSTALLED_GATE.encode("utf-8"), ( + "the overridden gate's bytes were not kept" + ) assert "WARNING" in r["proc"].stdout, r["proc"].stdout data = json.loads(r["receipt"].read_text(encoding="utf-8-sig")) over = data["overwroteUnexplained"] From 5002ebf5f5fe27f00350f0b4ee99976c8d521b28 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 03:35:55 -0600 Subject: [PATCH 06/14] Scope the install-gate "changes nothing" claim, print (no receipt), fix test docstring count Text repair for BACKLOG #1247. The receipt-mismatch refusal runs before any write; the changed-during-install refusal throws after the allowlist write, and the text now says so. The refusal prints (no receipt) when the receipt is absent, (no hash) only when it lacks a hash. The test docstring no longer carries a stale test count. Tests pin the new printed strings. Text-only: no review round run. Proposed PR title: Install gate: scope the refusal claim to the refusals it holds for (BACKLOG #1247) --- docs/WORKTREE-GATE.md | 4 +++- scripts/worktree/install-gate.ps1 | 16 +++++++++++----- tests/test_install_gate_records_the_install.py | 8 ++++---- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/docs/WORKTREE-GATE.md b/docs/WORKTREE-GATE.md index ddb9f7aaa7..dae3137e1e 100644 --- a/docs/WORKTREE-GATE.md +++ b/docs/WORKTREE-GATE.md @@ -244,7 +244,9 @@ and keeps the replaced gate as `worktree_gate.ps1.bak`. The installer **refuses installed gate that does not match its own receipt** (BACKLOG #1247): one whose content hash differs from the receipt's, one whose receipt cannot be read or records no hash, and one with no receipt at all. Each means something other than the installer may have written it. The refusal names the file and both -hashes, and changes nothing. A missing receipt refuses too, because the receipt is not protected by +hashes, and runs before any write, so it changes nothing. (The separate refusal for a gate that +changed between that check and the copy throws later, after the allowlist write: the allowlist and its +`.bak` are already written, the gate is not.) A missing receipt refuses too, because the receipt is not protected by the gate and deleting it must not silence the check; a box with no installed gate installs as before. Find out who wrote the gate, then pass `-OverwriteUnexplained`; the new receipt records the overwritten hash under `overwroteUnexplained`, and its bytes are kept as diff --git a/scripts/worktree/install-gate.ps1 b/scripts/worktree/install-gate.ps1 index 1c6693d433..107a769311 100644 --- a/scripts/worktree/install-gate.ps1 +++ b/scripts/worktree/install-gate.ps1 @@ -58,7 +58,9 @@ later install REFUSES when the installed gate's content differs from that hash, when the receipt cannot be read or records no hash, or when a gate is installed with no receipt at all: each means something other than this installer may have written the machine-global gate, and overwriting it - would erase the only evidence. Nothing on the box changes on a refusal. Find out who wrote it, then + would erase the only evidence. A receipt-mismatch refusal runs before any write, so nothing on the box + changes. The changed-during-install refusal is later: it throws after the allowlist write, so that + file (and its .bak) is already written when it fires and the gate itself is not. Find out who wrote it, then pass -OverwriteUnexplained; the new receipt records the hash that was overwritten, and its bytes are kept as worktree_gate.ps1.unexplained-, which no later install reuses. A box with no installed gate installs as before. -Status reports the same check. -Uninstall does not run it. @@ -305,8 +307,10 @@ function Get-UnexplainedGate([string]$Path) { $receiptPath = "$Path.receipt.json" $recordedSha = $null $unreadable = $false + $noReceipt = $false $problem = $null if (-not (Test-Path -LiteralPath $receiptPath)) { + $noReceipt = $true $problem = "it has no receipt at $receiptPath, so nothing records that this installer wrote it" } else { try { @@ -332,6 +336,7 @@ function Get-UnexplainedGate([string]$Path) { InstalledSha = $installedSha ReceiptSha = $recordedSha Unreadable = $unreadable + NoReceipt = $noReceipt Problem = $problem } } @@ -1134,7 +1139,7 @@ $resolved = foreach ($r in $Repo) { # from THIS checkout into a machine-global file every session runs. A checkout behind -UpstreamRef # would ship an old gate to every config dir, and -Status run from the same checkout would then find # nothing wrong. So compare against the ref first, and refuse unless the operator says they mean it. -# It sits above the allowlist write so a refusal leaves the box exactly as it was. +# It sits above the allowlist write so a receipt-mismatch refusal leaves the box exactly as it was. $sourceGate = Join-Path $RepoRoot "scripts\hooks\worktree_gate.ps1" $checkedSha = Get-GateHash $sourceGate $upstream = Get-UpstreamGate -RepoRoot $RepoRoot -Ref $UpstreamRef @@ -1168,7 +1173,8 @@ if ($dispatchRefusal) { New-Item -ItemType Directory -Force -Path $HooksDir | Out-Null # REFUSE TO OVERWRITE A GATE THAT DOES NOT MATCH ITS OWN RECEIPT (BACKLOG #1247), before the allowlist -# write, so a refusal leaves the box as it was. An unexplained write to this machine-global file was +# write, so a receipt-mismatch refusal leaves the box as it was (the changed-during-install refusal +# further down is later, after the allowlist write). An unexplained write to this machine-global file was # once overwritten in silence, and the .bak was the only evidence left afterwards. $unexplained = Get-UnexplainedGate $GateDst # What the guard saw, so a write between here and the copy below cannot pass as explained. @@ -1176,7 +1182,7 @@ $guardSha = Get-GateHash $GateDst if ($unexplained) { # Detail on Write-Host, not in the throw: the error view re-wraps a thrown message and joins its # lines, which put the two hashes on one run-on line. - $recorded = if ($unexplained.ReceiptSha) { $unexplained.ReceiptSha } elseif ($unexplained.Unreadable) { '(unreadable)' } else { '(no hash)' } + $recorded = if ($unexplained.ReceiptSha) { $unexplained.ReceiptSha } elseif ($unexplained.Unreadable) { '(unreadable)' } elseif ($unexplained.NoReceipt) { '(no receipt)' } else { '(no hash)' } $color = if ($OverwriteUnexplained) { 'Yellow' } else { 'Red' } Write-Host "The installed gate at $($unexplained.Path) does not match its receipt: $($unexplained.Problem)." -ForegroundColor $color Write-Host " installed gate sha256 : $($unexplained.InstalledSha)" -ForegroundColor $color @@ -1220,7 +1226,7 @@ $GateSrc = Join-Path $RepoRoot "scripts\hooks\worktree_gate.ps1" $gateBak = $null $replacedSha = Get-GateHash $GateDst if ($replacedSha -ne $guardSha) { - throw "Refusing to overwrite the installed gate at ${GateDst}: it changed during this install (guard saw $guardSha, now $replacedSha). Re-run." + throw "Refusing to overwrite the installed gate at ${GateDst}: it changed during this install (guard saw $guardSha, now $replacedSha). Re-run. The allowlist has already been written by then; the gate has not." } if (Test-Path -LiteralPath $GateDst) { $gateBak = "$GateDst.bak" diff --git a/tests/test_install_gate_records_the_install.py b/tests/test_install_gate_records_the_install.py index 10a1af7126..39900e85dd 100644 --- a/tests/test_install_gate_records_the_install.py +++ b/tests/test_install_gate_records_the_install.py @@ -217,8 +217,8 @@ def test_the_installed_gate_reports_when_it_was_INSTALLED_not_when_its_source_wa def test_the_install_leaves_a_receipt_whose_hash_matches_what_was_installed(tmp_path: Path) -> None: """A LIMIT OF THIS TEST, STATED RATHER THAN LEFT FOR SOMEBODY TO DISCOVER. - Mutating the source to read `Get-GateHash $GateSrc` instead of `$GateDst` leaves all four tests - GREEN, and no fixture can change that: immediately after `Copy-Item` the two files are + Mutating the source to read `Get-GateHash $GateSrc` instead of `$GateDst` leaves every test in + this file GREEN, and no fixture can change that: immediately after `Copy-Item` the two files are byte-identical, so hashing either gives the same digest. The rule "the receipt describes what was INSTALLED" is untestable at this point by construction, not by oversight. @@ -307,13 +307,13 @@ def test_an_unreadable_receipt_refuses(tmp_path: Path) -> None: def test_a_receipt_with_no_hash_refuses(tmp_path: Path) -> None: both = _refused(_run(tmp_path, receipt="nohash", expect_ok=False)) - assert "records no gate hash" in both, both + assert "records no gate hash" in both and "(no hash)" in both, both def test_a_gate_with_no_receipt_refuses(tmp_path: Path) -> None: """The receipt is not protected by gate rule 1a, so deleting it must not silence the check.""" both = _refused(_run(tmp_path, receipt="none", expect_ok=False)) - assert "has no receipt" in both, both + assert "has no receipt" in both and "(no receipt)" in both, both def test_the_override_installs_and_records_what_it_overwrote(tmp_path: Path) -> None: From 53d1e35504da91a429f037b63635aaaf8cfc302f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 03:43:49 -0600 Subject: [PATCH 07/14] mail.ps1 keys every addressed path on its enclosing worktree root -Send -To hashed the resolved path as given, so a path inside a worktree minted a box beside the real one that no drain reads, and was reported Queued; -Status from a subdirectory reported that shadow box, and -To all compared and hashed raw launch cwds. Every path is now raised to its worktree root with the drain's own Get-CcxWorktreeRoot (scripts/hooks/_hookinput.ps1), the root seat.ps1 keys a seat on. A -To path in no worktree is refused; -To all skips and counts a peer whose cwd is in none, and names a shared box once. -Status from no worktree keeps its cwd, the box an -AnchorRepo drain reads. Spelling variants (case, slashes, trailing separator, ..) already shared one key; pinned by test. BACKLOG #7581 (Argon S33-75). S33-76 (-Status NextDrainShowsAtLeast over-reports) is not built here. Proposed PR title: mail.ps1 keys every addressed path on its worktree root (BACKLOG #7581) Proposed banner: PARTIAL -- S33-75 built (path, -To all and -Status normalised to the worktree root; out-of-worktree -To refused). Remains: S33-76, -Status NextDrainShowsAtLeast counts expired, unparseable and unminted rows and omits the drain's frame and line-prefix bytes; and S33-75's second half, -To all reads only presence.ps1, so cross-PC and Codex seats are not broadcast to. --- docs/SESSION-MAIL.md | 14 +++- scripts/coord/mail.ps1 | 51 ++++++++++-- tests/test_session_mail_toplevel.py | 124 ++++++++++++++++++++++++++++ 3 files changed, 179 insertions(+), 10 deletions(-) create mode 100644 tests/test_session_mail_toplevel.py diff --git a/docs/SESSION-MAIL.md b/docs/SESSION-MAIL.md index 5e65348b20..84af4839bf 100644 --- a/docs/SESSION-MAIL.md +++ b/docs/SESSION-MAIL.md @@ -152,8 +152,9 @@ pwsh -NoProfile -File scripts\coord\mail.ps1 -List pwsh -NoProfile -File scripts\coord\mail.ps1 -Status ``` -- `-To ` -- the recipient **worktree** path. Matched case-insensitively and exactly. `all` - broadcasts to the live roster from [`presence.ps1`](../scripts/coord/presence.ps1). +- `-To ` -- the recipient **worktree** path. A path inside a worktree names that worktree's box, + and a path in no worktree is refused (see *Raised to the worktree root* below). Matched + case-insensitively and exactly. `all` broadcasts to the live roster from [`presence.ps1`](../scripts/coord/presence.ps1). - `-To ` -- a seat record's id, such as `autonomy-plan-62022e2c`, accepted when the seat registry holds a readable record for it that names a worktree. **Use this for a seat on another PC**: its worktree path does not exist here, so the path form cannot reach it. A seat id hashes the host as well as the @@ -209,6 +210,15 @@ spelled two ways, and a case-sensitive key splits it into two boxes that never s The normalisation also trims a trailing separator and folds forward slashes to back slashes, because some producers are git and some are Windows. +**Raised to the worktree root first.** Every path a send or `-Status` addresses is first raised to the +first directory at or above it that holds `.git`, by the drain's own rule (`Get-CcxWorktreeRoot` in +[`scripts/hooks/_hookinput.ps1`](../scripts/hooks/_hookinput.ps1)); `seat.ps1` keys a seat on the same +root. A path below the root hashed as given would mint a box beside the real one that no drain reads, +under a `Queued` line (BACKLOG #7581). So `-Send -To` refuses a path in no worktree, and `-To all` +skips a live peer whose cwd is in none and says how many it skipped. One consequence: `mail.ps1` +cannot address an `-AnchorRepo` container session by path, though `-Status` run from one still reads +its own box. + **Matched EXACTLY, never by prefix.** Every worktree path in this repo is an extension of the primary checkout's path. A prefix match therefore resolves *any* peer to some arbitrary worktree -- most likely the primary one -- and does so silently, because a wrong-but-existing box looks exactly like a right diff --git a/scripts/coord/mail.ps1 b/scripts/coord/mail.ps1 index a7031f7faa..2023bd372a 100644 --- a/scripts/coord/mail.ps1 +++ b/scripts/coord/mail.ps1 @@ -57,7 +57,12 @@ seat's worktree and host key to now, never to the old box, which every PC at that path reads. A record under it that names no host is refused, and so is any seat record that names no worktree: neither can be keyed to one PC's box. - A cwd is matched case-insensitively and EXACTLY, never by prefix: every worktree cwd in this repo is + A PATH IS FIRST RAISED TO ITS WORKTREE ROOT, the first directory at or above it holding `.git`, + by the drain's own rule (Get-CcxWorktreeRoot in scripts/hooks/_hookinput.ps1); seat.ps1 keys a + seat on the same root, read as `git rev-parse --show-toplevel`. A path inside a worktree therefore + names that worktree's box, and a -To path in no worktree is refused: hashed as given, either would + mint a box nobody drains under a "Queued" line (BACKLOG #7581). The roots are then compared + case-insensitively and EXACTLY, never by prefix: every worktree cwd in this repo is an extension of the primary checkout's path, so a prefix match resolves any peer to some arbitrary worktree. VS Code also records a lowercase drive letter where the Desktop app records an uppercase one, so a case-sensitive compare splits one worktree into two boxes. @@ -118,7 +123,7 @@ param( # a caller whose stdin stays open and silent (the Bash tool) waits forever. Measured 2026-10-13/14: # four sends hung. The one box checked got nothing. The refusal is right after this param block. [Parameter(ParameterSetName = 'Send')][switch]$Send, - # Recipient worktree. A path (matched case-insensitively and exactly), a seat id from the shared + # Recipient worktree. A path in a worktree (keyed on that worktree's root), a seat id from the shared # seat registry (e.g. autonomy-plan-62022e2c, for a seat on another PC), or "all" to broadcast to # every live peer in this repo. Defaults to nothing: refusing to guess is the point. [Parameter(ParameterSetName = 'Send')][string]$To, @@ -256,6 +261,11 @@ function Resolve-SeatRecipient { # healthy. See mail-key.ps1 for why the normalisation is load-bearing. . "$PSScriptRoot\mail-key.ps1" +# The worktree root a path sits in, by the DRAIN's rule: Get-CcxWorktreeRoot, the first directory at +# or above the path that holds `.git`. One definition, not a third copy beside the drain's and +# seat.ps1's; see ADDRESSING in the header. Functions only, so dot-sourcing it runs nothing. +. (Join-Path (Split-Path -Parent $PSScriptRoot) 'hooks/_hookinput.ps1') + # The claim primitive is shared with the drain for exactly the reason the box key is: three call sites # hand-rolling "did my move win" is three chances for one of them to drift back to a check that was # measured unable to tell a winner from a loser. See mail-claim.ps1. @@ -480,7 +490,11 @@ if ($Send) { $rosterUnavailable = @($rosterErr | Where-Object { $_ -match 'UNAVAILABLE' }).Count -gt 0 $roster = @() try { $roster = @($rosterJson | ConvertFrom-Json) } catch { $roster = @(); $rosterUnavailable = $true } - $me = (Get-Location).Path.TrimEnd('\', '/').ToLowerInvariant() + # Both sides raised to the worktree root, so a session whose cwd is a subdirectory is still + # this worktree, and a peer's box is the one its drain reads. + $me = Get-CcxWorktreeRoot (Get-Location).Path + if (-not $me) { $me = (Get-Location).Path } + $outside = 0 foreach ($r in $roster) { # Cwd, NOT Worktree. `Worktree` is the roster's DISPLAY LABEL -- a bare leaf name like # `builder--session-` -- while `Cwd` carries the addressable absolute path. The two @@ -501,8 +515,14 @@ if ($Send) { # This comparison used to be made against $r.Worktree -- a bare name tested against an # absolute path, so it could never match and NEVER excluded anyone. Self-exclusion rested # entirely on IsSelf. Against Cwd it finally does the job it was written to do. - if ($r.Cwd.TrimEnd('\', '/').ToLowerInvariant() -eq $me) { continue } - $targets += $r.Cwd + $top = Get-CcxWorktreeRoot $r.Cwd + # A peer whose cwd is in no worktree has no box a send can name; counted, not hashed. + if (-not $top) { $outside++; continue } + if (Test-CcxSamePath $top $me) { continue } + $targets += $top + } + if ($outside -gt 0) { + Write-Host "Skipped $outside live peer(s) whose cwd is in no git worktree: no box can be named for them." } if ($targets.Count -eq 0) { # THE TWO CASES ARE NOW SEPARATED BY EVIDENCE RATHER THAN BY ASSERTION, and they exit @@ -523,7 +543,12 @@ if ($Send) { } } elseif (Test-Path -LiteralPath $To -PathType Container) { - $targets = @((Resolve-Path -LiteralPath $To).Path) + $top = Get-CcxWorktreeRoot (Resolve-Path -LiteralPath $To).Path + if (-not $top) { + throw ("Refusing to send: '$To' is in no git worktree, so no drain reads a box keyed on it. " + + "Pass a worktree path, or a seat id from the shared seat registry.") + } + $targets = @($top) } else { # Not a directory here. It may be a seat id for a seat on another PC; see ADDRESSING. @@ -601,7 +626,14 @@ if ($Send) { # reporting layer. Every target gets its own row and its own status. # One row per recipient. A path is keyed through ConvertTo-BoxKey; a seat id already IS the key. $rows = @() - foreach ($t in $targets) { $rows += [pscustomobject]@{ To = $t; Key = (ConvertTo-BoxKey -Path $t); Cwd = $t } } + # Two sessions in one worktree share its box, so a broadcast names that box once. + $keyed = @{} + foreach ($t in $targets) { + $k = ConvertTo-BoxKey -Path $t + if ($keyed.ContainsKey($k)) { continue } + $keyed[$k] = $true + $rows += [pscustomobject]@{ To = $t; Key = $k; Cwd = $t } + } foreach ($s in $seatTargets) { $label = if ($s.Host) { "$($s.Key) (seat on $($s.Host))" } else { "$($s.Key) (seat)" } $cwd = if ($s.Worktree) { $s.Worktree } else { $s.Key } @@ -701,8 +733,11 @@ if ($List) { exit 0 } -# -Status (default): this worktree's own box. +# -Status (default): this worktree's own box, keyed on its root as the send path keys it. A cwd in +# no worktree keeps its own path: that is the box an -AnchorRepo drain reads (docs/SESSION-MAIL.md). $here = (Get-Location).Path +$hereTop = Get-CcxWorktreeRoot $here +if ($hereTop) { $here = $hereTop } $key = ConvertTo-BoxKey -Path $here # The box under the old path-only key, read only. The drain moves the inbox names this channel # minted into $key, so only those are counted as waiting; claiming/ and stranded/ stay where they are, diff --git a/tests/test_session_mail_toplevel.py b/tests/test_session_mail_toplevel.py new file mode 100644 index 0000000000..90c13ca150 --- /dev/null +++ b/tests/test_session_mail_toplevel.py @@ -0,0 +1,124 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""mail.ps1 addresses a box by the worktree TOPLEVEL, the way the drain and seat.ps1 key it. + +BACKLOG #7581 (Argon S33-75). A box is keyed on the recipient's worktree root: seat.ps1 publishes the +key of ``git rev-parse --show-toplevel``, and a session's drain reads the box of the worktree it runs +in. ``-Send -To `` used to hash the resolved path as given, so a path INSIDE a worktree minted +a box beside the real one that nobody drains, and the sender was told ``Queued``. ``-Status`` run +from a subdirectory reported that same shadow box. Each arm below drives the real scripts against a +throwaway repo and the repo's own fixture mail root, never a live queue. +""" + +from __future__ import annotations + +import json +import subprocess +from pathlib import Path +from typing import Any + +import pytest +from _session_mail_harness import ( + MAIL, + TIMEOUT, + injection, + mail_root, + repo, + requires_pwsh_on_windows, + run_drain, +) + +__all__ = ["repo"] # re-exported so pytest resolves the fixture in this module + +pytestmark = requires_pwsh_on_windows + + +def _mail(cwd: Path, root: Path, *args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [ + "pwsh", + "-NoProfile", + "-NonInteractive", + "-File", + str(MAIL), + "-MailRoot", + str(root), + *args, + ], + cwd=str(cwd), + capture_output=True, + text=True, + timeout=TIMEOUT, + check=False, + ) + + +def _status(cwd: Path, root: Path) -> Any: + proc = _mail(cwd, root, "-Status", "-Json") + assert proc.returncode == 0, proc.stderr + return json.loads(proc.stdout) + + +def _boxes(root: Path) -> list[str]: + d = root / "box" + return sorted(p.name for p in d.iterdir()) if d.is_dir() else [] + + +def test_a_send_to_a_path_inside_the_worktree_reaches_the_worktrees_drain(repo: Path) -> None: + sub = repo / "deep" / "er" + sub.mkdir(parents=True) + root = mail_root(repo) + send = _mail(repo, root, "-Send", "-Json", "-To", str(sub), "-Body", "sent to a subdirectory") + assert send.returncode == 0, send.stderr + rows = json.loads(send.stdout) + assert rows[0]["Key"] == _status(repo, root)["Key"], rows + # The box the drain reads, and the only box: no shadow box was minted for the subdirectory. + assert _boxes(root) == [rows[0]["Key"]] + assert " | sent to a subdirectory" in injection(run_drain(repo)) + + +@pytest.mark.parametrize("spell", ["upper", "slash", "trailing", "dotdot"]) +def test_every_spelling_of_the_worktree_addresses_one_box(repo: Path, spell: str) -> None: + (repo / "x").mkdir() + spelled = { + "upper": str(repo).upper(), + "slash": str(repo).replace("\\", "/"), + "trailing": str(repo) + "\\", + "dotdot": str(repo / "x" / ".."), + }[spell] + root = mail_root(repo) + send = _mail(repo, root, "-Send", "-Json", "-To", spelled, "-Body", "spelled") + assert send.returncode == 0, send.stderr + assert json.loads(send.stdout)[0]["Key"] == _status(repo, root)["Key"] + + +def test_a_send_to_a_directory_in_no_worktree_is_refused_and_writes_nothing( + repo: Path, tmp_path: Path +) -> None: + loose = tmp_path / "not-a-checkout" + loose.mkdir() + probe = subprocess.run( + ["git", "-C", str(loose), "rev-parse", "--show-toplevel"], + capture_output=True, + text=True, + check=False, + ) + assert probe.returncode != 0, f"{loose} is inside a checkout, so this arm proves nothing" + root = mail_root(repo) + send = _mail(repo, root, "-Send", "-To", str(loose), "-Body", "into the void") + assert send.returncode != 0, send.stdout + assert "in no git worktree" in send.stderr, send.stderr + assert _boxes(root) == [] + # The control: the same call to the worktree itself sends, so the refusal is not a broken send. + ok = _mail(repo, root, "-Send", "-To", str(repo), "-Body", "into the box") + assert ok.returncode == 0, ok.stderr + + +def test_status_from_a_subdirectory_reports_the_worktrees_own_box(repo: Path) -> None: + sub = repo / "nested" + sub.mkdir() + root = mail_root(repo) + at_top = _status(repo, root) + below = _status(sub, root) + assert below["Key"] == at_top["Key"], (below, at_top) + assert Path(below["Worktree"]) == Path(at_top["Worktree"]) From fb6df84d578212911267dc7a3301f030fa425bfe Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 03:47:47 -0600 Subject: [PATCH 08/14] Stop-hook notice shim emits a systemMessage so the missing-script notice is seen New-NoticeShimCommand is wired only on Stop rows (seat-record.ps1, wiki-write-prompt.ps1). It printed its missing-script notice as plain exit-0 stdout, which a Stop hook shows to neither the user nor the model, so the notice was as silent as the std shim it was built to replace. It now prints {"systemMessage": ""}, the field every hook event accepts and the user is shown; it does not block the Stop or add to context. Tests drive the installed Stop shims from a temp settings file: missing script gives a systemMessage (red before this change), a foreign repo stays silent, and a resolved script runs with no notice. BACKLOG #7575 (RC-S33-63). Proposed PR title: Stop-hook notice shim emits a systemMessage (BACKLOG #7575) Proposed ledger banner: CLOSED -- the notice shim on the Stop rows now emits a systemMessage the user sees; failing test plus fix in tests/test_announce_wiring.py. --- scripts/coord/install-coordination.ps1 | 8 +++ tests/test_announce_wiring.py | 75 ++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) diff --git a/scripts/coord/install-coordination.ps1 b/scripts/coord/install-coordination.ps1 index 7239fb8986..f26c97896a 100644 --- a/scripts/coord/install-coordination.ps1 +++ b/scripts/coord/install-coordination.ps1 @@ -261,7 +261,15 @@ function New-AnnounceShimCommand { # # The wiki write prompt needs the same shape for the same reason, so one builder serves any row that # sets Shim = "notice" and carries its own Notice text. +# +# WHY THE NOTICE IS {"systemMessage": ...} JSON AND NOT PLAIN TEXT (BACKLOG #7575). Every row that uses +# this shim is a Stop hook. Plain exit-0 stdout reaches context only on SessionStart, UserPromptSubmit +# and a few other events (scripts/hooks/precompact-reprime.ps1 records the list); on Stop it goes to +# the debug log and nobody sees it, so a plain-text notice was as silent as the std shim it replaced. +# systemMessage is a field every hook event accepts and the user is shown; it neither blocks the Stop +# nor adds to context -- the same form install-gate.ps1's fail-open notice uses. function New-NoticeShimCommand([string]$RelativeScript, [string]$Marker, [string]$Notice) { + $Notice =([ordered]@{ systemMessage = $Notice } | ConvertTo-Json -Compress) # The notice sits inside a single-quoted literal, so double any single quote it carries. $Notice = $Notice.Replace("'", "''") return ( diff --git a/tests/test_announce_wiring.py b/tests/test_announce_wiring.py index bf00187654..a2d7079074 100644 --- a/tests/test_announce_wiring.py +++ b/tests/test_announce_wiring.py @@ -482,3 +482,78 @@ def test_the_installed_announce_shim_is_inert_outside_a_git_repo( proc = _run_shim(_extract_shim(settings, tmp_path), outside) assert proc.returncode == 0 assert proc.stdout.strip() == "" + + +# -------------------------------------------------------------------------------------------------- +# The NOTICE shim on the Stop rows (seat recorder, wiki write prompt) -- BACKLOG #7575. +# +# Plain exit-0 stdout from a Stop hook reaches neither the user nor the model, so a plain-text notice +# on these rows was as silent as the std shim it was built to replace. The notice is a systemMessage, +# the field the user is shown on every event. +# -------------------------------------------------------------------------------------------------- + +_NOTICE_ROWS = [ + (_marker("SEAT_MARKER"), "scripts/hooks/seat-record.ps1"), + (_marker("WIKI_MARKER"), "scripts/hooks/wiki-write-prompt.ps1"), +] + + +def _stop_notice_shim(settings: Path, tmp_path: Path, marker: str) -> Path: + hits = [c for c in _cmds(load(settings), "Stop") if c.startswith(f"# {marker}\n")] + assert len(hits) == 1, f"expected exactly one Stop entry for {marker}, got {len(hits)}" + p = tmp_path / f"{marker}-shim.ps1" + p.write_text(hits[0], encoding="utf-8") + return p + + +def _run_stop_shim(shim: Path, cwd: Path) -> subprocess.CompletedProcess[str]: + return subprocess.run( + ["pwsh", "-NoProfile", "-NonInteractive", "-File", str(shim)], + cwd=str(cwd), + input=json.dumps({"session_id": "x", "hook_event_name": "Stop"}), + capture_output=True, + text=True, + timeout=TIMEOUT, + check=False, + ) + + +@pytest.mark.parametrize(("marker", "script"), _NOTICE_ROWS) +def test_a_stop_notice_shim_says_so_as_a_system_message( + settings: Path, tmp_path: Path, marker: str, script: str +) -> None: + """Red before #7575: stdout was the bare notice text, which a Stop hook shows nobody.""" + primary = _fixture_primary(tmp_path, with_announce=False) + wt = _linked_worktree(primary, tmp_path) + run_installer(settings) + proc = _run_stop_shim(_stop_notice_shim(settings, tmp_path, marker), wt) + assert proc.returncode == 0, proc.stderr + out = json.loads(proc.stdout) + assert set(out) == {"systemMessage"}, out + assert f"{script} is missing from this checkout" in out["systemMessage"] + + +@pytest.mark.parametrize(("marker", "script"), _NOTICE_ROWS) +def test_a_stop_notice_shim_is_silent_in_a_repo_that_is_not_messagefoundry( + settings: Path, tmp_path: Path, marker: str, script: str +) -> None: + primary = _fixture_primary(tmp_path, with_announce=False, with_presence=False) + run_installer(settings) + proc = _run_stop_shim(_stop_notice_shim(settings, tmp_path, marker), primary) + assert proc.returncode == 0 + assert proc.stdout.strip() == "", f"notice leaked into a foreign repo: {proc.stdout!r}" + + +@pytest.mark.parametrize(("marker", "script"), _NOTICE_ROWS) +def test_a_stop_notice_shim_runs_the_resolved_script_and_prints_no_notice( + settings: Path, tmp_path: Path, marker: str, script: str +) -> None: + primary = _fixture_primary(tmp_path, with_announce=False) + target = primary / script + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("Write-Output 'PRIMARY-STOP-HOOK-RAN'\n", encoding="utf-8") + wt = _linked_worktree(primary, tmp_path) + run_installer(settings) + proc = _run_stop_shim(_stop_notice_shim(settings, tmp_path, marker), wt) + assert proc.returncode == 0, proc.stderr + assert proc.stdout.strip() == "PRIMARY-STOP-HOOK-RAN", proc.stdout From c54cfbc7ca9eae713141559009b2cafdcedf66ce Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 03:58:28 -0600 Subject: [PATCH 09/14] mail.ps1 refuses a -To path below a worktree root instead of raising it Review round 1 (xhigh) falsified the first commit's premise: the drain keys a box on the cwd it runs in (mail-drain.ps1 $session.Dir), not on the worktree root, and Get-CcxWorktreeRoot raises a removed worktree's leftover directory under the primary to the primary's root. Raising paths therefore moved the shadow-box split to the drain end and could misdeliver to the primary session. So -Status and -To all go back to origin/main behaviour, and -Send -To now REFUSES a path inside a worktree that is not its root, naming the root. A path in no worktree still sends: that is the box an -AnchorRepo drain reads. BACKLOG #7581 (Argon S33-75). Proposed PR title: mail.ps1 refuses a -To path below a worktree root (BACKLOG #7581) Proposed banner: PARTIAL -- S33-75's -To half built: a path below a worktree root is refused, naming the root. Remains: the drain, mail-watch.ps1 and seat.ps1 key on different paths (cwd, raw hook cwd, show-toplevel), so a session launched below its root reads a box its seat id does not name -- one keyer for all of them is the fix; -To all reads only presence.ps1 (no cross-PC or Codex seats); S33-76 (-Status NextDrainShowsAtLeast counts expired, unparseable and unminted rows and omits the drain's frame and line-prefix bytes), confirmed by reading, unbuilt. --- docs/SESSION-MAIL.md | 17 ++--- scripts/coord/mail.ps1 | 63 +++++++------------ tests/test_session_mail_toplevel.py | 98 ++++++++++++++--------------- 3 files changed, 74 insertions(+), 104 deletions(-) diff --git a/docs/SESSION-MAIL.md b/docs/SESSION-MAIL.md index 84af4839bf..0cad54664e 100644 --- a/docs/SESSION-MAIL.md +++ b/docs/SESSION-MAIL.md @@ -152,9 +152,11 @@ pwsh -NoProfile -File scripts\coord\mail.ps1 -List pwsh -NoProfile -File scripts\coord\mail.ps1 -Status ``` -- `-To ` -- the recipient **worktree** path. A path inside a worktree names that worktree's box, - and a path in no worktree is refused (see *Raised to the worktree root* below). Matched - case-insensitively and exactly. `all` broadcasts to the live roster from [`presence.ps1`](../scripts/coord/presence.ps1). +- `-To ` -- the recipient **worktree** root. A path inside a worktree but not its root is + refused, naming the root: a session's drain keys its box on the cwd it runs in, normally the root, + so a box keyed on a subdirectory would go unread (BACKLOG #7581). A path in no worktree is still + accepted, for an `-AnchorRepo` session. Matched case-insensitively and exactly. `all` + broadcasts to the live roster from [`presence.ps1`](../scripts/coord/presence.ps1). - `-To ` -- a seat record's id, such as `autonomy-plan-62022e2c`, accepted when the seat registry holds a readable record for it that names a worktree. **Use this for a seat on another PC**: its worktree path does not exist here, so the path form cannot reach it. A seat id hashes the host as well as the @@ -210,15 +212,6 @@ spelled two ways, and a case-sensitive key splits it into two boxes that never s The normalisation also trims a trailing separator and folds forward slashes to back slashes, because some producers are git and some are Windows. -**Raised to the worktree root first.** Every path a send or `-Status` addresses is first raised to the -first directory at or above it that holds `.git`, by the drain's own rule (`Get-CcxWorktreeRoot` in -[`scripts/hooks/_hookinput.ps1`](../scripts/hooks/_hookinput.ps1)); `seat.ps1` keys a seat on the same -root. A path below the root hashed as given would mint a box beside the real one that no drain reads, -under a `Queued` line (BACKLOG #7581). So `-Send -To` refuses a path in no worktree, and `-To all` -skips a live peer whose cwd is in none and says how many it skipped. One consequence: `mail.ps1` -cannot address an `-AnchorRepo` container session by path, though `-Status` run from one still reads -its own box. - **Matched EXACTLY, never by prefix.** Every worktree path in this repo is an extension of the primary checkout's path. A prefix match therefore resolves *any* peer to some arbitrary worktree -- most likely the primary one -- and does so silently, because a wrong-but-existing box looks exactly like a right diff --git a/scripts/coord/mail.ps1 b/scripts/coord/mail.ps1 index 2023bd372a..7365aee214 100644 --- a/scripts/coord/mail.ps1 +++ b/scripts/coord/mail.ps1 @@ -57,12 +57,13 @@ seat's worktree and host key to now, never to the old box, which every PC at that path reads. A record under it that names no host is refused, and so is any seat record that names no worktree: neither can be keyed to one PC's box. - A PATH IS FIRST RAISED TO ITS WORKTREE ROOT, the first directory at or above it holding `.git`, - by the drain's own rule (Get-CcxWorktreeRoot in scripts/hooks/_hookinput.ps1); seat.ps1 keys a - seat on the same root, read as `git rev-parse --show-toplevel`. A path inside a worktree therefore - names that worktree's box, and a -To path in no worktree is refused: hashed as given, either would - mint a box nobody drains under a "Queued" line (BACKLOG #7581). The roots are then compared - case-insensitively and EXACTLY, never by prefix: every worktree cwd in this repo is + A -To PATH INSIDE A WORKTREE BUT NOT ITS ROOT IS REFUSED, naming the root (BACKLOG #7581). It is + hashed as given, and a session's drain keys its box on the cwd it runs in, which is its worktree + root unless it was launched below it; seat.ps1 publishes the root's key. So a box keyed on a + subdirectory is one no drain is likely to read, and a leftover directory of a removed worktree + nested under the primary is not quietly re-addressed to the primary's session either. A path in no + worktree is still accepted: that is the box an -AnchorRepo drain reads (docs/SESSION-MAIL.md). + A cwd is matched case-insensitively and EXACTLY, never by prefix: every worktree cwd in this repo is an extension of the primary checkout's path, so a prefix match resolves any peer to some arbitrary worktree. VS Code also records a lowercase drive letter where the Desktop app records an uppercase one, so a case-sensitive compare splits one worktree into two boxes. @@ -123,7 +124,7 @@ param( # a caller whose stdin stays open and silent (the Bash tool) waits forever. Measured 2026-10-13/14: # four sends hung. The one box checked got nothing. The refusal is right after this param block. [Parameter(ParameterSetName = 'Send')][switch]$Send, - # Recipient worktree. A path in a worktree (keyed on that worktree's root), a seat id from the shared + # Recipient worktree. A worktree ROOT path (matched case-insensitively and exactly), a seat id from the shared # seat registry (e.g. autonomy-plan-62022e2c, for a seat on another PC), or "all" to broadcast to # every live peer in this repo. Defaults to nothing: refusing to guess is the point. [Parameter(ParameterSetName = 'Send')][string]$To, @@ -261,9 +262,8 @@ function Resolve-SeatRecipient { # healthy. See mail-key.ps1 for why the normalisation is load-bearing. . "$PSScriptRoot\mail-key.ps1" -# The worktree root a path sits in, by the DRAIN's rule: Get-CcxWorktreeRoot, the first directory at -# or above the path that holds `.git`. One definition, not a third copy beside the drain's and -# seat.ps1's; see ADDRESSING in the header. Functions only, so dot-sourcing it runs nothing. +# Get-CcxWorktreeRoot, the drain's own test of which worktree a path sits in (the first directory at +# or above it holding `.git`). Reused rather than copied; functions only, so dot-sourcing runs nothing. . (Join-Path (Split-Path -Parent $PSScriptRoot) 'hooks/_hookinput.ps1') # The claim primitive is shared with the drain for exactly the reason the box key is: three call sites @@ -490,11 +490,7 @@ if ($Send) { $rosterUnavailable = @($rosterErr | Where-Object { $_ -match 'UNAVAILABLE' }).Count -gt 0 $roster = @() try { $roster = @($rosterJson | ConvertFrom-Json) } catch { $roster = @(); $rosterUnavailable = $true } - # Both sides raised to the worktree root, so a session whose cwd is a subdirectory is still - # this worktree, and a peer's box is the one its drain reads. - $me = Get-CcxWorktreeRoot (Get-Location).Path - if (-not $me) { $me = (Get-Location).Path } - $outside = 0 + $me = (Get-Location).Path.TrimEnd('\', '/').ToLowerInvariant() foreach ($r in $roster) { # Cwd, NOT Worktree. `Worktree` is the roster's DISPLAY LABEL -- a bare leaf name like # `builder--session-` -- while `Cwd` carries the addressable absolute path. The two @@ -515,14 +511,8 @@ if ($Send) { # This comparison used to be made against $r.Worktree -- a bare name tested against an # absolute path, so it could never match and NEVER excluded anyone. Self-exclusion rested # entirely on IsSelf. Against Cwd it finally does the job it was written to do. - $top = Get-CcxWorktreeRoot $r.Cwd - # A peer whose cwd is in no worktree has no box a send can name; counted, not hashed. - if (-not $top) { $outside++; continue } - if (Test-CcxSamePath $top $me) { continue } - $targets += $top - } - if ($outside -gt 0) { - Write-Host "Skipped $outside live peer(s) whose cwd is in no git worktree: no box can be named for them." + if ($r.Cwd.TrimEnd('\', '/').ToLowerInvariant() -eq $me) { continue } + $targets += $r.Cwd } if ($targets.Count -eq 0) { # THE TWO CASES ARE NOW SEPARATED BY EVIDENCE RATHER THAN BY ASSERTION, and they exit @@ -543,12 +533,15 @@ if ($Send) { } } elseif (Test-Path -LiteralPath $To -PathType Container) { - $top = Get-CcxWorktreeRoot (Resolve-Path -LiteralPath $To).Path - if (-not $top) { - throw ("Refusing to send: '$To' is in no git worktree, so no drain reads a box keyed on it. " + - "Pass a worktree path, or a seat id from the shared seat registry.") + $full = (Resolve-Path -LiteralPath $To).Path + # A path below a worktree root; see ADDRESSING. Refused, never raised: raising it would send a + # removed worktree's leftover directory to the primary checkout's session. + $top = Get-CcxWorktreeRoot $full + if ($top -and -not (Test-CcxSamePath $top $full)) { + throw ("Refusing to send: '$To' is inside the worktree $top but is not its root, and a box " + + "keyed on it is one no drain is likely to read. Send to the worktree root, or to its seat id.") } - $targets = @($top) + $targets = @($full) } else { # Not a directory here. It may be a seat id for a seat on another PC; see ADDRESSING. @@ -626,14 +619,7 @@ if ($Send) { # reporting layer. Every target gets its own row and its own status. # One row per recipient. A path is keyed through ConvertTo-BoxKey; a seat id already IS the key. $rows = @() - # Two sessions in one worktree share its box, so a broadcast names that box once. - $keyed = @{} - foreach ($t in $targets) { - $k = ConvertTo-BoxKey -Path $t - if ($keyed.ContainsKey($k)) { continue } - $keyed[$k] = $true - $rows += [pscustomobject]@{ To = $t; Key = $k; Cwd = $t } - } + foreach ($t in $targets) { $rows += [pscustomobject]@{ To = $t; Key = (ConvertTo-BoxKey -Path $t); Cwd = $t } } foreach ($s in $seatTargets) { $label = if ($s.Host) { "$($s.Key) (seat on $($s.Host))" } else { "$($s.Key) (seat)" } $cwd = if ($s.Worktree) { $s.Worktree } else { $s.Key } @@ -733,11 +719,8 @@ if ($List) { exit 0 } -# -Status (default): this worktree's own box, keyed on its root as the send path keys it. A cwd in -# no worktree keeps its own path: that is the box an -AnchorRepo drain reads (docs/SESSION-MAIL.md). +# -Status (default): this worktree's own box. $here = (Get-Location).Path -$hereTop = Get-CcxWorktreeRoot $here -if ($hereTop) { $here = $hereTop } $key = ConvertTo-BoxKey -Path $here # The box under the old path-only key, read only. The drain moves the inbox names this channel # minted into $key, so only those are counted as waiting; claiming/ and stranded/ stay where they are, diff --git a/tests/test_session_mail_toplevel.py b/tests/test_session_mail_toplevel.py index 90c13ca150..13a6cf5f3d 100644 --- a/tests/test_session_mail_toplevel.py +++ b/tests/test_session_mail_toplevel.py @@ -1,13 +1,12 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors -"""mail.ps1 addresses a box by the worktree TOPLEVEL, the way the drain and seat.ps1 key it. - -BACKLOG #7581 (Argon S33-75). A box is keyed on the recipient's worktree root: seat.ps1 publishes the -key of ``git rev-parse --show-toplevel``, and a session's drain reads the box of the worktree it runs -in. ``-Send -To `` used to hash the resolved path as given, so a path INSIDE a worktree minted -a box beside the real one that nobody drains, and the sender was told ``Queued``. ``-Status`` run -from a subdirectory reported that same shadow box. Each arm below drives the real scripts against a -throwaway repo and the repo's own fixture mail root, never a live queue. +"""mail.ps1 refuses a -To path inside a worktree that is not the worktree's root. + +BACKLOG #7581 (Argon S33-75). ``-Send -To `` hashes the path as given. A session's drain keys +its box on the cwd it runs in, normally its worktree root, and seat.ps1 publishes the root's key, so a +box keyed on a subdirectory is one no drain is likely to read -- and the sender was told ``Queued``. +The send is refused instead, naming the root. Each arm drives the real scripts against a throwaway +repo and its own fixture mail root, never a live queue. """ from __future__ import annotations @@ -15,10 +14,10 @@ import json import subprocess from pathlib import Path -from typing import Any import pytest from _session_mail_harness import ( + COORD, MAIL, TIMEOUT, injection, @@ -53,32 +52,43 @@ def _mail(cwd: Path, root: Path, *args: str) -> subprocess.CompletedProcess[str] ) -def _status(cwd: Path, root: Path) -> Any: - proc = _mail(cwd, root, "-Status", "-Json") - assert proc.returncode == 0, proc.stderr - return json.loads(proc.stdout) - - def _boxes(root: Path) -> list[str]: d = root / "box" return sorted(p.name for p in d.iterdir()) if d.is_dir() else [] -def test_a_send_to_a_path_inside_the_worktree_reaches_the_worktrees_drain(repo: Path) -> None: +def _worktree_root(path: Path) -> str: + """The decision mail.ps1 makes, read with the same function rather than with git.""" + lib = COORD.parent / "hooks" / "_hookinput.ps1" + proc = subprocess.run( + ["pwsh", "-NoProfile", "-NonInteractive", "-Command", + f". '{lib}'; [string](Get-CcxWorktreeRoot '{path}')"], + capture_output=True, text=True, timeout=TIMEOUT, check=True, + ) # fmt: skip + return proc.stdout.strip() + + +def test_a_send_to_a_path_below_the_worktree_root_is_refused_and_writes_nothing( + repo: Path, +) -> None: sub = repo / "deep" / "er" sub.mkdir(parents=True) root = mail_root(repo) - send = _mail(repo, root, "-Send", "-Json", "-To", str(sub), "-Body", "sent to a subdirectory") - assert send.returncode == 0, send.stderr - rows = json.loads(send.stdout) - assert rows[0]["Key"] == _status(repo, root)["Key"], rows - # The box the drain reads, and the only box: no shadow box was minted for the subdirectory. - assert _boxes(root) == [rows[0]["Key"]] - assert " | sent to a subdirectory" in injection(run_drain(repo)) + send = _mail(repo, root, "-Send", "-To", str(sub), "-Body", "sent to a subdirectory") + assert send.returncode != 0, send.stdout + assert "is not its root" in send.stderr, send.stderr + assert str(repo) in send.stderr, "the refusal must name the root to send to instead" + assert _boxes(root) == [], "a shadow box was minted for the subdirectory" + # The control: the root itself sends, and the worktree's drain shows it. + ok = _mail(repo, root, "-Send", "-To", str(repo), "-Body", "sent to the root") + assert ok.returncode == 0, ok.stderr + assert " | sent to the root" in injection(run_drain(repo)) @pytest.mark.parametrize("spell", ["upper", "slash", "trailing", "dotdot"]) -def test_every_spelling_of_the_worktree_addresses_one_box(repo: Path, spell: str) -> None: +def test_every_spelling_of_the_worktree_root_addresses_one_box(repo: Path, spell: str) -> None: + """A pin: these already shared a key through ConvertTo-BoxKeyPath and Resolve-Path. The new + below-the-root refusal must not take any of them for a subdirectory.""" (repo / "x").mkdir() spelled = { "upper": str(repo).upper(), @@ -87,38 +97,22 @@ def test_every_spelling_of_the_worktree_addresses_one_box(repo: Path, spell: str "dotdot": str(repo / "x" / ".."), }[spell] root = mail_root(repo) + plain = _mail(repo, root, "-Send", "-Json", "-To", str(repo), "-Body", "plain") send = _mail(repo, root, "-Send", "-Json", "-To", spelled, "-Body", "spelled") + assert plain.returncode == 0, plain.stderr assert send.returncode == 0, send.stderr - assert json.loads(send.stdout)[0]["Key"] == _status(repo, root)["Key"] + assert json.loads(send.stdout)[0]["Key"] == json.loads(plain.stdout)[0]["Key"] -def test_a_send_to_a_directory_in_no_worktree_is_refused_and_writes_nothing( +def test_a_path_in_no_worktree_still_sends_for_an_anchored_session( repo: Path, tmp_path: Path ) -> None: - loose = tmp_path / "not-a-checkout" - loose.mkdir() - probe = subprocess.run( - ["git", "-C", str(loose), "rev-parse", "--show-toplevel"], - capture_output=True, - text=True, - check=False, + """The must-not-trip arm. An -AnchorRepo drain keys its box on a cwd in no worktree, so that + path stays addressable; the refusal is only for a path below a worktree root.""" + container = tmp_path / "container" + container.mkdir() + assert _worktree_root(container) == "", ( + f"{container} sits in a worktree; this arm proves nothing" ) - assert probe.returncode != 0, f"{loose} is inside a checkout, so this arm proves nothing" - root = mail_root(repo) - send = _mail(repo, root, "-Send", "-To", str(loose), "-Body", "into the void") - assert send.returncode != 0, send.stdout - assert "in no git worktree" in send.stderr, send.stderr - assert _boxes(root) == [] - # The control: the same call to the worktree itself sends, so the refusal is not a broken send. - ok = _mail(repo, root, "-Send", "-To", str(repo), "-Body", "into the box") - assert ok.returncode == 0, ok.stderr - - -def test_status_from_a_subdirectory_reports_the_worktrees_own_box(repo: Path) -> None: - sub = repo / "nested" - sub.mkdir() - root = mail_root(repo) - at_top = _status(repo, root) - below = _status(sub, root) - assert below["Key"] == at_top["Key"], (below, at_top) - assert Path(below["Worktree"]) == Path(at_top["Worktree"]) + send = _mail(repo, mail_root(repo), "-Send", "-To", str(container), "-Body", "anchored") + assert send.returncode == 0, send.stderr From dcc787d233a78355773237000d2eeff820fe28e5 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 04:03:03 -0600 Subject: [PATCH 10/14] Notice-shim tests derive their rows from the installer and pin them to Stop Review round 1 repairs: the notice rows are parsed from $WIRING rather than hardcoded, and a test pins every notice row to the Stop event (the only event the systemMessage form is right for) and to an ASCII notice (the shim sets no output encoding). Adds the not-a-git-repo silence case and drops a restated premise from the test comment. The builder keeps its input parameter and names the escaped JSON separately. BACKLOG #7575 (RC-S33-63). Proposed PR title: Stop-hook notice shim emits a systemMessage (BACKLOG #7575) Proposed ledger banner: CLOSED -- the notice shim on the Stop rows now emits a systemMessage the user sees; failing test plus fix in tests/test_announce_wiring.py. Not live-measured in the app. --- scripts/coord/install-coordination.ps1 | 9 +++-- tests/test_announce_wiring.py | 48 ++++++++++++++++++-------- 2 files changed, 37 insertions(+), 20 deletions(-) diff --git a/scripts/coord/install-coordination.ps1 b/scripts/coord/install-coordination.ps1 index f26c97896a..3830a1e16d 100644 --- a/scripts/coord/install-coordination.ps1 +++ b/scripts/coord/install-coordination.ps1 @@ -263,15 +263,14 @@ function New-AnnounceShimCommand { # sets Shim = "notice" and carries its own Notice text. # # WHY THE NOTICE IS {"systemMessage": ...} JSON AND NOT PLAIN TEXT (BACKLOG #7575). Every row that uses -# this shim is a Stop hook. Plain exit-0 stdout reaches context only on SessionStart, UserPromptSubmit +# this shim is a Stop hook (tests/test_announce_wiring.py pins that). Plain exit-0 stdout reaches context only on SessionStart, UserPromptSubmit # and a few other events (scripts/hooks/precompact-reprime.ps1 records the list); on Stop it goes to # the debug log and nobody sees it, so a plain-text notice was as silent as the std shim it replaced. # systemMessage is a field every hook event accepts and the user is shown; it neither blocks the Stop # nor adds to context -- the same form install-gate.ps1's fail-open notice uses. function New-NoticeShimCommand([string]$RelativeScript, [string]$Marker, [string]$Notice) { - $Notice =([ordered]@{ systemMessage = $Notice } | ConvertTo-Json -Compress) - # The notice sits inside a single-quoted literal, so double any single quote it carries. - $Notice = $Notice.Replace("'", "''") + # The JSON sits inside a single-quoted literal, so double any single quote it carries. + $json = ([ordered]@{ systemMessage = $Notice } | ConvertTo-Json -Compress).Replace("'", "''") return ( "# $Marker`n" + '$c = (& git rev-parse --path-format=absolute --git-common-dir 2>$null); ' + @@ -282,7 +281,7 @@ function New-NoticeShimCommand([string]$RelativeScript, [string]$Marker, [string 'if (Test-Path -LiteralPath (Join-Path $b ''scripts/coord/presence.ps1'')) { $mf = $true } ' + "`$s = Join-Path `$b '$RelativeScript'; " + 'if (Test-Path -LiteralPath $s) { & $s; $hit = $true; break } } ' + - 'if (-not $hit -and $mf) { Write-Output ' + "'$Notice'" + ' } }' + 'if (-not $hit -and $mf) { Write-Output ' + "'$json'" + ' } }' ) } diff --git a/tests/test_announce_wiring.py b/tests/test_announce_wiring.py index a2d7079074..2497923ac8 100644 --- a/tests/test_announce_wiring.py +++ b/tests/test_announce_wiring.py @@ -485,17 +485,30 @@ def test_the_installed_announce_shim_is_inert_outside_a_git_repo( # -------------------------------------------------------------------------------------------------- -# The NOTICE shim on the Stop rows (seat recorder, wiki write prompt) -- BACKLOG #7575. -# -# Plain exit-0 stdout from a Stop hook reaches neither the user nor the model, so a plain-text notice -# on these rows was as silent as the std shim it was built to replace. The notice is a systemMessage, -# the field the user is shown on every event. +# The NOTICE shim on the Stop rows -- BACKLOG #7575. Why it emits a systemMessage is stated once, in +# the installer's comment above New-NoticeShimCommand. # -------------------------------------------------------------------------------------------------- -_NOTICE_ROWS = [ - (_marker("SEAT_MARKER"), "scripts/hooks/seat-record.ps1"), - (_marker("WIKI_MARKER"), "scripts/hooks/wiki-write-prompt.ps1"), -] +# Every Shim = "notice" row of $WIRING, parsed from the installer so an added or renamed row is +# exercised rather than silently skipped: (event, script, marker, notice text). +_NOTICE_ROW_RE = re.compile( + r'@\{ Event = "(\w+)";[^\n]*?Script = "([^"]+)";[^\n]*?Marker = \$(\w+); Shim = "notice"' + r'\s*\n\s*Notice = "([^"]*)"' +) +_NOTICE_ROWS_SRC = _NOTICE_ROW_RE.findall(_SRC) +_NOTICE_ROWS = [(_marker(var), script) for _event, script, var, _notice in _NOTICE_ROWS_SRC] + + +def test_the_notice_rows_were_parsed_and_are_all_stop_rows_with_ascii_notices() -> None: + """The systemMessage form is the right one only on Stop: on SessionStart or UserPromptSubmit + plain stdout reaches the model and a systemMessage would not. ASCII, because the shim sets no + output encoding, so a non-ASCII notice would reach the harness in the console code page.""" + assert len(_NOTICE_ROWS_SRC) >= 2, f"notice rows not parsed from {INSTALLER}" + rows = len(re.findall(r'Marker = \$\w+; Shim = "notice"', _SRC)) + assert len(_NOTICE_ROWS_SRC) == rows, "a notice row did not parse" + for event, script, _var, notice in _NOTICE_ROWS_SRC: + assert event == "Stop", f"{script}: a notice row on {event} needs a different notice form" + assert notice.isascii(), f"{script}: non-ASCII notice" def _stop_notice_shim(settings: Path, tmp_path: Path, marker: str) -> Path: @@ -533,15 +546,20 @@ def test_a_stop_notice_shim_says_so_as_a_system_message( assert f"{script} is missing from this checkout" in out["systemMessage"] -@pytest.mark.parametrize(("marker", "script"), _NOTICE_ROWS) -def test_a_stop_notice_shim_is_silent_in_a_repo_that_is_not_messagefoundry( - settings: Path, tmp_path: Path, marker: str, script: str +@pytest.mark.parametrize("marker", [m for m, _s in _NOTICE_ROWS]) +@pytest.mark.parametrize("where", ["foreign-repo", "not-a-repo"]) +def test_a_stop_notice_shim_is_silent_outside_a_messagefoundry_checkout( + settings: Path, tmp_path: Path, marker: str, where: str ) -> None: - primary = _fixture_primary(tmp_path, with_announce=False, with_presence=False) + if where == "foreign-repo": + cwd = _fixture_primary(tmp_path, with_announce=False, with_presence=False) + else: + cwd = tmp_path / "not-a-repo" + cwd.mkdir() run_installer(settings) - proc = _run_stop_shim(_stop_notice_shim(settings, tmp_path, marker), primary) + proc = _run_stop_shim(_stop_notice_shim(settings, tmp_path, marker), cwd) assert proc.returncode == 0 - assert proc.stdout.strip() == "", f"notice leaked into a foreign repo: {proc.stdout!r}" + assert proc.stdout.strip() == "", f"notice leaked outside MessageFoundry: {proc.stdout!r}" @pytest.mark.parametrize(("marker", "script"), _NOTICE_ROWS) From c6920f7122e80c3c6a50ef77ae87eb8d2facfb6d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 04:14:14 -0600 Subject: [PATCH 11/14] Withdraw the mail.ps1 addressing change; keep the spelling pins Review round 2 (xhigh) showed the below-root refusal also regresses: a session launched in a subdirectory has its drain key that subdirectory (Resolve-CcxHookSession Dir), so refusing that path, or raising it, cuts it off, and announce-session.ps1 would retry a refused peer on every prompt. The defect is a split between keyers (drain: session cwd; mail-watch.ps1: raw hook cwd; seat.ps1: show-toplevel), not a sender bug, so mail.ps1 and SESSION-MAIL.md return to origin/main. Kept: a pin that case, slash, trailing separator and .. spellings share one key. BACKLOG #7581 (Argon S33-75, S33-76). Proposed PR title: Pin mail.ps1 path-spelling box keys (BACKLOG #7581) Proposed banner: PARTIAL -- re-measured. Spelling half of S33-75 is not-a-bug (pinned). Subdirectory half reproduces but needs one keyer shared by mail-drain.ps1, mail-watch.ps1, seat.ps1 and mail.ps1 (drain keys on $session.Root, -AnchorRepo falls back to Dir); a sender-only fix was built, reviewed and withdrawn. Remains: that keyer; -To all reads only presence.ps1; S33-76 (-Status NextDrainShowsAtLeast over-reports), confirmed by reading, unbuilt. --- docs/SESSION-MAIL.md | 5 +- scripts/coord/mail.ps1 | 22 +----- tests/test_session_mail_toplevel.py | 104 +++++----------------------- 3 files changed, 19 insertions(+), 112 deletions(-) diff --git a/docs/SESSION-MAIL.md b/docs/SESSION-MAIL.md index 0cad54664e..5e65348b20 100644 --- a/docs/SESSION-MAIL.md +++ b/docs/SESSION-MAIL.md @@ -152,10 +152,7 @@ pwsh -NoProfile -File scripts\coord\mail.ps1 -List pwsh -NoProfile -File scripts\coord\mail.ps1 -Status ``` -- `-To ` -- the recipient **worktree** root. A path inside a worktree but not its root is - refused, naming the root: a session's drain keys its box on the cwd it runs in, normally the root, - so a box keyed on a subdirectory would go unread (BACKLOG #7581). A path in no worktree is still - accepted, for an `-AnchorRepo` session. Matched case-insensitively and exactly. `all` +- `-To ` -- the recipient **worktree** path. Matched case-insensitively and exactly. `all` broadcasts to the live roster from [`presence.ps1`](../scripts/coord/presence.ps1). - `-To ` -- a seat record's id, such as `autonomy-plan-62022e2c`, accepted when the seat registry holds a readable record for it that names a worktree. **Use this for a seat on another PC**: its worktree path diff --git a/scripts/coord/mail.ps1 b/scripts/coord/mail.ps1 index 7365aee214..a7031f7faa 100644 --- a/scripts/coord/mail.ps1 +++ b/scripts/coord/mail.ps1 @@ -57,12 +57,6 @@ seat's worktree and host key to now, never to the old box, which every PC at that path reads. A record under it that names no host is refused, and so is any seat record that names no worktree: neither can be keyed to one PC's box. - A -To PATH INSIDE A WORKTREE BUT NOT ITS ROOT IS REFUSED, naming the root (BACKLOG #7581). It is - hashed as given, and a session's drain keys its box on the cwd it runs in, which is its worktree - root unless it was launched below it; seat.ps1 publishes the root's key. So a box keyed on a - subdirectory is one no drain is likely to read, and a leftover directory of a removed worktree - nested under the primary is not quietly re-addressed to the primary's session either. A path in no - worktree is still accepted: that is the box an -AnchorRepo drain reads (docs/SESSION-MAIL.md). A cwd is matched case-insensitively and EXACTLY, never by prefix: every worktree cwd in this repo is an extension of the primary checkout's path, so a prefix match resolves any peer to some arbitrary worktree. VS Code also records a lowercase drive letter where the Desktop app records an uppercase @@ -124,7 +118,7 @@ param( # a caller whose stdin stays open and silent (the Bash tool) waits forever. Measured 2026-10-13/14: # four sends hung. The one box checked got nothing. The refusal is right after this param block. [Parameter(ParameterSetName = 'Send')][switch]$Send, - # Recipient worktree. A worktree ROOT path (matched case-insensitively and exactly), a seat id from the shared + # Recipient worktree. A path (matched case-insensitively and exactly), a seat id from the shared # seat registry (e.g. autonomy-plan-62022e2c, for a seat on another PC), or "all" to broadcast to # every live peer in this repo. Defaults to nothing: refusing to guess is the point. [Parameter(ParameterSetName = 'Send')][string]$To, @@ -262,10 +256,6 @@ function Resolve-SeatRecipient { # healthy. See mail-key.ps1 for why the normalisation is load-bearing. . "$PSScriptRoot\mail-key.ps1" -# Get-CcxWorktreeRoot, the drain's own test of which worktree a path sits in (the first directory at -# or above it holding `.git`). Reused rather than copied; functions only, so dot-sourcing runs nothing. -. (Join-Path (Split-Path -Parent $PSScriptRoot) 'hooks/_hookinput.ps1') - # The claim primitive is shared with the drain for exactly the reason the box key is: three call sites # hand-rolling "did my move win" is three chances for one of them to drift back to a check that was # measured unable to tell a winner from a loser. See mail-claim.ps1. @@ -533,15 +523,7 @@ if ($Send) { } } elseif (Test-Path -LiteralPath $To -PathType Container) { - $full = (Resolve-Path -LiteralPath $To).Path - # A path below a worktree root; see ADDRESSING. Refused, never raised: raising it would send a - # removed worktree's leftover directory to the primary checkout's session. - $top = Get-CcxWorktreeRoot $full - if ($top -and -not (Test-CcxSamePath $top $full)) { - throw ("Refusing to send: '$To' is inside the worktree $top but is not its root, and a box " + - "keyed on it is one no drain is likely to read. Send to the worktree root, or to its seat id.") - } - $targets = @($full) + $targets = @((Resolve-Path -LiteralPath $To).Path) } else { # Not a directory here. It may be a seat id for a seat on another PC; see ADDRESSING. diff --git a/tests/test_session_mail_toplevel.py b/tests/test_session_mail_toplevel.py index 13a6cf5f3d..660b0842e8 100644 --- a/tests/test_session_mail_toplevel.py +++ b/tests/test_session_mail_toplevel.py @@ -1,12 +1,13 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors -"""mail.ps1 refuses a -To path inside a worktree that is not the worktree's root. - -BACKLOG #7581 (Argon S33-75). ``-Send -To `` hashes the path as given. A session's drain keys -its box on the cwd it runs in, normally its worktree root, and seat.ps1 publishes the root's key, so a -box keyed on a subdirectory is one no drain is likely to read -- and the sender was told ``Queued``. -The send is refused instead, naming the root. Each arm drives the real scripts against a throwaway -repo and its own fixture mail root, never a live queue. +"""Every spelling of one worktree path addresses one mail box. + +BACKLOG #7581 (Argon S33-75) claims a different spelling of a worktree path addresses a box nobody +drains. Measured: case, slash direction, a trailing separator and a ``..`` segment already share one +key, through ConvertTo-BoxKeyPath and Resolve-Path, and these arms pin that. The subdirectory half of +the finding is real, but it is a split between the keyers (the drain keys on the session cwd, seat.ps1 +on the toplevel), and a sender-only change was measured to make it worse, so it is not changed here. +Each arm drives the real mail.ps1 against a throwaway repo and its own fixture mail root. """ from __future__ import annotations @@ -16,79 +17,25 @@ from pathlib import Path import pytest -from _session_mail_harness import ( - COORD, - MAIL, - TIMEOUT, - injection, - mail_root, - repo, - requires_pwsh_on_windows, - run_drain, -) +from _session_mail_harness import MAIL, TIMEOUT, mail_root, repo, requires_pwsh_on_windows __all__ = ["repo"] # re-exported so pytest resolves the fixture in this module pytestmark = requires_pwsh_on_windows -def _mail(cwd: Path, root: Path, *args: str) -> subprocess.CompletedProcess[str]: - return subprocess.run( - [ - "pwsh", - "-NoProfile", - "-NonInteractive", - "-File", - str(MAIL), - "-MailRoot", - str(root), - *args, - ], - cwd=str(cwd), - capture_output=True, - text=True, - timeout=TIMEOUT, - check=False, - ) - - -def _boxes(root: Path) -> list[str]: - d = root / "box" - return sorted(p.name for p in d.iterdir()) if d.is_dir() else [] - - -def _worktree_root(path: Path) -> str: - """The decision mail.ps1 makes, read with the same function rather than with git.""" - lib = COORD.parent / "hooks" / "_hookinput.ps1" +def _send_key(repo: Path, to: str) -> str: proc = subprocess.run( - ["pwsh", "-NoProfile", "-NonInteractive", "-Command", - f". '{lib}'; [string](Get-CcxWorktreeRoot '{path}')"], - capture_output=True, text=True, timeout=TIMEOUT, check=True, + ["pwsh", "-NoProfile", "-NonInteractive", "-File", str(MAIL), + "-MailRoot", str(mail_root(repo)), "-Send", "-Json", "-To", to, "-Body", "spelled"], + cwd=str(repo), capture_output=True, text=True, timeout=TIMEOUT, check=False, ) # fmt: skip - return proc.stdout.strip() - - -def test_a_send_to_a_path_below_the_worktree_root_is_refused_and_writes_nothing( - repo: Path, -) -> None: - sub = repo / "deep" / "er" - sub.mkdir(parents=True) - root = mail_root(repo) - send = _mail(repo, root, "-Send", "-To", str(sub), "-Body", "sent to a subdirectory") - assert send.returncode != 0, send.stdout - assert "is not its root" in send.stderr, send.stderr - assert str(repo) in send.stderr, "the refusal must name the root to send to instead" - assert _boxes(root) == [], "a shadow box was minted for the subdirectory" - # The control: the root itself sends, and the worktree's drain shows it. - ok = _mail(repo, root, "-Send", "-To", str(repo), "-Body", "sent to the root") - assert ok.returncode == 0, ok.stderr - assert " | sent to the root" in injection(run_drain(repo)) + assert proc.returncode == 0, proc.stderr + return str(json.loads(proc.stdout)[0]["Key"]) @pytest.mark.parametrize("spell", ["upper", "slash", "trailing", "dotdot"]) def test_every_spelling_of_the_worktree_root_addresses_one_box(repo: Path, spell: str) -> None: - """A pin: these already shared a key through ConvertTo-BoxKeyPath and Resolve-Path. The new - below-the-root refusal must not take any of them for a subdirectory.""" (repo / "x").mkdir() spelled = { "upper": str(repo).upper(), @@ -96,23 +43,4 @@ def test_every_spelling_of_the_worktree_root_addresses_one_box(repo: Path, spell "trailing": str(repo) + "\\", "dotdot": str(repo / "x" / ".."), }[spell] - root = mail_root(repo) - plain = _mail(repo, root, "-Send", "-Json", "-To", str(repo), "-Body", "plain") - send = _mail(repo, root, "-Send", "-Json", "-To", spelled, "-Body", "spelled") - assert plain.returncode == 0, plain.stderr - assert send.returncode == 0, send.stderr - assert json.loads(send.stdout)[0]["Key"] == json.loads(plain.stdout)[0]["Key"] - - -def test_a_path_in_no_worktree_still_sends_for_an_anchored_session( - repo: Path, tmp_path: Path -) -> None: - """The must-not-trip arm. An -AnchorRepo drain keys its box on a cwd in no worktree, so that - path stays addressable; the refusal is only for a path below a worktree root.""" - container = tmp_path / "container" - container.mkdir() - assert _worktree_root(container) == "", ( - f"{container} sits in a worktree; this arm proves nothing" - ) - send = _mail(repo, mail_root(repo), "-Send", "-To", str(container), "-Body", "anchored") - assert send.returncode == 0, send.stderr + assert _send_key(repo, spelled) == _send_key(repo, str(repo)) From 2296372d8c9f83e2450192bed2452c737b273cc8 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 04:25:32 -0600 Subject: [PATCH 12/14] Classify tests/test_session_mail_toplevel.py in the tooling manifest It tests scripts/coord/mail.ps1, a harness subject; test_every_non_engine_test_is_classified failed without it. BACKLOG #7581. --- tests/tooling_manifest.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/tooling_manifest.txt b/tests/tooling_manifest.txt index 3cceb042ea..a10c71cd82 100644 --- a/tests/tooling_manifest.txt +++ b/tests/tooling_manifest.txt @@ -219,6 +219,7 @@ tests/test_semgrep_install_retry.py tests/test_session_context_presence.py tests/test_session_mail_held.py tests/test_session_mail.py +tests/test_session_mail_toplevel.py tests/test_session_mail_watch_standdown.py tests/test_install_coordination_retired.py tests/test_session_registry.py From 41ca1f279447130b5a11c4c8bf577f1ebf90cbb8 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:08:52 -0600 Subject: [PATCH 13/14] install-gate: the receipt guard judges the one read it re-checks; two comments made true The guard now hashes the installed gate once and hands that hash to Get-UnexplainedGate (-InstalledSha), so $guardSha is the reading the guard judged rather than a second read. Restores "a refusal leaves the box exactly as it was" on the stale-source check, and corrects the header: editing the receipt silences the check, deleting it does not. Repairs the Lander's hold on PR 3249. BACKLOG #1247. --- scripts/worktree/install-gate.ps1 | 24 ++++++--- .../test_install_gate_records_the_install.py | 54 ++++++++++++++++++- 2 files changed, 70 insertions(+), 8 deletions(-) diff --git a/scripts/worktree/install-gate.ps1 b/scripts/worktree/install-gate.ps1 index 107a769311..e1789f08d3 100644 --- a/scripts/worktree/install-gate.ps1 +++ b/scripts/worktree/install-gate.ps1 @@ -300,10 +300,19 @@ function Get-GateHash([string]$Path) { # anyone silence this check by deleting one unprotected file. A refusal on a missing receipt costs a # box that still carries a pre-receipt install one deliberate -OverwriteUnexplained; it is the # stricter reading, and the receipt is still a convenience record, never attestation. Editing the -# receipt silences the check as well as deleting it would; rule 1a does not cover that either. -function Get-UnexplainedGate([string]$Path) { - if (-not (Test-Path -LiteralPath $Path)) { return $null } - $installedSha = Get-GateHash $Path +# receipt does silence the check, since rule 1a does not cover that either; deleting it does not, +# because a gate with no receipt refuses. +# +# -InstalledSha, when given, is the hash judged, in place of a fresh read of $Path: the install path +# passes the one hash it re-checks before the copy, so the gate it judged and the gate it re-checks +# are the same reading. $null there means no gate is installed. +function Get-UnexplainedGate { + param([string]$Path, [AllowNull()][object]$InstalledSha) + if (-not $PSBoundParameters.ContainsKey('InstalledSha')) { + if (-not (Test-Path -LiteralPath $Path)) { return $null } + $InstalledSha = Get-GateHash $Path + } + if ($null -eq $InstalledSha) { return $null } $receiptPath = "$Path.receipt.json" $recordedSha = $null $unreadable = $false @@ -1139,7 +1148,7 @@ $resolved = foreach ($r in $Repo) { # from THIS checkout into a machine-global file every session runs. A checkout behind -UpstreamRef # would ship an old gate to every config dir, and -Status run from the same checkout would then find # nothing wrong. So compare against the ref first, and refuse unless the operator says they mean it. -# It sits above the allowlist write so a receipt-mismatch refusal leaves the box exactly as it was. +# It sits above the allowlist write so a refusal leaves the box exactly as it was. $sourceGate = Join-Path $RepoRoot "scripts\hooks\worktree_gate.ps1" $checkedSha = Get-GateHash $sourceGate $upstream = Get-UpstreamGate -RepoRoot $RepoRoot -Ref $UpstreamRef @@ -1176,9 +1185,10 @@ New-Item -ItemType Directory -Force -Path $HooksDir | Out-Null # write, so a receipt-mismatch refusal leaves the box as it was (the changed-during-install refusal # further down is later, after the allowlist write). An unexplained write to this machine-global file was # once overwritten in silence, and the .bak was the only evidence left afterwards. -$unexplained = Get-UnexplainedGate $GateDst -# What the guard saw, so a write between here and the copy below cannot pass as explained. +# ONE read of the installed gate, judged by the guard and re-checked before the copy below, so a +# write between this read and that re-check cannot pass as explained. $guardSha = Get-GateHash $GateDst +$unexplained = Get-UnexplainedGate $GateDst -InstalledSha $guardSha if ($unexplained) { # Detail on Write-Host, not in the throw: the error view re-wraps a thrown message and joins its # lines, which put the two hashes on one run-on line. diff --git a/tests/test_install_gate_records_the_install.py b/tests/test_install_gate_records_the_install.py index 39900e85dd..6905721acf 100644 --- a/tests/test_install_gate_records_the_install.py +++ b/tests/test_install_gate_records_the_install.py @@ -47,7 +47,7 @@ # The receipt guard that precedes the allowlist write (BACKLOG #1247's last limb): from the check to # the comment that opens the allowlist read below it. -_GUARD_START = "$unexplained = Get-UnexplainedGate $GateDst" +_GUARD_START = "$guardSha = Get-GateHash $GateDst" _GUARD_END = "# READ AND MERGE BEFORE ANYTHING ON THIS BOX CHANGES" _INSTALLED_GATE = "# THE GATE THAT WAS ALREADY INSTALLED\n" @@ -345,3 +345,55 @@ def test_the_receipt_guard_runs_before_anything_on_the_box_changes() -> None: "Copy-Item -LiteralPath $GateSrc -Destination $GateDst", ): assert guard < text.index(write, install), f"the receipt guard runs after {write!r}" + + +def test_the_guard_judges_the_same_read_it_re_checks_before_the_copy(tmp_path: Path) -> None: + """The guard reads the installed gate ONCE: the hash it judges is the hash re-checked later. + + A second read for ``$guardSha`` would let a write between the two reads pass as explained, so + this counts the guard's reads of the installed gate, and checks the judged hash is the one + handed in rather than a fresh read of the file. + """ + if shutil.which("pwsh") is None: + pytest.skip("SKIP (nothing run): pwsh not on PATH") + dst = tmp_path / "worktree_gate.ps1" + dst.write_bytes(_INSTALLED_GATE.encode("utf-8")) + Path(f"{dst}.receipt.json").write_text( + json.dumps({"gateSha256": _content_sha(_INSTALLED_GATE.encode("utf-8"))}), encoding="utf-8" + ) + other = _content_sha(b"# a write after the read\n") + script = "\n".join( + [ + "$ErrorActionPreference = 'Stop'", + f"$GateDst = '{dst.as_posix()}'", + "$OverwriteUnexplained = $false", + "$checkedSha = 'X'", + _function("Get-GateHash").replace( + "function Get-GateHash", "function Get-GateHashReal", 1 + ), + "$script:hashReads = 0", + "function Get-GateHash([string]$Path) { $script:hashReads++; Get-GateHashReal $Path }", + _function("Get-UnexplainedGate"), + _guard(), + 'Write-Output "reads=$script:hashReads"', + # The judged hash is the one given, not a re-read: a file matching its receipt still + # reads as unexplained when the hash handed in differs. + f"$r = Get-UnexplainedGate $GateDst -InstalledSha '{other}'", + 'Write-Output "judged=$($r.InstalledSha)"', + 'Write-Output "none=$($null -eq (Get-UnexplainedGate $GateDst -InstalledSha $null))"', + ] + ) + runner = tmp_path / "run.ps1" + runner.write_text(script, encoding="utf-8") + proc = subprocess.run( + ["pwsh", "-NoProfile", "-NonInteractive", "-File", str(runner)], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + ) + out = proc.stdout + proc.stderr + assert proc.returncode == 0, out + assert "reads=1" in out, f"the guard must read the installed gate exactly once:\n{out}" + assert f"judged={other}" in out, out + assert "none=True" in out, out From 2a6235cb78eaeb6298b25fb05b92ee0e782e1c5a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:22:58 -0600 Subject: [PATCH 14/14] install-gate tests: name what the one-read test covers, pin the refusal's order Review round 1 findings that made a claim false: the new test's name said it covered the re-check before the copy, which it never runs; its "exactly once" assertion was a substring match; and with the guard anchor moved to the hash read, the ordering test no longer pinned the refusal itself ahead of the writes. Renamed, matched the whole line, and anchored the order on the throw. BACKLOG #1247. --- tests/test_install_gate_records_the_install.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/tests/test_install_gate_records_the_install.py b/tests/test_install_gate_records_the_install.py index 6905721acf..8859a44d42 100644 --- a/tests/test_install_gate_records_the_install.py +++ b/tests/test_install_gate_records_the_install.py @@ -337,8 +337,9 @@ def test_the_receipt_guard_runs_before_anything_on_the_box_changes() -> None: """A refusal says nothing was changed, so the guard must precede every install-path write.""" text = INSTALLER.read_text(encoding="utf-8") install = text.index("# " + "-" * 89 + " install\n") - guard = text.index(_GUARD_START) - assert install < guard, "the receipt guard is not on the install path" + assert install < text.index(_GUARD_START), "the receipt guard is not on the install path" + # The refusal itself, not just the hash read the guard opens with, must precede every write. + guard = text.index('throw "Refusing to overwrite the installed gate at $($unexplained.Path)') for write in ( "$bak = Write-GovernedRoots -Path $ReposFile", "Copy-Item -LiteralPath $GateDst -Destination $gateBak", @@ -347,12 +348,11 @@ def test_the_receipt_guard_runs_before_anything_on_the_box_changes() -> None: assert guard < text.index(write, install), f"the receipt guard runs after {write!r}" -def test_the_guard_judges_the_same_read_it_re_checks_before_the_copy(tmp_path: Path) -> None: - """The guard reads the installed gate ONCE: the hash it judges is the hash re-checked later. +def test_the_guard_reads_the_installed_gate_once_and_judges_that_read(tmp_path: Path) -> None: + """The guard reads the installed gate ONCE, and judges the hash it is handed. - A second read for ``$guardSha`` would let a write between the two reads pass as explained, so - this counts the guard's reads of the installed gate, and checks the judged hash is the one - handed in rather than a fresh read of the file. + This counts the guard's reads of the installed gate, and checks the judged hash is the one + handed in rather than a fresh read of the file. It does not exercise the later re-check. """ if shutil.which("pwsh") is None: pytest.skip("SKIP (nothing run): pwsh not on PATH") @@ -394,6 +394,8 @@ def test_the_guard_judges_the_same_read_it_re_checks_before_the_copy(tmp_path: P ) out = proc.stdout + proc.stderr assert proc.returncode == 0, out - assert "reads=1" in out, f"the guard must read the installed gate exactly once:\n{out}" + assert "reads=1" in out.splitlines(), ( + f"the guard must read the installed gate exactly once:\n{out}" + ) assert f"judged={other}" in out, out assert "none=True" in out, out