Commit graph

34 commits

Author SHA1 Message Date
ecuthiell
beed11c7f4
fix(init): use selected hook context in embedded initialization (#6464)
* 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

* fix(hooks): isolate tracked-file guard from Git routing (saa-cgh.98)

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

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

* fix(hooks): retain legitimate inherited tracking context (saa-cgh.98)

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

* test(hooks): isolate trusted global configuration fixture (saa-cgh.98)

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

* docs(hooks): explain conservative tracked-file guard (saa-cgh.98)

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

* refactor(git): resolve hooks paths in an explicit read-only context (saa-cgh.109.17.1)

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

* Bind init hook operations to the selected repository (saa-cgh.109.17)

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

* Give the hooks tail fixture an explicit remote context (saa-cgh.109.17)

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

* test(git): canonicalize the hooks fixture repository root (saa-cgh.109.17.1)

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

* fix(init): complete selected hook options and alias handling (saa-cgh.120)

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

* Clarify hooks resolver ownership and preserve work-tree diagnostics (saa-cgh.120)

Agent-Signature: Codex-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): keep embedded hook setup in the selected project (saa-cgh.120.12)

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

* fix(init,config): maintainer fixup for #6464

Pre-review CI repair:
- Annotate #nosec G702 on the selected hooks-path git invocation. No shell
  is involved, every path is passed as its own argv element, and both values
  reach that line absolute via resolveInitHooksContext.

Review iteration 1, blocking:
- internal/config: give the secret-config guard the inherited-env fallback
  that the structurally identical hook guard in cmd/bd/hooks.go already has.
  isGitTracked is the fail-open half of "refuse to write a secret key into a
  git-tracked config.yaml", and the scrub alone narrowed it to upward
  discovery from the config file's directory: under a detached work tree
  (GIT_DIR + GIT_WORK_TREE with no in-tree .git) the probe reported
  "untracked" and the secret was written into the tracked file. Probe the
  scrubbed environment first so inherited routing cannot hide a tracked
  file, then the inherited one; either probe reporting the path as tracked
  refuses the write. Adds the legitimate-routing subtest that the
  poisoned-routing matrix could not express.
- cmd/bd/config.go: the new comment claimed "All role commands ignore
  inherited Git routing". Only the writers were hardened -
  routing.DetectUserRole, beads.RepoContext.Role, `bd config show` and
  `bd doctor` still resolve beads.role through the inherited environment, so
  `bd config get beads.role` and `bd config show` can disagree under one
  environment. Narrow the comment to the four verbs it covers; widening the
  boundary to the readers is a separate change.

Review iteration 1, non-blocking:
- cmd/bd/worktree_cmd.go: disclose that ClearRouting unsets the variables on
  the bd process itself, and state what clearing the discovery-scope
  controls does to repository selection. The comment previously claimed the
  opposite of what the init path's own note admits.
- cmd/bd/init_proxied_server.go: drop isRoleGitRepo. With workDir set, gitUC
  is NewInitGitRepository(workDir), whose IsGitRepo runs the same
  `git rev-parse --git-dir` with the same Dir and scrubbed env; with workDir
  empty the helper returned its fallback. It was isRepo in both arms, plus a
  second git subprocess per `bd init --proxied`.
- cmd/bd/doctor/gitignore.go: omit the leading blank line when creating a
  fresh .gitignore, matching the two sibling writers this PR already
  conditionalized in cff94aa43.

Review iteration 2, non-blocking:
- cmd/bd/worktree_cmd.go: iteration 1's own rewrite lumped
  GIT_DISCOVERY_ACROSS_FILESYSTEM in with GIT_CEILING_DIRECTORIES as
  "removes an inherited stop". That is backwards. git(1) documents that
  discovery "does not cross filesystem boundaries" by default and that this
  variable "can be set to true to tell Git not to stop at filesystem
  boundaries" - it only ever permits, so clearing it *adds* a stop and
  narrows the walk. Split the clause per control: the ceiling widens,
  GIT_DISCOVERY_ACROSS_FILESYSTEM narrows (a repository reachable only
  across a mount point is no longer found by any `bd worktree` verb, with no
  opt-out), and ClearRouting's GIT_CONFIG prefix match drops the whole
  GIT_CONFIG* family for the command's lifetime rather than for one child
  probe. This comment is the only in-tree assertion about the variable's
  direction; export_auto.go:1083-1085 groups the two without claiming one.
- cmd/bd/config.go: "bd config's own beads.role reads and writes" covered
  `bd config show`, which the very next sentence lists as an exception. Name
  the four verbs that do scrub (get/set/unset/set-many, at config.go:209,
  :355, :609 and :902 - the only four git invocations in the file).
- internal/config: make the guard's fail-open default unspellable. The
  mirrored helper took `envs ...[]string`, so a future zero-probe call would
  fall through to "untracked" and write the secret with no compiler
  backstop. Promote the first environment to a required parameter. The tail
  stays variadic rather than matching the twin's fixed (clean, inherited)
  arity because the fallback's fixture guard has to probe one environment
  alone, and exec treats a nil Env as "inherit the current process" rather
  than as a disabled probe.

Pre-approval CI repair:
- Annotate the four gosec taint findings this PR newly introduces in package
  cmd/bd: G704 on the two connectivity probes in dolt.go, G702 on the
  staged-deletion probe in hooks.go and on the ls-remote probe in
  sync_git.go. None of the four is reported by the PR lane, whose lint is
  scoped to the diff (only-new-issues / --new-from-merge-base), and all four
  sit on lines this PR does not otherwise touch - but main.yml runs the same
  wrapper with BD_LINT_NEW_FROM_MERGE_BASE unset and sweeps the whole tree,
  so merging as-is turns main's Lint and PR Lint jobs red. Measured
  whole-tree at pr.yml's pinned golangci-lint v2.10.1 with
  --build-tags=gms_pure_go: origin/main 0 issues, this head 4, this head
  with the annotations 0. The findings are taint over-approximation rather
  than new exposure: gosec's analysis is not field-sensitive, so routing
  config discovery through env-derived paths marks the whole store value
  tainted and every remote URL read back off it inherits that. Each
  annotation states why its own call site is safe; the additions are
  comment-only, with no deletions and no behaviour change.

  The hooks.go annotation sits on the isExportFileStagedForDeletion
  declaration rather than on the exec.Command call. main has since rewritten
  that body to address the export file through nearestExistingDir +
  filepath.Rel, so a call-site comment both conflicted with the merge and
  described an argument the merged body no longer builds. On the declaration
  it merges cleanly and its justification holds for either body.

