Graphs that teach > graphs that impress. Turn any code into an interactive knowledge graph you can explore, search, and ask questions about. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, and more.
TypeScript antigravity-skillsbusiness-knowledgeclaude-codeclaude-skillscodebase-analysiscodexcodex-skillsdeveloper-tools-ai-agentgemini-cli-skillskarpathy-llm-wikiknowledge-baseknowledge-graphmemoryopencode-skillspi-agentunderstandcodevibe-coding
fix(mcp): report subproject untracked and non-ASCII paths in understand_diff
Isaiah Frantz0ba7fb88bda3
diff --git a/tests/mcp/changed-files.test.mjs b/tests/mcp/changed-files.test.mjsnew file mode 100644index 00000000..cb8c8f16--- /dev/null+++ b/tests/mcp/changed-files.test.mjs@@ -0,0 +1,120 @@+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import { changedFiles } from '../../understand-anything-plugin/packages/mcp/lib/changed-files.mjs';++const repos = [];++function git(cwd, args) {+ return execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();+}++function write(root, file, content = 'x\n') {+ mkdirSync(dirname(join(root, file)), { recursive: true });+ writeFileSync(join(root, file), content);+}++function commit(root, message = 'commit') {+ git(root, ['add', '-A']);+ git(root, ['-c', 'user.name=test', '-c', '[email protected]', 'commit', '-qm', message]);+}++/** Repo with a root project and an analyzed subproject at apps/service. */+function makeRepo() {+ const root = mkdtempSync(join(tmpdir(), 'ua-mcp-changed-'));+ repos.push(root);+ git(root, ['init', '-q']);+ // Default core.quotePath=true is what produces octal-escaped output.+ git(root, ['config', 'core.quotePath', 'true']);+ write(root, 'README.md');+ write(root, 'src/中文.py', 'v1\n');+ write(root, 'apps/service/src/main.py', 'v1\n');+ write(root, 'apps/service/src/中文.py', 'v1\n');+ write(root, 'apps/service/.ua/knowledge-graph.json', '{}');+ write(root, 'apps/other/src/x.py', 'v1\n');+ commit(root, 'init');+ return { root, service: join(root, 'apps/service') };+}++afterEach(() => {+ while (repos.length) rmSync(repos.pop(), { recursive: true, force: true });+});++describe('changedFiles — subprojects', () => {+ it('lists unstaged untracked files in a subproject relative to it', () => {+ const { service } = makeRepo();+ write(service, 'src/new.py');+ expect(changedFiles(service, {})).toEqual(['src/new.py']);+ });++ it('combines tracked and untracked changes on the same project-relative base', () => {+ const { root, service } = makeRepo();+ write(service, 'src/main.py', 'v2\n');+ write(service, 'src/new.py');+ write(root, 'apps/other/src/x.py', 'v2\n');+ write(root, 'apps/other/src/untracked.py');+ expect(changedFiles(service, {}).sort()).toEqual(['src/main.py', 'src/new.py']);+ });++ it('excludes analysis artifacts in the subproject', () => {+ const { service } = makeRepo();+ write(service, '.ua/knowledge-graph.json', '{"v":2}');+ write(service, '.ua/intermediate/x.json');+ expect(changedFiles(service, {})).toEqual([]);+ });+});++describe('changedFiles — non-ASCII paths', () => {+ it('returns modified non-ASCII paths verbatim at the repo root', () => {+ const { root } = makeRepo();+ write(root, 'src/中文.py', 'v2\n');+ expect(changedFiles(root, {})).toEqual(['src/中文.py']);+ });++ it('returns modified non-ASCII paths verbatim in a subproject', () => {+ const { service } = makeRepo();+ write(service, 'src/中文.py', 'v2\n');+ expect(changedFiles(service, {})).toEqual(['src/中文.py']);+ });++ it('returns untracked non-ASCII paths verbatim', () => {+ const { service } = makeRepo();+ write(service, 'src/新しい.py');+ expect(changedFiles(service, {})).toEqual(['src/新しい.py']);+ });++ it('preserves filenames with surrounding whitespace', () => {+ const { service } = makeRepo();+ write(service, 'src/ spaced .py');+ expect(changedFiles(service, {})).toEqual(['src/ spaced .py']);+ });+});++describe('changedFiles — staged and base modes', () => {+ it('staged=true reports only the index, relative to the subproject', () => {+ const { root, service } = makeRepo();+ write(service, 'src/中文.py', 'v2\n');+ git(root, ['add', 'apps/service/src/中文.py']);+ write(service, 'src/main.py', 'v2\n');+ write(service, 'src/new.py');+ expect(changedFiles(service, { staged: true })).toEqual(['src/中文.py']);+ });++ it('base compares a ref against HEAD, relative to the subproject', () => {+ const { root, service } = makeRepo();+ git(root, ['branch', 'base']);+ write(service, 'src/中文.py', 'v2\n');+ write(root, 'apps/other/src/x.py', 'v2\n');+ commit(root, 'change');+ write(service, 'src/new.py');+ expect(changedFiles(service, { base: 'base' })).toEqual(['src/中文.py']);+ });++ it('rejects option-shaped base refs', () => {+ const { service } = makeRepo();+ expect(() => changedFiles(service, { base: '--output=/tmp/x' })).toThrow(/Invalid base ref/);+ expect(() => changedFiles(service, { base: 'a..b' })).toThrow(/Invalid base ref/);+ });+});diff --git a/understand-anything-plugin/packages/mcp/README.md b/understand-anything-plugin/packages/mcp/README.mdindex 9e98e64b..e41bb5f7 100644--- a/understand-anything-plugin/packages/mcp/README.md+++ b/understand-anything-plugin/packages/mcp/README.md@@ -320,5 +320,8 @@ Run: `node client.mjs`- **Dashboard security** mirrors the viewer: binds to `127.0.0.1`, requiresthe one-time `?token=`, and only serves source files listed in the graph(≤ 1 MB, no binaries).-- **Monorepos**: pass the subdirectory as `projectPath`; git diff paths are- automatically re-rooted from the repository toplevel to the project dir.+- **Monorepos**: pass the subdirectory as `projectPath`; `understand_diff`+ scopes git to that directory and reports tracked and untracked changes+ relative to it, ignoring changes elsewhere in the repository.+- **Non-ASCII paths** are read from NUL-delimited git output (`-z`), so they+ match graph nodes verbatim regardless of `core.quotePath`.diff --git a/understand-anything-plugin/packages/mcp/bin/understand-anything-mcp.mjs b/understand-anything-plugin/packages/mcp/bin/understand-anything-mcp.mjsindex 13caa045..594a80db 100755--- a/understand-anything-plugin/packages/mcp/bin/understand-anything-mcp.mjs+++ b/understand-anything-plugin/packages/mcp/bin/understand-anything-mcp.mjs@@ -13,7 +13,7 @@** stdout is the JSON-RPC channel — diagnostics go to stderr only.*/-import { spawn, execFileSync } from "node:child_process";+import { spawn } from "node:child_process";import fs from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";@@ -35,6 +35,7 @@ import {formatExplainPrompt,buildOnboardingGuide,} from "@understand-anything/skill";+import { changedFiles } from "../lib/changed-files.mjs";const __dirname = path.dirname(fileURLToPath(import.meta.url));const VIEWER_BIN = path.resolve(__dirname, "../../viewer/bin/viewer.mjs");@@ -137,68 +138,6 @@ async function stalenessWarning(root, graph) {);}-function git(root, args) {- return execFileSync("git", args, {- cwd: root,- encoding: "utf8",- stdio: ["ignore", "pipe", "pipe"],- maxBuffer: 32 * 1024 * 1024,- }).trim();-}--/**- * Changed files relative to the project root (handles projects that live in- * a subdirectory of a larger git worktree).- */-function changedFiles(root, { staged, base }) {- const gitRoot = git(root, ["rev-parse", "--show-toplevel"]);- const prefix = path.relative(gitRoot, root); // "" when project is the repo root-- // Reject option-shaped refs: a leading "-" would make git parse the value- // as a flag (e.g. --output=<file> writes the diff somewhere unexpected).- // --end-of-options additionally stops revision parsing of flag-like input.- if (base && (base.startsWith("-") || base.includes(".."))) {- throw new Error(- `Invalid base ref "${base}" — must be a plain ref like 'main' or 'HEAD~3' (no leading '-', and '...' is added by the tool).`,- );- }-- const diffArgs = base- ? ["diff", "--name-only", "--end-of-options", `${base}...HEAD`]- : staged- ? ["diff", "--cached", "--name-only"]- : ["diff", "HEAD", "--name-only"];-- let files = git(root, diffArgs).split("\n").filter(Boolean);- if (!base && !staged) {- const untracked = git(root, [- "ls-files",- "--others",- "--exclude-standard",- ])- .split("\n")- .filter(Boolean);- files = [...files, ...untracked];- }-- // Generated analysis artifacts are not project source drift (mirrors- // core's PROJECT_PATHSPEC exclusions in staleness.ts).- const isArtifact = (f) =>- f === ".ua" ||- f.startsWith(".ua/") ||- f === ".understand-anything" ||- f.startsWith(".understand-anything/");-- return [- ...new Set(- files- .filter((f) => !prefix || f.startsWith(`${prefix}/`))- .map((f) => (prefix ? f.slice(prefix.length + 1) : f))- .filter((f) => !isArtifact(f)),- ),- ];-}-// ── Dashboard session management ──────────────────────────────────────────/** @type {Map<string, { url: string, child: import("node:child_process").ChildProcess }>} */diff --git a/understand-anything-plugin/packages/mcp/lib/changed-files.mjs b/understand-anything-plugin/packages/mcp/lib/changed-files.mjsnew file mode 100644index 00000000..7861b1e1--- /dev/null+++ b/understand-anything-plugin/packages/mcp/lib/changed-files.mjs@@ -0,0 +1,53 @@+import { execFileSync } from "node:child_process";++// Scope every query to the project directory and exclude generated analysis+// artifacts (mirrors core's PROJECT_PATHSPEC in staleness.ts).+const PROJECT_PATHSPEC = [+ "--",+ ".",+ ":(exclude).understand-anything",+ ":(exclude).understand-anything/**",+ ":(exclude).ua",+ ":(exclude).ua/**",+];++function gitPaths(root, args) {+ const out = execFileSync("git", [...args, ...PROJECT_PATHSPEC], {+ cwd: root,+ encoding: "utf8",+ stdio: ["ignore", "pipe", "pipe"],+ maxBuffer: 32 * 1024 * 1024,+ });+ return out.split("\0").filter(Boolean);+}++/**+ * Changed files relative to the project root, which may be a subdirectory of+ * a larger git worktree. `--relative` makes `git diff` report paths relative+ * to the cwd, matching `git ls-files`; `-z` disables C-style quoting so+ * non-ASCII paths match graph nodes verbatim.+ */+export function changedFiles(root, { staged, base } = {}) {+ // Reject option-shaped refs: a leading "-" would make git parse the value+ // as a flag (e.g. --output=<file> writes the diff somewhere unexpected).+ // --end-of-options additionally stops revision parsing of flag-like input.+ if (base && (base.startsWith("-") || base.includes(".."))) {+ throw new Error(+ `Invalid base ref "${base}" — must be a plain ref like 'main' or 'HEAD~3' (no leading '-', and '...' is added by the tool).`,+ );+ }++ const diff = ["diff", "--name-only", "-z", "--relative"];+ const files = gitPaths(+ root,+ base+ ? [...diff, "--end-of-options", `${base}...HEAD`]+ : staged+ ? [...diff, "--cached"]+ : [...diff, "HEAD"],+ );+ if (!base && !staged) {+ files.push(...gitPaths(root, ["ls-files", "--others", "--exclude-standard", "-z"]));+ }+ return [...new Set(files)];+}diff --git a/understand-anything-plugin/packages/mcp/package.json b/understand-anything-plugin/packages/mcp/package.jsonindex c31f3260..4199c9ee 100644--- a/understand-anything-plugin/packages/mcp/package.json+++ b/understand-anything-plugin/packages/mcp/package.json@@ -14,6 +14,7 @@},"files": ["bin",+ "lib","README.md"],"engines": {