Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
Store repo-relative paths as posix, and unify --in on path prefixes
anirudhkumar-nanonets4cfd6e8cdf1f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 3369600e..93ad3791 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -11,7 +11,17 @@ permissions:jobs:test:- runs-on: ubuntu-latest+ name: test (${{ matrix.os }})+ # Windows is not redundant coverage here: graft stores repo-relative paths and+ # parses them with `/` by hand, so a platform-separator leak matches nothing+ # rather than erroring. That class of bug is invisible to a posix-only matrix+ # (it shipped in 0.8.2 and took three user reports to find). `fail-fast: false`+ # so a Windows-only failure still reports the Linux result.+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, windows-latest]+ runs-on: ${{ matrix.os }}steps:- name: Checkout codeuses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4@@ -28,4 +38,10 @@ jobs:run: npm ci- name: Test+ # `npm test` is `node --test test/*.test.ts` — that glob is expanded by the+ # shell, and PowerShell (the Windows runner default) passes it through+ # literally while Node 20's `--test` does not glob. Pinning bash, which the+ # Windows runners ship via Git for Windows, makes both legs run the same+ # file set instead of the Windows one silently testing nothing.+ shell: bashrun: npm testdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 46527251..f9a5b0b2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,48 @@# Changelog+## Unreleased++### Fixed++- **Windows: path scoping and `map` work again.** graft stores a repo-relative path+ for every indexed file — in node ids, `node.path`, the extract cache, the freshness+ fingerprint — and it was produced with `relative()`, which returns the *platform*+ separator. So on Windows every stored path was `src\gate.ts`, while the query layer+ parses those strings with `/` by hand. Nothing errored; it just matched nothing:++ - `ask --in <path>` reported `nothing indexed under "…"` for **every** prefix,+ making path scoping unusable on the platform ([#33]).+ - `map` saw one path segment instead of several, so it emitted one single-file+ "directory" per file — on a large repo spending its whole token budget describing+ ~16 arbitrary files instead of the repo's shape ([#35]).+ - `callers <file.ts>`-style filename lookups missed.++ Repo-relative paths are now normalized to posix once, where they are created+ (`src/util/paths.ts`), instead of defensively at each consumer. Mac and Linux are+ unaffected — the conversion is the identity there, and existing graphs are+ byte-identical. **On Windows every cache key changes**, so the first `graft build`+ after upgrading re-parses the repo once and `graft check` may report drift until it+ runs. One-time, and `graft/` is a local gitignored cache — nothing to migrate.++ CI now runs a `windows-latest` leg, because this whole class of bug is invisible to+ a posix-only matrix.++### Changed++- **`--in` means the same thing on every command.** `ask --in` matched a segment-aware+ path prefix while `grep --in` and `callers --in` matched a bare substring, so+ `grep --in src` also swept up `lib/mysrc/`. All three now use the prefix rule, and+ all three accept either separator (`--in server\src\gpu` works on Windows). A prefix+ matching nothing indexed is now a loud error on all three rather than — for `grep`+ and `callers` — empty output the caller had to interpret.++ This is stricter: a mid-path fragment like `--in gpu` for `server/src/gpu` no longer+ matches. Pass a real prefix (`--in server/src/gpu`), a full file path+ (`--in src/a.ts`), or use `grep`'s pattern to match on content.++[#33]: https://github.com/NanoNets/Graft/issues/33+[#35]: https://github.com/NanoNets/Graft/issues/35+## 0.8.2### Fixeddiff --git a/README.md b/README.mdindex 9a4fbca6..54b6d40d 100644--- a/README.md+++ b/README.md@@ -254,7 +254,7 @@ graft callers <symbol> --direction out # the reverse: what the symbol itself cagraft callers <symbol> -d N # walk transitively out to depth N — full blast radius (was `graft impact`)graft grep "<regex>" [dir] # exhaustive regex search over indexed files, grouped by enclosing symbol (no LLM, no key)-graft grep "<regex>" --in <path> # narrow to files whose path contains this substring+graft grep "<regex>" --in <path> # narrow to files at or under this path prefixgraft grep "<regex>" -i --fixed # case-insensitive; treat the pattern as a literal string, not a regexgraft map [dir] # token-budgeted repo orientation — dir clusters, hubs, hotspots (no LLM, no key)diff --git a/src/ask/ask.ts b/src/ask/ask.tsindex 17e1c650..df8d5b06 100644--- a/src/ask/ask.ts+++ b/src/ask/ask.ts@@ -19,7 +19,15 @@ import matter from "gray-matter";import { contextDirFor } from "../context/node-file.js";import { savingsFooter, savingsFor, SAVINGS_TURN_NUDGE, type Savings } from "../context/savings.js";import { loadGraphCached, loadAskIndexCached } from "../graph/load.js";-import { pathUnderPrefix, scopeLabel, scopeOf, scopesHereClause, scopesOfGraph } from "../graph/scopes.js";+import {+ assertPrefixIndexed,+ pathUnderPrefix,+ scopeLabel,+ scopeOf,+ scopesHereClause,+ scopesOfGraph,+} from "../graph/scopes.js";+import { normalizePathPrefix } from "../util/paths.js";import { resolveSymbol } from "../graph/traverse.js";import type { EdgeV1, GraphV1, NodeV1, Relation } from "../graph/types.js";import { rankScopesAndFuse } from "./fuse.js";@@ -799,21 +807,16 @@ export function ask(dir: string, query: string, opts: AskOptions = {}): AskResulconst limit = opts.limit ?? 8;const corpus = loadCorpus(outDir);const graphRank = opts.graphRank ?? true;- // Trailing slash(es) stripped ONCE, up front, and this normalized value used- // everywhere below (validation, filtering, structural). `ask --in frontend/`- // must work exactly like `--in frontend` — `scopeLabel`/the footer's own- // `--in <scope>/` suggestion always includes the slash, so rejecting it- // would make the tool's own suggested next command fail.- const inPrefix = opts.in ? opts.in.replace(/\/+$/, "") : undefined;-- // `--in` validated up front, before any mode runs: a prefix matching no- // indexed node is a caller mistake (typo, wrong sub-project), not a- // legitimate zero-hit query, so it's a loud error rather than an empty pack.- if (inPrefix && corpus.graph && !corpus.graph.nodes.some((n) => pathUnderPrefix(n.path, inPrefix))) {- throw new Error(- `nothing indexed under "${inPrefix}/"${scopesHereClause(scopesOfGraph(corpus.graph))} (or any path prefix)`,- );- }+ // Normalized ONCE, up front, and this value used everywhere below+ // (validation, filtering, structural). `ask --in frontend/` must work exactly+ // like `--in frontend` — `scopeLabel`/the footer's own `--in <scope>/`+ // suggestion always includes the slash, so rejecting it would make the tool's+ // own suggested next command fail — and `--in frontend\sub` must work too,+ // because that is what a Windows shell's tab-completion produces.+ const inPrefix = opts.in ? normalizePathPrefix(opts.in) : undefined;++ // `--in` validated up front, before any mode runs.+ if (inPrefix && corpus.graph) assertPrefixIndexed(corpus.graph, inPrefix);let result: AskResult;if (corpus.graph) {diff --git a/src/cli.ts b/src/cli.tsindex 573ce5cb..3b6777ec 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -353,7 +353,7 @@ program.argument("[dir]", "repository root", ".").option("--direction <in|out>", 'edge direction: "in" = callers (default), "out" = callees').option("-d, --depth <n>", 'walk transitively up to N hops for blast radius, or "all" for the full connected closure (default 1)')- .option("--in <path>", "narrow matches to nodes whose path contains this substring")+ .option("--in <path>", "narrow matches to nodes at or under this path prefix").option("--json", "output as JSON").option(...NO_REFRESH_FLAG).action(@@ -392,7 +392,7 @@ program.argument("[dir]", "repository root", ".").option("-i, --ignore-case", "case-insensitive match").option("--fixed", "treat pattern as a literal string, not a regex")- .option("--in <path>", "narrow to files whose path contains this substring")+ .option("--in <path>", "narrow to files at or under this path prefix").option("--json", "output as JSON").option(...NO_REFRESH_FLAG).action(diff --git a/src/context/build.ts b/src/context/build.tsindex 840e344f..f23d04ae 100644--- a/src/context/build.ts+++ b/src/context/build.ts@@ -12,9 +12,10 @@* 5. Write one markdown file per node (preserving human notes) + a manifest.*/import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";-import { join, relative, resolve } from "node:path";+import { join, resolve } from "node:path";import { walkDir } from "../ingest/fs.js";import { contentHash } from "../util/id.js";+import { relPosix } from "../util/paths.js";import type { Summarizer } from "../ai/summarize.js";import type { FileSummary, SynthNode, Synthesizer } from "../ai/synthesize.js";import {@@ -118,7 +119,7 @@ export async function buildContext(dir: string, opts: BuildOptions): Promise<Bui// Phase 1: summarize each file, concurrent, content-hash cached.const work = await mapWithConcurrency(files, 8, async (file, i): Promise<FileWork | undefined> => {- const rel = relative(root, file);+ const rel = relPosix(root, file);opts.onProgress?.({ phase: "summarize", index: i, total: files.length, file: rel });let code: string;try {diff --git a/src/context/check.ts b/src/context/check.tsindex 237d46aa..a80f7ffa 100644--- a/src/context/check.ts+++ b/src/context/check.ts@@ -13,9 +13,10 @@* index a node's frontmatter disagrees with the manifest (hand-edited)*/import { existsSync, readFileSync } from "node:fs";-import { relative, resolve } from "node:path";+import { resolve } from "node:path";import { walkDir } from "../ingest/fs.js";import { contentHash } from "../util/id.js";+import { relPosix } from "../util/paths.js";import { CODE_EXTENSIONS } from "./build.js";import { contextDirFor, readManifest, readNodes } from "./node-file.js";@@ -60,7 +61,7 @@ export function checkContext(dir: string, opts: CheckOptions = {}): CheckResultif (file.startsWith(outDir)) continue;if (!exts.some((e) => file.toLowerCase().endsWith(e))) continue;try {- current.set(relative(root, file), contentHash(readFileSync(file, "utf8")));+ current.set(relPosix(root, file), contentHash(readFileSync(file, "utf8")));} catch {// Unreadable now → treat as removed below (it won't be in `current`).}diff --git a/src/context/node-file.ts b/src/context/node-file.tsindex 57382641..bad2aee9 100644--- a/src/context/node-file.ts+++ b/src/context/node-file.ts@@ -22,9 +22,10 @@* LLM and without re-reading every node body.*/import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, rmSync } from "node:fs";-import { join, relative, sep } from "node:path";+import { join } from "node:path";import matter from "gray-matter";import { contentHash, normalizeName } from "../util/id.js";+import { relPosix } from "../util/paths.js";// Value-only import of a constant; `write.ts` pulls in nothing from here, so no cycle.import { GRAPH_DIR } from "../graph/write.js";@@ -129,7 +130,7 @@ function stripTrailingSlashes(path: string): string {* must never abort a build, so write failures are swallowed.*/export function ensureGitignored(root: string, contextDir: string): void {- const rel = relative(root, contextDir).split(sep).join("/");+ const rel = relPosix(root, contextDir);if (rel === "" || rel.startsWith("..")) return; // dir is at/above the repo root — nothing sane to ignoreconst entry = `${stripTrailingSlashes(rel)}/`;const path = join(root, ".gitignore");@@ -166,7 +167,7 @@ export function ensureGitignored(root: string, contextDir: string): void {* must not fail over a convenience file.*/export function ensureSearchable(root: string, contextDir: string): void {- const rel = relative(root, contextDir).split(sep).join("/");+ const rel = relPosix(root, contextDir);if (rel === "" || rel.startsWith("..")) return; // outside the repo — nothing to re-admitconst dir = stripTrailingSlashes(rel);const entry = `!${dir}/`;diff --git a/src/graph/build.ts b/src/graph/build.tsindex 49a9cd15..1f917e7a 100644--- a/src/graph/build.ts+++ b/src/graph/build.ts@@ -14,11 +14,12 @@* one — the invariant `test/graph-incremental.test.ts` pins down.*/import { readFileSync } from "node:fs";-import { basename, dirname, relative, resolve, sep } from "node:path";+import { basename, dirname, resolve } from "node:path";import { walkDir } from "../ingest/fs.js";import { contextDirFor, ensureGitignored, ensureSearchable } from "../context/node-file.js";import { extractFile, languageOf, type Language, type RawEdge } from "./extract.js";import { contentHash } from "../util/id.js";+import { relPosix } from "../util/paths.js";import {emptyExtractCache,readExtractCache,@@ -120,7 +121,7 @@ function readGoModules(root: string): GoModule[] {try {const m = readFileSync(f, "utf8").match(/^\s*module\s+(\S+)/m);if (!m) continue;- const rel = relative(root, dirname(f)).split(sep).join("/");+ const rel = relPosix(root, dirname(f));mods.push({ module: m[1], dir: rel === "" ? "." : rel });} catch {/* unreadable go.mod — skip this module */diff --git a/src/graph/cards.ts b/src/graph/cards.tsindex c8efefda..ccface79 100644--- a/src/graph/cards.ts+++ b/src/graph/cards.ts@@ -15,7 +15,8 @@* `signature`, so cards are useful even in a $0 structure-only build.*/import { mkdirSync, writeFileSync, readFileSync, existsSync, readdirSync, rmSync } from "node:fs";-import { dirname, join, relative } from "node:path";+import { dirname, join } from "node:path";+import { relPosix } from "../util/paths.js";import matter from "gray-matter";import type { GraphV1, NodeV1 } from "./types.js";import { CACHE_DIR, readNodes } from "../context/node-file.js";@@ -166,7 +167,7 @@ export function writeCards(graph: GraphV1, outDir: string): CardStats {mkdirSync(dirname(cardPath), { recursive: true });writeFileSync(cardPath, renderCard(sourcePath, fileNode, symbols, concepts.get(sourcePath) ?? []));written.add(cardPath);- files.push({ card: relative(outDir, cardPath), path: sourcePath, symbols: symbols.length });+ files.push({ card: relPosix(outDir, cardPath), path: sourcePath, symbols: symbols.length });}let pruned = 0;diff --git a/src/graph/check.ts b/src/graph/check.tsindex 8c55058d..a0bd6d6e 100644--- a/src/graph/check.ts+++ b/src/graph/check.ts@@ -18,7 +18,8 @@* `pending` (never summarized) is not drift — it's a deliberate Tier-1-only build.*/import { readFileSync } from "node:fs";-import { relative, resolve } from "node:path";+import { resolve } from "node:path";+import { relPosix } from "../util/paths.js";import { contextDirFor } from "../context/node-file.js";import { extractFile, languageOf } from "./extract.js";import { listSourceFiles } from "./build.js";@@ -71,7 +72,7 @@ export function checkGraph(dir: string, opts: GraphCheckOptions = {}): GraphCheccontinue; // unreadable now → its nodes show up as `removed` below}try {- const { nodes } = extractFile(relative(root, file), source, lang);+ const { nodes } = extractFile(relPosix(root, file), source, lang);for (const n of nodes) current.set(n.id, n.body_hash);} catch {// parse failure → skip; the committed nodes for this file become `removed`.diff --git a/src/graph/resolve.ts b/src/graph/resolve.tsindex db0c1f72..8d50193f 100644--- a/src/graph/resolve.ts+++ b/src/graph/resolve.ts@@ -11,7 +11,7 @@* rather than guessed, so we never wire an edge to the wrong symbol.*/import { posix } from "node:path";-import { sep } from "node:path";+import { toPosixPath } from "../util/paths.js";import type { EdgeV1, Kind, NodeV1, Relation } from "./types.js";import type { RawEdge } from "./extract.js";@@ -65,7 +65,7 @@ export function resolveEdges(for (const n of nodes) {if (n.kind === "file") {if (hasGoModules && n.path.endsWith(".go")) {- const dir = posix.dirname(n.path.split(sep).join("/"));+ const dir = posix.dirname(toPosixPath(n.path));push(goFilesByDir, dir, n.id);}continue;@@ -218,7 +218,9 @@ function resolveTypedMember(*/function resolveImport(spec: string, file: string, byId: Map<string, NodeV1>): string {if (!spec.startsWith(".")) return spec;- const dir = posix.dirname(file.split(sep).join("/"));+ // Belt-and-braces: `node.path` is posix by construction (`../util/paths.ts`),+ // but this also accepts a hand-written or hand-edited graph.+ const dir = posix.dirname(toPosixPath(file));const base = posix.normalize(posix.join(dir, spec));const noExt = base.replace(/\.(js|jsx|mjs|cjs|ts|tsx|py)$/, "");const candidates = [diff --git a/src/graph/scopes.ts b/src/graph/scopes.tsindex bff80046..becc8432 100644--- a/src/graph/scopes.ts+++ b/src/graph/scopes.ts@@ -342,6 +342,23 @@ export function pathUnderPrefix(path: string, prefix: string): boolean {return prefix === "" || path === prefix || path.startsWith(`${prefix}/`);}+/**+ * Validate a normalized `--in` prefix against the graph before a query runs. A+ * prefix matching no indexed node is a caller mistake (typo, wrong sub-project,+ * or a mid-path fragment where a prefix is required) rather than a legitimate+ * zero-hit query, so every `--in`-taking command fails loudly and identically+ * instead of printing empty output the caller has to interpret.+ *+ * Pass the prefix through `normalizePathPrefix` first — an un-normalized+ * `src\gpu` or `src/` will not match anything here.+ */+export function assertPrefixIndexed(graph: GraphV1, prefix: string): void {+ if (!prefix || graph.nodes.some((n) => pathUnderPrefix(n.path, prefix))) return;+ throw new Error(+ `nothing indexed under "${prefix}/"${scopesHereClause(scopesOfGraph(graph))} (or any path prefix)`,+ );+}+/** Immediate subdirs of `root` that are themselves git repos (have `.git`).* Used by workspace federation (Task 5). */export function discoverWorkspaceChildren(root: string): string[] {diff --git a/src/graph/seed.ts b/src/graph/seed.tsindex d5ddd12a..1a7d7643 100644--- a/src/graph/seed.ts+++ b/src/graph/seed.ts@@ -44,7 +44,8 @@ import {rmSync,statSync,} from "node:fs";-import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";+import { basename, dirname, isAbsolute, join, resolve } from "node:path";+import { relPosix } from "../util/paths.js";import { ASK_INDEX_FILE } from "../ask/index-file.js";import { CACHE_DIR, contextDirFor } from "../context/node-file.js";import { EXTRACT_CACHE_PREFIX } from "./extract-cache.js";@@ -151,7 +152,7 @@ function seedable(rel: string): boolean {function copyTree(srcDir: string, outDir: string): void {cpSync(srcDir, outDir, {recursive: true,- filter: (src) => seedable(relative(srcDir, src).split(sep).join("/")),+ filter: (src) => seedable(relPosix(srcDir, src)),});}diff --git a/src/graph/source-files.ts b/src/graph/source-files.tsindex 474e7219..93847e1f 100644--- a/src/graph/source-files.ts+++ b/src/graph/source-files.ts@@ -7,8 +7,8 @@* {@link listSourceFiles} so its existing importers are unaffected.*/import { statSync } from "node:fs";-import { relative } from "node:path";import { walkDir } from "../ingest/fs.js";+import { relPosix } from "../util/paths.js";import { languageOf } from "./extract.js";/** The source files a graph build parses: supported languages, minus the output dir. */@@ -19,8 +19,9 @@ export function listSourceFiles(root: string, outDir: string): string[] {export interface SourceStat {/** Absolute path. */abs: string;- /** `relative(root, abs)` — exactly the form `buildGraph` uses for node ids and- * `checkGraph` diffs against, so cache keys and ids can never disagree. */+ /** Repo-relative, posix (`relPosix`) — exactly the form `buildGraph` uses for+ * node ids and `checkGraph` diffs against, so cache keys and ids can never+ * disagree. Posix on every platform: see `../util/paths.ts`. */rel: string;size: number;mtimeMs: number;@@ -40,7 +41,7 @@ export function listSourceStats(root: string, outDir: string): SourceStat[] {} catch {continue;}- out.push({ abs, rel: relative(root, abs), size: s.size, mtimeMs: s.mtimeMs });+ out.push({ abs, rel: relPosix(root, abs), size: s.size, mtimeMs: s.mtimeMs });}return out;}diff --git a/src/graph/traverse-cli.ts b/src/graph/traverse-cli.tsindex e1e425fd..30334663 100644--- a/src/graph/traverse-cli.ts+++ b/src/graph/traverse-cli.ts@@ -133,7 +133,17 @@ export function runCallersCommand(query: string, dir: string, opts: CallersCliOpprocess.exit(1);}- const matches = resolveSymbol(graph, query, opts.in ? { in: opts.in } : {});+ // `resolveSymbol` throws on an `--in` prefix that matches nothing indexed —+ // a caller mistake, reported in the same shape as the ones around it rather+ // than as a bare stack-trace message from the top-level handler.+ let matches: NodeV1[];+ try {+ matches = resolveSymbol(graph, query, opts.in ? { in: opts.in } : {});+ } catch (err) {+ console.error(`✗ ${err instanceof Error ? err.message : String(err)}`);+ process.exit(1);+ return;+ }if (matches.length === 0) {console.error(`✗ no symbol "${query}" in the graph — check spelling or run graft build`);process.exit(1);diff --git a/src/graph/traverse.ts b/src/graph/traverse.tsindex 7776065c..cfa339ab 100644--- a/src/graph/traverse.ts+++ b/src/graph/traverse.ts@@ -14,6 +14,8 @@*/import type { EdgeV1, GraphV1, NodeV1, Relation } from "./types.js";import { WALK_RELATIONS } from "./relations.js";+import { assertPrefixIndexed, pathUnderPrefix } from "./scopes.js";+import { normalizePathPrefix } from "../util/paths.js";/** Which way to walk the wiring graph: `in` = incoming edges (who points at* the symbol — callers / blast radius), `out` = outgoing edges (what the symbol@@ -27,7 +29,9 @@ export interface SymbolMatch {}export interface ResolveSymbolOptions {- /** Narrow candidates to nodes whose `path` contains this substring. */+ /** Narrow candidates to nodes at or under this repo-relative path prefix —+ * the same segment-aware rule `ask --in` and `grep --in` use, so `--in` means+ * one thing across every command. Normalized here, so either separator works. */in?: string;}@@ -73,7 +77,11 @@ export function resolveSymbol(graph: GraphV1, query: string, opts: ResolveSymbol);}- if (opts.in) matches = matches.filter((n) => n.path.includes(opts.in!));+ if (opts.in) {+ const prefix = normalizePathPrefix(opts.in);+ assertPrefixIndexed(graph, prefix);+ matches = matches.filter((n) => pathUnderPrefix(n.path, prefix));+ }return matches;}diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex 8133871f..ed08e12e 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -90,7 +90,7 @@ export const TOOLS: ToolDef[] = [description: '"in" (default) = callers/dependents; "out" = callees/dependencies',},depth: { description: 'transitive walk depth for blast radius (default 1 = direct edges only); pass "all" for the full connected closure — every source that would be affected' },- in: { type: 'string', description: 'narrow matches to nodes whose path contains this substring' },+ in: { type: 'string', description: 'narrow matches to nodes at or under this repo-relative path prefix, e.g. server/src' },},required: ['symbol'],},@@ -103,7 +103,7 @@ export const TOOLS: ToolDef[] = [type: 'object',properties: {pattern: { type: 'string', description: 'regex pattern (or literal string with fixed: true)' },- in: { type: 'string', description: 'narrow to files whose path contains this substring' },+ in: { type: 'string', description: 'narrow to files at or under this repo-relative path prefix, e.g. server/src' },ignore_case: { type: 'boolean', description: 'case-insensitive match' },fixed: { type: 'boolean', description: 'treat pattern as a literal string, not a regex' },},diff --git a/src/search/grep-cli.ts b/src/search/grep-cli.tsindex 0b25aaad..952ab62c 100644--- a/src/search/grep-cli.ts+++ b/src/search/grep-cli.ts@@ -96,7 +96,10 @@ export function runGrepCommand(pattern: string, dir: string, opts: GrepCliOptiontry {result = grepGraph(graph, root, pattern, { ignoreCase: opts.ignoreCase, fixed: opts.fixed, in: opts.in });} catch (err) {- console.error(`✗ invalid pattern "${pattern}": ${err instanceof Error ? err.message : String(err)}`);+ // `new RegExp` throws SyntaxError; anything else (an unindexed `--in` prefix)+ // is a different mistake and must not be reported as a bad pattern.+ const message = err instanceof Error ? err.message : String(err);+ console.error(err instanceof SyntaxError ? `✗ invalid pattern "${pattern}": ${message}` : `✗ ${message}`);process.exit(1);return;}diff --git a/src/search/grep.ts b/src/search/grep.tsindex 6e2d8dec..6057b272 100644--- a/src/search/grep.ts+++ b/src/search/grep.ts@@ -13,6 +13,8 @@ import { readFileSync } from "node:fs";import { join } from "node:path";import type { GraphV1, NodeV1 } from "../graph/types.js";import { WALK_RELATIONS } from "../graph/relations.js";+import { assertPrefixIndexed, pathUnderPrefix } from "../graph/scopes.js";+import { normalizePathPrefix } from "../util/paths.js";import { savingsFor, type Savings } from "../context/savings.js";export interface GrepHit {@@ -65,7 +67,8 @@ export interface GrepOptions {ignoreCase?: boolean;/** Treat `pattern` as a literal string (regex-escaped), not a regex. */fixed?: boolean;- /** Narrow to file nodes whose path contains this substring. */+ /** Narrow to file nodes at or under this repo-relative path prefix — the same+ * segment-aware rule `ask --in` and `callers --in` use. Either separator. */in?: string;/** Stop collecting hits after this many; the rest are tallied into* `truncated.hits`. Default 300. */@@ -140,7 +143,14 @@ export function grepGraph(graph: GraphV1, repoRoot: string, pattern: string, optconst regex = new RegExp(source, opts.ignoreCase ? "i" : "");const inDegree = computeInDegree(graph);- const fileNodes = graph.nodes.filter((n) => n.kind === "file" && (!opts.in || n.path.includes(opts.in)));+ // Same segment-aware prefix rule as `ask --in` / `callers --in`, and the same+ // loud failure when it matches nothing — `--in` used to mean a bare substring+ // here and a path prefix there, so `--in src` also swept up `lib/mysrc/`.+ const inPrefix = opts.in ? normalizePathPrefix(opts.in) : undefined;+ if (inPrefix) assertPrefixIndexed(graph, inPrefix);+ const fileNodes = graph.nodes.filter(+ (n) => n.kind === "file" && (inPrefix === undefined || pathUnderPrefix(n.path, inPrefix)),+ );const groups = new Map<string, GrepGroup>();let collected = 0;diff --git a/src/util/paths.ts b/src/util/paths.tsnew file mode 100644index 00000000..61a0a177--- /dev/null+++ b/src/util/paths.ts@@ -0,0 +1,56 @@+/**+ * Repo-relative paths, always posix.+ *+ * Every path graft stores — node ids, `node.path`, extract-cache keys, the+ * freshness fingerprint, the card manifest — is repo-relative and separated by+ * `/` on every platform. That is not cosmetic: the query layer parses these+ * strings with `/` as the separator, and does it by hand rather than through+ * `node:path`. `pathUnderPrefix` (`--in` scoping) tests+ * `startsWith(`${prefix}/`)`, `map`'s `dirKey` splits on `/` to cluster by+ * directory, `resolveSymbol` matches a filename query with+ * `endsWith("/" + query)`. Hand any of them a `src\gate.ts` and none of them+ * error — they match nothing, silently. On Windows that made every `--in`+ * report "nothing indexed under …" and made `map` emit one single-file+ * "directory" per file.+ *+ * So normalize once, here, where a path is *created*, instead of defensively at+ * each consumer — a consumer that forgets is a silent wrong answer, and there+ * are more consumers than producers.+ *+ * {@link toPosixPath} splits on the platform `sep`, never a literal `\`: a+ * posix filename may legitimately contain a backslash, and splitting on `"\\"`+ * would corrupt it. That also makes this module provably the identity function+ * on posix, which is what guarantees an existing Mac/Linux graph is byte-identical+ * across this change.+ */+import { relative, sep } from "node:path";++/** Platform separators → `/`. Identity on posix. */+export function toPosixPath(p: string): string {+ return sep === "/" ? p : p.split(sep).join("/");+}++/**+ * `relative(from, to)`, normalized to posix — the canonical form of every path+ * graft stores. Use this rather than bare `relative` for anything that lands in+ * the graph, a cache key, or a manifest. Bare `relative` is still right for+ * text shown in the terminal, where a native separator is what the platform's+ * users expect.+ */+export function relPosix(from: string, to: string): string {+ return toPosixPath(relative(from, to));+}++/**+ * Normalize a user-supplied path prefix (`--in`) so it can be compared against+ * a stored `node.path`: posix separators, no leading `./`, no trailing+ * separator. Windows users type — and their shell's tab-completion produces —+ * `--in server\src\gpu`, so both separators have to reduce to the same prefix.+ */+export function normalizePathPrefix(p: string): string {+ let out = toPosixPath(p);+ while (out.startsWith("./")) out = out.slice(2);+ // Trailing separators only; a bare "/" normalizes to "" (match everything),+ // which is exactly how `pathUnderPrefix` reads an empty prefix.+ return out.replace(/\/+$/, "");+}diff --git a/test/graph-posix-paths.test.ts b/test/graph-posix-paths.test.tsnew file mode 100644index 00000000..5d51cd9a--- /dev/null+++ b/test/graph-posix-paths.test.ts@@ -0,0 +1,138 @@+/**+ * The end-to-end guard on the posix-path invariant: after a real `buildGraph`,+ * no stored path may carry a platform separator — not a node id, not+ * `node.path`, not an extract-cache key, not a fingerprint key, not a card+ * manifest entry.+ *+ * These assertions pass trivially on posix. They are the regression test for+ * Windows, where `relative()` handed every one of those a `src\gate.ts` and the+ * query layer — which parses paths with `/` by hand — silently matched nothing.+ * They earn their keep on CI's `windows-latest` leg; deleting that leg makes+ * this file decorative.+ *+ * The nested fixture mirrors the five-file repro from issue #35 (`src/` ×3,+ * `lib/` ×1, `scripts/` ×1), so `map`'s directory clustering is exercised on a+ * genuinely built graph rather than on hand-written `GraphV1` stubs — the bug+ * lived in path *production*, so stubs cannot see it.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { buildGraph } from "../src/graph/build.js";+import { readExtractCache } from "../src/graph/extract-cache.js";+import { readFingerprint } from "../src/graph/fingerprint.js";+import { readGraph, wiringPath } from "../src/graph/write.js";+import { buildRepoMap } from "../src/graph/map.js";+import { ask } from "../src/ask/ask.js";+import type { GraphV1 } from "../src/graph/types.js";++const GATE = ["export function isActive(): boolean {", " return true;", "}", ""].join("\n");+const DIRECT = [+ 'import { isActive } from "./gate.js";',+ "export function callsItDirectly(): boolean {",+ " return isActive();",+ "}",+ "",+].join("\n");+const CONSUMER = ['import { isActive } from "./gate.js";', "export const check = isActive;", ""].join("\n");+const HELPER = ["export function helper(): number {", " return 1;", "}", ""].join("\n");+const TOOL = ["export function mjsOnlySymbol() {", " return 2;", "}", ""].join("\n");++/** Issue #35's repro: 5 files across 3 directories, one of them nested deeper. */+function repo(): string {+ const d = mkdtempSync(join(tmpdir(), "graft-posix-"));+ mkdirSync(join(d, "src", "deep"), { recursive: true });+ mkdirSync(join(d, "lib"), { recursive: true });+ mkdirSync(join(d, "scripts"), { recursive: true });+ writeFileSync(join(d, "src", "gate.ts"), GATE);+ writeFileSync(join(d, "src", "direct.ts"), DIRECT);+ writeFileSync(join(d, "src", "deep", "consumer.ts"), CONSUMER);+ writeFileSync(join(d, "lib", "helper.ts"), HELPER);+ writeFileSync(join(d, "scripts", "tool.mjs"), TOOL);+ return d;+}++const outOf = (d: string): string => join(d, "graft");+const graphOf = (d: string): GraphV1 => readGraph(wiringPath(outOf(d)))!;++test("a built graph stores no platform separator in any node id or path", async () => {+ const d = repo();+ await buildGraph(d, { reuse: false });+ const graph = graphOf(d);++ assert.ok(graph.nodes.length > 0, "fixture produced no nodes");+ for (const n of graph.nodes) {+ assert.ok(!n.path.includes("\\"), `node.path carries a backslash: ${n.path}`);+ assert.ok(!n.id.includes("\\"), `node id carries a backslash: ${n.id}`);+ }+ for (const e of graph.edges) {+ assert.ok(!e.source.includes("\\"), `edge source carries a backslash: ${e.source}`);+ assert.ok(!e.target.includes("\\"), `edge target carries a backslash: ${e.target}`);+ }+ // The nested file proves separators are converted at every depth, not just one.+ assert.ok(graph.nodes.some((n) => n.path === "src/deep/consumer.ts"));+});++test("the extract cache and fingerprint are keyed by posix paths", async () => {+ const d = repo();+ await buildGraph(d, { reuse: false });+ const out = outOf(d);++ const cacheKeys = Object.keys(readExtractCache(out).files);+ const printKeys = Object.keys(readFingerprint(out)?.files ?? {});+ assert.ok(cacheKeys.length > 0, "extract cache is empty");+ assert.ok(printKeys.length > 0, "fingerprint is empty");+ for (const k of [...cacheKeys, ...printKeys]) {+ assert.ok(!k.includes("\\"), `cache key carries a backslash: ${k}`);+ }+ // Both are keyed off the same `rel`, so they must agree exactly — a mismatch+ // is what makes `check` report drift that `build` then refuses to repair.+ assert.deepEqual(cacheKeys.sort(), printKeys.sort());+});++test("--in scopes a built graph by directory, at any depth", async () => {+ const d = repo();+ await buildGraph(d, { reuse: false });++ const scoped = ask(d, "isActive", { in: "src" });+ assert.ok(scoped.hits.length > 0, "no hits under src/");+ for (const h of scoped.hits) {+ assert.ok(h.pointer.startsWith("src/"), `leaked out of scope: ${h.pointer}`);+ }++ const deep = ask(d, "check", { in: "src/deep" });+ assert.ok(deep.hits.length > 0, "no hits under src/deep/");+ for (const h of deep.hits) {+ assert.ok(h.pointer.startsWith("src/deep/"), `leaked out of scope: ${h.pointer}`);+ }++ // A prefix that matches nothing is a caller mistake, reported loudly rather+ // than as an empty result the caller has to interpret.+ assert.throws(() => ask(d, "isActive", { in: "nosuchdir" }), /nothing indexed under "nosuchdir\//);+});++test("map clusters a built graph by directory, not one row per file (#35)", async () => {+ const d = repo();+ await buildGraph(d, { reuse: false });+ const map = buildRepoMap(graphOf(d));++ // 5 files across src/, lib/, scripts/ — three groups, not five.+ assert.deepEqual(map.dirs.map((e) => e.path).sort(), ["lib", "scripts", "src"]);+ assert.equal(map.dirs.find((e) => e.path === "src")?.files, 3);+ assert.equal(map.dirs.find((e) => e.path === "lib")?.files, 1);+ assert.equal(map.dirs.find((e) => e.path === "scripts")?.files, 1);+ // Every group is a real directory, not the "bottomed out on a file" fallback.+ assert.ok(map.dirs.every((e) => !e.isFile));+ assert.equal(map.dropped, 0);+});++test("the card manifest records posix card paths", async () => {+ const d = repo();+ const r = await buildGraph(d, { reuse: false });+ assert.ok(r.nodes > 0);++ const index = readFileSync(join(outOf(d), "INDEX.md"), "utf8");+ assert.ok(!/\(\S*\\\S*\.md\)/.test(index), "INDEX.md links carry a backslash");+});diff --git a/test/graph-traverse.test.ts b/test/graph-traverse.test.tsindex 5a41ea64..f4d17760 100644--- a/test/graph-traverse.test.ts+++ b/test/graph-traverse.test.ts@@ -9,6 +9,7 @@*/import { test } from "node:test";import assert from "node:assert/strict";+import { join } from "node:path";import { resolveSymbol, callersOf, calleesOf, impactOf, impactOfMany, impactOfFile } from "../src/graph/traverse.js";import type { EdgeV1, GraphV1, NodeV1, Relation } from "../src/graph/types.js";@@ -96,10 +97,42 @@ test("resolveSymbol: multi-match returns all matching nodes", () => {);});-test("resolveSymbol: --in filters candidates by path substring", () => {+test("resolveSymbol: --in filters candidates by path prefix", () => {const g = baseGraph();- const matches = resolveSymbol(g, "get", { in: "cache" });- assert.deepEqual(matches.map((n) => n.id), ["src/cache.ts#Cache.get"]);+ // An exact file path is a prefix of itself, so it narrows to that one file.+ assert.deepEqual(+ resolveSymbol(g, "get", { in: "src/cache.ts" }).map((n) => n.id),+ ["src/cache.ts#Cache.get"],+ );+ // A directory prefix keeps every match under it.+ assert.deepEqual(+ resolveSymbol(g, "get", { in: "src" }).map((n) => n.id).sort(),+ ["src/cache.ts#Cache.get", "src/other.ts#get"].sort(),+ );+});++test("resolveSymbol: --in is a path prefix, not a substring, and says so when it matches nothing", () => {+ const g = baseGraph();+ // "cache" is a mid-path fragment of "src/cache.ts". Substring matching used to+ // accept it, which also meant `--in src` swept up a sibling `lib/mysrc/`.+ // Failing loudly beats silently returning zero matches the caller must guess at.+ assert.throws(+ () => resolveSymbol(g, "get", { in: "cache" }),+ /nothing indexed under "cache\/"/,+ );+});++test("resolveSymbol: --in accepts a native-separator prefix", () => {+ const g = baseGraph();+ // `join` produces whatever separator this platform's shell and tab-completion+ // produce — `src\cache.ts` on Windows, where every `--in` used to match+ // nothing. Asserted via `join` rather than a literal `\` because a posix+ // filename may legitimately contain a backslash, so normalization is+ // deliberately keyed to the platform separator rather than to both.+ assert.deepEqual(+ resolveSymbol(g, "get", { in: join("src", "cache.ts") }).map((n) => n.id),+ ["src/cache.ts#Cache.get"],+ );});test("resolveSymbol: kind:'file' nodes are excluded when a symbol matches", () => {diff --git a/test/mcp-tools.test.ts b/test/mcp-tools.test.tsindex ec98a02d..a3ccf690 100644--- a/test/mcp-tools.test.ts+++ b/test/mcp-tools.test.ts@@ -147,12 +147,13 @@ test('graft_trace_calls round-trips a caller on the built fixture', async () =>test('graft_trace_calls: qualified/--in narrowing still resolves through the shared resolver', async () => {const d = builtRepo();- const r = await callTool(d, 'graft_trace_calls', { symbol: 'add', in: 'math' });+ const r = await callTool(d, 'graft_trace_calls', { symbol: 'add', in: 'src' });assert.equal(r.isError, false);assert.match(r.text, /calls ← sub/);+ // `in` is a path prefix: an unindexed one is a caller mistake, reported as such.const miss = await callTool(d, 'graft_trace_calls', { symbol: 'add', in: 'nowhere' });assert.equal(miss.isError, true);- assert.match(miss.text, /no symbol "add" in the graph/);+ assert.match(miss.text, /nothing indexed under "nowhere\//);});test('graft_trace_calls direction:out round-trips a callee, and reports a loud note when there are none', async () => {diff --git a/test/paths.test.ts b/test/paths.test.tsnew file mode 100644index 00000000..e52ae9ff--- /dev/null+++ b/test/paths.test.ts@@ -0,0 +1,81 @@+/**+ * Tests for the posix-path invariant (`src/util/paths.ts`) and the `--in` prefix+ * rule that depends on it.+ *+ * The bug these guard against was Windows-only and silent: `relative()` returns+ * the platform separator, so every stored path was `src\gate.ts`, while+ * `pathUnderPrefix` and `map`'s `dirKey` parse paths with `/` by hand. Nothing+ * threw — `--in` just matched nothing, and `map` clustered one "directory" per+ * file.+ *+ * That means most assertions here are trivially true on posix and only bite on+ * Windows, which is why CI runs a `windows-latest` leg. Where a test needs a+ * platform separator it builds one with `join`, never a literal `\`: on posix a+ * literal backslash is a legal filename character, and `toPosixPath` is+ * deliberately keyed to the platform `sep` rather than to both separators so it+ * can't corrupt such a name (and so it is provably the identity on posix, which+ * is what keeps existing Mac/Linux graphs byte-identical across this change).+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { join, sep } from "node:path";+import { normalizePathPrefix, relPosix, toPosixPath } from "../src/util/paths.js";+import { pathUnderPrefix } from "../src/graph/scopes.js";++test("toPosixPath: identity on an already-posix path, and idempotent", () => {+ assert.equal(toPosixPath("src/graph/build.ts"), "src/graph/build.ts");+ assert.equal(toPosixPath("build.ts"), "build.ts");+ assert.equal(toPosixPath(""), "");+ const once = toPosixPath(join("src", "graph", "build.ts"));+ assert.equal(toPosixPath(once), once);+ assert.equal(once, "src/graph/build.ts");+});++test("toPosixPath: converts the platform separator", () => {+ // On posix this asserts the identity case; on Windows it asserts the fix.+ assert.equal(toPosixPath(["a", "b", "c"].join(sep)), "a/b/c");+});++test("relPosix: repo-relative and posix on every platform", () => {+ const root = join(sep === "/" ? "/repo" : "C:\\repo");+ assert.equal(relPosix(root, join(root, "src", "gate.ts")), "src/gate.ts");+ assert.equal(relPosix(root, join(root, "gate.ts")), "gate.ts");+ // The output feeds string parsing that assumes `/`, so this is the invariant+ // that actually matters — never a platform separator, whatever the platform.+ assert.ok(!relPosix(root, join(root, "a", "b", "c.ts")).includes("\\"));+});++test("normalizePathPrefix: trailing separators and leading ./ reduce to one form", () => {+ assert.equal(normalizePathPrefix("src"), "src");+ assert.equal(normalizePathPrefix("src/"), "src");+ assert.equal(normalizePathPrefix("src///"), "src");+ assert.equal(normalizePathPrefix("./src"), "src");+ assert.equal(normalizePathPrefix("././src/"), "src");+ // `ask`'s own footer suggests `--in <scope>/` with the slash, so accepting the+ // trailing form is what keeps the tool's suggested next command runnable.+ assert.equal(normalizePathPrefix("server/src/gpu/"), "server/src/gpu");+ // A bare separator means "everywhere", which is how `pathUnderPrefix` reads "".+ assert.equal(normalizePathPrefix("/"), "");+});++test("normalizePathPrefix: a native-separator prefix normalizes to posix", () => {+ // `server\src\gpu` is what a Windows shell's tab-completion produces, and was+ // reported verbatim as matching nothing.+ assert.equal(normalizePathPrefix(join("server", "src", "gpu")), "server/src/gpu");+ assert.equal(normalizePathPrefix(join("server", "src", "gpu") + sep), "server/src/gpu");+});++test("pathUnderPrefix: segment-aware, so a prefix is not a substring", () => {+ assert.ok(pathUnderPrefix("src/gate.ts", "src"));+ assert.ok(pathUnderPrefix("src/a/b/gate.ts", "src/a"));+ // An exact file path is a prefix of itself — `--in src/gate.ts` scopes to one file.+ assert.ok(pathUnderPrefix("src/gate.ts", "src/gate.ts"));+ // The empty prefix matches everything.+ assert.ok(pathUnderPrefix("src/gate.ts", ""));++ // The cases substring matching got wrong, and which unifying grep/callers onto+ // this rule now excludes.+ assert.ok(!pathUnderPrefix("lib/mysrc/x.ts", "src"));+ assert.ok(!pathUnderPrefix("srcfoo/x.ts", "src"));+ assert.ok(!pathUnderPrefix("src/gate.ts", "gate.ts"));+});diff --git a/test/search-grep.test.ts b/test/search-grep.test.tsindex 7799c503..16cfe766 100644--- a/test/search-grep.test.ts+++ b/test/search-grep.test.ts@@ -164,13 +164,27 @@ test('grepGraph: a hit outside every symbol span groups as file-level (symbol: ntest('grepGraph: `in` filter narrows to matching file paths only', () => {const repo = needleRepo();const graph = loadBuiltGraph(repo);- const r = grepGraph(graph, repo, 'NEEDLE', { in: 'a.ts' });+ const r = grepGraph(graph, repo, 'NEEDLE', { in: 'src/a.ts' });assert.equal(r.filesSearched, 1);assert.equal(r.totalHits, 2);assert.ok(r.groups.every((g) => g.path === 'src/a.ts'));});+test('grepGraph: `in` is a path prefix, not a substring, and errors when it matches nothing', () => {+ const repo = needleRepo();+ const graph = loadBuiltGraph(repo);++ // A bare filename is a mid-path fragment of 'src/a.ts', not a prefix of it.+ assert.throws(() => grepGraph(graph, repo, 'NEEDLE', { in: 'a.ts' }), /nothing indexed under "a\.ts\//);++ // A directory prefix works, and either separator is accepted.+ assert.equal(grepGraph(graph, repo, 'NEEDLE', { in: 'src' }).filesSearched, 2);+ assert.equal(grepGraph(graph, repo, 'NEEDLE', { in: 'src/' }).filesSearched, 2);+ // Native separator — `src\a.ts` on Windows, where this used to match nothing.+ assert.equal(grepGraph(graph, repo, 'NEEDLE', { in: join('src', 'a.ts') }).filesSearched, 1);+});+test('grepGraph: `fixed` escapes regex metacharacters — "a.b" does not match "axb"', () => {const d = mkdtempSync(join(tmpdir(), 'graft-grep-fixed-'));writeFileSync(join(d, 'x.txt'), 'axb\na.b literal line\n');