beads/cmd/bd/prime_test.go
Okano, Osamu ef6c6e3e48
Follow up remaining runtime .beads fallbacks after GH#3124 (#3183)
* fix(workspace): align resolved workspace messaging and config lookup

intent(workspace): pure worktrees and external BEADS_DIR setups should work without implying a local .beads directory is required
decision(config): derive config repo roots from FindBeadsDir-backed workspace resolution instead of a local-only .beads walk
constraint(workspace-detection): keep FindBeadsDir ordering and storage behavior unchanged while making bd where the primary diagnostic hint
learned(testing): shared-server env and global .beads ignore rules can distort CGO suites, so regression coverage now normalizes those test paths

* fix(bootstrap): align no-workspace JSON wording

intent(bootstrap): machine-readable no-workspace output should match the resolved-workspace guidance used elsewhere on this branch
decision(bootstrap-json): reuse the shared workspace error helpers through a dedicated payload builder so tests can lock the JSON contract
constraint(review-loop): keep the bootstrap CLI flow unchanged outside the no-workspace JSON branch while adding a focused regression test

* fix(where): allow no-workspace diagnostics without db (beads-9f74-5l1)

intent(where): no-workspace guidance should point to a command that actually runs when workspace resolution fails
decision(startup): treat top-level where as a no-db command so it reaches its own handler before database preflight
constraint(where-tests): subprocess mode can change the exact hint text, so the regression test locks the JSON contract and stable guidance fragments instead

* fix(bootstrap): restore bd where guidance for no-workspace output (beads-9f74-3c3)

intent(bootstrap): no-workspace bootstrap guidance should match the resolved-workspace diagnostics introduced on this branch
decision(no-workspace-hints): reuse the shared hint that mentions bd where instead of the bootstrap-specific fallback text
constraint(bootstrap-tests): cover both the payload helper and subprocess CLI path so wording regressions are caught before release

* fix(workspace): remove no-workspace .beads fallbacks (beads-9f74-gr1)

intent(workspace-resolution): finish the GH#3124 follow-up for runtime paths that still fabricated local .beads state
rejected(no-workspace-fallback): inventing ./ .beads paths outside an active workspace hid shared-worktree resolution and created stray files
decision(setup-recipes): keep built-in bd setup recipes usable without a workspace but require an active workspace for custom recipe state
constraint(worktree-support): completion and backup helpers still need to resolve shared main-repo workspaces from a git worktree

* fix(config): skip no-workspace store init for store-free commands

intent(config): review-fix-loop found no-workspace config commands should reach their own graceful paths instead of failing in PersistentPreRun
decision(config-preflight): detect store-free config subcommands before DB synthesis so config.yaml, git-backed, and diagnostic flows can run without an opened store
constraint(json-contract): keep bd config validate --json machine-readable on stdout once pre-run stops short-circuiting into low-level DB errors
learned(config-preflight): the parent config command not being in noDbCommands leaked store init into show, validate, drift, apply, and yaml-only config helpers

* fix(ci): restore init prefix normalization and formatting

intent(ci): clear the current PR failures instead of leaving the branch blocked behind known red checks

decision(init-prefix): normalize dotted prefixes before persisting issue_prefix so config, metadata.json, and Dolt database naming stay aligned for Julia-style repos
constraint(fmt-check): CI runs gofmt over the whole repo, so the existing spacing drift in internal/jira/tracker_test.go had to be cleaned up on this branch to get a green run
learned(ci): the latest main CI was already red on the same formatting file and the same embedded shard, so rebasing surfaced pre-existing blockers rather than introducing a new shard-only regression
2026-04-10 21:23:14 -07:00

264 lines
8.1 KiB
Go

