mirror of
https://github.com/runbear-io/beardrive.git
synced 2026-08-25 08:08:08 +02:00
feat(hooks): user-scope agent sync hooks, one-command setup, --only scoping (#71)
* feat(hooks): register agent sync hooks per machine, not per project Agent platforms read hook config only from the directory a session starts in — never a parent, never a subfolder. Project-level hooks therefore fired only for sessions that happened to start at the mount, and, living inside a synced folder, they replicated one machine's agent config to the whole team (a second writer of a file bdrive already owns). Claude Code additionally ignores project hooks until the folder is trusted, so in practice they were often inert without any visible sign. Hooks now go to each platform's user config, once per machine, covering every session in every folder; the existing shell guard keeps them a no-op outside BearDrive projects. Install migrates away blocks older versions wrote into projects, and `bdrive hooks uninstall` removes ours while leaving foreign hooks untouched. Setup is also one command now. init absorbs the skill install, prints the hub link, and takes --server, so connecting to a named hub no longer needs a separate login; the runbook forbids preflight and command chaining, since each distinct command costs the user a permission prompt. For plugin users a PreToolUse hook auto-approves bdrive's own setup subcommands — narrowly: any shell operator in the command disqualifies it. Also drops --shared in favor of `init . --only wiki,docs`, which writes a managed block of .bdriveignore rules instead of a second scope mechanism. Because those rules sync, `sync --prune` now refuses on a scoped project rather than stripping everything outside the scope from the hub for everyone. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016aYntCWwdUhpzUfEk3ddyJ * docs: fix stale claims an audit found against the new CLI An audit of every doc surface against the code turned up claims that the user-scope hook move and the one-command init made false: project-level hooks "riding the repo", the Claude trust prompt, Codex's //hooks project layer, `--no-hooks` skipping the skill (it does not), prune reconciling against a per-device scope (it now refuses on a scoped project), and `--scan-interval`/`--remote-interval` documented as init flags when they only exist on `bdrive daemon run`. Also documents the surface added today — `--server`, `bdrive hooks uninstall`, and the plugin's PreToolUse auto-approval — refreshes the two sample `init` transcripts to the real output, and corrects hook matchers that had drifted from agenthooks.go. `bdrive scope` told users to narrow an existing mount with `bdrive init . --only <dirs>`, which resume then ignored — a dead end. Init now applies --only on resume, writing the scope block, so the advice works. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016aYntCWwdUhpzUfEk3ddyJ --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
22461a3b4f
commit
4e34d03e14
@@ -6,10 +6,18 @@
|
||||
// command, pipe event JSON (with a session_id) on stdin — so one hook command
|
||||
// works everywhere; only the config file format and event names differ:
|
||||
//
|
||||
// claude .claude/settings.json UserPromptSubmit / PostToolUse (project)
|
||||
// codex .codex/hooks.json UserPromptSubmit / PostToolUse (project)
|
||||
// gemini .gemini/settings.json BeforeAgent / AfterTool (project)
|
||||
// hermes ~/.hermes/config.yaml pre_llm_call / post_tool_call (user)
|
||||
// claude ~/.claude/settings.json UserPromptSubmit / PostToolUse
|
||||
// codex ~/.codex/hooks.json UserPromptSubmit / PostToolUse
|
||||
// gemini ~/.gemini/settings.json BeforeAgent / AfterTool
|
||||
// hermes ~/.hermes/config.yaml pre_llm_call / post_tool_call
|
||||
//
|
||||
// Every config is USER-level, written once per machine. Platforms read hook
|
||||
// config only from the directory a session starts in — never a parent, never
|
||||
// a subfolder — so a per-project file would fire only for sessions that
|
||||
// happen to start there, and (living inside a mount) would sync to the whole
|
||||
// team. One user-level registration covers every session in every folder;
|
||||
// the guard below makes it a no-op outside BearDrive projects. Install
|
||||
// migrates away any project-level hooks earlier versions wrote.
|
||||
//
|
||||
// The hook syncs the project and stamps changes with "<agent> session <id>"
|
||||
// (see `bdrive sync --note`), so hub history links every change to the agent
|
||||
@@ -54,14 +62,31 @@ type Result struct {
|
||||
Path string // config file the hooks live in
|
||||
Changed bool // false = already registered
|
||||
Note string // extra step the user must take, if any
|
||||
// Migrated names a project-level config an earlier version wrote, whose
|
||||
// hooks this run removed. Empty when there was nothing to clean up.
|
||||
Migrated string
|
||||
}
|
||||
|
||||
// mountGuard is the fast pre-check every hook opens with. It runs on every
|
||||
// tool call in every folder, so it stays pure shell — no process spawn on the
|
||||
// common "not a bdrive folder" path. It answers in both directions, because a
|
||||
// session's directory is rarely the mount root: walk up for an enclosing
|
||||
// mount (editor opened inside the synced wiki/), else ask the registry whether
|
||||
// any mount lives below (editor opened at the repo root above wiki/ and
|
||||
// docs/). Matching on .bdrive/config.json rather than the directory keeps
|
||||
// $BDRIVE_HOME (~/.bdrive, which has no config.json) from reading as a mount.
|
||||
func mountGuard() string {
|
||||
return `cd "${CLAUDE_PROJECT_DIR:-.}" 2>/dev/null || exit 0; ` +
|
||||
`d=$PWD; while [ ! -f "$d/.bdrive/config.json" ]; do case "$d" in ""|/) d=; break;; esac; d=${d%/*}; done; ` +
|
||||
`[ -n "$d" ] || grep -qF "\"$PWD/" "${BDRIVE_HOME:-$HOME/.bdrive}/mounts.json" 2>/dev/null || exit 0; ` +
|
||||
`command -v bdrive >/dev/null || exit 0; `
|
||||
}
|
||||
|
||||
// hookCommand is the one shell command every platform runs: sync the project
|
||||
// if it is a bdrive mount, stamping changes with the agent session id parsed
|
||||
// from the hook's stdin JSON. POSIX sh only — no jq, no bashisms.
|
||||
func hookCommand(label string) string {
|
||||
return `sh -c '` +
|
||||
`cd "${CLAUDE_PROJECT_DIR:-.}" && [ -d .bdrive ] && command -v bdrive >/dev/null || exit 0; ` +
|
||||
return `sh -c '` + mountGuard() +
|
||||
`s=; [ -t 0 ] || s=$(head -c 8192 2>/dev/null | tr -d \" | sed -n "s/.*session_id[[:space:]]*:[[:space:]]*\([a-zA-Z0-9_-]*\).*/\1/p" | head -n 1); ` +
|
||||
`if [ -n "$s" ]; then bdrive sync . --note "` + label + ` session $s" >/dev/null 2>&1 || true; ` +
|
||||
`else bdrive sync . >/dev/null 2>&1 || true; fi'`
|
||||
@@ -73,8 +98,7 @@ func hookCommand(label string) string {
|
||||
// is why stdout must NOT be discarded here). Claude-only: the JSON
|
||||
// contract is Claude Code's.
|
||||
func hookPullCommand(label string) string {
|
||||
return `sh -c '` +
|
||||
`cd "${CLAUDE_PROJECT_DIR:-.}" && [ -d .bdrive ] && command -v bdrive >/dev/null || exit 0; ` +
|
||||
return `sh -c '` + mountGuard() +
|
||||
`bdrive sync . --hook ` + label + ` 2>/dev/null'`
|
||||
}
|
||||
|
||||
@@ -82,8 +106,7 @@ func hookPullCommand(label string) string {
|
||||
// `bdrive read-log` parses the hook's stdin JSON itself and only appends to
|
||||
// a local spool, so this stays cheap enough to run on every read-tool call.
|
||||
func readHookCommand() string {
|
||||
return `sh -c '` +
|
||||
`cd "${CLAUDE_PROJECT_DIR:-.}" && [ -d .bdrive ] && command -v bdrive >/dev/null || exit 0; ` +
|
||||
return `sh -c '` + mountGuard() +
|
||||
`bdrive read-log . >/dev/null 2>&1 || true'`
|
||||
}
|
||||
|
||||
@@ -99,12 +122,12 @@ var platforms = map[string]platform{
|
||||
"claude": {
|
||||
label: "claude-code",
|
||||
projectDir: ".claude",
|
||||
install: func(folder string) (string, bool, error) {
|
||||
install: func(string) (string, bool, error) {
|
||||
// Reads happen through more than the Read tool: Grep consumes
|
||||
// the files its matches come from, and Bash reads whatever
|
||||
// files the command names (`read-log` mines both payloads).
|
||||
// Glob stays unmatched on purpose — listing names isn't reading.
|
||||
return mergeJSONHooks(filepath.Join(folder, ".claude", "settings.json"),
|
||||
return mergeJSONHooks(ConfigPath("", "claude"),
|
||||
"UserPromptSubmit", "PostToolUse", "Write|Edit|MultiEdit", "Read|Grep|Bash", "claude-code", 30, true,
|
||||
hookPullCommand("claude-code"))
|
||||
},
|
||||
@@ -112,20 +135,22 @@ var platforms = map[string]platform{
|
||||
"codex": {
|
||||
label: "codex",
|
||||
projectDir: ".codex",
|
||||
install: func(folder string) (string, bool, error) {
|
||||
install: func(string) (string, bool, error) {
|
||||
// Codex reads mostly happen through shell commands; read-log
|
||||
// mines the command line for the files it names.
|
||||
return mergeJSONHooks(filepath.Join(folder, ".codex", "hooks.json"),
|
||||
return mergeJSONHooks(ConfigPath("", "codex"),
|
||||
"UserPromptSubmit", "PostToolUse", "apply_patch", "read_file|shell", "codex", 30, false, "")
|
||||
},
|
||||
note: "run /hooks inside Codex once to trust the project's .codex layer",
|
||||
// Codex hooks are experimental and off by default, and Codex asks
|
||||
// the user to trust each hook definition once.
|
||||
note: "enable hooks in ~/.codex/config.toml ([features] codex_hooks = true), then trust the hook when Codex asks",
|
||||
},
|
||||
"gemini": {
|
||||
label: "gemini",
|
||||
projectDir: ".gemini",
|
||||
install: func(folder string) (string, bool, error) {
|
||||
install: func(string) (string, bool, error) {
|
||||
// Gemini uses its own event names and millisecond timeouts.
|
||||
return mergeJSONHooks(filepath.Join(folder, ".gemini", "settings.json"),
|
||||
return mergeJSONHooks(ConfigPath("", "gemini"),
|
||||
"BeforeAgent", "AfterTool", "write_file|replace|edit",
|
||||
"read_file|read_many_files|search_file_content|run_shell_command", "gemini", 30000, false, "")
|
||||
},
|
||||
@@ -163,8 +188,28 @@ func Registered(folder, agent string) bool {
|
||||
return err == nil && strings.Contains(string(data), marker)
|
||||
}
|
||||
|
||||
// ConfigPath returns where an agent's hooks are (or would be) registered.
|
||||
func ConfigPath(folder, agent string) string {
|
||||
// ConfigPath returns where an agent's hooks are (or would be) registered:
|
||||
// always the platform's USER-level config. The folder argument is ignored and
|
||||
// kept only so callers read naturally; see the package doc for why hooks are
|
||||
// no longer written per project.
|
||||
func ConfigPath(_ string, agent string) string {
|
||||
home, _ := os.UserHomeDir()
|
||||
switch agent {
|
||||
case "claude":
|
||||
return filepath.Join(home, ".claude", "settings.json")
|
||||
case "codex":
|
||||
return filepath.Join(home, ".codex", "hooks.json")
|
||||
case "gemini":
|
||||
return filepath.Join(home, ".gemini", "settings.json")
|
||||
case "hermes":
|
||||
return filepath.Join(home, ".hermes", "config.yaml")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// projectConfigPath is where PREVIOUS versions wrote a platform's hooks. Only
|
||||
// the migration in Install reads these, to strip blocks it left behind.
|
||||
func projectConfigPath(folder, agent string) string {
|
||||
switch agent {
|
||||
case "claude":
|
||||
return filepath.Join(folder, ".claude", "settings.json")
|
||||
@@ -172,11 +217,8 @@ func ConfigPath(folder, agent string) string {
|
||||
return filepath.Join(folder, ".codex", "hooks.json")
|
||||
case "gemini":
|
||||
return filepath.Join(folder, ".gemini", "settings.json")
|
||||
case "hermes":
|
||||
home, _ := os.UserHomeDir()
|
||||
return filepath.Join(home, ".hermes", "config.yaml")
|
||||
}
|
||||
return ""
|
||||
return "" // hermes was always user-level
|
||||
}
|
||||
|
||||
// Install registers the sync hooks for the given agents ("auto"/empty =
|
||||
@@ -196,11 +238,135 @@ func Install(folder string, agents []string) ([]Result, error) {
|
||||
if err != nil {
|
||||
return out, fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
out = append(out, Result{Agent: name, Path: path, Changed: changed, Note: p.note})
|
||||
// Earlier versions wrote hooks into the project. Leaving those behind
|
||||
// would run every hook twice — double-counting agent reads in the
|
||||
// hub's heatmap — so installing also migrates them away.
|
||||
migrated, err := removeProjectHooks(folder, name)
|
||||
if err != nil {
|
||||
return out, fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
out = append(out, Result{Agent: name, Path: path, Changed: changed, Note: p.note, Migrated: migrated})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Uninstall removes BearDrive's hooks from each agent's user config, leaving
|
||||
// every other hook in the file untouched.
|
||||
func Uninstall(agents []string) ([]Result, error) {
|
||||
if len(agents) == 0 || (len(agents) == 1 && agents[0] == "auto") {
|
||||
agents = Agents
|
||||
}
|
||||
var out []Result
|
||||
for _, name := range agents {
|
||||
if _, ok := platforms[name]; !ok {
|
||||
return out, fmt.Errorf("unknown agent %q (supported: %s)", name, strings.Join(Agents, ", "))
|
||||
}
|
||||
path := ConfigPath("", name)
|
||||
changed, err := removeHooks(path, name == "hermes")
|
||||
if err != nil {
|
||||
return out, fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
out = append(out, Result{Agent: name, Path: path, Changed: changed})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// removeProjectHooks strips our blocks from every pre-user-scope location:
|
||||
// earlier versions wrote the mount, its enclosing repo root, and the working
|
||||
// directory init ran from.
|
||||
func removeProjectHooks(folder, agent string) (string, error) {
|
||||
var cleaned []string
|
||||
for _, dir := range legacyHookDirs(folder) {
|
||||
path := projectConfigPath(dir, agent)
|
||||
if path == "" {
|
||||
continue
|
||||
}
|
||||
changed, err := removeHooks(path, false)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if changed {
|
||||
cleaned = append(cleaned, path)
|
||||
}
|
||||
}
|
||||
return strings.Join(cleaned, ", "), nil
|
||||
}
|
||||
|
||||
// legacyHookDirs lists the directories a previous version may have written.
|
||||
func legacyHookDirs(folder string) []string {
|
||||
dirs := []string{folder}
|
||||
if root := gitRootOf(folder); root != "" && root != folder {
|
||||
dirs = append(dirs, root)
|
||||
}
|
||||
if cwd, err := os.Getwd(); err == nil {
|
||||
if abs, err := filepath.Abs(cwd); err == nil && abs != folder {
|
||||
dirs = append(dirs, abs)
|
||||
}
|
||||
}
|
||||
return dirs
|
||||
}
|
||||
|
||||
// gitRootOf is the repository containing folder, if any.
|
||||
func gitRootOf(folder string) string {
|
||||
for cur := folder; ; cur = filepath.Dir(cur) {
|
||||
if _, err := os.Stat(filepath.Join(cur, ".git")); err == nil {
|
||||
return cur
|
||||
}
|
||||
if filepath.Dir(cur) == cur {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// removeHooks deletes every hook group carrying one of our markers, and
|
||||
// rewrites the file only if something was removed. A file we never touched is
|
||||
// left byte-identical.
|
||||
func removeHooks(path string, isYAML bool) (bool, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
root := map[string]any{}
|
||||
unmarshal, marshal := json.Unmarshal, func() ([]byte, error) { return json.MarshalIndent(root, "", " ") }
|
||||
if isYAML {
|
||||
unmarshal, marshal = yaml.Unmarshal, func() ([]byte, error) { return yaml.Marshal(root) }
|
||||
}
|
||||
if err := unmarshal(data, &root); err != nil {
|
||||
return false, fmt.Errorf("parse %s: %w", path, err)
|
||||
}
|
||||
hooks, ok := root["hooks"].(map[string]any)
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
changed := false
|
||||
for event, v := range hooks {
|
||||
arr, _ := v.([]any)
|
||||
var kept []any
|
||||
for _, it := range arr {
|
||||
if containsMarker(it, marker) || containsMarker(it, readMarker) {
|
||||
changed = true
|
||||
continue
|
||||
}
|
||||
kept = append(kept, it)
|
||||
}
|
||||
if len(kept) == 0 {
|
||||
delete(hooks, event)
|
||||
continue
|
||||
}
|
||||
hooks[event] = kept
|
||||
}
|
||||
if !changed {
|
||||
return false, nil
|
||||
}
|
||||
if len(hooks) == 0 {
|
||||
delete(root, "hooks")
|
||||
}
|
||||
return true, writeConfig(path, marshal)
|
||||
}
|
||||
|
||||
// mergeJSONHooks adds the pull + push + read hook trio to a Claude-style
|
||||
// hooks JSON file (Claude, Codex, and Gemini all use this shape:
|
||||
// hooks.<Event> is an array of {matcher?, hooks: [{type: "command", ...}]}
|
||||
|
||||
@@ -61,7 +61,7 @@ func TestInstallJSONPlatforms(t *testing.T) {
|
||||
}
|
||||
|
||||
// Claude: both events present, push is async, command carries the label.
|
||||
cl := readJSON(t, filepath.Join(folder, ".claude", "settings.json"))
|
||||
cl := readJSON(t, ConfigPath("", "claude"))
|
||||
hooks := cl["hooks"].(map[string]any)
|
||||
for _, ev := range []string{"UserPromptSubmit", "PostToolUse"} {
|
||||
if _, ok := hooks[ev]; !ok {
|
||||
@@ -84,7 +84,7 @@ func TestInstallJSONPlatforms(t *testing.T) {
|
||||
}
|
||||
|
||||
// Codex: same schema, its own label and matcher, no async field.
|
||||
cx, _ := json.Marshal(readJSON(t, filepath.Join(folder, ".codex", "hooks.json")))
|
||||
cx, _ := json.Marshal(readJSON(t, ConfigPath("", "codex")))
|
||||
if !strings.Contains(string(cx), "codex session $s") || !strings.Contains(string(cx), "apply_patch") {
|
||||
t.Fatalf("codex hooks wrong: %s", cx)
|
||||
}
|
||||
@@ -96,7 +96,7 @@ func TestInstallJSONPlatforms(t *testing.T) {
|
||||
}
|
||||
|
||||
// Gemini: its own event names and ms timeout.
|
||||
gm, _ := json.Marshal(readJSON(t, filepath.Join(folder, ".gemini", "settings.json")))
|
||||
gm, _ := json.Marshal(readJSON(t, ConfigPath("", "gemini")))
|
||||
for _, want := range []string{"BeforeAgent", "AfterTool", "gemini session $s", "30000", "bdrive read-log", "read_file|read_many_files|search_file_content|run_shell_command"} {
|
||||
if !strings.Contains(string(gm), want) {
|
||||
t.Fatalf("gemini hooks missing %q: %s", want, gm)
|
||||
@@ -110,13 +110,14 @@ func TestInstallIdempotentAndPreserving(t *testing.T) {
|
||||
|
||||
// Pre-existing user hook must survive the merge.
|
||||
pre := `{"permissions":{"allow":["Bash(ls:*)"]},"hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo mine"}]}]}}`
|
||||
os.MkdirAll(filepath.Join(folder, ".claude"), 0o755)
|
||||
os.WriteFile(filepath.Join(folder, ".claude", "settings.json"), []byte(pre), 0o644)
|
||||
os.MkdirAll(filepath.Join(folder, ".claude"), 0o755) // detection
|
||||
os.MkdirAll(filepath.Dir(ConfigPath("", "claude")), 0o755) // where hooks live now
|
||||
os.WriteFile(ConfigPath("", "claude"), []byte(pre), 0o644)
|
||||
|
||||
if _, err := Install(folder, []string{"claude"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := readJSON(t, filepath.Join(folder, ".claude", "settings.json"))
|
||||
cfg := readJSON(t, ConfigPath("", "claude"))
|
||||
raw, _ := json.Marshal(cfg)
|
||||
if !strings.Contains(string(raw), "echo mine") {
|
||||
t.Fatal("merge dropped the user's existing hook")
|
||||
@@ -129,7 +130,7 @@ func TestInstallIdempotentAndPreserving(t *testing.T) {
|
||||
}
|
||||
|
||||
// Second install: no change, byte-identical file.
|
||||
before, _ := os.ReadFile(filepath.Join(folder, ".claude", "settings.json"))
|
||||
before, _ := os.ReadFile(ConfigPath("", "claude"))
|
||||
results, err := Install(folder, []string{"claude"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -137,7 +138,7 @@ func TestInstallIdempotentAndPreserving(t *testing.T) {
|
||||
if results[0].Changed {
|
||||
t.Fatal("re-install reported a change")
|
||||
}
|
||||
after, _ := os.ReadFile(filepath.Join(folder, ".claude", "settings.json"))
|
||||
after, _ := os.ReadFile(ConfigPath("", "claude"))
|
||||
if string(before) != string(after) {
|
||||
t.Fatal("re-install rewrote the file")
|
||||
}
|
||||
@@ -151,8 +152,9 @@ func TestInstallUpgradesSyncOnlyConfig(t *testing.T) {
|
||||
old := `{"hooks":{
|
||||
"UserPromptSubmit":[{"hooks":[{"type":"command","command":"sh -c 'bdrive sync .'"}]}],
|
||||
"PostToolUse":[{"matcher":"Write|Edit|MultiEdit","hooks":[{"type":"command","command":"sh -c 'bdrive sync .'"}]}]}}`
|
||||
os.MkdirAll(filepath.Join(folder, ".claude"), 0o755)
|
||||
os.WriteFile(filepath.Join(folder, ".claude", "settings.json"), []byte(old), 0o644)
|
||||
os.MkdirAll(filepath.Join(folder, ".claude"), 0o755) // detection
|
||||
os.MkdirAll(filepath.Dir(ConfigPath("", "claude")), 0o755) // where hooks live now
|
||||
os.WriteFile(ConfigPath("", "claude"), []byte(old), 0o644)
|
||||
|
||||
results, err := Install(folder, []string{"claude"})
|
||||
if err != nil {
|
||||
@@ -161,7 +163,7 @@ func TestInstallUpgradesSyncOnlyConfig(t *testing.T) {
|
||||
if !results[0].Changed {
|
||||
t.Fatal("upgrade install reported unchanged")
|
||||
}
|
||||
cfg := readJSON(t, filepath.Join(folder, ".claude", "settings.json"))
|
||||
cfg := readJSON(t, ConfigPath("", "claude"))
|
||||
hooks := cfg["hooks"].(map[string]any)
|
||||
if got := len(hooks["UserPromptSubmit"].([]any)); got != 1 {
|
||||
t.Fatalf("UserPromptSubmit groups = %d, want the old one only", got)
|
||||
@@ -186,8 +188,9 @@ func TestInstallUpgradesReadMatcher(t *testing.T) {
|
||||
"PostToolUse":[
|
||||
{"matcher":"Write|Edit|MultiEdit","hooks":[{"type":"command","command":"sh -c 'bdrive sync .'"}]},
|
||||
{"matcher":"Read","hooks":[{"type":"command","command":"sh -c 'bdrive read-log .'"}]}]}}`
|
||||
os.MkdirAll(filepath.Join(folder, ".claude"), 0o755)
|
||||
os.WriteFile(filepath.Join(folder, ".claude", "settings.json"), []byte(old), 0o644)
|
||||
os.MkdirAll(filepath.Join(folder, ".claude"), 0o755) // detection
|
||||
os.MkdirAll(filepath.Dir(ConfigPath("", "claude")), 0o755) // where hooks live now
|
||||
os.WriteFile(ConfigPath("", "claude"), []byte(old), 0o644)
|
||||
|
||||
results, err := Install(folder, []string{"claude"})
|
||||
if err != nil {
|
||||
@@ -196,7 +199,7 @@ func TestInstallUpgradesReadMatcher(t *testing.T) {
|
||||
if !results[0].Changed {
|
||||
t.Fatal("matcher upgrade reported unchanged")
|
||||
}
|
||||
cfg := readJSON(t, filepath.Join(folder, ".claude", "settings.json"))
|
||||
cfg := readJSON(t, ConfigPath("", "claude"))
|
||||
hooks := cfg["hooks"].(map[string]any)
|
||||
if got := len(hooks["PostToolUse"].([]any)); got != 2 {
|
||||
t.Fatalf("PostToolUse groups = %d, want push + read (no duplicates)", got)
|
||||
@@ -227,8 +230,9 @@ func TestInstallUpgradesPullCommand(t *testing.T) {
|
||||
"PostToolUse":[
|
||||
{"matcher":"Write|Edit|MultiEdit","hooks":[{"type":"command","command":"sh -c 'bdrive sync .'","timeout":30,"async":true}]},
|
||||
{"matcher":"Read|Grep|Bash","hooks":[{"type":"command","command":"sh -c 'bdrive read-log .'","timeout":30,"async":true}]}]}}`
|
||||
os.MkdirAll(filepath.Join(folder, ".claude"), 0o755)
|
||||
os.WriteFile(filepath.Join(folder, ".claude", "settings.json"), []byte(old), 0o644)
|
||||
os.MkdirAll(filepath.Join(folder, ".claude"), 0o755) // detection
|
||||
os.MkdirAll(filepath.Dir(ConfigPath("", "claude")), 0o755) // where hooks live now
|
||||
os.WriteFile(ConfigPath("", "claude"), []byte(old), 0o644)
|
||||
|
||||
results, err := Install(folder, []string{"claude"})
|
||||
if err != nil {
|
||||
@@ -237,7 +241,7 @@ func TestInstallUpgradesPullCommand(t *testing.T) {
|
||||
if !results[0].Changed {
|
||||
t.Fatal("pull-command upgrade reported unchanged")
|
||||
}
|
||||
cfg := readJSON(t, filepath.Join(folder, ".claude", "settings.json"))
|
||||
cfg := readJSON(t, ConfigPath("", "claude"))
|
||||
hooks := cfg["hooks"].(map[string]any)
|
||||
if got := len(hooks["UserPromptSubmit"].([]any)); got != 1 {
|
||||
t.Fatalf("UserPromptSubmit groups = %d, want converged single group", got)
|
||||
@@ -331,7 +335,7 @@ func TestHookCommandExtraction(t *testing.T) {
|
||||
t.Skip("no /bin/sh")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
os.MkdirAll(filepath.Join(dir, ".bdrive"), 0o755)
|
||||
makeMount(t, dir)
|
||||
bin := filepath.Join(dir, "bin")
|
||||
os.MkdirAll(bin, 0o755)
|
||||
fake := "#!/bin/sh\necho \"$@\" > \"" + dir + "/args.txt\"\n"
|
||||
@@ -368,7 +372,7 @@ func TestReadHookCommand(t *testing.T) {
|
||||
t.Skip("no /bin/sh")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
os.MkdirAll(filepath.Join(dir, ".bdrive"), 0o755)
|
||||
makeMount(t, dir)
|
||||
bin := filepath.Join(dir, "bin")
|
||||
os.MkdirAll(bin, 0o755)
|
||||
fake := "#!/bin/sh\necho \"$@\" > \"" + dir + "/args.txt\"\ncat > \"" + dir + "/stdin.txt\"\n"
|
||||
@@ -402,6 +406,73 @@ func TestReadHookCommand(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// makeMount marks a folder as a mount root the way the hook guard tests for
|
||||
// it: the config file, not just the directory — `$BDRIVE_HOME` is a `.bdrive`
|
||||
// directory too, and must never read as a project.
|
||||
func makeMount(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Join(dir, ".bdrive"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, ".bdrive", "config.json"), []byte(`{"id":"m-test"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// The guard has to fire from wherever the agent session happens to start:
|
||||
// inside a synced subfolder (walk up), at a root above the mounts (registry),
|
||||
// and nowhere else — including the home directory, whose ~/.bdrive holds
|
||||
// device state rather than a project.
|
||||
func TestHookGuardFindsMountFromAnyDirectory(t *testing.T) {
|
||||
if _, err := os.Stat("/bin/sh"); err != nil {
|
||||
t.Skip("no /bin/sh")
|
||||
}
|
||||
root := t.TempDir()
|
||||
mount := filepath.Join(root, "wiki")
|
||||
inside := filepath.Join(mount, "notes")
|
||||
unrelated := filepath.Join(root, "src")
|
||||
for _, d := range []string{inside, unrelated} {
|
||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
makeMount(t, mount)
|
||||
|
||||
bin := filepath.Join(root, "bin")
|
||||
os.MkdirAll(bin, 0o755)
|
||||
fake := "#!/bin/sh\necho called > \"" + root + "/called.txt\"\n"
|
||||
os.WriteFile(filepath.Join(bin, "bdrive"), []byte(fake), 0o755)
|
||||
|
||||
// A registry naming the mount is what lets a session ABOVE it fire.
|
||||
home := filepath.Join(root, "home")
|
||||
os.MkdirAll(filepath.Join(home, ".bdrive"), 0o755)
|
||||
os.WriteFile(filepath.Join(home, ".bdrive", "mounts.json"),
|
||||
[]byte(`{"m-test":{"path":"`+mount+`"}}`), 0o644)
|
||||
|
||||
for _, tc := range []struct {
|
||||
dir string
|
||||
want bool
|
||||
why string
|
||||
}{
|
||||
{mount, true, "at the mount root"},
|
||||
{inside, true, "inside the mount (walk up)"},
|
||||
{root, true, "above the mount (registry)"},
|
||||
{unrelated, false, "a sibling folder with no mount"},
|
||||
{home, false, "the home dir, whose .bdrive is device state"},
|
||||
} {
|
||||
os.Remove(filepath.Join(root, "called.txt"))
|
||||
sh := "cd " + tc.dir + " && HOME=" + home + " BDRIVE_HOME=" + filepath.Join(home, ".bdrive") +
|
||||
" PATH=" + bin + ":$PATH " + hookCommand("claude-code")
|
||||
if err := runShell(t, sh, `{"session_id":"s1"}`); err != nil {
|
||||
t.Fatalf("%s: %v", tc.why, err)
|
||||
}
|
||||
_, err := os.Stat(filepath.Join(root, "called.txt"))
|
||||
if fired := err == nil; fired != tc.want {
|
||||
t.Errorf("%s: hook fired = %v, want %v", tc.why, fired, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func runShell(t *testing.T, script, stdin string) error {
|
||||
t.Helper()
|
||||
cmd := exec.Command("/bin/sh", "-c", script)
|
||||
@@ -412,3 +483,53 @@ func runShell(t *testing.T, script, stdin string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Uninstall is the exact inverse of install: our blocks go, everything the
|
||||
// user had stays, and a config we never touched is left byte-identical.
|
||||
func TestUninstallRemovesOnlyOurHooks(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
folder := t.TempDir()
|
||||
os.MkdirAll(filepath.Join(folder, ".claude"), 0o755)
|
||||
os.MkdirAll(filepath.Dir(ConfigPath("", "claude")), 0o755)
|
||||
|
||||
pre := `{"permissions":{"allow":["Bash(ls:*)"]},"hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo mine"}]}]}}`
|
||||
os.WriteFile(ConfigPath("", "claude"), []byte(pre), 0o644)
|
||||
before, _ := os.ReadFile(ConfigPath("", "claude"))
|
||||
|
||||
if _, err := Install(folder, []string{"claude"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
results, err := Uninstall([]string{"claude"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !results[0].Changed {
|
||||
t.Fatal("uninstall reported nothing removed")
|
||||
}
|
||||
after := readJSON(t, ConfigPath("", "claude"))
|
||||
raw, _ := json.Marshal(after)
|
||||
if strings.Contains(string(raw), "bdrive") {
|
||||
t.Fatalf("uninstall left our hooks behind: %s", raw)
|
||||
}
|
||||
if !strings.Contains(string(raw), "echo mine") {
|
||||
t.Fatalf("uninstall removed a hook that was not ours: %s", raw)
|
||||
}
|
||||
if _, ok := after["permissions"]; !ok {
|
||||
t.Fatal("uninstall dropped unrelated settings keys")
|
||||
}
|
||||
|
||||
// Round trip preserves the file's content (formatting may differ).
|
||||
var b map[string]any
|
||||
json.Unmarshal(before, &b)
|
||||
rb, _ := json.Marshal(b)
|
||||
if string(rb) != string(raw) {
|
||||
t.Fatalf("install+uninstall changed the config:\nbefore %s\nafter %s", rb, raw)
|
||||
}
|
||||
|
||||
// Uninstalling again is a silent no-op.
|
||||
results, err = Uninstall([]string{"claude"})
|
||||
if err != nil || results[0].Changed {
|
||||
t.Fatalf("second uninstall: changed=%v err=%v", results[0].Changed, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ func conflictFiles(t *testing.T, folder string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// A repo shares only its knowledge subfolder (`bdrive init --shared Wiki`);
|
||||
// A repo shares only its knowledge subfolder (a legacy include-list mount);
|
||||
// a teammate connects from their own checkout with the same scope. Wiki
|
||||
// content flows both ways; each side's code never leaves its machine.
|
||||
func TestSharedSubfolderScopeBothDevices(t *testing.T) {
|
||||
|
||||
@@ -164,6 +164,12 @@ func (f *Filter) Skip(rel string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Negated reports whether any `!` rule is in play. Scope narrowing is
|
||||
// written as negation rules, so this is how callers tell "these rules
|
||||
// exclude a few things" from "these rules exclude everything but a few
|
||||
// things" — the difference between a safe prune and a destructive one.
|
||||
func (f *Filter) Negated() bool { return f.negated }
|
||||
|
||||
// PruneDir reports whether a whole directory can be skipped during the
|
||||
// scan walk. Pruning is conservative: never with `!` rules (a child could
|
||||
// be re-included) or an include list (a deep child could match).
|
||||
|
||||
@@ -120,7 +120,7 @@ func TestPruneFindsHistoricallyDroppedPaths(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Prune reconciles against the shared rules only. A device's own --shared
|
||||
// Prune reconciles against the shared rules only. A device's own legacy
|
||||
// scope is a statement about its disk, not about what the team may hold, so
|
||||
// pruning must never act on it.
|
||||
func TestPruneIgnoresPerDeviceScope(t *testing.T) {
|
||||
|
||||
@@ -652,7 +652,7 @@ func (s *Session) materializeFile(rel string, want journal.FileState, cache map[
|
||||
// The rules are deliberately ignore-only. .bdriveignore syncs, so every
|
||||
// device agrees on it; the include list lives in this device's own
|
||||
// .bdrive/config.json and does not sync. Never reuse the cycle's main filter
|
||||
// here: a device with a narrow --shared scope would delete files a
|
||||
// here: a device with a legacy include-list scope would delete files a
|
||||
// whole-folder teammate legitimately syncs.
|
||||
func (s *Session) pruneOps(target map[string]journal.FileState, st *store.SyncState, seqBase int64) ([]journal.Op, error) {
|
||||
shared, err := loadFilter(s.Folder, nil) // nil include: shared rules only
|
||||
|
||||
@@ -0,0 +1,542 @@
|
||||
package webapp
|
||||
|
||||
// CLI onboarding e2e: builds the real bdrive binary and drives the exact
|
||||
// commands an agent (or the INSTALL_FOR_AGENTS.md runbook) runs against an
|
||||
// in-process hub — device-code login, init, re-init, hooks, stop. This is
|
||||
// the deterministic half of onboarding testing; the conversational half
|
||||
// (does the agent ask before mounting?) lives in the onboarding-e2e skill.
|
||||
//
|
||||
// The key regression this guards: `bdrive init` must register agent sync
|
||||
// hooks itself — a separate `bdrive hooks install` gets blocked by agent
|
||||
// permission classifiers, which is how teams end up without hooks.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/runbear-io/beardrive/internal/remote"
|
||||
)
|
||||
|
||||
// cliEnv is a signed-in CLI against a throwaway hub: the real binary, an
|
||||
// isolated HOME/BDRIVE_HOME, and a browser session for hub-side assertions.
|
||||
type cliEnv struct {
|
||||
run func(dir string, args ...string) (string, error)
|
||||
hub *httptest.Server
|
||||
browser *http.Client
|
||||
home string // the isolated HOME; hooks live under here now
|
||||
}
|
||||
|
||||
func newCLIEnv(t *testing.T) cliEnv {
|
||||
t.Helper()
|
||||
if testing.Short() {
|
||||
t.Skip("builds and execs the bdrive binary; skipped with -short")
|
||||
}
|
||||
bin := filepath.Join(t.TempDir(), "bdrive")
|
||||
build := exec.Command("go", "build", "-o", bin, "github.com/runbear-io/beardrive/cmd/bdrive")
|
||||
if out, err := build.CombinedOutput(); err != nil {
|
||||
t.Fatalf("go build: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
hub := startTestHub(t)
|
||||
|
||||
// Isolate the CLI completely: fresh BDRIVE_HOME and a fresh HOME, so
|
||||
// agent-platform detection can't see or touch the real ~/.codex etc.
|
||||
home := t.TempDir()
|
||||
env := append(envWithout("HOME", "BDRIVE_HOME"),
|
||||
"HOME="+home, "BDRIVE_HOME="+filepath.Join(home, ".bdrive"))
|
||||
run := func(dir string, args ...string) (string, error) {
|
||||
cmd := exec.Command(bin, args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = env
|
||||
out, err := cmd.CombinedOutput()
|
||||
return string(out), err
|
||||
}
|
||||
|
||||
// Sign in via the real device-code flow, approved over HTTP as the
|
||||
// runbook's "any signed-in browser" (a cookie session from /auth/login).
|
||||
login := exec.Command(bin, "login", "--device", hub.URL)
|
||||
login.Env = env
|
||||
logFile := filepath.Join(t.TempDir(), "login.log")
|
||||
f, err := os.Create(logFile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
login.Stdout, login.Stderr = f, f
|
||||
if err := login.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { login.Process.Kill() })
|
||||
code := waitForCode(t, logFile)
|
||||
browser := signedInBrowser(t, hub.URL)
|
||||
if _, err := browser.PostForm(hub.URL+"/auth/device", url.Values{"code": {code}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := login.Wait(); err != nil {
|
||||
out, _ := os.ReadFile(logFile)
|
||||
t.Fatalf("login --device: %v\n%s", err, out)
|
||||
}
|
||||
return cliEnv{run: run, hub: hub, browser: browser, home: home}
|
||||
}
|
||||
|
||||
func TestCLIOnboardingE2E(t *testing.T) {
|
||||
e := newCLIEnv(t)
|
||||
run, hub, browser := e.run, e.hub, e.browser
|
||||
|
||||
// --- Init in a folder where Claude Code is in use. Hooks must be
|
||||
// registered by init itself, before the first sync output.
|
||||
work := filepath.Join(t.TempDir(), "proj")
|
||||
if err := os.MkdirAll(filepath.Join(work, ".claude"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer run(work, "stop", work) // don't leak the daemon on failure
|
||||
out, err := run(work, "init", "--name", "cli-e2e", "--yes")
|
||||
if err != nil {
|
||||
t.Fatalf("init: %v\n%s", err, out)
|
||||
}
|
||||
if !strings.Contains(out, "claude") || !strings.Contains(out, "hooks registered") {
|
||||
t.Fatalf("init did not report registering claude hooks:\n%s", out)
|
||||
}
|
||||
settings, err := os.ReadFile(filepath.Join(e.home, ".claude", "settings.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("init did not write the user's .claude/settings.json: %v", err)
|
||||
}
|
||||
for _, want := range []string{"bdrive sync", "bdrive read-log"} {
|
||||
if !strings.Contains(string(settings), want) {
|
||||
t.Fatalf("user settings.json missing %q hook:\n%s", want, settings)
|
||||
}
|
||||
}
|
||||
// Nothing agent-shaped may be created inside the project: it would sync.
|
||||
assertNoProjectHookFiles(t, work)
|
||||
|
||||
// The project must actually exist on the hub, created under the account.
|
||||
if projects := hubProjects(t, browser, hub.URL); !strings.Contains(projects, "cli-e2e") {
|
||||
t.Fatalf("hub project list missing cli-e2e: %s", projects)
|
||||
}
|
||||
|
||||
// --- Re-running init resumes and converges hooks idempotently.
|
||||
out, err = run(work, "init", "--yes")
|
||||
if err != nil {
|
||||
t.Fatalf("re-init: %v\n%s", err, out)
|
||||
}
|
||||
if !strings.Contains(out, "resuming") || !strings.Contains(out, "hooks already registered") {
|
||||
t.Fatalf("re-init should resume with hooks already registered:\n%s", out)
|
||||
}
|
||||
|
||||
if out, err = run(work, "hooks"); err != nil || !strings.Contains(out, "hooks registered") {
|
||||
t.Fatalf("hooks status: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
if out, err = run(work, "stop", work); err != nil {
|
||||
t.Fatalf("stop: %v\n%s", err, out)
|
||||
}
|
||||
cfg1, err := os.ReadFile(filepath.Join(work, ".bdrive", "config.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// --- A second mount on the same machine (the "add another folder" flow)
|
||||
// must create a separate project and leave the first mount untouched.
|
||||
// Also the opt-out: --no-hooks must leave the platform config alone.
|
||||
work2 := filepath.Join(t.TempDir(), "proj2")
|
||||
if err := os.MkdirAll(filepath.Join(work2, ".claude"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer run(work2, "stop", work2)
|
||||
out, err = run(work2, "init", "--name", "cli-e2e-nohooks", "--yes", "--no-hooks")
|
||||
if err != nil {
|
||||
t.Fatalf("init --no-hooks: %v\n%s", err, out)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(work2, ".claude", "settings.json")); !os.IsNotExist(err) {
|
||||
t.Fatalf("--no-hooks still wrote .claude/settings.json (stat err: %v)", err)
|
||||
}
|
||||
if out, err = run(work2, "stop", work2); err != nil {
|
||||
t.Fatalf("stop: %v\n%s", err, out)
|
||||
}
|
||||
cfg1b, err := os.ReadFile(filepath.Join(work, ".bdrive", "config.json"))
|
||||
if err != nil || string(cfg1) != string(cfg1b) {
|
||||
t.Fatalf("second init disturbed the first mount's config (err %v):\nbefore: %s\nafter: %s", err, cfg1, cfg1b)
|
||||
}
|
||||
projects := hubProjects(t, browser, hub.URL)
|
||||
for _, want := range []string{"cli-e2e", "cli-e2e-nohooks"} {
|
||||
if !strings.Contains(projects, want) {
|
||||
t.Fatalf("hub missing project %q after second init: %s", want, projects)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Two sibling folders under one parent, each synced to a DIFFERENT project —
|
||||
// the shape a second project lands in on a machine that already syncs one.
|
||||
// The mounts must stay fully independent: separate ids, separate content, and
|
||||
// the first one's config untouched by the second's init.
|
||||
func TestCLISiblingProjectMounts(t *testing.T) {
|
||||
e := newCLIEnv(t)
|
||||
run, hub, browser := e.run, e.hub, e.browser
|
||||
|
||||
parent := t.TempDir()
|
||||
a, b := filepath.Join(parent, "a"), filepath.Join(parent, "b")
|
||||
for dir, file := range map[string]string{a: "brand.md", b: "adr.md"} {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, file), []byte("# "+file+"\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if out, err := run(a, "init", "--name", "project-a", "--yes"); err != nil {
|
||||
t.Fatalf("init a: %v\n%s", err, out)
|
||||
}
|
||||
defer run(a, "stop", a)
|
||||
cfgA, err := os.ReadFile(filepath.Join(a, ".bdrive", "config.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if out, err := run(b, "init", "--name", "project-b", "--yes"); err != nil {
|
||||
t.Fatalf("init b: %v\n%s", err, out)
|
||||
}
|
||||
defer run(b, "stop", b)
|
||||
|
||||
// The second init must not have touched the first mount.
|
||||
cfgAafter, err := os.ReadFile(filepath.Join(a, ".bdrive", "config.json"))
|
||||
if err != nil || string(cfgA) != string(cfgAafter) {
|
||||
t.Fatalf("init in b/ changed a/'s config (err %v):\nbefore: %s\nafter: %s", err, cfgA, cfgAafter)
|
||||
}
|
||||
cfgB, err := os.ReadFile(filepath.Join(b, ".bdrive", "config.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(cfgA) == string(cfgB) {
|
||||
t.Fatalf("sibling mounts share a config: %s", cfgA)
|
||||
}
|
||||
|
||||
// Each project holds its own file and not the other's.
|
||||
idA, idB := projectIDByName(t, browser, hub.URL, "project-a"), projectIDByName(t, browser, hub.URL, "project-b")
|
||||
pathsA, pathsB := hubPaths(t, browser, hub.URL, idA), hubPaths(t, browser, hub.URL, idB)
|
||||
if !pathsA["brand.md"] || pathsA["adr.md"] {
|
||||
t.Fatalf("project-a content wrong: %v", pathsA)
|
||||
}
|
||||
if !pathsB["adr.md"] || pathsB["brand.md"] {
|
||||
t.Fatalf("project-b content wrong: %v", pathsB)
|
||||
}
|
||||
}
|
||||
|
||||
// One project mounted from two folders on the SAME device. The remote journal
|
||||
// key is per-device, so a second mount would restart the sequence and
|
||||
// overwrite the first mount's ops — its files would vanish from the hub. Init
|
||||
// must refuse; if it ever accepts again, the first mount's file must survive.
|
||||
func TestCLISameProjectTwoMounts(t *testing.T) {
|
||||
e := newCLIEnv(t)
|
||||
run, hub, browser := e.run, e.hub, e.browser
|
||||
|
||||
first, second := filepath.Join(t.TempDir(), "first"), filepath.Join(t.TempDir(), "second")
|
||||
if err := os.MkdirAll(first, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(first, "adr.md"), []byte("# ADR\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out, err := run(first, "init", "--name", "dup", "--yes"); err != nil {
|
||||
t.Fatalf("init first: %v\n%s", err, out)
|
||||
}
|
||||
defer run(first, "stop", first)
|
||||
id := projectIDByName(t, browser, hub.URL, "dup")
|
||||
|
||||
if err := os.MkdirAll(second, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err := run(second, "init", "--project", id, "--yes")
|
||||
defer run(second, "stop", second)
|
||||
if err != nil {
|
||||
// The refusal must name the folder already holding the project.
|
||||
if !strings.Contains(out, first) {
|
||||
t.Fatalf("refusal should point at the existing mount %s:\n%s", first, out)
|
||||
}
|
||||
if config := filepath.Join(second, ".bdrive", "config.json"); fileExists(config) {
|
||||
t.Fatalf("refused init still wrote %s", config)
|
||||
}
|
||||
return
|
||||
}
|
||||
if paths := hubPaths(t, browser, hub.URL, id); !paths["adr.md"] {
|
||||
t.Fatalf("second mount erased the first mount's file from the hub: %v\n%s", paths, out)
|
||||
}
|
||||
}
|
||||
|
||||
// A mount below the session's directory (a repo root with wiki/ mounted) and
|
||||
// one above it (a session inside the synced folder) must both sync: agent
|
||||
// hooks run wherever the editor was opened, which is rarely the mount root.
|
||||
func TestCLISyncResolvesMountFromAnyDirectory(t *testing.T) {
|
||||
e := newCLIEnv(t)
|
||||
run := e.run
|
||||
|
||||
repo := t.TempDir()
|
||||
wiki := filepath.Join(repo, "wiki")
|
||||
deep := filepath.Join(wiki, "notes")
|
||||
for _, dir := range []string{deep, filepath.Join(repo, ".claude"), filepath.Join(wiki, ".claude")} {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(deep, "a.md"), []byte("# A\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Run init the way an agent does: from the repo root, naming the subfolder.
|
||||
if out, err := run(repo, "init", "wiki", "--name", "scoped", "--yes"); err != nil {
|
||||
t.Fatalf("init wiki: %v\n%s", err, out)
|
||||
}
|
||||
defer run(wiki, "stop", wiki)
|
||||
|
||||
// From the repo root: the mount is below, found through the registry.
|
||||
out, err := run(repo, "sync")
|
||||
if err != nil || !strings.Contains(out, wiki) {
|
||||
t.Fatalf("sync at the repo root missed the wiki mount: %v\n%s", err, out)
|
||||
}
|
||||
// From inside the mount: walk up to its root.
|
||||
out, err = run(deep, "sync")
|
||||
if err != nil || !strings.Contains(out, wiki) {
|
||||
t.Fatalf("sync inside the mount did not resolve its root: %v\n%s", err, out)
|
||||
}
|
||||
// Hooks are user-level; the repo and the mount stay clean.
|
||||
for _, dir := range []string{repo, wiki} {
|
||||
assertNoProjectHookFiles(t, dir)
|
||||
}
|
||||
|
||||
// Reaching the repo through a symlink must find the same mount: macOS
|
||||
// hands sessions /tmp paths for mounts registered under /private/tmp.
|
||||
link := filepath.Join(t.TempDir(), "link")
|
||||
if err := os.Symlink(repo, link); err != nil {
|
||||
t.Skipf("symlinks unavailable: %v", err)
|
||||
}
|
||||
if out, err := run(link, "sync"); err != nil || !strings.Contains(out, "project") {
|
||||
t.Fatalf("sync through a symlinked repo root missed the mount: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
// Wherever init runs — inside the mount, at a repo root, anywhere — the hooks
|
||||
// go to the user's config and the project tree is left clean. Platforms read
|
||||
// hook config only from the directory a session starts in, so one user-level
|
||||
// registration is what actually covers every session.
|
||||
func TestCLIInitWritesNoProjectHookFiles(t *testing.T) {
|
||||
e := newCLIEnv(t)
|
||||
run := e.run
|
||||
|
||||
repo := t.TempDir()
|
||||
wiki := filepath.Join(repo, "wiki")
|
||||
for _, dir := range []string{filepath.Join(repo, ".git"), filepath.Join(repo, ".claude"), filepath.Join(wiki, ".claude")} {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// Pre-existing project hooks from an older version, plus a foreign hook.
|
||||
stale := filepath.Join(repo, ".claude", "settings.json")
|
||||
old := `{"hooks":{"UserPromptSubmit":[` +
|
||||
`{"hooks":[{"type":"command","command":"sh -c 'bdrive sync .'"}]},` +
|
||||
`{"hooks":[{"type":"command","command":"echo mine"}]}]}}`
|
||||
if err := os.WriteFile(stale, []byte(old), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
out, err := run(wiki, "init", "--name", "in-repo", "--yes")
|
||||
if err != nil {
|
||||
t.Fatalf("init: %v\n%s", err, out)
|
||||
}
|
||||
defer run(wiki, "stop", wiki)
|
||||
|
||||
if !fileExists(filepath.Join(e.home, ".claude", "settings.json")) {
|
||||
t.Fatalf("hooks not registered in the user config:\n%s", out)
|
||||
}
|
||||
assertNoProjectHookFiles(t, wiki)
|
||||
// The stale project config keeps the foreign hook but loses ours.
|
||||
data, err := os.ReadFile(stale)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(data), "bdrive sync") {
|
||||
t.Fatalf("stale project hooks survived: %s", data)
|
||||
}
|
||||
if !strings.Contains(string(data), "echo mine") {
|
||||
t.Fatalf("migration removed a hook that was not ours: %s", data)
|
||||
}
|
||||
if !strings.Contains(out, "moved out of") {
|
||||
t.Fatalf("init did not report the migration:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// assertNoProjectHookFiles fails if BearDrive left agent config in a project.
|
||||
func assertNoProjectHookFiles(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
for _, rel := range []string{
|
||||
filepath.Join(".claude", "settings.json"),
|
||||
filepath.Join(".codex", "hooks.json"),
|
||||
filepath.Join(".gemini", "settings.json"),
|
||||
} {
|
||||
if fileExists(filepath.Join(dir, rel)) {
|
||||
t.Fatalf("%s exists in the project — hooks must be user-level only", filepath.Join(dir, rel))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func fileExists(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// hubPaths is the set of paths a project's history knows about.
|
||||
func hubPaths(t *testing.T, browser *http.Client, hubURL, projectID string) map[string]bool {
|
||||
t.Helper()
|
||||
resp, err := browser.Get(hubURL + "/api/p/" + projectID + "/history")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var body struct {
|
||||
Entries []struct{ Path string } `json:"entries"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths := map[string]bool{}
|
||||
for _, e := range body.Entries {
|
||||
paths[e.Path] = true
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
// projectID looks a project up by name through the hub's own API.
|
||||
func projectIDByName(t *testing.T, browser *http.Client, hubURL, name string) string {
|
||||
t.Helper()
|
||||
var body struct {
|
||||
Projects []struct{ ID, Name string } `json:"projects"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(hubProjects(t, browser, hubURL)), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range body.Projects {
|
||||
if p.Name == name {
|
||||
return p.ID
|
||||
}
|
||||
}
|
||||
t.Fatalf("no project named %q on the hub", name)
|
||||
return ""
|
||||
}
|
||||
|
||||
// startTestHub serves a minimal hub (auth + orgs + projects + store proxy)
|
||||
// on an ephemeral port, mirroring TestE2EServe's wiring without the seeds.
|
||||
func startTestHub(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
state := t.TempDir()
|
||||
be, err := remote.Open(t.Context(), "file://"+filepath.Join(state, "storage"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db, err := OpenProjectDB(filepath.Join(state, "projects.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := &Server{Root: be, Projects: db, Device: webDevice, Upload: UploadConfig{Enabled: true}}
|
||||
srv.Devices, _ = OpenDeviceRegistry(filepath.Join(state, "devices.json"))
|
||||
auth, err := OpenBuiltinAuth(filepath.Join(state, "auth.json"), false, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := auth.signup(e2eAdmin, "E2E Admin", e2ePassword); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv.Auth = auth
|
||||
orgs, err := OpenOrgDB(filepath.Join(state, "orgs.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := orgs.Create("default", e2eAdmin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv.Dir = LocalDirectory{OrgDB: orgs}
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
t.Cleanup(ts.Close)
|
||||
return ts
|
||||
}
|
||||
|
||||
// signedInBrowser returns an http client holding a hub session cookie for
|
||||
// the admin account — the "any signed-in browser" of the device flow.
|
||||
func signedInBrowser(t *testing.T, hubURL string) *http.Client {
|
||||
t.Helper()
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c := &http.Client{Jar: jar, Timeout: 10 * time.Second}
|
||||
resp, err := c.PostForm(hubURL+"/auth/login", url.Values{
|
||||
"email": {e2eAdmin}, "password": {e2ePassword},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if len(jar.Cookies(mustParse(t, hubURL))) == 0 {
|
||||
t.Fatal("browser sign-in left no session cookie")
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func hubProjects(t *testing.T, browser *http.Client, hubURL string) string {
|
||||
t.Helper()
|
||||
resp, err := browser.Get(hubURL + "/api/projects")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
var codeRe = regexp.MustCompile(`approve code: ([a-z0-9]+)`)
|
||||
|
||||
// waitForCode polls the login command's output for the device code it prints.
|
||||
func waitForCode(t *testing.T, logFile string) string {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(15 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
data, _ := os.ReadFile(logFile)
|
||||
if m := codeRe.FindSubmatch(data); m != nil {
|
||||
return string(m[1])
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
data, _ := os.ReadFile(logFile)
|
||||
t.Fatalf("login --device never printed a device code:\n%s", data)
|
||||
return ""
|
||||
}
|
||||
|
||||
func envWithout(names ...string) []string {
|
||||
var out []string
|
||||
Env:
|
||||
for _, kv := range os.Environ() {
|
||||
for _, n := range names {
|
||||
if strings.HasPrefix(kv, n+"=") {
|
||||
continue Env
|
||||
}
|
||||
}
|
||||
out = append(out, kv)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func mustParse(t *testing.T, raw string) *url.URL {
|
||||
t.Helper()
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return u
|
||||
}
|
||||
@@ -47,7 +47,7 @@ test("guide: manual fallback has the full command list and the docs link", async
|
||||
expect(manual).toContain("brew install runbear-io/tap/beardrive");
|
||||
expect(manual).toContain("bdrive login http://localhost:8993");
|
||||
expect(manual).toContain(`bdrive init --project ${pid}`);
|
||||
expect(manual).toContain("bdrive hooks install");
|
||||
expect(manual).not.toContain("bdrive hooks install"); // init registers hooks itself
|
||||
await expect(page.locator('.gd-manual a[href="https://docs.beardrive.ai/manual/install/"]')).toHaveCount(1);
|
||||
});
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ test("no-org account gets the onboarding empty state with the agent prompt", asy
|
||||
// The agent paste-prompt is the one path, with this hub's real origin
|
||||
// filled in; the by-hand route is a docs link.
|
||||
await expect(page.locator(".onboard .gd-code code")).toContainText(
|
||||
"to connect this folder to a new BearDrive project on http://localhost:8993.",
|
||||
"to set up a new BearDrive project on http://localhost:8993. Ask me which folder to sync.",
|
||||
);
|
||||
await expect(page.locator(".ob-alt a")).toHaveAttribute(
|
||||
"href",
|
||||
|
||||
@@ -16,15 +16,19 @@ export const INSTALL_DOC = "https://raw.githubusercontent.com/runbear-io/beardri
|
||||
export function ConnectGuide({ project }: { project: Project }) {
|
||||
const origin = window.location.origin;
|
||||
const prompt =
|
||||
"Follow " + INSTALL_DOC + "\nto connect this folder to BearDrive project " + project.id + " on " + origin + ".";
|
||||
"Follow " +
|
||||
INSTALL_DOC +
|
||||
"\nto set up BearDrive project " +
|
||||
project.id +
|
||||
" on " +
|
||||
origin +
|
||||
". Ask me which folder to sync.";
|
||||
const manual =
|
||||
"brew install runbear-io/tap/beardrive" +
|
||||
"\nbdrive skill install" +
|
||||
"\nbdrive login " +
|
||||
origin +
|
||||
"\nbdrive init --project " +
|
||||
project.id +
|
||||
"\nbdrive hooks install";
|
||||
project.id;
|
||||
|
||||
return (
|
||||
<div className="guide">
|
||||
@@ -59,20 +63,21 @@ export function ConnectGuide({ project }: { project: Project }) {
|
||||
<li>
|
||||
Sync hooks pull the latest before every agent turn, push edits seconds after they
|
||||
happen, and stamp each change with the session that made it; agent reads feed
|
||||
Insights.
|
||||
Insights. They register once per machine in your agent's own config, so every
|
||||
session is covered and nothing is written into the synced folder.
|
||||
</li>
|
||||
<li>
|
||||
The beardrive skill (and on Claude Code, the plugin — shared with Cowork) is
|
||||
installed for later sessions, so from then on you can just ask.
|
||||
</li>
|
||||
<li>Codex asks once to trust the project's hooks layer — answer yes, or run /hooks.</li>
|
||||
<li>Codex hooks are off by default: set [features] codex_hooks = true in ~/.codex/config.toml.</li>
|
||||
</ul>
|
||||
</details>
|
||||
<details className="gd-manual">
|
||||
<summary>Or run it yourself</summary>
|
||||
<p className="gd-desc">
|
||||
Same result, in the folder you want the files. Don't skip the last line — the hooks are
|
||||
what keep every turn starting from the latest state.
|
||||
Same result, in the folder you want the files. One command: init signs this device in,
|
||||
installs the skill, registers the sync hooks and starts syncing.
|
||||
</p>
|
||||
<GuideCode code={manual} />
|
||||
<p className="gd-desc">
|
||||
|
||||
@@ -19,9 +19,9 @@ export function EmptyState() {
|
||||
code={
|
||||
"Follow " +
|
||||
INSTALL_DOC +
|
||||
"\nto connect this folder to a new BearDrive project on " +
|
||||
"\nto set up a new BearDrive project on " +
|
||||
window.location.origin +
|
||||
"."
|
||||
". Ask me which folder to sync."
|
||||
}
|
||||
/>
|
||||
<p className="ob-alt">
|
||||
|
||||
+18
-20
File diff suppressed because one or more lines are too long
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>BearDrive</title>
|
||||
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32' fill='%23f5a623'><rect x='4' y='4' width='5.6' height='24'/><rect x='11.2' y='4' width='14.4' height='11.2'/><rect x='11.2' y='16.8' width='16.8' height='11.2'/></svg>">
|
||||
<script type="module" crossorigin src="/assets/index-pwEy71bM.js"></script>
|
||||
<script type="module" crossorigin src="/assets/index-Bs1oTv2s.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-D_6vQyDA.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
Reference in New Issue
Block a user