8000 #24: make runner/sensor/registry smell-agnostic (config-driven) by devill · Pull Request #39 · habit-hooks/habit-hooks · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -332,3 +332,17 @@ phases (PR #13). Each call below is an _agent decision_.
gated out, so a config that disables an input can't crash the run. The
catalogue entry lives in `customRules` (source `custom`) to stay under the
200-line cap.

- **Smell knowledge lives only in config; the sensor layer consumes it.** _(agent
decision, #24)_ All tool/smell mappings moved to `src/config/tool-smells.ts`:
the eslint raw→smell map, eslint/knip/jscpd/comment produces, and the ruff +
deptry `AdapterSpec`s. The eslint/jscpd/comment data is **derived from the
catalogue** (so adding a smell there auto-wires its translation and produces);
knip's raw issue types and the supplemental `parse-error` (an eslint fatal with
no catalogue rule) are the config literals. The runner, sensors, checks, and
rules registry now import these instead of hardcoding — the acceptance grep is
clean for non-test source. (Test files still pin concrete smell strings as
behaviour assertions.) Adding a new eslint smell touches only `src/config/`
(catalogue) + `src/cli/init/` (the scaffolded eslint config) — proved live by
the `deep-nesting` smell (#26). Realizes the locked "spec from config" via
config-derived constants rather than per-call DI, keeping the refactor low-risk.
5 changes: 3 additions & 2 deletions src/checks/comment-check.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Project, SyntaxKind, type Node, type SourceFile } from 'ts-morph';
import { COMMENT_SMELL } from '../config/tool-smells.js';
import type { Check, CommentCheckThresholds, Rule, Violation } from '../types.js';