Pre-approval base refresh (rebased onto 511849496):
- Reconcile this PR with gastownhall/beads#6477, which landed on main after
  this branch was first rebased and which changes the same reader. The two
  changes collide in both directions, and neither side's CI can see it: the
  PR lane builds this branch against its own base, main's lane never has the
  PR, and only the merged tree fails.
- #6477 direction: its new subtest
  TestConfig_ReadFailuresAreNotMissing/invalid_routing_boolean poisons
  GIT_CONFIG_NOSYSTEM and expects the beads.role read to exit 128. This PR
  scrubs GIT_CONFIG* for exactly that key, so git never sees the poison and
  the read succeeds. Replaced that row with
  TestConfig_BeadsRoleScrubsInheritedRoutingEnv, which pins both halves of
  the new contract: beads.role reads through the scrub, and a key outside it
  (user.name) still surfaces the same poison as an exit-128 read error
  rather than as an absent key. #6477's general guarantee is untouched -
  malformed_config still proves it for beads.role through the repository's
  own config file.
- Opposite direction: this PR's own
  TestInitGitRepositoryUsesSelectedDirectory/captured_home asserted
  require.NoError on a generic-constructor read, commented "The existing
  reader maps Git exit errors to absence" - the precise behaviour #6477
  removed. Expect the propagated exit error instead. The test's intent is
  unchanged and in fact better served: only the current caller environment
  can see the changed HOME's broken .gitconfig, so that error is itself the
  proof that generic role reads still use it.

* test(init): retarget the bare row to the work-tree-less install policy

This PR's TestInitEmbeddedHooksSelectedTail/bare row (authored
2026-09-09) asserted that a bare repository fails to resolve hooks
and installs nothing. #6457 (6a4b4aa14e, 2026-09-27) added
git.ResolveWorkTreelessHooksContext specifically to end that
behavior -- its own comment calls out "turning a supported
repository into a warning and no install at all" as the defect it
fixes -- so the row pinned a policy main had deliberately
superseded by the time the two met.

Retargeted in place rather than deleted, so the bare shape keeps
coverage through the embedded-init entry point (main's new
bare/git_dir_cwd rows cover only the proxied path): bare now
installs like any other selected repository, and being its own
common directory, its hooks path lands in its own config.

Mutation-proved load-bearing: removing the work-tree-less fallback
reds this row alone (the other eight rows stay green) with
".../hooks/pre-commit: no such file or directory" -- i.e. it
reproduces the original expectation exactly.

