* fix(init): refuse to initialize directly in the home directory
`bd init` in a directory that isn't a git repo (and has no explicit
BEADS_DIR) unconditionally `git init`s the directory, writes agent
scaffolding (CLAUDE.md, AGENTS.md, .gitignore, .agents/, .codex/,
.claude/settings.json), and commits — with no confirmation. Run in the
home directory this silently turns $HOME into a git repository and can
clobber an existing ~/CLAUDE.md. It's worse under --non-interactive
(auto-engaged whenever stdin isn't a TTY, i.e. whenever an agent runs
`bd init`): all of it happens with zero prompt (GH#4635).
Refuse the init when the current directory is the user's home directory
and it isn't already a git repo (and no explicit BEADS_DIR was given),
with a clear error pointing at the alternatives (cd into a project, or
set BEADS_DIR). The common fresh-project flow (mkdir proj && cd proj &&
bd init) and already-git-tracked homes are unaffected.
The guard runs as the first statement in init's RunE, ahead of every
path that has an effect. Position is the whole fix: --reinit-local /
--force reach countExistingIssues, which opens a real store (creating
the data directory, able to run migrations), and --proxied-server
dispatches to runInitProxiedServer -> EnsureGitRepo, i.e. a `git init`
in the current directory. Both run long before the point where a guard
placed with the rest of the path validation would fire.
Home is resolved from the OS account database (user.Current) in
preference to $HOME, so the guard keys off the real account home even
when $HOME is repointed — which this repo's own tests do constantly.
Both sources are best-effort: a CGO-free build's user.Current() falls
back to os.UserHomeDir() (i.e. $HOME on Unix) when the account is absent
from the passwd database, so this is a preference, not a guarantee of
$HOME-independence. Mirrors the home resolution in internal/beads'
isPathInSafeBoundary.
Tests: TestIsUserHomeDir and TestGuardInitInHomeDir cover the decision
(resolver stubbed, so the real home is never touched);
TestInitCommand_RefusesInHomeDirBeforeAnySideEffect runs the actual
command for plain / --reinit-local / --force / --proxied-server and
asserts not just the refusal but that nothing — .git, .beads, CLAUDE.md,
AGENTS.md, .gitignore, .agents, .codex, .claude — exists afterwards.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(init): key the home guard on caller intent, and give it a named exit code
Three blocking items, two reviewers converging on the first.
1. The guard read os.Getenv("BEADS_DIR") as "the user explicitly opted in".
It is not. Cobra's root PersistentPreRunE runs before RunE and, for a
no-DB command like init, resolves a beads dir and exports it
(selectedNoDBBeadsDir -> prepareSelectedNoDBContext ->
prepareSelectedCommandContext). That resolution bottoms out in
beads.FindBeadsDir(), which accepts any ancestor .beads/ for which
hasBeadsProjectFiles is true - and a config.yaml alone is enough. That is
the shape of this project's own legacy user-level ~/.beads/config.yaml,
so anyone carrying it got BEADS_DIR set for them and the guard failed
open. `bd -C <dir> init` opened the same hole, and that one does not even
move the working directory the scaffolding lands in.
The damage is not self-cancelling. The `git init` half is separately
gated on the same env so it stayed skipped, but the agent scaffolding is
not gated at all: addAgentsInstructions, InstallClaudeProject,
InstallCodexProject and InstallCursorProject all write relative to CWD.
So the bypass still clobbered ~/CLAUDE.md, ~/AGENTS.md and
~/.claude/settings.json - the files the guard exists to protect.
beadsDirFromCaller captures BEADS_DIR as the process INHERITED it, at
package initialization, which the language guarantees runs before main
and therefore before any bd code exports one of its own. The guard
consults that snapshot, so the question it asks is "did the caller name a
beads dir", not "does the process env happen to have one".
2. The refusal skipped all three of init's refusal conventions.
ExitHomeDirRefused = 13 joins 10/11/12, the message is printed and the
error carries only the code (the ExitLocalExistsRefused pattern), and
docs/recovery/init-safety.md gains an init-home-refused anchor - TOC
entry, symptom, why, three recovery paths, and the script-branching
snippet - which the message points at. `bd help init-safety` lists it.
NOT added: a cmd/bd/protocol case. That corpus states that §E3 freezes
10/11/12/130 and that a new stable code requires a spec revision, so
asserting 13 there would be claiming wire status the spec has not
granted. The constant plus the docs anchor give the refusal the same
in-repo scriptability without that claim; say the word if the spec should
be revised and I will add the corpus case too.
3. CHANGELOG [Unreleased] entry, citing #4635 and stating the scope limits.
Also from review: the message's BEADS_DIR escape hatch said "set BEADS_DIR
if you really mean to initialize here", which is not what happens - an
explicit BEADS_DIR makes hasExplicitBeadsDir true, skipping the git init and
the CWD-local .beads. It now says so.
Test coverage answers the point both reviewers made about the RunE-only
tests. TestInitThroughRootCmd_RefusesInHomeDirWithDiscoveredBeadsDir runs
through rootCmd.Execute, in a home carrying only .beads/config.yaml, and
asserts the precondition (pre-run really does discover it) before asserting
the refusal and that no scaffolding landed. --backend names a backend that
cannot exist as a circuit breaker, so a future fail-open stops there instead
of building a store in someone's home directory. Against the old code it
reproduces maphew's observation verbatim:
init ran past the home guard and got as far as backend selection:
unknown backend "review4795-home-guard-sentinel"
plus a unit case pinning that a bd-exported BEADS_DIR is not caller opt-in.
Reported-by: maphew, bee-ghosttrack
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(init): harden the home-dir guard (opt-out, git probe, exit 15)
Maintainer fixup on top of #4795 by harry-miller-trimble, for the three
majors and three of the minors from the adopt-pr review, the major, the
minor and the nit from its second round, and two of the minors from its
third. The contributor's commits are unchanged.
The BEADS_DIR opt-out still set up $HOME (major). The refusal said
`BEADS_DIR=<path>/.beads bd init` writes nothing in the home directory,
but an explicit BEADS_DIR only skips the git init. The agent files
(CLAUDE.md, AGENTS.md, .claude/, .codex/, .cursor/, .agents/) are
written relative to the working directory whatever BEADS_DIR says, and a
BEADS_DIR under $HOME counts as local, so ~/.gitignore was appended to
as well. guardInitInHomeDir now returns keepHomeClean for that case.
RunE forces skipAgents, which the proxied route also reads from its
input, and both routes gate the project .gitignore on keepHomeClean.
Init prints a note saying so, with a `bd setup <recipe> --global`
pointer for anyone who wanted an integration everywhere.
The refusal text, the CHANGELOG entry and the recovery playbook now say
what the opt-out does: it sets up only the named workspace, after a
`mkdir -p`, because init refuses a BEADS_DIR whose parent does not
exist. They no longer say nothing else is written, because Dolt and
metrics keep their own state under $HOME. The refusal's Why also stops
saying init overwrites existing files: it installs into them, and in
$HOME those are user-wide agent settings.
TestInitInUntrackedHomeWithCallerBeadsDir_SetsUpOnlyTheWorkspace runs
the direct route end to end against a Dolt server, once with the
workspace outside the home and once under it. Every seeded file must
come out unchanged, with nothing added. The proxied route's agent-file
and .gitignore gates are not covered by a test: there is no in-process
proxied init fixture to drive them.
The tracked-home probe trusted git's routing environment (major).
isGitRepo() is a plain `git rev-parse --git-dir`, so an inherited
GIT_DIR, or a home that only sits inside an enclosing work tree, stood
the guard down. Init's own git-init decision scrubs that environment,
then runs git init in the home and installs agent files into it. The
guard now asks isGitWorkTreeRoot(cwd), which runs
`rev-parse --show-toplevel` through initArtifactGitCommand and matches
the result against the home itself. Two new subtests pin both false
positives. Each asserts that isGitRepo() still reports true, so the
subtests keep reproducing the old probe.
Exit 13 was already taken (major). It is ExitGuardMismatch, "racer won,
skip gracefully", and 14 is ExitMigrationFrozen, so a wrapper branching
on exit codes would read this refusal as a benign skip. The refusal now
exits 15. The change is in init_safety.go, `bd help init-safety`,
ADR 0002, the playbook and the CHANGELOG. ADR 0002 also notes that 15
sits outside the protocol v0 §E3 freeze pinned in
cmd/bd/protocol/exit_codes_init_test.go.
The opt-out still set up a repository around the home (second round,
major). The tracked-home probe sends a home that only sits inside an
enclosing work tree, such as a dotfiles or monorepo checkout above it,
to the BEADS_DIR opt-out. Git finds that repository from the home, so
init set it up as the project: core.hooksPath, beads.role, fork routing
and the fork exclude, its origin as the workspace's Dolt remote, and a
bootstrap commit. That commit staged the home's legacy ~/.beads and then
whatever agent files the home holds, ~/.codex/auth.json among them, and
committed them with --no-verify. The proxied route did the same from its
tail.
keepHomeClean now also means "outside every repository". It is only
true when the home is not a work-tree root, so no repository git finds
from there is the home's own. On the direct route, RunE forces skipHooks
beside skipAgents; projectRoleRepo holds the six isInitRoleGitRepo
gates (the role prompt and pins, the GH#2950 safety net, fork routing,
the fork exclude) to keepHomeClean; and both origin-as-remote gates, the
bootstrap commit and the upstream advice are gated on it. On the proxied
route, the tail's isRepo probe, which gates the role, the fork exclude,
the commit and the upstream advice, and resolveProxiedInitRemoteURL are
gated on it; skipHooks reaches the tail through its input. What a flag
asks for still happens: --stealth and --setup-exclude write their
exclude, and an explicit --remote or a configured sync remote is still
used. The note, the refusal text, the CHANGELOG entry and the playbook
say what the opt-out leaves alone. Gating the commit also drops the
"skipped bootstrap commit" note the opt-out printed from an untracked
home.
Tests for it:
- The end-to-end test gains home_inside_a_repository. The home sits in
a repository with one commit and an origin, and holds a legacy
~/.beads; init runs without --quiet. The repository must keep its one
commit, nothing staged and its .git/config byte for byte (so no
core.hooksPath or beads.role). The workspace must not take its origin
as its Dolt remote, and init must print the note and no upstream
advice. The repository has no upstream remote, because fork routing
would create ~/.beads-planning under the suite's real HOME.
- TestProxiedInitTailKeepHomeCleanLeavesEnclosingRepoAlone runs the
proxied tail from a home inside a repository with an origin and an
upstream, so the fork exclude would fire. It requires no fork
exclude, no commit, nothing staged and the same .git/config.
- TestProxiedInitRemoteURLUsesSelectedProject gains a keep_home_clean
row (the origin is not used) and a configured_keep_home_clean row (a
configured remote still is).
- The guard's enclosing-repository subtest also checks that a caller
BEADS_DIR there returns keepHomeClean.
Second-round minor and nit:
- beadsDirFromCaller's comment and the playbook say why a BEADS_DIR read
from a .beads/.env does not count as the caller's, although
beadsDirProvidedAtStartup counts it for role detection. From the home
that file is the legacy ~/.beads/.env, so counting it would let the
same discovered ~/.beads opt out of the guard.
- The guard tests use t.Chdir, and the hand-rolled chdir helper is gone.
Validation: the init, home-guard and proxied-init tests pass against
the Dolt test container, as do the embedded init lane and the
proxied-server init integration tests. Mutation checks:
- Dropping the forced skipAgents fails both workspace subtests.
- Dropping the .gitignore gate fails the under-home subtest.
- Restoring the plain isGitRepo() probe fails both new false-positive
subtests.
- Disabling the guard fails every refusal test at the sentinel backend.
- Second round: dropping the forced skipHooks, the projectRoleRepo
gate, the commit gate, the late origin gate, the upstream advice gate
or the note each fails home_inside_a_repository on its own check.
Dropping the proxied tail's gate fails the tail test, and dropping the
proxied remote gate fails the keep_home_clean row. The third round
pins the early origin gate (below).
Third-round minors:
- The early origin gate picks the remote the early remote-safety check
probes, and a failed probe counts as Dolt history. The end-to-end
test gains unreachable_origin_reinit_local and
unreachable_origin_force: the home sits in a repository whose origin
path holds nothing, and init runs with --reinit-local or with --force.
Both must succeed and leave the repository as it was. Dropping the
early gate makes init probe that origin and refuse both rows with
exit 10.
- The playbook, the CHANGELOG entry and guardInitInHomeDir's comment
name the flags that still change the repository around the home:
--stealth and --setup-exclude write its .git/info/exclude, and the
interactive --contributor and --team wizards work in it (beads.role,
and possibly a sync branch). The opt-out's note is unchanged: none of
those writes is on its list.
Left for a follow-up:
- The proxied route's .gitignore gate is still unpinned. It needs an
in-process proxied init fixture, or the
`useLocalBeads && beadsDirIsLocal && !keepHomeClean` predicate pulled
out into a table-tested helper.
- Both routes still record the enclosing repository's origin-derived
repo_id, and its clone_id, on an opt-out workspace. That predates this
PR for every explicit-BEADS_DIR init and writes nothing to the
repository; skipping it is a behavior change of its own.
Third-round validation: the home-guard, init-tail and proxied-remote
tests pass in a hermetic env -i run against the Dolt 2.2.0 CI pin (41
tests and subtests, none skipped). Dropping !keepHomeClean from the
early origin gate fails both new rows with exit 10 and leaves the other
three rows passing. go vet, gofmt, the docsync test and the doc
freshness check pass.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Harry Miller <harry_miller@trimble.com>
---------
Co-authored-by: Harry Miller <harry_miller@trimble.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
711 lines
26 KiB
Go
711 lines
26 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"github.com/steveyegge/beads/internal/beads"
|
|
"github.com/steveyegge/beads/internal/config"
|
|
"github.com/steveyegge/beads/internal/configfile"
|
|
"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"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
"github.com/steveyegge/beads/internal/workapi"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
type initProxiedServerInput struct {
|
|
prefix string
|
|
database string
|
|
roleFlag string
|
|
initRemote string
|
|
initRemoteChanged bool
|
|
destroyToken string
|
|
serverConfigPath string
|
|
serverLogPath string
|
|
serverRootPath string
|
|
serverProxyPort int
|
|
serverProxyIdleTimeout time.Duration
|
|
externalConfig *configfile.ExternalDoltConfig
|
|
quiet bool
|
|
stealth bool
|
|
skipHooks bool
|
|
skipAgents bool
|
|
keepHomeClean bool // see guardInitInHomeDir
|
|
reinitLocal bool
|
|
contributor bool
|
|
team bool
|
|
teamServer bool
|
|
fromJSONL bool
|
|
nonInteractive bool
|
|
}
|
|
|
|
func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxiedServerInput) error {
|
|
if in.fromJSONL {
|
|
return fmt.Errorf("--from-jsonl is not supported with --proxied-server")
|
|
}
|
|
if in.contributor {
|
|
return fmt.Errorf("--contributor is not supported with --proxied-server")
|
|
}
|
|
if in.team {
|
|
return fmt.Errorf("--team is not supported with --proxied-server")
|
|
}
|
|
|
|
// Preflight the external dolt binary before any .beads/ write below
|
|
// (checkExistingBeadsData onward). This only applies to managed
|
|
// proxied-server mode (in.externalConfig == nil): external mode talks
|
|
// to a remote/pre-existing dolt sql-server over the network and never
|
|
// spawns a local dolt binary, so it has nothing to preflight here.
|
|
// Failing here means a missing/broken dolt produces a clean preflight
|
|
// error instead of a half-initialized .beads/ directory from a later
|
|
// failure in newManagedProxiedServerUOWProvider.
|
|
//
|
|
// Shares resolveAndProbeDolt (uow_factory.go) with
|
|
// newManagedProxiedServerUOWProvider, which this same `bd init
|
|
// --proxied-server` invocation goes on to call a few lines below via
|
|
// newProxiedServerUOWProvider: the shared doltVersionWarnOnce means the
|
|
// version advisory prints at most once for the command, not once per
|
|
// call site.
|
|
if in.externalConfig == nil {
|
|
// in.quiet, not the global quietFlag: init's local --quiet shadows
|
|
// the persistent flag, so the global is false under `bd init -q`.
|
|
if _, err := resolveAndProbeDolt(ctx, "bd init --proxied-server", in.quiet || quietFlag); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
if err := config.Initialize(); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to initialize config: %v\n", err)
|
|
}
|
|
|
|
if err := checkExistingBeadsData(in.prefix); err != nil {
|
|
return err
|
|
}
|
|
|
|
cwd, err := os.Getwd()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get current directory: %v", err)
|
|
}
|
|
|
|
fsProvider := fs.NewFileSystemProvider(cwd, newBeadsDirTemplates(), newInitFileSystemAdapters(cwd))
|
|
fsUseCase := fsProvider.BeadsDirFSUseCase()
|
|
gitUC := git.NewGitProvider(cwd).GitUseCase()
|
|
|
|
if in.stealth {
|
|
if err := fsUseCase.SetupStealthMode(ctx, !in.quiet); err != nil {
|
|
return fmt.Errorf("setting up stealth mode: %v", err)
|
|
}
|
|
in.skipHooks = true
|
|
}
|
|
|
|
prefix, err := resolveInitPrefix(in.prefix)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
proxiedInit, err := fsUseCase.ResolveProxiedInit(ctx, domain.ResolveProxiedInitParams{
|
|
Prefix: prefix,
|
|
DBFlag: in.database,
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("resolving proxied init: %v", err)
|
|
}
|
|
beadsDir, hasExplicitBeadsDir := proxiedInit.BeadsDir, proxiedInit.HasExplicit
|
|
dbName, projectID := proxiedInit.DBName, proxiedInit.ProjectID
|
|
beadsDirIsLocal := proxiedInit.IsLocal
|
|
useLocalBeads := !hasExplicitBeadsDir || beadsDirIsLocal
|
|
|
|
if in.teamServer && proxiedInit.DBNameDerived {
|
|
return fmt.Errorf(
|
|
"--team-server requires --database (or an existing .beads/metadata.json naming the database): bd cannot guess the name of the bts-provisioned database (guessed %q from the prefix)",
|
|
dbName)
|
|
}
|
|
|
|
if strings.Contains(filepath.Clean(cwd), string(filepath.Separator)+".beads"+string(filepath.Separator)) ||
|
|
strings.HasSuffix(filepath.Clean(cwd), string(filepath.Separator)+".beads") {
|
|
return fmt.Errorf("cannot initialize bd inside a .beads directory\nCurrent directory: %s", cwd)
|
|
}
|
|
|
|
if !hasExplicitBeadsDir {
|
|
// Bootstrap routing is handled separately in follow-up #6460.
|
|
res, err := gitUC.EnsureGitRepo(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to initialize git repository: %v", err)
|
|
}
|
|
if res.DidInit && !in.quiet {
|
|
fmt.Printf(" %s Initialized git repository\n", ui.RenderPass("✓"))
|
|
}
|
|
}
|
|
|
|
metadataBody, err := composeProxiedServerMetadataJSON(proxiedMetadataInputs{
|
|
dbName: dbName,
|
|
projectID: projectID,
|
|
teamServer: in.teamServer,
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("composing metadata.json: %v", err)
|
|
}
|
|
configYAMLBody := renderInitConfigYAML("", false)
|
|
|
|
clientInfo, err := buildProxiedServerClientInfo(in.serverRootPath, in.serverConfigPath, in.serverLogPath, in.serverProxyPort, in.serverProxyIdleTimeout, in.externalConfig)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
fsParams := domain.InitializeBeadsDirParams{
|
|
MetadataJSONBody: metadataBody,
|
|
ConfigYAMLBody: configYAMLBody,
|
|
ProxiedServerClientInfo: clientInfo,
|
|
SetNoCOW: true,
|
|
WriteProjectGitignore: useLocalBeads && beadsDirIsLocal && !in.keepHomeClean,
|
|
}
|
|
if useLocalBeads {
|
|
fsParams.LocalVersion = Version
|
|
}
|
|
|
|
fsResult, err := fsUseCase.InitializeBeadsDir(ctx, fsParams)
|
|
if err != nil {
|
|
return fmt.Errorf("initializing .beads directory: %v", err)
|
|
}
|
|
if fsResult.NoCOWErr != nil && !in.quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to set FS_NOCOW_FL on %s: %v\n", beadsDir, fsResult.NoCOWErr)
|
|
}
|
|
if fsResult.LocalVersionErr != nil && !in.quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to initialize version tracking: %v\n", fsResult.LocalVersionErr)
|
|
}
|
|
|
|
initUOWProvider, err := newProxiedServerUOWProviderAdopting(ctx, beadsDir, "")
|
|
if err != nil {
|
|
return fmt.Errorf("failed to open uow provider: %v", err)
|
|
}
|
|
defer func() { _ = initUOWProvider.Close(ctx) }()
|
|
|
|
remoteURL := resolveProxiedInitRemoteURL(ctx, cwd, in)
|
|
|
|
// Unlike the origin lookup above, ComputeRepoID and GetCloneID still inherit
|
|
// Git routing: under an inherited GIT_DIR/GIT_WORK_TREE, repo_id and clone_id
|
|
// can describe a different repository than remoteURL, or fail to resolve.
|
|
var repoID, cloneID string
|
|
if id, err := beads.ComputeRepoID(); err == nil {
|
|
repoID = id
|
|
} else if !in.quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: could not compute repository ID: %v\n", err)
|
|
}
|
|
if id, err := beads.GetCloneID(); err == nil {
|
|
cloneID = id
|
|
} else if !in.quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: could not compute clone ID: %v\n", err)
|
|
}
|
|
|
|
// The order is VERIFY, then bootstrap or adopt: Bootstrapper REFUSES an
|
|
// already-identified substrate, and asking first is how a front door tells a
|
|
// re-init from the collision that guard exists for.
|
|
verifier, err := proxiedInitVerifier(initUOWProvider)
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
adoptedPrefix, adoptedProjectID := prefix, projectID
|
|
if in.teamServer {
|
|
// bts owns the shared database: adopt identity and write nothing — no
|
|
// identity, no tracking metadata (repo_id/clone_id are per-clone
|
|
// fingerprints; last-init-wins overwrites feed false cross-project
|
|
// mismatch diagnostics), no Dolt remote.
|
|
adoptedPrefix, adoptedProjectID, err = adoptTeamServerIdentity(ctx, verifier, dbName, prefix, in.prefix != "", projectID)
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
} else {
|
|
existing, err := verifier.VerifyIdentity(ctx, issueops.VerifyIdentityRequest{})
|
|
if err != nil {
|
|
return HandleError("reading project identity from database %q: %v", dbName, err)
|
|
}
|
|
switch {
|
|
case existing.Prefix != "" || existing.ProjectID != "":
|
|
// Another rig — or an earlier init — already identified this
|
|
// database. ADOPT it: this route used to rewrite the prefix and the
|
|
// project id every time, which renamed the ids a co-tenant was
|
|
// about to mint.
|
|
adoptedPrefix, adoptedProjectID = existing.Prefix, existing.ProjectID
|
|
if !in.quiet {
|
|
fmt.Printf(" %s Adopted project identity from existing database\n", ui.RenderPass("✓"))
|
|
}
|
|
default:
|
|
bootstrapper, err := proxiedBootstrapper(initUOWProvider)
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
result, err := bootstrapper.Bootstrap(ctx, issueops.BootstrapRequest{
|
|
Prefix: prefix,
|
|
ProjectID: projectID,
|
|
})
|
|
if err != nil {
|
|
return HandleError("bootstrap project: %v", err)
|
|
}
|
|
adoptedPrefix, adoptedProjectID = result.Prefix, result.ProjectID
|
|
}
|
|
|
|
// The per-clone tracking state is written on EVERY init, adopt or not,
|
|
// which is why it is not on the role: a fresh clone of an
|
|
// already-identified database needs its own fingerprints precisely
|
|
// because it bootstrapped nothing.
|
|
if err := recordProxiedInitTrackingState(ctx, initUOWProvider, repoID, cloneID); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
// The Dolt remote is configured SEPARATELY from the identity, the way
|
|
// the direct route has always configured it: folding them into one call
|
|
// is what let a remote that could not be created fail a bootstrap that
|
|
// had already succeeded.
|
|
if remoteURL != "" {
|
|
if err := configureProxiedInitDoltRemote(ctx, initUOWProvider, remoteURL); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// metadata.json was written with a locally-minted project id before any
|
|
// DB connection existed; the adopted id must replace it before the tail
|
|
// git-commits .beads/.
|
|
if in.teamServer && adoptedProjectID != projectID {
|
|
fileCfg, err := configfile.Load(beadsDir)
|
|
if err != nil || fileCfg == nil {
|
|
return HandleError("failed to reload %s to adopt the provisioned project identity: %v", configfile.ConfigFileName, err)
|
|
}
|
|
fileCfg.ProjectID = adoptedProjectID
|
|
if err := fileCfg.Save(beadsDir); err != nil {
|
|
return HandleError("failed to save the provisioned project identity to %s: %v", configfile.ConfigFileName, err)
|
|
}
|
|
}
|
|
|
|
return runInitProxiedServerTail(cmd, ctx, in, runInitTailContext{
|
|
workDir: cwd,
|
|
beadsDir: beadsDir,
|
|
prefix: adoptedPrefix,
|
|
dbName: dbName,
|
|
useLocalBeads: useLocalBeads,
|
|
remoteURL: remoteURL,
|
|
fsUseCase: fsUseCase,
|
|
gitUC: gitUC,
|
|
})
|
|
}
|
|
|
|
func resolveInitPrefix(flagPrefix string) (string, error) {
|
|
prefix := flagPrefix
|
|
if prefix == "" {
|
|
prefix = config.GetString("issue-prefix")
|
|
}
|
|
if prefix == "" {
|
|
cwd, err := os.Getwd()
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to get current directory: %v", err)
|
|
}
|
|
prefix = filepath.Base(cwd)
|
|
}
|
|
prefix = strings.TrimLeft(prefix, ".")
|
|
prefix = strings.TrimRight(prefix, "-")
|
|
prefix = strings.ReplaceAll(prefix, ".", "_")
|
|
if len(prefix) > 0 && !((prefix[0] >= 'a' && prefix[0] <= 'z') || (prefix[0] >= 'A' && prefix[0] <= 'Z') || prefix[0] == '_') {
|
|
prefix = "bd_" + prefix
|
|
}
|
|
return prefix, nil
|
|
}
|
|
|
|
func resolveProxiedInitRemoteURL(ctx context.Context, workDir string, in initProxiedServerInput) string {
|
|
url, source := resolveInitConfiguredSyncRemote(in.initRemote, in.initRemoteChanged, resolveSyncRemote)
|
|
if url != "" {
|
|
return url
|
|
}
|
|
if source != initSyncRemoteNone {
|
|
return ""
|
|
}
|
|
// Under keepHomeClean the repository around the home is not the project's,
|
|
// so its origin is not this workspace's remote (see guardInitInHomeDir).
|
|
if !in.stealth && !in.keepHomeClean {
|
|
// Origin belongs to the selected project, independently of Beads storage.
|
|
gitUC := domain.NewGitUseCase(workDir, domaingit.NewInitGitRepository(workDir))
|
|
if originURL, err := gitUC.OriginRemoteURL(ctx); err == nil && originURL != "" {
|
|
return normalizeRemoteURL(originURL)
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// proxiedInitVerifier and proxiedBootstrapper hand back the two identity
|
|
// surfaces through the provider's own capability accessors.
|
|
//
|
|
// They are asked for SEPARATELY, and team-server mode is what that separation
|
|
// is for: it holds a verifier and never obtains a bootstrapper, so the path bd
|
|
// must not write on cannot reach the write.
|
|
func proxiedInitVerifier(provider uow.UnitOfWorkProvider) (issueops.InitVerifier, error) {
|
|
src, ok := provider.(uow.InitVerifierSource)
|
|
if !ok {
|
|
return nil, fmt.Errorf("proxied-server provider %T does not offer the identity-read surface", provider)
|
|
}
|
|
return src.InitVerifier()
|
|
}
|
|
|
|
func proxiedBootstrapper(provider uow.UnitOfWorkProvider) (issueops.Bootstrapper, error) {
|
|
src, ok := provider.(uow.BootstrapperSource)
|
|
if !ok {
|
|
return nil, fmt.Errorf("proxied-server provider %T does not offer the identity-seeding surface", provider)
|
|
}
|
|
return src.Bootstrapper()
|
|
}
|
|
|
|
// recordProxiedInitTrackingState seeds the per-clone bookkeeping: the
|
|
// repository and clone fingerprints, the synced-at marker and the recorded
|
|
// binary version.
|
|
//
|
|
// It is separate from the identity because its LIFETIME is: the identity is
|
|
// written once and then adopted forever, while these four describe the clone
|
|
// running init and are refreshed every time it runs. In the refusable one-time
|
|
// write, a re-init on a shared database would silently stop recording them.
|
|
func recordProxiedInitTrackingState(ctx context.Context, provider uow.UnitOfWorkProvider, repoID, cloneID string) error {
|
|
return uow.RunTx(ctx, provider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) {
|
|
cfg := uw.ConfigUseCase()
|
|
// An absent fingerprint is recorded as nothing rather than as "": an
|
|
// empty row reads back to cross-project verification as a clone whose
|
|
// fingerprint failed to compute.
|
|
if repoID != "" {
|
|
if err := cfg.SetMetadata(ctx, "repo_id", repoID); err != nil {
|
|
return "", fmt.Errorf("record repo_id: %w", err)
|
|
}
|
|
}
|
|
if cloneID != "" {
|
|
if err := cfg.SetMetadata(ctx, "clone_id", cloneID); err != nil {
|
|
return "", fmt.Errorf("record clone_id: %w", err)
|
|
}
|
|
}
|
|
if err := cfg.SetMetadata(ctx, "last_import_time", time.Now().UTC().Format(time.RFC3339)); err != nil {
|
|
return "", fmt.Errorf("record last_import_time: %w", err)
|
|
}
|
|
if err := cfg.SetLocalMetadata(ctx, workapi.MetadataKeyVersion, Version); err != nil {
|
|
return "", fmt.Errorf("record bd_version: %w", err)
|
|
}
|
|
return "bd init", nil
|
|
})
|
|
}
|
|
|
|
// configureProxiedInitDoltRemote adds the sync remote, skipping a name that is
|
|
// already taken.
|
|
func configureProxiedInitDoltRemote(ctx context.Context, provider uow.UnitOfWorkProvider, remoteURL string) error {
|
|
return uow.RunTx(ctx, provider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) {
|
|
remotes, err := uw.DoltRemoteUseCase().ListRemotes(ctx)
|
|
if err != nil {
|
|
return "", fmt.Errorf("list remotes: %w", err)
|
|
}
|
|
for _, r := range remotes {
|
|
if r.Name == "origin" {
|
|
return "", nil
|
|
}
|
|
}
|
|
if err := uw.DoltRemoteUseCase().CreateRemote(ctx, "origin", remoteURL); err != nil {
|
|
return "", fmt.Errorf("create remote origin: %w", err)
|
|
}
|
|
return "", nil
|
|
})
|
|
}
|
|
|
|
// adoptTeamServerIdentity reads the bts-provisioned identity out of the shared
|
|
// database, following the gateway contract: adopt if present, hard error if
|
|
// absent — bd never writes identity in team-server mode.
|
|
//
|
|
// ABSENT means "unprovisioned, tell them to run bts init" and UNREADABLE means
|
|
// "the connection failed, say so"; keeping those apart is the InitVerifier
|
|
// role's promise. The two markers arrive as ONE snapshot, so the prefix and the
|
|
// project id cannot come from either side of a concurrent write.
|
|
func adoptTeamServerIdentity(ctx context.Context, verifier issueops.InitVerifier, dbName, localPrefix string, prefixIsExplicit bool, localProjectID string) (prefix, projectID string, err error) {
|
|
identity, readErr := verifier.VerifyIdentity(ctx, issueops.VerifyIdentityRequest{})
|
|
if _, err := resolveInitIssuePrefix(true, identity.Prefix, dbName, localPrefix, readErr); err != nil {
|
|
if readErr == nil {
|
|
return "", "", fmt.Errorf(
|
|
"database %q has no project identity (config.issue_prefix) — provision it with 'bts init' (or heal an older bts database with 'bts migrate')",
|
|
dbName)
|
|
}
|
|
return "", "", err
|
|
}
|
|
// An explicit --prefix that disagrees must not be silently ignored; a
|
|
// merely derived prefix adopts silently.
|
|
if prefixIsExplicit && identity.Prefix != localPrefix {
|
|
return "", "", fmt.Errorf(
|
|
"--prefix %q conflicts with issue_prefix %q provisioned in database %q; omit --prefix to adopt the provisioned one",
|
|
localPrefix, identity.Prefix, dbName)
|
|
}
|
|
|
|
adoptedID, _, err := resolveInitProjectID(true, localProjectID, identity.ProjectID, dbName, readErr)
|
|
if err != nil {
|
|
if readErr == nil {
|
|
return "", "", fmt.Errorf(
|
|
"database %q has no project identity (metadata._project_id) — provision it with 'bts init' (or heal an older bts database with 'bts migrate')",
|
|
dbName)
|
|
}
|
|
return "", "", err
|
|
}
|
|
return identity.Prefix, adoptedID, nil
|
|
}
|
|
|
|
type proxiedMetadataInputs struct {
|
|
dbName string
|
|
projectID string
|
|
teamServer bool
|
|
}
|
|
|
|
func composeProxiedServerMetadataJSON(in proxiedMetadataInputs) ([]byte, error) {
|
|
cfg := configfile.DefaultConfig()
|
|
cfg.Backend = configfile.BackendDolt
|
|
cfg.Database = "dolt"
|
|
cfg.DoltDatabase = in.dbName
|
|
cfg.DoltMode = configfile.DoltModeProxiedServer
|
|
cfg.ProjectID = in.projectID
|
|
cfg.DoltTeamServer = in.teamServer
|
|
|
|
if filepath.IsAbs(cfg.DoltDataDir) {
|
|
cfg.DoltDataDir = ""
|
|
}
|
|
|
|
return json.MarshalIndent(cfg, "", " ")
|
|
}
|
|
|
|
func buildProxiedServerClientInfo(rootPath, configPath, logPath string, port int, idleTimeout time.Duration, external *configfile.ExternalDoltConfig) (*configfile.ProxiedServerClientInfo, error) {
|
|
if rootPath == "" && configPath == "" && logPath == "" && port == 0 && idleTimeout == 0 && external == nil {
|
|
return nil, nil
|
|
}
|
|
clean := func(p string) (string, error) {
|
|
if p == "" {
|
|
return "", nil
|
|
}
|
|
if !filepath.IsAbs(p) {
|
|
return "", fmt.Errorf("buildProxiedServerClientInfo: path %q is not absolute", p)
|
|
}
|
|
return filepath.Clean(p), nil
|
|
}
|
|
rootAbs, err := clean(rootPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
configAbs, err := clean(configPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
logAbs, err := clean(logPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if external != nil {
|
|
if err := external.Validate(); err != nil {
|
|
return nil, fmt.Errorf("buildProxiedServerClientInfo: %w", err)
|
|
}
|
|
}
|
|
return &configfile.ProxiedServerClientInfo{
|
|
RootPath: rootAbs,
|
|
ConfigPath: configAbs,
|
|
LogPath: logAbs,
|
|
Port: port,
|
|
IdleTimeout: idleTimeout,
|
|
External: external,
|
|
}, nil
|
|
}
|
|
|
|
type runInitTailContext struct {
|
|
workDir string
|
|
beadsDir string
|
|
prefix string
|
|
dbName string
|
|
useLocalBeads bool
|
|
remoteURL string
|
|
fsUseCase domain.BeadsDirFSUseCase
|
|
gitUC domain.GitUseCase
|
|
}
|
|
|
|
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.
|
|
// NewInitGitRepository runs `git rev-parse --git-dir` with Dir=workDir and
|
|
// scrubbed routing, so dropping discovery ceilings can select a containing
|
|
// parent repository, matching the role adapter's scrubbed reads and writes.
|
|
gitUC = domain.NewGitUseCase(t.workDir, domaingit.NewInitGitRepository(t.workDir))
|
|
}
|
|
// One probe answers both the role gate and the artifact gates: gitUC is the
|
|
// scrubbed selected-directory repository whenever workDir is set, and the
|
|
// supplied use case otherwise, so a separate role probe could only repeat it.
|
|
// Under keepHomeClean the repository it can find encloses the home instead
|
|
// of holding the project, so the tail treats the home as outside every
|
|
// repository: no role, no fork exclude, no upstream advice and no bootstrap
|
|
// commit, which would stage the legacy ~/.beads and the home's agent files
|
|
// into it (see guardInitInHomeDir). RunE sets skipHooks for the same case,
|
|
// which also covers a colocated jj repository.
|
|
isRepo := !in.keepHomeClean && gitUC.IsGitRepo(ctx)
|
|
|
|
if isRepo {
|
|
role := in.roleFlag
|
|
if role == "" {
|
|
role = "maintainer"
|
|
}
|
|
_, hasRole, _ := gitUC.BeadsRole(ctx)
|
|
if !hasRole || in.roleFlag != "" {
|
|
if err := gitUC.SetBeadsRole(ctx, role); err != nil && !in.quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role: %v\n", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
setupExclude, _ := cmd.Flags().GetBool("setup-exclude")
|
|
if setupExclude {
|
|
if err := t.fsUseCase.SetupForkExclude(ctx, !in.quiet); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err)
|
|
}
|
|
} else if !in.stealth && isRepo {
|
|
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)
|
|
}
|
|
} else {
|
|
shouldExclude, err := promptForkExclude(upstreamURL, in.quiet)
|
|
if err != nil && isCanceled(err) {
|
|
fmt.Fprintln(os.Stderr, "Setup canceled.")
|
|
return errCanceled()
|
|
}
|
|
if shouldExclude {
|
|
if err := t.fsUseCase.SetupForkExclude(ctx, !in.quiet); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if !in.skipHooks {
|
|
isJJ := gitUC.IsJujutsuRepo(ctx)
|
|
isColocated := gitUC.IsColocatedJJGit(ctx)
|
|
switch {
|
|
case isJJ && !isColocated:
|
|
// The install arm below took over the hook-status gate that used to
|
|
// wrap this whole switch. Keep it here too, or a pure-JJ repo with
|
|
// current hooks starts re-printing the alias hint on every init.
|
|
if !in.quiet && (!hooksInstalled() || hooksNeedUpdate()) {
|
|
printJJAliasInstructions()
|
|
}
|
|
case isColocated || isRepo:
|
|
// Resolve only an eligible Git branch, never skip/pure-JJ/nonrepo paths.
|
|
hookFS, hooks, err := withInitHooks(t.fsUseCase, t.workDir, t.beadsDir)
|
|
if err != nil {
|
|
if !in.quiet {
|
|
fmt.Fprintf(os.Stderr, "\n%s Failed to resolve git hooks: %v\n", ui.RenderWarn("⚠"), err)
|
|
}
|
|
} else if !hooks.installed() || hooks.needsUpdate() {
|
|
if hooks.installed() && !in.quiet {
|
|
fmt.Printf(" Updating hooks to version %s...\n", Version)
|
|
}
|
|
if isColocated {
|
|
if err := hookFS.InstallJJHooks(ctx); err != nil && !in.quiet {
|
|
fmt.Fprintf(os.Stderr, "\n%s Failed to install jj hooks: %v\n", ui.RenderWarn("⚠"), err)
|
|
} else if !in.quiet {
|
|
fmt.Printf(" Hooks installed (jujutsu mode - no staging)\n")
|
|
}
|
|
} else {
|
|
hooksParams := domain.HooksInstallParams{HookNames: managedHookNames, BeadsHooks: true}
|
|
if err := hookFS.InstallGitHooks(ctx, hooksParams); err != nil && !in.quiet {
|
|
fmt.Fprintf(os.Stderr, "\n%s Failed to install git hooks to .beads/hooks/: %v\n", ui.RenderWarn("⚠"), err)
|
|
} else if !in.quiet {
|
|
fmt.Printf(" Hooks installed to: .beads/hooks/\n")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if !in.stealth && !in.skipAgents {
|
|
agentsTemplate, _ := cmd.Flags().GetString("agents-template")
|
|
agentsProfileStr, _ := cmd.Flags().GetString("agents-profile")
|
|
agentsFile, _ := cmd.Flags().GetString("agents-file")
|
|
if agentsFile != "" {
|
|
if err := config.ValidateAgentsFile(agentsFile); err != nil {
|
|
return HandleError("invalid --agents-file: %v", err)
|
|
}
|
|
if err := t.fsUseCase.SetYAMLConfig(ctx, "agents.file", agentsFile); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to persist agents.file to config: %v\n", err)
|
|
}
|
|
}
|
|
resolvedAgentsFile := agentsFile
|
|
if resolvedAgentsFile == "" {
|
|
resolvedAgentsFile = config.SafeAgentsFile()
|
|
}
|
|
isBare := gitUC.IsBareGitRepo(ctx)
|
|
if isBare {
|
|
if !in.quiet {
|
|
fmt.Printf(" Skipping %s generation in bare repository\n", resolvedAgentsFile)
|
|
}
|
|
} else {
|
|
_ = t.fsUseCase.AddAgentsInstructions(ctx, domain.AgentsFileParams{
|
|
File: resolvedAgentsFile,
|
|
Verbose: !in.quiet,
|
|
TemplatePath: agentsTemplate,
|
|
Profile: agentsProfileStr,
|
|
HasRemote: t.remoteURL != "",
|
|
NoPush: config.GetBool("no-push"),
|
|
})
|
|
// As in direct init: --quiet drops the installer's progress,
|
|
// a failure still reaches stderr.
|
|
if err := t.fsUseCase.InstallClaudeProject(ctx, in.stealth, in.quiet); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to setup Claude hooks: %v\n", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
if !in.stealth && isRepo && t.useLocalBeads {
|
|
commitResult, err := gitUC.CommitInitArtifacts(ctx, domain.CommitInitArtifactsParams{
|
|
BeadsDir: ".beads/",
|
|
OptionalPaths: []string{
|
|
config.SafeAgentsFile(),
|
|
filepath.Join(".claude", "settings.json"),
|
|
"CLAUDE.md",
|
|
".gitignore",
|
|
},
|
|
Message: "bd init: initialize beads issue tracking",
|
|
NoVerify: true,
|
|
SkipHooks: true,
|
|
})
|
|
switch {
|
|
case err != nil && !in.quiet:
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to commit beads files: %v\n", err)
|
|
case err == nil && commitResult.DidCommit && !in.quiet:
|
|
fmt.Printf(" %s Committed beads files to git\n", ui.RenderPass("✓"))
|
|
}
|
|
}
|
|
|
|
if isRepo && !in.quiet {
|
|
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>"))
|
|
}
|
|
if !in.stealth && !in.initRemoteChanged && t.remoteURL == "" {
|
|
printInitNoDoltRemoteWarning(false)
|
|
}
|
|
}
|
|
|
|
if in.quiet {
|
|
return nil
|
|
}
|
|
fmt.Printf("\n%s bd initialized successfully!\n\n", ui.RenderPass("✓"))
|
|
fmt.Printf(" Backend: %s\n", ui.RenderAccent(configfile.BackendDolt))
|
|
fmt.Printf(" Mode: %s\n", ui.RenderAccent("proxied-server"))
|
|
fmt.Printf(" Database: %s\n", ui.RenderAccent(t.dbName))
|
|
fmt.Printf(" Issue prefix: %s\n", ui.RenderAccent(t.prefix))
|
|
fmt.Printf(" Issues will be named: %s\n\n", ui.RenderAccent(t.prefix+"-<hash> (e.g., "+t.prefix+"-a3f2dd)"))
|
|
fmt.Printf("Run %s to get started.\n\n", ui.RenderAccent("bd quickstart"))
|
|
return nil
|
|
}
|