package main
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
)
func TestOutputContextFunction(t *testing.T) {
tests := []struct {
name string
mcpMode bool
stealthMode bool
ephemeralMode bool
localOnlyMode bool
expectText []string
rejectText []string
}{
{
name: "CLI Normal (non-ephemeral)",
mcpMode: false,
stealthMode: false,
ephemeralMode: false,
localOnlyMode: false,
expectText: []string{"Beads Workflow Context", "bd dolt push", "git push"},
rejectText: []string{"bd export", "--from-main"},
},
{
name: "CLI Normal (ephemeral)",
mcpMode: false,
stealthMode: false,
ephemeralMode: true,
localOnlyMode: false,
expectText: []string{"Beads Workflow Context", "bd dolt pull", "ephemeral branch"},
rejectText: []string{"bd export", "git push", "--from-main"},
},
{
name: "CLI Stealth",
mcpMode: false,
stealthMode: true,
ephemeralMode: false, // stealth mode overrides ephemeral detection
localOnlyMode: false,
expectText: []string{"Beads Workflow Context", "bd close"},
rejectText: []string{"git push", "git pull", "git commit", "git status", "git add", "bd export"},
},
{
name: "CLI Local-only (no git remote)",
mcpMode: false,
stealthMode: false,
ephemeralMode: false,
localOnlyMode: true,
expectText: []string{"Beads Workflow Context", "bd close", "No git remote configured"},
rejectText: []string{"git push", "git pull", "--from-main", "bd export"},
},
{
name: "CLI Local-only overrides ephemeral",
mcpMode: false,
stealthMode: false,
ephemeralMode: true, // ephemeral is true but local-only takes precedence
localOnlyMode: true,
expectText: []string{"Beads Workflow Context", "bd close", "No git remote configured"},
rejectText: []string{"git push", "--from-main", "ephemeral branch", "bd export"},
},
{
name: "CLI Stealth overrides local-only",
mcpMode: false,
stealthMode: true,
ephemeralMode: false,
localOnlyMode: true, // local-only is true but stealth takes precedence
expectText: []string{"Beads Workflow Context", "bd close"},
rejectText: []string{"git push", "git pull", "git commit", "git status", "git add", "No git remote configured", "bd export"},
},
{
name: "MCP Normal (non-ephemeral)",
mcpMode: true,
stealthMode: false,
ephemeralMode: false,
localOnlyMode: false,
expectText: []string{"Beads Issue Tracker Active", "git push"},
rejectText: []string{"bd export", "--from-main"},
},
{
name: "MCP Normal (ephemeral)",
mcpMode: true,
stealthMode: false,
ephemeralMode: true,
localOnlyMode: false,
expectText: []string{"Beads Issue Tracker Active", "ephemeral branch"},
rejectText: []string{"bd export", "git push", "--from-main"},
},
{
name: "MCP Stealth",
mcpMode: true,
stealthMode: true,
ephemeralMode: false, // stealth mode overrides ephemeral detection
localOnlyMode: false,
expectText: []string{"Beads Issue Tracker Active", "bd close"},
rejectText: []string{"git push", "git pull", "git commit", "git status", "git add", "bd export"},
},
{
name: "MCP Local-only (no git remote)",
mcpMode: true,
stealthMode: false,
ephemeralMode: false,
localOnlyMode: true,
expectText: []string{"Beads Issue Tracker Active", "bd close"},
rejectText: []string{"git push", "git pull", "--from-main", "bd export"},
},
{
name: "MCP Local-only overrides ephemeral",
mcpMode: true,
stealthMode: false,
ephemeralMode: true, // ephemeral is true but local-only takes precedence
localOnlyMode: true,
expectText: []string{"Beads Issue Tracker Active", "bd close"},
rejectText: []string{"git push", "--from-main", "ephemeral branch", "bd export"},
},
{
name: "MCP Stealth overrides local-only",
mcpMode: true,
stealthMode: true,
ephemeralMode: false,
localOnlyMode: true, // local-only is true but stealth takes precedence
expectText: []string{"Beads Issue Tracker Active", "bd close"},
rejectText: []string{"git push", "git pull", "git commit", "git status", "git add", "bd export"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
defer stubIsEphemeralBranch(tt.ephemeralMode)()
defer stubPrimeHasGitRemote(!tt.localOnlyMode)() // localOnly = !primeHasGitRemote
var buf bytes.Buffer
err := outputPrimeContext(&buf, tt.mcpMode, tt.stealthMode)
if err != nil {
t.Fatalf("outputPrimeContext failed: %v", err)
}
output := buf.String()
for _, expected := range tt.expectText {
if !strings.Contains(output, expected) {
t.Errorf("Expected text not found: %s", expected)
}
}
for _, rejected := range tt.rejectText {
if strings.Contains(output, rejected) {
t.Errorf("Unexpected text found: %s", rejected)
}
}
})
}
}
func TestPrimeClaimGuidanceUsesAtomicClaim(t *testing.T) {
defer stubIsEphemeralBranch(false)()
defer stubPrimeHasGitRemote(true)()
var buf bytes.Buffer
if err := outputPrimeContext(&buf, false, false); err != nil {
t.Fatalf("outputPrimeContext failed: %v", err)
}
output := buf.String()
if !strings.Contains(output, "bd update <id> --claim") {
t.Fatal("prime output should teach bd update <id> --claim")
}
if strings.Contains(output, "bd update <id> --status=in_progress") {
t.Fatal("prime output should not teach bd update <id> --status=in_progress")
}
}
func TestPrimeContextUsesWorkspaceLanguage(t *testing.T) {
defer stubIsEphemeralBranch(false)()
defer stubPrimeHasGitRemote(true)()
var buf bytes.Buffer
if err := outputPrimeContext(&buf, false, false); err != nil {
t.Fatalf("outputPrimeContext failed: %v", err)
}
output := buf.String()
if !strings.Contains(output, "resolved") || !strings.Contains(output, "workspace") {
t.Fatalf("prime output should describe resolved workspace semantics: %s", output)
}
if strings.Contains(output, "when .beads/ detected") {
t.Fatal("prime output should not imply local .beads detection is required")
}
}
// stubIsEphemeralBranch temporarily replaces isEphemeralBranch
// with a stub returning returnValue.
//
// Returns a function to restore the original isEphemeralBranch.
// Usage:
//
// defer stubIsEphemeralBranch(true)()
func stubIsEphemeralBranch(isEphem bool) func() {
original := isEphemeralBranch
isEphemeralBranch = func() bool {
return isEphem
}
return func() {
isEphemeralBranch = original
}
}
// stubPrimeHasGitRemote temporarily replaces primeHasGitRemote
// with a stub returning returnValue.
//
// Returns a function to restore the original primeHasGitRemote.
// Usage:
//
// defer stubPrimeHasGitRemote(true)()
func stubPrimeHasGitRemote(hasRemote bool) func() {
original := primeHasGitRemote
primeHasGitRemote = func() bool {
return hasRemote
}
return func() {
primeHasGitRemote = original
}
}
func TestPrimeGlobalFallback(t *testing.T) {
// Create a temp directory to act as config dir
tmpDir := t.TempDir()
beadsConfigDir := filepath.Join(tmpDir, "beads")
if err := os.MkdirAll(beadsConfigDir, 0755); err != nil {
t.Fatalf("mkdir: %v", err)
}
content := "# Global PRIME override\nCustom instructions here.\n"
if err := os.WriteFile(filepath.Join(beadsConfigDir, "PRIME.md"), []byte(content), 0644); err != nil {
t.Fatalf("write PRIME.md: %v", err)
}
// Call the helper that resolves the global prime path
got := resolveGlobalPrimePath(tmpDir)
if got == "" {
t.Fatal("resolveGlobalPrimePath returned empty, want path to global PRIME.md")
}
data, err := os.ReadFile(got)
if err != nil {
t.Fatalf("ReadFile(%s): %v", got, err)
}
if string(data) != content {
t.Errorf("content = %q, want %q", string(data), content)
}
}
func TestPrimeGlobalFallback_Missing(t *testing.T) {
// When no global PRIME.md exists, should return empty string
tmpDir := t.TempDir()
got := resolveGlobalPrimePath(tmpDir)
if got != "" {
t.Errorf("resolveGlobalPrimePath = %q, want empty for missing file", got)
}
}