* fix(setup): keep bd setup claude --global's section in ~/.claude/CLAUDE.md bd setup claude --global put its hook in ~/.claude/settings.json but wrote the managed beads section into the current directory's CLAUDE.md, and --remove --global stripped it from there. Run from $HOME it created ~/CLAUDE.md with project scaffolding, which stops Claude Code reading AGENTS.md in projects below it; run inside a project it removed the section that project's own install had written, leaving its hooks. A global install and removal now manage the section in Claude Code's user-level ~/.claude/CLAUDE.md (created holding only the section, no project scaffolding), with hints naming bd setup claude --global. With global or plugin hooks, --check reports that file when the project's instructions have no beads section; a project install is still judged on the project's file alone. Project installs are unchanged. Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(setup): render the user-level CLAUDE.md section independently of the project ~/.claude/CLAUDE.md is shared by every project, but bd setup claude --global rendered and --check judged its section with the current directory's beads config (sync.remote, sync.git-remote, no-push). From a project with a remote and one without, --check called the other's install stale and its hint flipped the file back. The user-level file now always renders with the default options, so install and --check agree across projects. Also pin --check's fallback to the project's file and project hint when neither file has a section, tell existing --global users to re-run it, and name ~/.claude/CLAUDE.md in the ide-setup recipe table. Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(setup): judge the user-level Claude files from $HOME and ~/.claude Run from the home directory, the project's .claude/settings.json is the global one, so bd setup claude --check reported a global install as project hooks and judged ~/CLAUDE.md; its "Run: bd setup claude" hint then created the ~/CLAUDE.md a global install exists to avoid. Run from ~/.claude, the project's CLAUDE.md is the user-level file, and --check judged it with that directory's render options and the project hint. --check now reports hooks as global from $HOME and judges the user-level file there and from ~/.claude with the fixed options and the --global hint. With user-level hooks and no section in either file it names --global unless the project has its own CLAUDE.md. A --remove run from $HOME, which removes the global hooks, also removes the user-level section. The init agent-artifact test ran bd setup claude with HOME at the project, so its checks would now see a home directory; it gets a separate HOME and its goldens are unchanged. Rebase note (maintainer): rebased onto main after #7678 merged; main's agent-artifact harness already runs bd with a separate HOME, so this commit's harness edits to cmd/bd/agent_artifacts_embedded_test.go were dropped. Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * test(setup): pin --check's user-level choice beside project instructions With global hooks, --check judges ~/.claude/CLAUDE.md when the project's own CLAUDE.md has no beads section but the user-level file has one, and when run from the home directory whose ~/CLAUDE.md has no section. Nothing exercised either half of that condition: replacing it with false left the suite and goldens green. Add a subtest for each; each now fails when its half of the condition is dropped. Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(setup): name --global when --check finds no hooks from $HOME From the home directory --check with no hooks said 'Run: bd setup claude'. Following it runs a project install there, which creates ~/CLAUDE.md with project scaffolding, the file that stops Claude Code reading AGENTS.md in the projects below it. The missing-section hint at home already names --global; make the missing-hooks hint match, with a subtest. Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * docs(setup): qualify the --global CHANGELOG entry; watch ~/.claude/CLAUDE.md The CHANGELOG said --check from the home directory judges the user-level files, but a beads section still in ~/CLAUDE.md is judged instead, and the --global hint for a missing section applies only when the project has no CLAUDE.md of its own. Say both, mention the new missing-hooks hint at home, and re-wrap the paragraph. The embedded agent-artifact harness comment said a global install writes $HOME/CLAUDE.md; it now writes $HOME/.claude/CLAUDE.md. Track that path too and reword the comment. The bd init goldens do not change. Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(setup): word the user-level CLAUDE.md section for repositories that use beads bd setup claude --global writes its section to ~/.claude/CLAUDE.md, which Claude Code loads in every project, but rendered it with the project wording: "This project uses bd (beads)" and "Use bd for ALL task tracking — do NOT use TodoWrite". In a repository without beads that told the agent to give up its own task tools and pointed it at bd, whose answer there is "run 'bd init'", while the global hook, bd prime, stays silent outside a workspace. RenderOpts.UserLevel rewords the opening line and the task-tracking rules of both profiles so they apply only in beads repositories. The global env fixes it through agents.UserLevelRenderOpts, so install, in-place update and --check agree on the hash from every directory, and a project-worded section left in ~/.claude/CLAUDE.md reads as stale and is reworded by --global. The new minimal-user and full-user variants are pinned by golden and hash; the project rendering is unchanged. Also pin sameDir's symlink following: --check from a symlink to $HOME or to ~/.claude still judges the user-level files. Refreshed onto main past #7692, whose --remove takes the blank lines around the section with it and whose setup appends a section after one blank line: claude-setup-global-beside-project-install.golden no longer records the old hole (an extra blank line before the appended section, two left behind by --remove --global). Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
291 lines
11 KiB
Go
291 lines
11 KiB
Go
package agents
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
_ "embed"
|
|
"errors"
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// Profile identifies which template variant to render.
|
|
type Profile string
|
|
|
|
const (
|
|
// ProfileFull is the command-heavy profile for hookless agents (Codex, Factory, Mux, etc.).
|
|
ProfileFull Profile = "full"
|
|
// ProfileMinimal is the pointer-only profile for hook-enabled agents (Claude, Gemini).
|
|
ProfileMinimal Profile = "minimal"
|
|
)
|
|
|
|
// MarkerVersion is the current format version for BEGIN BEADS INTEGRATION markers.
|
|
// Bump this when the marker format itself changes (not when template content changes).
|
|
const MarkerVersion = 1
|
|
|
|
var (
|
|
// ErrNoSection is returned by ReplaceSection when no BEGIN marker exists.
|
|
ErrNoSection = errors.New("no beads section markers found")
|
|
// ErrMalformedMarkers is returned when markers exist but are invalid
|
|
// (e.g., END before BEGIN, or BEGIN without END).
|
|
ErrMalformedMarkers = errors.New("malformed beads section markers")
|
|
)
|
|
|
|
//go:embed defaults/beads-section-minimal.md
|
|
var beadsSectionMinimal string
|
|
|
|
//go:embed defaults/beads-section-codex.md
|
|
var beadsSectionCodex string
|
|
|
|
// SectionMeta holds metadata parsed from a BEGIN BEADS INTEGRATION marker.
|
|
type SectionMeta struct {
|
|
Version int
|
|
Profile Profile
|
|
Hash string
|
|
}
|
|
|
|
// RenderOpts controls conditional content in rendered templates.
|
|
type RenderOpts struct {
|
|
// HasRemote indicates whether a Dolt remote is configured.
|
|
// When false, "bd dolt push" is omitted from session-completion instructions.
|
|
HasRemote bool
|
|
// NoPush indicates the rig is declared local-only (no-push: true in config).
|
|
// When true, "bd dolt push" is omitted regardless of HasRemote.
|
|
NoPush bool
|
|
// UserLevel words the section for a user-level instructions file, such as
|
|
// ~/.claude/CLAUDE.md, that the agent loads in every repository: instead
|
|
// of stating that the current project uses bd, it applies only in
|
|
// repositories that do, and so do its task-tracking rules.
|
|
UserLevel bool
|
|
}
|
|
|
|
// omitsDoltPush reports whether rendered instructions leave out "bd dolt push":
|
|
// no Dolt remote is configured, or the workspace is declared no-push. The
|
|
// managed section and the AGENTS.md template around it share this rule.
|
|
func (o RenderOpts) omitsDoltPush() bool {
|
|
return !o.HasRemote || o.NoPush
|
|
}
|
|
|
|
// DefaultRenderOpts returns opts that assume a remote is configured,
|
|
// preserving backward-compatible behavior for callers that don't pass opts.
|
|
func DefaultRenderOpts() RenderOpts {
|
|
return RenderOpts{HasRemote: true}
|
|
}
|
|
|
|
// UserLevelRenderOpts returns the fixed opts for a user-level instructions
|
|
// file. No one repository's beads config applies to it, so it assumes a
|
|
// remote, as DefaultRenderOpts does.
|
|
func UserLevelRenderOpts() RenderOpts {
|
|
return RenderOpts{HasRemote: true, UserLevel: true}
|
|
}
|
|
|
|
// RenderSection returns the beads integration section for the given profile,
|
|
// wrapped in markers that include version, profile, and hash metadata for freshness detection.
|
|
// Assumes a Dolt remote is configured (backward-compatible). Use RenderSectionWithOpts
|
|
// to control conditional content.
|
|
func RenderSection(profile Profile) string {
|
|
return RenderSectionWithOpts(profile, DefaultRenderOpts())
|
|
}
|
|
|
|
// RenderSectionWithOpts renders the beads integration section with conditional content
|
|
// controlled by opts. When opts.HasRemote is false, "bd dolt push" is omitted from
|
|
// session-completion instructions.
|
|
func RenderSectionWithOpts(profile Profile, opts RenderOpts) string {
|
|
body := templateBodyWithOpts(profile, opts)
|
|
hash := computeHash(body)
|
|
beginMarker := fmt.Sprintf("<!-- BEGIN BEADS INTEGRATION v:%d profile:%s hash:%s -->", MarkerVersion, profile, hash)
|
|
return beginMarker + "\n" + body + "\n<!-- END BEADS INTEGRATION -->\n"
|
|
}
|
|
|
|
// CodexSectionBody returns the setup-managed Codex guidance body without
|
|
// Codex-specific markers.
|
|
func CodexSectionBody() string {
|
|
return normalizeEmbeddedMarkdown(beadsSectionCodex)
|
|
}
|
|
|
|
// ReplaceSection replaces an existing beads integration section in content with a
|
|
// freshly rendered section for the given profile. Returns the (possibly unchanged)
|
|
// content, whether it was modified, and any error.
|
|
// Assumes a Dolt remote is configured (backward-compatible). Use ReplaceSectionWithOpts
|
|
// to control conditional content.
|
|
//
|
|
// Errors:
|
|
// - ErrNoSection: no BEGIN marker found (caller should append instead)
|
|
// - ErrMalformedMarkers: BEGIN exists but END is missing or appears before BEGIN
|
|
func ReplaceSection(content string, profile Profile) (string, bool, error) {
|
|
return ReplaceSectionWithOpts(content, profile, DefaultRenderOpts())
|
|
}
|
|
|
|
// ReplaceSectionWithOpts replaces an existing beads integration section in content with a
|
|
// freshly rendered section for the given profile and opts.
|
|
func ReplaceSectionWithOpts(content string, profile Profile, opts RenderOpts) (string, bool, error) {
|
|
beginIdx := strings.Index(content, "<!-- BEGIN BEADS INTEGRATION")
|
|
if beginIdx == -1 {
|
|
return content, false, ErrNoSection
|
|
}
|
|
|
|
endMarker := "<!-- END BEADS INTEGRATION -->"
|
|
endIdx := strings.Index(content, endMarker)
|
|
if endIdx == -1 {
|
|
return "", false, fmt.Errorf("%w: BEGIN marker at offset %d but no END marker", ErrMalformedMarkers, beginIdx)
|
|
}
|
|
if endIdx < beginIdx {
|
|
return "", false, fmt.Errorf("%w: END marker at offset %d before BEGIN at %d", ErrMalformedMarkers, endIdx, beginIdx)
|
|
}
|
|
|
|
// Check if already current (hash freshness)
|
|
firstLine := content[beginIdx:]
|
|
if nl := strings.Index(firstLine, "\n"); nl != -1 {
|
|
firstLine = firstLine[:nl]
|
|
}
|
|
meta := ParseMarker(firstLine)
|
|
if meta != nil && meta.Hash == CurrentHashWithOpts(profile, opts) && meta.Profile == profile {
|
|
return content, false, nil // already up to date
|
|
}
|
|
|
|
// Replace section: consume exactly one trailing newline after END marker
|
|
endOfEndMarker := endIdx + len(endMarker)
|
|
if endOfEndMarker < len(content) && content[endOfEndMarker] == '\n' {
|
|
endOfEndMarker++
|
|
}
|
|
|
|
replaced := content[:beginIdx] + RenderSectionWithOpts(profile, opts) + content[endOfEndMarker:]
|
|
return replaced, true, nil
|
|
}
|
|
|
|
// CurrentHash returns the hash of the current template body for a profile.
|
|
// Callers can compare this against a parsed marker's hash to detect staleness.
|
|
// Assumes a Dolt remote is configured (backward-compatible).
|
|
func CurrentHash(profile Profile) string {
|
|
return CurrentHashWithOpts(profile, DefaultRenderOpts())
|
|
}
|
|
|
|
// CurrentHashWithOpts returns the hash for a profile with the given render opts.
|
|
func CurrentHashWithOpts(profile Profile, opts RenderOpts) string {
|
|
return computeHash(templateBodyWithOpts(profile, opts))
|
|
}
|
|
|
|
// ParseMarker parses a BEGIN BEADS INTEGRATION marker line and returns its metadata.
|
|
// Returns nil if the line is not a valid begin marker.
|
|
// Supports both legacy (no metadata) and new (profile + hash) formats.
|
|
func ParseMarker(line string) *SectionMeta {
|
|
line = strings.TrimSpace(line)
|
|
if !strings.HasPrefix(line, "<!-- BEGIN BEADS INTEGRATION") {
|
|
return nil
|
|
}
|
|
|
|
meta := &SectionMeta{}
|
|
|
|
// Extract the content between "<!-- BEGIN BEADS INTEGRATION" and "-->"
|
|
inner := strings.TrimPrefix(line, "<!-- BEGIN BEADS INTEGRATION")
|
|
inner = strings.TrimSuffix(inner, "-->")
|
|
inner = strings.TrimSpace(inner)
|
|
|
|
if inner == "" {
|
|
// Legacy format: <!-- BEGIN BEADS INTEGRATION -->
|
|
return meta
|
|
}
|
|
|
|
// Parse key:value pairs
|
|
for _, part := range strings.Fields(inner) {
|
|
k, v, ok := strings.Cut(part, ":")
|
|
if !ok {
|
|
continue
|
|
}
|
|
switch k {
|
|
case "v":
|
|
if n, err := strconv.Atoi(v); err == nil {
|
|
meta.Version = n
|
|
}
|
|
case "profile":
|
|
meta.Profile = Profile(v)
|
|
case "hash":
|
|
meta.Hash = v
|
|
}
|
|
}
|
|
|
|
return meta
|
|
}
|
|
|
|
// templateBody returns the raw body content (without markers) for a profile.
|
|
// Backward-compatible wrapper that assumes a Dolt remote is configured.
|
|
func templateBody(profile Profile) string {
|
|
return templateBodyWithOpts(profile, DefaultRenderOpts())
|
|
}
|
|
|
|
// templateBodyWithOpts returns the raw body content (without markers) for a
|
|
// profile, with conditional content controlled by opts.
|
|
func templateBodyWithOpts(profile Profile, opts RenderOpts) string {
|
|
var body string
|
|
switch profile {
|
|
case ProfileMinimal:
|
|
body = normalizeEmbeddedMarkdown(beadsSectionMinimal)
|
|
default:
|
|
// Full profile uses the same body as the legacy beads-section.md
|
|
// Strip the existing markers from the embedded content. Normalize CRLF→LF
|
|
// first so a Windows-checkout build (where //go:embed picks up CRLF bytes
|
|
// from the working tree) still matches the LF-only prefix/suffix below.
|
|
// Without this, the legacy markers stay in the body and RenderSection
|
|
// wraps them again, producing doubled markers in the installed file (#3552).
|
|
body = strings.ReplaceAll(beadsSection, "\r\n", "\n")
|
|
body = strings.TrimRight(body, "\n")
|
|
body = strings.TrimPrefix(body, "<!-- BEGIN BEADS INTEGRATION -->\n")
|
|
body = strings.TrimSuffix(body, "\n<!-- END BEADS INTEGRATION -->")
|
|
}
|
|
|
|
if opts.omitsDoltPush() {
|
|
body = stripDoltPushReferences(body)
|
|
}
|
|
if opts.UserLevel {
|
|
body = userLevelWording.Replace(body)
|
|
}
|
|
|
|
return body
|
|
}
|
|
|
|
// userLevelScope opens a user-level section: the agent loads that file in
|
|
// every repository, including ones that do not use beads.
|
|
const userLevelScope = "This Beads block applies only in beads repositories: repositories that use **bd (beads)** for issue tracking, with a `.beads/` directory. Ignore it in any other repository."
|
|
|
|
// userLevelWording rewords the lines of both profiles' bodies that state the
|
|
// current project uses bd, or that set a task-tracking rule with no condition,
|
|
// so they apply only in beads repositories (RenderOpts.UserLevel).
|
|
var userLevelWording = strings.NewReplacer(
|
|
"This project uses **bd (beads)** for issue tracking. Run `bd prime`",
|
|
userLevelScope+" In a beads repository, run `bd prime`",
|
|
"- Use `bd` for ALL task tracking",
|
|
"- In a beads repository, use `bd` for ALL task tracking",
|
|
"- Use `bd remember` for durable project facts",
|
|
"- In a beads repository, use `bd remember` for durable project facts",
|
|
"**IMPORTANT**: This project uses **bd (beads)** for ALL issue tracking.",
|
|
userLevelScope+"\n\n**IMPORTANT**: In a beads repository, use **bd (beads)** for ALL issue tracking.",
|
|
"- ✅ Use bd for ALL task tracking",
|
|
"- ✅ In a beads repository, use bd for ALL task tracking",
|
|
)
|
|
|
|
func normalizeEmbeddedMarkdown(content string) string {
|
|
return strings.TrimRight(strings.ReplaceAll(content, "\r\n", "\n"), "\n")
|
|
}
|
|
|
|
// stripDoltPushReferences removes "bd dolt push" directives from the template body.
|
|
// Strips the indented code-block line from session completion, and the
|
|
// informational Auto-Sync bullet that references dolt push/pull.
|
|
func stripDoltPushReferences(body string) string {
|
|
// Session completion code block: exactly " bd dolt push\n" (3-space indent).
|
|
// Pad both ends with "\n" so a single anchored ReplaceAll handles the line
|
|
// whether it appears at the start, middle, or end of the body, without
|
|
// accidentally matching a 4-space indented variant via substring.
|
|
const pushLine = " bd dolt push\n"
|
|
padded := "\n" + body + "\n"
|
|
padded = strings.ReplaceAll(padded, "\n"+pushLine, "\n")
|
|
body = padded[1 : len(padded)-1]
|
|
// Auto-Sync informational bullet (full profile only)
|
|
body = strings.ReplaceAll(body, "- Use `bd dolt push`/`bd dolt pull` for remote sync\n", "")
|
|
return body
|
|
}
|
|
|
|
// computeHash returns the first 8 hex chars of the SHA-256 of the body.
|
|
func computeHash(body string) string {
|
|
h := sha256.Sum256([]byte(body))
|
|
return fmt.Sprintf("%x", h[:4])
|
|
}
|