beads/scripts/ci/test-windows-env-helpers.sh
ecuthiell cefcabb1e3
fix(gitenv): retain explicit null config suppression (#6461)
* fix(exec): match Windows environment key identity (#5618)

Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions.

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>

* fix(worktree): scrub inherited Git routing state

Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics.

Fixes #5531

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell

* refactor(worktree): explain owned filtering and remove an unused shim

Document why filtering the fresh routing slice in place is safe and call
the shared routing-key classifier directly from tests. Retain the two
forwarders used by production worktree subprocess/removal paths.

Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671
Bead: saa-cgh.23
Agent-Signature: unknown-model/unknown-reasoning

* fix(config): isolate identity and tracked-file Git probes from routing

Reuse the worktree routing owner for GetIdentity and isGitTracked so
explicit cwd/path selection is not displaced by inherited repository,
index or injected config state. Preserve identity precedence and the
tracked-secret refusal contract, with real target/decoy regressions.

Follow-up: https://github.com/gastownhall/beads/issues/6222
Dependency: https://github.com/gastownhall/beads/pull/5623
Reported-by: bee-ghosttrack
Bead: saa-cgh.93
Agent-Signature: unknown-model/unknown-reasoning

* test(execenv): exercise every environment operation under both host rules

Thread the host choice through narrow private helpers behind the existing
exported functions. Keep one normalization owner and retain native wrapper
tests; the additional table covers both host branches for equality, prefix
matching, last-wins lookup, filtering and input preservation.

Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965
Bead: saa-cgh.78
Agent-Signature: unknown-model/unknown-reasoning

* docs(worktree): explain startup Git environment scope (saa-cgh.23)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(execenv): exercise exported host policy wiring (saa-cgh.78)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(config): share subprocess key identity for Git routing (saa-cgh.93)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(config): isolate role commands from Git routing (saa-cgh.99)

Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(env): exercise shared key helpers on native Windows (saa-cgh.78)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(config): explain role command routing policy (saa-cgh.99)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(config): isolate role readers from inherited Git routing (saa-cgh.109.1)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(doctor): isolate role lookups from inherited Git routing (saa-cgh.109.2)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(git): isolate domain role configuration from inherited routing (saa-cgh.109.5)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(doctor): isolate explicit-path worktree fallback from Git routing (saa-cgh.109.6)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): probe the selected repository before configuring roles (saa-cgh.109.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(beads): cover common-directory role routing (saa-cgh.109.1)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(git): explain system config routing flags (saa-cgh.109.6)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(init): explain role probe discovery ceiling behavior (saa-cgh.109.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(beads): scope stable worktree probes to selected path (saa-cgh.109.13)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): bind proxied tail Git operations to selected directory (saa-cgh.109.14)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* Clarify selected discovery probes and cover separate routing vectors (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Keep init role operations on the captured selected Git context (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Observe inline Git configuration directly in linked-worktree fixture (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Align selected-tail fixtures with captured role authority (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(beads): select explicit directory discovery context (GH#6384) (saa-cgh.120.6)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitenv): retain explicit Git config suppression (saa-cgh.120.7)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(config): pin identity under null config suppression (saa-cgh.120.7)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitenv): keep role authority off inherited config suppression

Maintainer review fixes for PR #6461 (adopt-pr iterations 1-2). Addresses the
three major findings raised against the contributor branch, plus the major,
three minors and nit that iteration 2 raised against the first fixup; each fix
is pinned by a test that was mutation-proved against the pre-fix source.

F1 (major, security) — the leaf exempts GIT_CONFIG_GLOBAL=/dev/null,
GIT_CONFIG_SYSTEM=/dev/null and GIT_CONFIG_NOSYSTEM from ScrubRouting. Null
suppression cannot redirect a read, but it can blind one, and DetectUserRole
answers a missed read with detectFromURL, whose no-remote and SSH arms both
return Maintainer. Reproduced on this branch: a global beads.role=contributor
with GIT_CONFIG_GLOBAL=/dev/null resolved to maintainer, where the leaf's
parent fb7a93ad4 scrubbed the entry and read contributor.

Taken the synthesis's alternative arm (a): keep the exemption where the value
has no authority, drop it where it does. New ScrubRoutingAndSuppression
applies at every beads.role reader — internal/routing, doctor/role.go,
config_show.go, RepoContext.Role, bd config get/set/unset/set-many, and the
domain adapter's key-specific arms (see A1: iteration 1 claimed that last site
and did not actually reach it). Arm (b), making roleFromGitConfig's miss
non-permissive, was declined: "no beads.role and no remote implies maintainer"
is documented base behavior for local projects, so closing it there would
reclassify every such user rather than the blinded slice this PR introduced.

F2 (major, blast radius) — the stack hardened every role reader and left four
writer/reader sites fully inherited, a divergence that did not exist at base:
an inherited GIT_DIR sends setBeadsRole's write to another repository while
the scrubbed readers look at the one the user is standing in. All four now
share the same boundary (init.go's getBeadsRole/setBeadsRole,
init_contributor.go, hooks.go's uninstall --get/--unset pair).

The required fix also asked for cmd.Dir = repoRoot on the init.go pair. Still
not taken, but not on the grounds iteration 1 recorded (see A2). What holds is
the measurement against the vector the fix targets: with GIT_DIR, GIT_WORK_TREE
and GIT_COMMON_DIR gone, no production path chdirs away from the invocation
directory — `grep -rn 'os\.Chdir' --include='*.go'` over production cmd/bd
returns nothing and `bd init` takes no path argument — so threading a repoRoot
through both signatures and their eight call sites buys no behavior change
against a redirect.

F3 (major, security) — this PR converted internal/config's isGitTracked probe
from inherited to scrub-only. The guard is fail-open by construction, so in a
legitimately routed checkout (bare repo.git, GIT_DIR/GIT_WORK_TREE exported,
no in-tree .git) the probe stopped answering and `bd config set
linear.api_key` would have written the credential into a tracked file.
Restored the two-probe shape sibling #6464 applied to the structural twin:
scrubbed probe first, inherited second, either "tracked" refuses.

F5 (minor) — disclose that scrubbing GIT_CEILING_DIRECTORIES widens upward
discovery rather than bounding it, in the worktree comment and the docs
paragraph that asserted only the narrowing effect. F2's fix extends that
trade-off to two more sites, so the disclosure is now load-bearing.

F7 (minor) — renamed isConfigSuppression to isConfigSuppressionControl and
documented why the NOSYSTEM arm is deliberately value-blind. Took the
rename/document arm rather than restricting the arm to git-true values, which
would have contradicted the PR's own pinned table.

F10 (nit) — pinned both suppression tables in the windows-latest required
list; verified each name matches the gate's grep exactly once.

--- Iteration 2 ---

The first fixup's F1 census named a site it did not reach, and its cmd.Dir
rationale named a mechanism that does not hold. Both are corrected here.

A1 (major, security) — the domain adapter's key-specific arm was guarded by
`key == "beads.role" && r.env == nil`, which is dead on the only production
role path: runInitProxiedServerTail rebinds the use case to
NewInitGitRepository whenever t.workDir != "" (its sole construction site
passes cwd), and that constructor captures ScrubRouting(os.Environ()) —
non-nil, suppression retained. The nil-env constructor has no
BeadsRole/SetBeadsRole caller, so the arm could only fire from tests, while
`bd init` under an inherited GIT_CONFIG_GLOBAL=/dev/null still missed a global
role, took hasRole=false, and persisted beads.role=maintainer into
repository-local config, where it outranks the global value for every later
read in a clean environment. Iteration 1 therefore left F1's escalation not
just alive but durable, on the one path the fix was supposed to close.

Fixed by keying the strict scrub on the config key alone and applying it to
whichever environment the repository already carries (roleAuthorityEnv). That
preserves capture semantics — NewInitGitRepository keeps its captured HOME,
the property git_test.go's captured_home case pins — and removes only the
suppression entries. Codex's alternative of rebuilding the constructor's whole
env was declined: it moves every key for no gain on this finding.

A2 (minor, contract fidelity) — iteration 1 justified declining cmd.Dir with
"repository selection is left to the working directory — the one input the
scrub keeps". That is false, and false in the file a future reader consults
before deciding whether to bound the pair: GIT_CEILING_DIRECTORIES is a routing
key too, so the scrub removes a bound rather than installing one. Measured from
a non-repository directory nested under a repository: `git config beads.role
<value>` fails "not in a git directory" while a ceiling below that repository is
inherited, and writes that repository's local config once the ceiling is
scrubbed. The decline itself stands, since the measurement behind it was made
against the GIT_DIR vector; getBeadsRole now records selection as the working
directory *or a containing ancestor*, which is also what makes
clearWorktreeGitRoutingEnv's existing cross-reference to "init's role probe"
true.

A3 (minor, consistency) — `bd config unset beads.role` and `bd config set-many
beads.role=` were the two spellings of that mutation still on ScrubRouting, in
the same file as the two that moved. Both measured inert: `git config <key>
<value>` and `--unset <key>` target the repository-local file, which the
suppression variables cannot select. Moved for parity rather than annotated,
because a divergence inside one file is how the next one starts.

Test evidence (minor) — the writer pair's two subtests both pass on the
redirect alone, so downgrading getBeadsRole back to ScrubRouting left them
green even though suppression is the load-bearing half at those sites
(init.go treats a getBeadsRole miss as permission to write a default role).
Added a global_null blinding subtest with the same unblinded fixture guard.

A4 (nit) — doctor/role.go's isGitRepo was the last probe in that file on the
suppression-retaining scrub, and it gates the "beads.role not configured"
warning. rev-parse is config-sensitive through safe.directory, which lives in
global config, so a retained GIT_CONFIG_GLOBAL=/dev/null can downgrade that
warning to "N/A (not a git repository)". Moved onto the same boundary as its
two siblings. As the finding records, the safe.directory precondition was not
reproduced end to end; the change is uniformity within the file.

Tests. Every pin reds only on its own defect:
- routing: reverting to ScrubRouting reds only the blinded-read subtest; the
  unblinded fixture guard and the PR's inject-vector table stay green.
- gitenv: keeping suppression reds 10 of 16 new subtests, none of the PR's.
- cmd/bd: restoring the inherited env reds both redirect subtests and names
  both halves ("the write did not land where bd is standing" / "an inherited
  GIT_DIR captured the write"), while the PR's own role roundtrip stays green
  — it followed the same redirect on both sides, so it never saw this.
- config: the two arms are proved separately. Scrub-only reds only the
  legitimate-routing subtest; inherited-only reds only the poisoned-routing
  subtest, so the new fallback cannot be read as a way around the scrub.
- domain/git (A1): restoring the r.env == nil provenance guard reds
  global_null only; unblinded stays green, and no other test in the package
  moves — which is the same measurement that confirms the arm had no coverage
  before this iteration.

Deferred to follow-up, recorded for the approval summary: F4 (delete
isRoleGitRepo and resolve the dead else-if), F6 (user.name degrading to
hostname, which needs the PR's own subtest re-pointed), F8 (execenv fold
divergence), F9 and F11 (GetIdentity hostname degradation under inherited
suppression). F9's mechanism is confirmed — identity supplied only via
GIT_CONFIG_COUNT is lost when GIT_CONFIG_* is stripped, git reports "Please
tell me who you are", while GIT_AUTHOR_*/GIT_COMMITTER_* survive — but its
"leave artifact commits on the inherited environment" arm would re-open the
GIT_DIR redirect this PR's tail swap closed, and the non-regressing arm
(re-injecting inline identity pre-scrub) is a design change with no observed
victim in this repo.

Validation (iteration 2): internal/{gitenv,routing,storage/domain/git} full
packages green; cmd/bd/doctor full package run; targeted cmd/bd run over the
role, config and init blast radius green at 54 tests; go build ./... clean; go
vet plus CGO_ENABLED=0 and GOOS=windows CGO_ENABLED=0 vet clean on every
changed package. Remaining local reds are base-parity, each matching the
recorded cause: cmd/bd/doctor's seven (the launcher's global
beads.role=maintainer short-circuits CheckBeadsRole before isGitRepo is
reached, plus Dolt server availability) and
TestInitContributorSetsBeadsRoleContributor ("--contributor requires
interactive prompts", this session's stdin is not a TTY).

--- Iteration 3 ---

Iteration 3 reviewed 0220eed32 and approved it: claude filed no findings,
codex's six fix validations all came back correct, synthesis recorded
Decision: approve, and the scorecard scored 881/1000 with Required Changes:
None. The residual was two minors and a nit, none of them merge gates. All
three are taken here because they are comment-and-constant scope, so nothing
in the approved behavior moves.

B1 (minor, blast radius; codex filed it as major, demoted at synthesis) — the
isGitRepo() gate that decides whether the role pair runs is still fully
inherited while the pair it guards is now strict, so from a non-repository
directory with an inherited GIT_DIR the gate opens, the scrubbed read misses,
and the safety-net write fails "not in a git directory". Recorded at the
GH#2950 safety net rather than restructured, for the three reasons the
demotion rests on. The achievable outcome is base parity: sync_git.go is
byte-identical at base and the pair was inherited there too, so a GIT_DIR
holder already reached Maintainer before this PR — more directly, by pointing
at a repository whose beads.role is maintainer. The failure is not silent:
init prints "Warning: failed to set beads.role" unless --quiet, and every
later detection prints "beads.role not configured (GH#2950)" with two Fix
lines. And the prescribed roleRepoAvailable() gate provably does not close it:
all five gate sites are bare `if isGitRepo()` with no else, so a strict gate
answers false in exactly the described band, nothing is written, the role
stays unset, and detection still falls to detectFromURL. The optional
hardening is therefore declined rather than deferred — it would delete a
warning and change no role — and the comment says so, so the next reader does
not mistake a gate change for closing the fail-open path.

B2 (minor, contract fidelity) — the getBeadsRole rationale iteration 2 wrote
to close A2 introduced a new overstatement in its closing sentence: "bd init
takes no path argument — the residual is upward discovery from an unintended
cwd, not a redirect". `bd -C <dir>` is a redirect and takes no path argument.
Verified in tree rather than from the finding: applyChangeDirSelection
(main.go) resolves the target's .beads dir and sets BEADS_DIR with no chdir,
it runs from the root PersistentPreRunE ahead of every init-related early
return in that hook, and init honors BEADS_DIR for workspace selection — so
`bd -C other init` acts on other/.beads while the pair reads and writes
beads.role in the invocation repository. init.go's own "PersistentPreRun
doesn't run for init command" note is about the later skipsStoreInit return,
not about -C, which is what made this vector easy to miss twice. Reachability
is bounded: -C requires an existing beads project at the target, so the
pairing arises on re-init rather than first init. Comment narrowed to name the
residual; threading init's resolved project root through the pair is the
stronger arm and stays out of scope as a behavior change.

B3 (nit, architectural consistency) — the adapter selected the role-authority
boundary on a bare "beads.role" literal while the use case passed the
unexported beadsRoleConfigKey, two spellings of one contract the compiler
could not couple. Exported it as domain.BeadsRoleConfigKey and compared
against it at both adapter arms; no new import edge, since package git already
imports domain. Mutation-proved rather than asserted: replacing the
comparison with the case-variant "Beads.Role" the finding names reds
TestInitGitRepositoryRoleIgnoresInheritedConfigSuppression/global_null alone
while unblinded stays green, so the drift the nit describes is caught by an
existing pin. The comparison is still exact, not case-folded: git config names
are case-insensitive, so a caller hand-writing a variant spelling would bypass
roleAuthorityEnv, but folding widens which keys take the strict environment
and no production caller passes anything but the const — a behavior change the
nit did not ask for.

Validation (iteration 3): go build ./... clean; go vet plus CGO_ENABLED=0 and
GOOS=windows CGO_ENABLED=0 vet clean on cmd/bd, cmd/bd/doctor,
internal/storage/domain, internal/storage/domain/git and internal/gitenv;
internal/storage/domain/... full packages green (domain, db, fs, git); targeted
cmd/bd role run green at 19 subtests with no skips
(TestBeadsRoleCommandsIgnoreInheritedGitRouting and
TestBeadsRoleWriterIgnoresInheritedGitRouting, including the suppression
subtest added in iteration 2); gofmt and git diff --check clean. Full cmd/bd is
still not run locally: it times out at base as well. The iteration-1 deferrals
are unchanged and still owed follow-up bead ids at finalize (F4, F6/F11, F8,
F9).

---------

Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Bee <bee@ghosttrack.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-27 15:59:08 -07:00

47 lines
1.6 KiB
Bash

#!/usr/bin/env bash
# Run the actual helper packages on Windows, including their native-only tests.
set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
cd "$root"
# These environment helpers are pure Go; no C compiler is needed for this lane.
export CGO_ENABLED=0
# shellcheck source=../../.buildflags
source .buildflags
go_bin=$(command -v go) || { echo 'Go is required for Windows environment tests' >&2; exit 1; }
host=$("$go_bin" env GOHOSTOS GOOS) || exit $?
if [[ "$host" != $'windows\nwindows' ]]; then
echo 'Environment helper tests require native Windows Go host and target' >&2
exit 1
fi
log=$(mktemp)
trap 'rm -f "$log"' EXIT
if "$go_bin" test -count=1 -v ./internal/execenv ./internal/githooksenv ./internal/gittraceenv ./internal/gitenv >"$log" 2>&1; then
cat "$log"
else
status=$?
cat "$log"
exit "$status"
fi
# Additional passing cases are welcome; these Windows boundaries must execute.
required=(
TestEnvironmentOperationsForBothHosts/Windows
TestKeyEqualUsesHostSemantics
TestDisabledEnvUsesHostKeySemantics
TestScrubEnvWindowsCaseInsensitiveNames
TestScrubEnvDoesNotEqualFoldUnicodeKeys
TestStderrDirectedWindowsLeadingSlashIsFileTarget
TestScrubRoutingUsesHostKeySemantics
TestScrubRoutingPreservesConfigSuppression
TestScrubRoutingAndSuppressionDropsSuppression
)
for name in "${required[@]}"; do
count=$(grep -Ec "^[[:space:]]*--- PASS: $name \\(" "$log" || true)
if [[ "$count" != 1 ]]; then
echo "Required Windows test did not pass exactly once: $name" >&2
exit 1
fi
done