---------

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>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-29 16:54:33 -07:00
Julian Knutsen
cba2037589
fix(bootstrap): probe git remotes for dolt data instead of rejecting; exit non-zero when bootstrap declines (#5743, #5663) (#6037)
* fix(bootstrap): probe git remotes for dolt data instead of rejecting them

`bd init` derives sync.remote from the git origin and persists it to the
git-tracked .beads/config.yaml — by design, because the first `bd dolt push`
creates refs/dolt/data on that same git remote. `bd bootstrap` then rejected
exactly that value: isGitCodeRepoURL classified any .git-suffixed or
known-forge URL as "not a Dolt remote" and returned Action=none *before* the
refs/dolt/data origin auto-detect that would have hydrated the clone. Every
fresh clone of such a repo got no database, and deleting the sync.remote line
by hand was the only way out (#5743, #5663).

The #4421 CPU storm this guard was added for is not a property of "the URL
points at a forge". Dolt's dbfactory routes by scheme: a raw http(s):// URL
goes to the remotesapi client, which speaks its wire protocol at github.com
and retries forever; a git+https/git+ssh URL goes to the git remote factory,
which shells out to git and fails cleanly. So the classifier is a good router
and a bad rejector.

Route on it instead: when sync.remote classifies as a forge URL, normalize it
to its git+ form and probe refs/dolt/data with the existing 10s-bounded
`git ls-remote` helper, then

  - data present: Action=sync from the git+ URL, never the raw form
  - definitively absent: note it and fall through to origin auto-detect,
    backup, issues.jsonl and fresh init, matching `bd init`'s own "remote has
    no Dolt data yet" behavior
  - probe error (UNKNOWN): Action=none with a new Blocked flag; never clone
    something we could not verify

Non-forge remotes (dolthub://, s3://, remotesapi http(s) endpoints,
self-hosted git+ssh) keep the trusted-as-is path untouched, so GH#3339 still
holds: normalization now happens only inside the forge branch, where a
remotesapi endpoint cannot appear.

Blocked/BlockedRemote are additive JSON fields; the exit-code half of the fix
follows in the next commit.

Refs #5743, #5663

* fix(bootstrap): exit non-zero when bootstrap declines to set up a database

Action=="none" was two different outcomes wearing one name: "a database
already exists, nothing to do" and "bootstrap refused and left you with no
database". printBootstrapPlan printed "✓ Database already exists" for both,
and RunE returned nil for both — so a rejected sync.remote reported success,
exited 0, and left the user with `bd list` saying "no beads database found"
(#5743, #5663).

The split was already encoded in the plan: every genuine no-op sets
HasExisting. Use it.

  - printBootstrapPlan reserves the success tick for HasExisting plans and
    otherwise reports the reason on stderr. Blocked plans additionally get a
    runnable `git ls-remote <url> refs/dolt/data` hint (the git+ prefix is
    stripped, as the probe itself strips it) and a pointer at the sync.remote
    line in config.yaml.
  - bootstrapPlanOutcome maps the plan to an exit status in one place, so
    text, --json and --dry-run all agree. JSON mode returns SilentExit, since
    the plan (carrying "blocked": true) is already on stdout.
  - The "Could not verify existing server database" branch is marked Blocked
    for the same reason: it also declined without confirming a database, and
    it also false-ticked.

Refs #5743, #5663

* fix(init): normalize git-forge sync.remote URLs before cloning

Init never had bootstrap's forge guard: a configured
`sync.remote: https://github.com/org/repo.git` was passed to DOLT_CLONE
verbatim, which Dolt routes to the remotesapi client — the same retry storm
(#4421) the bootstrap guard exists to prevent. Route it the same way
bootstrap now does: forge URLs are converted to their git+ form, which
selects the git remote factory, and everything else is left byte-identical so
a user-configured remotesapi endpoint (http://myserver:7007/mydb) is never
rewritten (GH#3339).

Also documents, at the two places someone would go looking after a bootstrap
failure, why init deliberately persists a plain git origin as sync.remote:
bootstrap probes refs/dolt/data to resolve it (#5743), so un-persisting here
would be the wrong fix and would strand every already-committed
.beads/config.yaml.

This commit is independent of the bootstrap fix and can be dropped from a
release cherry-pick if the minimum diff is wanted.

Refs #5743, #5663, #4421

* fix(sync): thread git's stderr into the refs/dolt/data probe error

The probe wrapped only the exec error, and exec.ExitError.Error() is just
"exit status 128" — git's actual complaint sits unread in ExitError.Stderr,
which cmd.Output() had already captured. A context timeout was worse still:
"signal: killed". Since bootstrap's blocked message is built from this error,
the fix's primary failure path told users nothing that distinguished bad
credentials from DNS from a deleted repository.

Now the error carries git's own first stderr line ("Permission denied
(publickey)", "Repository not found", "Invalid username or token") and names a
timeout as a timeout.

Also drops the remote and ref name from the wrapper. Every caller already
names the remote it probed, so wrapping here too produced messages that said
both twice: `... on sync.remote "X": probe refs/dolt/data on X: exit status
128`.

Refs #5743

* fix(bootstrap): derive the blocked verdict once; keep local recovery reachable

Review round on #6037. Every change below fixes a confirmed defect in this
PR's own new code.

State leak (the #5743 bug, reintroduced). existingBootstrapDBPlan's "none"
verdict was copied into the working plan, so every later branch inherited its
HasExisting/Blocked/Reason. A probe error on top of a seeded HasExisting=true
produced action=none + blocked=true + has_existing=true, which printed the
success tick and exited 0; a seeded server-verify error leaked blocked=true
into a *successful* sync plan's JSON, violating the field's own contract that
nothing clones from a blocked plan. The verdict is now held aside as an
explicit fallback instead of merged in, and Blocked is derived in one place
from the finished plan rather than hand-set by any branch.

Local recovery. A probe error used to return immediately, so an offline laptop
or credential-less CI runner was denied the backup/JSONL restore that the same
machine would have got if the probe had merely answered "no data". Restoring a
local backup touches no remote: the fail-closed rule now applies only to
remote actions, and the block is emitted at the tail, after every local source
has been tried.

Origin auto-detect is skipped once sync.remote is configured. sync.remote is
the authoritative remote, so hydrating from whatever git origin happens to be
— a fork, an old experiment, the code repo under the dedicated-data-repo
pattern — is not recovery, and finalizeSyncedBootstrap would then have
rewritten the team's committed sync.remote to point at it. This also removes
the second identical ls-remote in the flagship pre-first-push case (init
persists the git origin as sync.remote, so the two legs were probing the same
repository for the same ref), and makes the fall-through tests hermetic: the
origin leg is not behind the injectable probe seam.

Remote wiring. The fall-through made executeInitAction reachable with a
configured sync.remote for the first time, and it never registered the remote
as Dolt "origin". The promise that "the first bd dolt push creates
refs/dolt/data on that same git remote" then breaks: push either refuses to
adopt a remote without consent or adopts the git origin — a different
repository — and rewrites the committed sync.remote to match. Two machines
bootstrapping in the pre-push window would mint independent Dolt identities
and diverge. The provisioning actions now wire the routed remote, as the sync
action and bd init already did. bd init gets the same routing on its own
wiring call: its no-Dolt-data-yet path never clones, so a raw https forge URL
was stored verbatim in dolt_remotes and the *first* push took it to the
remotesapi client — #4421, one leg further down.

--dry-run always exits 0. bd doctor documents `bd bootstrap --dry-run` as the
safe inspection step, and a preview that aborts a set -e provisioning script
is a worse contract than a preview that merely reports. The blocked state is
still printed and still in the JSON, so the preview does predict what a real
run would refuse to do.

Credentials. sync.remote is commonly an https URL with an embedded CI token.
The reason, the hint and the blocked_remote JSON field all echoed it verbatim
into logs and agent transcripts; so did the sync plan's "Remote:" line. All
display paths now go through redactRemoteURL, which drops http(s) userinfo
whole and keeps only the account selector for ssh so the hint stays runnable.

Hints. The old remediation could name a config file that does not hold the key
(resolveSyncRemote reads a merged scope and a deprecated alias), and following
it was actively harmful: deleting sync.remote and re-running hits the same
auth failure on the git-origin probe, which swallows its error, so bootstrap
would "succeed" by creating a fresh database diverged from the team's history.
The hints now reproduce the probe, point at access, and offer `bd dolt remote
add` — never deletion.

One owner for the routing rule. doltRemoteURL (sync_remote.go) is now the
single definition of "classify, then normalize forge URLs only". It replaces
initCloneURL and the copy this PR had inlined into detectBootstrapAction: if
bd init and bd bootstrap ever disagree about the URL derived from one
committed sync.remote, that is the #5743 class of skew all over again.

Tests: blocked-with-HasExisting and blocked-leaking-into-sync (neither was
covered), probe-error-still-restores/imports, credential scrubbing on both the
plan and the printed output, dry-run exit status, the real probe's stderr
thread-through, and redactRemoteURL itself. The probe-error fixture now uses
the error shape production actually produces instead of a fabricated one, the
printer tests use the shared mutexed capture helpers, and the "#4421 pin"
comment is rescoped: it pins the routing, not the classifier, which still has
an unlisted-forge gap tracked as a follow-up.

Refs #5743, #5663, #4421

* fix(bootstrap): redact --json credentials, scrub git stderr, cut detect complexity

Maintainer fixup addressing PR #6037 review findings.

- Add BootstrapPlan.MarshalJSON so `bd bootstrap --json` (and
  `--dry-run --json`) redacts the credential-bearing sync_remote on a copy,
  matching the human print path. Closes the deterministic token leak to stdout
  while leaving the raw plan executeBootstrapPlan clones from untouched.
- Scrub credential-bearing URLs from the folded `git ls-remote` stderr at the
  source (scrubURLCredentials in gitLsRemoteProbeError) so a tokenized URL git
  echoes cannot reach plan.Reason, which flows to both stderr and JSON.
- Reduce detectBootstrapPlan cyclomatic 22->12 and cognitive 27->13 by
  extracting planConfiguredSyncRemote, gitOriginSyncPlan, and
  localFileRecoveryPlan. Detection order and plan-mutation semantics are
  preserved (a forge remote with no Dolt data still records SyncRemote so a
  local-recovery workspace stays wired to it).
- Drop the dead `plan.Blocked = true` in existingBootstrapDBPlan; the wrapper
  derives Blocked once from Action=="none" && !HasExisting.

Tests: assert the token is absent from the plan JSON (and MarshalJSON does not
mutate the source plan), and that tokenized git stderr is scrubbed while
credential-free diagnostics pass through unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-29 18:23:57 -07:00
Vishnu J
5ff61baef3
fix(init): verify refs/dolt/data before remote-history refusal (#5136)
* fix(init): verify refs/dolt/data before remote-history refusal

bd init --reinit-local refused solely because sync.remote was set,
claiming the remote had Dolt history without checking refs/dolt/data.
Git remotes with only ordinary branches tripped a false positive and
stranded workspaces with no way to set issue-prefix (GH#4861).

Probe gitRemoteHasDoltDataRef for configured sync.remote in both early
and late safety checks; re-probe on confirmation callbacks.

Fixes #4861

* fix(init): tri-state the refs/dolt/data probe so a failed check refuses

gitRemoteHasDoltDataRef collapsed "no refs/dolt/data" and "could not ask"
(timeout, DNS, credential refusal) into the same false, so a probe
failure silently fell through ADR-0002's refusal gate instead of
tripping it. Add gitRemoteHasDoltDataRefStatus / gitOriginHasDoltDataRefStatus
returning (bool, error), and route all four init.go call sites (both the
new sync.remote probe from GH#4861 and the two pre-existing git-origin
probes) through resolveRemoteHasDoltDataProbe, which treats a probe error
as UNKNOWN and fails closed (refuse) rather than open. The confirmation
re-probe in handleRemoteSafetyDecision now treats a probe error as
"unchanged" too, so only a genuine true->false transition aborts —
a transient network blip no longer spuriously kills a confirmed
--discard-remote flow.

Replace TestCheckRemoteSafety_ConfiguredRemoteWithoutDoltData, which
called the pure CheckRemoteSafety directly and passed whether or not
init.go actually probed anything, with a caller-level regression test:
bd init --reinit-local against a real bare-repo sync.remote, with and
without a pushed refs/dolt/data ref.

Also restore the "Remote has no Dolt data yet; initialized a fresh local
database" message on the configured-remote/no-history path, which the
GH#4861 fix silently dropped by skipping cloneFromRemoteWithMode.

Addresses maphew's review on #5136.

* test(init): make the sync.remote regression test hermetic

BD_SYNC_REMOTE works (viper AutomaticEnv maps BD_-prefixed vars to config
keys, config.go:165-169 — confirmed empirically via `bd config get
sync.remote`), but the test relied on the inherited environment: any
ambient ~/.beads/config.yaml, ~/.config/bd/config.yaml, or stray BD_*/
BEADS_* var on the machine running the test could leak in unnoticed.

Add hermeticInitEnv: strips inherited BD_*/BEADS_* vars and points HOME
at an isolated tempdir (distinct from workDir — metrics.go caches to
$HOME/.beads/eventsData, which collides with the project .beads/ this
test asserts on if HOME == workDir).

Verified under `env -i` with an isolated HOME/XDG_CONFIG_HOME and no
inherited env: without BD_SYNC_REMOTE, init succeeds; with it pointed at
a Dolt-data-free bare repo, only the pre-#4861-fix binary refuses (the
actual bug); with it pointed at a repo with pushed refs/dolt/data, both
pre- and post-fix binaries correctly refuse.
2026-08-07 10:34:35 -07:00
CI Bot
37c97e0b79 fix(init): guard JSONL init against remote history
_codex-gpt-5.5-xhigh on behalf of CI Bot_

Agent-Signature: codex-gpt-5.5-medium on behalf of matt wilkie
Agent-Signature: claude-unknown-model-high on behalf of matt wilkie
Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of matt wilkie
2026-06-22 15:28:38 -07:00
matt wilkie
d7d3dad580
fix(dolt): adopt git origin on first push (#3940)
* fix(dolt): adopt git origin on first push

bd dolt push now wires an existing git origin when no Dolt remote is configured, while init without origin stays local and doctor shows the concrete adoption command. This keeps refs/dolt/data sync discoverable without treating plain remotes as existing Dolt history.\n\n_kilocode-openai/gpt-5.5- on behalf of maphew_

* fix(dolt): address origin adoption review nits

Share Dolt remote URL normalization between the push adoption path and doctor guidance, fail before mutating Dolt state when no beads workspace is selected, and cover CheckRemoteConsistency's adoption detail.

_codex-gpt-5-medium on behalf of maphew_
2026-05-18 10:43:51 -07:00
guyua9
7f7708e1b1 fix: preserve Windows drive remotes for dolt sync 2026-04-29 02:20:38 +08:00
Steven Syrek
c6d0cc2fd9
fix(init): refuse --force when remote has Dolt history (#3455)
* fix(init): refuse --force when remote has Dolt history

bd init --force in a repo whose origin has refs/dolt/data silently
skipped the bootstrap-from-remote path and then wired origin as a Dolt
remote anyway. The next write auto-pushed an orphan history, failing
with "no common ancestor". Recovery options were all destructive.

This change:

- Adds --reinit-local (named-intent replacement for --force) and
  --discard-remote (explicit cross-boundary authorization).
- Routes --force to --reinit-local with a DeprecationWarning. --force
  continues to work for ≥2 releases.
- Refuses bd init --force / --reinit-local when origin has
  refs/dolt/data, unless --discard-remote is also passed. Exit code 10
  (ExitRemoteDivergenceRefused).
- Adds stable numeric exit codes for init refusals (10/11/12).
- Adds bd init-safety documenting the full flag surface and the
  destroy-token format.
- Adds an internal race-safety re-check: if remote state changes
  during the TTY confirmation window, abort rather than overwrite.
- Retrofits the existing destroy-token echo at init.go:231 to not
  print a copy-pasteable destructive invocation, matching the new
  error-text-no-echo ADR invariant.

Adds:
- cmd/bd/init_safety.go — CheckRemoteSafety chokepoint (pure fn).
- cmd/bd/init_safety_test.go — guard matrix (13 cases) + subprocess
  regression test with a synthetic refs/dolt/data fixture.
- docs/adr/0002-init-safety-invariants.md — ADR encoding the five
  invariants (single-source identity, scope-bound --force, central
  chokepoint, error-text-no-echo, race-safety).
- docs/RECOVERY.md — named recovery playbooks per refusal exit code.
- .github/CODEOWNERS — review ownership for init*.go pointing at the
  ADR so future flags must extend the guard matrix.

Historical pattern (git log for cmd/bd/init.go): 8+ prior commits
patched individual surfaces of this class without encoding the
invariant. The guard matrix test is the structural hedge — adding a
new flag or data source is a signal to extend the table, not to add
another `&& !someFlag` at the call site.

(bd-q83)

* fix(init): satisfy lint for origin safety helpers (bd-main-nwo)

---------

Co-authored-by: matt wilkie <maphew@gmail.com>
2026-04-24 09:01:35 -07:00
beads/crew/emma
273c377e2c fix: add timeout and prompt suppression to git ls-remote probe
gitLsRemoteHasRef is a network call used for auto-detection during
init/bootstrap. Add 10s timeout to prevent hangs on unreachable
remotes, and GIT_TERMINAL_PROMPT=0 to avoid blocking on SSH
credential prompts.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 14:08:57 -07:00
cwalv
4d14fb8ce1 feat: auto-detect beads database on git origin during bootstrap
When running `bd bootstrap` in a fresh clone, probe origin for
refs/dolt/data and automatically clone the existing beads database
instead of creating unrelated state. `bd init` warns if the ref
exists and suggests using `bd bootstrap` instead.

Fixes #2580
2026-03-14 00:18:13 -07:00
Osamu Okano
24836dd25b
fix(init): skip AGENTS.md generation in bare repositories 2026-03-02 20:25:52 +09:00
Matt Wilkie
612b3705ab fix: suppress git upstream warning for repos with no remotes
Brand-new repos with no remotes now skip the 'Git upstream not configured'
warning during bd init. The warning only appears when remotes exist (has
origin but no upstream), where it is actionable.

Adds gitHasAnyRemotes() guard to distinguish between 'new repo' and
'repo with origin but no upstream'.

Extracted from PR #2060 per code review feedback.

Amp-Thread-ID: https://ampcode.com/threads/T-019c955c-5c61-76ba-8dee-638aac3b6106
Co-authored-by: Amp <amp@ampcode.com>
2026-02-25 08:22:20 -07:00
beads/crew/emma
ff7244b619 feat: remove JSONL sync-branch pipeline, replace with Dolt-in-Git
Remove 10,955 lines of dead code from the JSONL sync-branch pipeline,
now replaced by native Dolt push/pull via git remotes.

Deleted:
- internal/syncbranch/ (5,720 lines: worktree management, integrity checks)
- cmd/bd/deletion_tracking.go (3-way JSONL merge)
- cmd/bd/snapshot_manager.go (JSONL snapshot tracking)
- cmd/bd/doctor/sync_branch_jsonl.go (JSONL validation)
- cmd/bd/doctor/fix/sync_branch.go (sync branch repair)
- All associated test files

Preserved:
- bd export / bd import (manual tools)
- isGitRepo(), gitHasUpstream() (still have callers)
- Doctor check stubs (return StatusOK N/A)

Added:
- BootstrapFromGitRemote() for Dolt-in-Git bootstrap
- Dolt push in bd sync via store.Push()
- sync.git-remote config key
- HasRemote() on DoltStore

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Executed-By: beads/crew/emma
Rig: beads
Role: crew
2026-02-18 20:13:55 -08:00
collins
87eab16982 chore: remove 3-way merge engine remnants (bd-aswyy)
Delete merge_driver.go no-op stub, remove attemptAutoMerge,
merge3WayAndPruneDeletions, applyDeletionsFromMerge, isIssueNotFoundError,
CheckMergeDriver doctor check, checkMergeDriverConfig warning, and all
associated tests. Update stale comments referencing 3-way merge. Simplify
import conflict detection to just error and exit.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 19:05:16 -08:00
Steven Syrek
a742db4f92 chore: remove dead git-portable sync functions (gitCommitBeadsDir, gitPush)
Remove four unused functions from sync_git.go that are dead code
since the migration to Dolt-native storage:
- gitCommitBeadsDir: staged and committed sync files in .beads/
- gitPush: pushed to upstream remote
- isPushPermissionDenied: only used by gitPush
- showPushPermissionGuidance: only used by gitPush

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 12:31:20 +01:00
beads/crew/emma
761d2e7637 Merge pull request #1186 from peterkc/feature/contributor-prompt-recovery
feat(init): add contributor prompt and push-fail recovery

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

Executed-By: beads/crew/emma
Rig: beads
Role: crew
2026-01-29 20:05:53 -08:00
Myles Henderson
c23a84801d feat: add events JSONL export (opt-in via events.export config)
Add GetAllEventsSince to the Storage interface and implement it in
SQLite, Dolt, and Memory backends. Create exportEventsToJSONL which
reads events_last_exported_id from metadata, fetches new events, appends
them as JSON lines, and updates the high-water mark.

Hook the events export into daemon_sync and autoflush, guarded by
config.GetBool("events.export") so it's opt-in. Add events.jsonl to
the sync file list in gitCommitBeadsDir. Add --events and --events-reset
flags to the export command (always available regardless of config).

Include a test verifying GetAllEventsSince returns all event columns.

Tickets: bd-w9f, bd-8fq, bd-w9w, bd-1ai, bd-2qd, bd-b22, bd-mmc, bd-3pc
2026-01-24 17:40:39 -05:00
Peter Chanthamynavong
b080961c1a
feat(sync): detect push permission errors during sync
- Implement git push permission detection and guidance
- Check for permission errors during daemon branch sync
- Add comprehensive tests for error detection logic

Helps contributors understand and resolve access issues during the synchronization process.
2026-01-20 20:53:01 -08:00
Peter Chanthamynavong
5d93aaf722
fix(sync): remove orphaned restoreBeadsDirFromBranch function (#1121)
Remove dead code that was inadvertently orphaned when PR #918 refactored
the sync flow. The function was never called since v0.47.0.

The function caused GH#1100 by running `git checkout HEAD -- .beads/`
which restored the entire .beads/ directory, overwriting uncommitted
config.yaml changes.

Add regression test (TestConfigPreservedDuringSync) to prevent similar
restoration logic from being reintroduced.

Fixes #1100
2026-01-15 19:22:52 -08:00
Peter Chanthamynavong
0a48519561
feat(context): centralize RepoContext API for git operations (#1102)
Centralizes repository context resolution via RepoContext API, fixing bugs where git commands run in the wrong repo when BEADS_DIR points elsewhere or in worktree scenarios.
2026-01-15 07:55:08 -08:00
slit
f36c8f6556 fix(sync): Handle redirected beads directories in gitCommitBeadsDir
When beads directory is redirected to a different repository (via bd-arjb),
gitCommitBeadsDir() was running git add from the current working directory's
repo root instead of the beads directory's repo root, causing exit status 128.

This fix adds the same redirect handling already present in gitHasBeadsChanges()
and gitHasUncommittedBeadsChanges() - checking GetRedirectInfo() and using
filepath.Dir(beadsDir) as the repo root when redirected.

Fixes: git add failed: exit status 128 errors during bd sync
2026-01-13 11:51:20 -08:00
Phredrick Phool
465f39b366 Merge remote-tracking branch 'origin/main' into fix-jj-detached-head-upstream-check
# Conflicts:
#	cmd/bd/sync_git_test.go
2026-01-12 06:49:51 -06:00
Phredrick Phool
78fec4bc45 fix(daemon): check sync-branch upstream for jj/jujutsu compatibility
When sync-branch is configured, check that branch's upstream instead of
current HEAD's upstream. This fixes --auto-push with jj/jujutsu which
always operates in detached HEAD mode.

Adds gitBranchHasUpstream(branch) to check specific branch's upstream
tracking, independent of current HEAD state.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-12 06:44:31 -06:00
Steve Yegge
8942261a12 fix: skip beads restore when directory is redirected (bd-lmqhe)
When a repo has a .beads/redirect file pointing to a shared beads
directory, restoreBeadsDirFromBranch would fail because it runs
git checkout from the local repo but with a path outside that repo.

Skip the restore when the beads directory is redirected since the
beads dir is managed by a different repo anyway.

Fixes: bd-lmqhe

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 22:09:13 -08:00
Peter Chanthamynavong
1561374c04
feat(sync): pull-first sync with 3-way merge (#918)
* feat(sync): implement pull-first synchronization strategy

- Add --pull-first flag and logic to sync command
- Introduce 3-way merge stub for issue synchronization
- Add concurrent edit tests for the pull-first flow

Ensures local changes are reconciled with remote updates before pushing to prevent data loss.

* feat(sync): implement 3-way merge and state tracking

- Implement 3-way merge algorithm for issue synchronization
- Add base state storage to track changes between syncs
- Add comprehensive tests for merge logic and persistence

Ensures data consistency and prevents data loss during concurrent
issue updates.

* feat(sync): implement field-level conflict merging

- Implement field-level merge logic for issue conflicts
- Add unit tests for field-level merge strategies

Reduces manual intervention by automatically resolving overlapping updates at the field level.

* refactor(sync): simplify sync flow by removing ZFC checks

The previous sync implementation relied on Zero-False-Convergence (ZFC)
staleness checks which are redundant following the transition to
structural 3-way merging. This legacy logic added complexity and
maintenance overhead without providing additional safety.

This commit introduces a streamlined sync pipeline:
- Remove ZFC staleness validation from primary sync flow
- Update safety documentation to reflect current merge strategy
- Eliminate deprecated unit tests associated with ZFC logic

These changes reduce codebase complexity while maintaining data
integrity through the robust structural 3-way merge implementation.

* feat(sync): default to pull-first sync workflow

- Set pull-first as the primary synchronization workflow
- Refactor core sync logic for better maintainability
- Update concurrent edit tests to validate 3-way merge logic

Reduces merge conflicts by ensuring local state is current before pushing changes.

* refactor(sync): clean up lint issues in merge code

- Remove unused error return from MergeIssues (never returned error)
- Use _ prefix for unused _base parameter in mergeFieldLevel
- Update callers to not expect error from MergeIssues
- Keep nolint:gosec for trusted internal file path

* test(sync): add mode compatibility and upgrade safety tests

Add tests addressing Steve's PR #918 review concerns:

- TestSyncBranchModeWithPullFirst: Verifies sync-branch config
  storage and git branch creation work with pull-first
- TestExternalBeadsDirWithPullFirst: Verifies external BEADS_DIR
  detection and pullFromExternalBeadsRepo
- TestUpgradeFromOldSync: Validates upgrade safety when
  sync_base.jsonl doesn't exist (first sync after upgrade)
- TestMergeIssuesWithBaseState: Comprehensive 3-way merge cases
- TestLabelUnionMerge: Verifies labels use union (no data loss)

Key upgrade behavior validated:
- base=nil (no sync_base.jsonl) safely handles all cases
- Local-only issues kept (StrategyLocal)
- Remote-only issues kept (StrategyRemote)
- Overlapping issues merged (LWW scalars, union labels)

* fix(sync): report line numbers for malformed JSON

Problem:
- JSON decoding errors when loading sync base state lacked line numbers
- Difficult to identify location of syntax errors in large state files

Solution:
- Include line number reporting in JSON decoder errors during state loading
- Add regression tests for malformed sync base file scenarios

Impact:
- Users receive actionable feedback for corrupted state files
- Faster troubleshooting of manual configuration errors

* fix(sync): warn on large clock skew during sync

Problem:
- Unsynchronized clocks between systems could lead to silent merge errors
- No mechanism existed to alert users of significant timestamp drift

Solution:
- Implement clock skew detection during sync merge
- Log a warning when large timestamp differences are found
- Add comprehensive unit tests for skew reporting

Impact:
- Users are alerted to potential synchronization risks
- Easier debugging of time-related merge issues

* fix(sync): defer state update until remote push succeeds

Problem:
- Base state updated before confirming remote push completion
- Failed pushes resulted in inconsistent local state tracking

Solution:
- Defer base state update until after the remote push succeeds

Impact:
- Ensures local state accurately reflects remote repository status
- Prevents state desynchronization during network or push failures

* fix(sync): prevent concurrent sync operations

Problem:
- Multiple sync processes could run simultaneously
- Overlapping operations risk data corruption and race conditions

Solution:
- Implement file-based locking using gofrs/flock
- Add integration tests to verify locking behavior

Impact:
- Guarantees execution of a single sync process at a time
- Eliminates potential for data inconsistency during sync

* docs: document sync architecture and merge model

- Detail the 3-way merge model logic
- Describe the core synchronization architecture principles

* fix(lint): explicitly ignore lock.Unlock return value

errcheck linter flagged bare defer lock.Unlock() calls. Wrap in
anonymous function with explicit _ assignment to acknowledge
intentional ignore of unlock errors during cleanup.

* fix(lint): add sync_merge.go to G304 exclusions

The loadBaseState and saveBaseState functions use file paths derived
from trusted internal sources (beadsDir parameter from config). Add
to existing G304 exclusion list for safe JSONL file operations.

* feat(sync): integrate sync-branch into pull-first flow

When sync.branch is configured, doPullFirstSync now:
- Calls PullFromSyncBranch before merge
- Calls CommitToSyncBranch after export

This ensures sync-branch mode uses the correct branch for
pull/push operations.

* test(sync): add E2E tests for sync-branch and external BEADS_DIR

Adds comprehensive end-to-end tests:
- TestSyncBranchE2E: verifies pull→merge→commit flow with remote changes
- TestExternalBeadsDirE2E: verifies sync with separate beads repository
- TestExternalBeadsDirDetection: edge cases for repo detection
- TestCommitToExternalBeadsRepo: commit handling

* refactor(sync): remove unused rollbackJSONLFromGit

Function was defined but never called. Pull-first flow saves base
state after successful push, making this safety net unnecessary.

* test(sync): add export-only mode E2E test

Add TestExportOnlySync to cover --no-pull flag which was the only
untested sync mode. This completes full mode coverage:

- Normal (pull-first): sync_test.go, sync_merge_test.go
- Sync-branch: sync_modes_test.go:TestSyncBranchE2E (PR#918)
- External BEADS_DIR: sync_external_test.go (PR#918)
- From-main: sync_branch_priority_test.go
- Local-only: sync_local_only_test.go
- Export-only: sync_modes_test.go:TestExportOnlySync (this commit)

Refs: #911

* docs(sync): add sync modes reference section

Document all 6 sync modes with triggers, flows, and use cases.
Include mode selection decision tree and test coverage matrix.

Co-authored-by: Claude <noreply@anthropic.com>

* test(sync): upgrade sync-branch E2E tests to bare repo

- Replace mocked repository with real bare repo setup
- Implement multi-machine simulation in sync tests
- Refactor test logic to handle distributed states

Coverage: sync-branch end-to-end scenarios

* test(sync): add daemon sync-branch E2E tests

- Implement E2E tests for daemon sync-branch flow
- Add test cases for force-overwrite scenarios

Coverage: daemon sync-branch workflow in cmd/bd

* docs(sync): document sync-branch paths and E2E architecture

- Describe sync-branch CLI and Daemon execution flow
- Document the end-to-end test architecture

* build(nix): update vendorHash for gofrs/flock dependency

New dependency added for file-based sync locking changes the
Go module checksum.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-01-07 21:27:20 -08:00
beads/crew/wolf
a61cbde692 fix(sync): handle .beads/redirect in git status checks (bd-arjb)
When running from a crew directory with .beads/redirect pointing to a shared
beads directory in another repo, git status commands would fail with:
  fatal: /path/to/mayor/rig/.beads: is outside repository

The fix detects when beadsDir is redirected and runs git commands from the
directory containing the actual .beads/ using git -C <targetRepoDir>.

Updated functions:
- gitHasBeadsChanges(): checks redirect and runs git from target repo
- gitHasUncommittedBeadsChanges(): same fix for pre-flight check

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 19:57:19 -08:00
emma
9b84ef73dd fix(sync): atomic export and force-push detection (bd-3bhl, bd-4hh5)
bd-3bhl: Add sync rollback on git commit failure
- Use exportToJSONLDeferred() instead of exportToJSONL() for atomic sync
- Call finalizeExport() only after git commit succeeds
- Rollback JSONL from git HEAD on commit failure
- Add rollbackJSONLFromGit() helper function
- Coverage: regular commit, sync branch, external beads repo paths

bd-4hh5: Fix false-positive force-push detection
- Use explicit refspec in CheckForcePush fetch
- +refs/heads/beads-sync:refs/remotes/origin/beads-sync
- Ensures tracking ref is always created/updated
- Fixes stale ref comparison causing false positives

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 23:14:11 -08:00
ruby
32aea46ca6 test(sync): add unit tests for gitHasUncommittedBeadsChanges (bd-p7i2)
Extract parseGitStatusForBeadsChanges helper function from
gitHasUncommittedBeadsChanges to enable unit testing without git setup.

Add 14 test cases covering:
- Empty/no changes
- Modified files (staged, unstaged, both)
- Added files (staged, with modifications)
- Untracked files (should return false)
- Deleted files (should return false)
- Renamed/copied files
- Edge cases (short status line)

Part of GH#885 follow-up.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 16:22:20 -08:00
beads/crew/fang
44a5c3a0ec feat: detect uncommitted JSONL changes before sync (GH#885, bd-vd8e)
Add pre-flight safety check to detect when a previous sync exported
but failed before commit, leaving JSONL in an inconsistent state.

- Add gitHasUncommittedBeadsChanges() helper in sync_git.go
- Call in sync pre-flight checks after merge/rebase check
- If uncommitted changes detected, force re-export to reconcile state

This catches the failure mode early before it compounds across worktrees.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 15:10:47 -08:00
dave
6c4b67f65d fix: respect sync.remote config in bd sync (GH#872, bd-ypvj)
The sync.remote config was being set via `bd config set sync.remote <name>`
but `bd sync` was still using 'origin' for git pull/push operations.

Changes:
- Updated gitPull() and gitPush() in sync_git.go to accept a configuredRemote
  parameter that takes precedence over git's branch tracking config
- Updated sync.go to read sync.remote config and pass it to gitPull/gitPush
- Updated daemon_sync.go to read sync.remote config for all daemon sync ops
- Added user-facing messages to show which remote is being used

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

Executed-By: beads/crew/dave
Rig: beads
Role: crew
2026-01-03 13:24:28 -08:00
beads/crew/emma
363c5a3819 fix: bd sync fails with exit 128 in bare repo worktrees (GH#827)
Two fixes for bare repo worktree setups:

1. fork_protection.go: Use git.GetGitDir() instead of hardcoding .git
   In worktrees, .git is a file containing gitdir path, not a directory.
   Using GetGitDir() handles this correctly.

2. sync_git.go: Simplify gitHasBeadsChanges to use absolute paths
   The previous code used git -C main-repo-root status, but in bare
   repo worktrees GetMainRepoRoot() returns the parent of the bare repo
   which is not a valid working tree. Using absolute paths without -C
   lets git find the repo from cwd, which always works.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 11:05:05 -08:00
Steve Yegge
d3b6855aa9 fix: resolve lint errors blocking CI
- Add explicit error checking for fmt.Fprintf/Fprintln in claude.go
- Add gosec nolint for safe exec.CommandContext calls in sync_git.go
- Remove unused error return from findTownRoutes in routes.go

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 15:58:24 -08:00
Steve Yegge
71e2f22849 fix: Add nolint comments for gosec/errcheck/unparam warnings
Fixes CI lint failures by adding appropriate nolint directives for:
- G204 (subprocess with variable) - git commands with trusted inputs
- G304 (file inclusion via variable) - paths from internal helpers
- G302/G306 (file permissions) - .gitignore needs 0644
- errcheck (unchecked return values) - fmt.Fprint* to stdout/stderr
- unparam (unused parameters) - reserved for future use
2025-12-29 14:39:43 -08:00
Steve Yegge
7ff5481966 fix: resolve golangci-lint errors (errcheck, gosec, unparam)
- orphans.go: check fmt.Scanln return value
- edit.go: #nosec G204 for trusted $EDITOR execution
- sync_git.go: #nosec G204 for git commands with internal branch names
- worktree_cmd.go: #nosec G304/G306 for .gitignore file operations
- migrations: handle rows.Close() error
- doctor_pollution.go: mark unused path parameter

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 20:50:54 -08:00
Steve Yegge
6c14fd2225 refactor: Split large cmd/bd files to meet 800-line limit (bd-xtf5)
Split 6 files exceeding 800 lines by extracting cohesive function groups:

- show.go (1592→578): extracted show_thread.go, close.go, edit.go, update.go
- doctor.go (1295→690): extracted doctor_fix.go, doctor_health.go, doctor_pollution.go
- sync.go (1201→749): extracted sync_git.go
- compact.go (1199→775): extracted compact_tombstone.go, compact_rpc.go
- linear.go (1190→641): extracted linear_sync.go, linear_conflict.go
- main.go (1148→800): extracted main_help.go, main_errors.go, main_daemon.go

All files now under 800-line acceptance criteria.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 18:43:09 -08:00