Skip to content

chore: fix 67 ruff violations across SDK (unblock CI)#103

Merged
Gradata merged 6 commits intomainfrom
chore/ruff-cleanup
Apr 17, 2026
Merged

chore: fix 67 ruff violations across SDK (unblock CI)#103
Gradata merged 6 commits intomainfrom
chore/ruff-cleanup

Conversation

@Gradata
Copy link
Copy Markdown
Owner

@Gradata Gradata commented Apr 17, 2026

Summary

Key changes

  • enhancements/self_improvement/__init__.py — add __all__ to re-export hub (silences 45 F401)
  • _file_lock.pycontextlib.suppress(OSError) replaces 2 try/except/pass
  • _events.py — collapse nested with open / with platform_lock into single-line
  • rule_enforcement.py — simplify boolean return
  • _graduation.py — combine nested if in domain filter
  • rule_engine/_models.py — move Lesson import into TYPE_CHECKING
  • rule_engine/__init__.py — sort __all__

Test plan

  • ruff check src/gradata/ → all checks passed
  • pytest tests/ → 3670 passed, 21 skipped, 2 xfailed
  • Pre-existing flaky Windows cp1252 test_cli_export_writes_cursorrules is unrelated

Generated with Gradata

Gradata and others added 6 commits April 16, 2026 23:57
…ompts

Two measured waste eliminations:

1. inject_brain_rules: mandatory_reminder block restated every mandatory
   rule verbatim in a recency tag. mandatory_block already places them in
   primacy position — the reminder was defensive redundancy costing
   ~50-200 tok/session per mandatory rule.

2. context_inject: MIN_MESSAGE_LEN raised 10 → 60 to skip brain FTS
   search on trivial follow-ups ("ok", "yes", "continue"). Previous
   threshold only filtered 1-9 char messages, causing ~400 tok of
   wasted context per ack-style reply.

Council audit (adversarial, synthesized from Skeptic + Architect +
Pragmatist) found my earlier measurement methodology used synthetic
inputs that masked real per-operation costs. Real heavy session
(10 prompts, 30 edits, 5 agents) accumulates ~9.6K gradata tokens;
context_inject alone can contribute 3.5K when prompts are substantive.

Tests: 2884 passed, 1 preexisting cp1252 Windows unicode failure
in test_rule_to_hook (unrelated to injection).

Co-Authored-By: Gradata <noreply@gradata.ai>
…imits

Rule_enforcement was re-injecting SessionStart rules on every Write/Edit,
costing ~165 tok/edit for zero added primacy value. Default it off behind
GRADATA_RULE_ENFORCEMENT=1 opt-in for ablation.

Also add env knobs for tuning injection volume without redeploying:
- context_inject: GRADATA_CONTEXT_INJECT kill switch + MIN_MESSAGE_LEN
  raised 60 -> 100 so ack-style replies skip FTS cost
- inject_brain_rules: GRADATA_MAX_RULES, GRADATA_MIN_CONFIDENCE,
  GRADATA_MAX_META_RULES for tuning SessionStart payload

Tests updated to opt into rule_enforcement where they exercise the hook
and to use a >=100 char message for context_inject.

Co-Authored-By: Gradata <noreply@gradata.ai>
Telemetry showed 10 SessionStart events in a long session re-injected
1.9KB each (~3.7k tokens total) — duplicative because the compact summary
already carries rules from the prior session, and the new session's
primacy slot is consumed by that summary.

Skip inject_brain_rules when source is 'compact' or 'resume'. Opt back
in with GRADATA_INJECT_ON_COMPACT=1 for ablation.

Co-Authored-By: Gradata <noreply@gradata.ai>
…d metas

When a meta-rule is injected, its source_lesson_ids are added to a mutex
set; individual RULE/PATTERN leaves whose _lesson_id() is in that set are
skipped so the principle isn't double-injected as both the meta and its
concrete leaves.

Freed slots get refilled: rank_rules is now called with a 3x overshoot
so the render loop has candidates beyond the MAX_RULES cap; the cap is
enforced at render time (cluster_lines + individual_lines <= MAX_RULES)
rather than at rank time.

