* 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>
412 lines
16 KiB
Go
412 lines
16 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/steveyegge/beads/cmd/bd/doctor"
|
|
"github.com/steveyegge/beads/internal/config"
|
|
"github.com/steveyegge/beads/internal/gitenv"
|
|
"github.com/steveyegge/beads/internal/gitignore"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
)
|
|
|
|
// setupStealthMode configures git settings for stealth operation.
|
|
// Only configures git-level invisibility (.git/info/exclude).
|
|
// Tool-specific setup (Claude, Cursor, etc.) is handled by `bd setup <tool>`.
|
|
// Uses .git/info/exclude (per-repository) instead of global gitignore because:
|
|
// - Global gitignore doesn't support absolute paths (GitHub #704)
|
|
// - .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 := 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")
|
|
}
|
|
} else {
|
|
return fmt.Errorf("failed to setup git exclude: %w", err)
|
|
}
|
|
}
|
|
|
|
if verbose {
|
|
fmt.Printf("\n%s Stealth mode configured successfully!\n\n", ui.RenderPass("✓"))
|
|
fmt.Printf(" Git exclude: %s\n", ui.RenderAccent(".git/info/exclude configured"))
|
|
fmt.Printf("\nYour beads setup is now %s - other repo collaborators won't see any beads-related files.\n", ui.RenderAccent("invisible"))
|
|
fmt.Printf("To set up a specific AI tool, run: %s\n\n", ui.RenderAccent("bd setup <claude|cursor|aider|...> --stealth"))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// setupGitExclude configures .git/info/exclude to ignore beads and claude files
|
|
// 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 {
|
|
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 {
|
|
return err
|
|
}
|
|
if verbose {
|
|
if len(added) == 0 {
|
|
fmt.Printf("Git exclude already configured for stealth mode\n")
|
|
} else {
|
|
fmt.Printf("Configured git exclude for stealth mode: %s\n", excludePath)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// resolveGitExcludePath returns the path to .git/info/exclude for repoPath, using --git-common-dir
|
|
// so worktrees resolve to the main repo's exclude file (GH#1053). An empty repoPath resolves
|
|
// against the current directory.
|
|
//
|
|
// The probe scrubs inherited Git routing so the exclude file always belongs to repoPath (or the
|
|
// current directory) rather than to an inherited GIT_DIR. The fork detector that gates the fork
|
|
// caller is scrubbed the same way, and a split between the two halves appends beads patterns to an
|
|
// unrelated repository's exclude file.
|
|
func resolveGitExcludePath(repoPath string) (string, error) {
|
|
args := make([]string, 0, 3)
|
|
if repoPath != "" {
|
|
args = append(args, "-C", repoPath)
|
|
}
|
|
args = append(args, "rev-parse", "--git-common-dir")
|
|
// #nosec G702 - fixed "git" command; args are constant subcommands plus an internal repoPath,
|
|
// never attacker-controlled input.
|
|
probe := exec.Command("git", args...)
|
|
probe.Env = gitenv.ScrubRouting(os.Environ())
|
|
out, err := probe.Output()
|
|
if err != nil {
|
|
// "not a git repository" stays the prefix: setupStealthMode matches it with
|
|
// strings.Contains to treat this as a skip rather than a failure. Because the probe
|
|
// deliberately ignores inherited routing, the operator needs to be told so — and
|
|
// git's own reason ("not a git repository (or any of the parent directories)",
|
|
// dubious ownership) is what distinguishes the cases. exec.ExitError.Error() is only
|
|
// "exit status 128"; Output() leaves that reason unread in ExitError.Stderr.
|
|
var exitErr *exec.ExitError
|
|
if errors.As(err, &exitErr) {
|
|
if detail := firstNonEmptyLine(string(exitErr.Stderr)); detail != "" {
|
|
return "", fmt.Errorf("not a git repository (inherited Git routing is ignored here): %s", detail)
|
|
}
|
|
}
|
|
return "", fmt.Errorf("not a git repository (inherited Git routing is ignored here): %w", err)
|
|
}
|
|
gitDir := strings.TrimSpace(string(out))
|
|
// git prints --git-common-dir relative to its working directory (repoPath when -C is used), so
|
|
// anchor relative results back to repoPath.
|
|
if !filepath.IsAbs(gitDir) {
|
|
base := repoPath
|
|
if base == "" {
|
|
base = "."
|
|
}
|
|
gitDir = filepath.Join(base, gitDir)
|
|
}
|
|
return filepath.Join(gitDir, "info", "exclude"), nil
|
|
}
|
|
|
|
// addExcludePatterns ensures each pattern exists as an exact line in repoPath's .git/info/exclude,
|
|
// appending any missing ones under header. It returns the patterns it actually added (empty when all
|
|
// were already present) and the resolved exclude path. repoPath "" resolves against the current
|
|
// directory. This is the shared core for stealth, fork, and project-pattern exclude setup.
|
|
func addExcludePatterns(repoPath, header string, patterns []string) (added []string, excludePath string, err error) {
|
|
excludePath, err = resolveGitExcludePath(repoPath)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
|
|
if err = os.MkdirAll(filepath.Dir(excludePath), 0755); err != nil {
|
|
return nil, "", fmt.Errorf("failed to create git info directory: %w", err)
|
|
}
|
|
|
|
var existing string
|
|
var content []byte
|
|
// #nosec G304 - git config path
|
|
if readContent, rerr := os.ReadFile(excludePath); rerr == nil {
|
|
content = readContent
|
|
existing = string(content)
|
|
} else if !os.IsNotExist(rerr) {
|
|
return nil, excludePath, fmt.Errorf("failed to read git exclude file: %w", rerr)
|
|
}
|
|
|
|
for _, p := range patterns {
|
|
// Exact line match avoids false positives (e.g. ".beads/issues.jsonl" matching ".beads/").
|
|
if !containsExactPattern(existing, p) {
|
|
added = append(added, p)
|
|
}
|
|
}
|
|
if len(added) == 0 {
|
|
return nil, excludePath, nil
|
|
}
|
|
|
|
lines := []string{header}
|
|
if len(content) > 0 {
|
|
lines = []string{"", header}
|
|
}
|
|
newContent := gitignore.AppendLines(content, append(lines, added...))
|
|
|
|
// #nosec G306 - config file needs 0644
|
|
if err = os.WriteFile(excludePath, newContent, 0644); err != nil {
|
|
return nil, excludePath, fmt.Errorf("failed to write git exclude file: %w", err)
|
|
}
|
|
return added, excludePath, nil
|
|
}
|
|
|
|
// projectExcludeHeader labels the project-root ignore patterns (.dolt/, *.db, …) that beads routes
|
|
// into .git/info/exclude instead of a tracked .gitignore when git ops are disabled. It is kept
|
|
// neutral (not "added by bd init --stealth") because both bd init --stealth and bd doctor --fix
|
|
// write it.
|
|
const projectExcludeHeader = "# Beads: Dolt files kept local via .git/info/exclude (stealth / no-git-ops)"
|
|
|
|
// addProjectPatternsToGitExclude appends project-root ignore patterns (.dolt/, *.db, etc.) to
|
|
// .git/info/exclude rather than a tracked .gitignore. Stealth / no-git-ops repos use this so beads
|
|
// never creates or modifies a visible .gitignore that would expose its presence to repo
|
|
// collaborators. repoPath is the repository root ("" resolves against the current directory).
|
|
func addProjectPatternsToGitExclude(repoPath string, patterns []string, verbose bool) error {
|
|
added, excludePath, err := addExcludePatterns(repoPath, projectExcludeHeader, patterns)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if verbose {
|
|
if len(added) == 0 {
|
|
fmt.Printf("Git exclude already has Dolt file patterns\n")
|
|
} else {
|
|
fmt.Printf("Configured git exclude for Dolt files: %s\n", excludePath)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// removeBeadsProjectGitignoreSection strips the bd-managed section from the tracked project-root
|
|
// .gitignore at repoPath, reversing doctor.EnsureProjectGitignore. It removes only the header beads
|
|
// writes (doctor.ProjectGitignoreHeader) plus the Dolt pattern lines beads added directly beneath
|
|
// it, so unrelated user patterns are preserved. If beads was the .gitignore's only content the file
|
|
// is removed entirely, restoring true stealth. Returns true when it changed (or removed) the file;
|
|
// a repo with no beads section (or no .gitignore) is left untouched.
|
|
func removeBeadsProjectGitignoreSection(repoPath string) (bool, error) {
|
|
gitignorePath := filepath.Join(repoPath, ".gitignore")
|
|
// #nosec G304 - path is the repo-root .gitignore
|
|
content, err := os.ReadFile(gitignorePath)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return false, nil
|
|
}
|
|
return false, fmt.Errorf("failed to read .gitignore: %w", err)
|
|
}
|
|
|
|
managed := make(map[string]bool, len(doctor.ProjectGitignorePatterns))
|
|
for _, p := range doctor.ProjectGitignorePatterns {
|
|
managed[p] = true
|
|
}
|
|
|
|
lines := strings.Split(string(content), "\n")
|
|
out := make([]string, 0, len(lines))
|
|
changed := false
|
|
for i := 0; i < len(lines); i++ {
|
|
if strings.TrimSpace(lines[i]) == doctor.ProjectGitignoreHeader {
|
|
changed = true
|
|
// Drop the blank separator beads writes before the header, if we just emitted one.
|
|
if n := len(out); n > 0 && strings.TrimSpace(out[n-1]) == "" {
|
|
out = out[:n-1]
|
|
}
|
|
// Skip the header and the bd-managed pattern lines directly beneath it.
|
|
i++
|
|
for i < len(lines) && managed[strings.TrimSpace(lines[i])] {
|
|
i++
|
|
}
|
|
i-- // compensate for the loop's i++
|
|
continue
|
|
}
|
|
out = append(out, lines[i])
|
|
}
|
|
if !changed {
|
|
return false, nil
|
|
}
|
|
|
|
newContent := strings.Join(out, "\n")
|
|
if strings.TrimSpace(newContent) == "" {
|
|
// beads was the only reason this .gitignore existed — remove it for true stealth.
|
|
if err := os.Remove(gitignorePath); err != nil {
|
|
return false, fmt.Errorf("failed to remove emptied .gitignore: %w", err)
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
// #nosec G306 - gitignore needs to be readable by git and collaborators
|
|
if err := os.WriteFile(gitignorePath, []byte(newContent), 0644); err != nil {
|
|
return false, fmt.Errorf("failed to write .gitignore: %w", err)
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
// isStealthRepo reports whether beads must keep its footprint out of tracked git files for the
|
|
// workspace at repoPath. It keys off the persisted no-git-ops flag — the same signal bd prime uses
|
|
// for the stealth session-close protocol (GH#593). bd init --stealth sets it, and a user may also
|
|
// set it directly; either way beads routes ignores into .git/info/exclude rather than a tracked
|
|
// .gitignore.
|
|
func isStealthRepo(repoPath string) bool {
|
|
beadsDir := doctor.ResolveBeadsDirForRepo(repoPath)
|
|
return config.GetStringFromDir(beadsDir, "no-git-ops") == "true"
|
|
}
|
|
|
|
// trackedGitignoreHasBeadsSection reports whether the tracked project-root .gitignore at repoPath
|
|
// still carries the bd-managed section header — i.e. a previous run leaked Dolt patterns into a
|
|
// git-visible file. Used by the stealth doctor check to flag the leak for --fix to clean up.
|
|
func trackedGitignoreHasBeadsSection(repoPath string) bool {
|
|
// #nosec G304 - path is the repo-root .gitignore
|
|
content, err := os.ReadFile(filepath.Join(repoPath, ".gitignore"))
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return containsExactPattern(string(content), doctor.ProjectGitignoreHeader)
|
|
}
|
|
|
|
// checkProjectExcludeStealth is the stealth-mode counterpart to doctor.CheckProjectGitignore: it
|
|
// verifies the project-root ignore patterns live in .git/info/exclude instead of a tracked
|
|
// .gitignore. Reusing the "Project Gitignore" name keeps the --fix dispatch and ordering stable.
|
|
func checkProjectExcludeStealth(repoPath string) doctor.DoctorCheck {
|
|
excludePath, err := resolveGitExcludePath(repoPath)
|
|
if err != nil {
|
|
return doctor.DoctorCheck{
|
|
Name: "Project Gitignore",
|
|
Status: doctor.StatusOK,
|
|
Message: "N/A (not a git repository)",
|
|
}
|
|
}
|
|
|
|
var content string
|
|
// #nosec G304 - git config path
|
|
if data, err := os.ReadFile(excludePath); err == nil {
|
|
content = string(data)
|
|
} else if !os.IsNotExist(err) {
|
|
check := doctor.DoctorCheck{
|
|
Name: "Project Gitignore",
|
|
Status: doctor.StatusWarning,
|
|
Message: "Unable to read .git/info/exclude",
|
|
Detail: err.Error(),
|
|
}
|
|
if trackedGitignoreHasBeadsSection(repoPath) {
|
|
// The leak is the privacy failure, and --fix strips it from the tracked
|
|
// .gitignore whether or not the exclude can be read (doctor_fix.go runs both
|
|
// halves), so it stays the headline and keeps its actionable Fix.
|
|
check.Message = "Stealth mode: Dolt patterns are exposed in the tracked .gitignore"
|
|
check.Detail += "; tracked .gitignore also contains the beads section"
|
|
check.Fix = "Run: bd doctor --fix"
|
|
}
|
|
return check
|
|
}
|
|
|
|
var missing []string
|
|
for _, p := range doctor.ProjectGitignorePatterns {
|
|
if !containsExactPattern(content, p) {
|
|
missing = append(missing, p)
|
|
}
|
|
}
|
|
|
|
leaked := trackedGitignoreHasBeadsSection(repoPath)
|
|
|
|
if len(missing) > 0 || leaked {
|
|
var details []string
|
|
message := "Stealth mode: .git/info/exclude missing Dolt exclusion patterns"
|
|
if len(missing) > 0 {
|
|
details = append(details, "Missing from .git/info/exclude: "+strings.Join(missing, ", "))
|
|
}
|
|
if leaked {
|
|
// A previous run leaked the patterns into the tracked .gitignore; --fix moves them out.
|
|
message = "Stealth mode: Dolt patterns are exposed in the tracked .gitignore"
|
|
details = append(details, "Tracked .gitignore contains the beads section; bd doctor --fix will move it into .git/info/exclude")
|
|
}
|
|
return doctor.DoctorCheck{
|
|
Name: "Project Gitignore",
|
|
Status: doctor.StatusWarning,
|
|
Message: message,
|
|
Detail: strings.Join(details, "; "),
|
|
Fix: "Run: bd doctor --fix",
|
|
}
|
|
}
|
|
return doctor.DoctorCheck{
|
|
Name: "Project Gitignore",
|
|
Status: doctor.StatusOK,
|
|
Message: "Dolt and credential files excluded via .git/info/exclude (stealth)",
|
|
}
|
|
}
|
|
|
|
// setupForkExclude configures .git/info/exclude for fork workflows (GH#742)
|
|
// Adds beads files and Claude artifacts to keep PRs to upstream clean.
|
|
// 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 {
|
|
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 {
|
|
return err
|
|
}
|
|
if verbose {
|
|
if len(added) == 0 {
|
|
fmt.Printf("%s Git exclude already configured\n", ui.RenderPass("✓"))
|
|
} else {
|
|
fmt.Printf("\n%s Added to .git/info/exclude:\n", ui.RenderPass("✓"))
|
|
for _, p := range added {
|
|
fmt.Printf(" %s\n", p)
|
|
}
|
|
fmt.Println("\nNote: .git/info/exclude is local-only and won't affect upstream.")
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// containsExactPattern checks if content contains the pattern as an exact line
|
|
// This avoids false positives like ".beads/issues.jsonl" matching ".beads/"
|
|
func containsExactPattern(content, pattern string) bool {
|
|
for _, line := range strings.Split(content, "\n") {
|
|
if strings.TrimSpace(line) == pattern {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// promptForkExclude asks if user wants to configure .git/info/exclude for fork workflow (GH#742)
|
|
func promptForkExclude(upstreamURL string, quiet bool) (bool, error) {
|
|
if quiet {
|
|
return false, nil // Don't prompt in quiet mode
|
|
}
|
|
|
|
fmt.Printf("\n%s Detected fork (upstream: %s)\n\n", ui.RenderAccent("▶"), upstreamURL)
|
|
fmt.Println("Would you like to configure .git/info/exclude to keep beads files local?")
|
|
fmt.Println("This prevents beads from appearing in PRs to upstream.")
|
|
fmt.Print("\n[Y/n]: ")
|
|
|
|
reader := bufio.NewReader(os.Stdin)
|
|
response, err := readLineWithContext(getRootContext(), reader, os.Stdin)
|
|
if err != nil {
|
|
if isCanceled(err) {
|
|
return false, err
|
|
}
|
|
response = ""
|
|
}
|
|
response = strings.TrimSpace(strings.ToLower(response))
|
|
|
|
// Default to yes (empty or "y" or "yes")
|
|
return response == "" || response == "y" || response == "yes", nil
|
|
}
|