diff --git a/back2base-container/entrypoint.sh b/back2base-container/entrypoint.sh index 07ba51e..e18ff96 100644 --- a/back2base-container/entrypoint.sh +++ b/back2base-container/entrypoint.sh @@ -15,6 +15,19 @@ else . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/status.sh" fi +# Verbose-only logger. ALWAYS returns 0 so it is safe as the last command of +# a function. The inline idiom +# [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo "..." +# returns 1 when verbose is off; as a function's final command that return +# value propagates and, under the top-level `set -e`, aborts the entrypoint +# mid-startup. Route every verbose detail line through here instead. +_vlog() { + if [ "${BACK2BASE_VERBOSE:-0}" = "1" ]; then + echo "$@" + fi + return 0 +} + # Once any phase fails, demote every subsequent phase to chatty mode so # debugging output isn't lost behind the spinner. _FANCY_FAILED=0 @@ -108,7 +121,7 @@ if [ -d /repos ]; then REPO_DIR=$(find /repos -maxdepth 1 -mindepth 1 -type d | head -1) if [ -n "$REPO_DIR" ]; then cd "$REPO_DIR" - [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo ":: Working directory: $REPO_DIR" + _vlog ":: Working directory: $REPO_DIR" fi fi @@ -134,7 +147,7 @@ if [ -z "${MEMORY_NAMESPACE:-}" ] && [ -d /workspace ]; then fi fi export MEMORY_NAMESPACE - [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo ":: Memory namespace: $MEMORY_NAMESPACE" + _vlog ":: Memory namespace: $MEMORY_NAMESPACE" fi _phase2_workspace_setup() { @@ -225,7 +238,7 @@ seed_if_missing() { if [ ! -e "$target_path" ] && [ -e "$default_path" ]; then mkdir -p "$(dirname "$target_path")" cp "$default_path" "$target_path" - [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo ":: seeded $target_path from defaults" + _vlog ":: seeded $target_path from defaults" fi } @@ -259,7 +272,7 @@ filter_mcp_by_profile() { # ── Explicit profile (unchanged behavior) ── profile="$BACK2BASE_PROFILE" if [ "$profile" = "full" ]; then - [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo ":: MCP profile: full (all servers)" + _vlog ":: MCP profile: full (all servers)" return 0 fi if [ ! -f "$profiles_file" ] || [ ! -f "$mcp_file" ] || ! command -v jq &>/dev/null; then @@ -298,7 +311,7 @@ filter_mcp_by_profile() { mv -f "$tmp" "$mcp_file" local count count=$(jq '.mcpServers | length' "$mcp_file") - [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo ":: MCP profile: $profile ($count servers enabled)" + _vlog ":: MCP profile: $profile ($count servers enabled)" else rm -f "$tmp" echo ":: ⚠ MCP filtering failed, keeping full server set" @@ -330,7 +343,7 @@ pull_mcp_images() { ' "$mcp_file" 2>/dev/null | sort -u) if [ -z "$images" ]; then - [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo ":: No Docker-based MCP servers in profile, skipping image pulls" + _vlog ":: No Docker-based MCP servers in profile, skipping image pulls" return 0 fi @@ -344,16 +357,16 @@ pull_mcp_images() { done <<< "$images" if [ -z "$missing" ]; then - [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo ":: MCP images already present, skipping pulls" + _vlog ":: MCP images already present, skipping pulls" return 0 fi - [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo ":: Pulling missing MCP server images..." + _vlog ":: Pulling missing MCP server images..." for img in $missing; do docker pull -q "$img" & done wait - [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo ":: MCP images up to date" + _vlog ":: MCP images up to date" } _phase "Pulling MCP server images" pull_mcp_images @@ -370,7 +383,7 @@ seed_skills_if_missing() { # outer if already verified the path is NOT a populated dir. rm -rf "$HOME/.claude/skills" cp -RL /opt/back2base/defaults/skills "$HOME/.claude/skills" - [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo ":: seeded $HOME/.claude/skills from image defaults" + _vlog ":: seeded $HOME/.claude/skills from image defaults" fi fi } @@ -383,7 +396,7 @@ seed_agents_if_missing() { if [ -d "$defaults" ]; then rm -rf "$HOME/.claude/agents" cp -RL "$defaults" "$HOME/.claude/agents" - [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo ":: seeded $HOME/.claude/agents from image defaults" + _vlog ":: seeded $HOME/.claude/agents from image defaults" fi fi } @@ -395,7 +408,7 @@ seed_commands_if_missing() { if [ -d /opt/back2base/defaults/commands ]; then rm -rf "$HOME/.claude/commands" cp -RL /opt/back2base/defaults/commands "$HOME/.claude/commands" - [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo ":: seeded $HOME/.claude/commands from image defaults" + _vlog ":: seeded $HOME/.claude/commands from image defaults" fi fi } @@ -412,7 +425,7 @@ seed_plugins_if_missing() { if [ -d /opt/back2base/defaults/plugins ]; then rm -rf "$HOME/.claude/plugins" cp -RL /opt/back2base/defaults/plugins "$HOME/.claude/plugins" - [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo ":: seeded $HOME/.claude/plugins from image defaults" + _vlog ":: seeded $HOME/.claude/plugins from image defaults" fi fi } diff --git a/back2base-container/lib/prelaunch-overview.sh b/back2base-container/lib/prelaunch-overview.sh index 8a4bce3..e2426c5 100644 --- a/back2base-container/lib/prelaunch-overview.sh +++ b/back2base-container/lib/prelaunch-overview.sh @@ -38,6 +38,22 @@ run_prelaunch_overview() { return 0 fi + # Content-address the overview by the repo's HEAD tree hash. The overview + # output is non-deterministic, so regenerating it every start rewrites + # CLAUDE.md and makes the whole system prompt cache-cold. ~/.claude is a + # persistent host mount, so the stored hash survives container restarts. + # Known limitation: uncommitted worktree changes don't alter HEAD^{tree}, + # so dirty-only changes won't regenerate — acceptable for a coarse overview. + local tree_hash hash_file + hash_file="$HOME/.claude/.overview-tree-hash" + tree_hash=$(git -C "$PWD" rev-parse 'HEAD^{tree}' 2>/dev/null || echo "") + if [ -n "$tree_hash" ] && [ -f "$hash_file" ] \ + && [ "$(cat "$hash_file" 2>/dev/null)" = "$tree_hash" ] \ + && grep -q 'back2base:overview-begin' "$claude_md" 2>/dev/null; then + echo ":: overview: repo unchanged (tree ${tree_hash:0:8}…) — keeping existing overview" >&2 + return 0 + fi + local prompt prompt="$(cat "$prompt_path")" @@ -150,6 +166,11 @@ run_prelaunch_overview() { return 0 fi + # Stamp the tree hash so the next start with an unchanged repo skips. + if [ -n "$tree_hash" ]; then + echo "$tree_hash" > "$hash_file" 2>/dev/null || true + fi + local lines lines=$(wc -l < "$tmp_out" | tr -d ' ') echo ":: overview: ${lines} lines, ${elapsed}s" >&2 diff --git a/back2base-container/test/entrypoint-phase-exit.bats b/back2base-container/test/entrypoint-phase-exit.bats new file mode 100644 index 0000000..974fa51 --- /dev/null +++ b/back2base-container/test/entrypoint-phase-exit.bats @@ -0,0 +1,99 @@ +#!/usr/bin/env bats +# +# Regression for the v0.38.2 "container exits the moment setup finishes" bug. +# +# Several phase functions ended with a bare verbose guard: +# [ "${BACK2BASE_VERBOSE:-0}" = "1" ] && echo "..." +# When BACK2BASE_VERBOSE is unset (the normal interactive launch) the test is +# false, the && short-circuits, and the compound command returns 1. As the +# LAST command of a function, that becomes the function's return value. The +# function is dispatched by _phase under the top-level `set -e`, so the call — +# a simple command returning 1 — trips set -e and aborts entrypoint.sh right +# after the previous phase's ✓. The container dies before `exec claude`. +# +# (At the top level `false && echo` is exempt from set -e, which is why the +# bug only manifested through a function call, not the inline guard itself.) +# +# Fix: route all verbose logging through _vlog, which always returns 0, and +# forbid inline verbose guards from creeping back in. + +setup() { + REPO_DIR="$(cd "$BATS_TEST_DIRNAME/.." && pwd)" + ENTRYPOINT="$REPO_DIR/entrypoint.sh" +} + +# Print the definition of a shell function from entrypoint.sh (sed range). +extract_fn() { + sed -n "/^$1()/,/^}/p" "$ENTRYPOINT" +} + +@test "_vlog is defined in entrypoint.sh" { + run extract_fn _vlog + [ -n "$output" ] +} + +@test "_vlog returns 0 with verbose off (safe as a function's last command)" { + fn="$(extract_fn _vlog)" + run bash -c " + set -e + unset BACK2BASE_VERBOSE + $fn + _vlog ':: some detail' + echo RC=\$? + " + [ "$status" -eq 0 ] + [[ "$output" == *"RC=0"* ]] +} + +@test "_vlog still prints when verbose on" { + fn="$(extract_fn _vlog)" + run bash -c " + set -e + export BACK2BASE_VERBOSE=1 + $fn + _vlog ':: visible detail' + " + [ "$status" -eq 0 ] + [[ "$output" == *"visible detail"* ]] +} + +@test "_vlog is silent when verbose off" { + fn="$(extract_fn _vlog)" + run bash -c " + set -e + unset BACK2BASE_VERBOSE + $fn + _vlog ':: hidden detail' + echo DONE + " + [ "$status" -eq 0 ] + [[ "$output" != *"hidden detail"* ]] + [[ "$output" == *"DONE"* ]] +} + +@test "a function ending in _vlog returns 0 under set -e with verbose off" { + vlog="$(extract_fn _vlog)" + run bash -c " + set -e + unset BACK2BASE_VERBOSE + $vlog + some_phase() { + local x=1 + _vlog ':: tail detail' + } + some_phase + echo SURVIVED + " + [ "$status" -eq 0 ] + [[ "$output" == *"SURVIVED"* ]] +} + +@test "no inline BACK2BASE_VERBOSE && guards remain (use _vlog instead)" { + # A bare `[ ... BACK2BASE_VERBOSE ... ] && echo` is the footgun. After the + # fix every such line must be gone — verbose logging goes through _vlog, + # which is exit-status-safe in any position. + # Exclude comment lines (the _vlog doc block intentionally shows the old + # idiom as the anti-pattern to avoid). + run grep -nE '^[^#]*\[ "\$\{BACK2BASE_VERBOSE:-0\}" = "1" \][[:space:]]*&&' "$ENTRYPOINT" + [ -z "$output" ] +} diff --git a/back2base-container/test/prelaunch-overview.bats b/back2base-container/test/prelaunch-overview.bats index 5334cdb..4354d70 100644 --- a/back2base-container/test/prelaunch-overview.bats +++ b/back2base-container/test/prelaunch-overview.bats @@ -127,6 +127,69 @@ exit 0' echo "$output" | grep -q 'still running' } +@test "skips regeneration when tree hash unchanged and markers present" { + export BACK2BASE_OVERVIEW=1 + stub_claude 'touch "$CLAUDE_INVOKED_MARKER"; echo "fresh overview"; exit 0' + export CLAUDE_INVOKED_MARKER="$TEST_TMP/claude-ran" + + # A git repo whose HEAD tree hash we pre-store, plus existing markers. + REPO_DIR="$TEST_TMP/repo" + mkdir -p "$REPO_DIR" && cd "$REPO_DIR" + git init -q . && echo hi > f.txt && git add -A \ + && git -c user.email=t@t -c user.name=t commit -qm init + printf '%s\n' "" "old overview" "" \ + >> "$HOME/.claude/CLAUDE.md" + git rev-parse 'HEAD^{tree}' > "$HOME/.claude/.overview-tree-hash" + + . "$HELPER" + run run_prelaunch_overview + [ "$status" -eq 0 ] + echo "$output" | grep -q 'repo unchanged' + [ ! -f "$CLAUDE_INVOKED_MARKER" ] + grep -q 'old overview' "$HOME/.claude/CLAUDE.md" +} + +@test "regenerates when tree hash differs" { + export BACK2BASE_OVERVIEW=1 + stub_claude 'touch "$CLAUDE_INVOKED_MARKER"; echo "fresh overview"; exit 0' + export CLAUDE_INVOKED_MARKER="$TEST_TMP/claude-ran" + + REPO_DIR="$TEST_TMP/repo" + mkdir -p "$REPO_DIR" && cd "$REPO_DIR" + git init -q . && echo hi > f.txt && git add -A \ + && git -c user.email=t@t -c user.name=t commit -qm init + printf '%s\n' "" "old overview" "" \ + >> "$HOME/.claude/CLAUDE.md" + echo "stale-hash-value" > "$HOME/.claude/.overview-tree-hash" + + . "$HELPER" + run run_prelaunch_overview + [ "$status" -eq 0 ] + [ -f "$CLAUDE_INVOKED_MARKER" ] + grep -q 'fresh overview' "$HOME/.claude/CLAUDE.md" + # Hash file refreshed to the current tree + [ "$(cat "$HOME/.claude/.overview-tree-hash")" = "$(git rev-parse 'HEAD^{tree}')" ] +} + +@test "regenerates when markers absent even if hash matches" { + export BACK2BASE_OVERVIEW=1 + stub_claude 'touch "$CLAUDE_INVOKED_MARKER"; echo "fresh overview"; exit 0' + export CLAUDE_INVOKED_MARKER="$TEST_TMP/claude-ran" + + REPO_DIR="$TEST_TMP/repo" + mkdir -p "$REPO_DIR" && cd "$REPO_DIR" + git init -q . && echo hi > f.txt && git add -A \ + && git -c user.email=t@t -c user.name=t commit -qm init + # Matching hash but NO markers in CLAUDE.md (e.g. file was reset) + git rev-parse 'HEAD^{tree}' > "$HOME/.claude/.overview-tree-hash" + + . "$HELPER" + run run_prelaunch_overview + [ "$status" -eq 0 ] + [ -f "$CLAUDE_INVOKED_MARKER" ] + grep -q 'fresh overview' "$HOME/.claude/CLAUDE.md" +} + @test "missing claude binary skips gracefully" { export BACK2BASE_OVERVIEW=1 rm -f "$STUB_BIN/claude" diff --git a/gid.go b/gid.go index 212555e..a67ffaa 100644 --- a/gid.go +++ b/gid.go @@ -33,21 +33,26 @@ func probeDockerGID() string { return gid } +// resolveGID resolves the docker socket GID. Order: env override → cache +// file → live probe (≈0.5–1.5s busybox spin-up; refreshes the cache) → +// "999" default. The cache is consulted before probing because the socket +// GID is effectively static per machine — if it ever changes (Docker +// reinstall), delete the cache file or set BACK2BASE_DOCKER_GID. func resolveGID(envOverride, cacheFile string) string { if envOverride != "" { return envOverride } - if probed := probeGIDFunc(); probed != "" { - os.WriteFile(cacheFile, []byte(probed), 0644) - return probed - } - if cached, err := os.ReadFile(cacheFile); err == nil { if gid, ok := parseGIDOutput(string(cached)); ok { return gid } } + if probed := probeGIDFunc(); probed != "" { + os.WriteFile(cacheFile, []byte(probed), 0644) + return probed + } + return "999" } diff --git a/gid_test.go b/gid_test.go index 8be998b..70109e4 100644 --- a/gid_test.go +++ b/gid_test.go @@ -69,3 +69,39 @@ func TestGIDEnvOverride(t *testing.T) { t.Errorf("gid = %q, want 42 from env", gid) } } + +func TestGIDCachePreferredOverProbe(t *testing.T) { + orig := probeGIDFunc + probeCalled := false + probeGIDFunc = func() string { probeCalled = true; return "111" } + defer func() { probeGIDFunc = orig }() + + dir := t.TempDir() + cacheFile := filepath.Join(dir, "docker-gid") + os.WriteFile(cacheFile, []byte("991"), 0644) + + gid := resolveGID("", cacheFile) + if gid != "991" { + t.Errorf("gid = %q, want 991 from cache", gid) + } + if probeCalled { + t.Error("probe ran despite valid cache — cache must be consulted first") + } +} + +func TestGIDProbeWritesCache(t *testing.T) { + orig := probeGIDFunc + probeGIDFunc = func() string { return "555" } + defer func() { probeGIDFunc = orig }() + + dir := t.TempDir() + cacheFile := filepath.Join(dir, "docker-gid") // doesn't exist yet + + if gid := resolveGID("", cacheFile); gid != "555" { + t.Errorf("gid = %q, want 555 from probe", gid) + } + cached, err := os.ReadFile(cacheFile) + if err != nil || string(cached) != "555" { + t.Errorf("cache = %q (err %v), want 555 persisted", cached, err) + } +} diff --git a/run.go b/run.go index f1b6266..4f7eb3e 100644 --- a/run.go +++ b/run.go @@ -186,37 +186,38 @@ func runClaude(cmd *cobra.Command, args []string) error { // We only need --no-cache --pull when a "critical" file actually changed // — Dockerfile, top-level *.sh (entrypoint, init-firewall), or lib/*.sh // (shell helpers shipped into the image). Anything else: a normal `build` - // is enough. - criticalHashPath := filepath.Join(s.cfg.Home, ".payload-critical-hash") - newHash, hashErr := criticalFilesHash(shipFS()) - if hashErr != nil { - // If we can't hash, fall back to the conservative behavior: - // when payload was extracted, do a no-cache rebuild. - if s.extracted { + // is enough. When nothing was extracted this run, decideRebuild is a + // guaranteed no-op, so skip hashing the embedded FS entirely. + if s.extracted { + criticalHashPath := filepath.Join(s.cfg.Home, ".payload-critical-hash") + newHash, hashErr := criticalFilesHash(shipFS()) + if hashErr != nil { + // If we can't hash, fall back to the conservative behavior: + // when payload was extracted, do a no-cache rebuild. fmt.Fprintf(os.Stderr, ":: warning: hashing critical files failed (%v) — falling back to --no-cache --pull\n", hashErr) if err := runBuild(true); err != nil { return err } - } - } else { - oldHash, _ := readCriticalHash(criticalHashPath) - rebuild, noCache := decideRebuild(s.extracted, oldHash, newHash) - if rebuild { - if noCache { - fmt.Fprintln(os.Stderr, ":: critical container files changed — rebuilding image (--no-cache --pull)") - } else { - fmt.Fprintln(os.Stderr, ":: container payload updated — rebuilding image (cached layers reused)") - } - if err := runBuild(noCache); err != nil { - return err - } - // Only persist the new hash after a successful no-cache rebuild - // — otherwise a half-finished upgrade could leave the cache - // claiming "all current" when the image hasn't actually been - // rebuilt with the new critical files. - if noCache { - if err := writeCriticalHash(criticalHashPath, newHash); err != nil { - fmt.Fprintf(os.Stderr, ":: warning: could not persist critical hash: %v\n", err) + } else { + oldHash, _ := readCriticalHash(criticalHashPath) + rebuild, noCache := decideRebuild(s.extracted, oldHash, newHash) + if rebuild { + if noCache { + fmt.Fprintln(os.Stderr, ":: critical container files changed — rebuilding image (--no-cache --pull)") + } else { + fmt.Fprintln(os.Stderr, ":: container payload updated — rebuilding image (cached layers reused)") + } + if err := runBuild(noCache); err != nil { + return err + } + // Only persist the new hash after a successful no-cache rebuild + // — otherwise a half-finished upgrade could leave the cache + // claiming "all current" when the image hasn't actually been + // rebuilt with the new critical files. + if noCache { + if err := writeCriticalHash(criticalHashPath, newHash); err != nil { + fmt.Fprintf(os.Stderr, ":: warning: could not persist critical hash: %v\n", err) + } } } } @@ -269,16 +270,30 @@ func resolveNamespace(repoPath string) string { return ns } +// gitRootCache memoizes gitRoot per directory. A launch calls gitRoot for +// the cwd (resolveRepoPath) and again for the resolved root +// (resolveNamespace); caching the result under both keys saves the second +// `git rev-parse` subprocess. +var gitRootCache = map[string]string{} + // gitRoot returns the repo root containing dir, or "" if not in a git tree. func gitRoot(dir string) string { if dir == "" { return "" } + if root, ok := gitRootCache[dir]; ok { + return root + } out, err := exec.Command("git", "-C", dir, "rev-parse", "--show-toplevel").Output() - if err != nil { - return "" + root := "" + if err == nil { + root = strings.TrimSpace(string(out)) + } + gitRootCache[dir] = root + if root != "" { + gitRootCache[root] = root // the root's root is itself } - return strings.TrimSpace(string(out)) + return root } // criticalFilesHash computes a sha256 over the files whose contents directly