From b461092b29afaccfe245be6e810ff32dad8437ba Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 21 Nov 2026 15:06:17 +0000 Subject: [PATCH 1/2] feat(ask): experimental bartender smallest-sufficient retrieval Prototype Alexandria-style summary cards and AFR-style shortlisting behind codemap ask / MCP ask, returning MATCH with compact cards or explicit NO_MATCH. Opt-in only; credits everoo/bartender and documents the mapping. Co-authored-by: Jordan Coin Jackson --- README.md | 8 +- ask/ask.go | 468 +++++++++++++++++++++++++++++++++++ ask/ask_test.go | 155 ++++++++++++ ask_cmd.go | 103 ++++++++ ask_cmd_test.go | 55 ++++ docs/COMMANDS.md | 14 ++ docs/MCP.md | 8 +- docs/design/BARTENDER-ASK.md | 57 +++++ main.go | 10 + mcp/ask_test.go | 65 +++++ mcp/main.go | 40 +++ mcp/surface_hygiene_test.go | 2 + 12 files changed, 981 insertions(+), 4 deletions(-) create mode 100644 ask/ask.go create mode 100644 ask/ask_test.go create mode 100644 ask_cmd.go create mode 100644 ask_cmd_test.go create mode 100644 docs/design/BARTENDER-ASK.md create mode 100644 mcp/ask_test.go diff --git a/README.md b/README.md index 632fb51..b951d10 100644 --- a/README.md +++ b/README.md @@ -117,14 +117,19 @@ codemap --deps . # dependency flow codemap --importers # who imports a file codemap blast-radius # review bundle: diff + deps + importers codemap find "" # where is X defined +codemap ask "" # EXPERIMENTAL: smallest-sufficient cards or NO_MATCH codemap handoff . # save a handoff for the next agent codemap doctor # validate agent integrations ``` +### Experimental: `codemap ask` (bartender) + +Opt-in prototype of [bartender](https://github.com/everoo/bartender) ideas from [everoo](https://github.com/everoo): compact, deduplicated summary cards from codemap's map, Adaptive Fuzzy Retrieval-style shortlisting, and an explicit `NO_MATCH` when nothing is reliable enough. Default commands are unchanged. Design map and open questions: [docs/design/BARTENDER-ASK.md](docs/design/BARTENDER-ASK.md). + ## Agent integration - **Hooks**: automatic context at session start, before and after edits, and at compaction. [docs/HOOKS.md](docs/HOOKS.md) -- **MCP**: `codemap mcp` serves 19 tools over stdio. [docs/MCP.md](docs/MCP.md) +- **MCP**: `codemap mcp` serves 20 tools over stdio (including experimental `ask`). [docs/MCP.md](docs/MCP.md) - **Codex**: `codemap setup` configures it; trust the hooks once from `/hooks`. [docs/MCP.md](docs/MCP.md#codex) ## Go deeper @@ -137,6 +142,7 @@ codemap doctor # validate agent integrations | see every flag and mode | [docs/COMMANDS.md](docs/COMMANDS.md) | | tune what the agent sees | [docs/CONFIG.md](docs/CONFIG.md) | | use the MCP tools or Codex | [docs/MCP.md](docs/MCP.md) | +| try experimental ask / bartender cards | [docs/design/BARTENDER-ASK.md](docs/design/BARTENDER-ASK.md) | | add a language | [CONTRIBUTING.md](CONTRIBUTING.md#adding-a-new-language) | ## Roadmap diff --git a/ask/ask.go b/ask/ask.go new file mode 100644 index 0000000..28a97cb --- /dev/null +++ b/ask/ask.go @@ -0,0 +1,468 @@ +// Package ask is an EXPERIMENTAL bartender-inspired retrieval surface. +// +// It builds compact, deduplicated summary cards from codemap's existing +// dependency map and returns the smallest sufficient answer for a question, +// or an explicit NO_MATCH when nothing is reliable enough. +// +// Design credit: [bartender](https://github.com/everoo/bartender) by everoo +// (Alexandria cards, Adaptive Fuzzy Retrieval, smallest-sufficient / NO_MATCH). +// See docs/design/BARTENDER-ASK.md for the concept map and open questions. +package ask + +import ( + "context" + "crypto/sha1" + "encoding/hex" + "fmt" + "io" + "path" + "sort" + "strings" + "unicode" + + "codemap/analysis" + "codemap/find" + "codemap/scanner" +) + +const ( + Schema = "codemap.ask/v1-experimental" + StatusMatch = "MATCH" + StatusNoMatch = "NO_MATCH" + + // DefaultLimit is how many find hits to consider before adaptive cut. + DefaultLimit = 8 + // DefaultBudgetBytes caps the rendered answer (cards + framing). + DefaultBudgetBytes = 1200 + // minScoreFloor rejects weak lexical matches as unreliable for a MATCH. + minScoreFloor = 1.5 + // relativeKeep keeps a trailing hit only when it is within this fraction + // of the best score (adaptive shortlist, not a fixed top-K dump). + relativeKeep = 0.45 + maxSymbols = 5 + maxLinks = 3 + maxCards = 5 +) + +// Card is a compact routing card derived from the codemap map (Alexandria-inspired). +type Card struct { + ID string `json:"id"` + Revision string `json:"revision"` + Type string `json:"type"` + Label string `json:"label"` + Capsule string `json:"capsule"` + Paths []string `json:"paths"` + Links []string `json:"links,omitempty"` + Score float64 `json:"score,omitempty"` +} + +// Answer is the smallest sufficient retrieval outcome for one question. +type Answer struct { + Schema string `json:"schema"` + Experimental bool `json:"experimental"` + Status string `json:"status"` + Query string `json:"query"` + Message string `json:"message"` + Cards []Card `json:"cards,omitempty"` + Coverage analysis.Coverage `json:"coverage"` + BudgetBytes int `json:"budget_bytes"` + UsedBytes int `json:"used_bytes"` +} + +// Options controls retrieval budgets for one ask call. +type Options struct { + Limit int + BudgetBytes int +} + +// Run answers query from root's existing codemap scan: find ranks candidates, +// cards summarize them, and adaptive early-stop keeps only what fits the budget. +func Run(ctx context.Context, root string, filters scanner.Filters, query string, opts Options) (Answer, error) { + query = strings.TrimSpace(query) + answer := Answer{ + Schema: Schema, + Experimental: true, + Query: query, + BudgetBytes: opts.BudgetBytes, + } + if answer.BudgetBytes <= 0 { + answer.BudgetBytes = DefaultBudgetBytes + } + if query == "" { + answer.Status = StatusNoMatch + answer.Message = noMatchMessage("empty query") + answer.UsedBytes = len(answer.Message) + return answer, nil + } + + limit := opts.Limit + if limit <= 0 { + limit = DefaultLimit + } + + outcome, err := scanner.ScanForDeps(ctx, root, filters) + if err != nil { + return Answer{}, err + } + answer.Coverage = scanner.CoverageFromSources(outcome.Sources) + + hits := find.Rank(outcome.Analyses, query, limit) + var graph *scanner.FileGraph + if fg, graphErr := scanner.BuildFileGraphFromOutcome(ctx, root, outcome, filters); graphErr == nil { + graph = fg + answer.Coverage = scanner.CoverageFromSources(fg.Coverage.Sources) + for i := range hits { + importers := fg.Importers[hits[i].Path] + hits[i].Importers = len(importers) + hits[i].Hub = fg.IsFileHub(hits[i].Path) + if pkg, shared := fg.SharedGoPackage(hits[i].Path); shared { + hits[i].Package = pkg + } + } + } + + reliable := filterReliableHits(hits, query) + if len(reliable) == 0 { + answer.Status = StatusNoMatch + answer.Message = noMatchMessage("") + answer.UsedBytes = len(RenderText(answer)) + return answer, nil + } + + byPath := make(map[string]scanner.FileAnalysis, len(outcome.Analyses)) + for _, a := range outcome.Analyses { + byPath[a.Path] = a + } + + shortlist := adaptiveShortlist(reliable) + cards := make([]Card, 0, len(shortlist)) + seen := make(map[string]struct{}) + for _, hit := range shortlist { + card := buildCard(hit, byPath[hit.Path], graph) + if _, dup := seen[card.ID]; dup { + continue + } + seen[card.ID] = struct{}{} + cards = append(cards, card) + } + + kept := selectWithinBudget(cards, answer.BudgetBytes) + if len(kept) == 0 { + answer.Status = StatusNoMatch + answer.Message = noMatchMessage("candidates exceeded compact budget") + answer.UsedBytes = len(RenderText(answer)) + return answer, nil + } + + answer.Status = StatusMatch + answer.Cards = kept + answer.Message = matchMessage(kept) + answer.UsedBytes = len(RenderText(answer)) + return answer, nil +} + +func filterReliableHits(hits []find.Hit, query string) []find.Hit { + qtokens := splitIdentTokens(query) + if len(qtokens) == 0 { + return nil + } + out := make([]find.Hit, 0, len(hits)) + for _, hit := range hits { + if hit.Score < minScoreFloor { + continue + } + overlap := overlapQueryTokens(hit, qtokens) + need := 1 + if len(qtokens) >= 2 { + // Multi-word questions must share at least two tokens with the + // card surface so a lone common verb ("save") cannot MATCH. + need = 2 + } + if overlap < need { + continue + } + out = append(out, hit) + } + return out +} + +// splitIdentTokens mirrors find's identifier splitting: camelCase, snake_case, +// path separators, and punctuation all become lowercase words of length >= 2. +func splitIdentTokens(s string) []string { + var out []string + var cur []rune + flush := func() { + if len(cur) >= 2 { + out = append(out, strings.ToLower(string(cur))) + } + cur = cur[:0] + } + runes := []rune(s) + for i, r := range runes { + switch { + case !unicode.IsLetter(r) && !unicode.IsDigit(r): + flush() + case unicode.IsUpper(r) && len(cur) > 0 && (!unicode.IsUpper(runes[i-1]) || + i+1 < len(runes) && unicode.IsLower(runes[i+1])): + flush() + cur = append(cur, r) + default: + cur = append(cur, r) + } + } + flush() + seen := make(map[string]struct{}, len(out)) + uniq := out[:0] + for _, tok := range out { + if _, ok := seen[tok]; ok { + continue + } + seen[tok] = struct{}{} + uniq = append(uniq, tok) + } + return uniq +} + +func overlapQueryTokens(hit find.Hit, qtokens []string) int { + parts := splitIdentTokens(hit.Path + " " + strings.Join(hit.Matched, " ")) + have := make(map[string]struct{}, len(parts)) + for _, p := range parts { + have[p] = struct{}{} + } + n := 0 + for _, q := range qtokens { + if _, ok := have[q]; ok { + n++ + } + } + return n +} + +func adaptiveShortlist(hits []find.Hit) []find.Hit { + if len(hits) == 0 { + return nil + } + best := hits[0].Score + out := make([]find.Hit, 0, len(hits)) + for _, hit := range hits { + if hit.Score < minScoreFloor { + break + } + if hit.Score < best*relativeKeep && len(out) > 0 { + break + } + out = append(out, hit) + if len(out) >= maxCards { + break + } + } + return out +} + +func buildCard(hit find.Hit, analysis scanner.FileAnalysis, graph *scanner.FileGraph) Card { + cardType := "file" + if hit.Hub { + cardType = "hub" + } + if hit.Package != "" { + cardType = "package" + } + + base := path.Base(hit.Path) + label := base + if hit.Hub { + label += " hub" + } + if hit.Package != "" { + label = hit.Package + " package" + } + label = trimTokens(label, 15) + + symbols := append([]string{}, analysis.Functions...) + symbols = append(symbols, analysis.Types...) + if len(symbols) > maxSymbols { + symbols = symbols[:maxSymbols] + } + + var links []string + importers, imports := 0, len(analysis.Imports) + if graph != nil { + importers = len(graph.Importers[hit.Path]) + if list := graph.Importers[hit.Path]; len(list) > 0 { + links = append(links, takeBasenames(list, maxLinks)...) + } + if list := graph.Imports[hit.Path]; len(list) > 0 { + links = append(links, takeBasenames(list, maxLinks)...) + } + if imports == 0 { + imports = len(graph.Imports[hit.Path]) + } + } + links = uniqueStable(links) + + lang := analysis.Language + if lang == "" { + lang = strings.TrimPrefix(path.Ext(hit.Path), ".") + } + + parts := []string{lang} + if importers > 0 || hit.Importers > 0 { + n := importers + if n == 0 { + n = hit.Importers + } + parts = append(parts, fmt.Sprintf("←%d", n)) + } + if imports > 0 { + parts = append(parts, fmt.Sprintf("→%d", imports)) + } + if len(symbols) > 0 { + parts = append(parts, "symbols: "+strings.Join(symbols, ", ")) + } + if len(hit.Matched) > 0 { + parts = append(parts, "matched: "+strings.Join(hit.Matched, ", ")) + } + capsule := trimTokens(strings.Join(parts, " · "), 55) + + id := "file:" + hit.Path + if hit.Package != "" { + id = "package:" + hit.Package + } + revision := shortHash(id + "|" + capsule) + + return Card{ + ID: id, + Revision: revision, + Type: cardType, + Label: label, + Capsule: capsule, + Paths: []string{hit.Path}, + Links: links, + Score: hit.Score, + } +} + +func selectWithinBudget(cards []Card, budget int) []Card { + if budget <= 0 { + budget = DefaultBudgetBytes + } + framing := len(matchMessage(nil)) + 64 + remaining := budget - framing + if remaining < 80 { + remaining = 80 + } + kept := make([]Card, 0, len(cards)) + used := 0 + for _, card := range cards { + cost := len(card.Label) + len(card.Capsule) + len(card.ID) + 24 + for _, p := range card.Paths { + cost += len(p) + } + if len(kept) > 0 && used+cost > remaining { + break + } + kept = append(kept, card) + used += cost + if len(kept) >= maxCards { + break + } + } + return kept +} + +func matchMessage(cards []Card) string { + if len(cards) == 0 { + return "MATCH — compact cards selected" + } + if len(cards) == 1 { + return "MATCH — smallest sufficient card" + } + return fmt.Sprintf("MATCH — %d compact cards (adaptive shortlist)", len(cards)) +} + +func noMatchMessage(detail string) string { + base := "NO_MATCH — no sufficiently reliable relevant record found" + if detail == "" { + return base + } + return base + " (" + detail + ")" +} + +// RenderText writes the agent-facing compact answer. +func RenderText(a Answer) string { + var b strings.Builder + fmt.Fprintf(&b, "EXPERIMENTAL codemap ask (%s)\n", a.Schema) + fmt.Fprintf(&b, "%s\n", a.Message) + if a.Query != "" { + fmt.Fprintf(&b, "query: %s\n", a.Query) + } + for i, card := range a.Cards { + fmt.Fprintf(&b, "%d. %s [%s] %s\n", i+1, card.Paths[0], card.Type, card.Label) + fmt.Fprintf(&b, " %s\n", card.Capsule) + if len(card.Links) > 0 { + fmt.Fprintf(&b, " links: %s\n", strings.Join(card.Links, ", ")) + } + fmt.Fprintf(&b, " id=%s rev=%s score=%.3f\n", card.ID, card.Revision, card.Score) + } + notes := make([]string, 0, len(a.Coverage.Sources)) + for _, s := range a.Coverage.Sources { + if s.Detail != "" { + notes = append(notes, s.Detail) + } + } + if a.Coverage.Status != "" { + if len(notes) == 0 { + fmt.Fprintf(&b, "Coverage: %s\n", a.Coverage.Status) + } else { + fmt.Fprintf(&b, "Coverage: %s — %s\n", a.Coverage.Status, strings.Join(notes, "; ")) + } + } + fmt.Fprintf(&b, "budget_cap: %d bytes\n", a.BudgetBytes) + return b.String() +} + +// Render writes RenderText to w. +func Render(w io.Writer, a Answer) { + _, _ = io.WriteString(w, RenderText(a)) +} + +func takeBasenames(paths []string, n int) []string { + out := make([]string, 0, n) + for _, p := range paths { + out = append(out, path.Base(p)) + if len(out) >= n { + break + } + } + return out +} + +func uniqueStable(in []string) []string { + seen := make(map[string]struct{}, len(in)) + out := make([]string, 0, len(in)) + for _, s := range in { + if s == "" { + continue + } + if _, ok := seen[s]; ok { + continue + } + seen[s] = struct{}{} + out = append(out, s) + } + sort.Strings(out) + return out +} + +func trimTokens(s string, max int) string { + fields := strings.Fields(s) + if len(fields) <= max { + return strings.Join(fields, " ") + } + return strings.Join(fields[:max], " ") +} + +func shortHash(s string) string { + sum := sha1.Sum([]byte(s)) + return hex.EncodeToString(sum[:6]) +} diff --git a/ask/ask_test.go b/ask/ask_test.go new file mode 100644 index 0000000..6da1e29 --- /dev/null +++ b/ask/ask_test.go @@ -0,0 +1,155 @@ +package ask + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "codemap/find" + "codemap/scanner" +) + +func TestRunReturnsMatchWithCompactCards(t *testing.T) { + root := writeAskFixture(t) + answer, err := Run(context.Background(), root, scanner.Filters{}, "UseTheme SaveTheme", Options{Limit: 5, BudgetBytes: 900}) + if err != nil { + t.Fatal(err) + } + if answer.Status != StatusMatch { + t.Fatalf("status = %s message = %q", answer.Status, answer.Message) + } + if !answer.Experimental || answer.Schema != Schema { + t.Fatalf("experimental markers missing: %+v", answer) + } + if len(answer.Cards) == 0 { + t.Fatal("expected at least one card") + } + text := RenderText(answer) + if !strings.Contains(text, "EXPERIMENTAL") || !strings.Contains(text, "MATCH") { + t.Fatalf("render missing markers:\n%s", text) + } + if answer.UsedBytes <= 0 { + t.Fatalf("used_bytes=%d", answer.UsedBytes) + } + for _, card := range answer.Cards { + if card.ID == "" || card.Revision == "" || card.Capsule == "" || card.Label == "" { + t.Fatalf("incomplete card: %+v", card) + } + if len(strings.Fields(card.Label)) > 15 { + t.Fatalf("label too long: %q", card.Label) + } + } +} + +func TestRunReturnsExplicitNoMatch(t *testing.T) { + root := writeAskFixture(t) + answer, err := Run(context.Background(), root, scanner.Filters{}, "quantum flux capacitor zucchini", Options{}) + if err != nil { + t.Fatal(err) + } + if answer.Status != StatusNoMatch { + t.Fatalf("status = %s cards=%+v", answer.Status, answer.Cards) + } + if !strings.Contains(answer.Message, StatusNoMatch) { + t.Fatalf("message = %q", answer.Message) + } + if len(answer.Cards) != 0 { + t.Fatalf("NO_MATCH must not return cards, got %+v", answer.Cards) + } +} + +func TestRunEmptyQueryIsNoMatch(t *testing.T) { + answer, err := Run(context.Background(), t.TempDir(), scanner.Filters{}, " ", Options{}) + if err != nil { + t.Fatal(err) + } + if answer.Status != StatusNoMatch || !strings.Contains(answer.Message, "empty query") { + t.Fatalf("got %+v", answer) + } +} + +func TestAdaptiveShortlistStopsOnWeakTrail(t *testing.T) { + hits := []find.Hit{ + {Path: "a.go", Score: 8.0}, + {Path: "b.go", Score: 6.0}, + {Path: "c.go", Score: 2.0}, // below relativeKeep of best + {Path: "d.go", Score: 0.1}, // below floor + } + got := adaptiveShortlist(hits) + if len(got) != 2 || got[0].Path != "a.go" || got[1].Path != "b.go" { + t.Fatalf("shortlist = %+v", got) + } +} + +func TestFilterReliableHitsRequiresOverlap(t *testing.T) { + hits := []find.Hit{ + {Path: "main_test.go", Score: 5.5, Matched: []string{"TestNonexistentPath"}}, + {Path: "theme/use_theme.go", Score: 9.0, Matched: []string{"UseTheme", "SaveTheme"}}, + } + if got := filterReliableHits(hits, "quantum flux capacitor zucchini"); len(got) != 0 { + t.Fatalf("expected NO reliable hits for nonsense, got %+v", got) + } + if got := filterReliableHits(hits, "nonexistent flibbertigibbet xyzzy"); len(got) != 0 { + t.Fatalf("single accidental token among many should NO_MATCH, got %+v", got) + } + got := filterReliableHits(hits, "UseTheme SaveTheme") + if len(got) != 1 || got[0].Path != "theme/use_theme.go" { + t.Fatalf("UseTheme SaveTheme filter = %+v", got) + } + if got := filterReliableHits(hits, "theme persistence"); len(got) != 0 { + // Lexical only: "persistence" does not stem to Persist/Preference. + t.Fatalf("synonym-only second token should stay NO_MATCH in this slice, got %+v", got) + } +} + +func TestSelectWithinBudgetKeepsSmallestPrefix(t *testing.T) { + cards := []Card{ + {ID: "1", Label: "one", Capsule: "alpha beta gamma", Paths: []string{"a.go"}, Score: 2}, + {ID: "2", Label: "two", Capsule: strings.Repeat("word ", 40), Paths: []string{"b.go"}, Score: 1.5}, + {ID: "3", Label: "three", Capsule: "delta", Paths: []string{"c.go"}, Score: 1.2}, + } + kept := selectWithinBudget(cards, 220) + if len(kept) < 1 || kept[0].ID != "1" { + t.Fatalf("kept = %+v", kept) + } + if len(kept) > 2 { + t.Fatalf("budget should stop early, kept %d", len(kept)) + } +} + +func TestDedupPackageCardsShareLogicalID(t *testing.T) { + hit := find.Hit{Path: "pkg/a.go", Package: "example.com/pkg", Score: 1.2, Importers: 3} + analysis := scanner.FileAnalysis{Path: "pkg/a.go", Language: "go", Functions: []string{"Load"}} + first := buildCard(hit, analysis, nil) + second := buildCard(hit, analysis, nil) + if first.ID != second.ID || first.ID != "package:example.com/pkg" { + t.Fatalf("ids = %q %q", first.ID, second.ID) + } + if first.Revision != second.Revision { + t.Fatal("identical capsules should share revision") + } +} + +func writeAskFixture(t *testing.T) string { + t.Helper() + root := t.TempDir() + files := map[string]string{ + "go.mod": "module fixture\n\ngo 1.24\n", + "theme/use_theme.go": "package theme\n\nfunc UseTheme() {}\nfunc SaveTheme() {}\n", + "storage/preferences.go": "package storage\n\nfunc LoadTheme() {}\nfunc PersistPreference() {}\n", + "net/client.go": "package net\n\nfunc FetchJSON() {}\nfunc Retry() {}\n", + "unrelated/math.go": "package unrelated\n\nfunc Add(a, b int) int { return a + b }\n", + } + for name, body := range files { + path := filepath.Join(root, name) + 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) + } + } + return root +} diff --git a/ask_cmd.go b/ask_cmd.go new file mode 100644 index 0000000..3bb30c3 --- /dev/null +++ b/ask_cmd.go @@ -0,0 +1,103 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "os" + "path/filepath" + "strings" + + "codemap/ask" + "codemap/cmd" + "codemap/config" + "codemap/scanner" +) + +func runAskSubcommand(args []string, launchDir string) int { + fs := flag.NewFlagSet("ask", flag.ContinueOnError) + fs.SetOutput(os.Stderr) + limit := fs.Int("limit", ask.DefaultLimit, "Maximum candidate cards to consider before adaptive cut") + budget := fs.Int("budget", ask.DefaultBudgetBytes, "Byte budget for the compact answer") + jsonMode := fs.Bool("json", false, "Emit a single JSON object") + fs.Usage = func() { + fmt.Fprintln(os.Stderr, "Usage: codemap ask [options] ") + fmt.Fprintln(os.Stderr) + fmt.Fprintln(os.Stderr, "EXPERIMENTAL — bartender-inspired smallest-sufficient context.") + fmt.Fprintln(os.Stderr, "Builds compact deduplicated summary cards from codemap's map and") + fmt.Fprintln(os.Stderr, "returns MATCH with the smallest useful set, or explicit NO_MATCH.") + fmt.Fprintln(os.Stderr, "Does not change default codemap commands. See docs/design/BARTENDER-ASK.md.") + fmt.Fprintln(os.Stderr) + fmt.Fprintln(os.Stderr, "Credit: https://github.com/everoo/bartender (everoo)") + fmt.Fprintln(os.Stderr) + fmt.Fprintln(os.Stderr, "Options:") + fs.PrintDefaults() + } + var words []string + rest := args + for { + if err := fs.Parse(rest); err != nil { + if errors.Is(err, flag.ErrHelp) { + return 0 + } + return 2 + } + rest = fs.Args() + if len(rest) == 0 { + break + } + words = append(words, rest[0]) + rest = rest[1:] + } + query := strings.TrimSpace(strings.Join(words, " ")) + if query == "" { + fmt.Fprintln(os.Stderr, "Error: codemap ask needs a question") + return 2 + } + if *limit <= 0 { + fmt.Fprintln(os.Stderr, "Error: --limit must be greater than zero") + return 2 + } + if *budget <= 0 { + fmt.Fprintln(os.Stderr, "Error: --budget must be greater than zero") + return 2 + } + + absRoot, err := filepath.Abs(launchDir) + if err == nil { + absRoot, _, err = cmd.ResolveNearestGitRoot(absRoot) + } + if err == nil { + _, err = cmd.ValidateProjectPath(absRoot) + } + if err != nil { + fmt.Fprintf(os.Stderr, "Error resolving project root: %v\n", err) + return 1 + } + + fmt.Fprintln(os.Stderr, "EXPERIMENTAL: codemap ask (bartender prototype). Default commands are unchanged.") + + cmd.EnsureAutoConfig(absRoot) + cfg := config.Load(absRoot) + answer, err := ask.Run(context.Background(), absRoot, scanner.Filters{Only: cfg.Only, Exclude: cfg.Exclude, MaxFiles: cfg.MaxFiles}, query, ask.Options{ + Limit: *limit, + BudgetBytes: *budget, + }) + if err != nil { + fmt.Fprintf(os.Stderr, "Error answering question: %v\n", err) + return 1 + } + if *jsonMode { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + if err := enc.Encode(answer); err != nil { + fmt.Fprintf(os.Stderr, "Error encoding JSON: %v\n", err) + return 1 + } + return 0 + } + ask.Render(os.Stdout, answer) + return 0 +} diff --git a/ask_cmd_test.go b/ask_cmd_test.go new file mode 100644 index 0000000..fc79007 --- /dev/null +++ b/ask_cmd_test.go @@ -0,0 +1,55 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestAskSubcommandMatchAndNoMatch(t *testing.T) { + root := t.TempDir() + files := map[string]string{ + "go.mod": "module fixture\n\ngo 1.24\n", + "theme/use_theme.go": "package theme\n\nfunc UseTheme() {}\nfunc SaveTheme() {}\n", + "net/client.go": "package net\n\nfunc FetchJSON() {}\n", + } + for name, body := range files { + path := filepath.Join(root, name) + 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) + } + } + + out := captureMainOutput(func() { + if code := runAskSubcommand([]string{"UseTheme", "SaveTheme"}, root); code != 0 { + t.Fatalf("ask exit = %d", code) + } + }) + if !strings.Contains(out, "EXPERIMENTAL") || !strings.Contains(out, "MATCH") { + t.Fatalf("output =\n%s", out) + } + + out = captureMainOutput(func() { + if code := runAskSubcommand([]string{"quantum", "flux", "capacitor", "zucchini"}, root); code != 0 { + t.Fatalf("ask exit = %d", code) + } + }) + if !strings.Contains(out, "NO_MATCH") { + t.Fatalf("output =\n%s", out) + } +} + +func TestAskSubcommandRequiresQuery(t *testing.T) { + out := captureMainOutput(func() { + if code := runAskSubcommand(nil, t.TempDir()); code != 2 { + t.Fatalf("exit = %d, want 2", code) + } + }) + if !strings.Contains(out, "needs a question") { + t.Fatalf("output =\n%s", out) + } +} diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index 8bfc82e..cad35f9 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -10,6 +10,7 @@ codemap --importers f # who imports a file codemap blast-radius # review bundle: diff + deps + importers codemap collide # rank open PRs by shared-file merge-order hazard codemap find "" # where is X defined: rank by path, symbol names, then body text ("(body)" tag), with importer counts +codemap ask "" # EXPERIMENTAL: smallest-sufficient summary cards or NO_MATCH (bartender) codemap handoff . # save layered handoff for cross-agent continuation codemap context # machine-readable project context JSON codemap doctor # validate agent integrations @@ -144,12 +145,25 @@ codemap blast-radius --json --ref main . codemap blast-radius --text --ref main . ``` +### Ask (experimental) + +Bartender-inspired smallest-sufficient context. Opt-in; does not change other commands. + +```bash +codemap ask "where is theme persistence handled?" +codemap ask --json --budget 900 "hub config loading" +``` + +Returns compact deduplicated summary cards from codemap's map, or an explicit +`NO_MATCH`. Design map and credit: [BARTENDER-ASK.md](design/BARTENDER-ASK.md). + ### Skyline ```bash codemap --skyline --animate ``` + ![codemap skyline](../assets/skyline-animated.gif) ### Remote repos diff --git a/docs/MCP.md b/docs/MCP.md index 6cfd781..0778112 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -125,11 +125,11 @@ Both values may be repository roots or subdirectories. An explicit `--setup-root` preserves the existing shared policy-and-runtime-state behavior, and managed MCP definitions created while it is active retain it automatically. -## Available Tools (19) +## Available Tools (20) -`codemap mcp` serves 19 tools over stdio. When it is registered, hook nudges name the matching tool next to the CLI command, for example `codemap --importers X (MCP: get_importers)`. +`codemap mcp` serves 20 tools over stdio. When it is registered, hook nudges name the matching tool next to the CLI command, for example `codemap --importers X (MCP: get_importers)`. -`get_structure`, `get_diff`, `get_importers`, `get_dependencies`, and `get_handoff` declare an `OutputSchema` and return typed structured content alongside the text response, so callers get parseable results instead of prose. +`get_structure`, `get_diff`, `get_importers`, `get_dependencies`, `get_handoff`, and experimental `ask` declare an `OutputSchema` and return typed structured content alongside the text response, so callers get parseable results instead of prose. ### Project Analysis @@ -139,6 +139,7 @@ and managed MCP definitions created while it is active retain it automatically. | `get_dependencies` | Dependency flow with imports, functions, and hub files | | `get_diff` | Changed files with line counts and impact analysis | | `find` | Rank files by path and function/type names, then body text (`(body)` tag), with importer count and hub status per hit | +| `ask` | **[EXPERIMENTAL]** Smallest-sufficient summary cards from the map, or explicit `NO_MATCH` (bartender prototype; see [BARTENDER-ASK.md](design/BARTENDER-ASK.md)) | | `find_file` | Find files by name pattern | | `get_importers` | Find all files that import a specific file | | `get_hubs` | List all hub files (3+ importers) with dependent counts | @@ -187,6 +188,7 @@ Once configured, Claude can use these tools automatically. Try asking: - "What have I been editing this session?" - "What skills are available for refactoring?" - "Build a handoff summary I can continue in another agent" +- "Ask for the smallest sufficient context about theme persistence (experimental ask tool)" ## Handoff Tool Notes diff --git a/docs/design/BARTENDER-ASK.md b/docs/design/BARTENDER-ASK.md new file mode 100644 index 0000000..9bc9e64 --- /dev/null +++ b/docs/design/BARTENDER-ASK.md @@ -0,0 +1,57 @@ +# Bartender → codemap `ask` (experimental) + +Status: **working vertical slice**, opt-in only. Default CLI/MCP behavior is unchanged. + +Design credit: [bartender](https://github.com/everoo/bartender) by [everoo](https://github.com/everoo) (Jordan's collaborator). Bartender is design docs today; this prototype brings a first retrieval loop into codemap. + +## Goal + +Agents using codemap (CLI and MCP) can ask a question about a codebase and get the **smallest sufficient context** built from compact, **deduplicated summary cards** of codemap's existing map — or an explicit **`NO_MATCH`** when nothing is reliable enough — instead of large dumps. + +## Concept map + +| Bartender / Alexandria idea | Implemented in this slice | Left open | +| --- | --- | --- | +| Alexandria: deduplicated, versioned knowledge store | In-memory cards derived from one `ScanForDeps` + `FileGraph`; stable `id` (`file:` / `package:`) and `revision` (hash of capsule) | Persistent store, hot/warm/cold tiers, append-only provenance, contributor consent | +| Routing card: short label + ~50-token capsule | `Card.Label` (≤15 tokens) + `Card.Capsule` (≤55 tokens) from path, language, ←/→ counts, symbols, match hints | Multi-type graph entries (objective, solution, experience, test), typed edges beyond importer/import basenames | +| Adaptive Fuzzy Retrieval (AFR) | Lexical rank via existing `find.Rank`, adaptive shortlist (score floor + relative keep), byte-budget early stop | Embeddings, bandit answer/expand/clarify, multi-hop expansion, historical revision expand | +| Smallest sufficient answer | `MATCH` with 1–N cards that fit `--budget` / `budget` | LLM synthesis of a prose answer from cards; participant expand round-trip | +| Explicit `NO_MATCH` | Terminal status + message when empty query, no hits, weak scores, or nothing fits budget | Distinguishing "not in map" vs "map incomplete" beyond coverage footer | +| Participating-AI tool instruction | MCP `ask` description tells agents to prefer compact cards over dumps | A/B of tool-use / routing prompts; Governor experiments | +| Learning / outcome reports | Not implemented | Minimal success/failure reports, correction loop into Alexandria | + +## Surfaces (opt-in) + +```bash +codemap ask "where is theme persistence handled?" +codemap ask --json --budget 900 "hub config loading" +``` + +MCP tool: `ask` (description prefixed `[EXPERIMENTAL bartender prototype]`). + +Schema: `codemap.ask/v1-experimental`. + +## What it builds on + +- **Scan / graph:** `scanner.ScanForDeps`, `BuildFileGraphFromOutcome`, coverage contract +- **Retrieval vocabulary:** `find.Rank` (same identifier splitting / BM25 style as `codemap find`) +- **CLI / MCP conventions:** subcommand before flags (like `find`), structured MCP output + bounded text, experimental banner on stderr for CLI + +It does **not** invent a parallel indexer or replace `find`, `context`, or `get_structure`. + +## Open design questions for everoo + +1. Should Alexandria cards in codemap stay **derived ephemeral views** of the map, or become a **persisted** `.codemap/` store that survives sessions and accepts corrections? +2. Is lexical rank + adaptive cut enough for the first falsifiable experiment, or should the slice require an embedding / hybrid path before calling the experiment "AFR"? +3. For `NO_MATCH`, should agents be nudged to fall back to `find` / `get_file_context`, or is silence (solve normally) the intended bartender rule? +4. Do package-level cards (`package:…`) correctly express Go's import granularity, or should hubs always stay file-addressed with package only as a link? +5. What is the preferred expand protocol when a card is "close but incomplete" — deeper capsule, prior revision, or neighboring card IDs? +6. License / credit line: is linking bartender + everoo in README + this note the right attribution for landing in codemap? +7. Lexical reliability currently requires **two** shared identifier tokens for multi-word questions (to avoid lone verbs like `save` matching unrelated tests). That makes synonym-only seconds (`theme persistence`) an intentional `NO_MATCH` in this slice — should AFR soften that with stemming, embeddings, or an expand step? + +## Non-goals for this PR + +- Changing default hook / session-start payloads +- Training classifiers or calling external LLMs inside codemap +- Public commons contribution / consent flows +- Replacing handoff or context envelopes diff --git a/main.go b/main.go index be5dd46..15b5800 100644 --- a/main.go +++ b/main.go @@ -255,6 +255,15 @@ func main() { return } + // Handle "ask" subcommand before global flag parsing (EXPERIMENTAL bartender prototype). + if len(os.Args) >= 2 && os.Args[1] == "ask" { + root, _ := os.Getwd() + if code := runAskSubcommand(os.Args[2:], root); code != 0 { + os.Exit(code) + } + return + } + // Handle "collide" subcommand before global flag parsing if len(os.Args) >= 2 && os.Args[1] == "collide" { root, _ := os.Getwd() @@ -367,6 +376,7 @@ func main() { fmt.Println(" codemap blast-radius [path] # Compact bounded blast-radius bundle") fmt.Println(" codemap collide # Rank open PRs by shared-file merge-order hazard") fmt.Println(" codemap find # Where is X defined: rank by path, symbol names, then body text") + fmt.Println(" codemap ask # EXPERIMENTAL: smallest-sufficient cards or NO_MATCH (bartender)") fmt.Println() fmt.Println("Project config:") fmt.Println(" codemap config init # Create .codemap/config.json (auto-detects extensions)") diff --git a/mcp/ask_test.go b/mcp/ask_test.go new file mode 100644 index 0000000..4e1a8c0 --- /dev/null +++ b/mcp/ask_test.go @@ -0,0 +1,65 @@ +package codemapmcp + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "codemap/ask" +) + +func TestHandleAskMatchAndNoMatch(t *testing.T) { + root := t.TempDir() + files := map[string]string{ + "go.mod": "module fixture\n\ngo 1.24\n", + "theme/use_theme.go": "package theme\n\nfunc UseTheme() {}\nfunc SaveTheme() {}\n", + "storage/preferences.go": "package storage\n\nfunc LoadTheme() {}\n", + "net/client.go": "package net\n\nfunc FetchJSON() {}\n", + } + for name, body := range files { + path := filepath.Join(root, name) + 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) + } + } + + match, structured, err := handleAsk(context.Background(), nil, AskInput{Path: root, Query: "UseTheme SaveTheme", Budget: 900}) + if err != nil { + t.Fatal(err) + } + text := resultText(t, match) + if !strings.Contains(text, "EXPERIMENTAL") || !strings.Contains(text, ask.StatusMatch) { + t.Fatalf("match text =\n%s", text) + } + answer, ok := structured.(ask.Answer) + if !ok || answer.Status != ask.StatusMatch || len(answer.Cards) == 0 { + t.Fatalf("structured = %#v", structured) + } + + miss, structured, err := handleAsk(context.Background(), nil, AskInput{Path: root, Query: "quantum flux capacitor zucchini"}) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(resultText(t, miss), ask.StatusNoMatch) { + t.Fatalf("no-match text =\n%s", resultText(t, miss)) + } + missAnswer, ok := structured.(ask.Answer) + if !ok || missAnswer.Status != ask.StatusNoMatch || len(missAnswer.Cards) != 0 { + t.Fatalf("no-match structured = %#v", structured) + } +} + +func TestHandleAskRejectsEmptyQuery(t *testing.T) { + result, _, err := handleAsk(context.Background(), nil, AskInput{Path: t.TempDir(), Query: " "}) + if err != nil { + t.Fatal(err) + } + if !result.IsError || !strings.Contains(resultText(t, result), "needs a query") { + t.Fatalf("result = %#v", result) + } +} diff --git a/mcp/main.go b/mcp/main.go index 550fc59..084fef7 100644 --- a/mcp/main.go +++ b/mcp/main.go @@ -19,6 +19,7 @@ import ( "unicode/utf8" "codemap/analysis" + "codemap/ask" "codemap/config" "codemap/find" "codemap/handoff" @@ -79,6 +80,7 @@ var statusTools = []statusTool{ {"find_file", "Search by filename"}, {"get_importers", "Find what imports a file"}, {"find", "Rank files by path and symbol match"}, + {"ask", "[EXPERIMENTAL] Smallest-sufficient cards or NO_MATCH"}, {"status", "Verify MCP connection"}, {"start_watch", "Start watching a project"}, {"stop_watch", "Stop watching a project"}, @@ -192,6 +194,13 @@ type FindQueryInput struct { Limit int `json:"limit,omitempty" jsonschema:"Maximum hits to return (default 10)"` } +type AskInput struct { + Path string `json:"path" jsonschema:"Path to the project directory"` + Query string `json:"query" jsonschema:"Question about the codebase (goal + necessary constraints)"` + Limit int `json:"limit,omitempty" jsonschema:"Maximum candidate cards before adaptive cut (default 8)"` + Budget int `json:"budget,omitempty" jsonschema:"Byte budget for the compact answer (default 1200)"` +} + type ImportersInput struct { Path string `json:"path" jsonschema:"Path to the project directory"` File string `json:"file" jsonschema:"Relative path to the file to check (e.g. src/utils.ts)"` @@ -277,6 +286,13 @@ func NewServer(options RuntimeOptions) *mcp.Server { Description: "Rank project files by how well their path and function/type names match a query (lexical BM25 over split identifiers). Good for \"where is X defined\" when the query uses words from the code's names. Each hit reports importer count and hub status, so it also says how risky the file is to edit. Also scores file contents; hits that matched only in a body are tagged \"(body)\". For a free-text symptom, grep the body text too.", }, handleFind) + // Tool: ask - EXPERIMENTAL bartender-inspired smallest-sufficient retrieval + mcp.AddTool(server, &mcp.Tool{ + Name: "ask", + Description: "[EXPERIMENTAL bartender prototype] Ask a question about the codebase and receive the smallest sufficient context built from compact deduplicated summary cards of codemap's map, or an explicit NO_MATCH when nothing is reliable enough. Prefer this over dumping get_structure/get_dependencies when you only need a short answer. Does not change other tools. Design credit: https://github.com/everoo/bartender", + OutputSchema: mustSchemaFor[ask.Answer](), + }, handleAsk) + // Tool: status - Verify MCP connection mcp.AddTool(server, &mcp.Tool{ Name: "status", @@ -1007,6 +1023,30 @@ func handleFind(ctx context.Context, req *mcp.CallToolRequest, input FindQueryIn return textResult(buf.String()), nil, nil } +func handleAsk(ctx context.Context, req *mcp.CallToolRequest, input AskInput) (*mcp.CallToolResult, any, error) { + if cancelled := cancellationResult(ctx, "Ask"); cancelled != nil { + return cancelled, nil, nil + } + absRoot, invalid := validateProjectPath(input.Path) + if invalid != nil { + return invalid, nil, nil + } + if strings.TrimSpace(input.Query) == "" { + return errorResult("ask needs a query"), nil, nil + } + answer, err := ask.Run(ctx, absRoot, scanner.ConfiguredFilters(absRoot), input.Query, ask.Options{ + Limit: input.Limit, + BudgetBytes: input.Budget, + }) + if err != nil { + if cancelled := cancellationResult(ctx, "Ask"); cancelled != nil { + return cancelled, nil, nil + } + return errorResult("Failed to answer question: " + err.Error()), nil, nil + } + return textResult(ask.RenderText(answer)), answer, nil +} + func normalizeImporterFile(root, file string) string { file = filepath.FromSlash(file) if filepath.IsAbs(file) { diff --git a/mcp/surface_hygiene_test.go b/mcp/surface_hygiene_test.go index 67eef08..18018ca 100644 --- a/mcp/surface_hygiene_test.go +++ b/mcp/surface_hygiene_test.go @@ -68,6 +68,7 @@ func TestTextResultCallerClassification(t *testing.T) { "handleGetDependencies": {1, 0}, "handleGetDiff": {2, 0}, "handleFind": {1, 0}, + "handleAsk": {1, 0}, "handleFindFile": {3, 0}, "handleStatus": {1, 0}, "handleListProjects": {4, 0}, @@ -191,6 +192,7 @@ func TestStatusInventoryExactlyMatchesRegisteredTools(t *testing.T) { sort.Strings(registered) expected := []string{ + "ask", "find", "find_file", "get_activity", From 32d7c5f762078fbe6290d3d5ca6dfeb5550d566d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 21 Nov 2026 15:11:46 +0000 Subject: [PATCH 2/2] fix(ask): gofmt and broaden experimental ask tests Satisfy CI formatting check and cover JSON/validation CLI paths plus graph-backed card rendering helpers. Co-authored-by: Jordan Coin Jackson --- ask/ask.go | 4 ++-- ask/ask_test.go | 41 +++++++++++++++++++++++++++++++--------- ask_cmd_test.go | 50 +++++++++++++++++++++++++++++++++++++++++++++++++ mcp/ask_test.go | 12 ++++++++++++ 4 files changed, 96 insertions(+), 11 deletions(-) diff --git a/ask/ask.go b/ask/ask.go index 28a97cb..301f67d 100644 --- a/ask/ask.go +++ b/ask/ask.go @@ -26,8 +26,8 @@ import ( ) const ( - Schema = "codemap.ask/v1-experimental" - StatusMatch = "MATCH" + Schema = "codemap.ask/v1-experimental" + StatusMatch = "MATCH" StatusNoMatch = "NO_MATCH" // DefaultLimit is how many find hits to consider before adaptive cut. diff --git a/ask/ask_test.go b/ask/ask_test.go index 6da1e29..a454e8e 100644 --- a/ask/ask_test.go +++ b/ask/ask_test.go @@ -120,27 +120,50 @@ func TestSelectWithinBudgetKeepsSmallestPrefix(t *testing.T) { } func TestDedupPackageCardsShareLogicalID(t *testing.T) { - hit := find.Hit{Path: "pkg/a.go", Package: "example.com/pkg", Score: 1.2, Importers: 3} - analysis := scanner.FileAnalysis{Path: "pkg/a.go", Language: "go", Functions: []string{"Load"}} - first := buildCard(hit, analysis, nil) - second := buildCard(hit, analysis, nil) + hit := find.Hit{Path: "pkg/a.go", Package: "example.com/pkg", Score: 1.2, Importers: 3, Hub: true, Matched: []string{"Load"}} + analysis := scanner.FileAnalysis{ + Path: "pkg/a.go", + Functions: []string{"Load", "Save", "Parse", "Validate", "Reset", "Extra"}, + Types: []string{"Config"}, + Imports: []string{"os"}, + } + graph := &scanner.FileGraph{ + Importers: map[string][]string{"pkg/a.go": {"b/one.go", "b/two.go", "b/three.go", "b/four.go"}}, + Imports: map[string][]string{"pkg/a.go": {"c/dep.go", "c/other.go"}}, + } + first := buildCard(hit, analysis, graph) + second := buildCard(hit, analysis, graph) if first.ID != second.ID || first.ID != "package:example.com/pkg" { t.Fatalf("ids = %q %q", first.ID, second.ID) } if first.Revision != second.Revision { t.Fatal("identical capsules should share revision") } + if len(first.Links) == 0 || !strings.Contains(first.Capsule, "symbols:") { + t.Fatalf("card should include graph links and symbols: %+v", first) + } + if got := trimTokens(strings.Repeat("word ", 20), 5); len(strings.Fields(got)) != 5 { + t.Fatalf("trimTokens = %q", got) + } + if got := uniqueStable([]string{"", "b", "a", "b"}); strings.Join(got, ",") != "a,b" { + t.Fatalf("uniqueStable = %v", got) + } + var buf strings.Builder + Render(&buf, Answer{Schema: Schema, Status: StatusMatch, Message: matchMessage(nil), Cards: []Card{first}, BudgetBytes: 900}) + if !strings.Contains(buf.String(), first.Paths[0]) { + t.Fatalf("Render missing path:\n%s", buf.String()) + } } func writeAskFixture(t *testing.T) string { t.Helper() root := t.TempDir() files := map[string]string{ - "go.mod": "module fixture\n\ngo 1.24\n", - "theme/use_theme.go": "package theme\n\nfunc UseTheme() {}\nfunc SaveTheme() {}\n", - "storage/preferences.go": "package storage\n\nfunc LoadTheme() {}\nfunc PersistPreference() {}\n", - "net/client.go": "package net\n\nfunc FetchJSON() {}\nfunc Retry() {}\n", - "unrelated/math.go": "package unrelated\n\nfunc Add(a, b int) int { return a + b }\n", + "go.mod": "module fixture\n\ngo 1.24\n", + "theme/use_theme.go": "package theme\n\nfunc UseTheme() {}\nfunc SaveTheme() {}\n", + "storage/preferences.go": "package storage\n\nfunc LoadTheme() {}\nfunc PersistPreference() {}\n", + "net/client.go": "package net\n\nfunc FetchJSON() {}\nfunc Retry() {}\n", + "unrelated/math.go": "package unrelated\n\nfunc Add(a, b int) int { return a + b }\n", } for name, body := range files { path := filepath.Join(root, name) diff --git a/ask_cmd_test.go b/ask_cmd_test.go index fc79007..ca83290 100644 --- a/ask_cmd_test.go +++ b/ask_cmd_test.go @@ -53,3 +53,53 @@ func TestAskSubcommandRequiresQuery(t *testing.T) { t.Fatalf("output =\n%s", out) } } + +func TestAskSubcommandJSONAndValidation(t *testing.T) { + root := t.TempDir() + files := map[string]string{ + "go.mod": "module fixture\n\ngo 1.24\n", + "theme/use_theme.go": "package theme\n\nfunc UseTheme() {}\nfunc SaveTheme() {}\n", + } + for name, body := range files { + path := filepath.Join(root, name) + 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) + } + } + + out := captureMainOutput(func() { + if code := runAskSubcommand([]string{"--json", "--budget", "800", "UseTheme", "SaveTheme"}, root); code != 0 { + t.Fatalf("ask exit = %d", code) + } + }) + if !strings.Contains(out, `"status"`) || !strings.Contains(out, "MATCH") { + t.Fatalf("json output =\n%s", out) + } + out = captureMainOutput(func() { + if code := runAskSubcommand([]string{"--limit", "0", "UseTheme"}, root); code != 2 { + t.Fatalf("limit exit = %d", code) + } + }) + if !strings.Contains(out, "--limit") { + t.Fatalf("limit error =\n%s", out) + } + out = captureMainOutput(func() { + if code := runAskSubcommand([]string{"--budget", "0", "UseTheme"}, root); code != 2 { + t.Fatalf("budget exit = %d", code) + } + }) + if !strings.Contains(out, "--budget") { + t.Fatalf("budget error =\n%s", out) + } + out = captureMainOutput(func() { + if code := runAskSubcommand([]string{"--help"}, root); code != 0 { + t.Fatalf("help exit = %d", code) + } + }) + if !strings.Contains(out, "EXPERIMENTAL") { + t.Fatalf("help =\n%s", out) + } +} diff --git a/mcp/ask_test.go b/mcp/ask_test.go index 4e1a8c0..f28e5ae 100644 --- a/mcp/ask_test.go +++ b/mcp/ask_test.go @@ -63,3 +63,15 @@ func TestHandleAskRejectsEmptyQuery(t *testing.T) { t.Fatalf("result = %#v", result) } } + +func TestHandleAskCancelled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + result, _, err := handleAsk(ctx, nil, AskInput{Path: t.TempDir(), Query: "UseTheme SaveTheme"}) + if err != nil { + t.Fatal(err) + } + if !result.IsError || !strings.Contains(strings.ToLower(resultText(t, result)), "cancel") { + t.Fatalf("result = %#v", result) + } +}