export const DEFAULT_COMMENT_CHECK_THRESHOLDS: CommentCheckThresholds = {
Expand Down Expand Up @@ -31,7 +32,7 @@ function truncate(text: string): string {

function makeViolation(file: string, comment: Node, kind: CommentKind): Violation {
return {
ruleId: 'non-essential-comment',
ruleId: COMMENT_SMELL,
source: 'comment:non-essential',
file,
line: comment.getStartLineNumber(),
Expand Down Expand Up @@ -80,7 +81,7 @@ function buildProject(files: string[]): Project {
}

function resolveThresholds(rules: Rule[]): CommentCheckThresholds {
const rule = rules.find((r) => r.id === 'non-essential-comment');
const rule = rules.find((r) => r.id === COMMENT_SMELL);
return rule?.commentCheck ?? DEFAULT_COMMENT_CHECK_THRESHOLDS;
}

Expand Down
19 changes: 2 additions & 17 deletions src/checks/eslint-wrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
type BinResolution,
} from '../wrap/notices.js';
import { spawnTarget } from '../wrap/resolve.js';
import { ESLINT_SMELL_MAP, PARSE_ERROR_SMELL } from '../config/tool-smells.js';
import { parseJsonStdout } from '../wrap/run.js';
import type { Check, CheckOutcome, Violation } from '../types.js';

Expand Down Expand Up @@ -58,22 +59,6 @@ function isConfigError(result: ShellResult, parsed: EslintFileResult[] | null):
return result.exitCode !== 0 && result.exitCode !== 1;
}

const ESLINT_SMELL_MAP: Record<string, string> = {
'max-lines-per-function': 'oversized-function',
'max-params': 'too-many-parameters',
complexity: 'high-complexity',
'max-lines': 'oversized-file',
'no-unused-vars': 'unused-variable',
eqeqeq: 'loose-equality',
'no-var': 'var-declaration',
'prefer-const': 'non-const-binding',
'no-duplicate-imports': 'duplicate-import',
'no-warning-comments': 'warning-comment',
'@typescript-eslint/no-explicit-any': 'explicit-any',
'@typescript-eslint/no-non-null-assertion': 'non-null-assertion',
'@typescript-eslint/no-inferrable-types': 'redundant-type-annotation',
};

function messageToViolation(filePath: string, m: EslintMessage & { ruleId: string }): Violation {
const smell = ESLINT_SMELL_MAP[m.ruleId] ?? m.ruleId;
const title = lookupPrompt(smell)?.title ?? m.ruleId;
Expand All @@ -84,7 +69,7 @@ function messageToViolation(filePath: string, m: EslintMessage & { ruleId: strin

function fatalToViolation(filePath: string, m: EslintMessage): Violation {
return {
ruleId: 'parse-error',
ruleId: PARSE_ERROR_SMELL,
source: 'eslint:fatal',
file: filePath,
line: m.line,
Expand Down
4 changes: 2 additions & 2 deletions src/checks/jscpd-wrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import { detectTool } from '../detect/tool.js';
import { hasPackageJsonKey } from '../detect/package-json.js';
import { absolutize, emptyOutcome, firstLine, noticesFor, type BinResolution } from '../wrap/notices.js';
import { isSpawnSkip, skipOutcome, spawnWrapped } from '../wrap/run.js';
import { JSCPD_SMELL } from '../config/tool-smells.js';
import type { Check, CheckOutcome, Violation } from '../types.js';

const require = createRequire(import.meta.url);

const SMELL = 'duplicated-code';
const REPORT_FILENAME = 'jscpd-report.json';

const JSCPD_CONFIG_FILES = ['.jscpd.json', 'jscpd.json'];
Expand Down Expand Up @@ -84,7 +84,7 @@ function locationDescription(loc: JscpdLocation, cwd: string): string {

function buildViolation(self: JscpdLocation, partner: JscpdLocation, cwd: string): Violation {
return {
ruleId: SMELL,
ruleId: JSCPD_SMELL,
source: 'jscpd:duplication',
file: absolutize(cwd, self.name),
line: self.startLoc.line,
Expand Down
8 changes: 1 addition & 7 deletions src/checks/knip-wrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { join } from 'node:path';
import { hasPackageJsonKey } from '../detect/package-json.js';
import { absolutize, emptyOutcome, firstLine, noticesFor, type BinResolution } from '../wrap/notices.js';
import { isSpawnSkip, parseJsonStdout, skipOutcome, spawnWrapped } from '../wrap/run.js';
import { KNIP_SMELL_MAP } from '../config/tool-smells.js';
import { buildKnipArgs, consumerKnipMajor, resolveKnipBin } from './knip-resolve.js';
import {
KNOWN_KEYS,
Expand Down Expand Up @@ -31,13 +32,6 @@ interface IssueContext {
issueFile: string;
}

const KNIP_SMELL_MAP: Record<string, string> = {
classMembers: 'unused-class-member',
files: 'unused-file',
exports: 'unused-export',
dependencies: 'unused-dependency',
};

function knipSmell(issueType: string): string {
return KNIP_SMELL_MAP[issueType] ?? issueType;
}
Expand Down
52 changes: 52 additions & 0 deletions src/config/tool-smells.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { describe, expect, it } from 'vitest';
import { defaultRules } from './catalogue.js';
import {
COMMENT_SMELL,
ESLINT_PRODUCES,
ESLINT_SMELL_MAP,
JSCPD_SMELL,
PARSE_ERROR_SMELL,
} from './tool-smells.js';

// These prove the sensor/check layer's smell knowledge is DERIVED from the
// catalogue: adding a smell there auto-wires its translation and produces with
// zero edits to runner/sensor/check code (issue #24; deep-nesting is the live
// demonstrator).
describe('tool-smells derivation', () => {
it('derives the eslint raw->smell map from every catalogue eslint rule with a sourceRuleId', () => {
for (const rule of defaultRules) {
if (rule.source === 'eslint' && rule.sourceRuleId !== undefined) {
expect(ESLINT_SMELL_MAP[rule.sourceRuleId], rule.id).toBe(rule.id);
}
}
});

it('eslint produces every catalogue eslint smell plus the supplemental parse-error', () => {
for (const rule of defaultRules.filter((r) => r.source === 'eslint')) {
expect(ESLINT_PRODUCES).toContain(rule.id);
}
expect(ESLINT_PRODUCES).toContain(PARSE_ERROR_SMELL);
});

it('jscpd and comment smells are the catalogue rules for those sources', () => {
expect(JSCPD_SMELL).toBe(defaultRules.find((r) => r.source === 'jscpd')?.id);
expect(COMMENT_SMELL).toBe(defaultRules.find((r) => r.source === 'custom')?.id);
});
});

// Concrete value pins: a catalogue rename or typo fails the suite immediately.
// Keep alongside the derivation tests above so both the derivation logic AND
// the actual string values are guarded.
describe('tool-smells concrete values', () => {
it('JSCPD_SMELL is duplicated-code', () => {
expect(JSCPD_SMELL).toBe('duplicated-code');
});

it('COMMENT_SMELL is non-essential-comment', () => {
expect(COMMENT_SMELL).toBe('non-essential-comment');
});

it('PARSE_ERROR_SMELL is parse-error', () => {
expect(PARSE_ERROR_SMELL).toBe('parse-error');
});
});
67 changes: 67 additions & 0 deletions src/config/tool-smells.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import type { Rule, RuleSource } from '../types.js';
import type { AdapterSpec, DeclarativeSensorSpec } from '../sensors/adapter.js';
import { defaultRules } from './catalogue.js';

// The single home for tool/smell knowledge (issue #24): the sensor and check
// layers receive these from config and never hardcode a smell id. eslint/jscpd
// data is derived from the catalogue, so adding a smell there auto-wires it.

function rulesFor(source: RuleSource): Rule[] {
return defaultRules.filter((rule) => rule.source === source);
}

function smellsFor(source: RuleSource): string[] {
return rulesFor(source).map((rule) => rule.id);
}

function rawToSmell(source: RuleSource): Record<string, string> {
const map: Record<string, string> = {};
for (const rule of rulesFor(source)) {
if (rule.sourceRuleId !== undefined) map[rule.sourceRuleId] = rule.id;
}
return map;
}

// `parse-error` is a supplemental smell (eslint fatal) with no catalogue rule.
export const PARSE_ERROR_SMELL = 'parse-error';

export const ESLINT_SMELL_MAP = rawToSmell('eslint');
export const ESLINT_PRODUCES = [...smellsFor('eslint'), PARSE_ERROR_SMELL];

export const JSCPD_SMELL = smellsFor('jscpd')[0];
export const COMMENT_SMELL = smellsFor('custom')[0];

// knip's raw issue types are tool-specific, not catalogue rule ids, so the
// translation lives here in config.
export const KNIP_SMELL_MAP: Record<string, string> = {
classMembers: 'unused-class-member',
files: 'unused-file',
exports: 'unused-export',
dependencies: 'unused-dependency',
};
export const KNIP_PRODUCES = Object.values(KNIP_SMELL_MAP);

// Python tool specs (the generalized AdapterSpec model): ruff + deptry.
export const RUFF_SPEC: DeclarativeSensorSpec = {
id: 'ruff',
produces: ['high-complexity', 'too-many-parameters', 'oversized-function', 'unused-variable', 'unused-import'],
command: 'ruff check --output-format=json --select=C901,PLR0913,PLR0915,F841,F401 ${files}',
items: '[]',
fields: { smell: 'code', file: 'filename', line: 'location.row', column: 'location.column', message: 'message' },
map: {
C901: 'high-complexity',
PLR0913: 'too-many-parameters',
PLR0915: 'oversized-function',
F841: 'unused-variable',
F401: 'unused-import',
},
};

export const DEPTRY_SPEC: AdapterSpec = {
id: 'deptry',
command: 'deptry . --json-output <report>',
items: '[]',
fields: { smell: 'error.code', file: 'location.file', line: 'location.line', message: 'error.message' },
map: { DEP002: 'unused-dependency' },
};
export const DEPTRY_PRODUCES = Object.values(DEPTRY_SPEC.map ?? {});
5 changes: 2 additions & 3 deletions src/rules/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@ import type { CommentCheckThresholds, Rule } from '../types.js';
import { DEFAULT_COMMENT_CHECK_THRESHOLDS } from '../checks/comment-check.js';
import { defaultConfig, defaultRules } from '../config/defaults.js';
import { mergeRules } from '../config/merge.js';
import { COMMENT_SMELL } from '../config/tool-smells.js';
import type { CommentCheckConfig, HabitHooksConfig } from '../config/schema.js';
import { loadGuidance } from '../prompts/loader.js';

const COMMENT_RULE_ID = 'non-essential-comment';

function resolvePromptsDir(config: HabitHooksConfig, configDir: string): string | undefined {
if (config.prompts === undefined) return undefined;
return isAbsolute(config.prompts) ? config.prompts : resolve(configDir, config.prompts);
Expand All @@ -32,7 +31,7 @@ function resolveCommentThresholds(config: CommentCheckConfig | undefined): Comme

function attachCommentThresholds(rules: Rule[], config: CommentCheckConfig | undefined): Rule[] {
const thresholds = resolveCommentThresholds(config);
return rules.map((rule) => (rule.id === COMMENT_RULE_ID ? { ...rule, commentCheck: thresholds } : rule));
return rules.map((rule) => (rule.id === COMMENT_SMELL ? { ...rule, commentCheck: thresholds } : rule));
}

export function buildRules(config: HabitHooksConfig, configDir: string): Rule[] {
Expand Down
31 changes: 22 additions & 9 deletions src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,11 @@ import { buildPythonPresetSensors } from './sensors/python-preset.js';
import { mapIssues, type MapperDirs, type RoutingLookup } from './mapper/mapper.js';
import { guide } from './guide/guide.js';
import type { SensorSink } from './wrap/notices.js';
import { COMMENT_SMELL } from './config/tool-smells.js';
import type { Sensor } from './sensors/types.js';
import type { HabitHooksConfig, Language } from './config/schema.js';
import type { Rule, Violation } from './types.js';

const COMMENT_SMELL = 'non-essential-comment';

export interface RunResult {
stdout: string;
stderr: string[];
Expand Down Expand Up @@ -89,18 +88,32 @@ function resolvePromptsDir(config: HabitHooksConfig, configDir: string): string
return isAbsolute(config.prompts) ? config.prompts : resolve(configDir, config.prompts);
}

interface ResolvedInputs {
cwd: string;
config: HabitHooksConfig;
configDir: string;
files: string[];
scope: ResolvedScope;
baseline: BaselineFile | null;
}

function buildRunContext(inputs: ResolvedInputs): RunContext {
const { cwd, config, configDir, files, scope, baseline } = inputs;
const promptsDir = resolvePromptsDir(config, configDir);
const configWarnings = config.rules !== undefined ? [RULES_DEPRECATION] : [];
const snoozeIndex = createSnoozeIndex(cwd);
const needsExtractionReplace = config.needsExtraction?.replace === true;
return { cwd, files, scope, baseline, snoozeIndex, language: config.language ?? 'typescript', promptsDir, configWarnings, needsExtractionReplace };
}

async function buildContext(cwd: string, options: RunOptions): Promise<{ ctx: RunContext; rules: Rule[] }> {
const { config, configDir } = await resolveConfig(cwd, options);
const rules = buildRules(config, configDir);
const language: Language = config.language ?? 'typescript';
const files = await discoverFiles(cwd, language, config.scope?.exclude);
const scope = resolveScope(options.scopeFlags ?? {}, config.scope, cwd);
const baseline = resolveBaseline(cwd, options);
const promptsDir = resolvePromptsDir(config, configDir);
const configWarnings = config.rules !== undefined ? [RULES_DEPRECATION] : [];
const snoozeIndex = createSnoozeIndex(cwd);
const needsExtractionReplace = config.needsExtraction?.replace === true;
return { ctx: { cwd, files, scope, baseline, snoozeIndex, language, promptsDir, configWarnings, needsExtractionReplace }, rules };
return { ctx: buildRunContext({ cwd, config, configDir, files, scope, baseline }), rules };
}

// A sensor runs only when at least one smell it produces has an active rule
Expand Down Expand Up @@ -147,8 +160,8 @@ function filterViolations(violations: Violation[], rules: Rule[], ctx: RunContex
}

// Routing for the mapper: the merged smell config wins; otherwise the catalogue
// (prompt registry) supplies severity/title for supplemental smells such as
// `parse-error`, so its `enforced` severity survives. Unknown smells -> uncoached.
// (prompt registry) supplies severity/title for supplemental smells, so their
// enforced severity survives. Unknown smells -> uncoached.
function buildRouting(rules: Rule[]): RoutingLookup {
const byId = new Map(rules.map((r) => [r.id, r] as const));
return (smell) => {
Expand Down
12 changes: 3 additions & 9 deletions src/sensors/deptry-sensor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,14 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { runTool } from '../wrap/shell.js';
import { isSpawnFailure, recordSpawnFailure, spawnFailureWarning, type SensorSink } from '../wrap/notices.js';
import { extractIssues, type AdapterSpec } from './adapter.js';
import { DEPTRY_PRODUCES, DEPTRY_SPEC } from '../config/tool-smells.js';
import { extractIssues } from './adapter.js';
import type { Issue, Sensor } from './types.js';

// deptry analyses the whole project and reports unused dependencies. Its
// `--json-output` must target a real file (writing to /dev/stdout yields nothing
// when stdout is a pipe), so deptry uses the temp-report pattern rather than the
// stdout declarative adapter — but reuses the adapter's extractIssues to map.
const DEPTRY_SPEC: AdapterSpec = {
id: 'deptry',
command: 'deptry . --json-output <report>',
items: '[]',
fields: { smell: 'error.code', file: 'location.file', line: 'location.line', message: 'error.message' },
map: { DEP002: 'unused-dependency' },
};

function parseReport(path: string): Issue[] {
if (!existsSync(path)) return [];
Expand Down Expand Up @@ -47,5 +41,5 @@ async function runDeptry(cwd: string, sink: SensorSink): Promise<Issue[]> {
}

export function deptrySensor(sink: SensorSink): Sensor {
return { id: 'deptry', produces: ['unused-dependency'], run: (ctx) => runDeptry(ctx.cwd, sink) };
return { id: 'deptry', produces: DEPTRY_PRODUCES, run: (ctx) => runDeptry(ctx.cwd, sink) };
}
5 changes: 3 additions & 2 deletions src/sensors/needs-extraction.ts
96C7
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { JSCPD_SMELL } from '../config/tool-smells.js';
import type { Issue, Sensor } from './types.js';

const SMELL = 'needs-extraction';
const INPUT_SMELLS = ['oversized-file', 'duplicated-code'] as const;
const INPUT_SMELLS = ['oversized-file', JSCPD_SMELL] as const;

function fileOf(issue: Issue): string | null {
const file = issue.details.file;
Expand Down Expand Up @@ -32,7 +33,7 @@ function needsExtractionIssue(file: string): Issue {
}

function combine(deps: Issue[]): Issue[] {
const duplicated = filesWith(deps, 'duplicated-code');
const duplicated = filesWith(deps, JSCPD_SMELL);
return [...filesWith(deps, 'oversized-file')].filter((file) => duplicated.has(file)).map(needsExtractionIssue);
}

Expand Down
Loading
0