On current brain: 1822B -> 1319B per SessionStart (27% smaller), and
leaf categories diversify from {LEADS, DEMO_PREP, DRAFTING} to
{DRAFTING, TONE, DATA_INTEGRITY, ARCHITECTURE, CODE} while the LEADS +
DEMO_PREP principles still land via metas.

Opt-out: GRADATA_META_RULE_MUTEX=0 for ablation. Mirrors the existing
cluster-vs-meta mutex pattern (meta_covered_categories).

Co-Authored-By: Gradata <noreply@gradata.ai>
Fixes all ruff lint errors on main that were blocking CI:
- F401 unused imports: add __all__ to self_improvement/__init__.py
  re-export hub
- SIM105 try/except/pass -> contextlib.suppress in _file_lock.py
- SIM102 collapse nested if in _graduation domain-filter path
- SIM103 simplify boolean return in rule_enforcement.py
- SIM117 combine nested `with` in _events._locked_append_many
- RUF022 sort __all__ in rules/rule_engine/__init__.py (unsafe-fix)
- TC001 move Lesson import into TYPE_CHECKING in rule_engine/_models.py
- UP037 remove quotes from type annotations

No behavior changes. 3670 tests pass; the flaky Windows cp1252
test_cli_export_writes_cursorrules remains pre-existing and
unrelated.

Co-Authored-By: Gradata <noreply@gradata.ai>
Copy link
Copy Markdown

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gradata has reached the 50-review limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 17, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5a2d6f42-e6ca-4da6-8bb9-23a784d45ca6

📥 Commits

Reviewing files that changed from the base of the PR and between cedd97a and 9c50b6d.

📒 Files selected for processing (15)
  • src/gradata/_encryption.py
  • src/gradata/_events.py
  • src/gradata/_file_lock.py
  • src/gradata/cli.py
  • src/gradata/enhancements/behavioral_extractor.py
  • src/gradata/enhancements/llm_synthesizer.py
  • src/gradata/enhancements/self_improvement/__init__.py
  • src/gradata/enhancements/self_improvement/_confidence.py
  • src/gradata/hooks/dispatch_post.py
  • src/gradata/hooks/rule_enforcement.py
  • src/gradata/middleware/_core.py
  • src/gradata/rules/rule_engine/__init__.py
  • src/gradata/rules/rule_engine/_formatting.py
  • src/gradata/rules/rule_engine/_models.py
  • src/gradata/rules/rule_engine/_scoring.py
💤 Files with no reviewable changes (8)
  • src/gradata/enhancements/behavioral_extractor.py
  • src/gradata/middleware/_core.py
  • src/gradata/enhancements/llm_synthesizer.py
  • src/gradata/_encryption.py
  • src/gradata/enhancements/self_improvement/_confidence.py
  • src/gradata/rules/rule_engine/_scoring.py
  • src/gradata/cli.py
  • src/gradata/rules/rule_engine/_formatting.py
📜 Recent review details
🧰 Additional context used
📓 Path-based instructions (2)
src/gradata/**/*.py

⚙️ CodeRabbit configuration file

src/gradata/**/*.py: This is the core SDK. Check for: type safety (from future import annotations required), no print()
statements (use logging), all functions accepting BrainContext where DB access occurs, no hardcoded paths. Severity
scoring must clamp to [0,1]. Confidence values must be in [0.0, 1.0].

Files:

  • src/gradata/rules/rule_engine/_models.py
  • src/gradata/_events.py
  • src/gradata/_file_lock.py
  • src/gradata/hooks/dispatch_post.py
  • src/gradata/hooks/rule_enforcement.py
  • src/gradata/enhancements/self_improvement/__init__.py
  • src/gradata/rules/rule_engine/__init__.py
src/gradata/hooks/**

⚙️ CodeRabbit configuration file

src/gradata/hooks/**: JavaScript hooks for Claude Code integration. Check for: no shell injection (no execSync with user
input), temp files must use per-user subdirectory, HTTP calls must have timeouts, errors must be silent (never block
the tool chain).

Files:

  • src/gradata/hooks/dispatch_post.py
  • src/gradata/hooks/rule_enforcement.py
🔇 Additional comments (10)
src/gradata/hooks/rule_enforcement.py (1)

98-98: Boolean simplification is correct and preserves behavior.

Line 98 keeps the same domain-mismatch semantics while making the return path clearer.

src/gradata/hooks/dispatch_post.py (1)

71-72: Result collection update is safe and idiomatic.

Line 71 preserves truthy-only concatenation behavior while simplifying the key check.

src/gradata/enhancements/self_improvement/__init__.py (2)

24-34: Explicit type re-exports are correct and preserve import compatibility.

This keeps from gradata.enhancements.self_improvement import ... stable for core shared types and transition.


80-129: __all__ definition is well-scoped and consistent with imported symbols.

Good explicit public surface declaration; this cleanly addresses linting without changing behavior.

src/gradata/rules/rule_engine/_models.py (1)

10-13: LGTM! Correct TYPE_CHECKING pattern.

The conditional import of Lesson for type checking only is safe and follows best practices. With from __future__ import annotations (line 7), the type annotation on line 32 becomes a string at runtime, and dataclasses don't validate types at runtime, so the actual Lesson class is only needed for static type checkers.

src/gradata/rules/rule_engine/__init__.py (1)

64-110: LGTM! all sorted correctly.

The alphabetical sorting of __all__ satisfies the RUF022 lint rule. The section comments (# engine, # scoring, etc.) serve as organizational markers but don't strictly group items by their source module—for instance, _ELIGIBLE_STATES (imported from _engine at line 17) appears after the # scoring comment. This is minor and doesn't affect functionality.

src/gradata/_file_lock.py (3)

45-46: LGTM! Import modernization aligns with PEP 585.

Moving Generator to collections.abc follows Python 3.9+ best practices. The change is correct and improves compatibility with modern type checking.


113-114: LGTM! Cleaner exception handling with contextlib.suppress.

Replacing try/except OSError: pass with contextlib.suppress(OSError) is more idiomatic and aligns with ruff SIM105. The behavior is preserved—unlock errors are silently ignored as intended.


157-158: LGTM! Consistent refactor across platform implementations.

Applying the same contextlib.suppress(OSError) pattern to the POSIX unlock maintains symmetry with the Windows implementation. Both platforms now use idiomatic error handling.

src/gradata/_events.py (1)

48-53: LGTM! Combining context managers improves readability.

The refactor from nested with statements to a single multi-context with statement is semantically equivalent and cleaner. The exit order is preserved: platform_lock exits first (unlocking the file in its finally block), then the file handle closes. This matches ruff SIM117.


📝 Walkthrough

Ruff Lint Cleanup

  • Fixed 67 ruff violations across 15 files (F401, SIM102/103/105/117, RUF022, TC001, UP037) to unblock CI; no behavioral changes
  • Removed unused imports (os, typing.Generator) from multiple modules (_encryption.py, llm_synthesizer.py, _core.py, cli.py, _scoring.py)
  • Added __all__ export list to enhancements/self_improvement/__init__.py (61 lines) to explicitly enumerate public API and silence F401 violations for re-exported symbols
  • Simplified error handling: replaced try/except OSError: pass with contextlib.suppress(OSError) in _file_lock.py
  • Combined nested context managers in _events.py: merged with open() and with platform_lock() into single-line context manager
  • Moved runtime imports to TYPE_CHECKING: shifted Lesson import to conditional block in rule_engine/_models.py to reduce startup dependencies
  • Simplified boolean logic: replaced explicit conditional return with direct negation in rule_enforcement.py
  • Reordered __all__ in rule_engine/init.py for consistency; reorganized exports into commented sections (engine, scoring, formatting)
  • Minor whitespace cleanup: removed extraneous blank lines in behavioral_extractor.py, _formatting.py
  • Test results: ruff check passed; pytest: 3,670 passed, 21 skipped, 2 xfailed

Walkthrough

This PR performs code quality improvements across the gradata codebase: removing unused imports, refactoring context managers and exception handling, converting a runtime import to TYPE_CHECKING guards, adding explicit __all__ declarations, reordering exported symbols, and simplifying logic conditions.

Changes

Cohort / File(s) Summary
Unused Import Cleanup
src/gradata/_encryption.py, src/gradata/enhancements/llm_synthesizer.py, src/gradata/middleware/_core.py, src/gradata/cli.py, src/gradata/enhancements/self_improvement/_confidence.py
Removed unused os imports and simplified from gradata._types imports. No functional behavior changed.
Context Manager & Exception Handling Refactoring
src/gradata/_events.py, src/gradata/_file_lock.py
Consolidated nested with statements into single context manager; replaced try/except OSError: pass with contextlib.suppress(OSError). Behavior preserved.
Type Import Reorganization
src/gradata/_file_lock.py, src/gradata/rules/rule_engine/_models.py, src/gradata/rules/rule_engine/_scoring.py
Moved Generator from typing to collections.abc; converted Lesson import to TYPE_CHECKING guard; removed unused TYPE_CHECKING block.
API Export Declaration
src/gradata/enhancements/self_improvement/__init__.py
Added explicit __all__ list enumerating public re-exports including constants, functions, and types from submodules.
Export Reordering
src/gradata/rules/rule_engine/__init__.py
Reorganized __all__ entries into logical sections (engine, scoring, formatting); no symbols added or removed.
Logic Refactoring
src/gradata/hooks/dispatch_post.py, src/gradata/hooks/rule_enforcement.py
Simplified result-collection check using .get() instead of membership test; replaced conditional early-return with boolean negation expression.
Formatting Cleanup
src/gradata/enhancements/behavioral_extractor.py, src/gradata/rules/rule_engine/_formatting.py
Removed extra blank lines between sections.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested labels

refactor

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'chore: fix 67 ruff violations across SDK (unblock CI)' directly and accurately summarizes the main change: fixing ruff lint violations to unblock CI.
Description check ✅ Passed The description comprehensively explains the changes: 67 ruff lint violations fixed across 15 files with no behavior changes, lists key files modified, and includes test results confirming the fixes work correctly.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/ruff-cleanup

Comment @coderabbitai help to get the list of available commands and usage tips.

@Gradata Gradata merged commit ffb3060 into main Apr 17, 2026
4 of 17 checks passed
@Gradata Gradata deleted the chore/ruff-cleanup branch April 17, 2026 15:37
Gradata added a commit that referenced this pull request Apr 19, 2026
Covers: gradata.patterns deprecation (remove in v0.8.0), Alert dedup (#109),
Meta-Harness A-D, multi-tenant SDK (#102), BM25 JIT ranking (#101),
gradata seed/mine CLI, rule_verifier wiring, security hardening, and 67+66
ruff-violation fixes (#100, #103).

Co-Authored-By: Gradata <noreply@gradata.ai>
Gradata added a commit that referenced this pull request Apr 19, 2026
Covers: gradata.patterns deprecation (remove in v0.8.0), Alert dedup (#109),
Meta-Harness A-D, multi-tenant SDK (#102), BM25 JIT ranking (#101),
gradata seed/mine CLI, rule_verifier wiring, security hardening, and 67+66
ruff-violation fixes (#100, #103).

Co-Authored-By: Gradata <noreply@gradata.ai>
Gradata added a commit that referenced this pull request Apr 20, 2026
* docs: v0.6.1 changelog entry covering post-v0.6.0 work through PR #114

Covers: gradata.patterns deprecation (remove in v0.8.0), Alert dedup (#109),
Meta-Harness A-D, multi-tenant SDK (#102), BM25 JIT ranking (#101),
gradata seed/mine CLI, rule_verifier wiring, security hardening, and 67+66
ruff-violation fixes (#100, #103).

Co-Authored-By: Gradata <noreply@gradata.ai>

* docs(changelog): qualify env-centralization claim

CodeRabbit flagged that GRADATA_RULE_VERIFIER is still read directly in
rule_pipeline.py. Weaken the claim rather than block on the migration.

Co-Authored-By: Gradata <noreply@gradata.ai>

---------

Co-authored-by: Gradata <noreply@gradata.ai>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant