Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

feat(cli): bound `ix smells` with --limit, count/shown and a non-source orphan filter (CL-20C) (#828)

Ian Hockb6319fccf401
diff --git a/docs/llm-format.md b/docs/llm-format.md
index 316ff939..7a18b191 100644
--- a/docs/llm-format.md
+++ b/docs/llm-format.md
@@ -336,11 +336,16 @@ region id=ingestion-parsers label="Ingestion / Parsers" kind=subsystem level=2 f
`ix smells`:
```
-smells rev=42 count=2 version=smell_v1
+smells rev=42 count=2 shown=2 version=smell_v1
smell kind=has_smell.god_module file=Region.scala confidence=0.91 chunks=42 fan_in=18 fan_out=9
smell kind=has_smell.orphan_file file=tmp.py confidence=0.8 connections=0
```
+`count` is the number of candidates after non-source orphan files (docs,
+templates, data/config) are dropped; `filtered_non_source=<k>` appears when any
+were. Output stops at `--limit` (default 50, highest confidence first); when it
+cuts, a `diagnostic code=results_truncated` record follows the header.
+
`ix impact <leaf>`:
```
diff --git a/ix-cli/src/cli/__tests__/common-option-validation.test.ts b/ix-cli/src/cli/__tests__/common-option-validation.test.ts
index 291074a7..fc547351 100644
--- a/ix-cli/src/cli/__tests__/common-option-validation.test.ts
+++ b/ix-cli/src/cli/__tests__/common-option-validation.test.ts
@@ -86,6 +86,7 @@ describe("common CLI option validation", () => {
[["inventory", "--kind", "file", "--limit", "1e3"], "--limit"],
[["rank", "--by", "dependents", "--kind", "class", "--top", "10abc"], "--top"],
[["patches", "--limit", "-1"], "--limit"],
+ [["smells", "--limit", "abc"], "--limit"],
[["search", "term", "--as-of", "abc"], "--as-of"],
[["search", "term", "--as-of", "1e3"], "--as-of"],
[["map", "--level", "nope"], "--level"],
diff --git a/ix-cli/src/cli/__tests__/llm-renderers.test.ts b/ix-cli/src/cli/__tests__/llm-renderers.test.ts
index 348cce72..4562399c 100644
--- a/ix-cli/src/cli/__tests__/llm-renderers.test.ts
+++ b/ix-cli/src/cli/__tests__/llm-renderers.test.ts
@@ -173,7 +173,7 @@ describe("renderSmellsLlm", () => {
{ file_id: "b", file: "big.ts", smell: "has_smell.god_module", confidence: 0.9, signals: { chunks: 0, fan_in: 23, fan_out: 2 }, inference_version: "smell_v1" },
],
});
- expect(lines[0]).toBe("smells rev=9 count=2 version=smell_v1");
+ expect(lines[0]).toBe("smells rev=9 count=2 shown=2 version=smell_v1");
expect(lines[1]).toBe("smell kind=has_smell.god_module file=big.ts confidence=0.9 fan_in=23 fan_out=2");
expect(lines[1]).not.toContain("chunks=");
expect(lines[2]).toBe("smell kind=has_smell.orphan_file file=low.py confidence=0.5 connections=0");
diff --git a/ix-cli/src/cli/__tests__/smells-limit.test.ts b/ix-cli/src/cli/__tests__/smells-limit.test.ts
new file mode 100644
index 00000000..3bda15e4
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/smells-limit.test.ts
@@ -0,0 +1,270 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { Command } from "commander";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const fakeClient = {
+ runSmells: vi.fn(),
+ listSmells: vi.fn(),
+};
+
+vi.mock("../../client/factory.js", () => ({ createClient: () => fakeClient }));
+vi.mock("../resolve.js", () => ({ resolveReadSystemId: async () => undefined }));
+vi.mock("../bootstrap.js", () => ({ resolveWorkspaceId: () => "ws-test" }));
+
+import {
+ isNonSourceOrphan,
+ registerSmellsCommand,
+ selectSmells,
+ type SmellCandidate,
+ type SmellReport,
+} from "../commands/smells.js";
+
+function cand(file: string, confidence: number, smell = "has_smell.orphan_file"): SmellCandidate {
+ return { file_id: file, file, smell, confidence, signals: { connectivity: 0 }, inference_version: "smell_v1" };
+}
+
+function report(candidates: SmellCandidate[]): SmellReport {
+ return { rev: 7, run_at: "2026-10-11T00:00:00Z", count: candidates.length, candidates };
+}
+
+/** n source candidates with distinct confidences, deliberately not in order. */
+function synthetic(n: number): SmellCandidate[] {
+ return Array.from({ length: n }, (_, i) => cand(`src/f${i}.ts`, ((i * 37) % n) / n));
+}
+
+describe("isNonSourceOrphan shell dotfiles", () => {
+ it("keeps .bashrc and .zshrc", () => {
+ expect(isNonSourceOrphan(cand(".bashrc", 0.5))).toBe(false);
+ expect(isNonSourceOrphan(cand("home/.zshrc", 0.5))).toBe(false);
+ // core-ingestion's languageFromPath parses .zshenv as Bash too.
+ expect(isNonSourceOrphan(cand("home/.zshenv", 0.5))).toBe(false);
+ expect(isNonSourceOrphan(cand(".gitignore", 0.5))).toBe(true);
+ });
+});
+
+describe("selectSmells", () => {
+ it("keeps the top 50 by confidence out of 120", () => {
+ const all = synthetic(120);
+ const { slice } = selectSmells(report(all), 50);
+ expect(slice.total).toBe(120);
+ expect(slice.shown).toBe(50);
+ expect(slice.truncated).toBe(true);
+ const max = Math.max(...all.map(c => c.confidence));
+ expect(slice.rows[0].confidence).toBe(max);
+ for (let i = 1; i < slice.rows.length; i++) {
+ expect(slice.rows[i - 1].confidence).toBeGreaterThanOrEqual(slice.rows[i].confidence);
+ }
+ });
+
+ it("is stable among ties", () => {
+ const tied = [cand("src/a.ts", 0.5), cand("src/b.ts", 0.9), cand("src/c.ts", 0.5), cand("src/d.ts", 0.5)];
+ const { slice } = selectSmells(report(tied), 3);
+ expect(slice.rows.map(c => c.file)).toEqual(["src/b.ts", "src/a.ts", "src/c.ts"]);
+ });
+
+ it("returns everything for an uncapped limit", () => {
+ const { slice } = selectSmells(report(synthetic(120)), Infinity);
+ expect(slice.shown).toBe(120);
+ expect(slice.truncated).toBe(false);
+ });
+
+ it("filters non-source orphans before the cut", () => {
+ const rows = [
+ cand("README.md", 0.99),
+ cand("docs/guide.mdx", 0.98),
+ ...synthetic(10),
+ ];
+ const { slice, filteredNonSource } = selectSmells(report(rows), 5);
+ expect(filteredNonSource).toBe(2);
+ expect(slice.total).toBe(10);
+ expect(slice.shown).toBe(5);
+ expect(slice.rows.every(c => c.file.startsWith("src/"))).toBe(true);
+ });
+});
+
+describe("isNonSourceOrphan", () => {
+ it.each(["README.md", "docs/guide.mdx", "templates/page.hbs", "config.yaml", "LICENSE"])(
+ "drops orphan %s", (file) => {
+ expect(isNonSourceOrphan(cand(file, 0.5))).toBe(true);
+ },
+ );
+
+ it.each(["src/a.ts", "scripts/run.sh", "Dockerfile", "styles/x.css"])(
+ "keeps orphan %s", (file) => {
+ expect(isNonSourceOrphan(cand(file, 0.5))).toBe(false);
+ },
+ );
+
+ it("never drops a god_module or weak_component row", () => {
+ expect(isNonSourceOrphan(cand("docs/big.md", 0.9, "has_smell.god_module"))).toBe(false);
+ expect(isNonSourceOrphan(cand("docs/big.md", 0.9, "has_smell.weak_component_member"))).toBe(false);
+ });
+});
+
+describe("ix smells command (mocked client)", () => {
+ let logs: string[];
+
+ beforeEach(() => {
+ logs = [];
+ vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => { logs.push(args.map(String).join(" ")); });
+ vi.spyOn(process.stderr, "write").mockImplementation(() => true);
+ fakeClient.runSmells.mockResolvedValue(report(synthetic(80)));
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ process.exitCode = undefined;
+ });
+
+ async function run(...args: string[]): Promise<string[]> {
+ const program = new Command();
+ program.exitOverride();
+ registerSmellsCommand(program);
+ await program.parseAsync(["smells", ...args], { from: "user" });
+ return logs.join("\n").split("\n");
+ }
+
+ it("llm: caps at 50 with a truncation diagnostic", async () => {
+ const lines = await run("--format", "llm");
+ expect(lines[0]).toBe("smells rev=7 count=80 shown=50 version=smell_v1");
+ expect(lines[1]).toMatch(/^diagnostic code=results_truncated /);
+ expect(lines[1]).toContain("Raise --limit");
+ expect(lines.filter(l => l.startsWith("smell ")).length).toBe(50);
+ });
+
+ it("text: header counts, 50 rows and the hint", async () => {
+ const lines = await run();
+ const header = lines.find(l => l.includes("Architecture Smells"))!;
+ expect(header).toContain("80 candidates");
+ expect(header).toContain("showing 50");
+ expect(lines.filter(l => l.includes("src/f")).length).toBe(50);
+ expect(lines.some(l => l.includes("Raise --limit"))).toBe(true);
+ });
+
+ it("text: --limit 10 prints 10 rows", async () => {
+ const lines = await run("--limit", "10");
+ expect(lines.filter(l => l.includes("src/f")).length).toBe(10);
+ });
+
+ it("text: reports hidden non-source orphans", async () => {
+ fakeClient.runSmells.mockResolvedValue(report([cand("README.md", 0.9), cand("src/a.ts", 0.5)]));
+ const lines = await run();
+ const header = lines.find(l => l.includes("Architecture Smells"))!;
+ expect(header).toContain("1 candidates");
+ expect(header).toContain("1 non-source orphan files hidden");
+ expect(lines.some(l => l.includes("README.md"))).toBe(false);
+ expect(lines.some(l => l.includes("Raise --limit"))).toBe(false);
+ });
+
+ it("json: uncapped without --limit (MCP path-filter contract)", async () => {
+ await run("--format", "json");
+ const out = JSON.parse(logs.join("\n"));
+ expect(out.candidates.length).toBe(80);
+ expect(out.count).toBe(80);
+ expect(out.shown).toBe(80);
+ expect(out.truncated).toBe(false);
+ expect(out.filtered_non_source).toBeUndefined();
+ });
+
+ it("json: plain output keeps docs orphans so MCP path queries can match them", async () => {
+ fakeClient.runSmells.mockResolvedValue(report([cand("README.md", 0.9), cand("src/a.ts", 0.5)]));
+ await run("--format", "json");
+ const out = JSON.parse(logs.join("\n"));
+ expect(out.candidates.map((c: { file: string }) => c.file)).toEqual(["README.md", "src/a.ts"]);
+ expect(out.filtered_non_source).toBeUndefined();
+ });
+
+ it("json: --limit filters non-source orphans", async () => {
+ fakeClient.runSmells.mockResolvedValue(report([cand("README.md", 0.9), cand("src/a.ts", 0.5)]));
+ await run("--format", "json", "--limit", "10");
+ const out = JSON.parse(logs.join("\n"));
+ expect(out.count).toBe(1);
+ expect(out.filtered_non_source).toBe(1);
+ });
+
+ it("json: --limit 5 cuts and keeps the total", async () => {
+ await run("--format", "json", "--limit", "5");
+ const out = JSON.parse(logs.join("\n"));
+ expect(out.candidates.length).toBe(5);
+ expect(out.count).toBe(80);
+ expect(out.shown).toBe(5);
+ expect(out.truncated).toBe(true);
+ });
+
+ it("--limit 0 shows everything", async () => {
+ const lines = await run("--format", "llm", "--limit", "0");
+ expect(lines[0]).toBe("smells rev=7 count=80 shown=80 version=smell_v1");
+ expect(lines.some(l => l.startsWith("diagnostic"))).toBe(false);
+ });
+
+ it("--limit 0 keeps non-source orphans in every format", async () => {
+ fakeClient.runSmells.mockResolvedValue(report([cand("README.md", 0.9), cand("src/a.ts", 0.5)]));
+ await run("--format", "json", "--limit", "0");
+ const out = JSON.parse(logs.join("\n"));
+ expect(out.candidates.map((c: { file: string }) => c.file)).toEqual(["README.md", "src/a.ts"]);
+ expect(out.filtered_non_source).toBeUndefined();
+
+ logs.length = 0;
+ const lines = await run("--format", "llm", "--limit", "0");
+ expect(lines.some(l => l.includes("README.md"))).toBe(true);
+ expect(lines.some(l => l.includes("filtered_non_source"))).toBe(false);
+ });
+
+ describe("--list", () => {
+ const claims = Array.from({ length: 6 }, (_, i) => ({
+ smell: "has_smell.orphan_file",
+ entity_id: `entity-${i}-0123456789`,
+ confidence: [0.2, 0.9, 0.5, 0.7, 0.1, 0.6][i],
+ inference_version: "smell_v1",
+ }));
+
+ beforeEach(() => {
+ fakeClient.listSmells.mockResolvedValue({ smells: claims });
+ });
+
+ it("without --limit prints every claim in stored order, unchanged", async () => {
+ const lines = await run("--list", "--format", "llm");
+ expect(lines[0]).toBe("smells count=6 version=smell_v1");
+ expect(lines.filter(l => l.startsWith("smell ")).length).toBe(6);
+ logs.length = 0;
+ await run("--list", "--format", "json");
+ const out = JSON.parse(logs.join("\n"));
+ expect(Object.keys(out)).toEqual(["count", "inference_version", "smells"]);
+ expect(out.smells.map((s: { confidence: number }) => s.confidence)).toEqual(claims.map(c => c.confidence));
+ });
+
+ it("llm: --limit keeps the highest-confidence claims and says so", async () => {
+ const lines = await run("--list", "--format", "llm", "--limit", "2");
+ expect(lines[0]).toBe("smells count=6 shown=2 version=smell_v1");
+ expect(lines[1]).toMatch(/^diagnostic code=results_truncated /);
+ const rows = lines.filter(l => l.startsWith("smell "));
+ expect(rows.length).toBe(2);
+ expect(rows[0]).toContain("confidence=0.9");
+ expect(rows[1]).toContain("confidence=0.7");
+ });
+
+ it("json: --limit cuts and keeps the total", async () => {
+ await run("--list", "--format", "json", "--limit", "3");
+ const out = JSON.parse(logs.join("\n"));
+ expect(out.count).toBe(6);
+ expect(out.shown).toBe(3);
+ expect(out.truncated).toBe(true);
+ expect(out.smells.map((s: { confidence: number }) => s.confidence)).toEqual([0.9, 0.7, 0.6]);
+ });
+
+ it("text: --limit prints that many rows with a header count and hint", async () => {
+ const lines = await run("--list", "--limit", "1");
+ expect(lines.some(l => l.includes("6 total · showing 1"))).toBe(true);
+ expect(lines.filter(l => l.includes("entity-")).length).toBe(1);
+ expect(lines.some(l => l.includes("Raise --limit"))).toBe(true);
+ });
+
+ it("--limit 0 lists everything", async () => {
+ await run("--list", "--format", "json", "--limit", "0");
+ const out = JSON.parse(logs.join("\n"));
+ expect(out.smells.length).toBe(6);
+ expect(out.truncated).toBe(false);
+ });
+ });
+});
diff --git a/ix-cli/src/cli/commands/smells.ts b/ix-cli/src/cli/commands/smells.ts
index 229b53b8..b2591823 100644
--- a/ix-cli/src/cli/commands/smells.ts
+++ b/ix-cli/src/cli/commands/smells.ts
@@ -6,9 +6,9 @@ import { createClient } from "../../client/factory.js";
import { resolveWorkspaceId } from "../bootstrap.js";
import { resolveReadSystemId } from "../resolve.js";
import { llmLine, llmError, type LlmValue } from "../llm.js";
-import { printJson } from "../format.js";
+import { printJson, sliceRanked, truncationHint, type Slice } from "../format.js";
-interface SmellCandidate {
+export interface SmellCandidate {
file_id: string;
file: string;
smell: string;
@@ -17,13 +17,90 @@ interface SmellCandidate {
inference_version: string;
}
-interface SmellReport {
+export interface SmellReport {
rev: number;
run_at: string;
count: number;
candidates: SmellCandidate[];
}
+/** Default cap on text and llm output. JSON is uncapped unless --limit is given. */
+const DEFAULT_LIMIT = 50;
+
+/**
+ * Extensions of files that hold no parsed code: docs, templates and
+ * data/config. An orphan of one of these is not an architecture finding.
+ * CSS, HTML, SQL and shell stay out of this set: an orphan stylesheet, page
+ * or script can be a real finding.
+ */
+const NON_SOURCE_EXTENSIONS = new Set([
+ // docs
+ ".md", ".mdx", ".markdown", ".rst", ".txt", ".adoc",
+ // templates
+ ".hbs", ".handlebars", ".ejs", ".mustache", ".njk", ".j2", ".jinja", ".jinja2",
+ ".liquid", ".tmpl", ".tpl", ".template",
+ // data / config
+ ".json", ".jsonc", ".yaml", ".yml", ".toml", ".ini", ".lock", ".csv", ".svg",
+]);
+
+/** Extensionless basenames that are build files, so still source. */
+const EXTENSIONLESS_SOURCE = new Set([
+ "dockerfile", "containerfile", "makefile", "gnumakefile", "rakefile", "gemfile",
+ "justfile", "jenkinsfile", "vagrantfile", "procfile", "podfile", "brewfile",
+ "fastfile", "guardfile", "berksfile", "capfile", "snakefile", "tiltfile",
+ "build", "workspace",
+ // shell dotfiles the ingester parses as Bash
+ ".bashrc", ".bash_profile", ".bash_aliases", ".bash_logout", ".zshrc", ".zprofile", ".zshenv", ".profile",
+]);
+
+/**
+ * True for an Orphan File row whose path is a doc, template or data/config
+ * file, or an extensionless file such as README or LICENSE that is not a
+ * known build file. Never true for any other smell kind.
+ */
+export function isNonSourceOrphan(c: SmellCandidate): boolean {
+ if (c.smell !== "has_smell.orphan_file") return false;
+ const path = c.file ?? "";
+ const base = (path.split(/[\\/]/).pop() ?? "").toLowerCase();
+ if (base === "") return false;
+ const dot = base.lastIndexOf(".");
+ // No extension (README, LICENSE, CODEOWNERS) or a bare dotfile (.gitignore):
+ // non-source unless it is a known build file.
+ if (dot <= 0) return !EXTENSIONLESS_SOURCE.has(base);
+ return NON_SOURCE_EXTENSIONS.has(base.slice(dot));
+}
+
+export interface SmellSelection {
+ slice: Slice<SmellCandidate>;
+ /** Orphan File rows dropped as non-source before the cut. */
+ filteredNonSource: number;
+}
+
+/**
+ * Drop non-source orphan rows, rank by confidence (highest first, stable among
+ * ties), then cut to `limit`. `total` on the slice counts what survived the
+ * filter.
+ */
+export function selectSmells(report: SmellReport, limit: number, filterNonSource = true): SmellSelection {
+ const kept = filterNonSource ? report.candidates.filter(c => !isNonSourceOrphan(c)) : report.candidates;
+ const sorted = [...kept].sort((a, b) => b.confidence - a.confidence);
+ return {
+ slice: sliceRanked(sorted, limit),
+ filteredNonSource: report.candidates.length - kept.length,
+ };
+}
+
+/**
+ * The cap to apply: an explicit --limit wins (0 = all). Without one, text and
+ * llm stop at DEFAULT_LIMIT and JSON returns everything, because MCP ix_smells
+ * and plugin fallbacks filter the JSON by path themselves.
+ */
+function resolveLimit(raw: string | undefined, format: string): number {
+ if (raw === undefined) return format === "json" ? Infinity : DEFAULT_LIMIT;
+ const n = parseInt(raw, 10);
+ return !Number.isFinite(n) || n <= 0 ? Infinity : n;
+}
+
const SMELL_LABELS: Record<string, string> = {
"has_smell.orphan_file": "Orphan File",
"has_smell.god_module": "God Module",
@@ -40,6 +117,7 @@ export function registerSmellsCommand(program: Command): void {
.option("--god-module-fan <n>", "Min fan-in/out for god module", "15")
.option("--weak-max-neighbors <n>", "Max neighbors for weak component", "1")
.option("--list", "List existing smell claims without rerunning")
+ .option("--limit <n>", "Max candidates to show, highest confidence first (0 = all, non-source orphans included; with --list, caps the stored claims)")
.addHelpText("after", `
Runs graph-query-based architecture smell detection and stores results as
versioned claims (inference_version=smell_v1) on affected File nodes.
@@ -53,6 +131,8 @@ Examples:
ix smells
ix smells --god-module-chunks 15 --god-module-fan 10
ix smells --format json
+ ix smells --limit 200
+ ix smells --limit 0
ix smells --list`)
.action(async (opts: {
format: string;
@@ -61,6 +141,7 @@ Examples:
godModuleFan: string;
weakMaxNeighbors: string;
list?: boolean;
+ limit?: string;
}) => {
const client = createClient();
const systemId = await resolveReadSystemId(client);
@@ -75,12 +156,21 @@ Examples:
process.exitCode = 1;
return;
}
+ // Without --limit, --list prints every stored claim, as before. With
+ // one, it keeps the highest-confidence claims (0 = all). Claim rows
+ // carry only an entity id, so no path filter applies here.
+ const listLimit = opts.limit === undefined ? undefined : resolveLimit(opts.limit, opts.format);
+ const listSlice = sliceRanked<any>(
+ result.smells ?? [],
+ listLimit ?? Infinity,
+ listLimit === undefined ? undefined : (s) => -(Number(s.confidence) || 0),
+ );
if (opts.format === "json") {
- const smells = result.smells ?? [];
printJson({
- count: smells.length,
+ count: listSlice.total,
+ ...(listLimit === undefined ? {} : { shown: listSlice.shown, truncated: listSlice.truncated }),
inference_version: "smell_v1",
- smells: smells.map((s: any) => ({
+ smells: listSlice.rows.map((s: any) => ({
smell: s.smell,
entity_id: s.entity_id?.slice(0, 12),
confidence: s.confidence,
@@ -88,20 +178,21 @@ Examples:
});
return;
}
- const smells = result.smells ?? [];
if (opts.format === "llm") {
- for (const line of renderSmellsListLlm(smells)) console.log(line);
+ for (const line of renderSmellsListLlm(listSlice.rows, listLimit === undefined ? undefined : listSlice)) console.log(line);
return;
}
- if (smells.length === 0) {
+ if (listSlice.total === 0) {
console.log(chalk.dim("No smell claims found. Run `ix smells` to detect."));
return;
}
- console.log(`\n${chalk.bold("Smell Claims")} ${chalk.dim(`(${smells.length} total)`)}\n`);
- for (const s of smells) {
+ const shownNote = listSlice.truncated ? ` · showing ${listSlice.shown}` : "";
+ console.log(`\n${chalk.bold("Smell Claims")} ${chalk.dim(`(${listSlice.total} total${shownNote})`)}\n`);
+ for (const s of listSlice.rows) {
const label = SMELL_LABELS[s.smell] ?? s.smell;
console.log(` ${chalk.yellow(label.padEnd(20))} ${chalk.dim(s.entity_id?.slice(0, 8))} ${chalk.dim(s.inference_version ?? "")}`);
}
+ if (listSlice.truncated) console.log(chalk.dim(`\n${truncationHint(listSlice, "smell claims")}`));
return;
}
@@ -126,14 +217,27 @@ Examples:
return;
}
+ // Plain `--format json` is the raw contract MCP ix_smells and plugin
+ // fallbacks path-filter themselves, so it neither caps nor drops rows
+ // unless --limit is passed. An explicit `--limit 0` means everything,
+ // so it drops nothing either, in every format.
+ const rawJson = opts.format === "json" && opts.limit === undefined;
+ const limit = resolveLimit(opts.limit, opts.format);
+ const everything = opts.limit !== undefined && limit === Infinity;
+ const selection = selectSmells(report, limit, !(rawJson || everything));
+ const { slice, filteredNonSource } = selection;
+
if (opts.format === "json") {
// Compact: hoist inference_version to top, drop file_id UUIDs
- const compact = {
+ const compact: Record<string, unknown> = {
rev: report.rev,
run_at: report.run_at,
- count: report.count,
+ count: slice.total,
+ shown: slice.shown,
+ truncated: slice.truncated,
+ ...(filteredNonSource > 0 ? { filtered_non_source: filteredNonSource } : {}),
inference_version: "smell_v1",
- candidates: report.candidates.map(c => ({
+ candidates: slice.rows.map(c => ({
file: c.file,
smell: c.smell,
confidence: c.confidence,
@@ -145,23 +249,29 @@ Examples:
}
if (opts.format === "llm") {
- for (const line of renderSmellsRunLlm(report)) console.log(line);
+ for (const line of renderSmellsRunLlm(report, selection)) console.log(line);
return;
}
+ const countText = slice.truncated
+ ? `${slice.total} candidates · showing ${slice.shown}`
+ : `${slice.total} candidates`;
+ const hiddenText = filteredNonSource > 0
+ ? ` (${filteredNonSource} non-source orphan files hidden)`
+ : "";
console.log(
`\n${chalk.bold("Architecture Smells")} ` +
- chalk.dim(`rev ${report.rev} · ${report.count} candidates`)
+ chalk.dim(`rev ${report.rev} · ${countText}${hiddenText}`)
);
- if (report.count === 0) {
+ if (slice.total === 0) {
console.log(chalk.green("\n No smell candidates found."));
return;
}
- // Group by smell kind
+ // Group the shown rows by smell kind; each group stays confidence-sorted.
const byKind = new Map<string, SmellCandidate[]>();
- for (const c of report.candidates) {
+ for (const c of slice.rows) {
if (!byKind.has(c.smell)) byKind.set(c.smell, []);
byKind.get(c.smell)!.push(c);
}
@@ -170,8 +280,7 @@ Examples:
const label = SMELL_LABELS[kind] ?? kind;
console.log(`\n${chalk.bold(label)} ${chalk.dim(`(${candidates.length})`)}`);
- const sorted = [...candidates].sort((a, b) => b.confidence - a.confidence);
- for (const c of sorted) {
+ for (const c of candidates) {
const conf = confidenceBar(c.confidence);
const fileName = c.file.length > 45
? "…" + c.file.slice(-44)
@@ -181,6 +290,8 @@ Examples:
}
}
+ if (slice.truncated) console.log(chalk.dim(`\n${truncationHint(slice, "smell candidates")}`));
+
console.log(chalk.dim(`\nSmell claims stored with inference_version=smell_v1. Use 'ix smells --list' to retrieve.`));
});
}
@@ -192,9 +303,23 @@ function confidenceBar(conf: number): string {
return color(bar);
}
-/** Render `ix smells --list` claims as llm records. */
-export function renderSmellsListLlm(smells: any[]): string[] {
- const lines = [llmLine("smells", [["count", smells.length], ["version", "smell_v1"]])];
+/**
+ * Render `ix smells --list` claims as llm records. With a slice (an explicit
+ * --limit), the header carries the total and `shown`, plus a truncation
+ * diagnostic when rows were cut.
+ */
+export function renderSmellsListLlm(smells: any[], slice?: Slice<unknown>): string[] {
+ const lines = [llmLine("smells", [
+ ["count", slice ? slice.total : smells.length],
+ ["shown", slice ? slice.shown : undefined],
+ ["version", "smell_v1"],
+ ])];
+ if (slice?.truncated) {
+ lines.push(llmLine("diagnostic", [
+ ["code", "results_truncated"],
+ ["message", truncationHint(slice, "smell claims")],
+ ]));
+ }
for (const s of smells) {
lines.push(llmLine("smell", [
["kind", s.smell],
@@ -206,11 +331,29 @@ export function renderSmellsListLlm(smells: any[]): string[] {
return lines;
}
-/** Render a fresh `ix smells` detection run as llm records, highest-confidence first. */
-export function renderSmellsRunLlm(report: SmellReport): string[] {
- const lines = [llmLine("smells", [["rev", report.rev], ["count", report.count], ["version", "smell_v1"]])];
- const sorted = [...report.candidates].sort((a, b) => b.confidence - a.confidence);
- for (const c of sorted) {
+/**
+ * Render a fresh `ix smells` detection run as llm records, highest-confidence
+ * first. Without a selection, every candidate is shown (no filter, no cap).
+ */
+export function renderSmellsRunLlm(report: SmellReport, selection?: SmellSelection): string[] {
+ const { slice, filteredNonSource } = selection ?? {
+ slice: sliceRanked([...report.candidates].sort((a, b) => b.confidence - a.confidence), Infinity),
+ filteredNonSource: 0,
+ };
+ const lines = [llmLine("smells", [
+ ["rev", report.rev],
+ ["count", slice.total],
+ ["shown", slice.shown],
+ ["filtered_non_source", filteredNonSource > 0 ? filteredNonSource : undefined],
+ ["version", "smell_v1"],
+ ])];
+ if (slice.truncated) {
+ lines.push(llmLine("diagnostic", [
+ ["code", "results_truncated"],
+ ["message", truncationHint(slice, "smell candidates")],
+ ]));
+ }
+ for (const c of slice.rows) {
lines.push(llmLine("smell", [
["kind", c.smell],
["file", c.file],
diff --git a/ix-cli/src/mcp/server.ts b/ix-cli/src/mcp/server.ts
index a3ebcceb..42a7d27d 100644
--- a/ix-cli/src/mcp/server.ts
+++ b/ix-cli/src/mcp/server.ts
@@ -1030,7 +1030,7 @@ async function runSmells(runIx: IxRunner, input: ToolInput): Promise<CallToolRes
const path = typeof input.path === "string" ? normalizePath(input.path) : null;
const limit = numberArg(input, "limit");
- const candidates = parsed.candidates
+ const matched = parsed.candidates
.filter((candidate) => {
if (path === null || !isRecord(candidate) || typeof candidate.file !== "string") {
return path === null;
@@ -1041,10 +1041,15 @@ async function runSmells(runIx: IxRunner, input: ToolInput): Promise<CallToolRes
// architecture smells here" — for the `src` an agent had just used
// successfully against ix_inventory on files stored as `ix-cli/src/...`.
return normalizePath(candidate.file).includes(path);
- })
- .slice(0, limit);
-
- const payload = { ...parsed, count: candidates.length, candidates };
+ });
+ const candidates = matched.slice(0, limit);
+
+ // shown/truncated describe this response, not the CLI's, so recompute them
+ // after the path filter and limit.
+ const meta = "shown" in parsed
+ ? { shown: candidates.length, truncated: parsed.truncated === true || matched.length > candidates.length }
+ : {};
+ const payload = { ...parsed, count: candidates.length, ...meta, candidates };
// Compact, and the object once rather than twice. The indent was two spaces
// per level of a list of smell candidates, and the structured copy was the
// same bytes again.
diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.md
index 66d2c24c..9a9cb8d4 100644
--- a/skills/ix/references/flags.md
+++ b/skills/ix/references/flags.md
@@ -738,6 +738,7 @@ Detect architecture smells in the codebase.
| `--god-module-fan` | `<n>` | `15` | Min fan-in/out for god module |
| `--weak-max-neighbors` | `<n>` | `1` | Max neighbors for weak component |
| `--list` | — | off | List existing smell claims without rerunning |
+| `--limit` | `<n>` | 50 (text/llm); all (json) | Max candidates, highest confidence first; 0 = all, unfiltered. Otherwise non-source orphan files (docs, templates, data) are dropped before the cut. With `--list`, caps the stored claims (all when omitted) |
### `ix stats`