8000 #11: auto-prune stale snoozes on full-repo runs by devill · Pull Request #34 · 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
11 changes: 11 additions & 0 deletions docs/DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -284,3 +284,14 @@ phases (PR #13). Each call below is an _agent decision_.
sat exactly at the `max-lines: 200` limit, and discovery is a distinct
responsibility from orchestration; the move keeps runner under the cap and gives
the `scope.exclude` knob a focused home. Reversible — it could be inlined back.

- **Auto-prune is a CLI side effect, not part of `run()`.** _(agent decision,
#11)_ Auto-pruning fixed baseline entries mutates a checked-in file, so it
lives outside `run()` (which stays a pure evaluator) in `runWithAutoPrune`,
alongside the other baseline mutations in the command layer. It fires only when
`run()` reports `scopeMode === 'all'` (a full-repo run); scoped runs are a
guaranteed no-op. It runs a **baseline-free** full scan (a second `run()` with
`applyBaseline: false`) so a sensor gated off by the baseline can't make a
snoozed file look falsely clean, and shares one reaper (`reapBaseline`) with
manual `baseline prune`. The pruned set is printed so the mutation is never
silent. Reversible — auto-prune could move into `run()` or behind a flag.
96 changes: 96 additions & 0 deletions src/baseline/auto-prune.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { afterEach, describe, expect, it } from 'vitest';
import { rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { runWithAutoPrune } from './auto-prune.js';
import { loadBaseline, saveBaseline } from './store.js';
import { lastCommitHash } from './file-hash.js';
import { createGitRepo, type GitRepo } from '../../tests/helpers/git.js';

const DIRTY_FN = `export function tooMany(a: number, b: number, c: number, d: number): number {
return a + b + c + d;
}
`;
const CLEAN_FN = `export function add(a: number, b: number): number {
return a + b;
}
`;

function snooze(repo: GitRepo, file: string): void {
saveBaseline(repo.cwd, {
version: 2,
files: { [file]: { snoozedAtCommit: lastCommitHash(repo.cwd, file) ?? '' } },
});
}

const LENIENT_CONFIG = `export default { scope: { exclude: ['bad.ts'] } };\n`;

describe('runWithAutoPrune', () => {
let repo: GitRepo;

afterEach(() => {
if (repo) rmSync(repo.cwd, { recursive: true, force: true });
});

it('prunes a now-clean baselined file on a full-repo run and reports it', async () => {
repo = createGitRepo({ withEslint: true });
repo.writeFile('bad.ts', DIRTY_FN);
repo.commitAll('add bad');
snooze(repo, 'bad.ts');
repo.writeFile('bad.ts', CLEAN_FN);
repo.commitAll('fix bad');
< 8000 /td>
const result = await runWithAutoPrune(repo.cwd, { scopeFlags: { all: true } });

expect(loadBaseline(repo.cwd).files['bad.ts']).toBeUndefined();
expect(result.stdout).toContain('Auto-pruned');
expect(result.stdout).toContain('bad.ts');
});

it('keeps a still-violating baselined file on a full-repo run', async () => {
repo = createGitRepo({ withEslint: true });
repo.writeFile('bad.ts', DIRTY_FN);
repo.commitAll('add bad');
snooze(repo, 'bad.ts');

await runWithAutoPrune(repo.cwd, { scopeFlags: { all: true } });

expect(loadBaseline(repo.cwd).files['bad.ts']).toBeDefined();
});

it('never mutates the baseline on a scoped run, even when the snoozed file is now clean', async () => {
repo = createGitRepo({ withEslint: true });
repo.writeFile('bad.ts', DIRTY_FN);
repo.commitAll('add bad');
snooze(repo, 'bad.ts');
repo.writeFile('bad.ts', CLEAN_FN);
repo.commitAll('fix bad');

await runWithAutoPrune(repo.cwd, { scopeFlags: { last: 1 } });

expect(loadBaseline(repo.cwd).files['bad.ts']).toBeDefined();
});

it('forwards configPath to the re-scan so the same rules govern both the main run and auto-prune', async () => {
// Scenario: a custom config excludes bad.ts from scope. Under that config,
// bad.ts is never scanned → never appears as violating. Without the fix,
// the re-scan uses default config discovery (no exclusion) and still finds
// bad.ts violating, so the baseline entry is kept even though the main run
// would never surface it. With the fix, the re-scan uses the same custom
// config, sees bad.ts as out-of-scope, and correctly prunes the stale entry.
repo = createGitRepo({ withEslint: true });
repo.writeFile('bad.ts', DIRTY_FN);
repo.commitAll('add bad');
snooze(repo, 'bad.ts');

// Custom config excludes bad.ts — the user is no longer tracking it.
const configPath = join(repo.cwd, 'lenient.config.js');
writeFileSync(configPath, LENIENT_CONFIG);

await runWithAutoPrune(repo.cwd, { configPath, scopeFlags: { all: true } });

// The baseline entry for bad.ts is stale under the custom config (the file
// is excluded from scope). The fix ensures auto-prune uses the same config
// as the main run, so it correctly prunes the entry.
expect(loadBaseline(repo.cwd).files['bad.ts']).toBeUndefined();
});
});
36 changes: 36 additions & 0 deletions src/baseline/auto-prune.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { run, type RunOptions, type RunResult } from '../runner.js';
import { loadBaseline, saveBaseline, BASELINE_VERSION } from './store.js';
import { toRepoRelative } from './filter.js';
import { reapBaseline } from './reap.js';

// Auto-prune reaps baseline entries whose smell is actually fixed. It runs a
// baseline-free full scan so a sensor gated off by the baseline can't make a
// snoozed file look falsely clean, then shares the reaper with `baseline prune`.
// configPath must match the one used for the main run so the re-scan sees the
// same rules — using a different (or default-discovered) config could wrongly
// mark a still-snoozed file as clean and prune it.
export async function autoPruneFullRepo(cwd: string, configPath?: string): Promise<string[]> {
const baseline = loadBaseline(cwd);
if (Object.keys(baseline.files).length === 0) return [];
const scan = await run(cwd, { configPath, scopeFlags: { all: true }, applyBaseline: false });
const violating = new Set(scan.violations.map((v) => toRepoRelative(cwd, v.file)));
const { files, pruned } = reapBaseline(cwd, baseline, violating);
if (pruned.length > 0) saveBaseline(cwd, { version: BASELINE_VERSION, files });
return pruned;
}

export function autoPruneNotice(pruned: string[]): string {
const entries = pruned.length === 1 ? 'entry' : 'entries';
return `🧹 Auto-pruned ${String(pruned.length)} fixed baseline ${entries}: ${pruned.join(', ')}\n`;
}

// run() is a pure evaluator; auto-prune is the one side effect a full-repo run
// performs. A scoped run never mutates the baseline (a file can look clean only
// because its smell is outside the diff), so it is a guaranteed no-op.
export async function runWithAutoPrune(cwd: string, options: RunOptions): Promise<RunResult> {
const result = await run(cwd, options);
if (result.scopeMode !== 'all') return result;
const pruned = await autoPruneFullRepo(cwd, options.configPath);
if (pruned.length === 0) return result;
return { ...result, stdout: result.stdout + autoPruneNotice(pruned) };
}
14 changes: 3 additions & 11 deletions src/baseline/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
type BaselineFile,
} from './store.js';
import { toRepoRelative } from './filter.js';
import { reapBaseline } from './reap.js';

export interface CommandResult {
stdout: string;
Expand Down Expand Up @@ -118,21 +119,12 @@ export function baselineForget(cwd: string, paths: string[]): CommandResult {
return ok(`baseline forget: removed ${String(removed)} entry/entries\n`);
}

function shouldKeepEntry(cwd: string, relPath: string, violating: Set<string>): boolean {
if (!existsSync(join(cwd, relPath))) return false;
return violating.has(relPath);
}

export async function baselinePrune(cwd: string): Promise<CommandResult> {
const baseline = loadBaseline(cwd);
const violating = new Set(await collectViolatingFiles(cwd));
const kept = Object.entries(baseline.files).filter(([rel]) =>
shouldKeepEntry(cwd, rel, violating),
);
const files = Object.fromEntries(kept) as Record<string, BaselineEntry>;
const removed = Object.keys(baseline.files).length - kept.length;
const { files, pruned } = reapBaseline(cwd, baseline, violating);
saveBaseline(cwd, { version: BASELINE_VERSION, files });
return ok(`baseline prune: removed ${String(removed)} entry/entries\n`);
return ok(`baseline prune: removed ${String(pruned.length)} entry/entries\n`);
}

type EntryState = 'current' | 'stale-changed' | 'stale-missing';
Expand Down
26 changes: 26 additions & 0 deletions src/baseline/reap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import type { BaselineEntry, BaselineFile } from './store.js';

export interface ReapResult {
files: Record<string, BaselineEntry>;
pruned: string[];
}

function shouldKeep(cwd: string, relPath: string, violating: Set<string>): boolean {
if (!existsSync(join(cwd, relPath))) return false;
return violating.has(relPath);
}

// The one reaper shared by manual `baseline prune` and full-repo auto-prune:
// drop an entry whose file is gone, or present but no longer in the violating
// set (the smell was fixed). `violating` must come from a baseline-free scan.
export function reapBaseline(cwd: string, baseline: BaselineFile, violating: Set<string>): ReapResult {
const files: Record<string, BaselineEntry> = {};
const pruned: string[] = [];
for (const [rel, entry] of Object.entries(baseline.files)) {
if (shouldKeep(cwd, rel, violating)) files[rel] = entry;
else pruned.push(rel);
}
return { files, pruned };
}
4 changes: 2 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import { Command, CommanderError, Option } from 'commander';
import { run } from './runner.js';
import { runWithAutoPrune } from './baseline/auto-prune.js';
import { registerBaselineCommands } from './cli/baseline-commands.js';
import { registerInitCommand } from './cli/init-command.js';
import type { ScopeFlags } from './git/resolve-scope.js';
Expand Down Expand Up @@ -47,7 +47,7 @@ function toScopeFlags(opts: CliOptions): ScopeFlags {
async function executeRun(opts: CliOptions): Promise<void> {
const configPath = opts.config !== undefined ? resolve(process.cwd(), opts.config) : undefined;
const scopeFlags = toScopeFlags(opts);
const result = await run(process.cwd(), { configPath, scopeFlags });
const result = await runWithAutoPrune(process.cwd(), { configPath, scopeFlags });
process.stdout.write(result.stdout);
for (const line of result.stderr) process.stderr.write(`${line}\n`);
process.exitCode = result.exitCode;
Expand Down
20 changes: 20 additions & 0 deletions src/rule-files.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { relative } from 'node:path';
import picomatch from 'picomatch';
import type { Rule } from './types.js';

function buildMatcher(patterns: string[] | undefined): ((_path: string) => boolean) | null {
if (!patterns || patterns.length === 0) return null;
return picomatch(patterns);
}

export function filterFilesForRule(rule: Rule, files: string[], cwd: string): string[] {
const includeMatcher = buildMatcher(rule.include);
const excludeMatcher = buildMatcher(rule.exclude);
if (!includeMatcher && !excludeMatcher) return files;
return files.filter((file) => {
const rel = relative(cwd, file);
if (includeMatcher && !includeMatcher(rel)) return false;
if (excludeMatcher && excludeMatcher(rel)) return false;
return true;
});
}
30 changes: 7 additions & 23 deletions src/runner.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { dirname, isAbsolute, relative, resolve } from 'node:path';
import picomatch from 'picomatch';
import { dirname, isAbsolute, resolve } from 'node:path';
import { filterFilesForRule } from './rule-files.js';
import { discoverFiles } from './discover.js';
import { loadConfig, loadConfigFromPath, RULES_DEPRECATION } from './config/load.js';
import { buildRules } from './rules/registry.js';
import { lookupPrompt } from './prompts/registry.js';
import { resolvePackagedDir } from './prompts/packaged-dir.js';
import { resolveScope, type ResolvedScope, type ScopeFlags } from './git/resolve-scope.js';
import { resolveScope, type ResolvedScope, type ScopeFlags, type ScopeMode } from './git/resolve-scope.js';
import { loadBaseline, type BaselineFile } from './baseline/store.js';
import { partitionBySnooze } from './baseline/filter.js';
import { createSnoozeIndex, type SnoozeIndex } from './baseline/snooze-index.js';
Expand All @@ -20,14 +20,15 @@ import type { Rule, Violation } from './types.js';

const COMMENT_SMELL = 'non-essential-comment';

interface RunResult {
export interface RunResult {
stdout: string;
stderr: string[];
exitCode: number;
violations: Violation[];
scopeMode: ScopeMode;
}

interface RunOptions {
export interface RunOptions {
configPath?: string;
scopeFlags?: ScopeFlags;
applyBaseline?: boolean;
Expand All @@ -44,23 +45,6 @@ interface RunContext {
configWarnings: string[];
}

function buildMatcher(patterns: string[] | undefined): ((_path: string) => boolean) | null {
if (!patterns || patterns.length === 0) return null;
return picomatch(patterns);
}

function filterFilesForRule(rule: Rule, files: string[], cwd: string): string[] {
const includeMatcher = buildMatcher(rule.include);
const excludeMatcher = buildMatcher(rule.exclude);
if (!includeMatcher && !excludeMatcher) return files;
return files.filter((file) => {
const rel = relative(cwd, file);
if (includeMatcher && !includeMatcher(rel)) return false;
if (excludeMatcher && excludeMatcher(rel)) return false;
return true;
});
}

function applyScopeToRule(rule: Rule, files: string[], scope: ResolvedScope): string[] {
if (!rule.changedFilesOnly) return files;
const changed = scope.changedFiles;
Expand Down Expand Up @@ -181,5 +165,5 @@ export async function run(cwd: string, options: RunOptions = {}): Promise<RunRes
const mapped = mapIssues(violations.map(violationToIssue), buildRouting(rules), dirs);
const rendered = await guide({ result: mapped, dirs, cwd });
const stderr = [...ctx.configWarnings, ...detected.notices];
return { stdout: rendered.stdout, exitCode: rendered.exitCode, violations, stderr };
return { stdout: rendered.stdout, exitCode: rendered.exitCode, violations, stderr, scopeMode: ctx.scope.mode };
}
0