fix(init): write embedded excludes in the selected project (#6462)
* 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 * fix(config): share subprocess key identity for Git routing (saa-cgh.93) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * 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> * 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 * test(execenv): exercise exported host policy wiring (saa-cgh.78) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * docs(worktree): explain startup Git environment scope (saa-cgh.23) 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(init): isolate role configuration from inherited Git routing (saa-cgh.109.3) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): use the selected origin in contributor setup (saa-cgh.109.7) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): isolate Git writes in planning repositories (saa-cgh.109.9) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(init): retain inherited planning commit author (saa-cgh.109.9) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): align embedded role gates with selected Git context (saa-cgh.109.12) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): scope embedded artifact Git operations to selected directory (saa-cgh.109.15) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(init): cover selected optional artifacts and explain refused commits (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * Honor role-probe cancellation and exercise actual fork planning (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * fix(init): warn when automatic contributor role write fails (saa-cgh.109.3) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(init): cover successful nonquiet contributor role writes (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * Assert the automatic contributor setup banner alongside warnings (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * test(init): read persisted role routing from the store (saa-cgh.120) Agent-Signature: Codex-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(init): probe the selected repository before configuring roles (saa-cgh.109.8) 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(init): bind proxied tail Git operations to selected directory (saa-cgh.109.14) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(gitignore): preserve CRLF when appending project rules (saa-cgh.96) Reported by bee-ghosttrack in gastownhall/beads#6343. Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(gitignore): pin detector edge cases and clarify append behavior (saa-cgh.96) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(gitignore): preserve line endings in Git exclude appends (saa-cgh.104) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(gitignore): clarify exclude fixture path variable (saa-cgh.104) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(gitignore): refuse exclude writes after read errors (saa-cgh.110) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * refactor(gitignore): share append byte composition (saa-cgh.105) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * docs(gitignore): explain append aliasing and trailing CR completion (saa-cgh.105) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * refactor(gitignore): use shared composition for exclude rules (saa-cgh.111) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(gitignore): omit the empty exclude leading separator (saa-cgh.112) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): bind exclude writers to the selected Git directory (saa-cgh.109.16) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * Explain restoration of absent routing variables in selected exclude tests (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 * Align selected-tail fixtures with captured role authority (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * fix(init): write embedded excludes in the selected project (saa-cgh.120.11) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): scrub the fork auto-detect gate; scope the startup-scrub claims Maintainer review fixup for PR #6462 (adoption review iterations 1-2). Gating major — hardened startup probe with an unhardened twin ------------------------------------------------------------ config.gitDirsForRepo (internal/config/config.go:419-424) is scrubbed by this stack, but its byte-identical database-path twin beads.worktreeFallbackBeadsDirForRepo (internal/beads/beads.go:1054-1058) runs the same `git -C <repoPath> rev-parse --git-dir --git-common-dir` for the same purpose and is not. Two claims added in this range asserted the boundary was universal: - docs/reference/worktrees.md:15 "Startup Git discovery probes for every `bd` command scrub inherited Git routing variables" (false universal) - cmd/bd/worktree_cmd.go:712 "Startup config discovery applies the same boundary to its one pre-hook Git probe" (false singular) Both are narrowed here to name only the plane that is actually scrubbed, and to state that the `.beads` database-discovery probes still honor inherited routing. The review offered a code arm (scrub beads.gitOutput, beads.worktreeFallbackBeadsDirForRepo, and internal/git/gitdir.go:32) as the alternative. That arm is DECLINED for this leaf, measured rather than assumed: - Open sibling PR #6461 already carries it. At refs/pull/6461/head, internal/beads/beads.go:293 routes gitOutput through gitOutputEnv(gitenv.ScrubRouting(os.Environ())) and :1069 sets cmd.Env = gitenv.ScrubRouting(os.Environ()) in the ResolveBeadsDirForRepo twin, with internal/beads/{beads,context}_test.go coverage. Our head has zero gitenv references under internal/beads (grep control). - internal/git/gitdir.go is restructured wholesale by open sibling PR #6464 (loadGitContext/ResolveHooksContext), which documents "Routing variables are honored, not filtered" as a deliberate choice. - internal/beads/ and internal/git/ are not among this PR's 47 files, so the code arm would rewrite two functions an open, non-ancestor sibling is already rewriting in files this PR does not otherwise touch. The twin is filed as bd-p4che with the failure scenario, the three unhardened sites, the required decoy test, and the #6461 merge-order note, so the work is tracked whether or not #6461 lands. Minor — fork auto-detect gate left on inherited routing ------------------------------------------------------ cmd/bd/init.go:2002 gated the fork auto-detect block on the unscrubbed isGitRepo() while the same single hunk hardened three setupForkExcludeAt(cwd, …) call sites around it, and five sibling role gates in this PR already use the scrubbed isInitRoleGitRepo(ctx). Under the invalid inherited GIT_DIR this PR's own matrix uses, that gate returns false in a real fork clone and silently suppresses the whole block — prompt, non-interactive auto-configure, and the hardened writer at :2007/:2019. Switched to isInitRoleGitRepo(ctx) (same argv, plus the scrub). Pinned by a new fork_auto_invalid row in TestEmbeddedInitSelectedExcludeRouting: it drops --setup-exclude so the exclude write is reachable only through the gate, adds an upstream remote so the already-scrubbed detectForkSetup reports a fork, and keeps --role=maintainer so autoConfigureForkContributor stays an early return and the gate is the only path that can add the pattern. The row carries the same fixture guard the sibling role test uses, asserting the inherited probe really is refused. Mutation-proved: with the gate reverted to isGitRepo() and the row in place, only fork_auto_invalid fails ("selected exclude = "# owned project exclude\nkeep-me/\n"; want ... "**/RECOVERY*.md"") while all six incumbent subtests stay green — so the row adds coverage rather than duplicating an existing fixture. Not taken (non-gating, recorded so the next pass grades the call rather than re-filing it) ---------------------------------------------------------------------------- - per-key `beads.role` scrub inside the generic accessor (internal/storage/domain/git/git.go:110,133): the constructor contract it straddles is owned by the parent legs; #6464 also edits this file. - splitting gitenv.routingKeys into redirect vs fence sets (internal/gitenv/routing.go): the class was filed on the parent PRs and the set is shared by the whole family; changing it here would fork a primitive five open branches consume. - deleting the three zero-caller wrappers in cmd/bd/init_stealth.go: cmd/bd/init_stealth.go is concurrently rewritten by open sibling #6461, which does not carry this leg's setupStealthModeAt/setupGitExcludeAt split (base566c84ba8greps 0 for those names; this head greps 5), so deleting them here would conflict that rewrite. Correction (iteration 2): the earlier reason for this bullet — "the file is byte-identical across the open siblings at this head" — does not reproduce and is withdrawn. git diff --name-only HEAD refs/adopt/pr6461 -- cmd/bd/init_stealth.go is NON-empty precisely because this PR created the ...At split; byte-identity with a sibling is only obtainable for siblings that already carry this leg (empty against refs/adopt-pr-probe/6464). The decision stands on the concurrent-rewrite reason above. - nit, non-git `bd init` note (cmd/bd/init.go): no code change is owed on the merits, which is its own reason rather than the execenv one it previously borrowed. commitEmbeddedInitArtifacts (cmd/bd/init.go:3477-3483) re-establishes the dropped repo gate as its own SCRUBBED `rev-parse --git-dir` probe via initArtifactGitCommand (:3537-3541); only the added stderr line is new. - nit, unexporting execenv.KeyHasPrefixForOS: internal/execenv/execenv.go is byte-identical to both siblings resolvable at this head (refs/adopt/pr6461 and refs/adopt-pr-probe/6464 both diff empty), so unexporting it here would fork a file they share. Correction (iteration 2): the earlier "across all four open siblings" quantifier overstated what is measurable — iteration 1's other two probe refs no longer exist in this worktree, so the claim is scoped to two. Iteration 2 (non-gating cleanup; no code, test, or behavior change) ------------------------------------------------------------------ The iteration-2 review found zero blockers and zero majors in this fixup's delta and the quality scorecard decided approve. All three of its items were documentation or record-keeping and are discharged here: - Contract fidelity nit: the narrowed worktrees.md sentence had fixed WHICH PLANE scrubs but kept the original's unconditional frequency ("on every `bd` command"), while the probe its appositive names — worktreeFallbackConfigPath — runs only under `primaryConfigPath == "" && beadsEnvConfigPath == ""` (internal/config/config.go:183). Reworded to separate the two: the scrub is unconditional FOR THAT PROBE, and the probe itself is a fallback that runs only when nothing earlier in startup already resolved a config path, with an ancestor .beads/config.yaml or an explicit BEADS_DIR as the short-circuits. Stated as a general condition plus examples rather than swapping one unconditional claim for another. The review's suggested wording cited internal/config/config.go:183; the line number is dropped because no file under docs/reference cites Go line numbers (6 Go-path mentions across that tree, none with :NNN) and a line citation in a doc rots. The file reference is kept so the claim stays checkable. - Release-safety minor: bd-p4che's required-fix section now also names the two PROSE sites that assert the unhardened state (this worktrees.md paragraph and clearWorktreeGitRoutingEnv's doc comment), with a drift-proof `git grep "still honor inherited routing"` anchor, because its close-out instruction previously named only the three code sites. If #6461 merges first, it adds the byte-for-byte pre-image of this paragraph at the same location, so this fixup's hunk applies CLEANLY and would leave the falsified wording behind silently; nothing in CI pins the file (absent from scripts/check_doc_freshness_test.go). Only that merge order is silent, and the direction is safe either way since stale wording under-claims protection. - Debuggability nit: the two "Not taken" bullets above are corrected, see the inline "Correction (iteration 2)" notes. Validation ---------- - git diff --check clean; go build + go vet ./cmd/bd ./internal/config green. - 25 blast-radius cmd/bd tests green with BEADS_TEST_EMBEDDED_DOLT=1 and BEADS_TEST_REQUIRE_EXCLUDE_PERMISSION=1 (exclude/stealth writers, fork auto-detect, init-role and worktree routing), incl. TestEmbeddedInitSelectedExcludeRouting 7/7. The one skip (TestInitPromptNonGitRepo) is the pre-existing "Dolt test server not running" opt-in. - An initial run showed 21 reds at 0.00s from a concurrent session sweeping the shared /tmp/beads-bd-tests-* root; all pass under an isolated TMPDIR. - Iteration 2 touches one Markdown file and no Go source, so the code validation above still stands at this tree: git diff --name-only for the iteration-2 delta is docs/reference/worktrees.md alone. git diff --check clean. worktrees.md is not in scripts/check_doc_freshness_test.go's freshnessDocuments and is named by no workflow, Makefile target, or test, so no gate covers it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(git): reconcile role-config tests with the preserved read-error contract Base advanced 11 commits during finalize and #6477 ("preserve config read errors instead of treating them as absent",cf683435e) landed in the one package this PR co-edits, internal/storage/domain/git. The rebase was clean and no production code conflicts, but the two changes falsify each other's test expectations in opposite directions: - #6477's invalid_routing_boolean row injects GIT_CONFIG_NOSYSTEM to force a beads.role read failure. This PR scrubs routing for beads.role, and gitenv.IsRoutingKeyForOS classifies every GIT_CONFIG* key as routing, so the injector can no longer reach that read. Retarget the row to test.marker so it still proves a routing-induced failure is surfaced rather than swallowed, and narrow the BeadsRole propagation assertion to malformed_config, which breaks the repository's own config and is therefore immune to the scrub. Add a positive pin that beads.role now resolves as absent without error under the same poison. - This PR's captured_home asserted NoError on the strength of "the existing reader maps Git exit errors to absence", which is exactly the contract #6477 removed. Expect the error instead, matching the adjacent assertion that the inherited writer fails on the same broken HOME. #6477's guarantee is unchanged: the merged GetConfig keeps its classification block and still uses cmd.Output(), which is what populates exitErr.Stderr. Only this one injector for this one key stopped producing a failure. internal/storage/domain/git 45/45 pass; removing the scrub from GetConfig makes the new pin fail, so it is non-vacuous. cmd/bd blast radius 28/28 pass with BEADS_TEST_EMBEDDED_DOLT=1, covering all six base-added init/temp-root tests. --------- Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com> Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
4f84628118
commit
70a12ba664
11 changed files with 876 additions and 110 deletions
|
|
@ -34,3 +34,15 @@ func newFileSystemAdapters() domain.BeadsDirFSAdapters {
|
|||
SetYAMLConfig: config.SetYamlConfig,
|
||||
}
|
||||
}
|
||||
|
||||
// newInitFileSystemAdapters keeps the selected Git project separate from storage paths.
|
||||
func newInitFileSystemAdapters(workDir string) domain.BeadsDirFSAdapters {
|
||||
adapters := newFileSystemAdapters()
|
||||
adapters.SetupForkExclude = func(verbose bool) error {
|
||||
return setupForkExcludeAt(workDir, verbose)
|
||||
}
|
||||
adapters.SetupStealthMode = func(verbose bool) error {
|
||||
return setupStealthModeAt(workDir, verbose)
|
||||
}
|
||||
return adapters
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1016,7 +1016,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
// reinit has passed its held-gate confirmation. Remote safety above
|
||||
// still evaluates the flag before this point.
|
||||
if stealth {
|
||||
if err := setupStealthMode(!quiet); err != nil {
|
||||
if err := setupStealthModeAt(cwd, !quiet); err != nil {
|
||||
return fmt.Errorf("setting up stealth mode: %v", err)
|
||||
}
|
||||
|
||||
|
|
@ -1996,15 +1996,15 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
setupExclude, _ := cmd.Flags().GetBool("setup-exclude")
|
||||
if setupExclude {
|
||||
// Manual flag - always configure
|
||||
if err := setupForkExclude(!quiet); err != nil {
|
||||
if err := setupForkExcludeAt(cwd, !quiet); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err)
|
||||
}
|
||||
} else if !stealth && isGitRepo() {
|
||||
} else if !stealth && isInitRoleGitRepo(ctx) {
|
||||
// Auto-detect fork and prompt (skip if stealth - it handles exclude already)
|
||||
if isFork, upstreamURL := detectForkSetup(); isFork {
|
||||
if nonInteractive {
|
||||
// In non-interactive mode, auto-configure fork exclude
|
||||
if err := setupForkExclude(!quiet); err != nil {
|
||||
if err := setupForkExcludeAt(cwd, !quiet); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err)
|
||||
}
|
||||
} else {
|
||||
|
|
@ -2016,7 +2016,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
}
|
||||
}
|
||||
if shouldExclude {
|
||||
if err := setupForkExclude(!quiet); err != nil {
|
||||
if err := setupForkExcludeAt(cwd, !quiet); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1447,86 +1447,6 @@ func TestInitGateBusyClassifiedAsLockContention(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestEmbeddedInitGitBootstrapRouting(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt init tests")
|
||||
}
|
||||
bd := buildEmbeddedBD(t)
|
||||
for _, name := range []string{"fresh", "decoy", "invalid", "existing_invalid", "explicit_storage", "quiet"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
existing, decoy, home := newInitRoleFixture(t)
|
||||
target := t.TempDir()
|
||||
if name == "existing_invalid" {
|
||||
target = existing
|
||||
}
|
||||
global := filepath.Join(home, ".gitconfig")
|
||||
initRoleFixtureGit(t, existing, "config", "--file", global, "user.name", "Bootstrap Fixture")
|
||||
initRoleFixtureGit(t, existing, "config", "--file", global, "user.email", "bootstrap@example.invalid")
|
||||
missingGit := filepath.Join(home, "missing git dir")
|
||||
if name == "invalid" || name == "existing_invalid" {
|
||||
t.Setenv("GIT_DIR", missingGit)
|
||||
} else if name == "decoy" || name == "explicit_storage" {
|
||||
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
|
||||
t.Setenv("GIT_WORK_TREE", decoy)
|
||||
}
|
||||
preserveInitRoleInputs(t, global, filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "HEAD"))
|
||||
beadsDir := filepath.Join(target, ".beads")
|
||||
args := []string{"init", "--prefix", "bootstrapfixture", "--non-interactive", "--skip-hooks", "--skip-agents", "--role", "maintainer"}
|
||||
if name == "quiet" {
|
||||
args = append(args, "--quiet")
|
||||
}
|
||||
cmd := exec.Command(bd, args...)
|
||||
cmd.Dir = target
|
||||
env := bdEnv(home)
|
||||
for _, key := range []string{"BEADS_DIR", "BEADS_DB", "BD_DB", "BD_DOLT_HOST", "BD_DOLT_PORT"} {
|
||||
env = envWithout(env, key)
|
||||
}
|
||||
if name == "explicit_storage" {
|
||||
beadsDir = filepath.Join(home, "separate storage", ".beads")
|
||||
if err := os.MkdirAll(filepath.Dir(beadsDir), 0750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env = append(env, "BEADS_DIR="+beadsDir)
|
||||
}
|
||||
cmd.Env = append(env, "DOLT_ROOT_PATH="+home, "BD_DOLT_MODE=embedded", "BD_EVENTS_JOURNAL=false")
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("embedded bootstrap failed: %v\n%s", err, out)
|
||||
}
|
||||
cfg, err := configfile.Load(beadsDir)
|
||||
if err != nil || cfg == nil || cfg.DoltMode != configfile.DoltModeEmbedded {
|
||||
t.Fatalf("embedded metadata missing: %+v (%v)", cfg, err)
|
||||
}
|
||||
if info, err := os.Stat(filepath.Join(beadsDir, "embeddeddolt", "bootstrapfixture", ".dolt")); err != nil || !info.IsDir() {
|
||||
t.Fatalf("embedded database missing: %v", err)
|
||||
}
|
||||
gitDir := filepath.Join(target, ".git")
|
||||
if name == "explicit_storage" {
|
||||
if _, err := os.Stat(gitDir); !os.IsNotExist(err) {
|
||||
t.Fatalf("explicit storage must skip repository creation: %v", err)
|
||||
}
|
||||
} else {
|
||||
actualGit := initRoleFixtureGit(t, target, "rev-parse", "--absolute-git-dir")
|
||||
wantInfo, err := os.Stat(gitDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actualInfo, err := os.Stat(actualGit)
|
||||
if err != nil || !os.SameFile(wantInfo, actualInfo) {
|
||||
t.Fatalf("selected Git directory = %q (%v)", actualGit, err)
|
||||
}
|
||||
}
|
||||
wantBanner := name != "quiet" && name != "existing_invalid" && name != "explicit_storage"
|
||||
if got := strings.Count(string(out), "Initialized git repository"); (wantBanner && got != 1) || (!wantBanner && got != 0) {
|
||||
t.Errorf("initialization banner count = %d, want visible=%v: %s", got, wantBanner, out)
|
||||
}
|
||||
if _, err := os.Stat(missingGit); !os.IsNotExist(err) {
|
||||
t.Errorf("init created the inherited invalid Git directory: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbeddedInitRoleRouting(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt init tests")
|
||||
|
|
@ -1606,6 +1526,90 @@ func TestEmbeddedInitRoleRouting(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestEmbeddedInitSelectedExcludeRouting(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt init tests")
|
||||
}
|
||||
bd := buildEmbeddedBD(t)
|
||||
for _, name := range []string{"stealth_decoy", "stealth_invalid", "fork_decoy", "fork_invalid", "quiet_stealth", "quiet_fork", "fork_auto_invalid"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
target, decoy, home := newInitRoleFixture(t)
|
||||
global := filepath.Join(home, ".gitconfig")
|
||||
initRoleFixtureGit(t, target, "config", "--file", global, "user.name", "Exclude Fixture")
|
||||
initRoleFixtureGit(t, target, "config", "--file", global, "user.email", "exclude@example.invalid")
|
||||
exclude := filepath.Join(target, ".git", "info", "exclude")
|
||||
const existing = "# owned project exclude\nkeep-me/\n"
|
||||
if err := os.WriteFile(exclude, []byte(existing), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
preserveInitRoleInputs(t, filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "info", "exclude"), global)
|
||||
missing := filepath.Join(home, "missing-inherited.git")
|
||||
routing := filepath.Join(decoy, ".git")
|
||||
if strings.HasSuffix(name, "invalid") {
|
||||
routing = missing
|
||||
}
|
||||
t.Setenv("GIT_DIR", routing)
|
||||
t.Setenv("GIT_WORK_TREE", decoy)
|
||||
storage := filepath.Join(home, "separate storage", ".beads")
|
||||
if err := os.MkdirAll(filepath.Dir(storage), 0750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args := []string{"init", "--prefix", "excludefixture", "--non-interactive", "--skip-hooks", "--skip-agents", "--role", "maintainer"}
|
||||
stealth, quiet := strings.Contains(name, "stealth"), strings.HasPrefix(name, "quiet")
|
||||
want := "**/RECOVERY*.md"
|
||||
banner := "Added to .git/info/exclude:"
|
||||
if stealth {
|
||||
args = append(args, "--stealth")
|
||||
want, banner = ".claude/settings.local.json", "Stealth mode configured successfully!"
|
||||
} else if strings.Contains(name, "auto") {
|
||||
// Auto-detect arm: without --setup-exclude the exclude write is
|
||||
// reached only through the fork auto-detect gate, so this row
|
||||
// covers that gate's own repository probe rather than the
|
||||
// already-hardened writer. An upstream remote makes the scrubbed
|
||||
// detectForkSetup report a fork; --role=maintainer keeps
|
||||
// autoConfigureForkContributor an early return, so the gate is
|
||||
// the only path that can add the pattern.
|
||||
initRoleFixtureGit(t, target, "remote", "add", "upstream", filepath.Join(home, "upstream.git"))
|
||||
if isGitRepo() {
|
||||
t.Fatal("invalid routing must refuse the inherited repository probe")
|
||||
}
|
||||
} else {
|
||||
args = append(args, "--setup-exclude")
|
||||
}
|
||||
if quiet {
|
||||
args = append(args, "--quiet")
|
||||
}
|
||||
env := bdEnv(home)
|
||||
for _, key := range []string{"BEADS_DIR", "BEADS_DB", "BD_DB", "BD_DOLT_HOST", "BD_DOLT_PORT"} {
|
||||
env = envWithout(env, key)
|
||||
}
|
||||
cmd := exec.Command(bd, args...)
|
||||
cmd.Dir, cmd.Env = target, append(env, "BEADS_DIR="+storage, "DOLT_ROOT_PATH="+home, "BD_DOLT_MODE=embedded", "BD_EVENTS_JOURNAL=false")
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("embedded exclude init failed: %v\n%s", err, out)
|
||||
}
|
||||
data, err := os.ReadFile(exclude)
|
||||
if err != nil || !strings.HasPrefix(string(data), existing) || !containsExactPattern(string(data), want) || !containsExactPattern(string(data), ".beads/") {
|
||||
t.Fatalf("selected exclude = %q (%v); want original lines and %q", data, err, want)
|
||||
}
|
||||
if strings.Contains(string(out), banner) == quiet {
|
||||
t.Errorf("exclude banner does not match quiet=%v: %s", quiet, out)
|
||||
}
|
||||
cfg, err := configfile.Load(storage)
|
||||
if err != nil || cfg == nil || cfg.DoltMode != configfile.DoltModeEmbedded {
|
||||
t.Fatalf("selected storage metadata = %+v, %v", cfg, err)
|
||||
}
|
||||
if info, err := os.Stat(filepath.Join(storage, "embeddeddolt", "excludefixture", ".dolt")); err != nil || !info.IsDir() {
|
||||
t.Fatalf("embedded database missing from selected storage: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(missing); !os.IsNotExist(err) {
|
||||
t.Errorf("inherited Git directory was created: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbeddedInitArtifactRouting(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt init tests")
|
||||
|
|
@ -1648,3 +1652,83 @@ func TestEmbeddedInitArtifactRouting(t *testing.T) {
|
|||
t.Errorf("embedded init did not commit target metadata: %v: %s", err, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbeddedInitGitBootstrapRouting(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt init tests")
|
||||
}
|
||||
bd := buildEmbeddedBD(t)
|
||||
for _, name := range []string{"fresh", "decoy", "invalid", "existing_invalid", "explicit_storage", "quiet"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
existing, decoy, home := newInitRoleFixture(t)
|
||||
target := t.TempDir()
|
||||
if name == "existing_invalid" {
|
||||
target = existing
|
||||
}
|
||||
global := filepath.Join(home, ".gitconfig")
|
||||
initRoleFixtureGit(t, existing, "config", "--file", global, "user.name", "Bootstrap Fixture")
|
||||
initRoleFixtureGit(t, existing, "config", "--file", global, "user.email", "bootstrap@example.invalid")
|
||||
missingGit := filepath.Join(home, "missing git dir")
|
||||
if name == "invalid" || name == "existing_invalid" {
|
||||
t.Setenv("GIT_DIR", missingGit)
|
||||
} else if name == "decoy" || name == "explicit_storage" {
|
||||
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
|
||||
t.Setenv("GIT_WORK_TREE", decoy)
|
||||
}
|
||||
preserveInitRoleInputs(t, global, filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "HEAD"))
|
||||
beadsDir := filepath.Join(target, ".beads")
|
||||
args := []string{"init", "--prefix", "bootstrapfixture", "--non-interactive", "--skip-hooks", "--skip-agents", "--role", "maintainer"}
|
||||
if name == "quiet" {
|
||||
args = append(args, "--quiet")
|
||||
}
|
||||
cmd := exec.Command(bd, args...)
|
||||
cmd.Dir = target
|
||||
env := bdEnv(home)
|
||||
for _, key := range []string{"BEADS_DIR", "BEADS_DB", "BD_DB", "BD_DOLT_HOST", "BD_DOLT_PORT"} {
|
||||
env = envWithout(env, key)
|
||||
}
|
||||
if name == "explicit_storage" {
|
||||
beadsDir = filepath.Join(home, "separate storage", ".beads")
|
||||
if err := os.MkdirAll(filepath.Dir(beadsDir), 0750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env = append(env, "BEADS_DIR="+beadsDir)
|
||||
}
|
||||
cmd.Env = append(env, "DOLT_ROOT_PATH="+home, "BD_DOLT_MODE=embedded", "BD_EVENTS_JOURNAL=false")
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("embedded bootstrap failed: %v\n%s", err, out)
|
||||
}
|
||||
cfg, err := configfile.Load(beadsDir)
|
||||
if err != nil || cfg == nil || cfg.DoltMode != configfile.DoltModeEmbedded {
|
||||
t.Fatalf("embedded metadata missing: %+v (%v)", cfg, err)
|
||||
}
|
||||
if info, err := os.Stat(filepath.Join(beadsDir, "embeddeddolt", "bootstrapfixture", ".dolt")); err != nil || !info.IsDir() {
|
||||
t.Fatalf("embedded database missing: %v", err)
|
||||
}
|
||||
gitDir := filepath.Join(target, ".git")
|
||||
if name == "explicit_storage" {
|
||||
if _, err := os.Stat(gitDir); !os.IsNotExist(err) {
|
||||
t.Fatalf("explicit storage must skip repository creation: %v", err)
|
||||
}
|
||||
} else {
|
||||
actualGit := initRoleFixtureGit(t, target, "rev-parse", "--absolute-git-dir")
|
||||
wantInfo, err := os.Stat(gitDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actualInfo, err := os.Stat(actualGit)
|
||||
if err != nil || !os.SameFile(wantInfo, actualInfo) {
|
||||
t.Fatalf("selected Git directory = %q (%v)", actualGit, err)
|
||||
}
|
||||
}
|
||||
wantBanner := name != "quiet" && name != "existing_invalid" && name != "explicit_storage"
|
||||
if got := strings.Count(string(out), "Initialized git repository"); (wantBanner && got != 1) || (!wantBanner && got != 0) {
|
||||
t.Errorf("initialization banner count = %d, want visible=%v: %s", got, wantBanner, out)
|
||||
}
|
||||
if _, err := os.Stat(missingGit); !os.IsNotExist(err) {
|
||||
t.Errorf("init created the inherited invalid Git directory: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
|
@ -14,7 +15,9 @@ import (
|
|||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/gitenv"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
domaingit "github.com/steveyegge/beads/internal/storage/domain/git"
|
||||
"github.com/steveyegge/beads/internal/storage/fs"
|
||||
"github.com/steveyegge/beads/internal/storage/git"
|
||||
"github.com/steveyegge/beads/internal/storage/uow"
|
||||
|
|
@ -95,7 +98,7 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie
|
|||
return fmt.Errorf("failed to get current directory: %v", err)
|
||||
}
|
||||
|
||||
fsProvider := fs.NewFileSystemProvider(cwd, newBeadsDirTemplates(), newFileSystemAdapters())
|
||||
fsProvider := fs.NewFileSystemProvider(cwd, newBeadsDirTemplates(), newInitFileSystemAdapters(cwd))
|
||||
fsUseCase := fsProvider.BeadsDirFSUseCase()
|
||||
gitUC := git.NewGitProvider(cwd).GitUseCase()
|
||||
|
||||
|
|
@ -283,6 +286,7 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie
|
|||
}
|
||||
|
||||
return runInitProxiedServerTail(cmd, ctx, in, runInitTailContext{
|
||||
workDir: cwd,
|
||||
beadsDir: beadsDir,
|
||||
prefix: adoptedPrefix,
|
||||
dbName: dbName,
|
||||
|
|
@ -507,6 +511,7 @@ func buildProxiedServerClientInfo(rootPath, configPath, logPath string, port int
|
|||
}
|
||||
|
||||
type runInitTailContext struct {
|
||||
workDir string
|
||||
beadsDir string
|
||||
prefix string
|
||||
dbName string
|
||||
|
|
@ -516,17 +521,34 @@ type runInitTailContext struct {
|
|||
gitUC domain.GitUseCase
|
||||
}
|
||||
|
||||
func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initProxiedServerInput, t runInitTailContext) error {
|
||||
isRepo := t.gitUC.IsGitRepo(ctx)
|
||||
func (t runInitTailContext) isRoleGitRepo(ctx context.Context, fallback bool) bool {
|
||||
// Isolated tail contexts without a selected path retain their supplied use case.
|
||||
if t.workDir == "" {
|
||||
return fallback
|
||||
}
|
||||
// Dropping discovery ceilings can select a containing parent repository,
|
||||
// matching the role adapter's existing scrubbed reads and writes.
|
||||
probe := exec.CommandContext(ctx, "git", "rev-parse", "--git-dir")
|
||||
probe.Dir, probe.Env = t.workDir, gitenv.ScrubRouting(os.Environ())
|
||||
return probe.Run() == nil
|
||||
}
|
||||
|
||||
if isRepo {
|
||||
func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initProxiedServerInput, t runInitTailContext) error {
|
||||
gitUC := t.gitUC
|
||||
if t.workDir != "" {
|
||||
// Only the selected tail uses this scope; earlier bootstrap keeps its provider.
|
||||
gitUC = domain.NewGitUseCase(t.workDir, domaingit.NewInitGitRepository(t.workDir))
|
||||
}
|
||||
isRepo := gitUC.IsGitRepo(ctx)
|
||||
|
||||
if t.isRoleGitRepo(ctx, isRepo) {
|
||||
role := in.roleFlag
|
||||
if role == "" {
|
||||
role = "maintainer"
|
||||
}
|
||||
_, hasRole, _ := t.gitUC.BeadsRole(ctx)
|
||||
_, hasRole, _ := gitUC.BeadsRole(ctx)
|
||||
if !hasRole || in.roleFlag != "" {
|
||||
if err := t.gitUC.SetBeadsRole(ctx, role); err != nil && !in.quiet {
|
||||
if err := gitUC.SetBeadsRole(ctx, role); err != nil && !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -538,7 +560,7 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr
|
|||
fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err)
|
||||
}
|
||||
} else if !in.stealth && isRepo {
|
||||
if isFork, upstreamURL, _ := t.gitUC.DetectFork(ctx); isFork {
|
||||
if isFork, upstreamURL, _ := gitUC.DetectFork(ctx); isFork {
|
||||
if in.nonInteractive {
|
||||
if err := t.fsUseCase.SetupForkExclude(ctx, !in.quiet); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err)
|
||||
|
|
@ -562,8 +584,8 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr
|
|||
if hooksInstalled() && !in.quiet {
|
||||
fmt.Printf(" Updating hooks to version %s...\n", Version)
|
||||
}
|
||||
isJJ := t.gitUC.IsJujutsuRepo(ctx)
|
||||
isColocated := t.gitUC.IsColocatedJJGit(ctx)
|
||||
isJJ := gitUC.IsJujutsuRepo(ctx)
|
||||
isColocated := gitUC.IsColocatedJJGit(ctx)
|
||||
switch {
|
||||
case isJJ && !isColocated:
|
||||
if !in.quiet {
|
||||
|
|
@ -606,7 +628,7 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr
|
|||
if resolvedAgentsFile == "" {
|
||||
resolvedAgentsFile = config.SafeAgentsFile()
|
||||
}
|
||||
isBare := t.gitUC.IsBareGitRepo(ctx)
|
||||
isBare := gitUC.IsBareGitRepo(ctx)
|
||||
if isBare {
|
||||
if !in.quiet {
|
||||
fmt.Printf(" Skipping %s generation in bare repository\n", resolvedAgentsFile)
|
||||
|
|
@ -627,7 +649,7 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr
|
|||
}
|
||||
|
||||
if !in.stealth && isRepo && t.useLocalBeads {
|
||||
commitResult, err := t.gitUC.CommitInitArtifacts(ctx, domain.CommitInitArtifactsParams{
|
||||
commitResult, err := gitUC.CommitInitArtifacts(ctx, domain.CommitInitArtifactsParams{
|
||||
BeadsDir: ".beads/",
|
||||
OptionalPaths: []string{
|
||||
config.SafeAgentsFile(),
|
||||
|
|
@ -648,7 +670,7 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr
|
|||
}
|
||||
|
||||
if isRepo && !in.quiet {
|
||||
if t.gitUC.HasAnyRemotes(ctx) && !t.gitUC.HasUpstream(ctx) {
|
||||
if gitUC.HasAnyRemotes(ctx) && !gitUC.HasUpstream(ctx) {
|
||||
fmt.Fprintf(os.Stderr, "\n%s Git upstream not configured\n", ui.RenderWarn("⚠"))
|
||||
fmt.Fprintf(os.Stderr, " For sync workflows, set your upstream with:\n")
|
||||
fmt.Fprintf(os.Stderr, " %s\n\n", ui.RenderAccent("git remote add upstream <repo-url>"))
|
||||
|
|
|
|||
|
|
@ -1,12 +1,24 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/gitenv"
|
||||
"github.com/steveyegge/beads/internal/storage/dbproxy/proxy"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
storagefs "github.com/steveyegge/beads/internal/storage/fs"
|
||||
storagegit "github.com/steveyegge/beads/internal/storage/git"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
|
@ -226,3 +238,337 @@ func TestIsTeamServerManaged_RequiresProxiedServerMode(t *testing.T) {
|
|||
cfg.DoltMode = configfile.DoltModeProxiedServer
|
||||
assert.True(t, cfg.IsTeamServerManaged())
|
||||
}
|
||||
|
||||
func TestProxiedInitTailRoleIgnoresInheritedGitRouting(t *testing.T) {
|
||||
for _, entry := range os.Environ() {
|
||||
key := gitenv.EntryKey(entry)
|
||||
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
|
||||
t.Setenv(key, "")
|
||||
require.NoError(t, os.Unsetenv(key))
|
||||
}
|
||||
}
|
||||
home := t.TempDir()
|
||||
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
|
||||
t.Setenv(key, home)
|
||||
}
|
||||
globalPath := filepath.Join(home, ".gitconfig")
|
||||
require.NoError(t, os.WriteFile(globalPath, nil, 0600))
|
||||
runGit := func(t *testing.T, dir string, args ...string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ())
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoError(t, err, "fixture git %v: %s", args, out)
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, initial, flag, want string
|
||||
}{
|
||||
{"explicit", "maintainer", "contributor", "contributor"},
|
||||
{"default", "", "", "maintainer"},
|
||||
{"retained", "contributor", "", "contributor"},
|
||||
} {
|
||||
for _, poison := range []string{"repository", "inline_config"} {
|
||||
t.Run(tc.name+"/"+poison, func(t *testing.T) {
|
||||
target, decoy := t.TempDir(), t.TempDir()
|
||||
for _, dir := range []string{target, decoy} {
|
||||
runGit(t, dir, "init", "--quiet")
|
||||
runGit(t, dir, "config", "--local", "core.hooksPath", ".git/hooks")
|
||||
}
|
||||
if tc.initial != "" {
|
||||
runGit(t, target, "config", "--local", "beads.role", tc.initial)
|
||||
}
|
||||
runGit(t, decoy, "config", "--local", "beads.role", "decoy-role")
|
||||
if poison == "repository" {
|
||||
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
|
||||
t.Setenv("GIT_WORK_TREE", decoy)
|
||||
} else {
|
||||
t.Setenv("GIT_CONFIG_COUNT", "1")
|
||||
t.Setenv("GIT_CONFIG_KEY_0", "beads.role")
|
||||
t.Setenv("GIT_CONFIG_VALUE_0", "injected-role")
|
||||
}
|
||||
env := os.Environ()
|
||||
before, err := os.ReadFile(filepath.Join(decoy, ".git", "config"))
|
||||
require.NoError(t, err)
|
||||
gitUC := storagegit.NewGitProvider(target).GitUseCase()
|
||||
require.True(t, gitUC.IsGitRepo(t.Context()), "valid inherited repository must reach role branch")
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().Bool("setup-exclude", false, "")
|
||||
// Existing flags exclude all filesystem integrations; nil fsUseCase must stay unused.
|
||||
in := initProxiedServerInput{roleFlag: tc.flag, quiet: true, stealth: true, skipHooks: true, skipAgents: true}
|
||||
require.NoError(t, runInitProxiedServerTail(cmd, t.Context(), in, runInitTailContext{gitUC: gitUC}))
|
||||
require.Equal(t, tc.want, runGit(t, target, "config", "--local", "--get", "beads.role"))
|
||||
after, err := os.ReadFile(filepath.Join(decoy, ".git", "config"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(before), string(after), "proxied tail changed decoy")
|
||||
globalAfter, err := os.ReadFile(globalPath)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, globalAfter)
|
||||
require.True(t, slices.Equal(env, os.Environ()), "proxied tail changed inherited environment")
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type proxiedRoleProbeUseCase struct {
|
||||
domain.GitUseCase
|
||||
roleReads int
|
||||
}
|
||||
|
||||
func (u *proxiedRoleProbeUseCase) BeadsRole(ctx context.Context) (string, bool, error) {
|
||||
u.roleReads++
|
||||
return u.GitUseCase.BeadsRole(ctx)
|
||||
}
|
||||
|
||||
func TestProxiedInitTailRoleProbeUsesSelectedDirectory(t *testing.T) {
|
||||
for _, entry := range os.Environ() {
|
||||
key := gitenv.EntryKey(entry)
|
||||
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
|
||||
t.Setenv(key, "")
|
||||
require.NoError(t, os.Unsetenv(key))
|
||||
}
|
||||
}
|
||||
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
|
||||
runGit := func(t *testing.T, dir string, args ...string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ())
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoError(t, err, "fixture git %v: %s", args, out)
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, kind, initial, flag, want string
|
||||
}{
|
||||
{"explicit", "ordinary", "maintainer", "contributor", "contributor"},
|
||||
{"default", "ordinary", "", "", "maintainer"},
|
||||
{"retained", "ordinary", "contributor", "", "contributor"},
|
||||
{"bare_explicit", "bare", "maintainer", "contributor", "contributor"},
|
||||
{"bare_default", "bare", "", "", "maintainer"},
|
||||
{"bare_retained", "bare", "contributor", "", "contributor"},
|
||||
{"nonrepo_with_decoy_and_global_role", "nonrepo", "", "", ""},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
home, target, decoy := t.TempDir(), t.TempDir(), t.TempDir()
|
||||
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
|
||||
t.Setenv(key, home)
|
||||
}
|
||||
globalData := ""
|
||||
if tc.kind == "nonrepo" {
|
||||
globalData = "[beads]\n\trole = global-role\n"
|
||||
}
|
||||
globalPath := filepath.Join(home, ".gitconfig")
|
||||
require.NoError(t, os.WriteFile(globalPath, []byte(globalData), 0600))
|
||||
runGit(t, decoy, "init", "--quiet")
|
||||
runGit(t, decoy, "config", "--local", "core.hooksPath", ".git/hooks")
|
||||
runGit(t, decoy, "config", "--local", "beads.role", "decoy-role")
|
||||
if tc.kind == "bare" {
|
||||
runGit(t, target, "init", "--bare", "--quiet")
|
||||
runGit(t, target, "config", "--local", "core.hooksPath", filepath.Join(target, "hooks"))
|
||||
} else if tc.kind == "ordinary" {
|
||||
runGit(t, target, "init", "--quiet")
|
||||
runGit(t, target, "config", "--local", "core.hooksPath", ".git/hooks")
|
||||
}
|
||||
if tc.initial != "" {
|
||||
runGit(t, target, "config", "--local", "beads.role", tc.initial)
|
||||
}
|
||||
probe := exec.Command("git", "rev-parse", "--git-dir")
|
||||
probe.Dir, probe.Env = target, gitenv.ScrubRouting(os.Environ())
|
||||
require.Equal(t, tc.kind != "nonrepo", probe.Run() == nil, "owned target repository precondition")
|
||||
if tc.kind == "nonrepo" {
|
||||
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
|
||||
} else {
|
||||
invalid := filepath.Join(t.TempDir(), "invalid-git-dir")
|
||||
require.NoError(t, os.WriteFile(invalid, []byte("not a Git directory\n"), 0600))
|
||||
t.Setenv("GIT_DIR", invalid)
|
||||
}
|
||||
t.Setenv("GIT_WORK_TREE", decoy)
|
||||
t.Chdir(decoy)
|
||||
base := storagegit.NewGitProvider(target).GitUseCase()
|
||||
require.Equal(t, tc.kind == "nonrepo", base.IsGitRepo(t.Context()), "inherited probe precondition")
|
||||
if tc.kind == "nonrepo" {
|
||||
role, found, err := base.BeadsRole(t.Context())
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
require.Equal(t, "global-role", role, "global config alone must not manufacture a repository")
|
||||
}
|
||||
gitUC := &proxiedRoleProbeUseCase{GitUseCase: base}
|
||||
before, err := os.ReadFile(filepath.Join(decoy, ".git", "config"))
|
||||
require.NoError(t, err)
|
||||
env := os.Environ()
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().Bool("setup-exclude", false, "")
|
||||
in := initProxiedServerInput{roleFlag: tc.flag, quiet: true, stealth: true, skipHooks: true, skipAgents: true}
|
||||
require.NoError(t, runInitProxiedServerTail(cmd, t.Context(), in, runInitTailContext{workDir: target, gitUC: gitUC}))
|
||||
require.Zero(t, gitUC.roleReads, "selected tail must bypass the inherited role provider")
|
||||
if tc.kind == "nonrepo" {
|
||||
entries, err := os.ReadDir(target)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, entries)
|
||||
} else {
|
||||
require.Equal(t, tc.want, runGit(t, target, "config", "--local", "--get", "beads.role"))
|
||||
}
|
||||
after, err := os.ReadFile(filepath.Join(decoy, ".git", "config"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(before), string(after), "tail changed decoy config")
|
||||
globalAfter, err := os.ReadFile(globalPath)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, globalData, string(globalAfter))
|
||||
require.True(t, slices.Equal(env, os.Environ()), "tail changed inherited environment")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type initTailForkObservation struct {
|
||||
domain.BeadsDirFSUseCase
|
||||
calls int
|
||||
}
|
||||
|
||||
func (f *initTailForkObservation) SetupForkExclude(context.Context, bool) error {
|
||||
f.calls++
|
||||
return nil // Observe fork selection; the exclude writer has separate coverage.
|
||||
}
|
||||
|
||||
func TestProxiedInitTailGitUsesSelectedDirectory(t *testing.T) {
|
||||
for _, entry := range os.Environ() {
|
||||
key := gitenv.EntryKey(entry)
|
||||
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
|
||||
t.Setenv(key, "")
|
||||
require.NoError(t, os.Unsetenv(key))
|
||||
}
|
||||
}
|
||||
home := t.TempDir()
|
||||
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
|
||||
t.Setenv(key, home)
|
||||
}
|
||||
runGit := func(dir string, args ...string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ())
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoError(t, err, "fixture git %v: %s", args, out)
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
read := func(path string) []byte {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(path)
|
||||
require.NoError(t, err)
|
||||
return data
|
||||
}
|
||||
for _, name := range []string{"decoy", "invalid", "nonrepo"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
target, decoy := t.TempDir(), t.TempDir()
|
||||
for _, dir := range []string{target, decoy} {
|
||||
if dir != target || name != "nonrepo" {
|
||||
runGit(dir, "init", "--quiet")
|
||||
for key, value := range map[string]string{"user.name": "Fixture", "user.email": "fixture@example.test", "commit.gpgSign": "false", "core.hooksPath": ".git/hooks"} {
|
||||
runGit(dir, "config", "--local", key, value)
|
||||
}
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "seed"), []byte("seed\n"), 0600))
|
||||
runGit(dir, "add", "seed")
|
||||
runGit(dir, "-c", "core.hooksPath=", "commit", "-m", "seed")
|
||||
}
|
||||
require.NoError(t, os.Mkdir(filepath.Join(dir, ".beads"), 0755))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, ".beads", "artifact"), []byte(dir), 0600))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "CLAUDE.md"), []byte("optional\n"), 0600))
|
||||
}
|
||||
runGit(decoy, "remote", "add", "upstream", "https://example.test/decoy.git")
|
||||
runGit(decoy, "config", "beads.role", "decoy-role")
|
||||
foreignIndex := filepath.Join(t.TempDir(), "foreign-index")
|
||||
require.NoError(t, os.WriteFile(foreignIndex, read(filepath.Join(decoy, ".git", "index")), 0600))
|
||||
preserved := map[string][]byte{}
|
||||
for _, path := range []string{foreignIndex, filepath.Join(decoy, ".git", "index"), filepath.Join(decoy, ".git", "config")} {
|
||||
preserved[path] = read(path)
|
||||
}
|
||||
decoyHead := runGit(decoy, "rev-parse", "HEAD")
|
||||
gitDir := filepath.Join(decoy, ".git")
|
||||
if name == "invalid" {
|
||||
gitDir = filepath.Join(t.TempDir(), "missing-git-dir")
|
||||
}
|
||||
t.Setenv("GIT_DIR", gitDir)
|
||||
t.Setenv("GIT_WORK_TREE", decoy)
|
||||
t.Setenv("GIT_INDEX_FILE", foreignIndex)
|
||||
t.Chdir(decoy)
|
||||
env := os.Environ()
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().Bool("setup-exclude", false, "")
|
||||
fs := &initTailForkObservation{}
|
||||
in := initProxiedServerInput{skipHooks: true, skipAgents: true, nonInteractive: true}
|
||||
stderr := captureStderr(t, func() {
|
||||
require.NoError(t, runInitProxiedServerTail(cmd, t.Context(), in, runInitTailContext{workDir: target, beadsDir: filepath.Join(target, ".beads"), useLocalBeads: true, fsUseCase: fs, gitUC: storagegit.NewGitProvider(target).GitUseCase()}))
|
||||
})
|
||||
require.Zero(t, fs.calls, "decoy fork selected")
|
||||
require.NotContains(t, stderr, "Git upstream not configured", "decoy remotes selected")
|
||||
if name == "nonrepo" {
|
||||
_, err := os.Stat(filepath.Join(target, ".git"))
|
||||
require.True(t, os.IsNotExist(err), "tail manufactured a repository")
|
||||
} else {
|
||||
require.Equal(t, "2", runGit(target, "rev-list", "--count", "HEAD"), "target artifacts were not committed")
|
||||
require.Equal(t, target, runGit(target, "show", "HEAD:.beads/artifact"))
|
||||
require.Equal(t, "optional", runGit(target, "show", "HEAD:CLAUDE.md"))
|
||||
require.Empty(t, runGit(target, "diff", "--cached", "--name-only"))
|
||||
}
|
||||
require.Equal(t, decoyHead, runGit(decoy, "rev-parse", "HEAD"), "decoy HEAD changed")
|
||||
for path, before := range preserved {
|
||||
require.Equal(t, before, read(path), "tail changed %s", path)
|
||||
}
|
||||
require.True(t, slices.Equal(env, os.Environ()), "tail changed inherited environment")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxiedInitExcludeUsesSelectedDirectory(t *testing.T) {
|
||||
for _, name := range []string{"stealth", "setup_exclude", "target_fork", "decoy_fork"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
worktree, decoy, commonExclude, privateExclude := newInitExcludeRepos(t)
|
||||
if name == "target_fork" {
|
||||
initExcludeGit(t, worktree, "remote", "add", "upstream", "https://example.test/target.git")
|
||||
} else if name == "decoy_fork" {
|
||||
initExcludeGit(t, decoy, "remote", "add", "upstream", "https://example.test/decoy.git")
|
||||
}
|
||||
storage := t.TempDir()
|
||||
t.Setenv("BEADS_DIR", storage)
|
||||
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
|
||||
t.Setenv("GIT_WORK_TREE", decoy)
|
||||
decoyConfig, err := os.ReadFile(filepath.Join(decoy, ".git", "config"))
|
||||
require.NoError(t, err)
|
||||
env := os.Environ()
|
||||
// Construct the same selected provider/adapter used before the real init tail.
|
||||
fsUseCase := storagefs.NewFileSystemProvider(worktree, newBeadsDirTemplates(), newInitFileSystemAdapters(worktree)).BeadsDirFSUseCase()
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().Bool("setup-exclude", name == "setup_exclude", "")
|
||||
in := initProxiedServerInput{stealth: name == "stealth", quiet: true, nonInteractive: true, skipHooks: true, skipAgents: true}
|
||||
tail := runInitTailContext{workDir: worktree, beadsDir: storage, fsUseCase: fsUseCase, gitUC: storagegit.NewGitProvider(worktree).GitUseCase()}
|
||||
for range 2 {
|
||||
stderr := captureStderr(t, func() {
|
||||
if in.stealth {
|
||||
require.NoError(t, fsUseCase.SetupStealthMode(t.Context(), false))
|
||||
}
|
||||
require.NoError(t, runInitProxiedServerTail(cmd, t.Context(), in, tail))
|
||||
})
|
||||
require.Empty(t, stderr)
|
||||
}
|
||||
want := "# preserved\r\n"
|
||||
if in.stealth {
|
||||
want += "\r\n# Beads stealth mode (added by bd init --stealth)\r\n.beads/\r\n.claude/settings.local.json\r\n"
|
||||
} else if name != "decoy_fork" {
|
||||
want += "\r\n# Beads fork protection (bd init)\r\n.beads/\r\n**/RECOVERY*.md\r\n**/SESSION*.md\r\n"
|
||||
}
|
||||
data, err := os.ReadFile(commonExclude)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, string(data), "selected common exclude bytes")
|
||||
data, err = os.ReadFile(filepath.Join(decoy, ".git", "info", "exclude"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "# preserved\r\n", string(data))
|
||||
data, err = os.ReadFile(filepath.Join(decoy, ".git", "config"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, decoyConfig, data)
|
||||
_, err = os.Stat(privateExclude)
|
||||
require.ErrorIs(t, err, os.ErrNotExist)
|
||||
entries, err := os.ReadDir(storage)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, entries, "storage location became the Git project")
|
||||
require.True(t, slices.Equal(env, os.Environ()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,8 +24,12 @@ import (
|
|||
// - .git/info/exclude is designed for user-specific, repo-local ignores
|
||||
// - Patterns are relative to repo root, so ".beads/" works correctly
|
||||
func setupStealthMode(verbose bool) error {
|
||||
return setupStealthModeAt("", verbose)
|
||||
}
|
||||
|
||||
func setupStealthModeAt(repoPath string, verbose bool) error {
|
||||
// Setup per-repository git exclude file (skip if not in a git repo)
|
||||
if err := setupGitExclude(verbose); err != nil {
|
||||
if err := setupGitExcludeAt(repoPath, verbose); err != nil {
|
||||
if strings.Contains(err.Error(), "not a git repository") {
|
||||
if verbose {
|
||||
fmt.Printf("Not in a git repository — skipping git exclude setup\n")
|
||||
|
|
@ -49,7 +53,11 @@ func setupStealthMode(verbose bool) error {
|
|||
// This is the correct approach for per-repository user-specific ignores (GitHub #704).
|
||||
// Unlike global gitignore, patterns here are relative to the repo root.
|
||||
func setupGitExclude(verbose bool) error {
|
||||
added, excludePath, err := addExcludePatterns("",
|
||||
return setupGitExcludeAt("", verbose)
|
||||
}
|
||||
|
||||
func setupGitExcludeAt(repoPath string, verbose bool) error {
|
||||
added, excludePath, err := addExcludePatterns(repoPath,
|
||||
"# Beads stealth mode (added by bd init --stealth)",
|
||||
[]string{".beads/", ".claude/settings.local.json"})
|
||||
if err != nil {
|
||||
|
|
@ -343,7 +351,11 @@ func checkProjectExcludeStealth(repoPath string) doctor.DoctorCheck {
|
|||
// This is separate from stealth mode - fork protection is specifically about
|
||||
// preventing beads/Claude files from appearing in upstream PRs.
|
||||
func setupForkExclude(verbose bool) error {
|
||||
added, _, err := addExcludePatterns("",
|
||||
return setupForkExcludeAt("", verbose)
|
||||
}
|
||||
|
||||
func setupForkExcludeAt(repoPath string, verbose bool) error {
|
||||
added, _, err := addExcludePatterns(repoPath,
|
||||
"# Beads fork protection (bd init)",
|
||||
[]string{".beads/", "**/RECOVERY*.md", "**/SESSION*.md"})
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ import (
|
|||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/cmd/bd/doctor"
|
||||
"github.com/steveyegge/beads/internal/gitenv"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestSetupGitExclude_Worktree verifies that setupGitExclude writes to the main
|
||||
|
|
@ -620,6 +622,77 @@ func TestAddExcludePatternsCreatesMissingFile(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func initExcludeGit(t *testing.T, dir string, args ...string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ())
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoError(t, err, "fixture git %v: %s", args, out)
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
|
||||
func newInitExcludeRepos(t *testing.T) (worktree, decoy, commonExclude, privateExclude string) {
|
||||
t.Helper()
|
||||
for _, entry := range os.Environ() {
|
||||
key := gitenv.EntryKey(entry)
|
||||
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
|
||||
// Setenv registers restoration; Unsetenv then makes the key absent during the test.
|
||||
t.Setenv(key, "")
|
||||
require.NoError(t, os.Unsetenv(key))
|
||||
}
|
||||
}
|
||||
home := t.TempDir()
|
||||
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
|
||||
t.Setenv(key, home)
|
||||
}
|
||||
mainDir, decoy := t.TempDir(), t.TempDir()
|
||||
for _, dir := range []string{mainDir, decoy} {
|
||||
initExcludeGit(t, dir, "init", "--quiet")
|
||||
for key, value := range map[string]string{"user.name": "Fixture", "user.email": "fixture@example.test", "commit.gpgSign": "false", "core.hooksPath": filepath.Join(home, "hooks")} {
|
||||
initExcludeGit(t, dir, "config", "--local", key, value)
|
||||
}
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, ".git", "info", "exclude"), []byte("# preserved\r\n"), 0600))
|
||||
}
|
||||
initExcludeGit(t, mainDir, "commit", "--allow-empty", "-m", "fixture")
|
||||
worktree = filepath.Join(t.TempDir(), "selected worktree")
|
||||
initExcludeGit(t, mainDir, "worktree", "add", "--quiet", "-b", "selected", worktree)
|
||||
commonExclude = filepath.Join(mainDir, ".git", "info", "exclude")
|
||||
privateExclude = filepath.Join(initExcludeGit(t, worktree, "rev-parse", "--absolute-git-dir"), "info", "exclude")
|
||||
t.Chdir(decoy)
|
||||
return worktree, decoy, commonExclude, privateExclude
|
||||
}
|
||||
|
||||
func TestGitExcludeExplicitPathSelectsCommonDir(t *testing.T) {
|
||||
for _, key := range []string{"GIT_DIR", "GIT_COMMON_DIR"} {
|
||||
t.Run(key, func(t *testing.T) {
|
||||
worktree, decoy, commonExclude, privateExclude := newInitExcludeRepos(t)
|
||||
t.Setenv(key, filepath.Join(decoy, ".git"))
|
||||
t.Setenv("GIT_WORK_TREE", decoy)
|
||||
// The empty-path API resolves against the current directory, which is the
|
||||
// decoy here; the probe scrubs inherited routing, so that selection comes
|
||||
// from the working directory rather than from the key set above.
|
||||
inherited, err := resolveGitExcludePath("")
|
||||
require.NoError(t, err)
|
||||
got, err := os.Stat(inherited)
|
||||
require.NoError(t, err)
|
||||
want, err := os.Stat(filepath.Join(decoy, ".git", "info", "exclude"))
|
||||
require.NoError(t, err)
|
||||
require.True(t, os.SameFile(got, want))
|
||||
added, _, err := addExcludePatterns(worktree, "# selected", []string{".beads/"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{".beads/"}, added)
|
||||
data, err := os.ReadFile(commonExclude)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "# preserved\r\n\r\n# selected\r\n.beads/\r\n", string(data))
|
||||
data, err = os.ReadFile(filepath.Join(decoy, ".git", "info", "exclude"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "# preserved\r\n", string(data))
|
||||
_, err = os.Stat(privateExclude)
|
||||
require.ErrorIs(t, err, os.ErrNotExist)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckProjectExcludeStealthReadBoundaries(t *testing.T) {
|
||||
for _, name := range []string{"directory", "directory_clean", "missing", "dangling_symlink", "patterns", "leak"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -709,8 +709,10 @@ func worktreeGitEnvKey(entry string) string {
|
|||
|
||||
// clearWorktreeGitRoutingEnv establishes the command working directory as the
|
||||
// repository-selection boundary without changing process identity or signal
|
||||
// semantics. Startup config discovery applies the same boundary to its one
|
||||
// pre-hook Git probe.
|
||||
// semantics. Startup config discovery applies the same scrub to its pre-hook
|
||||
// config-path probe only; the .beads database discovery probes in
|
||||
// internal/beads still honor inherited routing, so the two planes can resolve
|
||||
// different repositories.
|
||||
func clearWorktreeGitRoutingEnv(cmd *cobra.Command) error {
|
||||
if !hasWorktreeCommandAncestor(cmd) {
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -15,10 +15,15 @@ override discovery with `BEADS_DIR`.
|
|||
Startup *config* discovery — the `rev-parse` probe in `internal/config`'s
|
||||
`gitDirsForRepo`, which locates a linked worktree's shared `.beads` config —
|
||||
scrubs inherited Git routing variables such as `GIT_DIR` and `GIT_WORK_TREE`
|
||||
from its subprocess environment. Other startup Git probes still honor inherited
|
||||
routing, including `internal/git`'s process-cached repository context. Clearing
|
||||
those variables from the `bd` process environment applies only to `bd worktree`
|
||||
commands.
|
||||
from its subprocess environment whenever it runs. The scrub is unconditional for
|
||||
that probe, but the probe is a fallback, not a per-command step: it runs only
|
||||
when nothing earlier in startup has already resolved a config path
|
||||
(`internal/config/config.go`), so an ancestor `.beads/config.yaml` or an
|
||||
explicit `BEADS_DIR` short-circuits it. Other startup Git probes still honor
|
||||
inherited routing, including `internal/git`'s process-cached repository context
|
||||
and the `.beads` database discovery probes in `internal/beads`, so those
|
||||
variables can still select which workspace `bd` opens. Clearing those variables
|
||||
from the `bd` process environment applies only to `bd worktree` commands.
|
||||
|
||||
```
|
||||
project/
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import (
|
|||
"strings"
|
||||
|
||||
internalgit "github.com/steveyegge/beads/internal/git"
|
||||
"github.com/steveyegge/beads/internal/gitenv"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
)
|
||||
|
||||
|
|
@ -18,15 +19,22 @@ func NewGitRepository(workDir string) domain.GitRepository {
|
|||
return &gitRepositoryImpl{workDir: workDir}
|
||||
}
|
||||
|
||||
// NewInitGitRepository binds init artifact operations to the selected workDir.
|
||||
// The generic constructor retains inherited routing for its existing callers.
|
||||
func NewInitGitRepository(workDir string) domain.GitRepository {
|
||||
return &gitRepositoryImpl{workDir: workDir, env: gitenv.ScrubRouting(os.Environ())}
|
||||
}
|
||||
|
||||
type gitRepositoryImpl struct {
|
||||
workDir string
|
||||
env []string
|
||||
}
|
||||
|
||||
var _ domain.GitRepository = (*gitRepositoryImpl)(nil)
|
||||
|
||||
func (r *gitRepositoryImpl) gitCmd(ctx context.Context, args ...string) *exec.Cmd {
|
||||
cmd := exec.CommandContext(ctx, "git", args...)
|
||||
cmd.Dir = r.workDir
|
||||
cmd.Dir, cmd.Env = r.workDir, r.env
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
|
@ -98,7 +106,11 @@ func (r *gitRepositoryImpl) GetConfig(ctx context.Context, key string) (string,
|
|||
if key == "" {
|
||||
return "", false, fmt.Errorf("git: GetConfig: key must not be empty")
|
||||
}
|
||||
out, err := r.gitCmd(ctx, "config", "--get", key).Output()
|
||||
cmd := r.gitCmd(ctx, "config", "--get", key)
|
||||
if key == "beads.role" && r.env == nil {
|
||||
cmd.Env = gitenv.ScrubRouting(os.Environ())
|
||||
}
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
var exitErr *exec.ExitError
|
||||
if errors.As(err, &exitErr) {
|
||||
|
|
@ -121,7 +133,11 @@ func (r *gitRepositoryImpl) SetConfig(ctx context.Context, key, value string) er
|
|||
if key == "" {
|
||||
return fmt.Errorf("git: SetConfig: key must not be empty")
|
||||
}
|
||||
out, err := r.gitCmd(ctx, "config", key, value).CombinedOutput()
|
||||
cmd := r.gitCmd(ctx, "config", key, value)
|
||||
if key == "beads.role" && r.env == nil {
|
||||
cmd.Env = gitenv.ScrubRouting(os.Environ())
|
||||
}
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("git: SetConfig %s: %w: %s", key, err, bytes.TrimSpace(out))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,9 +5,14 @@ import (
|
|||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/gitenv"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func (s *testSuite) TestIsGitRepo_FalseOutsideRepo() {
|
||||
|
|
@ -72,7 +77,9 @@ func (s *testSuite) TestConfig_ReadFailuresAreNotMissing() {
|
|||
}{
|
||||
{"malformed_config", "beads.role", 128},
|
||||
{"invalid_key", "invalid", 1},
|
||||
{"invalid_routing_boolean", "beads.role", 128},
|
||||
// beads.role reads now scrub GIT_CONFIG* routing, so a routing poison can
|
||||
// only reach a key that is not role-scoped.
|
||||
{"invalid_routing_boolean", "test.marker", 128},
|
||||
} {
|
||||
s.Run(tc.name, func() {
|
||||
switch tc.name {
|
||||
|
|
@ -97,11 +104,21 @@ func (s *testSuite) TestConfig_ReadFailuresAreNotMissing() {
|
|||
diagnostic := strings.TrimSpace(string(exitErr.Stderr))
|
||||
s.Require().NotEmpty(diagnostic)
|
||||
s.Contains(err.Error(), diagnostic)
|
||||
if tc.name != "invalid_key" {
|
||||
if tc.name == "malformed_config" {
|
||||
_, _, roleErr := domain.NewGitUseCase(s.tmpDir, s.repo).BeadsRole(s.Ctx())
|
||||
s.Require().Error(roleErr)
|
||||
s.ErrorAs(roleErr, &exitErr)
|
||||
}
|
||||
if tc.name == "invalid_routing_boolean" {
|
||||
// The same poison that fails the read above cannot reach beads.role,
|
||||
// which resolves as absent rather than as a preserved read failure.
|
||||
role, roleFound, roleErr := s.repo.GetConfig(s.Ctx(), "beads.role")
|
||||
s.Require().NoError(roleErr)
|
||||
s.False(roleFound)
|
||||
s.Empty(role)
|
||||
_, _, useCaseErr := domain.NewGitUseCase(s.tmpDir, s.repo).BeadsRole(s.Ctx())
|
||||
s.Require().NoError(useCaseErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -288,3 +305,180 @@ func (s *testSuite) TestExec_HappensInWorkDir() {
|
|||
s.Require().NoError(err)
|
||||
s.True(info.IsDir())
|
||||
}
|
||||
|
||||
func TestRoleConfigIgnoresInheritedGitRouting(t *testing.T) {
|
||||
for _, entry := range os.Environ() {
|
||||
key := gitenv.EntryKey(entry)
|
||||
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
|
||||
t.Setenv(key, "")
|
||||
require.NoError(t, os.Unsetenv(key))
|
||||
}
|
||||
}
|
||||
home := t.TempDir()
|
||||
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
|
||||
t.Setenv(key, home)
|
||||
}
|
||||
runGit := func(t *testing.T, dir string, args ...string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ())
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoError(t, err, "fixture git %v: %s", args, out)
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, local, global, want string
|
||||
}{
|
||||
{"repository", "maintainer", "", "maintainer"},
|
||||
{"inline_config", "maintainer", "", "maintainer"},
|
||||
{"default_global", "", "contributor", "contributor"},
|
||||
{"absent", "", "", ""},
|
||||
{"literal", "custom role = exact", "", "custom role = exact"},
|
||||
{"empty", " \t ", "", ""},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
target, decoy := t.TempDir(), t.TempDir()
|
||||
for _, dir := range []string{target, decoy} {
|
||||
runGit(t, dir, "init", "--quiet")
|
||||
runGit(t, dir, "config", "--local", "core.hooksPath", ".git/hooks")
|
||||
}
|
||||
runGit(t, target, "config", "--local", "test.marker", "target")
|
||||
runGit(t, decoy, "config", "--local", "test.marker", "decoy")
|
||||
runGit(t, decoy, "config", "--local", "beads.role", "decoy-role")
|
||||
if tc.local != "" {
|
||||
runGit(t, target, "config", "--local", "beads.role", tc.local)
|
||||
}
|
||||
global := ""
|
||||
if tc.global != "" {
|
||||
global = "[beads]\n\trole = " + tc.global + "\n"
|
||||
}
|
||||
globalPath := filepath.Join(home, ".gitconfig")
|
||||
require.NoError(t, os.WriteFile(globalPath, []byte(global), 0600))
|
||||
wantGeneric, changedDir := "decoy", decoy
|
||||
if tc.name == "inline_config" {
|
||||
t.Setenv("GIT_CONFIG_COUNT", "2")
|
||||
t.Setenv("GIT_CONFIG_KEY_0", "beads.role")
|
||||
t.Setenv("GIT_CONFIG_VALUE_0", "injected-role")
|
||||
t.Setenv("GIT_CONFIG_KEY_1", "test.marker")
|
||||
t.Setenv("GIT_CONFIG_VALUE_1", "injected-marker")
|
||||
wantGeneric, changedDir = "injected-marker", target
|
||||
} else {
|
||||
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
|
||||
t.Setenv("GIT_WORK_TREE", decoy)
|
||||
}
|
||||
env := os.Environ()
|
||||
before, err := os.ReadFile(filepath.Join(decoy, ".git", "config"))
|
||||
require.NoError(t, err)
|
||||
repo := NewGitRepository(target)
|
||||
useCase := domain.NewGitUseCase(target, repo)
|
||||
got, found, err := useCase.BeadsRole(t.Context())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.want, got)
|
||||
require.Equal(t, tc.want != "", found)
|
||||
require.NoError(t, useCase.SetBeadsRole(t.Context(), "new role = exact"))
|
||||
require.Equal(t, "new role = exact", runGit(t, target, "config", "--local", "--get", "beads.role"))
|
||||
after, err := os.ReadFile(filepath.Join(decoy, ".git", "config"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(before), string(after), "role write changed decoy")
|
||||
// Ordinary config commands keep their existing inherited context.
|
||||
got, found, err = repo.GetConfig(t.Context(), "test.marker")
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
require.Equal(t, wantGeneric, got)
|
||||
require.NoError(t, repo.SetConfig(t.Context(), "test.marker", "changed"))
|
||||
require.Equal(t, "changed", runGit(t, changedDir, "config", "--local", "--get", "test.marker"))
|
||||
globalAfter, err := os.ReadFile(globalPath)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, global, string(globalAfter))
|
||||
require.True(t, slices.Equal(env, os.Environ()), "adapter changed inherited environment")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitGitRepositoryUsesSelectedDirectory(t *testing.T) {
|
||||
for _, entry := range os.Environ() {
|
||||
key := gitenv.EntryKey(entry)
|
||||
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
|
||||
t.Setenv(key, "")
|
||||
require.NoError(t, os.Unsetenv(key))
|
||||
}
|
||||
}
|
||||
home := t.TempDir()
|
||||
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
|
||||
t.Setenv(key, home)
|
||||
}
|
||||
runGit := func(dir string, args ...string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ())
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoError(t, err, "fixture git %v: %s", args, out)
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
for _, kind := range []string{"ordinary", "nested", "linked", "bare", "nonrepo", "captured_home"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
target, decoy := t.TempDir(), t.TempDir()
|
||||
runGit(decoy, "init", "--quiet")
|
||||
runGit(decoy, "config", "test.marker", "decoy")
|
||||
if kind == "bare" {
|
||||
runGit(target, "init", "--bare", "--quiet")
|
||||
} else if kind != "nonrepo" {
|
||||
runGit(target, "init", "--quiet")
|
||||
}
|
||||
if kind != "nonrepo" {
|
||||
runGit(target, "config", "test.marker", "target")
|
||||
}
|
||||
if kind == "nested" {
|
||||
target = filepath.Join(target, "nested")
|
||||
require.NoError(t, os.Mkdir(target, 0755))
|
||||
} else if kind == "linked" {
|
||||
runGit(target, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "-c", "commit.gpgSign=false", "-c", "core.hooksPath=", "commit", "--allow-empty", "-m", "seed")
|
||||
linked := filepath.Join(t.TempDir(), "linked")
|
||||
runGit(target, "-c", "core.hooksPath=", "worktree", "add", "--detach", linked)
|
||||
target = linked
|
||||
}
|
||||
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
|
||||
t.Setenv("GIT_WORK_TREE", decoy)
|
||||
t.Chdir(decoy)
|
||||
inherited := NewGitRepository(target)
|
||||
marker, found, err := inherited.GetConfig(t.Context(), "test.marker")
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
require.Equal(t, "decoy", marker, "generic constructor must retain inherited routing")
|
||||
env := os.Environ()
|
||||
selected := NewInitGitRepository(target)
|
||||
isRepo, err := selected.IsGitRepo(t.Context())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, kind != "nonrepo", isRepo)
|
||||
bare, err := selected.IsBareGitRepo(t.Context())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, kind == "bare", bare)
|
||||
marker, found, err = selected.GetConfig(t.Context(), "test.marker")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, kind != "nonrepo", found)
|
||||
if found {
|
||||
require.Equal(t, "target", marker)
|
||||
}
|
||||
require.True(t, slices.Equal(env, os.Environ()))
|
||||
if kind == "captured_home" {
|
||||
changedHome := t.TempDir()
|
||||
require.NoError(t, os.WriteFile(filepath.Join(changedHome, ".gitconfig"), []byte("[invalid\n"), 0600))
|
||||
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
|
||||
t.Setenv(key, changedHome)
|
||||
}
|
||||
role, found, err := inherited.GetConfig(t.Context(), "beads.role")
|
||||
// The generic reader runs under the caller's current environment, so the
|
||||
// broken HOME config surfaces as a preserved read failure, not absence.
|
||||
require.Error(t, err, "generic role reads still use the current caller environment")
|
||||
require.False(t, found)
|
||||
require.Empty(t, role)
|
||||
require.Error(t, inherited.SetConfig(t.Context(), "beads.role", "decoy"))
|
||||
require.NoError(t, selected.SetConfig(t.Context(), "beads.role", "contributor"))
|
||||
role, found, err = selected.GetConfig(t.Context(), "beads.role")
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
require.Equal(t, "contributor", role, "role reads and writes share the constructor's captured HOME")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue