Skip to content

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.

Merge origin/main into feat-stale-graph-warning

jiang4wqy48c54509376f
diff --cc .claude-plugin/plugin.json
index ff092871,c9027626..779bd010
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@@ -1,7 -1,7 +1,7 @@@
{
"name": "understand-anything",
"description": "AI-powered codebase understanding — analyze, visualize, and explain any project",
- "version": "2.8.3",
- "version": "2.9.3",
++ "version": "2.9.4",
"author": {
"name": "Egonex"
},
diff --cc .copilot-plugin/plugin.json
index da47a728,34460dc3..7841d335
--- a/.copilot-plugin/plugin.json
+++ b/.copilot-plugin/plugin.json
@@@ -1,7 -1,7 +1,7 @@@
{
"name": "understand-anything",
"description": "AI-powered codebase understanding — analyze, visualize, and explain any project",
- "version": "2.8.3",
- "version": "2.9.3",
++ "version": "2.9.4",
"author": {
"name": "Egonex"
},
diff --cc .cursor-plugin/plugin.json
index 479afdcf,8a0fd94d..5dcbccd6
--- a/.cursor-plugin/plugin.json
+++ b/.cursor-plugin/plugin.json
@@@ -2,7 -2,7 +2,7 @@@
"name": "understand-anything",
"displayName": "Understand Anything",
"description": "AI-powered codebase understanding — analyze, visualize, and explain any project",
- "version": "2.8.3",
- "version": "2.9.3",
++ "version": "2.9.4",
"author": {
"name": "Egonex"
},
diff --cc tests/skill/understand/test_skill_graph_freshness.test.mjs
index 6cd79f41,00000000..c3a5deac
mode 100644,000000..100644
--- a/tests/skill/understand/test_skill_graph_freshness.test.mjs
+++ b/tests/skill/understand/test_skill_graph_freshness.test.mjs
@@@ -1,71 -1,0 +1,71 @@@
+import { readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(__dirname, "../../..");
+
+const graphConsumerSkills = [
+ "understand-chat",
+ "understand-explain",
+ "understand-diff",
+ "understand-onboard",
+ "understand-domain",
+];
+
+const requiredFreshnessInstructions = [
+ "gitCommitHash",
+ "git rev-parse HEAD",
+ 'git rev-parse --verify --end-of-options "${GRAPH_COMMIT_RAW}^{commit}"',
+ "git diff --name-only \"$GRAPH_COMMIT\" HEAD -- .",
+ "git diff --cached --name-only -- .",
+ "git diff --name-only -- .",
+ "git ls-files --others --exclude-standard -- .",
+ "working-tree",
+ "hash mismatch",
+ "project diff is empty",
- "Ignore `.understand-anything/`",
++ "Ignore the selected data directory (`.ua/` or legacy `.understand-anything/`)",
+ "warn",
+ "continue",
+ "Run `/understand`",
+];
+
+describe("graph-consuming skills", () => {
+ it.each(graphConsumerSkills)(
+ "%s checks committed and working-tree freshness before using a graph",
+ (skillName) => {
+ const skillPath = resolve(
+ repoRoot,
+ "understand-anything-plugin",
+ "skills",
+ skillName,
+ "SKILL.md",
+ );
+ const content = readFileSync(skillPath, "utf-8");
+
+ for (const instruction of requiredFreshnessInstructions) {
+ expect(content).toContain(instruction);
+ }
+ expect(content).not.toContain(
+ 'git diff --name-only "$GRAPH_COMMIT_RAW" HEAD -- .',
+ );
+ },
+ );
+
+ it("understand-domain applies the preflight only to its existing-graph path", () => {
+ const content = readFileSync(
+ resolve(
+ repoRoot,
+ "understand-anything-plugin",
+ "skills",
+ "understand-domain",
+ "SKILL.md",
+ ),
+ "utf-8",
+ );
+
+ expect(content).toContain("When `--full` is used, skip this preflight");
+ expect(content).toContain("Phase 3: Derive from Existing Graph");
+ });
+});
diff --cc tests/skill/viewer/test_viewer.test.mjs
index 00000000,530c27ae..bcce56c7
mode 000000,100644..100644
--- a/tests/skill/viewer/test_viewer.test.mjs
+++ b/tests/skill/viewer/test_viewer.test.mjs
@@@ -1,0 -1,158 +1,195 @@@
+ // End-to-end tests for the standalone viewer (packages/viewer/bin/viewer.mjs).
+ // Spawns the real server against a fixture project and exercises the token
+ // gate, graph sanitisation, file-content allowlist, and .ua/legacy resolution.
+ import { describe, it, expect, beforeAll, afterAll } from "vitest";
-import { spawn } from "node:child_process";
++import { execFileSync, spawn } from "node:child_process";
+ import { mkdtempSync, rmSync, mkdirSync, writeFileSync, existsSync } from "node:fs";
+ import { tmpdir } from "node:os";
+ import { join, dirname, resolve } from "node:path";
+ import { fileURLToPath } from "node:url";
+
+ const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
+ const VIEWER_BIN = join(
+ REPO_ROOT,
+ "understand-anything-plugin",
+ "packages",
+ "viewer",
+ "bin",
+ "viewer.mjs",
+ );
+ const VIEWER_DIST = join(REPO_ROOT, "understand-anything-plugin", "packages", "viewer", "dist");
+
-function fixtureGraph() {
++function fixtureGraph(gitCommitHash) {
+ return {
+ version: "1.0.0",
+ project: {
+ name: "fixture", languages: ["ts"], frameworks: [], description: "d",
- analyzedAt: "t", gitCommitHash: "",
++ analyzedAt: "2026-07-17T00:00:00.000Z", gitCommitHash,
+ },
+ nodes: [
+ {
+ id: "file:src/a.ts", type: "file", name: "a.ts", filePath: "src/a.ts",
+ summary: "s", tags: [], complexity: "simple",
+ },
+ ],
+ edges: [],
+ layers: [],
+ tour: [],
+ };
+ }
+
++function git(projectRoot, ...args) {
++ return execFileSync("git", args, {
++ cwd: projectRoot,
++ encoding: "utf8",
++ }).trim();
++}
++
+ function setupProject(dataDirName) {
+ const root = mkdtempSync(join(tmpdir(), "ua-viewer-"));
- const dataDir = join(root, dataDirName);
- mkdirSync(dataDir, { recursive: true });
- writeFileSync(join(dataDir, "knowledge-graph.json"), JSON.stringify(fixtureGraph()));
+ mkdirSync(join(root, "src"), { recursive: true });
+ writeFileSync(join(root, "src", "a.ts"), "export const a = 1;\n");
+ writeFileSync(join(root, "secret.txt"), "not in graph\n");
++ git(root, "init");
++ git(root, "config", "user.email", "[email protected]");
++ git(root, "config", "user.name", "Viewer Tests");
++ git(root, "add", "--all");
++ git(root, "commit", "-m", "baseline");
++
++ const dataDir = join(root, dataDirName);
++ mkdirSync(dataDir, { recursive: true });
++ writeFileSync(
++ join(dataDir, "knowledge-graph.json"),
++ JSON.stringify(fixtureGraph(git(root, "rev-parse", "HEAD"))),
++ );
+ return root;
+ }
+
+ /** Start the viewer and wait for the printed URL. Returns { proc, url, token, port }. */
+ function startViewer(projectRoot) {
+ return new Promise((resolvePromise, rejectPromise) => {
+ const proc = spawn(
+ process.execPath,
+ [VIEWER_BIN, projectRoot, "--no-open", "--port", "0"],
+ { env: { ...process.env }, stdio: ["ignore", "pipe", "pipe"] },
+ );
+ let out = "";
+ const timer = setTimeout(() => {
+ proc.kill();
+ rejectPromise(new Error(`viewer did not start.\n${out}`));
+ }, 10_000);
+ const onData = (chunk) => {
+ out += String(chunk);
+ const m = out.match(/http:\/\/127\.0\.0\.1:(\d+)\/\?token=([a-f0-9]+)/);
+ if (m) {
+ clearTimeout(timer);
+ resolvePromise({ proc, url: m[0], port: Number(m[1]), token: m[2] });
+ }
+ };
+ proc.stdout.on("data", onData);
+ proc.stderr.on("data", onData);
+ proc.on("exit", (code) => {
+ clearTimeout(timer);
+ rejectPromise(new Error(`viewer exited with ${code}.\n${out}`));
+ });
+ });
+ }
+
+ describe.skipIf(!existsSync(VIEWER_DIST))("understand-anything-viewer", () => {
+ let root;
+ let viewer;
+
+ beforeAll(async () => {
+ root = setupProject(".ua");
+ viewer = await startViewer(root);
+ }, 15_000);
+
+ afterAll(() => {
+ viewer?.proc.kill();
+ if (root) rmSync(root, { recursive: true, force: true });
+ });
+
+ const base = () => `http://127.0.0.1:${viewer.port}`;
+
+ it("serves the embedded dashboard index", async () => {
+ const res = await fetch(`${base()}/`);
+ expect(res.status).toBe(200);
+ expect(await res.text()).toContain("<!doctype html>");
+ });
+
+ it("rejects data requests without the token", async () => {
+ const res = await fetch(`${base()}/knowledge-graph.json`);
+ expect(res.status).toBe(403);
+ });
+
+ it("serves the graph from .ua/ with a valid token", async () => {
+ const res = await fetch(`${base()}/knowledge-graph.json?token=${viewer.token}`);
+ expect(res.status).toBe(200);
+ const graph = await res.json();
+ expect(graph.nodes).toHaveLength(1);
+ expect(graph.nodes[0].filePath).toBe("src/a.ts");
+ });
+
++ it("serves a protected no-store freshness report", async () => {
++ const denied = await fetch(`${base()}/staleness.json`);
++ expect(denied.status).toBe(403);
++ expect(denied.headers.get("cache-control")).toBe("no-store");
++
++ const res = await fetch(
++ `${base()}/staleness.json?token=${viewer.token}`,
++ );
++ expect(res.status).toBe(200);
++ expect(res.headers.get("cache-control")).toBe("no-store");
++ expect(await res.json()).toMatchObject({
++ graphs: {
++ knowledge: {
++ status: "fresh",
++ graphCommitHash: git(root, "rev-parse", "HEAD"),
++ headCommitHash: git(root, "rev-parse", "HEAD"),
++ },
++ },
++ });
++ });
++
+ it("serves file content only for files listed in the graph", async () => {
+ const ok = await fetch(
+ `${base()}/file-content.json?token=${viewer.token}&path=${encodeURIComponent("src/a.ts")}`,
+ );
+ expect(ok.status).toBe(200);
+ const body = await ok.json();
+ expect(body.content).toContain("export const a");
+ expect(body.language).toBe("typescript");
+
+ const denied = await fetch(
+ `${base()}/file-content.json?token=${viewer.token}&path=secret.txt`,
+ );
+ expect(denied.status).toBe(404);
+ });
+
+ it("rejects path traversal in file-content", async () => {
+ const res = await fetch(
+ `${base()}/file-content.json?token=${viewer.token}&path=${encodeURIComponent("../outside.txt")}`,
+ );
+ expect(res.status).toBe(400);
+ });
+
+ it("blocks static requests escaping dist/", async () => {
+ const res = await fetch(`${base()}/%2e%2e/package.json`);
+ expect([403, 404]).toContain(res.status);
+ });
+
+ it("falls back to legacy .understand-anything/ projects", async () => {
+ const legacyRoot = setupProject(".understand-anything");
+ const legacyViewer = await startViewer(legacyRoot);
+ try {
+ const res = await fetch(
+ `http://127.0.0.1:${legacyViewer.port}/knowledge-graph.json?token=${legacyViewer.token}`,
+ );
+ expect(res.status).toBe(200);
+ expect((await res.json()).nodes).toHaveLength(1);
+ } finally {
+ legacyViewer.proc.kill();
+ rmSync(legacyRoot, { recursive: true, force: true });
+ }
+ }, 15_000);
+ });
diff --cc understand-anything-plugin/.claude-plugin/plugin.json
index ff092871,c9027626..779bd010
--- a/understand-anything-plugin/.claude-plugin/plugin.json
+++ b/understand-anything-plugin/.claude-plugin/plugin.json
@@@ -1,7 -1,7 +1,7 @@@
{
"name": "understand-anything",
"description": "AI-powered codebase understanding — analyze, visualize, and explain any project",
- "version": "2.8.3",
- "version": "2.9.3",
++ "version": "2.9.4",
"author": {
"name": "Egonex"
},
diff --cc understand-anything-plugin/package.json
index ed9443a8,b9748551..c27d6b17
--- a/understand-anything-plugin/package.json
+++ b/understand-anything-plugin/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "@understand-anything/skill",
- "version": "2.8.3",
- "version": "2.9.3",
++ "version": "2.9.4",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
diff --cc understand-anything-plugin/packages/core/src/__tests__/graph-freshness.integration.test.ts
index b455a8f1,00000000..e79b1a21
mode 100644,000000..100644
--- a/understand-anything-plugin/packages/core/src/__tests__/graph-freshness.integration.test.ts
+++ b/understand-anything-plugin/packages/core/src/__tests__/graph-freshness.integration.test.ts
@@@ -1,480 -1,0 +1,485 @@@
+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 {
+ getGraphFreshness,
+ getGraphFreshnessBatch,
+} from "../staleness.js";
+
+const temporaryDirectories: string[] = [];
+
+function git(cwd: string, ...args: string[]): string {
+ return execFileSync("git", args, {
+ cwd,
+ encoding: "utf8",
+ }).trim();
+}
+
+function createTemporaryDirectory(prefix = "ua-freshness-"): string {
+ const directory = mkdtempSync(join(tmpdir(), prefix));
+ temporaryDirectories.push(directory);
+ return directory;
+}
+
+function writeProjectFile(
+ projectDir: string,
+ relativePath: string,
+ contents: string,
+): void {
+ const filePath = join(projectDir, ...relativePath.split("/"));
+ mkdirSync(dirname(filePath), { recursive: true });
+ writeFileSync(filePath, contents, "utf8");
+}
+
+function commitAll(repoDir: string, message: string): string {
+ git(repoDir, "add", "--all");
+ git(repoDir, "commit", "-m", message);
+ return git(repoDir, "rev-parse", "HEAD");
+}
+
+function createRepository(
+ initialFiles: Record<string, string> = {
+ "src/index.ts": "export const value = 1;\n",
+ },
+): { repoDir: string; baseline: string } {
+ const repoDir = createTemporaryDirectory();
+ git(repoDir, "init");
+ git(repoDir, "config", "user.email", "[email protected]");
+ git(repoDir, "config", "user.name", "Freshness Tests");
+
+ for (const [relativePath, contents] of Object.entries(initialFiles)) {
+ writeProjectFile(repoDir, relativePath, contents);
+ }
+
+ return {
+ repoDir,
+ baseline: commitAll(repoDir, "baseline"),
+ };
+}
+
+afterEach(() => {
+ for (const directory of temporaryDirectories.splice(0)) {
+ rmSync(directory, {
+ recursive: true,
+ force: true,
+ maxRetries: 5,
+ retryDelay: 100,
+ });
+ }
+});
+
+describe(
+ "getGraphFreshness with a real Git repository",
+ { timeout: 15_000 },
+ () => {
+ it("returns fresh for a clean project at the analyzed commit", async () => {
+ const { repoDir, baseline } = createRepository();
+
+ await expect(
+ getGraphFreshness(repoDir, {
+ graphCommitHash: baseline,
+ lastAnalyzedAt: "2026-07-10T00:00:00.000Z",
+ }),
+ ).resolves.toEqual({
+ status: "fresh",
+ graphCommitHash: baseline,
+ headCommitHash: baseline,
+ changedFileCount: 0,
+ changedFiles: [],
+ commitsBehind: 0,
+ commitsAhead: 0,
+ lastAnalyzedAt: "2026-07-10T00:00:00.000Z",
+ });
+ });
+
+ it.each([
+ {
+ name: "unstaged",
+ path: "src/index.ts",
+ prepare(repoDir: string) {
+ writeProjectFile(repoDir, "src/index.ts", "export const value = 2;\n");
+ },
+ },
+ {
+ name: "staged",
+ path: "src/staged.ts",
+ prepare(repoDir: string) {
+ writeProjectFile(repoDir, "src/staged.ts", "export const staged = true;\n");
+ git(repoDir, "add", "src/staged.ts");
+ },
+ },
+ {
+ name: "untracked",
+ path: "src/untracked.ts",
+ prepare(repoDir: string) {
+ writeProjectFile(
+ repoDir,
+ "src/untracked.ts",
+ "export const untracked = true;\n",
+ );
+ },
+ },
+ ])("returns dirty for $name project changes", async ({ path, prepare }) => {
+ const { repoDir, baseline } = createRepository();
+ prepare(repoDir);
+
+ await expect(
+ getGraphFreshness(repoDir, { graphCommitHash: baseline }),
+ ).resolves.toMatchObject({
+ status: "dirty",
+ graphCommitHash: baseline,
+ headCommitHash: baseline,
+ changedFileCount: 1,
+ changedFiles: [path],
+ commitsBehind: 0,
+ commitsAhead: 0,
+ });
+ });
+
+ it("deduplicates paths changed in both the index and working tree", async () => {
+ const { repoDir, baseline } = createRepository();
+ writeProjectFile(repoDir, "src/index.ts", "export const value = 2;\n");
+ git(repoDir, "add", "src/index.ts");
+ writeProjectFile(repoDir, "src/index.ts", "export const value = 3;\n");
+
+ await expect(
+ getGraphFreshness(repoDir, { graphCommitHash: baseline }),
+ ).resolves.toMatchObject({
+ status: "dirty",
+ changedFileCount: 1,
+ changedFiles: ["src/index.ts"],
+ });
+ });
+
- it("ignores untracked Understand Anything output files", async () => {
++ it.each([".understand-anything", ".ua"])(
++ "ignores untracked Understand Anything output files in %s",
++ async (dataDir) => {
+ const { repoDir, baseline } = createRepository();
+ writeProjectFile(
+ repoDir,
- ".understand-anything/knowledge-graph.json",
++ `${dataDir}/knowledge-graph.json`,
+ "{}\n",
+ );
+ writeProjectFile(
+ repoDir,
- ".understand-anything/intermediate/batch-0.json",
++ `${dataDir}/intermediate/batch-0.json`,
+ "{}\n",
+ );
+
+ await expect(
+ getGraphFreshness(repoDir, { graphCommitHash: baseline }),
+ ).resolves.toMatchObject({
+ status: "fresh",
+ changedFileCount: 0,
+ changedFiles: [],
+ });
- });
-
- it("ignores commits that only change Understand Anything output files", async () => {
- const { repoDir, baseline } = createRepository();
- writeProjectFile(
- repoDir,
- ".understand-anything/knowledge-graph.json",
- "{}\n",
- );
- const headCommit = commitAll(repoDir, "persist generated graph");
-
- await expect(
- getGraphFreshness(repoDir, { graphCommitHash: baseline }),
- ).resolves.toEqual({
- status: "fresh",
- graphCommitHash: baseline,
- headCommitHash: headCommit,
- changedFileCount: 0,
- changedFiles: [],
- commitsBehind: 0,
- commitsAhead: 0,
- });
- });
-
- it("still reports source changes beside ignored output files", async () => {
- const { repoDir, baseline } = createRepository();
- writeProjectFile(
- repoDir,
- ".understand-anything/knowledge-graph.json",
- "{}\n",
- );
- writeProjectFile(repoDir, "src/real-change.ts", "export const changed = true;\n");
-
- await expect(
- getGraphFreshness(repoDir, { graphCommitHash: baseline }),
- ).resolves.toMatchObject({
- status: "dirty",
- changedFileCount: 1,
- changedFiles: ["src/real-change.ts"],
- });
- });
++ },
++ );
++
++ it.each([".understand-anything", ".ua"])(
++ "ignores commits that only change Understand Anything output files in %s",
++ async (dataDir) => {
++ const { repoDir, baseline } = createRepository();
++ writeProjectFile(repoDir, `${dataDir}/knowledge-graph.json`, "{}\n");
++ const headCommit = commitAll(repoDir, "persist generated graph");
++
++ await expect(
++ getGraphFreshness(repoDir, { graphCommitHash: baseline }),
++ ).resolves.toEqual({
++ status: "fresh",
++ graphCommitHash: baseline,
++ headCommitHash: headCommit,
++ changedFileCount: 0,
++ changedFiles: [],
++ commitsBehind: 0,
++ commitsAhead: 0,
++ });
++ },
++ );
++
++ it.each([".understand-anything", ".ua"])(
++ "still reports source changes beside ignored output files in %s",
++ async (dataDir) => {
++ const { repoDir, baseline } = createRepository();
++ writeProjectFile(repoDir, `${dataDir}/knowledge-graph.json`, "{}\n");
++ writeProjectFile(
++ repoDir,
++ "src/real-change.ts",
++ "export const changed = true;\n",
++ );
++
++ await expect(
++ getGraphFreshness(repoDir, { graphCommitHash: baseline }),
++ ).resolves.toMatchObject({
++ status: "dirty",
++ changedFileCount: 1,
++ changedFiles: ["src/real-change.ts"],
++ });
++ },
++ );
+
+ it("resolves an abbreviated graph hash to the full matching commit", async () => {
+ const { repoDir, baseline } = createRepository();
+
+ await expect(
+ getGraphFreshness(repoDir, {
+ graphCommitHash: baseline.slice(0, 8),
+ }),
+ ).resolves.toMatchObject({
+ status: "fresh",
+ graphCommitHash: baseline,
+ headCommitHash: baseline,
+ });
+ });
+
+ it("reports a graph behind the current project history", async () => {
+ const { repoDir, baseline } = createRepository();
+ writeProjectFile(repoDir, "src/index.ts", "export const value = 2;\n");
+ const head = commitAll(repoDir, "project change");
+
+ await expect(
+ getGraphFreshness(repoDir, { graphCommitHash: baseline }),
+ ).resolves.toMatchObject({
+ status: "stale",
+ relation: "behind",
+ graphCommitHash: baseline,
+ headCommitHash: head,
+ changedFileCount: 1,
+ changedFiles: ["src/index.ts"],
+ commitsBehind: 1,
+ commitsAhead: 0,
+ });
+ });
+
+ it("reports a graph ahead of the checked-out project history", async () => {
+ const { repoDir, baseline } = createRepository();
+ writeProjectFile(repoDir, "src/future.ts", "export const future = true;\n");
+ const graphCommit = commitAll(repoDir, "future graph commit");
+ git(repoDir, "checkout", "--detach", baseline);
+
+ await expect(
+ getGraphFreshness(repoDir, { graphCommitHash: graphCommit }),
+ ).resolves.toMatchObject({
+ status: "stale",
+ relation: "ahead",
+ graphCommitHash: graphCommit,
+ headCommitHash: baseline,
+ changedFileCount: 1,
+ changedFiles: ["src/future.ts"],
+ commitsBehind: 0,
+ commitsAhead: 1,
+ });
+ });
+
+ it("reports divergent project histories without calling either side behind", async () => {
+ const { repoDir, baseline } = createRepository();
+ git(repoDir, "checkout", "-b", "graph-history");
+ writeProjectFile(repoDir, "src/graph.ts", "export const graph = true;\n");
+ const graphCommit = commitAll(repoDir, "graph-side change");
+
+ git(repoDir, "checkout", "-b", "head-history", baseline);
+ writeProjectFile(repoDir, "src/head.ts", "export const head = true;\n");
+ const headCommit = commitAll(repoDir, "head-side change");
+
+ await expect(
+ getGraphFreshness(repoDir, { graphCommitHash: graphCommit }),
+ ).resolves.toMatchObject({
+ status: "stale",
+ relation: "diverged",
+ graphCommitHash: graphCommit,
+ headCommitHash: headCommit,
+ changedFileCount: 2,
+ changedFiles: ["src/graph.ts", "src/head.ts"],
+ commitsBehind: 1,
+ commitsAhead: 1,
+ });
+ });
+
+ it("ignores commits that only touch a sibling monorepo project", async () => {
+ const { repoDir, baseline } = createRepository({
+ "apps/target/src/index.ts": "export const target = 1;\n",
+ "apps/sibling/src/index.ts": "export const sibling = 1;\n",
+ });
+ writeProjectFile(
+ repoDir,
+ "apps/sibling/src/index.ts",
+ "export const sibling = 2;\n",
+ );
+ const head = commitAll(repoDir, "sibling-only change");
+ const targetProject = join(repoDir, "apps", "target");
+
+ await expect(
+ getGraphFreshness(targetProject, { graphCommitHash: baseline }),
+ ).resolves.toEqual({
+ status: "fresh",
+ graphCommitHash: baseline,
+ headCommitHash: head,
+ changedFileCount: 0,
+ changedFiles: [],
+ commitsBehind: 0,
+ commitsAhead: 0,
+ });
+ });
+
+ it("ignores staged, unstaged, and untracked changes in a sibling project", async () => {
+ const { repoDir, baseline } = createRepository({
+ "apps/target/src/index.ts": "export const target = 1;\n",
+ "apps/sibling/src/staged.ts": "export const staged = 1;\n",
+ "apps/sibling/src/unstaged.ts": "export const unstaged = 1;\n",
+ });
+ writeProjectFile(
+ repoDir,
+ "apps/sibling/src/staged.ts",
+ "export const staged = 2;\n",
+ );
+ git(repoDir, "add", "apps/sibling/src/staged.ts");
+ writeProjectFile(
+ repoDir,
+ "apps/sibling/src/unstaged.ts",
+ "export const unstaged = 2;\n",
+ );
+ writeProjectFile(
+ repoDir,
+ "apps/sibling/src/untracked.ts",
+ "export const untracked = true;\n",
+ );
+ const targetProject = join(repoDir, "apps", "target");
+
+ await expect(
+ getGraphFreshness(targetProject, { graphCommitHash: baseline }),
+ ).resolves.toEqual({
+ status: "fresh",
+ graphCommitHash: baseline,
+ headCommitHash: baseline,
+ changedFileCount: 0,
+ changedFiles: [],
+ commitsBehind: 0,
+ commitsAhead: 0,
+ });
+ });
+
+ it("counts only selected-project commits and returns project-relative paths", async () => {
+ const { repoDir, baseline } = createRepository({
+ "apps/target/src/index.ts": "export const target = 1;\n",
+ "apps/sibling/src/index.ts": "export const sibling = 1;\n",
+ });
+ writeProjectFile(
+ repoDir,
+ "apps/sibling/src/index.ts",
+ "export const sibling = 2;\n",
+ );
+ commitAll(repoDir, "sibling-only change");
+ writeProjectFile(
+ repoDir,
+ "apps/target/src/index.ts",
+ "export const target = 2;\n",
+ );
+ commitAll(repoDir, "target-project change");
+ const targetProject = join(repoDir, "apps", "target");
+
+ await expect(
+ getGraphFreshness(targetProject, { graphCommitHash: baseline }),
+ ).resolves.toMatchObject({
+ status: "stale",
+ relation: "behind",
+ changedFileCount: 1,
+ changedFiles: ["src/index.ts"],
+ commitsBehind: 1,
+ commitsAhead: 0,
+ });
+ });
+
+ it("preserves spaces and non-ASCII characters in changed paths", async () => {
+ const specialPath = "src/space name-文件.ts";
+ const { repoDir, baseline } = createRepository({
+ [specialPath]: "export const value = 1;\n",
+ });
+ writeProjectFile(repoDir, specialPath, "export const value = 2;\n");
+ commitAll(repoDir, "change special path");
+
+ await expect(
+ getGraphFreshness(repoDir, { graphCommitHash: baseline }),
+ ).resolves.toMatchObject({
+ status: "stale",
+ changedFileCount: 1,
+ changedFiles: [specialPath],
+ });
+ });
+
+ it("evaluates multiple graph commits in one batch", async () => {
+ const { repoDir, baseline } = createRepository();
+ writeProjectFile(repoDir, "src/domain.ts", "export const domain = 1;\n");
+ const domainCommit = commitAll(repoDir, "domain graph commit");
+ writeProjectFile(repoDir, "src/index.ts", "export const value = 2;\n");
+ const headCommit = commitAll(repoDir, "knowledge graph drift");
+
+ await expect(
+ getGraphFreshnessBatch(repoDir, {
+ knowledge: { graphCommitHash: baseline },
+ domain: { graphCommitHash: domainCommit },
+ }),
+ ).resolves.toMatchObject({
+ knowledge: {
+ status: "stale",
+ relation: "behind",
+ headCommitHash: headCommit,
+ commitsBehind: 2,
+ },
+ domain: {
+ status: "stale",
+ relation: "behind",
+ headCommitHash: headCommit,
+ commitsBehind: 1,
+ changedFiles: ["src/index.ts"],
+ },
+ });
+ });
+
+ it("returns missing-graph-commit without consulting Git", async () => {
+ const projectDir = createTemporaryDirectory();
+
+ await expect(
+ getGraphFreshness(projectDir, {
+ graphCommitHash: " ",
+ lastAnalyzedAt: "2026-07-10T00:00:00.000Z",
+ }),
+ ).resolves.toEqual({
+ status: "unknown",
+ reason: "missing-graph-commit",
+ lastAnalyzedAt: "2026-07-10T00:00:00.000Z",
+ });
+ });
+
+ it("returns git-head-unavailable outside a Git repository", async () => {
+ const projectDir = createTemporaryDirectory();
+
+ await expect(
+ getGraphFreshness(projectDir, { graphCommitHash: "deadbeef" }),
+ ).resolves.toEqual({
+ status: "unknown",
+ reason: "git-head-unavailable",
+ graphCommitHash: "deadbeef",
+ });
+ });
+
+ it("returns graph-commit-unavailable for an unknown graph commit", async () => {
+ const { repoDir, baseline } = createRepository();
+
+ await expect(
+ getGraphFreshness(repoDir, { graphCommitHash: "deadbeef" }),
+ ).resolves.toEqual({
+ status: "unknown",
+ reason: "graph-commit-unavailable",
+ graphCommitHash: "deadbeef",
+ headCommitHash: baseline,
+ });
+ });
+ },
+);
diff --cc understand-anything-plugin/packages/core/src/staleness.ts
index 41db325b,0750ba3f..93bb06d8
--- a/understand-anything-plugin/packages/core/src/staleness.ts
+++ b/understand-anything-plugin/packages/core/src/staleness.ts
@@@ -6,356 -6,6 +6,358 @@@ export interface StalenessResult
changedFiles: string[];
}
+export type GraphFreshnessRelation = "behind" | "ahead" | "diverged";
+
+export type GraphFreshnessUnknownReason =
+ | "missing-graph-commit"
+ | "git-head-unavailable"
+ | "graph-commit-unavailable"
+ | "git-command-timeout"
+ | "freshness-request-failed";
+
+export type GraphFreshnessResult =
+ | {
+ status: "fresh";
+ graphCommitHash: string;
+ headCommitHash: string;
+ changedFileCount: 0;
+ changedFiles: [];
+ commitsBehind: 0;
+ commitsAhead: 0;
+ lastAnalyzedAt?: string;
+ }
+ | {
+ status: "dirty";
+ graphCommitHash: string;
+ headCommitHash: string;
+ changedFileCount: number;
+ changedFiles: string[];
+ commitsBehind: 0;
+ commitsAhead: 0;
+ lastAnalyzedAt?: string;
+ }
+ | {
+ status: "stale";
+ relation: GraphFreshnessRelation;
+ graphCommitHash: string;
+ headCommitHash: string;
+ changedFileCount: number;
+ changedFiles: string[];
+ commitsBehind: number;
+ commitsAhead: number;
+ lastAnalyzedAt?: string;
+ }
+ | {
+ status: "unknown";
+ reason: GraphFreshnessUnknownReason;
+ graphCommitHash?: string;
+ headCommitHash?: string;
+ lastAnalyzedAt?: string;
+ };
+
+export interface GraphFreshnessInput {
+ graphCommitHash?: string | null;
+ lastAnalyzedAt?: string;
+}
+
+interface ProjectGitSnapshot {
+ projectDir: string;
+ repoRoot: string;
+ headCommitHash: string;
+ dirtyFiles: string[];
+}
+
+const GIT_TIMEOUT_MS = 5_000;
+const GIT_MAX_BUFFER_BYTES = 4 * 1024 * 1024;
+const PROJECT_PATHSPEC = [
+ "--",
+ ".",
+ ":(exclude).understand-anything",
+ ":(exclude).understand-anything/**",
++ ":(exclude).ua",
++ ":(exclude).ua/**",
+] as const;
+
+class GitCommandError extends Error {
+ constructor(
+ readonly exitCode: number | null,
+ readonly timedOut: boolean,
+ ) {
+ super(timedOut ? "Git command timed out" : "Git command failed");
+ }
+}
+
+function runGit(projectDir: string, args: string[]): Promise<Buffer> {
+ return new Promise((resolve, reject) => {
+ execFile(
+ "git",
+ args,
+ {
+ cwd: projectDir,
+ encoding: null,
+ timeout: GIT_TIMEOUT_MS,
+ maxBuffer: GIT_MAX_BUFFER_BYTES,
+ windowsHide: true,
+ },
+ (error, stdout) => {
+ if (error) {
+ reject(
+ new GitCommandError(
+ typeof error.code === "number" ? error.code : null,
+ error.killed === true && error.signal !== null,
+ ),
+ );
+ return;
+ }
+
+ resolve(Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout));
+ },
+ );
+ });
+}
+
+function parseScalar(output: Buffer): string {
+ return output.toString("utf8").trim();
+}
+
+function parseNulDelimitedPaths(output: Buffer): string[] {
+ const value = output.toString("utf8");
+ if (value.length === 0) return [];
+
+ const paths = value.split("\0");
+ if (paths.at(-1) === "") paths.pop();
+ return paths.filter((path) => path.length > 0);
+}
+
+function uniqueSortedPaths(...pathGroups: string[][]): string[] {
+ return [...new Set(pathGroups.flat())].sort();
+}
+
+function optionalAnalysisTime(
+ input: GraphFreshnessInput,
+): Pick<GraphFreshnessInput, "lastAnalyzedAt"> {
+ return input.lastAnalyzedAt === undefined
+ ? {}
+ : { lastAnalyzedAt: input.lastAnalyzedAt };
+}
+
+function unknownReason(error: unknown, fallback: GraphFreshnessUnknownReason) {
+ return error instanceof GitCommandError && error.timedOut
+ ? "git-command-timeout"
+ : fallback;
+}
+
+async function createProjectGitSnapshot(
+ projectDir: string,
+): Promise<ProjectGitSnapshot> {
+ const repoRoot = parseScalar(
+ await runGit(projectDir, ["rev-parse", "--show-toplevel"]),
+ );
+ const headCommitHash = parseScalar(
+ await runGit(projectDir, ["rev-parse", "HEAD"]),
+ );
+ const [staged, unstaged, untracked] = await Promise.all([
+ runGit(projectDir, [
+ "diff",
+ "--cached",
+ "--name-only",
+ "-z",
+ "--relative",
+ ...PROJECT_PATHSPEC,
+ ]),
+ runGit(projectDir, [
+ "diff",
+ "--name-only",
+ "-z",
+ "--relative",
+ ...PROJECT_PATHSPEC,
+ ]),
+ runGit(projectDir, [
+ "ls-files",
+ "--others",
+ "--exclude-standard",
+ "-z",
+ ...PROJECT_PATHSPEC,
+ ]),
+ ]);
+
+ return {
+ projectDir,
+ repoRoot,
+ headCommitHash,
+ dirtyFiles: uniqueSortedPaths(
+ parseNulDelimitedPaths(staged),
+ parseNulDelimitedPaths(unstaged),
+ parseNulDelimitedPaths(untracked),
+ ),
+ };
+}
+
+async function isAncestor(
+ projectDir: string,
+ ancestor: string,
+ descendant: string,
+): Promise<boolean> {
+ try {
+ await runGit(projectDir, [
+ "merge-base",
+ "--is-ancestor",
+ ancestor,
+ descendant,
+ ]);
+ return true;
+ } catch (error) {
+ if (error instanceof GitCommandError && error.exitCode === 1) return false;
+ throw error;
+ }
+}
+
+async function evaluateGraphFreshness(
+ snapshot: ProjectGitSnapshot,
+ input: GraphFreshnessInput,
+ requestedGraphCommitHash: string,
+): Promise<GraphFreshnessResult> {
+ let graphCommitHash: string;
+ try {
+ graphCommitHash = parseScalar(
+ await runGit(snapshot.projectDir, [
+ "rev-parse",
+ "--verify",
+ "--end-of-options",
+ `${requestedGraphCommitHash}^{commit}`,
+ ]),
+ );
+ } catch (error) {
+ return {
+ status: "unknown",
+ reason: unknownReason(error, "graph-commit-unavailable"),
+ graphCommitHash: requestedGraphCommitHash,
+ headCommitHash: snapshot.headCommitHash,
+ ...optionalAnalysisTime(input),
+ };
+ }
+
+ let committedFiles: string[];
+ try {
+ committedFiles = parseNulDelimitedPaths(
+ await runGit(snapshot.projectDir, [
+ "diff",
+ "--name-only",
+ "-z",
+ "--relative",
+ graphCommitHash,
+ snapshot.headCommitHash,
+ ...PROJECT_PATHSPEC,
+ ]),
+ );
+ } catch (error) {
+ return {
+ status: "unknown",
+ reason: unknownReason(error, "graph-commit-unavailable"),
+ graphCommitHash,
+ headCommitHash: snapshot.headCommitHash,
+ ...optionalAnalysisTime(input),
+ };
+ }
+
+ if (committedFiles.length === 0) {
+ if (snapshot.dirtyFiles.length > 0) {
+ return {
+ status: "dirty",
+ graphCommitHash,
+ headCommitHash: snapshot.headCommitHash,
+ changedFileCount: snapshot.dirtyFiles.length,
+ changedFiles: snapshot.dirtyFiles,
+ commitsBehind: 0,
+ commitsAhead: 0,
+ ...optionalAnalysisTime(input),
+ };
+ }
+
+ return {
+ status: "fresh",
+ graphCommitHash,
+ headCommitHash: snapshot.headCommitHash,
+ changedFileCount: 0,
+ changedFiles: [],
+ commitsBehind: 0,
+ commitsAhead: 0,
+ ...optionalAnalysisTime(input),
+ };
+ }
+
+ try {
+ const [countsOutput, graphIsAncestor, headIsAncestor] = await Promise.all([
+ runGit(snapshot.projectDir, [
+ "rev-list",
+ "--left-right",
+ "--count",
+ `${graphCommitHash}...${snapshot.headCommitHash}`,
+ ...PROJECT_PATHSPEC,
+ ]),
+ isAncestor(
+ snapshot.projectDir,
+ graphCommitHash,
+ snapshot.headCommitHash,
+ ),
+ isAncestor(
+ snapshot.projectDir,
+ snapshot.headCommitHash,
+ graphCommitHash,
+ ),
+ ]);
+ const [commitsAhead, commitsBehind] = parseScalar(countsOutput)
+ .split(/\s+/)
+ .map((value) => Number.parseInt(value, 10));
+
+ if (
+ !Number.isFinite(commitsAhead) ||
+ !Number.isFinite(commitsBehind) ||
+ commitsAhead < 0 ||
+ commitsBehind < 0
+ ) {
+ throw new GitCommandError(null, false);
+ }
+
+ const relation: GraphFreshnessRelation = graphIsAncestor
+ ? "behind"
+ : headIsAncestor
+ ? "ahead"
+ : "diverged";
+ const changedFiles = uniqueSortedPaths(
+ committedFiles,
+ snapshot.dirtyFiles,
+ );
+
+ return {
+ status: "stale",
+ relation,
+ graphCommitHash,
+ headCommitHash: snapshot.headCommitHash,
+ changedFileCount: changedFiles.length,
+ changedFiles,
+ commitsBehind,
+ commitsAhead,
+ ...optionalAnalysisTime(input),
+ };
+ } catch (error) {
+ return {
+ status: "unknown",
+ reason: unknownReason(error, "graph-commit-unavailable"),
+ graphCommitHash,
+ headCommitHash: snapshot.headCommitHash,
+ ...optionalAnalysisTime(input),
+ };
+ }
+}
+
+function parseChangedFiles(output: string): string[] {
+ return output
+ .split("\n")
+ .map((line) => line.trim())
+ .filter((line) => line.length > 0);
+}
+
/**
* Get the list of files that changed between a given commit and HEAD.
* Returns an empty array if there are no changes or if git encounters an error.
diff --cc understand-anything-plugin/packages/dashboard/src/__tests__/vite-staleness.test.ts
index 80ec286e,00000000..1cb7eb09
mode 100644,000000..100644
--- a/understand-anything-plugin/packages/dashboard/src/__tests__/vite-staleness.test.ts
+++ b/understand-anything-plugin/packages/dashboard/src/__tests__/vite-staleness.test.ts
@@@ -1,263 -1,0 +1,266 @@@
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import {
+ createServer,
+ request as httpRequest,
+ type Server,
+} from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { createDashboardDataMiddleware } from "../../vite.config";
+import { isDashboardFreshnessReport } from "../freshness";
+
+interface HttpResult {
+ status: number;
+ body: unknown;
+ cacheControl: string | null;
+}
+
+let originalGraphDir: string | undefined;
+let tempProject: string;
+let baselineCommit: string;
+const servers: Server[] = [];
+
+function git(...args: string[]): string {
+ return execFileSync("git", args, {
+ cwd: tempProject,
+ encoding: "utf8",
+ }).trim();
+}
+
+function writeProjectFile(relativePath: string, contents: string): void {
+ const filePath = path.join(tempProject, ...relativePath.split("/"));
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, contents, "utf8");
+}
+
+function commitAll(message: string): string {
+ git("add", "--all");
+ git("commit", "-m", message);
+ return git("rev-parse", "HEAD");
+}
+
- function graphDirectory(): string {
- const directory = path.join(tempProject, ".understand-anything");
++function graphDirectory(dataDir = ".understand-anything"): string {
++ const directory = path.join(tempProject, dataDir);
+ fs.mkdirSync(directory, { recursive: true });
+ return directory;
+}
+
+function writeGraph(
+ fileName: "knowledge-graph.json" | "domain-graph.json",
+ commitHash: string,
++ dataDir = ".understand-anything",
+): void {
+ fs.writeFileSync(
- path.join(graphDirectory(), fileName),
++ path.join(graphDirectory(dataDir), fileName),
+ JSON.stringify({
+ project: {
+ gitCommitHash: commitHash,
+ analyzedAt: "2026-07-10T00:00:00.000Z",
+ },
+ nodes: [],
+ edges: [],
+ }),
+ "utf8",
+ );
+}
+
+async function startDashboardServer(accessToken: string): Promise<string> {
+ const middleware = createDashboardDataMiddleware(accessToken);
+ const server = createServer((req, res) => {
+ middleware(req, res, () => {
+ res.statusCode = 404;
+ res.end();
+ });
+ });
+ servers.push(server);
+
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", () => resolve());
+ });
+ const address = server.address();
+ if (!address || typeof address === "string") {
+ throw new Error("Dashboard test server did not expose a TCP port");
+ }
+ return `http://127.0.0.1:${address.port}`;
+}
+
+function requestJson(baseUrl: string, requestPath: string): Promise<HttpResult> {
+ return new Promise((resolve, reject) => {
+ const request = httpRequest(
+ `${baseUrl}${requestPath}`,
+ { agent: false },
+ (response) => {
+ const chunks: Buffer[] = [];
+ response.on("data", (chunk: Buffer) => chunks.push(chunk));
+ response.on("end", () => {
+ const text = Buffer.concat(chunks).toString("utf8");
+ resolve({
+ status: response.statusCode ?? 0,
+ body: text.length > 0 ? JSON.parse(text) : null,
+ cacheControl: response.headers["cache-control"] ?? null,
+ });
+ });
+ },
+ );
+ request.once("error", reject);
+ request.end();
+ });
+}
+
+beforeEach(() => {
+ originalGraphDir = process.env.GRAPH_DIR;
+ tempProject = fs.mkdtempSync(path.join(os.tmpdir(), "ua-dashboard-"));
+ process.env.GRAPH_DIR = tempProject;
+
+ git("init");
+ git("config", "user.email", "[email protected]");
+ git("config", "user.name", "Dashboard Tests");
+ writeProjectFile("src/index.ts", "export const value = 1;\n");
+ baselineCommit = commitAll("baseline");
+});
+
+afterEach(async () => {
+ for (const server of servers.splice(0)) {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+ if (originalGraphDir === undefined) {
+ delete process.env.GRAPH_DIR;
+ } else {
+ process.env.GRAPH_DIR = originalGraphDir;
+ }
+ fs.rmSync(tempProject, {
+ recursive: true,
+ force: true,
+ maxRetries: 5,
+ retryDelay: 100,
+ });
+});
+
+describe(
+ "dashboard graph freshness endpoint",
+ { timeout: 15_000 },
+ () => {
+ it("rejects an unauthorized request before serving freshness data", async () => {
+ writeGraph("knowledge-graph.json", baselineCommit);
+ const baseUrl = await startDashboardServer("test-token");
+
+ await expect(requestJson(baseUrl, "/staleness.json")).resolves.toEqual({
+ status: 403,
+ body: { error: "Forbidden: missing or invalid token" },
+ cacheControl: "no-store",
+ });
+ });
+
- it("serves a knowledge-only report to an authorized request", async () => {
- writeGraph("knowledge-graph.json", baselineCommit);
- const baseUrl = await startDashboardServer("test-token");
-
- const response = await requestJson(
- baseUrl,
- "/staleness.json?token=test-token",
- );
-
- expect(response.status).toBe(200);
- expect(response.cacheControl).toBe("no-store");
- expect(isDashboardFreshnessReport(response.body)).toBe(true);
- expect(response.cacheControl).toBe("no-store");
- expect(response.body).toMatchObject({
- graphs: {
- knowledge: {
- status: "fresh",
- graphCommitHash: baselineCommit,
- headCommitHash: baselineCommit,
++ it.each([".understand-anything", ".ua"])(
++ "serves a knowledge-only report from %s to an authorized request",
++ async (dataDir) => {
++ writeGraph("knowledge-graph.json", baselineCommit, dataDir);
++ const baseUrl = await startDashboardServer("test-token");
++
++ const response = await requestJson(
++ baseUrl,
++ "/staleness.json?token=test-token",
++ );
++
++ expect(response.status).toBe(200);
++ expect(response.cacheControl).toBe("no-store");
++ expect(isDashboardFreshnessReport(response.body)).toBe(true);
++ expect(response.body).toMatchObject({
++ graphs: {
++ knowledge: {
++ status: "fresh",
++ graphCommitHash: baselineCommit,
++ headCommitHash: baselineCommit,
++ },
+ },
- },
- });
- expect(
- (response.body as { graphs: Record<string, unknown> }).graphs,
- ).not.toHaveProperty("domain");
- });
++ });
++ expect(
++ (response.body as { graphs: Record<string, unknown> }).graphs,
++ ).not.toHaveProperty("domain");
++ },
++ );
+
+ it("reports knowledge and domain graph freshness independently", async () => {
+ writeProjectFile("src/index.ts", "export const value = 2;\n");
+ const headCommit = commitAll("project change");
+ writeGraph("knowledge-graph.json", headCommit);
+ writeGraph("domain-graph.json", baselineCommit);
+ const baseUrl = await startDashboardServer("test-token");
+
+ const response = await requestJson(
+ baseUrl,
+ "/staleness.json?token=test-token",
+ );
+ expect(isDashboardFreshnessReport(response.body)).toBe(true);
+ expect(response).toMatchObject({
+ status: 200,
+ body: {
+ graphs: {
+ knowledge: {
+ status: "fresh",
+ graphCommitHash: headCommit,
+ },
+ domain: {
+ status: "stale",
+ relation: "behind",
+ graphCommitHash: baselineCommit,
+ headCommitHash: headCommit,
+ commitsBehind: 1,
+ changedFiles: ["src/index.ts"],
+ },
+ },
+ },
+ });
+ });
+
+ it("returns 404 when the required knowledge graph is missing", async () => {
+ const baseUrl = await startDashboardServer("test-token");
+
+ await expect(
+ requestJson(baseUrl, "/staleness.json?token=test-token"),
+ ).resolves.toEqual({
+ status: 404,
+ body: { error: "No knowledge graph found. Run /understand first." },
+ cacheControl: "no-store",
+ });
+ });
+
+ it("returns a safe 500 response for invalid knowledge graph JSON", async () => {
+ fs.writeFileSync(
+ path.join(graphDirectory(), "knowledge-graph.json"),
+ "{not-json",
+ "utf8",
+ );
+ const baseUrl = await startDashboardServer("test-token");
+
+ await expect(
+ requestJson(baseUrl, "/staleness.json?token=test-token"),
+ ).resolves.toEqual({
+ status: 500,
+ body: { error: "Failed to read graph file" },
+ cacheControl: "no-store",
+ });
+ });
+
+ it("returns a safe 500 response for invalid optional domain graph JSON", async () => {
+ writeGraph("knowledge-graph.json", baselineCommit);
+ fs.writeFileSync(
+ path.join(graphDirectory(), "domain-graph.json"),
+ "{not-json",
+ "utf8",
+ );
+ const baseUrl = await startDashboardServer("test-token");
+
+ await expect(
+ requestJson(baseUrl, "/staleness.json?token=test-token"),
+ ).resolves.toEqual({
+ status: 500,
+ body: { error: "Failed to read graph file" },
+ cacheControl: "no-store",
+ });
+ });
+ },
+);
diff --cc understand-anything-plugin/packages/viewer/bin/viewer.mjs
index 00000000,a84eecc3..6b535a1d
mode 000000,100644..100644
--- a/understand-anything-plugin/packages/viewer/bin/viewer.mjs
+++ b/understand-anything-plugin/packages/viewer/bin/viewer.mjs
@@@ -1,0 -1,327 +1,391 @@@
+ #!/usr/bin/env node
+ /**
+ * understand-anything-viewer — serve a generated knowledge graph in the
+ * dashboard UI with nothing but Node.js. Read-only, no Claude Code, no LLM.
+ *
+ * Usage:
+ * understand-anything-viewer [project-dir] [--port <n>] [--no-open]
+ *
+ * The project directory (default: cwd) must contain a data directory —
+ * `.ua/` or legacy `.understand-anything/` — with a knowledge-graph.json
+ * produced by /understand.
+ *
+ * Security model mirrors the dashboard dev server (vite.config.ts):
+ * - binds to 127.0.0.1 only
+ * - every data endpoint requires the one-time ?token= printed at startup
+ * - graph JSON is served with node filePaths relativised to the project
+ * - /file-content.json only serves files listed in the graph, capped at
+ * 1 MB, never binary
+ */
+ import { createServer } from "node:http";
+ import { spawn } from "node:child_process";
+ import crypto from "node:crypto";
+ import fs from "node:fs";
+ import path from "node:path";
+ import { fileURLToPath } from "node:url";
++import { getGraphFreshnessBatch } from "./dist/staleness.js";
+
+ const DIST_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "dist");
+ const MAX_SOURCE_FILE_BYTES = 1024 * 1024;
+ // Legacy directory first — projects analyzed before the `.ua` rename keep
+ // their existing `.understand-anything/` data.
+ const UA_DIR_CANDIDATES = [".understand-anything", ".ua"];
+
+ // ── CLI args ───────────────────────────────────────────────────────────────
+
+ const args = process.argv.slice(2);
+ let projectRoot = process.cwd();
+ let port = 5173;
+ let portExplicit = false;
+ let openBrowser = true;
+
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i];
+ if (a === "--port") {
+ port = Number(args[++i]);
+ portExplicit = true;
+ // 0 asks the OS for any free port.
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
+ console.error("Error: --port must be an integer between 0 and 65535");
+ process.exit(1);
+ }
+ } else if (a === "--no-open") {
+ openBrowser = false;
+ } else if (a === "--help" || a === "-h") {
+ console.log("Usage: understand-anything-viewer [project-dir] [--port <n>] [--no-open]");
+ process.exit(0);
+ } else if (!a.startsWith("-")) {
+ projectRoot = path.resolve(a);
+ } else {
+ console.error(`Error: unknown option ${a}`);
+ process.exit(1);
+ }
+ }
+
+ if (!fs.existsSync(DIST_DIR)) {
+ console.error(
+ "Error: embedded dashboard build not found. This tarball was packed " +
+ "without running the build — run `pnpm --filter understand-anything-viewer build` first.",
+ );
+ process.exit(1);
+ }
+
+ const graphDir = UA_DIR_CANDIDATES
+ .map((d) => path.join(projectRoot, d))
+ .find((d) => fs.existsSync(path.join(d, "knowledge-graph.json")));
+
+ if (!graphDir) {
+ console.error(
+ `Error: no knowledge graph found under ${projectRoot}\n` +
+ "Expected .ua/knowledge-graph.json (or legacy .understand-anything/). " +
+ "Generate one with /understand first, or pass the project directory as an argument.",
+ );
+ process.exit(1);
+ }
+
+ const ACCESS_TOKEN = process.env.UNDERSTAND_ACCESS_TOKEN || crypto.randomBytes(16).toString("hex");
+
+ // ── Helpers (mirroring vite.config.ts) ────────────────────────────────────
+
+ function sendJson(res, statusCode, payload) {
+ res.statusCode = statusCode;
+ res.setHeader("Content-Type", "application/json");
+ res.end(JSON.stringify(payload));
+ }
+
+ function normalizeGraphPath(filePath) {
+ const rawPath = path.isAbsolute(filePath)
+ ? filePath.startsWith(projectRoot)
+ ? path.relative(projectRoot, filePath)
+ : null
+ : filePath;
+ if (rawPath === null) return null;
+ const normalized = path.normalize(rawPath);
+ if (
+ !normalized ||
+ normalized === "." ||
+ normalized.includes("\0") ||
+ normalized === ".." ||
+ normalized.startsWith(`..${path.sep}`) ||
+ path.isAbsolute(normalized)
+ ) {
+ return null;
+ }
+ return normalized.split(path.sep).join("/");
+ }
+
+ function graphFilePathSet() {
+ const allowed = new Set();
+ try {
+ const raw = JSON.parse(fs.readFileSync(path.join(graphDir, "knowledge-graph.json"), "utf-8"));
+ for (const node of raw.nodes ?? []) {
+ if (typeof node.filePath !== "string") continue;
+ const normalized = normalizeGraphPath(node.filePath);
+ if (normalized) allowed.add(normalized);
+ }
+ } catch {
+ return allowed;
+ }
+ return allowed;
+ }
+
+ function detectLanguage(filePath) {
+ const ext = path.extname(filePath).slice(1).toLowerCase();
+ const byExt = {
+ bash: "bash", c: "c", cc: "cpp", cpp: "cpp", cs: "csharp", css: "css",
+ go: "go", h: "c", hpp: "cpp", html: "markup", java: "java",
+ js: "javascript", jsx: "jsx", json: "json", md: "markdown",
+ mjs: "javascript", py: "python", rb: "ruby", rs: "rust", sh: "bash",
+ ts: "typescript", tsx: "tsx", txt: "text", yaml: "yaml", yml: "yaml",
+ };
+ return byExt[ext] ?? "text";
+ }
+
+ function readSourceFile(url) {
+ const reject = (message, statusCode = 400) => ({ statusCode, payload: { error: message } });
+ const requestedPath = url.searchParams.get("path") ?? "";
+ if (!requestedPath) return reject("Missing path");
+ if (requestedPath.includes("\0")) return reject("Invalid path");
+ if (path.isAbsolute(requestedPath)) return reject("Absolute paths are not allowed");
+
+ const normalizedPath = path.normalize(requestedPath);
+ if (
+ normalizedPath === "." ||
+ normalizedPath.startsWith(`..${path.sep}`) ||
+ normalizedPath === ".." ||
+ path.isAbsolute(normalizedPath)
+ ) {
+ return reject("Path must stay inside the project");
+ }
+
+ const absoluteFile = path.resolve(projectRoot, normalizedPath);
+ const relativeToRoot = path.relative(projectRoot, absoluteFile);
+ if (
+ !relativeToRoot ||
+ relativeToRoot.startsWith(`..${path.sep}`) ||
+ relativeToRoot === ".." ||
+ path.isAbsolute(relativeToRoot)
+ ) {
+ return reject("Path must stay inside the project");
+ }
+ const safeRelativePath = relativeToRoot.split(path.sep).join("/");
+ if (!graphFilePathSet().has(safeRelativePath)) {
+ return reject("File is not in the knowledge graph", 404);
+ }
+
+ let stat;
+ try {
+ stat = fs.statSync(absoluteFile);
+ } catch {
+ return reject("File not found", 404);
+ }
+ if (!stat.isFile()) return reject("Path is not a file");
+ if (stat.size > MAX_SOURCE_FILE_BYTES) return reject("File is too large to preview", 413);
+
+ const buffer = fs.readFileSync(absoluteFile);
+ if (buffer.includes(0)) return reject("Binary files cannot be previewed", 415);
+
+ const content = buffer.toString("utf8");
+ return {
+ statusCode: 200,
+ payload: {
+ path: safeRelativePath,
+ language: detectLanguage(relativeToRoot),
+ content,
+ sizeBytes: buffer.byteLength,
+ lineCount: content.length === 0 ? 0 : content.split(/\r\n|\n|\r/).length,
+ },
+ };
+ }
+
+ function serveGraphJson(res, fileName) {
+ const candidate = path.join(graphDir, fileName);
+ if (fs.existsSync(candidate)) {
+ try {
+ const raw = JSON.parse(fs.readFileSync(candidate, "utf-8"));
+ // Sanitise absolute node filePaths so the developer's directory
+ // layout is never sent to the browser.
+ if (Array.isArray(raw.nodes)) {
+ raw.nodes = raw.nodes.map((node) => {
+ if (typeof node.filePath !== "string") return node;
+ const abs = node.filePath;
+ const rel = abs.startsWith(projectRoot)
+ ? abs.slice(projectRoot.length).replace(/^[\\/]/, "")
+ : path.isAbsolute(abs)
+ ? path.basename(abs)
+ : abs;
+ return { ...node, filePath: rel };
+ });
+ }
+ sendJson(res, 200, raw);
+ } catch {
+ sendJson(res, 500, { error: "Failed to read graph file" });
+ }
+ return;
+ }
+ if (fileName === "knowledge-graph.json") {
+ sendJson(res, 404, { error: "No knowledge graph found. Run /understand first." });
+ } else {
+ res.statusCode = 404;
+ res.end();
+ }
+ }
+
++function readGraphMetadata(fileName) {
++ const graph = JSON.parse(
++ fs.readFileSync(path.join(graphDir, fileName), "utf-8"),
++ );
++ return {
++ graphCommitHash:
++ typeof graph.project?.gitCommitHash === "string"
++ ? graph.project.gitCommitHash
++ : undefined,
++ lastAnalyzedAt:
++ typeof graph.project?.analyzedAt === "string"
++ ? graph.project.analyzedAt
++ : undefined,
++ };
++}
++
++async function readGraphFreshness() {
++ const knowledgeGraph = path.join(graphDir, "knowledge-graph.json");
++ if (!fs.existsSync(knowledgeGraph)) {
++ return {
++ statusCode: 404,
++ payload: { error: "No knowledge graph found. Run /understand first." },
++ };
++ }
++
++ const domainGraph = path.join(graphDir, "domain-graph.json");
++ let inputs;
++ try {
++ inputs = {
++ knowledge: readGraphMetadata("knowledge-graph.json"),
++ ...(fs.existsSync(domainGraph)
++ ? { domain: readGraphMetadata("domain-graph.json") }
++ : {}),
++ };
++ } catch {
++ return {
++ statusCode: 500,
++ payload: { error: "Failed to read graph file" },
++ };
++ }
++
++ return {
++ statusCode: 200,
++ payload: {
++ graphs: await getGraphFreshnessBatch(projectRoot, inputs),
++ },
++ };
++}
++
+ const CONTENT_TYPES = {
+ ".css": "text/css", ".html": "text/html", ".ico": "image/x-icon",
+ ".js": "text/javascript", ".json": "application/json", ".map": "application/json",
+ ".png": "image/png", ".svg": "image/svg+xml", ".txt": "text/plain",
+ ".wasm": "application/wasm", ".woff": "font/woff", ".woff2": "font/woff2",
+ };
+
+ function serveStatic(res, pathname) {
+ const relative = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
+ const absolute = path.resolve(DIST_DIR, relative);
+ if (absolute !== DIST_DIR && !absolute.startsWith(DIST_DIR + path.sep)) {
+ res.statusCode = 403;
+ res.end("Forbidden");
+ return;
+ }
+ if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) {
+ res.statusCode = 404;
+ res.end("Not found");
+ return;
+ }
+ res.setHeader("Content-Type", CONTENT_TYPES[path.extname(absolute).toLowerCase()] ?? "application/octet-stream");
+ res.end(fs.readFileSync(absolute));
+ }
+
+ // ── Server ────────────────────────────────────────────────────────────────
+
+ const PROTECTED = new Set([
+ "/knowledge-graph.json",
+ "/domain-graph.json",
+ "/diff-overlay.json",
+ "/meta.json",
+ "/config.json",
+ "/file-content.json",
++ "/staleness.json",
+ ]);
+
+ const server = createServer((req, res) => {
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
+ const pathname = url.pathname;
+
++ if (pathname === "/staleness.json") {
++ res.setHeader("Cache-Control", "no-store");
++ }
++
+ if (!PROTECTED.has(pathname)) {
+ serveStatic(res, pathname);
+ return;
+ }
+
+ if (url.searchParams.get("token") !== ACCESS_TOKEN) {
+ sendJson(res, 403, { error: "Forbidden: missing or invalid token" });
+ return;
+ }
+
+ if (pathname === "/file-content.json") {
+ const result = readSourceFile(url);
+ sendJson(res, result.statusCode, result.payload);
+ return;
+ }
+
++ if (pathname === "/staleness.json") {
++ void readGraphFreshness()
++ .then((result) => sendJson(res, result.statusCode, result.payload))
++ .catch(() => {
++ sendJson(res, 500, { error: "Failed to read graph freshness" });
++ });
++ return;
++ }
++
+ if (pathname === "/config.json") {
+ const candidate = path.join(graphDir, "config.json");
+ if (fs.existsSync(candidate)) {
+ try {
+ sendJson(res, 200, JSON.parse(fs.readFileSync(candidate, "utf-8")));
+ } catch {
+ sendJson(res, 500, { error: "Failed to read config file" });
+ }
+ return;
+ }
+ sendJson(res, 200, { autoUpdate: false, outputLanguage: "en" });
+ return;
+ }
+
+ serveGraphJson(res, pathname.slice(1));
+ });
+
+ function listen(attemptPort, attemptsLeft) {
+ server.once("error", (err) => {
+ if (err.code === "EADDRINUSE" && !portExplicit && attemptsLeft > 0) {
+ listen(attemptPort + 1, attemptsLeft - 1);
+ } else {
+ console.error(`Error: could not bind 127.0.0.1:${attemptPort} — ${err.message}`);
+ process.exit(1);
+ }
+ });
+ server.listen(attemptPort, "127.0.0.1", () => {
+ const address = server.address();
+ const boundPort = typeof address === "object" && address ? address.port : attemptPort;
+ const dashboardUrl = `http://127.0.0.1:${boundPort}/?token=${ACCESS_TOKEN}`;
+ console.log(`\n Serving graph from ${graphDir}`);
+ console.log(` 🔑 Dashboard URL: ${dashboardUrl}\n`);
+ if (openBrowser) {
+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
+ spawn(opener, [dashboardUrl], { shell: process.platform === "win32", stdio: "ignore", detached: true }).unref();
+ }
+ });
+ }
+
+ listen(port, 10);
diff --cc understand-anything-plugin/packages/viewer/build.mjs
index 00000000,3130a7e2..f2548b5c
mode 000000,100644..100644
--- a/understand-anything-plugin/packages/viewer/build.mjs
+++ b/understand-anything-plugin/packages/viewer/build.mjs
@@@ -1,0 -1,29 +1,34 @@@
+ #!/usr/bin/env node
+ /**
+ * Build the standalone viewer: build the dashboard (and its core dependency),
+ * then embed the compiled frontend under this package's dist/ so the packed
+ * tarball is fully self-contained (no runtime dependencies).
+ *
+ * Run from anywhere inside the monorepo:
+ * pnpm --filter understand-anything-viewer build
+ */
+ import { execSync } from "node:child_process";
-import { cpSync, rmSync, existsSync } from "node:fs";
++import { cpSync, rmSync, existsSync, mkdirSync } from "node:fs";
+ import { dirname, join } from "node:path";
+ import { fileURLToPath } from "node:url";
+
+ const here = dirname(fileURLToPath(import.meta.url));
+ const dashboardDist = join(here, "..", "dashboard", "dist");
++const coreStaleness = join(here, "..", "core", "dist", "staleness.js");
+ const viewerDist = join(here, "dist");
++const viewerServerDist = join(here, "bin", "dist");
+
+ execSync("pnpm --filter @understand-anything/core build", { stdio: "inherit", cwd: here });
+ execSync("pnpm --filter @understand-anything/dashboard build", { stdio: "inherit", cwd: here });
+
+ if (!existsSync(dashboardDist)) {
+ console.error(`Error: dashboard build output not found at ${dashboardDist}`);
+ process.exit(1);
+ }
+
+ rmSync(viewerDist, { recursive: true, force: true });
+ cpSync(dashboardDist, viewerDist, { recursive: true });
++rmSync(viewerServerDist, { recursive: true, force: true });
++mkdirSync(viewerServerDist, { recursive: true });
++cpSync(coreStaleness, join(viewerServerDist, "staleness.js"));
+ console.log(`Embedded dashboard build into ${viewerDist}`);
diff --cc understand-anything-plugin/packages/viewer/package.json
index 00000000,320bc612..a16a5b3c
mode 000000,100644..100644
--- a/understand-anything-plugin/packages/viewer/package.json
+++ b/understand-anything-plugin/packages/viewer/package.json
@@@ -1,0 -1,27 +1,27 @@@
+ {
+ "name": "understand-anything-viewer",
- "version": "2.9.3",
++ "version": "2.9.4",
+ "description": "Standalone read-only viewer for Understand-Anything knowledge graphs — no Claude Code or LLM required.",
+ "type": "module",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/Egonex-AI/Understand-Anything.git",
+ "directory": "understand-anything-plugin/packages/viewer"
+ },
+ "bin": {
+ "understand-anything-viewer": "bin/viewer.mjs"
+ },
+ "files": [
+ "bin",
+ "dist",
+ "README.md"
+ ],
+ "engines": {
+ "node": ">=18"
+ },
+ "scripts": {
+ "build": "node build.mjs",
+ "pack:release": "node build.mjs && npm pack"
+ }
+ }
diff --cc understand-anything-plugin/skills/understand-chat/SKILL.md
index 34e80022,5ae14bf0..e12e9176
--- a/understand-anything-plugin/skills/understand-chat/SKILL.md
+++ b/understand-anything-plugin/skills/understand-chat/SKILL.md
@@@ -31,26 -31,11 +31,26 @@@ The knowledge graph JSON has this struc
## Instructions
- 1. Check that `.understand-anything/knowledge-graph.json` exists in the current project root. If not, tell the user to run `/understand` first.
+ 1. **Resolve the data directory `$UA_DIR`.** Run `UA_DIR=$([ -d .understand-anything ] && echo .understand-anything || echo .ua)` — this is the legacy `.understand-anything/` when it already exists, otherwise the new `.ua/`. Check that `$UA_DIR/knowledge-graph.json` exists in the current project root. If not, tell the user to run `/understand` first.
-2. **Read project metadata only** — use Grep or Read with a line limit to extract just the `"project"` section from the top of the file for context (name, description, languages, frameworks).
+2. **Check graph freshness before using graph-derived context**:
+ - Read `project.gitCommitHash` from the graph metadata as `GRAPH_COMMIT_RAW`. Resolve it as a commit before using it in any Git diff, then compare it with `git rev-parse HEAD` and inspect project-scoped committed and working-tree changes from the project root:
+ ```bash
+ GRAPH_COMMIT=$(git rev-parse --verify --end-of-options "${GRAPH_COMMIT_RAW}^{commit}" 2>/dev/null)
+ git rev-parse HEAD
+ git diff --name-only "$GRAPH_COMMIT" HEAD -- .
+ git diff --cached --name-only -- .
+ git diff --name-only -- .
+ git ls-files --others --exclude-standard -- .
+ ```
+ - The `-- .` pathspec is required: commits that only touch a sibling monorepo project must not make this graph stale. A hash mismatch alone is not stale when the project diff is empty.
- - Ignore `.understand-anything/` paths in every command's output because they are generated graph artifacts, not project source drift.
++ - Ignore the selected data directory (`.ua/` or legacy `.understand-anything/`) in every command's output because it contains generated graph artifacts, not project source drift.
+ - If the committed diff or any working-tree command reports project files, warn before answering that graph-derived context may omit those changes. Suggest: Run `/understand` to refresh the graph.
+ - Run the commit diff only when `GRAPH_COMMIT_RAW` resolves successfully. If the graph commit or Git metadata is missing, invalid, or unavailable, give a brief best-effort warning and continue instead of blocking.
-3. **Search for relevant nodes** — use Grep to search the knowledge graph file for the user's query keywords: "$ARGUMENTS"
+3. **Read project metadata only** — use Grep or Read with a line limit to extract just the `"project"` section from the top of the file for context (name, description, languages, frameworks).
+
+4. **Search for relevant nodes** — use Grep to search the knowledge graph file for the user's query keywords: "$ARGUMENTS"
- Search `"name"` fields: `grep -i "query_keyword"` in the graph file
- Search `"summary"` fields for semantic matches
- Search `"tags"` arrays for topic matches
diff --cc understand-anything-plugin/skills/understand-diff/SKILL.md
index f0cdf5d7,62d4fb12..13880f31
--- a/understand-anything-plugin/skills/understand-diff/SKILL.md
+++ b/understand-anything-plugin/skills/understand-diff/SKILL.md
@@@ -37,20 -37,7 +37,20 @@@ The knowledge graph JSON has this struc
- If on a feature branch: `git diff main...HEAD --name-only` (or the base branch)
- If the user specifies a PR number: get the diff from that PR
-3. **Read project metadata only** — use Grep or Read with a line limit to extract just the `"project"` section for context.
+3. **Read project metadata and check graph freshness** — use Grep or Read with a line limit to extract the `"project"` section, including `gitCommitHash` as `GRAPH_COMMIT_RAW`, then:
+ - Resolve it as a commit before using it in any Git diff. From the project root, compare the resolved commit with `git rev-parse HEAD` and inspect project-scoped committed and working-tree changes:
+ ```bash
+ GRAPH_COMMIT=$(git rev-parse --verify --end-of-options "${GRAPH_COMMIT_RAW}^{commit}" 2>/dev/null)
+ git rev-parse HEAD
+ git diff --name-only "$GRAPH_COMMIT" HEAD -- .
+ git diff --cached --name-only -- .
+ git diff --name-only -- .
+ git ls-files --others --exclude-standard -- .
+ ```
+ - The `-- .` pathspec is required: commits that only touch a sibling monorepo project must not make this graph stale. A hash mismatch alone is not stale when the project diff is empty.
- - Ignore `.understand-anything/` paths in every command's output because they are generated graph artifacts, not project source drift.
++ - Ignore the selected data directory (`.ua/` or legacy `.understand-anything/`) in every command's output because it contains generated graph artifacts, not project source drift.
+ - If the committed diff or any working-tree command reports project files, warn before impact analysis that the graph may omit those changes. Suggest: Run `/understand` to refresh the graph.
+ - Run the commit diff only when `GRAPH_COMMIT_RAW` resolves successfully. If the graph commit or Git metadata is missing, invalid, or unavailable, give a brief best-effort warning and continue instead of blocking.
4. **Find nodes for changed files** — for each changed file path, use Grep to search the knowledge graph for:
- Nodes with matching `"filePath"` values (e.g., `grep "changed/file/path"`)
diff --cc understand-anything-plugin/skills/understand-domain/SKILL.md
index 3296e778,702ecf18..0c42eeea
--- a/understand-anything-plugin/skills/understand-domain/SKILL.md
+++ b/understand-anything-plugin/skills/understand-domain/SKILL.md
@@@ -88,23 -94,9 +94,23 @@@ Use `$PLUGIN_ROOT` for every reference
### Phase 1: Detect Existing Graph
- 1. Check if `$PROJECT_ROOT/.understand-anything/knowledge-graph.json` exists
+ 1. Check if `$UA_DIR/knowledge-graph.json` exists
-2. If it exists AND `--full` was NOT passed → proceed to Phase 3 (derive from graph)
-3. Otherwise → proceed to Phase 2 (lightweight scan)
+2. If it exists AND `--full` was NOT passed, check freshness before deriving from it:
+ - Read `project.gitCommitHash` from the graph metadata as `GRAPH_COMMIT_RAW`. Change to `$PROJECT_ROOT`, resolve it as a commit before using it in any Git diff, compare the resolved commit with `git rev-parse HEAD`, and inspect project-scoped committed and working-tree changes:
+ ```bash
+ GRAPH_COMMIT=$(git rev-parse --verify --end-of-options "${GRAPH_COMMIT_RAW}^{commit}" 2>/dev/null)
+ git rev-parse HEAD
+ git diff --name-only "$GRAPH_COMMIT" HEAD -- .
+ git diff --cached --name-only -- .
+ git diff --name-only -- .
+ git ls-files --others --exclude-standard -- .
+ ```
+ - The `-- .` pathspec is required: commits that only touch a sibling monorepo project must not make this graph stale. A hash mismatch alone is not stale when the project diff is empty.
- - Ignore `.understand-anything/` paths in every command's output because they are generated graph artifacts, not project source drift.
++ - Ignore the selected data directory (`.ua/` or legacy `.understand-anything/`) in every command's output because it contains generated graph artifacts, not project source drift.
+ - If the committed diff or any working-tree command reports project files, warn that domain extraction may omit those changes. Suggest: Run `/understand` to refresh the knowledge graph.
+ - Run the commit diff only when `GRAPH_COMMIT_RAW` resolves successfully. If the graph commit or Git metadata is missing, invalid, or unavailable, give a brief best-effort warning and continue instead of blocking.
+3. After that preflight, proceed to Phase 3 (derive from graph).
+4. Otherwise, proceed to Phase 2 (lightweight scan). When `--full` is used, skip this preflight because the command performs a fresh scan instead of consuming the existing graph.
### Phase 2: Lightweight Scan (Path 1)
diff --cc understand-anything-plugin/skills/understand-explain/SKILL.md
index a04101fe,cf403485..540481fa
--- a/understand-anything-plugin/skills/understand-explain/SKILL.md
+++ b/understand-anything-plugin/skills/understand-explain/SKILL.md
@@@ -31,24 -31,9 +31,24 @@@ The knowledge graph JSON has this struc
## Instructions
- 1. Check that `.understand-anything/knowledge-graph.json` exists. If not, tell the user to run `/understand` first.
+ 1. **Resolve the data directory `$UA_DIR`.** Run `UA_DIR=$([ -d .understand-anything ] && echo .understand-anything || echo .ua)` — this is the legacy `.understand-anything/` when it already exists, otherwise the new `.ua/`. Check that `$UA_DIR/knowledge-graph.json` exists. If not, tell the user to run `/understand` first.
-2. **Find the target node** — use Grep to search the knowledge graph for the component: "$ARGUMENTS"
+2. **Check graph freshness before using graph-derived context**:
+ - Read `project.gitCommitHash` from the graph metadata as `GRAPH_COMMIT_RAW`. Resolve it as a commit before using it in any Git diff, then compare it with `git rev-parse HEAD` and inspect project-scoped committed and working-tree changes from the project root:
+ ```bash
+ GRAPH_COMMIT=$(git rev-parse --verify --end-of-options "${GRAPH_COMMIT_RAW}^{commit}" 2>/dev/null)
+ git rev-parse HEAD
+ git diff --name-only "$GRAPH_COMMIT" HEAD -- .
+ git diff --cached --name-only -- .
+ git diff --name-only -- .
+ git ls-files --others --exclude-standard -- .
+ ```
+ - The `-- .` pathspec is required: commits that only touch a sibling monorepo project must not make this graph stale. A hash mismatch alone is not stale when the project diff is empty.
- - Ignore `.understand-anything/` paths in every command's output because they are generated graph artifacts, not project source drift.
++ - Ignore the selected data directory (`.ua/` or legacy `.understand-anything/`) in every command's output because it contains generated graph artifacts, not project source drift.
+ - If the committed diff or any working-tree command reports project files, warn before explaining that graph-derived context may omit those changes. Suggest: Run `/understand` to refresh the graph.
+ - Run the commit diff only when `GRAPH_COMMIT_RAW` resolves successfully. If the graph commit or Git metadata is missing, invalid, or unavailable, give a brief best-effort warning and continue instead of blocking.
+
+3. **Find the target node** — use Grep to search the knowledge graph for the component: "$ARGUMENTS"
- For file paths (e.g., `src/auth/login.ts`): search for `"filePath"` matches
- For function notation (e.g., `src/auth/login.ts:verifyToken`): search for the function name in `"name"` fields filtered by the file path
- Note the exact node `id`, `type`, `summary`, `tags`, and `complexity`
diff --cc understand-anything-plugin/skills/understand-onboard/SKILL.md
index a84ea256,6c13823b..b2c8a2f8
--- a/understand-anything-plugin/skills/understand-onboard/SKILL.md
+++ b/understand-anything-plugin/skills/understand-onboard/SKILL.md
@@@ -30,34 -30,19 +30,34 @@@ The knowledge graph JSON has this struc
## Instructions
- 1. Check that `.understand-anything/knowledge-graph.json` exists. If not, tell the user to run `/understand` first.
+ 1. **Resolve the data directory `$UA_DIR`.** Run `UA_DIR=$([ -d .understand-anything ] && echo .understand-anything || echo .ua)` — this is the legacy `.understand-anything/` when it already exists, otherwise the new `.ua/`. Check that `$UA_DIR/knowledge-graph.json` exists. If not, tell the user to run `/understand` first.
-2. **Read project metadata** — use Grep or Read with a line limit to extract the `"project"` section (name, description, languages, frameworks).
+2. **Check graph freshness before using graph-derived context**:
+ - Read `project.gitCommitHash` from the graph metadata as `GRAPH_COMMIT_RAW`. Resolve it as a commit before using it in any Git diff, then compare it with `git rev-parse HEAD` and inspect project-scoped committed and working-tree changes from the project root:
+ ```bash
+ GRAPH_COMMIT=$(git rev-parse --verify --end-of-options "${GRAPH_COMMIT_RAW}^{commit}" 2>/dev/null)
+ git rev-parse HEAD
+ git diff --name-only "$GRAPH_COMMIT" HEAD -- .
+ git diff --cached --name-only -- .
+ git diff --name-only -- .
+ git ls-files --others --exclude-standard -- .
+ ```
+ - The `-- .` pathspec is required: commits that only touch a sibling monorepo project must not make this graph stale. A hash mismatch alone is not stale when the project diff is empty.
- - Ignore `.understand-anything/` paths in every command's output because they are generated graph artifacts, not project source drift.
++ - Ignore the selected data directory (`.ua/` or legacy `.understand-anything/`) in every command's output because it contains generated graph artifacts, not project source drift.
+ - If the committed diff or any working-tree command reports project files, warn before generating the guide that onboarding content may omit those changes. Suggest: Run `/understand` to refresh the graph.
+ - Run the commit diff only when `GRAPH_COMMIT_RAW` resolves successfully. If the graph commit or Git metadata is missing, invalid, or unavailable, give a brief best-effort warning and continue instead of blocking.
-3. **Read layers** — Grep for `"layers"` to get the full layers array. These define the architecture and will structure the guide.
+3. **Read project metadata** — use Grep or Read with a line limit to extract the `"project"` section (name, description, languages, frameworks).
-4. **Read the tour** — Grep for `"tour"` to get the guided walkthrough steps. These provide the recommended learning path.
+4. **Read layers** — Grep for `"layers"` to get the full layers array. These define the architecture and will structure the guide.
-5. **Read file-level structural nodes only** — use Grep to find nodes with file-level types (`file`, `config`, `document`, `service`, `pipeline`, `table`, `schema`, `resource`, `endpoint`) in the knowledge graph. Skip function-level and class-level nodes to keep the guide high-level. Extract each node's `name`, `filePath`, `summary`, and `complexity`.
+5. **Read the tour** — Grep for `"tour"` to get the guided walkthrough steps. These provide the recommended learning path.
-6. **Identify complexity hotspots** — from the file-level nodes, find those with the highest `complexity` values. These are areas new developers should approach carefully.
+6. **Read file-level structural nodes only** — use Grep to find nodes with file-level types (`file`, `config`, `document`, `service`, `pipeline`, `table`, `schema`, `resource`, `endpoint`) in the knowledge graph. Skip function-level and class-level nodes to keep the guide high-level. Extract each node's `name`, `filePath`, `summary`, and `complexity`.
-7. **Generate the onboarding guide** with these sections:
+7. **Identify complexity hotspots** — from the file-level nodes, find those with the highest `complexity` values. These are areas new developers should approach carefully.
+
+8. **Generate the onboarding guide** with these sections:
- **Project Overview**: name, languages, frameworks, description (from project metadata)
- **Architecture Layers**: each layer's name, description, and key files (from layers + file nodes)
- **Key Concepts**: important patterns and design decisions (from node summaries and tags)