diff --git a/docs/WORKTREE-GATE.md b/docs/WORKTREE-GATE.md index 7a3aeb238a..dae3137e1e 100644 --- a/docs/WORKTREE-GATE.md +++ b/docs/WORKTREE-GATE.md @@ -239,6 +239,20 @@ 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 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 +`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: - **Every config dir, not just `~/.claude`.** The hook is registered into `~/.claude/settings.json` **and** diff --git a/scripts/coord/account-availability.ps1 b/scripts/coord/account-availability.ps1 index 43a76ac346..fd429d956c 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([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 + } +} + +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,15 +137,34 @@ 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 $ConfigDir + $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 + # 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, 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) { - $eff = ConvertTo-UtcDateTime $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 + $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) { 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,20 +178,25 @@ 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 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. + # 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 "" @@ -180,8 +220,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 $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 + # 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 @@ -220,6 +266,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 $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/scripts/coord/install-coordination.ps1 b/scripts/coord/install-coordination.ps1 index 7239fb8986..3830a1e16d 100644 --- a/scripts/coord/install-coordination.ps1 +++ b/scripts/coord/install-coordination.ps1 @@ -261,9 +261,16 @@ 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 (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) { - # 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); ' + @@ -274,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/scripts/worktree/install-gate.ps1 b/scripts/worktree/install-gate.ps1 index 6a0474e970..e1789f08d3 100644 --- a/scripts/worktree/install-gate.ps1 +++ b/scripts/worktree/install-gate.ps1 @@ -53,6 +53,18 @@ 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. 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. + 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 +76,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 +115,10 @@ 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 that does not match its own receipt (BACKLOG #1247). The cases and + # what the override records are stated once, in .DESCRIPTION above. + [switch]$OverwriteUnexplained ) $ErrorActionPreference = "Stop" @@ -276,6 +292,64 @@ function Get-GateHash([string]$Path) { } } +# 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. Editing the +# 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 + $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 { + $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)" + $unreadable = $true + } + 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 + Unreadable = $unreadable + NoReceipt = $noReceipt + 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 @@ -790,6 +864,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 @@ -1098,6 +1181,33 @@ 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 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. +# 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. + $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 + 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 # 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,10 +1234,20 @@ $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 ($replacedSha -ne $guardSha) { + 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" 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 @@ -1170,6 +1290,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) { + [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_announce_wiring.py b/tests/test_announce_wiring.py index bf00187654..2497923ac8 100644 --- a/tests/test_announce_wiring.py +++ b/tests/test_announce_wiring.py @@ -482,3 +482,96 @@ 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 -- BACKLOG #7575. Why it emits a systemMessage is stated once, in +# the installer's comment above New-NoticeShimCommand. +# -------------------------------------------------------------------------------------------------- + +# 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: + 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", [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: + 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), cwd) + assert proc.returncode == 0 + assert proc.stdout.strip() == "", f"notice leaked outside MessageFoundry: {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 diff --git a/tests/test_coord_usage.py b/tests/test_coord_usage.py index 9cc1980b37..4c2708bca4 100644 --- a/tests/test_coord_usage.py +++ b/tests/test_coord_usage.py @@ -4155,6 +4155,185 @@ 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 + + # 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 read-only marker makes the overwriting File.Move throw, after the temp file is written.""" + root = tmp_path / ".claude-account-9" + 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 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: + """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() + + +@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. diff --git a/tests/test_install_gate_records_the_install.py b/tests/test_install_gate_records_the_install.py index 7d48957552..8859a44d42 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 @@ -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 = "$guardSha = Get-GateHash $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: Literal["match", "mismatch", "garbage", "nohash", "none", "nogate"] = "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,19 @@ 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") script = "\n".join( [ @@ -94,8 +136,12 @@ 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'}", + f"$checkedSha = '{_content_sha(src.read_bytes())}'", _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 +157,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"), @@ -169,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. @@ -191,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" ) @@ -208,3 +254,148 @@ 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], 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}" + 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" + if receipt_before is not None: + assert r["receipt"].read_bytes() == receipt_before, "a refusal must not rewrite the receipt" + 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) + 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 + 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), 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: + both = _refused(_run(tmp_path, receipt="nohash", expect_ok=False)) + 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 and "(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") + 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"] + 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") + 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", + "Copy-Item -LiteralPath $GateSrc -Destination $GateDst", + ): + assert guard < text.index(write, install), f"the receipt guard runs after {write!r}" + + +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. + + 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") + 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.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 diff --git a/tests/test_session_mail_toplevel.py b/tests/test_session_mail_toplevel.py new file mode 100644 index 0000000000..660b0842e8 --- /dev/null +++ b/tests/test_session_mail_toplevel.py @@ -0,0 +1,46 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""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 + +import json +import subprocess +from pathlib import Path + +import pytest +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 _send_key(repo: Path, to: str) -> str: + proc = subprocess.run( + ["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 + 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: + (repo / "x").mkdir() + spelled = { + "upper": str(repo).upper(), + "slash": str(repo).replace("\\", "/"), + "trailing": str(repo) + "\\", + "dotdot": str(repo / "x" / ".."), + }[spell] + assert _send_key(repo, spelled) == _send_key(repo, str(repo)) 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