* fix(hooks): inject BEADS INTEGRATION above trailing exec block (GH#3537)
When bd preserves an existing hook (e.g. .git/hooks/<name> copied into .beads/hooks/<name>) whose tail is an exec-replacing chain, the unconditional bottom-append in injectHookSection landed the BEADS INTEGRATION block below the exec — making it unreachable. The most common case is the hook produced by 'pre-commit init-templatedir', which ends with two exec calls inside an if/elif/else/fi ladder.
Add findExecBlockInjectionPoint that detects the pattern: a final exec line whose only trailing siblings are control-flow closers (fi, else, elif, then), exit, echo, comments, or blank lines. When detected, walk backward past elif/else/then continuations and indented body lines to find the start of the enclosing if-block, then inject the bd section just above it. Otherwise fall back to the existing append-at-end behaviour.
Tests cover: pre-commit's actual hook output, bare trailing exec, exec in middle (must NOT trigger), and a non-exec hook (must keep existing behaviour). New helpers are pure functions with no I/O.
--no-verify used: local pre-commit hook runs golangci-lint without the gms_pure_go build tag CONTRIBUTING.md mandates (ICU headers not installed locally — not a documented requirement). Verified clean with: golangci-lint run --new-from-rev=main --build-tags=gms_pure_go ./cmd/bd/ → 0 issues.
Refs: GH#3537
* test(hooks): cover remaining branches of findExecBlockInjectionPoint helpers
Codecov flagged 91.66% patch coverage on PR #3556. The two uncovered branches in my new code were:
- findExecBlockInjectionPoint:206 — the comment/blank-line skip in the backward-walk loop (no fixture had a comment between the if-opener and the exec line).
- isAllowedAfterExec:252 — the 'elif <args>' / 'else <args>' branch (existing fixtures only hit the bare 'else'/'fi' switch case).
Adds three focused tests: TestInjectHookSection_IfBlockWithCommentInBody (the integration fixture), and table-driven TestIsAllowedAfterExec_TableDriven + TestIsExecLine_TableDriven covering every branch of both helpers. All four functions touched by this PR now report 100% coverage.
* address review nits: doc edge cases + TrimRight + idempotency/double-block tests
Five nits from automated review on PR #3556. The two functional changes:
1. strings.Split off-by-one. Replaced strings.Split(content, '\\n') with strings.Split(strings.TrimRight(content, '\\n'), '\\n') to eliminate the spurious empty trailing element from files that end in newline. The behaviour was correct in practice but the trim makes the intent explicit and removes the off-by-one ambiguity.
2. findExecBlockInjectionPoint godoc. Documented three line-based-heuristic limitations: heredoc bodies containing exec, trailing-comment exec lines (e.g. 'exec /bin/foo # disabled'), and disjoint exec blocks separated by real code. Each is covered or harmless in practice but worth flagging to future maintainers.
3. New table-driven case 'two disjoint exec blocks, real code after both' — confirms the safe -1 fallback behaviour when the file isn't strictly exec-terminating.
4. New TestInjectHookSection_Idempotent_PrecommitTemplate — runs injectHookSection twice on a pre-commit-templated hook and asserts the output is identical. Locks in the idempotency that the marker logic already provides for free, in case a future refactor moves the strip-and-re-inject path.
* fix(hooks): preserve user content when migrating v0.62.x → v1.0.x (GH#3536)
preservePreexistingHooks treated any file containing the BEADS INTEGRATION begin marker as wholly bd-managed and skipped it during preservation. But the v0.62.x inline-injection model only injected a *block* into otherwise-user-owned files (custom dispatchers, framework integrations, husky setups). On migration to v1.0.x's relocate-to-.beads/hooks/ model, that user content was silently discarded — only the bare bd shim ended up in .beads/hooks/<name>.
Fix: when the begin marker is present, strip the bd section using the existing removeHookSection helper, then preserve any remaining user content. Only skip if stripping leaves nothing meaningful (an isOnlyShebangOrEmpty check). The inlineHookMarker case (GH#1120 one-liners) is unchanged — those files genuinely were wholly bd-owned.
Tests cover: stripping a v0.62.x file (user content survives), skipping a wholly-managed file (v1.0.x bare shim and bare-marker-block), and leaving non-marker hooks alone. Plus a table-driven test for the new isOnlyShebangOrEmpty helper.
--no-verify used: local pre-commit hook runs golangci-lint without the gms_pure_go build tag CONTRIBUTING.md mandates (ICU headers not installed locally — not a documented requirement). Verified clean with: golangci-lint run --new-from-rev=main --build-tags=gms_pure_go ./cmd/bd/ → 0 issues.
Refs: GH#3536
* test(hooks): extract shouldPreserveHookContent for direct unit-test coverage
Codecov flagged 53% patch coverage on PR #3557. The strip-and-preserve logic was inlined inside preservePreexistingHooks (which does file I/O and depends on git context), so unit tests could only exercise it via cumbersome integration tests that proved test-isolation-fragile in this package.
Extract shouldPreserveHookContent(content, fromHusky) (string, bool) — a pure function with no I/O, no git context, no globals — that holds the per-file decision logic. preservePreexistingHooks now calls it inline and acts on the returned (transformedContent, keep) tuple.
Add table-driven tests covering every branch: inline marker (skip), v0.62.x marker block with user content (strip + keep), marker block with only shebang (strip leaves nothing → skip), no markers (preserve verbatim), husky v8 sanitisation (with and without prior marker strip). Plus a focused regression test that proves the dispatcher above the marker block survives the strip.
Coverage on the new pure function: 100%. preservePreexistingHooks coverage unchanged from baseline (still exercised by the existing TestInstallHooksBeads_* integration tests).
* fixup: spelling — sanitised → sanitized (lint)
* address review nits: CRLF normalisation + godoc + edge tests
Three nits from automated review on PR #3557:
1. CRLF normalisation gap. The new strip-then-preserve path inherited a Windows / autocrlf=true edge case where '\\r\\n' could end up in .beads/hooks/<name>. Mirror what injectHookSection does on its inject path — normalize after the strip with a single ReplaceAll.
2. isOnlyShebangOrEmpty godoc. Make the design choice explicit: non-shebang comment lines are intentionally treated as non-content; a file that's just shebang + comment is classified empty and skipped.
3. Edge-case tests. Add TestShouldPreserveHookContent_TwoBlankLinesBeforeMarker (locks in the boundary where removeHookSection collapses '\\n\\n\\n' → '\\n\\n') and TestShouldPreserveHookContent_CRLFNormalised (locks in the new normalisation).
* fix(hooks): preserve husky v8/v9 hook layout when copying to .beads/hooks/ (GH#3132)
When beads sets core.hooksPath=.beads/hooks/ and copies hooks from a
husky-managed directory, two bugs break the preserved hooks:
Bug 1 (v8): Husky v8 hooks source $(dirname "$0")/_/husky.sh, but the
_/ helper directory was skipped by preservePreexistingHooks (which skips
directories). Fix: create a relative symlink from .beads/hooks/_/ to the
original _/ directory.
Bug 2 (v9): Husky v9 sets core.hooksPath=.husky/_/ where each hook is a
shim that sources an "h" dispatcher. The dispatcher uses
dirname(dirname($0)) to resolve user hooks in the parent .husky/
directory — this path math breaks when the shim is relocated. Fix: detect
v9 shims and replace them with the actual user hook content from .husky/,
then remove the now-unnecessary h dispatcher.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(hooks): ignore os.Remove error for husky h-dispatcher cleanup
errcheck flagged the unchecked os.Remove call. Failure here is harmless
(the h dispatcher is a stale artifact of husky v9 shim replacement), so
explicitly discard the error using the `_ = os.Remove(...)` convention
used elsewhere in the package (e.g. export_auto.go, rules.go, edit.go).
* fix(hooks): make husky v9 shim replacement actually run
TestInstallHooksBeads_HuskyV9Shims was failing on CI because the Bug 2
fix in fixHuskyHookLayout had two detection bugs that made it a no-op:
1. It keyed off targetDir/h to detect v9, but preservePreexistingHooks
intentionally skips copying the `h` dispatcher to the target — so the
detection always failed and the function returned early.
2. Even once detection is fixed, it then checked each target file for
the shim source line (`. "$(dirname "$0")/h"`) before replacing, but
sanitizeHuskyHook has already stripped that exact line during copy,
so the content check would never match.
Fix both:
- Detect v9 from sourceDir/h (always present when source is .husky/_/).
- Iterate sourceDir entries instead of targetDir and drop the content
check — in a v9 source every non-`h` file is a shim by construction,
so the source-entry → user-hook mapping is unambiguous.
Also remove the now-dead `os.Remove(hPath)` that tried to clean up the
target `h` that was never copied.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
When export.git-add=true (the v1.0.1+ default), the pre-commit hook in
a worktree stages a spurious issues.jsonl at the repo root instead of
(or in addition to) .beads/issues.jsonl. The ghost file lands in the
commit's diff but not on disk — easy to miss and painful to clean up.
Root cause (not what the issue body guessed): the absolute path passed
to `git add` was always correct. The bug is env inheritance. Git
invokes the pre-commit hook with GIT_DIR/GIT_WORK_TREE/GIT_INDEX_FILE/
GIT_COMMON_DIR/GIT_PREFIX set in the environment, and bd's git-add
subprocesses inherit them.
Both call sites set `cmd.Dir = filepath.Dir(fullPath)` (= `.beads/`).
With GIT_DIR set in the environment and GIT_WORK_TREE unset, git
defaults the work-tree to cwd. So the subprocess's git sees `.beads/`
as the work-tree root and records `.beads/issues.jsonl` at the root of
that broken view — which ends up in the worktree's actual index as a
bare `issues.jsonl`. Verified empirically: with GIT_DIR set and
cwd=`.beads/`, `git rev-parse --show-toplevel` returns the `.beads/`
directory itself.
Fix, in two parts:
1. scrubGitHookEnv() strips the vars that poison repo/worktree
auto-discovery, index routing, object routing, and config
injection:
- discovery: GIT_DIR, GIT_WORK_TREE, GIT_COMMON_DIR, GIT_PREFIX,
GIT_CEILING_DIRECTORIES, GIT_DISCOVERY_ACROSS_FILESYSTEM
- index: GIT_INDEX_FILE
- objects: GIT_OBJECT_DIRECTORY, GIT_ALTERNATE_OBJECT_DIRECTORIES
- config: the whole GIT_CONFIG* family (covers the case where the
parent invoked `git -c core.worktree=… commit`, which sets
GIT_CONFIG_PARAMETERS / GIT_CONFIG_COUNT in the child env)
With these cleared, git rediscovers the repo/worktree from cwd.
2. hookWorkTreeRoot() reads the inherited GIT_DIR to determine the
worktree whose hook is currently firing. If the target path is
outside that worktree, gitAddFile returns without staging. This
prevents a narrower but real regression that would otherwise land
after part 1 alone: in the .beads/redirect configuration, fullPath
points into the main repo (not the worktree), and post-scrub git
would silently stage the file into main's index from a worktree
hook. The existing preCommitHookBody template (init_git_hooks.go)
documents the same intent: "For worktrees: .beads is in the main
repo's working tree... we skip it."
The guard uses pathInsideDir which handles the macOS symlinked-parent
case: on /tmp → /private/tmp, a fresh-file target expressed as
/tmp/.../new.txt compared against a worktree root resolved to
/private/tmp/... would otherwise misclassify as outside the worktree.
pathInsideDir resolves the parent of each side via EvalSymlinks and
reattaches the basename — sufficient for the real caller shapes, since
gitAddFile's parent directory (beadsDir or the export output dir)
always exists at call time.
Also fixes the variant reported in a follow-up comment where the
.beads/redirect workaround did not resolve the root ghost: the env
pollution broke git-add inside the `bd export -o` subprocess spawned
from exportJSONLForCommit (that subprocess has BD_GIT_HOOK stripped,
but git env vars preserved, so its PostRun auto-export hits the same
bug via the shared gitAddFile).
Deduplicates the parallel git-add invocation in exportJSONLForCommit
by delegating to gitAddFile, so both call sites share the env scrub
and the cross-worktree guard.
Adds:
- TestGitAddFile_InWorktreeHook_StagesCorrectPath — end-to-end
worktree regression test; fails on main, passes with the fix.
- TestGitAddFile_RedirectCase_DoesNotStageInMainRepo — verifies
the cross-worktree skip does not pollute main's index when a
worktree has .beads/redirect pointing into main.
- TestGitAddFile_NonHookContext_GuardDoesNotFire — regression guard
confirming the cross-worktree skip is a no-op outside git hooks.
- TestScrubGitHookEnv — unit test for the env scrub helper, covering
the discovery/index/object vars and the GIT_CONFIG* family, and
verifying non-discovery vars (author/committer/editor/pager) pass
through untouched.
- TestPathInsideDir — covers structural cases plus the macOS
fresh-file + symlinked-parent regression.
- TestHookWorkTreeRoot — covers linked-worktree gitdir file,
plain-repo .git, bare/unrecognized, and not-a-hook contexts.
Workaround for users on older releases remains `BD_EXPORT_GIT_ADD=false`.
Closes GH#3311
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When no-git-ops=true is set, bd still attempted to git add the
auto-export file on every write, producing a warning on every
invocation. Users had to set both no-git-ops=true and
export.git-add=false separately.
Check the no-git-ops flag in both the auto-export path
(export_auto.go) and the pre-commit hook export path (hooks.go).
When no-git-ops is true, skip the git add without warning.
Co-authored-by: kev <kglynn@pryoninc.com>
* fix: enable auto-export by default with canonical issues.jsonl name (GH#2973)
Users expected JSONL export to refresh automatically but export.auto
defaulted to false, requiring explicit opt-in. Also the default filename
(export.jsonl) didn't match the canonical issues.jsonl used in docs and
git hooks. Change defaults: export.auto=true, export.path=issues.jsonl,
export.git-add=true so viewers (bv) and git workflows see fresh data
without extra configuration.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(init): add auto-export prompt and document export.* config (GH#2973)
Interactive bd init now asks whether to enable auto-export (default: yes).
Users can opt out during setup instead of discovering the setting later.
Also documents the export.* config namespace in bd config --help with
all four keys (export.auto, export.path, export.interval, export.git-add)
and adds export examples.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: document export.* auto-export config keys (GH#2973)
Document the export.auto/path/interval/git-add keys in docs/CONFIG.md
and note the default-on switch in CHANGELOG.md [Unreleased].
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(export): don't prime throttle on empty init and skip git-add without git (GH#2973)
Review feedback on #3204 surfaced two regressions in the default-on
auto-export path:
1. bd init's PersistentPostRun fired maybeAutoExport with zero issues,
writing an empty .beads/issues.jsonl and saving export-state.json with
the current dolt commit + timestamp. The next `bd create` was then
throttled for up to export.interval (default 60s) because the
timestamp check in maybeAutoExport returned before considering the new
commit, leaving issues.jsonl stale on fresh repos.
Skip saving state and remove the empty file when the export produced
no issues and no memories. The next write runs a real export
immediately.
2. export.git-add defaulting to true emitted
`Warning: auto-export: git add failed: exit status 128` on every
write in the supported standalone BEADS_DIR flow where init
intentionally skips `git init`. Gate the git add call on isGitRepo()
so standalone users get silent, working auto-export.
Adds a scripttest regression guard for the init -> immediate create
path.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(memory): disable auto-export in concurrent test (GH#2973)
TestEmbeddedMemoryConcurrent started failing on this branch after
auto-export became the default: every concurrent 'bd remember'/'bd
forget' call now fires maybeAutoExport, which reads store state after
the write. Under 8-worker contention this intermittently leaves a
forgotten key visible to 'bd memories'.
The test exercises memory concurrency, not export behavior; opt it
out of auto-export so the signal stays focused. Followup: investigate
the race between write commit and post-write auto-export read in
embedded Dolt concurrent paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
When `bd init` chains existing husky hooks into `.beads/hooks/`, it
blindly copied per-hook files whose `. "$(dirname "$0")/_/husky.sh"`
(v8) or `. "$(dirname "$0")/h"` (v9) source line dangles in the new
location. Result: v8 commits fail loudly with `husky.sh: No such file
or directory`; v9 commits silently no-op because husky's dispatcher
resolves to `.beads/<hook>` (does not exist) and exits 0, skipping all
of the user's lint-staged / formatter / etc. commands.
Detect husky source dirs and rewrite hook bodies to drop the helper
source line, injecting `node_modules/.bin` on PATH so `npx` and
project-local binaries continue to resolve. Skip copying husky's `h`
and `husky.sh` dispatchers, which are no longer needed once hooks are
inlined.
* fix(workspace): align resolved workspace messaging and config lookup
intent(workspace): pure worktrees and external BEADS_DIR setups should work without implying a local .beads directory is required
decision(config): derive config repo roots from FindBeadsDir-backed workspace resolution instead of a local-only .beads walk
constraint(workspace-detection): keep FindBeadsDir ordering and storage behavior unchanged while making bd where the primary diagnostic hint
learned(testing): shared-server env and global .beads ignore rules can distort CGO suites, so regression coverage now normalizes those test paths
* fix(bootstrap): align no-workspace JSON wording
intent(bootstrap): machine-readable no-workspace output should match the resolved-workspace guidance used elsewhere on this branch
decision(bootstrap-json): reuse the shared workspace error helpers through a dedicated payload builder so tests can lock the JSON contract
constraint(review-loop): keep the bootstrap CLI flow unchanged outside the no-workspace JSON branch while adding a focused regression test
* fix(where): allow no-workspace diagnostics without db (beads-9f74-5l1)
intent(where): no-workspace guidance should point to a command that actually runs when workspace resolution fails
decision(startup): treat top-level where as a no-db command so it reaches its own handler before database preflight
constraint(where-tests): subprocess mode can change the exact hint text, so the regression test locks the JSON contract and stable guidance fragments instead
* fix(bootstrap): restore bd where guidance for no-workspace output (beads-9f74-3c3)
intent(bootstrap): no-workspace bootstrap guidance should match the resolved-workspace diagnostics introduced on this branch
decision(no-workspace-hints): reuse the shared hint that mentions bd where instead of the bootstrap-specific fallback text
constraint(bootstrap-tests): cover both the payload helper and subprocess CLI path so wording regressions are caught before release
* fix(workspace): remove no-workspace .beads fallbacks (beads-9f74-gr1)
intent(workspace-resolution): finish the GH#3124 follow-up for runtime paths that still fabricated local .beads state
rejected(no-workspace-fallback): inventing ./ .beads paths outside an active workspace hid shared-worktree resolution and created stray files
decision(setup-recipes): keep built-in bd setup recipes usable without a workspace but require an active workspace for custom recipe state
constraint(worktree-support): completion and backup helpers still need to resolve shared main-repo workspaces from a git worktree
* fix(config): skip no-workspace store init for store-free commands
intent(config): review-fix-loop found no-workspace config commands should reach their own graceful paths instead of failing in PersistentPreRun
decision(config-preflight): detect store-free config subcommands before DB synthesis so config.yaml, git-backed, and diagnostic flows can run without an opened store
constraint(json-contract): keep bd config validate --json machine-readable on stdout once pre-run stops short-circuiting into low-level DB errors
learned(config-preflight): the parent config command not being in noDbCommands leaked store init into show, validate, drift, apply, and yaml-only config helpers
* fix(ci): restore init prefix normalization and formatting
intent(ci): clear the current PR failures instead of leaving the branch blocked behind known red checks
decision(init-prefix): normalize dotted prefixes before persisting issue_prefix so config, metadata.json, and Dolt database naming stay aligned for Julia-style repos
constraint(fmt-check): CI runs gofmt over the whole repo, so the existing spacing drift in internal/jira/tracker_test.go had to be cleaned up on this branch to get a green run
learned(ci): the latest main CI was already red on the same formatting file and the same embedded shard, so rebasing surfaced pre-existing blockers rather than introducing a new shard-only regression
GetMainRepoRoot() already falls back to regular repo root for
non-worktree repos, making the IsWorktree() guard redundant.
Simplify all 5 call sites.
Co-Authored-By: osamu2001 <osamu2001@users.noreply.github.com>
git.GetRepoRoot() returns the worktree root, which causes
core.hooksPath to point to a non-existent path. Use
git.GetMainRepoRoot() in worktrees so hooks resolve correctly.
* fix: export JSONL in pre-commit hook for atomic code+issues commits (GH#2489)
The pre-commit hook skipped auto-export because BD_GIT_HOOK=1 was set,
preventing issue state from landing in the same git commit as code changes.
Fix: shell out to 'bd export' as a subprocess with BD_GIT_HOOK cleared,
so the JSONL snapshot is written and optionally staged before the commit
completes. This restores the atomic code+issues workflow users expect.
Refs: GH#2489, GH#1863
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: correct "initialises" misspelling caught by golangci-lint
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Replaces the deprecated github.com/charmbracelet/lipgloss v1 with
charm.land/lipgloss/v2. Key changes:
- Import path: github.com/charmbracelet/lipgloss → charm.land/lipgloss/v2
- AdaptiveColor replaced with LightDark() for controlled background
detection (avoids compat package which probes terminal at init time,
reintroducing the OSC 11 leak from GH#1303)
- SetColorProfile() replaced with DisableColors() function that resets
all styles to plain text for hook/non-TTY contexts
- Colors and styles initialized in init() for controlled lifecycle
- Removes direct dependency on github.com/muesli/termenv
Supersedes Renovate PR #2841 which only updated go.mod without fixing
import paths or API changes.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The 30s default was killing legitimate chained pre-commit pipelines
(linters, formatters, type-checkers) before they could complete.
Increase to 300s with BEADS_HOOK_TIMEOUT env var documented as
escape hatch. Users can still Ctrl-C out of truly hung hooks.
PR: #2746
Co-Authored-By: matt wilkie <maphew@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
When beads redirects core.hooksPath, preserve all user hooks from the
original hooks directory (not just the ones beads manages). Skip
directories, dotfiles, and .sample files. Fixes hook loss for non-managed
hooks like commit-msg, pre-rebase, etc.
PR: #2738
Co-Authored-By: Gissur Simonarson <gzur@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Remove Gas Town identity infrastructure from beads hooks:
- agentIdentity struct and compound format parsing
- GT_ROLE env var detection, path-based detection
- gt mol status integration (getPinnedMolecule)
- Rig/Role/Molecule commit trailers
Replace with simple BD_ACTOR env var check for Executed-By trailer.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
When bd init installs hooks to .beads/hooks/ and sets a local
core.hooksPath, it shadows any global core.hooksPath the user had
configured, silently disabling their global hooks. Copy non-beads
hooks from the previously effective hooks directory into the target
before the override takes effect.
Fixes#2729
Co-Authored-By: gzur <gzur@gzur.net>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
git resolves relative core.hooksPath relative to the working tree root,
so in worktrees .beads/hooks resolves to <worktree>/.beads/hooks/ which
does not exist. Using an absolute path ensures hooks are found regardless
of which worktree the git operation runs in.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Wrap `bd hooks run` in generated hook sections with a configurable timeout
(default 30s, override via BEADS_HOOK_TIMEOUT) so a hung process cannot
block git operations indefinitely. Handle exit code 124 (timeout) and
exit code 3 (database not initialized) as non-fatal warnings.
Closes#2453Closes#2449
Co-Authored-By: Marco Del Pin <marco.delpin@gmail.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add recursion depth guard (maxInjectDepth=5) to prevent stack overflow
- Handle reversed markers (END before BEGIN) in both inject and remove
- Use hookMigrationWriteFromHookFile for marker_broken to preserve user
content instead of discarding it with write-from-template
- Extract removeOrphanedBeginBlock and removeMarkerLine helpers
- Remove dead hookSectionEnd constant (replaced by hookSectionEndPrefix)
- Add tests for reversed markers and versioned END marker matching
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Executed-By: beads/crew/emma
Rig: beads
Role: crew
END marker now includes version (e.g. "# --- END BEADS INTEGRATION v0.58.0 ---")
matching the BEGIN marker format. All marker matching uses hookSectionEndPrefix
for backward compatibility with unversioned END markers.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Executed-By: beads/crew/emma
Rig: beads
Role: crew
When a BEGIN marker exists without a matching END (as in v0.57.0 format),
injectHookSection now removes the stale block before injecting the new
section, instead of appending a duplicate. removeHookSection also handles
orphaned BEGIN markers. Matching now uses hookSectionEndPrefix for
forward compatibility with versioned END markers.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Executed-By: beads/crew/emma
Rig: beads
Role: crew
Our shell shims set BD_GIT_HOOK=1 before invoking bd, but third-party
hook runners (lefthook, husky, etc.) call 'bd hooks run' directly
without it. The ui package init() has already set the lipgloss color
profile by the time Run executes, so we must both set the env var and
reset the profile to Ascii to prevent termenv OSC 11 background queries.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Three fixes to hooks.go:
1. uninstallHooks() now resets core.hooksPath when it points to
.beads/hooks or .beads-hooks, preventing silently broken hooks
2. Remove misleading --chain success message that claimed hooks were
renamed to .old (section markers make --chain a no-op)
3. Update help text to describe what hooks actually do (run chained
hooks, add trailers) instead of claiming sync/validate behavior
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Executed-By: beads/polecats/jade
Rig: beads
Role: polecats
The embed directive loaded 5 hook template files into the binary, but
installHooksWithOptions() only used map keys for iteration — content was
always generated dynamically by generateHookSection(). Templates also had
a hardcoded v0.56.1 version that drifted from the dynamic Version variable.
- Remove //go:embed directive, hooksFS, and getEmbeddedHooks()
- Replace with static managedHookNames slice
- Change installHooksWithOptions to accept []string instead of map[string]string
- Remove dead installHooks() wrapper (never called)
- Delete cmd/bd/templates/hooks/ directory (5 template files)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Executed-By: beads/polecats/granite
Rig: beads
Role: polecats
Use BEGIN/END section markers in git hooks, consistent with how
AGENTS.md integration already works. This preserves user content
outside the markers across bd init re-runs, hook upgrades, and
bd hooks install.
Changes:
- Add hookSectionBeginPrefix/hookSectionEnd constants and helpers:
generateHookSection(), injectHookSection(), removeHookSection()
- Update installHooksWithOptions() to inject sections into existing
hook files instead of replacing them. Legacy bd hooks (shim/inline)
are migrated to section format; non-bd hooks get sections appended.
- Update uninstallHooks() to remove only the beads section, preserving
user content. Files with only a shebang remaining are deleted.
- Update getHookVersion() to scan the entire file (not just first 15
lines) and recognize section markers anywhere.
- Update hooksInstalled()/detectExistingHooks() to recognize section
marker format as bd hooks.
- Update buildPreCommitHook/buildPostMergeHook/buildJJPreCommitHook
in init_git_hooks.go to use section markers.
- Update all 5 hook templates to section marker format.
- Add comprehensive tests for section injection, removal, install
idempotency, and uninstall with user content preservation.
Fixes#1380
Amp-Thread-ID: https://ampcode.com/threads/T-019ca7b3-8137-7218-8707-b7ae93c31ab5
Co-authored-by: Amp <amp@ampcode.com>
CheckGitHooks() guarded on Version != "" which skipped inline bd hooks
(empty version string), while hooksNeedUpdate() correctly treated them as
outdated. Replace the guard with IsBdHook to handle inline hooks consistently.
Consolidate hooksNeedUpdate() to delegate to CheckGitHooks(), eliminating
duplicated version-checking logic.
Follow-up to GH#1466 / PR #2008.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: auto-update stale hooks during bd init (GH#1466)
bd init now detects outdated git hooks and reinstalls them, not just
missing ones. Previously, hooksInstalled() only checked existence and
signature — hooks from older CLI versions were never updated.
Adds hooksNeedUpdate() which uses getHookVersion() to compare hook
version markers against the current CLI version. Shim hooks are skipped
(they delegate to bd hooks run and are never stale).
Adds bd-hooks-version markers to all inline hook templates so newly
installed hooks are properly versioned and not flagged as outdated on
subsequent bd init runs.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: address review findings for stale hooks detection
- Fix misleading test: "non-executable hook files" now uses current
version to isolate the permissions variable, documenting that
hooksNeedUpdate checks version not permissions
- Distinguish file-not-found from permission/IO errors in
hooksNeedUpdate — warn on stderr for non-NotExist errors instead
of silently continuing
- Add user feedback distinguishing "update" from fresh "install" —
prints "Updating hooks to version X.Y.Z..." when overwriting
existing outdated hooks
- Document calling context constraint in hooksNeedUpdate doc comment
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: check scanner.Err in getHookVersion and handle read errors in hooksNeedUpdate
getHookVersion now checks scanner.Err() after reading hook files,
surfacing I/O errors instead of silently misclassifying hooks as
non-bd (which caused hooksNeedUpdate to skip them with no warning).
hooksNeedUpdate now tracks read errors and returns true when hooks
exist but couldn't be read, attempting re-install rather than silently
skipping the update.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Remove FindJSONLPath, FindJSONLInDir, JSONLExport config field, JSONL
bootstrap detection, post-merge JSONL import hook, and findActualJSONLFile.
Update hasBeadsProjectFiles to check for dolt/ directory instead of JSONL
files. Simplify error messages and hook descriptions to remove JSONL
references. Update comments across types, storage, and doctor subsystem.
29 files changed, -882/+79 lines.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1. FORMATTING: gofmt 14 files.
2. LINT:
- Delete dead code cmd/bd/bootstrap.go (unused bootstrapEmbeddedDolt)
- Prefix unused 'actor' param in wisps.go updateWisp with _
- Prefix unused 'ctx' param in telemetry.go buildTraceProvider with _
3. TESTS: Add skipIfNoDolt to test helpers that call dolt.New() without
a running test server. In CI (no dolt installed), these tests now skip
instead of failing with "server unreachable at 127.0.0.1:3307".
Delete TestOpenFromConfig_Embedded and TestOpenFromConfig_DefaultsToEmbedded
which tested removed embedded Dolt functionality.
Fixed packages: beads_test, cmd/bd, cmd/bd/doctor, cmd/bd/doctor/fix,
internal/tracker, internal/utils
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Convert ~250 instances of direct fmt.Fprintf(os.Stderr)+os.Exit(1)
to FatalError/FatalErrorWithHint/FatalErrorRespectJSON across 54 files.
Complex multi-line messages, warnings, loop-internal errors, and
JSON-branching patterns intentionally preserved where the helpers
do not fit cleanly.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
On Windows and WSL with NTFS-mounted repos, `bd hooks install` can
write hook files with CRLF line endings. This causes git to fail with:
/usr/bin/env: 'sh\r': No such file or directory
Two sources of CRLF contamination:
1. Embedded hook templates may have CRLF when built on Windows/NTFS
(go:embed captures files as-is from disk)
2. The prepare-commit-msg template already contained CRLF
Fix:
- Normalize embedded hook content with strings.ReplaceAll("\r\n", "\n")
before writing to disk in both hooks.go and init_git_hooks.go
- Add .gitattributes rules to enforce LF for shell scripts and hook
templates regardless of platform
In dolt-native mode, Dolt is the source of truth and JSONL files are
not needed. Two regressions reintroduced unconditional JSONL export:
1. 10821225 (Feb 17) reverted bd sync from the no-op introduced in
d6a8462a (Feb 15), re-adding JSONL export under the rationale that
"hooks, scripts still expect bd sync to produce an up-to-date JSONL
file." This is only true in git-portable mode.
2. ff7244b6 (Feb 18) rewrote hooks.go to remove the sync-branch
pipeline, but inadvertently dropped the dolt-native guard from
runPrePushHook that was added in 9e2aa962 (Jan 25). This caused
pre-push to block pushes due to "uncommitted JSONL changes" that
the hooks themselves were generating — a circular trap.
Add sync.mode=dolt-native guards to all hook and sync paths:
- runPreCommitHook: skip JSONL flush and auto-staging
- hookPreCommitDolt: skip Dolt->JSONL export
- runPrePushHook: skip JSONL dirty-state check (restores 9e2aa962)
- runPostMergeHook: skip JSONL->Dolt import
- runPostCheckoutHook: skip JSONL->Dolt import
- bd sync: skip JSONL export, preserve Dolt remote push
Fixes: #1863
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Executed-By: beads/crew/leeloo
Rig: beads
Role: crew
Delete daemon_compat.go which contained the deprecated --no-daemon flag,
boolToFlag, truncateString, and formatUptime utility functions. Remove
dead isDaemonAutoSyncing code path from prime.go. Clean up --no-daemon
args from hook sync invocations and daemon config references.
Part of dolt-1s40: Dolt-Native Beads v2
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Executed-By: beads/crew/emma
Rig: beads
Role: crew
- Remove auto-detection of running dolt sql-server in bd init; server
mode now requires explicit --server flag
- Delete dead init_dolt_cgo.go and init_dolt_nocgo.go
- Doctor server check: embedded mode returns StatusOK not StatusWarning
- Update configfile comments to reflect embedded as default
- Fix store.go initSchemaOnDB using wrong receiver (s.db → db)
- Guard auto-import in dolt-native sync mode
- Update sync mode defaults and staleness checks for embedded-first
Closes: gt-dolt-embedded-default
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
The pre-push hook runs 'bd sync --flush-only' which may create uncommitted
changes to .beads/issues.jsonl. Without auto-staging these changes, the
subsequent uncommitted-changes check would fail, causing an infinite loop
where users cannot push without --no-verify.
This fix adds auto-staging after flush, matching the behavior of the
pre-commit hook.
Fixes#1208
Remove crew detection as well - beads should know nothing about
Gas Town roles. All role detection (crew, polecat, witness, etc.)
should be handled by gastown.
Changes:
- parseAgentIdentity: only accepts compound format (rig/role/name)
- detectAgentFromPath: now returns nil (deprecated)
Gastown should set GT_ROLE in compound format (e.g., beads/crew/jane)
rather than relying on beads to expand simple formats.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Remove hardcoded Gas Town role detection (polecat, witness, refinery,
mayor, deacon) from bd hooks. These are Gas Town concepts and should
be handled by gastown, not beads core.
Keeps crew role detection as it is a shared concept.
Closes bd-7nd6t
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
The pre-push hook was checking for uncommitted JSONL changes even in
dolt-native sync mode where JSONL files don't exist. This blocked pushes
unnecessarily. Now skips the check entirely when sync.mode is dolt-native.
Fixes: hq-6ymh
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Executed-By: mayor
Role: mayor
- Add jsonlFilePaths constant to eliminate duplicate file list definitions
- Update all usages in hook.go and hooks.go to use the shared constant
- Include beads.jsonl for backwards compatibility with older installations
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
When bd init installs hooks with chaining, it renames the user's original
hook to .old and creates a new bd hook that chains to it. If bd doctor
later runs bd hooks install --chain, it would:
1. Not recognize the inline bd hook (from bd init) as a bd hook
2. Rename it to .old, overwriting the user's original hook
3. Install a new shim hook
This fix addresses two root causes:
1. Detection mismatch: areBdShimsInstalled() and getHookVersion() now
recognize inline bd hooks (which have "# bd (beads)" marker) in
addition to shim hooks (which have "# bd-shim" marker)
2. No .old protection: bd hooks install --chain now checks if .old
already exists before renaming, preserving the user's original hook
Fixes#1120
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit implements the git hook infrastructure for Dolt storage backend
as specified in the design document.
Changes:
- Add `bd hook` command (singular) for git hooks to call directly
- Implement per-worktree export state tracking in .beads/export-state/
- Add post-checkout guard to only import if JSONL changed
- Add hook chaining configuration (chain_strategy, chain_timeout_ms)
- Support hooks in .beads/hooks/ directory with git config core.hooksPath
- Implement branch-then-merge import pattern for Dolt storage
- Update bd init to install hooks to .beads/hooks/ for Dolt backend
- Add --beads flag to `bd hooks install` command
The new `bd hook` command supports:
- pre-commit: Export database to JSONL, stage changes
- post-merge: Import JSONL to database after pull/merge
- post-checkout: Import JSONL after branch checkout (with guard)
For Dolt backend, uses branch-then-merge pattern:
1. Create jsonl-import branch
2. Import JSONL data to branch
3. Merge branch to main (cell-level conflict resolution)
4. Delete branch on success
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Git hooks are shared across all worktrees and live in the common git
directory (e.g., /repo/.git/hooks), not the worktree-specific directory
(e.g., /repo/.git/worktrees/feature/hooks).
The core issue was in GetGitHooksDir() which used GetGitDir() instead
of GetGitCommonDir(). This caused hooks to be installed to/read from
the wrong location when running in a worktree.
Additionally, several places in the codebase manually constructed
hooks paths using gitDir + "hooks" instead of calling GetGitHooksDir().
These have been updated to use the proper worktree-aware path.
Affected areas:
- GetGitHooksDir() now uses GetGitCommonDir()
- CheckGitHooks() uses GetGitHooksDir()
- installHooks/uninstallHooks use GetGitHooksDir()
- runChainedHook() uses GetGitHooksDir()
- Doctor checks use git-common-dir for hooks paths
- Reset command uses GetGitCommonDir() for hooks and beads-worktrees
Symptoms that this fixes:
- Chained hooks (pre-commit.old) not running in worktrees
- bd hooks install not finding/installing hooks correctly in worktrees
- bd hooks list showing incorrect status in worktrees
- bd doctor reporting incorrect hooks status in worktrees
Co-authored-by: Zain Rizvi <4468967+ZainRizvi@users.noreply.github.com>
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.