Changelog#
All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
Unreleased#
2.18.1 - 2026-11-16#
Added#
sync-developmentcan no longer deadlock silently (#277). After the 2.18.0 release the workflow refused to resetdevelopmentand reported success, so the branches sat diverged for a whole release cycle with the only trace a workflow annotation.developmentkept the prerelease version and lacked seven fixes that were onmain; merging further work into it and cutting the next release from it would have regressed them.
Worse, both remedies its own error message named were already satisfied. "Land that work on main" - it had landed, as a rebase, so the SHAs differed and the guard could not see them. "Dispatch this workflow" - dispatching ran the identical job with the identical guard, and the workflow declared no inputs, so there was nothing to override. It took a manual archive plus a force-push past branch protection.
Three changes, all of them in this release:
- A refusal now fails the job. It exited 0, which in the Actions list is indistinguishable from a sync that worked. A refusal always needs a human to act, so it is actionable by definition and belongs red.
workflow_dispatchgained aforceinput, which is the escape hatch the refusal message had been promising all along. It still archivesdevelopment's tip toarchive/development-<sha>before resetting, so it stays recoverable.- The refusal message now says what actually works. It points at
force, and atgit cherry origin/main origin/developmentfor judging whetherforceis safe, with the two caveats that matter: it strips whitespace, so on Python it cannot tell an indentation change apart, and a patch-id proves a patch was once in the history rather than thatmaincarries it now. A human can check the second one; the workflow deliberately does not decide on it.
A content shortcut was built for this, and then removed. Worth recording rather than quietly dropping, because the idea is attractive enough that someone will propose it again. A rebase-merged release leaves development's commits on main under different SHAs, so patch-id equality looks like it proves the reset lossless, and the deadlock above is exactly the case it would settle. It shipped briefly as a permission on top of the version check - all-match approves, anything else falls through - on the reasoning that it could then only approve a reset the guard would otherwise refuse. Two review findings sank it.
First, git cherry compares patch-ids with whitespace stripped (git patch-id's default) and offers no way to change it; patchid.verbatim in the config does not reach it, on git 2.50. This is a Python project, so two commits differing only in indentation are different behaviour and identical patches. That one is fixable, with git log -p --no-prefix | git patch-id --verbatim (CodeAnt on #283).
Second, and fatally: a patch-id says a patch once existed in main's history, never that main's tree carries it now. An apply-then-revert on main leaves the id in place, so a development holding that patch read as "already upstream" and the reset discarded a change main no longer had. Excluding patches whose exact inverse also appears catches the simple case; a context change between the apply and the revert makes the inverse differ, and the exclusion misses it. Both halves were demonstrated in a scratch repository rather than argued about (CodeRabbit on #284).
That second one does not close, for the same structural reason the current-state predicates fail: development legitimately holds content main never had - the rcN version string, [Unreleased] entries main has since dated - so it is never a content subset, and no sound current-content proof can approve the cases the shortcut existed for. Every patch-id approximation therefore keeps a residual where it can silently approve discarding work, which is the one thing the file exists to prevent.
Nothing replaces it. A refusal is loud now and force clears it in one click, archiving first, so the judgement a heuristic cannot make sits with a human who can also check whether main's current tree has the change. The reasoning is recorded in the workflow header so the shortcut is not rebuilt from scratch.
- RELEASE_PAT is gated on an environment, and the CI gates that were documented but not configured are now real (#282). Three findings, one of them embarrassing.
sync-development.yml's job now runs under a sync-write environment whose required reviewer must approve before the job starts, and therefore before any code in it can reach RELEASE_PAT. workflow_dispatch runs a workflow file from the selected ref, so anyone with write access could dispatch a modified copy of that job from a branch and be handed the token; no guard written inside the workflow can stop that, since the same person can delete the guard, and an environment approval is the one thing outside the workflow's control. Raised by CodeAnt on #281 and correct. Two limits stated rather than glossed: the token stays a repository secret because publish.yml's build job needs it and is deliberately left ungated so releases do not pause, and publish.yml has its own workflow_dispatch, so that route is still open; and the ordinary post-release sync now waits for an approval, so it is no longer hands-off.
The pypi environment had no protection rules at all. publish.yml has described it as "reviewer-gated - a human approves before the production upload (the safety valve)" since release automation landed, and SECURITY.md and the contributor docs repeat it. It was never configured: both pypi and pypi-rc carried an empty protection_rules, so every final release published to PyPI unattended and the two environments differed only in name. A required reviewer is now set on pypi and deliberately not on pypi-rc, which is what the comment always claimed. Nothing in the workflows changed; the wiring was already right and only the setting was missing.
CHANGELOG history is a required check, on main and on development, which it was not: the #278 guard could go red while a merge went through anyway, which is most of its value gone. Making it required needed a fix first. The job carried a job-level if: github.event_name == 'pull_request', so on a release branch (where ci.yml runs on the push as well as on the pull request) one context name reported two different conclusions for the same commit - skipped from the push, success from the pull request. Harmless while advisory, ambiguous the moment it gates a merge. The condition moved to each step, so the job reports success either way with nothing heavy run on a push. Test / Windows / Python 3.12 was added to the required set at the same time, for the same reason: it had been able to fail without blocking since the day it was introduced.
- CI refuses a change that edits the notes of an already-released version (#278). Rebasing a feature branch across a release silently rewrites published release notes, and it never conflicts, so nothing asks. A branch's entries sit under
## [Unreleased]->### Fixed; the release workflow renames that heading to## [X.Y.Z] - <date>and inserts a fresh empty[Unreleased]; a later rebase sees### Fixedeither side with identical surrounding context and merges the entries into the dated section.
That happened four times in a single day - on the branches for #266, #270, #275 and #276 - and every instance was caught only by diffing the dated sections by hand afterwards. Nothing in the gate could see it: the rebase reported success, the suite passed, and mkdocs build --strict passed. Had one merged, a tagged release on PyPI would have grown notes describing work it did not contain.
The job reads the base branch name through an env entry rather than inline ${{ }} expansion, so a branch name carrying shell metacharacters cannot be spliced into the script before bash sees a quote (template injection; zizmor flags it, and sync-development.yml already reads inputs.force this way for the same reason).
scripts/check_changelog_history.py now asserts that every dated section present in both the base branch and the head is byte-identical, including the compare-link footers (those were corrupted once by the same mechanism). Adding a new dated section stays allowed, because that is what the release workflow does, and [Unreleased] stays freely editable. It runs as a CHANGELOG history job on pull requests only, since a push has no base to compare against.
Three holes in the guard itself, found in review and fixed before it gated anything. Worth recording because two of them would have made it worse than useless:
- It compared against the base tip, which fails valid pull requests. When a release lands on the base while a branch is open, the base gains a dated section the branch has never seen, and the deleted-section check reported the branch as having lost published notes - wrong, and actively misleading, since the branch is merely out of date. It now compares against the merge base: the newest state the branch actually diverged from, so a later release is irrelevant while any edit to a section that existed at the branch point is still caught. Pinned by a test, and verified by mutation: restoring the base-tip comparison fails it.
- Duplicate detection was quadratic.
list.countper heading rescanned the whole list, so a changelog with many headings cost quadratic CI time on PR-controlled input; it usesCounternow. - A duplicate release heading hid an edit. Both headings collapse to one key and the last copy wins, so an edited first copy compared equal and passed. A changelog has no legitimate duplicate release heading, so one is now refused outright with the version named.
- Reading the base blob could raise instead of reporting.
text=Truedecodes, so an invalid blob raisedUnicodeDecodeErrorout of the checker. It now decodes strictly and reports "cannot tell". An intermediate fix usederrors="replace", which was worse than the crash it removed: every invalid byte becomes the same U+FFFD, so two different undecodable bytes compared equal and an edit between them slipped through silently (b"x\xff"andb"x\xfe"are distinct bytes and identical after replacement). Refusing to guess is the honest answer, and the third exit state exists so that does not have to be forced into a pass or a fail.
A fourth report - that a removed compare-link footer slips through - turned out not to hold: footers sit inside the last dated section's body, so removing one changes that section and is already caught. Verified rather than assumed, and left alone.
A deleted or renamed dated heading counts too, not only an edited one. The first implementation compared only versions present in both files, so removing a released section and its notes was never looked at and passed - and a deletion is strictly worse than an edit, since an edit at least leaves something to compare (caught in review on #279).
Three exit states rather than two, deliberately: 0 intact, 1 a released section was edited or lost, and 2 "could not tell" (an unreadable base ref, a missing or undecodable file). Collapsing the third into 0 would let a misconfigured job silently stop guarding, which is the exact failure mode the check exists to remove; raising a traceback instead would be nearly as bad, since either way CI stops reporting what it was added for.
Changed#
- CI: bump
anthropics/claude-code-actionv1.0.269 -> v1.0.271 (folded in from Dependabot PR #285). Still SHA-pinned. The SHA was verified against its dereferenced tag object, since these tags are annotated and the naive ref lookup returns the tag object rather than the commit:refs/tags/v1.0.271dereferences to commit4fa93a8, which is what the PR proposed, and our outgoing pin61a9c27is whatv1.0.269dereferences to. The three upstream commits in the range touch only the bundled Claude Code / Agent SDK version (2.1.319 -> 2.1.322), the lockfiles, and upstream's own release workflow; no action input was added, renamed or removed, soanthropic_api_key,promptandclaude_argsinclaude-review.ymlare unaffected. Workflow only - nothing in the published wheel changes.
Deliberately not taken to the current latest (v1.0.275), reversing the previous round's habit. The 2.17.2 bump went straight to the newest tag so the next Dependabot round would have nothing to raise, which was safe then because the whole range was version strings. It is not safe here: v1.0.273 is published by upstream as "v1.0.273 (breaking changes)" and carries six of them, including restrict_untrusted_prs (a new input defaulting to true that denies code-running commands on pull requests from authors without write access) and a switch to running sessions in auto mode by default. Several look like improvements worth having, but adopting a breaking change to the review action is a deliberate decision, not something to absorb silently into a release branch heading for main. Dependabot will re-raise v1.0.275, which is the right place to weigh it.
Fixed#
- SAFE302 reports a Go package-level
varonly when it is actually mutated (#204). The rule fired on every package-levelvar, which reported a construct rather than the hazard it names. Go'sconstaccepts only compile-time basic values, so a package-level slice, map, struct or-ldflags-written string cannot be aconst: the rule was flagging an idiom with no alternative. Measured on fzf, 120 findings with 97% in library code, the largest non-structural default code in the project.
The result was the wrong way round, which is the part that made it actively harmful:
// a.go -> 2 findings, no hazard possible
var version = "dev" // written by -ldflags; const impossible
var defaultShapes = []string{"round", "sharp"} // a slice cannot be const at all
// b.go -> 1 finding, the real hazard
var counter int
func Inc() { counter++ }
func Reset() { counter = 0 }
The harmless file outscored the hazardous one, so triage by count pointed away from the problem. On that example the rule now reports counter alone.
Five shapes count as mutation, each confirmed against the grammar: assignment (x = v, x += v), increment or decrement, a write to the var's contents (shapes[0] = v, cfg.Field = v, which never rebind the name and would have been missed by a bare-identifier check), address-of (&x, which hands mutation rights to whoever receives the pointer even though no write is visible), and the mutating builtins delete(m, k) / clear(m) / copy(dst, src) - caught in review on #276, since those rebind nothing and so appeared in none of the other four. A package-level map emptied by delete is shared mutable state just as much as one reassigned. A sentinel error (var ErrNF = errors.New(...)) is never reassigned and is now clean - the old test suite asserted that sentinels should fire, which was documenting the defect.
Three limits, stated rather than left to be discovered. Mutation is detected per file, as everything in safelint is, so a var written only from another file in the same package is missed. The detector is not scope-aware, so a function-local x := 1; x = 2 keeps a package-level x reporting - the conservative direction, preserving the old behaviour for that name rather than inventing a false negative, but it means a finding is not proof the package binding itself was written. And a write through an arbitrary function's argument is not recognised: only the builtins are, because anything further needs interprocedural analysis safelint does not do anywhere.
Same design mistake as #201 (SAFE305 on every JavaScript var) and fixed the same way: report where the hazard is observable, and name it in the message. Bundled skill content changed: run safelint skill install --force.
- SAFE000 on a Rust
str!/i32!macro now names the real cause instead of blaming your syntax (#174).tree-sitter-rustcannot parse a macro whose name is a primitive type keyword: the lexer resolves the word as a type token before it can be a macro identifier, and<primitive> !is not a valid invocation in the grammar. The file gets aSAFE000and every rule reports nothing for it - worse than a false positive, because a false positive is visible and suppressible while this silently removes a file from analysis. Found on ruff, where 3 affected files sat among 6,066 findings.
Not obscure: str! is snapbox's inline-snapshot macro, so any crate using inline snapshots loses those files. Still unfixable by a dependency bump, which was checked rather than assumed: tree-sitter-rust 0.24.2 remains the latest release on PyPI and still fails.
So the message changed, not the parsing:
SAFE000 Parse error (syntax error) at line 2, column 23 - a macro named after a
primitive type (such as snapbox's `str!`) cannot be parsed by tree-sitter-rust, so
this file was NOT analysed; the code itself is valid Rust and there is nothing here to fix
This is per-cause, not per-language, which is the distinction 2.17.2 explicitly could not make. C and C++ carry an unconditional parse_error_hint because a parse failure there is routinely the preprocessor's doing. Rust cannot: most Rust parse failures genuinely are the user's mistake, so a blanket hint would excuse real errors. LanguageDefinition therefore gained parse_error_cause, a hook that inspects the tree and recognises one specific construct, and the advice now resolves in three tiers: recognised cause, then the language's blanket hint, then the generic "check syntax".
Every parse error in the file has to be this shape for the cause-specific wording to appear. Claiming it on a first match was wrong in both directions (caught in review on #275): with a genuine error earlier in the file, SAFE000 reports that line while the message said there was nothing to fix, and with the macro first the message is right about its own location but still tells the reader a broken file is fine. A file with a real syntax error as well now falls back to the generic advice, because "nothing here to fix" would be false there.
Detection covers all three delimiter forms, which recover differently (str![1] and str!(1) leave the bare ! as the error with the name beside it; str!{1} puts the name in the error node), and every primitive name. The opposite error - telling someone their broken code is fine - is what most of the new tests guard: an unbalanced paren, a missing semicolon, a stray brace, an unclosed string and a genuinely broken non-primitive macro all still get the generic advice, and string! / i32x4! are ordinary identifiers that parse fine.
Documented in docs/languages/rust.md under Limitations, and in the bundled Rust skill addendum, which tells an agent not to rewrite valid source to satisfy the parser and to count SAFE000 before calling a Rust project clean. Bundled skill content changed: run safelint skill install --force.
2.18.0 - 2026-11-07#
Added#
- The run summary now says how many files it could not analyse (#175). A parse failure removes a file from analysis entirely: one
SAFE000is emitted and then every rule skips it. The summary counted it infiles_checkedas though it had been examined, so a clean report over a tree where a quarter of the files were never read looked identical to a genuinely clean project. On the validation corpora the signal was invisible in practice: 3 parse errors among 6,066 findings on ruff, 46 among ~2,900 on superset, and 25-54% of files on real C/C++ projects (#206).
Pretty output gains one line, printed only when the count is non-zero:
It is deliberately a separate line rather than a clause on the summary, so it reads identically whether or not there were findings. The clean run is the case it exists for.
The count comes from a new LintResult.analysis_skipped flag, not from counting SAFE000 violations. That distinction is load-bearing: ignore = ["SAFE000"] is the documented way to silence parse noise and would have zeroed a counting-based implementation while the coverage gap remained. It also covers a file safelint could not read at all, which ran no rules either. A file that was excluded, or whose language is not registered, is not counted: nothing was attempted for it, so it is not lost coverage. That is why the field is analysis_skipped (default False) rather than a parsed flag defaulting True, which would have claimed a successful parse for files never opened.
Four causes count as not-analysed, not just a parse failure: a tree-sitter parse error, an unreadable file, one larger than max_file_size_bytes, and one refused before reading (a symlink escaping the tree, or a non-regular file such as a FIFO). The last three produce only a stderr warning and no violation at all, so the flag is the only place they can surface; counting them as analysed let files_analysed claim full coverage over a file never examined. A file that was excluded, or whose language is not registered, deliberately does not count: nothing was attempted, it is out of scope by configuration rather than lost, and counting it would make files_analysed meaningless on any project with an exclude list.
--format jsonreports per-language file counts and splits analysed from checked (#175, #196). Three newsummarykeys:
| Key | Meaning |
|---|---|
files_analysed |
files_checked - files_skipped, the number that rules actually ran against. This is the coverage number. |
files_skipped |
Files reached but not analysed. |
files_checked_by_language |
Sparse {language: count} map keyed by the names --language accepts. |
files_checked keeps its existing meaning (everything reached), so no consumer breaks. The per-language map is derived from the language registry via get_language_for_file, so all nine languages are covered with no per-language branching and a tenth would be too. It is sparse by choice: a language that contributed nothing is absent rather than present with a zero, so "absent means none read" is unambiguous.
This closes the false-clean route the validation harness works around by re-deriving safelint's own discovery rules in a second model, which is where five earlier defects came from (#192). A consumer can now distinguish "no findings in your Go" from "no Go was read".
SARIF deliberately does not carry these. It has no natural home for run-level counts, and a properties bag entry would be a safelint-specific extension no SARIF consumer reads; the parse failures are still present there as ordinary SAFE000 results. format_json / format_sarif take them as one optional coverage= argument of the new exported safelint.formatters.RunCoverage type, which keeps their existing public signature intact.
Bundled skill content changed: run safelint skill install --force. All 14 client files gained the new summary keys and, more importantly, an instruction not to report a clean run without checking files_skipped first. Their example headline Clean run: 12 files checked, no violations. was itself the false-clean claim this issue is about, and now reads files analysed with a second variant for when files were skipped.
Changed#
- CI now runs the test suite on Windows. One
windows-latestjob on Python 3.12 alongside the four Ubuntu jobs. Coverage stays enforced on the Ubuntu jobs only: a handful of tests are legitimately skipped on Windows (a filename carrying a control character cannot exist there, and the validation-harness fixtures are#!/bin/shscripts Windows cannot execute), so their lines never run and the percentage is structurally lower. Enforcing the same 97% threshold on both would force a choice between deleting honest skips and lowering the gate for everyone; the job is there to catch platform behaviour, which it does either way. safelint is full of path handling (test-dir membership, changed-set matching, symlink containment, drive letters) and an Ubuntu-only matrix structurally cannot see a bug in any of it, which is why #265 sat unreproducible. One Windows job rather than four: these bugs are platform-dependent, not Python-version-dependent, so a second Windows interpreter would mostly re-run the same assertions at twice the cost.
Fixed#
- Validation harness: ask the binary what it scanned instead of modelling it (#192).
_check_selection_has_filesguarded the one outcome the validation programme must never produce, a committed zero-findings report for source that was never examined, by re-deriving safelint's file discovery inside the harness: extension, excluded directory names, file-versus-directory, symlink-or-not. That second model drifted five separate times, each drift its own route to a false clean, and each found in review rather than by the check itself.
The project-wide eligibility model is deleted, not corrected: EXCLUDED_DIR_NAMES, _any_eligible, and _is_scannable's symlink and file-versus-directory guessing are gone. What replaced them cannot drift:
| Route to a false clean | Now caught by |
|---|---|
Wrong --lang |
summary.files_checked_by_language[lang] == 0, safelint's own per-language tally (new, #196) |
Files only under .venv/ or node_modules/ |
summary.files_checked == 0 (shipped 2.14.3) |
| A symlinked source file | summary.files_checked == 0 |
A directory named generated.py |
summary.files_checked == 0 |
Mistyped --include |
the harness, which is correct: --include is a harness-side filter safelint never sees, so no amount of asking the binary can reveal a typo in it |
The wrong---lang route is the one files_checked alone could never catch, because it counts every language: --lang rust against a Python repository reports a healthy positive count, filters every finding out by extension, and writes up scanned=N, findings=0. That is why this half waited on the per-language breakdown.
A missing files_checked_by_language degrades to "cannot check" rather than failing. The harness exists to validate a published release, which may predate the key, and the map is sparse by design, so "absent because old binary" and "absent because this language contributed nothing" are indistinguishable from the map alone. files_checked == 0 still guards an older binary. Pinned by a test, because treating absence as zero would have made the harness unusable against every earlier release.
EXTENSIONS stays: the harness needs it to filter findings by language regardless, and it is not a model of discovery.
One piece of mirroring survives, deliberately. SCANNER_EXCLUDED_DIR_NAMES (safelint's default-skipped directory names) is still needed by the --include pre-flight, and review on #273 showed why: without it an --include pointing only into .venv/ passed the pre-flight, the project-wide per-language tally stayed positive on source elsewhere, the findings filtered to empty, and the run would have been written up as clean for a subtree never examined. A sixth false-clean route, opened by the change that removed five. It is now pinned by a named regression test, and the drift risk is bounded to one question ("is this include pointing somewhere safelint ignores?") rather than spanning the whole eligibility model. safelint check --list-files is what would retire it.
- SAFE104
complexity: amatch/switchcounts once, not once per arm (#181). McCabe measures hand-written control flow, and a dispatch table is not that. The arms are value comparisons, or in Rust a compiler-checked exhaustive match: no fall-through, no ordering dependency, and adding a variant is a compile error rather than a silent gap. A twenty-arm lookup carries a cognitive load nearer 1 than 20.
Counting each arm made dispatch tables the dominant finding on real code. match_arm alone was 50% of every counted decision point across astral-sh/ty, and 54% of ruff's 656 SAFE104 findings fell to at or under the threshold once arms stopped counting individually, every one of them a lookup table where "split into smaller functions" was not applicable advice. The issue's headline example, a 13-arm string lookup, drops from 14 to 2.
A guarded arm keeps its surcharge, because it can fall through to a later arm, so exhaustiveness proves nothing about it: Rust's n if cond =>, Java 21's case Integer i when i > 0, and Python's case X if cond (counted as the ordinary if_clause it parses to). Verified against the grammars rather than assumed, since all three expose the guard differently: Rust on a condition field, Java as a child of type guard with no field name, Python as a guard field.
Applied to all nine languages, which also fixed an existing inconsistency. Rust, Go, Java, JavaScript, PHP and C counted every arm; Python counted its match as nothing at all, so the same dispatch table scored 0 in Python and N in Rust. Python now counts the construct like everywhere else, making it marginally stricter. docs/languages/python.md had claimed case added one, which was never true. A parametrised parity test covers all nine so a future language cannot quietly reintroduce per-arm counting for only some of them.
Genuinely branchy code is untouched: binary_like.rs fn fmt, reported at 27 and confirmed as real control flow, still fires. Bundled skill content changed: run safelint skill install --force.
-
Windows: an absolute
exclude_paths/extend_exclude_pathsentry silently excluded nothing. Found by the new Windows CI job on its first run, which is the whole argument for having it. Exclusion matches a path normalised withPath.as_posix()against the raw configured pattern, so any pattern carrying backslashes could never match:extend_exclude_paths = ["C:\\vendor"](and anything built withstr(Path(...)), the documented form) excluded nothing and the entire tree was linted anyway. Patterns are now folded to forward slashes on Windows, once at construction so both the file and directory-prune matchers are fixed together. Guarded to Windows because a backslash is a legitimate escape character in a POSIX glob, so folding everywhere would change documented Linux and macOS behaviour for a Windows-only problem. -
The validation harness could not run on Windows at all.
scripts/validate_real_world.pyimported the POSIX-onlyresourcemodule at the top of its measurement wrapper, so every harness invocation died withModuleNotFoundError: No module named 'resource'. The import is now defensive: the wrapper still measures wall time and still reports the run, and only the peak-RSS figure is unavailable. Dev tooling only, nothing in the published wheel. -
Windows path matching:
test_dirsmembership ignored case, contradicting the rest of safelint (#265). safelint compares paths two ways and they disagreed. Changed-set membership usesPath.__eq__, which case-folds on Windows, so two spellings of one path are the same file. Test-dir membership comparesPath.partstuples with raw string equality, which does not. On a case-insensitive filesystem atest_dirsentry ofpackages/core/src/testtherefore matched nothing when the directory on disk was spelledpackages/Core/src/Test, silently mis-scoping SAFE601missing_assertions, SAFE701test_existenceand SAFE702test_couplingacross the whole tree. The comparison now goes throughos.path.normcase, which is the identity function on POSIX, so Linux and macOS behaviour is unchanged (asserted, not assumed). -
A changed-file set safelint cannot match now warns instead of reading as "nothing changed" (#265). SAFE702 answers "did this file change?" by canonical-path equality. When the caller's spelling differs from the files being linted, the comparison finds nothing and the rule skips every file, which is indistinguishable from a clean run. That is the reported symptom: the same commit passed locally on Windows and failed SAFE702 on Linux CI for five branches running.
The trigger is deliberately "none of the changed paths exist" rather than "any is missing", because a commit that deletes files legitimately carries paths that are gone and warning per entry would be noise. One safelint: warning: line on stderr, never a failed run, per the project's typo-guard convention. The message names the likely cause: a drive-less rooted path is what Git Bash hands a wrapper on Windows, and Python there reports is_absolute() == False for it, so resolve() anchors it under the current drive and directory and it can never match the walker's path. The underlying comparison is unchanged; loosening it would trade a silent false negative for a silent false positive.
2.17.2 - 2026-11-07#
Changed#
- CI: bump
anthropics/claude-code-actionv1.0.264 -> v1.0.269 (folded in from Dependabot PR #267, which asked for v1.0.267; taken to the current latest so the next Dependabot round has nothing to raise). Still SHA-pinned. The SHA was verified against its dereferenced tag object, since these tags are annotated and the naive ref lookup returns the tag object rather than the commit:refs/tags/v1.0.269dereferences to commit61a9c27. The five upstream commits in the range touch only the bundled Claude Code / Agent SDK version (2.1.312 -> 2.1.319) plus lockfiles; no action input was added, renamed or removed, soanthropic_api_key,promptandclaude_argsinclaude-review.ymlare unaffected. Workflow only - nothing in the published wheel changes.
Fixed#
- SAFE000 on C and C++ no longer blames the user for valid code (#206).
Parse error (syntax error) at line 135, column 4 - check syntax near this locationwas wrong on both counts: the syntax is fine and there is nothing at that location to check. safelint parses the source as written and never runs the preprocessor, so ordinary C that a compiler accepts oncecpphas run is not standalone-valid to the parser:
// conditional compilation INSIDE an expression (curl, block_ip.c)
if(ip->maskbits <= 0 ||
#ifdef AF_INET6
(ip->family == AF_INET6 && ip->maskbits > 128) ||
#endif
ip->maskbits > 32)
// a function-like macro standing in for parameters (curl, evhiperfifo.c)
static void timer_cb(EV_P_ struct ev_timer *w, int revents)
C and C++ now carry their own parse-error advice, naming the preprocessor as the likely cause. LanguageDefinition gained an optional parse_error_hint; it defaults to None, so every other language keeps the generic wording - Python's parse errors really are syntax errors.
The hint is per-language, not per-cause, and that limit is recorded in a test rather than glossed: safelint cannot tell valid-but-unpreprocessed code from a genuine typo, because both arrive as the same ERROR node, so a real mistake now also reads as a possible preprocessor issue. Naming the likelier cause is still the better default at the measured rate.
- The C and C++ parse-coverage limit is now documented with measurements (#206). The language pages listed C and C++ as supported without qualification, so a clean run read as a clean project. On stock defaults, a quarter to a half of the files in four widely deployed codebases fail to parse and are therefore dropped from every other rule: curl
61a31e0277/1101 (25%), redisb540ca4351/845 (42%), fmt4afd0e443/79 (54%), leveldb7ee830d60/133 (45%). Headers fare worst, which is why the two C++ projects come out above the two C ones.
Re-measuring also corrected the figures in the issue itself, which put fmt at 24% and leveldb at 9%. Those two rows had counted only .cc files and omitted the headers, where most of the failures are; the C rows counted both, which is why curl and redis reproduced exactly and the C++ pair did not. An isolated 2.14.3 returns identical counts on the same checkouts, so this is the approach's behaviour and not a regression in any release since.
Added as a "Parse coverage" section on docs/languages/c.md and cpp.md (causes, per-error-kind breakdown, and what to do about it), a note under SAFE000 in docs/configuration/rules.md, and a block in the bundled C and C++ skill addenda telling an agent not to read a clean run as a clean project and not to rewrite working code to satisfy the parser. Bundled skill content changed: run safelint skill install --force.
The preprocessor is not the whole story, and the docs now say so. A .h header in a C++ project lints as C, so C++ syntax in it defeats the C grammar on its own, whatever the preprocessor would have done. Measuring the split: re-running fmt's 24 failing .h headers under the C++ grammar clears 4 and leaves 20 still failing, so the grammar mismatch is a real but minority cause, and renaming to .hpp / .hxx / .hh recovers only those 4. Two further caveats were wrong by omission: the coverage count is only meaningful from safelint check . --all-files (a bare run covers git-modified files alone), and linting cc -E output costs more than line numbers, since it drops every inactive branch and removes the directives that the opt-in SAFE311 and SAFE312 rules match, retiring both rules silently. The .h figures also assume safelint[c,cpp]; a cpp-only install never reads those headers.
Not addressed here: the summary still gives no skipped-file count (#175), and a preprocessor-tolerant parse pass (item 4 of #206) remains open.
2.17.1 - 2026-11-07#
Fixed#
- SAFE801
tainted_sink: a binding's taint is scoped to the block that declares it (#250). Every tracker kept one flatname -> statusmap per function, so a nested block that rebound a name overwrote the function-wide entry and the outer binding came back without its taint:
let input = std::env::var("CMD").unwrap(); // tainted
{ let input = "safe"; } // cleared the entry
cmd.arg(input); // tainted - was NOT reported
A false negative in a security rule, which is the worse direction. Probing it turned up two things the issue did not report. The flat map was wrong in both directions - with the outer binding clean and the inner block's shadow tainted, the rule reported a sink reading a value that is clean - and the bug was not limited to the two languages named: C, C++ and Go are affected as well, which the issue asked to be checked rather than assumed.
Fixed in all five (Rust, JavaScript / TypeScript, C, C++, Go) by one shared mechanism. A block-scoped declaration now pushes the name's prior state onto a stack and the tracker restores it on the first node at or past the block's end. That works because every tracker walks its function once in pre-order, so start_byte never goes backwards - an invariant the whole design rests on, now asserted by a test in four grammars rather than assumed.
Three languages are deliberately untouched, for reasons worth recording because extending the fix to them would introduce the very bug it removes: Python has no block scope; PHP's locals are function-scoped, so an inner { $c = "safe"; } genuinely overwrites the outer $c; and shadowing a local in a nested block is a compile error in Java. JavaScript var is excluded for the same reason - it is function-scoped and hoisted, so an inner-block var really does rebind the function-wide name, and scoping it would turn a true positive into a false negative. Only declaring forms are scoped, so a plain x = value inside a block still writes through to the binding in scope.
A declaration in a loop or control-statement header needed the statement itself recognised as the scope, not just a block: for (let p = 0; ...) and Go's if cmd := get(); c { } else { ... } put the declaration as a sibling of the body, so the ancestor walk went straight past the loop to the enclosing block and the header binding outlived its statement. Wrong in both directions again, and the else-branch case loses a finding, which is the dangerous one. Found by CodeRabbit and CodeAnt independently on the review round, where the code comment asserted the opposite.
C also needed the clearing done per declarator rather than once per declaration. C scopes each declarator from the end of its own declarator, so in char *a = b, *b = "safe"; the b in a's initialiser is the outer, tainted one; clearing every name up front cleared it before that initialiser was read.
Measured across 14 corpora in five languages (761 SAFE801 findings): zero changed. Not one finding gained or lost on axios, vue core, elysia, express, zod, cloudflare templates, ripgrep, rust std, fmt, leveldb, redis, curl, cobra or fzf. For a change touching five trackers and the shared contract, that is the result worth having: the repros are fixed and nothing else moved. The shape it closes is narrow in real code, which is also why it survived this long.
-
SAFE305: the documented fix was a keyword swap for only one of the five shapes. The rule's docs, the JavaScript and TypeScript pages, the JavaScript addendum and all 14 client files said the first three shapes were "a mechanical fix: replace
varwithlet". Run againstnode, two of those three throw when the keyword is swapped where it stands: a block escape becomesReferenceError: w is not defined, because the binding no longer exists at the use, and a read before the declaration becomesReferenceError: Cannot access 'w' before initialization, which makes the hazard visible rather than fixing it. Only the loop-capture shape is a true one-token swap (3,3,3becomes0,1,2, and that change is the fix). Each shape now states its own fix: move the declaration above the block, move the read, swap the keyword, rename, or declare above theswitch. Found by CodeAnt as three Major findings; the wrong advice mattered most in the bundled skill files, which agents act on directly. -
SAFE305
wide_scope_declaration: avarread from a laterswitchclause is now reported (#255). The fifth shape, and the one each of the other four misses for a different reason. It is not an escape, because a case clause is not a lexical scope and both sites share the one the switch's braces open; and it is not a read before the declaration, because that compares source order and the declaration comes first. What makes it a hazard is execution order, since a switch may be entered at any of its clauses:
Verified against node: as var the read is undefined, and as let it throws Cannot access 'w' before initialization. So the declaration genuinely blocks the let conversion the rule exists to recommend, which is why leaving it out was an inconsistency in the rule's own contract (since #201 it reports exactly where the hoisting is observable, and this is observable). The fix is to declare the variable above the switch, which the message says.
Measured: zero occurrences across the JavaScript and TypeScript corpora, so this adds no findings to any project measured and buys no noise either. It is shipped for the correctness of the contract rather than for a count, and the shape it closes was recorded as a known limit in 2.16.0 rather than discovered since. default: counts in both directions, being a clause like any other and a distinct node type that has disagreed with switch_case about scope before.
No fall-through analysis is involved and none would help: a clause carrying a label is directly reachable whenever the discriminant matches, so the hazard holds whether or not the declaring clause ends in break, and the discriminant's value is exactly what cannot be known. A read in the same clause is clean, a read in an earlier clause keeps the read-before-declaration wording, and a var that also leaves the switch keeps the escape wording, which describes the more pressing half.
-
A TypeScript non-null assertion no longer hides a function's name.
const handler = (() => {})!parses asnon_null_expression > parenthesized_expression > arrow_function, and that wrapper was missing from the pass-through list added in 2.17.0, so every per-function rule reportedFunction "<anonymous>"for a function the source names. A non-null assertion is a type-level claim about the value and says nothing about the function, exactly like theas/satisfies/ angle-assertion forms beside it. The wrappers compose, so(((...) as Fn)!)needs all of them peeled; both orders are pinned. Found by CodeAnt on the SAFE105 change below, where the same gap cost the new route a genuine recursion finding. -
SAFE105
no_recursion: recursion through aconst/let/var-bound function is now detected (#259). Anarrow_functionhas no name of its own; the name sits on the binding holding it. The rule matched only the function's own name, so it was silent on the declaration form most of the JavaScript and TypeScript ecosystem uses, while firing correctly onfunction fact() {}beside it:
const fact = (n) => (n <= 1 ? 1 : n * fact(n - 1)); // was clean, now reported
function fact(n) { return n <= 1 ? 1 : n * fact(n - 1); } // always reported
A rule whose purpose is to find unbounded stack growth going quiet on the dominant shape is worse than no rule, because the clean run reads as reassurance.
Measured across the JavaScript and TypeScript corpora: 91 new findings across 35 functions, none removed. The two units differ because the rule reports one finding per call site, so a function with four self-calls is four findings; #259's own estimate of 39 counted functions, with a cruder script. What the 35 are is the point: mergeDeep (a deep merge whose depth is its input's), hasAdditionalProperties and getDiscriminator (recursive JSON-schema walks), Vue's setScopeId and recursiveGetSubtree over the vnode tree, axios's visit over an arbitrarily nested object. Thirteen were read by hand and every one is genuine recursion over user-shaped data. SAFE105 is warning severity, so these are advisory rather than blocking under the default fail_on.
Only a variable declarator lends its name, and only to a bare call. The three binding forms look alike and do not behave alike, which was verified against node rather than reasoned about: const fact = (n) => fact(n - 1) returns a value, while { walk: (n) => walk(n - 1) } and class T { fact = (n) => fact(n - 1) } both raise ReferenceError, because an object property and a class field are not lexical bindings. An arrow also does not bind its own this, so this.walk(...) inside an object-literal arrow is not a self-call. Reporting on either would have been a finding about a call that cannot recurse.
Recorded rather than claimed fixed: class T { fact = (n) => n * this.fact(n - 1) } really does recurse and is still not reported. Reaching it means matching the enclosing class against the receiver so a sibling object's this.fact(...) is not mistaken for it, which is separate work from naming the function.
The existing guards do the rest, and they are what keeps this from becoming a wrapper-reporting machine: a member-access callee is never a bare call, so const trim = (s) => s.trim() stays clean; a nested binding of the same name shadows the outer one, now resolved through the binding as well so const walk = (n) => { const walk = (m) => m; return walk(n); } stays clean too; and a computed key lends no name, since the verdict would rest on a variable whose value is unknown. JavaScript and TypeScript only: Java's lambdas sit in a variable_declarator spelled identically, so the route is gated by language rather than left to match for free.
2.17.0 - 2026-11-04#
Added#
- SAFE601
missing_assertions:assertion_call_prefixes, so a project's ownassert*helper counts (#251). Matching was by exact call name, so a test whose only assertion went through the project's own helper read as assertion-free. A call whose name starts with an entry in this list (["assert"]by default) now counts, and enumerating helpers per project is no longer the only option: commons-lang alone would have needed eightextend_assertion_calls_javaentries to clear half of its findings.
Live only inside a function the rule has identified as a test, which is what makes it safe: inside a test an assert-prefixed call is an assertion, while a production method named assertValid() is nobody's assertion and is never credited. Per language through the usual key chain, so a Go project that also writes mustEqual can say assertion_call_prefixes_go = ["assert", "must"]; the suffixed key is the one each language page and bundled skill file now names, because the bare form reaches Python alone. To go back to exact names alone, set the key for the language you mean: the bare assertion_call_prefixes = [] reaches Python only, since the bare key is Python's throughout safelint and is deliberately kept out of the other languages' lookup chain (assertion_call_prefixes_java = [], _rust, _go, _javascript, _php; TypeScript takes either its own or the JavaScript one it inherits). An empty-string entry is dropped rather than honoured, because it is a prefix of every name and would credit every call in every test.
In Rust this is the one route that reaches a plain call. assertion_calls_rust is matched against macro names only, deliberately - a function literally named panic is not an assertion - so a helper written as fn assert_roundtrip(...) was previously never credited whatever the config said. That limit is now lifted for assert*-named helpers and documented for the rest.
Findings removed by this route, measured across the validation corpus: django 1637, framework (Laravel) 1472, guava 1162, ruff 880, commons-lang 451, ripgrep 98, monolog 93, guzzle 67, core 60, zod 53, axios 18, cobra 15, fzf 13. These are the class #251 predicted from the other direction: it measured 464 of commons-lang's 873 findings and 1160 of Guava's 3363 as calling an assert* helper, against the 451 and 1162 removed here.
Changed#
- SAFE901
spring_field_injectionno longer reports test classes (#208). Field injection in a test is the pattern Spring's own reference documentation and sample code use, and the argument for constructor injection does not carry over: the framework instantiates a@SpringBootTestclass itself, so there is no constructor the user controls in the ordinary way, and the usual case for constructor injection is substantially about making a class easy to unit-test, which inverts when applied to the test.
Measured on Spring PetClinic, written by the Spring team as the reference example: 17 findings, all 17 in test classes, 63% of the project's whole default output, and not one in production code. So on the project most likely to be used as a sanity check for Spring support, a majority of safelint's output argued against the framework's documented pattern. All 17 clear; the remaining 10 findings are untouched.
The rule joins the five skip_test_code rules from #198 rather than adding a second mechanism, so skip_test_code and test_dirs are the keys it reads, with the same meaning they have there. They are per-rule, as every rule option is, so a project with non-standard test directories sets test_dirs under spring_field_injection too. The three Java test-filename conventions (*Test.java / *Tests.java / *IT.java) account for every PetClinic finding, so no annotation detection was needed. Its default test_dirs is deliberately narrower than the five share, ["test", "tests"] rather than also __tests__ and spec: test_dirs is matched as a path component anywhere in the path, so spec would have skipped every class under a production package named spec (src/main/java/com/acme/spec/ is an ordinary place to keep an API specification) while __tests__ cannot occur in a Maven or Gradle source root at all. Re-measured on PetClinic after the narrowing: still 0 SAFE901 findings and the same 10 others. Set skip_test_code = false for the strict reading.
- SAFE601: a test's callbacks assert on the test's behalf (#252). The assertion counters walk a body with
skip_types=function_typesand so stop at any nested function. For a callback-style test that is the wrong answer: the assertions live inside a callback written inline in the test - an Express route handler, a promise continuation, aforEachlambda - and the test read as assertion-free. The skip is dropped for a function identified as a test, and kept for every function that is not one, which is the false negative it exists to prevent (an ordinary function must not be credited for an inner definition's asserts).
The boundary is the test's own syntax tree, so a callback defined elsewhere and merely passed by name is not covered; it is not nested in the test, and following the value would be a different analysis. C therefore gains nothing from this route at all, having no nested function, closure or lambda, and the documentation says so per language rather than claiming the general case everywhere.
Findings removed: framework 150, express 64, guzzle 63, guava 47, core 39, django 35, axios 34, chartjs 33, fzf 19, ruff 13. Express is the case the issue was filed from; its own estimate was 10, and the true figure is 64 because the suite's dominant idiom is router.handle(req, {}, function (err) { assert.ifError(err); ... }), with the assertions one callback deep throughout.
The trade, recorded rather than left to be found: an inner definition inside a test now credits the test even when nothing calls it, because "handed to someone else" and "defined and never used" are the same tree shape - a callback is passed by reference too, so telling them apart would mean following the value. A test carrying a dead assertion helper is a rare thing to miss, and the finding would be about dead code rather than about assertions.
-
SAFE601:
@TestFactoryis a default Java marker again, as a consequence of #252. It was excluded in 2.16.0 for a structural reason: a factory returns a stream ofDynamicTests whose assertions live inside lambdas, its own body never asserts, and the counters stopped at nested functions, so including it reported every well-written factory. That limitation is exactly what #252 removed for a function identified as a test, and a factory is one, so the exclusion no longer buys anything. It also cost real coverage: while@TestFactorywas not a marker, a factory was not a test at all, so one producingDynamicTests that assert nothing was invisible to the rule. Measured on commons-lang's four@TestFactorymethods (the only ones in the corpus): zero new findings, all four correctly read as asserting. -
SAFE601: test identity is resolved whatever
test_functions_onlysays. It was read only when the scoping was on, which was fine while identity decided one thing. It now decides three (whether the function is checked, whether anassert*helper counts, whether a callback's assertions count), so undertest_functions_only = falsea genuine test silently lost both new routes while production functions kept them off as intended. No change to which functions are checked in either mode.
Fixed#
-
SAFE601: four
node:assertfunctions were missing from the JavaScript defaults (#256).notDeepEqual,notDeepStrictEqual,doesNotMatchandpartialDeepStrictEqual(Node 22.13+) were absent while their siblingsnotEqualandnotStrictEqualwere present, so a node:test / Jest / Vitest test asserting only with one of them reported as having no assertions. This surfaced in 2.16.0 rather than before it: reaching JS tests through their registration callback (#222) is what made the contents of the list matter, since the whole callback was previously skipped. The fullnode:assertsurface is now pinned by a test so the list cannot drift from the module again without failing. A duplicateassertentry was dropped from the same list while here;console.assertneeds no entry of its own, becausecall_namestrips the receiver. -
A function bound to a name is no longer reported as
<anonymous>(#165). Modern JavaScript and TypeScript declare most functions as an expression bound to a name, and anarrow_functionhas nonamefield of its own: the name sits on the enclosingvariable_declaratoror object-literalpair. Every per-function rule read that field alone, soconst Footer = () => {}over the length limit reportedFunction "<anonymous>"although the source names it. On one real project that was 8 of 8 SAFE101 findings, and with several in a file the reader had to open each line to learn what was being reported.
Measured across the JavaScript and TypeScript corpora: 380 findings now name their function. Object-literal entries ({ loadUser: () => {} }) are covered, and so are class fields (class Store { loadAll = () => {} }, the standard shape for an auto-bound method, which the two grammars spell differently: JavaScript field_definition.property, TypeScript public_field_definition.name) and bindings behind a pass-through wrapper, which includes the ordinary TypeScript const handler = (() => {}) as RequestHandler. The class-field route changes no finding on the validation corpora - the shape occurs there but never on a function any rule reports - so it is recorded as a gap closed rather than a measured improvement. A genuinely nameless function keeps <anonymous>, because inventing a label for an IIFE or an inline callback would be worse than an honest absence, and so does a key that is not statically spelled: the text of { [readFile]: ... } is [readFile], and treating that as a name would have let SAFE304 exempt the function as I/O-signalling on the strength of a variable whose value is unknown.
Six rules each carried their own copy of the naive lookup, which is how one gap came to affect all of them; there is now one resolver. It also closes two false positives in SAFE304, which exempts a function whose name already signals I/O: while the name read <anonymous> the exemption could not match, so the rule reported readFile and sendCode asking them to be renamed to signal what they plainly signal.
SAFE601 deliberately still identifies a test by the function's own name. A binding that happens to start with test is just a variable in JavaScript, and crediting it made chartjs read four testA: entries of a TypeScript type fixture as tests and elysia one const test = (app) => app.group(...) helper: five findings, all false, against no true one. JavaScript's real test-identity route is the registration call, which the rule handles separately.
2.16.0 - 2026-11-02#
Added#
- SAFE601
missing_assertions: registered for Go (#221). The rule'slanguagetuple omitted Go and_FUNCTION_TYPES_BY_LANGhad no Go entry, so every.gofile was skipped; on the codebase this was found on, 66_test.gofiles with about 1,600t.Fatal/t.Fatalfcalls, the rule checked the Python tests beside them and none of the Go ones. Go has no production assertion idiom, which is why it was left out, and that reasoning holds: the rule is meaningful there only as the "tests must assert something" guard thattest_functions_onlynow gives by default.assertion_calls_gois the*testing.T/B/Ffailure API (Error,Errorf,Fatal,Fatalf,Fail,FailNow);SkipandLogare deliberately absent, because skipping or logging is not asserting. - SAFE601:
assertion_receivers, matching an assertion by its receiver (#221). Testify exposes dozens of assertion functions per package (Equal,NoError,Len,ErrorIs, ...), so a name list would be long, would go stale against the library and would collide with ordinary method names.assertion_receivers_go = ["assert", "require"]says "any call on this package counts" instead. Only an identifier receiver qualifies, sos.deps.assert.Equal(...)is not passed off as testify. Every other language resolves the key to empty and matches on names alone. - SAFE601:
test_registration_calls, so a test written as a callback counts as a test (#222). Withtest_functions_only = truea function was checked only when its name started with atest_function_prefixesentry. Every JavaScript and TypeScript test is a callback -it("name", () => {}),test("name", function () {})- whose name resolves to<anonymous>, so none of them was ever checked: for the JS family the option did not scope the rule to tests, it turned the rule off for them. On the Next.js app this was found on, 7 test files with 18it()tests, not one could be checked with the option on. Defaults are["it", "test"]for the JS family and["Run", "Fuzz"]for Go. Matching is against the whole callee chain, becausecall_namekeeps only the trailing bareword (it.only(...)resolves to"only"), so the modifier forms (.only/.skip/.concurrent/.failing), the parametrisedit.each(table)(...), node:test'st.test(...)and Go'st.Run(...)/f.Fuzz(...)are all covered by those names. - SAFE601:
test_markers, so a test identified by an attribute or annotation counts as a test (#163). Rust and Java name their tests in free prose -#[test] fn empty_input_is_zero(),@Test void shouldRejectShortPassword()- and Rust's dominant idiom puts them inside the production file under#[cfg(test)] mod tests, so neither the name nor the filename identifies them.test_markers_rust = ["test", "rstest"]andtest_markers_java = ["Test", "ParameterizedTest", "RepeatedTest", "TestTemplate"](@TestFactoryis deliberately absent: its assertions live in theDynamicTestlambdas it returns, which the counter cannot see, so including it reported every well-written factory; #252 is the general case). A qualified marker matches on its trailing segment, so#[tokio::test],#[rstest::rstest]and@org.junit.jupiter.api.Testneed no entry of their own, and stacked attributes (#[test]under#[should_panic]) are read as the separate items they are.#[cfg(test)]is not a marker: it marks test context, and a#[cfg(test)] fn helper()is test support rather than a test case. - SAFE601: a finding on a registered test is named by its title.
Test "rejects a short password" has no assertionsrather thanFunction "<anonymous>"at a line number. A computed title (Go's table-drivent.Run(c.name, ...)) keeps the anonymous label rather than printing an expression where a title belongs. - SAFE601:
test_function_prefixesis now per language. The conventions differ in case as well as shape:["test"]everywhere,["Test", "Fuzz"]for Go, whose toolchain requires the capital, so the shipped lowercase default matched no Go test at all.BenchmarkandExampleare deliberately out: a benchmark has no assertion to make, and an example asserts through its// Output:comment, which is not a call. - Bundled skill docs: the SAFE601 row in all 14 client files and the SAFE601 guidance in all 9 language addenda now describe the scoped default and the three identity routes; the Go addendum moves SAFE601 out of its "deliberately skipped" list, and the Python addendum gains the row it never had. Agents reading the old copy would act on "functions without internal assertions", which is no longer what the rule reports. Run
safelint skill install --forceto pick up the new copies. - SAFE601
missing_assertions:extend_assertion_callsappends instead of replacing (#220).assertion_callsreplaces the default list, so a project that wanted to add one helper had to copy all 66 default names into its config and then keep them in step with future releases. The new key is appended to whatever the base list resolves to, and works per language through the same key chain (extend_assertion_calls_javascriptand friends, with TypeScript inheriting the JavaScript one). Mirrorsresource_lifecycle'sextend_tracked_functions.assertion_callskeeps its replace semantics, because narrowing the list is a supported thing to want.
Changed#
- SAFE601
missing_assertions:test_functions_onlynow defaults totrue(#163). The previous default demanded assertions in every function, production code included, and across four real codebases that made SAFE601 56-92% of all output: 557 of 987 findings on a Python service (every one in a non-test file, across 126 production modules), 157 of 233 on spring-petclinic, 154 of 232 on a JavaScript app, 624 of 679 on a Rust binary. A getter, a trait conversion and a migration hook asserting nothing is correct design, so the findings that mattered were indistinguishable from the ones that did not. The rule is named for assertions in tests; "every function must assert" is the unusual reading, and it is still one line away (test_functions_only = false).
Not a breaking contract change, which is why this is MINOR: the rule is opt-in (enabled = false), so this narrows what an already-enabled rule reports rather than changing a default anyone gets without asking. If you enabled SAFE601 and rely on whole-codebase coverage, set test_functions_only = false.
Measured after the change, SAFE601 findings and its share of all output, before -> after: spring-petclinic 178 (95%) -> 3 (25%), guava 49038 (94%) -> 3457 (55%), ripgrep 2900 (92%) -> 139 (35%), cobra 506 (82%) -> 75 (40%), fzf 1123 (68%) -> 47 (8%), requests 359 (77%) -> 11 (9%), rich 1077 (75%) -> 11 (3%), express 1483 (97%) -> 89 (69%). Every one of those is non-zero, which is the point: the rule still finds assertion-free tests in all five idioms (name prefix, registration callback, Go subtest, #[test], @Test) rather than going quiet.
-
SAFE601: a function that registers tests is no longer reported. The assertion counters stop at nested functions by design, or an outer function would be credited for a closure's asserts. So a Mocha / Jest
describeblock, and a Go table-drivenTestXxxwhose assertions all live int.Runsubtests, asserted nothing in their own bodies and reported. Each callback they register is now checked on its own merit and the registering function is skipped. A matching name with no callback argument does not qualify, so a productionrunner.test(value)still leaves its enclosing function answerable. -
SAFE601:
test_functions_onlyis validated as a boolean. A quotedtest_functions_only = "false"is a non-empty string, so a plain truth test read it astrueand kept the behaviour the user had just tried to opt out of. It now raises, like every other boolean key.
Fixed#
- SAFE305
wide_scope_declaration: aswitch's cases are one scope, not one each. A case clause is not a lexical scope; the braces of theswitchare. Treating eachcaseas its own made twovar yin different cases read as disjoint declarations, so the redeclaration went unreported although converting both toletis an unconditionalSyntaxError: Identifier 'y' has already been declared.default:is a separate grammar node that was in no scope table at all, so it resolved to function top level while its siblingcaseresolved to itself, and the two disagreed about where they lived. Both now share the switch body.
One shape is lost in the trade and is recorded rather than quietly dropped: a var declared in one case and read from a later case. That ran as var and throws Cannot access 'w' before initialization as let, so it genuinely blocks the conversion, but it is none of the rule's four shapes (source order puts the declaration first, and both sites are in the one scope). Per-case scoping used to report it as a block escape, which was the right answer by the wrong reasoning and cost the redeclaration shape above. Pinned by a test and filed as #255.
- SAFE305
wide_scope_declaration: only a binding that MERGES with thevaris a redeclaration. The candidate list was every other binding of the name, so alet/constin a nested block, a catch parameter and a class name all counted. Each of those is its own binding thatletis free to shadow, so these reported a redeclaration that no engine rejects and asked for a rename that nothing requires:
function f() {
var err = null;
try { run(); } catch (err) { log(err); } // its own binding
return err;
}
Only another var declarator or one of the function's own parameters merges into the same binding. Verified against node --check: every excluded shape parses once the var becomes let, and the included ones do not. A let at the same scope as the var is a genuine collision but also an unconditional SyntaxError, so no running codebase holds one. Express and Axios report identically before and after (3 and 0 SAFE305), so this removes noise without moving the measured numbers.
A second review round on the fix caught one more: it is the declarator's NAME that has to hold the binding, not merely the declaration somewhere above it, because a binding in the INITIALISER belongs to its own construct. var Foo = class Foo {}; scopes the inner Foo to the class body, so let Foo = class Foo {} parses and there is nothing to rename. A named function expression is the same shape and was already excluded, by the nested-function filter rather than by this test.
-
SAFE601
missing_assertions: a Go receiver safelint cannot resolve is no longer treated as no receiver. The receiver resolver answers "none" both to a genuinely bare call (mustEqual(...)) and to a selector whose operand is not a plain identifier (s.logger.Errorf(...),newLogger().Fatal(...),loggers[0].Error(...)). Reading the second as bare put it on the name-only path, so a test whose only call wass.logger.Errorf("...")counted as asserting: the exact failure thetesting-typed receiver rule was added to prevent, arriving through the other branch. A bare call now has to have an identifier callee; anything with an unresolvable receiver counts for nothing. The existing chained-receiver test usedEqual, which is not a configured name, so it passed on name matching alone and left this uncovered. -
SAFE601: an interpolated template literal is treated as a computed test title.
it(`case ${name} runs`, ...)printed the source text verbatim, so the finding readTest "case ${name} runs"and sent the reader looking for a test by a name that does not exist. It now falls back to the function label, the same as Go's table-drivent.Run(c.name, ...). A plain backtick title with no interpolation is still used. - SAFE601: Go's
*testing.Tfailure methods are counted only on atesting-typed receiver.call_namestrips the receiver before matching, so the shippedErrorf/Errornames were credited tofmt.Errorf("...")anderr.Error(). Neither is an edge case in a Go test: either one silenced the finding completely, so a test asserting nothing read as clean. The receiver now decides - a bare call still matches on name alone (which is what lets a project add its own helper), a receiver inassertion_receivers_gocounts as testify, and any other receiver must be atesting-typed parameter of the function being checked. A subtest literal resolves its ownt. - SAFE601: Go's
TestMainis not reported.TestMain(m *testing.M)is the package's setup harness, not a test: it matches theTestprefix, has nothing to assert, and itsm.Run()cannot excuse it either, because the delegation guard needs a callback argument andm.Run()takes none. It reported on every Go package that has one. - SAFE601: a comment between a Rust attribute and its
fnno longer loses the marker. tree-sitter puts comments in the same sibling chain as attributes, so#[test]followed by#[ignore] // flaky, or by a comment line above thefn, ended the attribute walk before the marker was seen. The test was then silently left out of the rule under the new default scope. - SAFE601
missing_assertions: MockMvc, Truth, Mockito and AssertJ exception assertions now count. Measured while verifying the scoping change: with the rule scoped to tests, spring-petclinic still reported 45 findings and all 45 were the same thing. A Spring MVC test asserts through the chainedmockMvc.perform(...).andExpect(status().isOk()), andandExpectwas not inassertion_calls_java, so every@WebMvcTestmethod in the project read as assertion-free; adding it takes petclinic to 3 findings. Also added: Truth'sassertWithMessage(its message form never callsassertThat, so a Truth test written that way read as assertion-free - used throughout Guava's own tests), AssertJ'sassertThatThrownBy/assertThatExceptionOfType/assertThatNoException/assertThatCode, and Mockito'sverify/verifyNoInteractions/verifyNoMoreInteractions. -
SAFE601 / SAFE701 / SAFE702: a relative
test_dirsentry is anchored at the file's project root._is_test_fileabsolutised each relative entry against the working directory, soPath("test").absolute()became<cwd>/testand never matched/abs/project/test/app.js. Every relative entry therefore matched nothing whenever safelint was pointed at a path outside the working directory -safelint check /abs/projectfrom elsewhere, an ordinary CI invocation. Found on Express, which reported zero SAFE601 findings from outside its checkout and 89 from inside it. The exclusion side (theskip_test_codefamily) was already fixed for this and anchors at the project root; only the inclusion side was left, so the two disagreed about where tests live. It mattered less whiletest_functions_onlywas off: now that it is on, a wrong "not a test file" answer skips the whole file. Atestscomponent above the project root still does not match (so a checkout living under~/tests/is not read as all test code), and a traversing entry (["../../../"]) still matches nothing. -
SAFE801
tainted_sink: the message now says whether a source was traced or only a parameter seeded (#158). Taint is seeded from two places that are not equally good evidence, and until now both produced the same sentence:
$mailbox was an Eloquent model loaded from the database, never request input. It was tainted only because the tracker seeds every function parameter, which is what makes an intra-procedural analysis useful; it is not a finding that attacker data is in play. Against FreeScout, 0 of 10 SAFE801 findings had a traced source, yet every message read like the one above.
There are now two wordings:
| Message | Evidence |
|---|---|
Tainted variable "x" flows into dangerous sink "s" |
a recognised source (input(), $_GET['q'], os.Getenv, a framework request accessor) was traced to the sink |
Parameter-derived value "x" reaches dangerous sink "s" |
only a parameter was seeded; the sink is real, but what callers pass is the open question |
Both still report, and the parameter kind is worth reading - it is how an injection arrives once a caller is attacker-facing. What changed is that it no longer claims to have traced untrusted input. Re-measured on FreeScout's app/ tree after the receiver fix above: 5 SAFE801 findings, all five parameter-derived, which is the honest reading of all of them (three unserialize calls on database and queue payloads, a shell_exec wrapper, and an unserialize of a decrypted value).
The distinction follows the flow, not the spelling. A value derived from a parameter stays parameter-derived (built = "sh -c " + cmd); mixing a parameter with a source escalates to the stronger wording (cmd = prefix + input()); reassignment overwrites the origin along with the taint, in both directions; and a closure capturing a source-tainted local inherits the stronger wording through the capture, which Java, Rust and Go each needed because they analyse closures in a second pass seeded from the enclosing scope.
All nine languages, since the overstatement was never PHP-specific. No new rule code and no config: the two messages are the same hazard seen with different amounts of evidence, so filtering is a matter of the message prefix in --format json.
Deciding the origin costs one extra pass of the tracker's own is_tainted per assignment and per hit, asked with the tainted set narrowed to source-derived names and - at the hit - with the sink's own required property, so a source that the sink's property-typed sanitiser already cleared does not count as traced for it. Re-using that function rather than growing a parallel worklist is what keeps the origin answer from drifting away from the taint answer. Measured on FreeScout's app/ tree with SAFE801 on: 1.53s -> 1.69s, about 10%. SAFE801 is opt-in, so nobody pays it who had not already chosen the expensive rule.
If you parse SAFE801 messages, this is a breaking change to that text, and the only one. For anything programmatic, note that the analysis trackers grew a public source_traced set (hit keys that reached a source) and a public source_seeded set (variables whose taint did), alongside the existing tainted and sink_hits; sink_hits keeps its (call_node, var, sink) shape.
- SAFE305
wide_scope_declaration: report avaronly where its hoisting is observable (#201). The rule reported everyvar, which inverted its own value. On Express, 1748 of 1960 default findings (89%, across 136 of 141 files) were SAFE305, so thevars whose hoisting actually bites were indistinguishable from the rest and the other ten rules were drowned out. Every finding was technically true, and these two were reported identically:
var path = require("node:path"); // hoisting unobservable; `const` is the same
function f(xs) {
if (xs.length) { var found = xs[0]; }
return found; // hoisting is what makes this work
}
Four shapes now report, each with a message naming the hazard: used (read or assigned) outside the block it is declared in; read before its declaration in the same execution scope; declared in a loop and captured by a closure inside it; or re-declaring a name already bound in an overlapping scope (an earlier var, or a parameter). The fourth is new and is the one let rejects or silently shadows, so the fix is a rename rather than a keyword swap.
Measured on the projects the issue cites, same pinned commits, stock defaults: Express 1748 -> 3 SAFE305 (total findings 1960 -> 214) and Axios 186 -> 0. All three Express survivors are genuine redeclarations - two var colonIndex in one function in lib/utils.js, and var name over a parameter of the same name in examples/mvc/lib/boot.js - and each blocks a let conversion until renamed.
Reaching that number took four false-positive classes out, each found by running against the real projects rather than by reasoning: a named function expression's own name counted as a read of a var shadowing it; a nested callback's parameter counted as a read of the outer binding; a read inside a nested function counted as read-before-declaration although the closure runs afterwards; and a redeclaration was reported as read-before-declaration, which is the wrong diagnosis because the earlier reads resolve to the earlier binding. Each has a regression test named for the project it came from.
If you want every var reported as a codemod trigger, this rule no longer does that; eslint no-var is built for it.
The SAFE305 row in all 14 bundled client skill files still said "the rule fires on every var declaration", which the agents reading them would have acted on. Updated to the four observable shapes, including that a redeclaration needs a rename rather than a keyword swap and that a var the rule stayed quiet about should not be converted unasked. Run safelint skill install --force to pick up the new copies.
Review follow-ups on the fix itself, all on PR #248. The scope tables the rule needs - where this scope binds names, which identifiers read them, which other sites bind them - are properties of the scope, not of the declaration, but were rebuilt with a fresh tree walk for every var. That made the rule quadratic in the number of declarations sharing a function, which bites hardest on exactly the legacy files it is aimed at: a synthetic 1000-var function took 11.1s, and 2000 took 45.1s (4x per doubling). They are now built once per scope and cached, which is linear: the same files take 0.075s and 0.160s. Express and Axios report identically before and after (3 and 0 SAFE305), so this is a pure cost change.
Three behaviour corrections from the same review. A redeclaration now requires the two bindings' block scopes to overlap - one containing the other, or either at function top level. The check previously accepted any second binding of the name anywhere in the hoisting scope, so two sibling for (var i ...) loops reported each other although let is legal in both, which is a slice of exactly the noise this issue removed. The reference scan needed the same lesson: it matches by name across the whole scope, so with the redeclaration suppressed the second loop's i read as the first one escaping its block, and the first loop's as the second being read before its declaration. A block now owns the references inside it, so a name bound in a disjoint sibling block takes its own. if (c) { var x = 1; } else { var x = 2; } is the same shape; an inner block is contained by the outer one, so a genuinely nested redeclaration still reports. The Express survivors are unaffected (a function-top-level scope overlaps every block), and the measured numbers above are after this fix.
A redeclaration is now also reported even when nothing reads the name - the other three shapes need a reference to be observable, but let rejects a duplicate binding whether or not it is ever read, so bailing out early was wrong. And the escape message said a var is "read" outside its block when a plain assignment (state = 2) triggers it just as much; it now says "used". The redeclaration message no longer claims let rejects every such case either: at the same scope it does, but from a nested block let would quietly bind a separate shadowing variable instead, which is a different hazard with the same fix (rename one of them).
- SAFE801
tainted_sink: a zero-argument call is no longer treated as a receiver-payload sink (#158). Every tracker reported a tainted receiver when the call had no arguments, on the reasoning that a no-argument call must be carrying its payload in the receiver. It need not:
$folder is a webklex/php-imap folder, query() builds an IMAP search rather than SQL, and it takes no arguments, so there was neither an argument nor a receiver carrying user data. Against FreeScout, 0 of 10 SAFE801 findings substantiated the claim that user input reaches a dangerous sink, and 6 were this one shape. Membership in receiver_sinks is now the only accepted evidence, which is what that list has always been documented to mean. Java's openConnection / openStream SSRF defaults are unaffected (they are declared), and an end-to-end test pins that the shipped config still catches URL SSRF.
If you relied on the old behaviour for a sink whose payload genuinely is its receiver, add it to receiver_sinks_<lang>. The decision now lives in one place, SinkKinds.receiver_is_payload, rather than being repeated in all seven trackers.
-
Not changed: the bareword
querystays in the defaultsinks_php. #158 also recommended dropping it, because as a bareword it matches php-imap'sFolder::query(), Eloquent'sModel::query()and Laravel'sDB::query(). Measured after the receiver fix above, all three are silent already - every one of them is a zero-argument call - while$db->query('SELECT '.$_GET['id'])still reports. Dropping the name would have cost that true positive, the commonest PHP SQL injection there is, to fix false positives that were already gone. Tests pin all four shapes. -
SAFE601
missing_assertions:unittest.mockand DjangoTestCaseassertions now count (#220). Withtest_functions_only = true, a Django codebase of about 3,300 files still reported 100 test functions as assertion-free. 55 of them asserted only throughunittest.mock(assert_called_once_withand friends) and several more through Django'sTestCaseAPI, so the rule was reporting "this test asserts nothing" about tests that assert.
mock is in the standard library, so its assertions are as standard as assertEqual. Added: the assert_called* / assert_any_call / assert_has_calls / assert_not_called family and its assert_awaited* async mirrors, plus Django's assertContains, assertRedirects, assertTemplateUsed, assertNumQueries, assertRaisesMessage, assertFormError, assertJSONEqual, assertHTMLEqual, assertInHTML, assertQuerySetEqual and the rest of that API.
The Django names are unconditional rather than gated behind [python] framework = "django". Every one is spelled assert* and nothing else defines them, so counting one as an assertion is right in any project, and a false-positive fix should not depend on the preset being configured. Adding a name here can only ever suppress a finding, never raise one, which is also why the change ships with a control test asserting that a test with no assertion at all still reports.
- SAFE803
null_dereference: a literal fallback argument stops the finding (#155).d.get(k, default)returnsdefaultwhen the key is absent, so the defaulting form is the Python safe-navigation idiom. The rule matched on the call name alone and never looked at the arguments, so it reportedconfig.get("connector", {}).get("timezone", "UTC").strip(): it fired hardest on the code written to be safe. On the project where this was found, the defaulting form was the large majority of the 31 SAFE803 findings.
The fallback slot is now checked for the three default nullable_methods names that have one - get, pop and next, all taking it second - plus getattr, which takes it third and is handled for anyone who adds it (it is not a default entry). The fallback must be a literal whose value is non-None by construction - a dict, list, set or tuple display, a string, a number, a bool, ..., a comprehension, a generator expression or a lambda. Everything else still reports:
d.get(k, None).x # the fallback IS None
d.get(k, fallback).x # a name is opaque; it may well BE None
d.get(k, compute()).x # ...as may a call's return value
d.get(k, a or b).x # an or-chain falls through to its last operand
d.get(*args).x # a splat hides the positional count
d.get(k, **kw).x # ...as does a keyword splat
d.get(k, default=f).x # a keyword argument is not positional
Grouping is peeled first, so d.get(k, ({})).x is recognised as the dict literal it is; (None) peels to None and still reports.
Two limits worth stating, because the suppression is syntactic and does not prove the call cannot return None. A mapping that stores None under the key returns it whatever the default is, and next(it, {}) yields whatever the iterator produced if it produced None; neither is visible in the syntax. Deciding those needs value tracking the rule does not have, so it takes the miss instead of firing on every defaulting lookup, which is the noise the issue was filed about. Both are pinned by tests so the gap is recorded rather than discovered.
It is scoped to those names rather than "any call with two arguments": session.find("Model", 42).name and cursor.fetchone(1, 2).value take arguments that are not fallbacks and still report. JavaScript is unchanged, deliberately - Map.prototype.get ignores a second argument rather than returning it, so treating one as a fallback there would hide a real null dereference.
Not changed: the duplicate-looking findings reported alongside this. config.get(a, {}).get(b, "x") produced two SAFE803 on one line, and four wild cases looked like exact duplicates. They are two different dereferences, differing by column; the rule makes a single pass and visits each node once. What makes them look identical is that the CLI gutter is line-addressed.
Security#
- Dev lockfile:
certifiandfilelockbumped to clear four Dependabot advisories.certifi2026.7.22 -> 2026.10.23 (critical: the previous releases bundle emSign root CAs whose intermediate CA keys were compromised; fixed upstream in 2026.10.18) andfilelock3.32.2 -> 4.2.4 (one high and two low, all fixed in 4.2.1; the high one is aReadWriteLocksymlink-planting issue on the SQLite lock database). Both are transitive dev dependencies - the published wheel's only runtime dependency istree-sitter, so no released artefact is affected and no version bump is needed. Lock-only change, sopublish.yml's version gate skips it.
2.15.0 - 2026-10-28#
Added#
logging_on_error(SAFE203) gained per-languagelog_methodslists.log_methods(Python, bare key) pluslog_methods_javascript/log_methods_typescript/log_methods_java/log_methods_php/log_methods_cpp. The accepted names had been hardcoded in the rule; they are now configurable like every other name list, matched with the receiver discarded ($logger->notice($e)resolves tonotice). Per language rather than one flat list because whether a stdout write counts is a question about the language's culture: Java's list deliberately omitsprintln, sinceSystem.out.printlnin a catch block is the anti-pattern the rule exists to find.
Changed#
- SAFE203
logging_on_error: a handler that re-raises is not swallowing the error (#159, #199). The rule asked for a logging call in everyexcept/catchbody and said the error was "swallowed" when it found none. A handler that re-raises swallows nothing, and logging there actively hurts - you get two reports of one failure, the second at the wrong altitude, which is why the standard advice is to log at the boundary that handles the error rather than at every frame it passes through.
The test is now whether every exit path out of the handler leaves by raising, which is stricter than "contains a raise" in the direction that matters:
except ValueError as err:
raise RuntimeError("bad") from err # clean: the add-context re-raise
except ValueError as exc:
print(f"failed: {exc}") # clean: report, then propagate
raise
except ValueError:
if never_true:
raise
return None # still reported: this path really does swallow
When only some arms propagate, the finding anchors at the arm that falls through, not at the except line. On a handler with several branches, "something in here leaks" leaves the reader to work out which; the line number is the whole value of the report. The clause stays the anchor when the handler falls through as a unit, because there the handler itself is the problem.
Language-agnostic from the start rather than Python-first: all six languages with try/catch (Python, JavaScript, TypeScript, Java, PHP, C++) share the exit-path analysis. What differs is what re-raising means in each. Python needs no check on what is raised, because a raise inside an except chains the active exception automatically. The C-family languages have no such automatic chaining, so the thrown value is examined: re-throwing the caught binding counts, and so does a fresh error that carries it along -
catch (IOException e) {
throw new ConfigException("loading " + path, e); // clean: the original is attached
}
which is the C-family spelling of raise RuntimeError(msg) from err. Exempting the Python form while reporting the Java one would be the same one-act-judged-two-ways problem as the print question below. throw new Error("x") with no mention of the caught value still discards the original and still wants logging; so does throw makeError(e) outside C++, because a factory's return value need not be a wrapper (C++ constructs the thrown value with a plain call, so there it counts). C and Rust have no try/catch, and Rust's analogue SAFE207 already had its own propagation logic; Go has neither, its nearest rule being SAFE209 empty_error_check.
Python's log_methods also accepts print, print_exception and print_exc (#199). Rust's SAFE207, the documented analogue of this rule, has always counted println! / eprintln! / print! as making the failure visible, so one act was being judged two ways across the two languages; and reporting Rich's console.print_exception(show_locals=True) as an unlogged error branch is the rule contradicting the code's obvious intent. Scoped to Python, where a script or CLI legitimately prints its own failure.
Four of safelint's own # nosafe: SAFE203 annotations are gone as a result. All four sat on cleanup-and-reraise handlers in _skill_install.py and core/_cache.py - close the orphan fd, drop the temp file, raise - which the rule now reads correctly; their comments already said "not a swallow". 33 remain, in two groups: the _diagnostics.print_* handlers the architecture docs describe (the rule recognises only logger-shaped names, and those are deliberately spelled print_* so that SAFE304 exempts them), and the ten optional-grammar except ImportError fallbacks across languages/*.py and __init__.py, where a missing grammar is surfaced later as an install hint rather than at import time. The count is up by one on 2.14.x: the new parent-module stat helper treats an absent file as a value rather than an error.
Measured. Python, where the exit-path and print halves both apply: Django 1476 -> 1146 (-22%), Rich 109 -> 68 (-38%), FastAPI 72 -> 37 (-49%), Flask 57 -> 38 (-33%), requests 81 -> 60 (-26%). The C-family gets the exit-path and wrapping halves, and the wrapping one dominates there because throw new X("ctx", e) is the standard way to add context: Guava 1519 -> 1140 (-25%), Commons Lang 168 -> 139 (-17%), laravel/framework 669 -> 593 (-11%), Guzzle 370 -> 337 (-9%), axios 91 -> 86, zod 138 -> 136; express, elysia, monolog, fmt and leveldb unchanged, having neither shape. SAFE203 is enabled by default, so this moves existing finding counts.
- SAFE102
nesting_depthno longer countswithortryas a nesting level (#166). The rule exists to keep decisions shallow - that is what makes a function hard to follow and to test - and a resource or error-handling wrapper adds indentation without adding a branch:
with open(path) as fh: # depth 0
for row in fh: # depth 1
if row: # depth 2 - clears the default cap
handle(row)
What settles it is actionability rather than tidiness: a developer told to reduce nesting in with session: for x: if y: has no good move short of restructuring resource handling, which is a worse outcome than the nesting it was flagged for. The finding was unactionable even where the count was literally correct.
This extends a principle the rule already applied rather than introducing one - Java's synchronized block and Rust's unsafe block were never nesting steps, for exactly this reason. Removed from Python (with, try), Java (try, try-with-resources), JavaScript / TypeScript (try), PHP (try) and C++ (try); Rust, Go and C had none to remove, so all nine languages now agree. switch and match remain steps, because they branch.
Measured: Django 1301 -> 722 (-45%), Guzzle 73 -> 42 (-42%), requests 24 -> 16 (-33%), Rich 81 -> 65 (-20%). The 45% matches the figure this issue reported from a different sample, which is a good sign the effect is stable rather than sample-specific.
nesting_depth is enabled by default, so this moves existing finding counts - which is why it is a MINOR release rather than a patch, and why the whole accumulated 2.14.4 stack ships as 2.15.0.
- SAFE802
return_value_ignored: the Pythonflagged_callsdefault is trimmed from sixteen names to seven (#156). The list had been ported from C/POSIX semantics, where checking the return code is correct and necessary, without adjusting for Python's. Two groups left it.
Six return None, so the rule demanded the caller check a value that cannot exist: remove, unlink, rename, makedirs, mkdir, rmdir. The os.* forms all return None; the pathlib forms return either None (Path.unlink, Path.mkdir, Path.rmdir) or a Path that nothing acts on (Path.rename, Path.replace). Because names are matched with the receiver discarded, these also covered list.remove and every other method of the name. This half, and the os-name tests covering it, are @Jah-yee's work (PRs #216 / #227).
Three return a value idiomatic Python discards: write (a byte count), seek (the new position) and truncate. On Django these were 404 of the 614 findings left after the six above went, so they were the larger half of the problem rather than a tidy-up after it - a correction to this issue's original framing, which identified the None-returning names as the main cause.
What stayed, and why: send and sendfile, which return a byte count and may transfer fewer bytes than asked; run / call / check_output, because subprocess.run returns a CompletedProcess whose returncode matters; and replace, deliberately ambiguous, since str.replace and Path.replace both return a value worth keeping while os.replace does not. sendall went too: it returns None and raises on error, so it fails the same test as the six above - sendall exists precisely so the short-write check is unnecessary, which is the opposite of what an earlier draft of this entry concluded from it. The docs now state that matching ignores the receiver, with asyncio.run() as the worked example.
Measured: Django 821 -> 133 (-84%), Rich 57 -> 2, requests 61 -> 36. The rule is disabled by default, so no existing user's output moves unless they have opted in. flagged_calls_c is unchanged - there the return code genuinely is the point - and every removed name is still reachable by listing it in flagged_calls.
-
CI: bump six pinned GitHub Actions (folded in from Dependabot PRs #236 and #238):
astral-sh/setup-uvv10.2.0 -> v10.3.0,anthropics/claude-code-actionv1.0.244 -> v1.0.248,actions/upload-artifactv7.0.1 -> v7.0.2 andactions/download-artifactv8.0.1 -> v8.0.2, across nine pin sites. Still SHA-pinned. Each SHA was verified against its tag, dereferencing where the tag is annotated:claude-code-action's is, so the naive ref lookup returns the tag object rather than the commit - the same trap as the previous round.actions/checkoutis untouched despite also sitting at av7.0.1; matching on the pinned SHA rather than the version comment is what kept the two apart. The second round (#238) addedanthropics/claude-code-actionv1.0.248 -> v1.0.255 andpypa/gh-action-pypi-publishv1.14.2 -> v1.14.3, both annotated tags and both dereferenced before pinning. Workflow only - nothing in the published wheel changes. -
Dev lockfile refreshed (folded in from Dependabot PR #239):
virtualenv21.14.5 -> 21.15.1, a transitive dev dependency via pre-commit. Regenerating with the currentuvalso moves the lockfile format fromrevision = 3torevision = 5; that is this repository's ownuvwriting its current format, not something the bump imposed, anduv lock --checkplus a fulluv syncand test run confirm it reads cleanly. The resolved version is newer than the 21.14.13 the PR proposed, because regenerating takes the latest and 21.15.1 landed in the meantime. Nothing in the published wheel changes -virtualenvis not a runtime dependency. -
SAFE304
side_effects:read,status,spawn,outputandrecvare no longer Rust defaults (#178). Call names are resolved with the receiver discarded - deliberately, so thatfs::read_to_stringandstd::fs::read_to_stringboth match one entry - which is right for free functions and wrong for methods. As bare method names these five matched whatever they were called on, and Rust's standard library spends those verbs on non-I/O operations that are pervasive in ordinary code:RwLock::readfor locks,mpsc::Receiver::recvfor channels,tokio::spawnfor tasks,statusandoutputas accessors on any domain type.writeis not among the five and still fires onMutex::write(): it has to stay for thewrite!macro, whose target is instead checked syntactically (see the SAFE304 entry below). The same caveat applies toflush,connectandsend_to, which remain bare names on the list. Confirmed on Ruff atcrates/ruff_db/src/files.rs:520(a salsa query accessor),system/memory_fs.rs:104(RwLock::read) andvendored.rs:93(a zip-archive wrapper).
They remain in SAFE303's list, where the enclosing function's own name must also signal purity - the same split Go's list already uses for Get / Post / Do / Exec / Query. The specific spellings (read_to_string, read_dir, write_all, read_line) carry the same coverage without the collisions. Add any of them back via io_functions_rust.
- SAFE801
tainted_sink: barequeryandexecuteare no longer Rust sink defaults (#180). Rust has no database API in its standard library, so as barewords they matched any builder, any LSP snapshot accessor and any closure parameter of that name. Validating every finding rather than sampling: 1 defensible out of 9 across ty and Ruff, with 30 of Ruff's 55 beingsnapshot.query()on aDocumentSnapshot. The crate-specific spellings stay (query_as,query_scalar,execute_batch), as doarg/args/open; list your crate's entry point explicitly if you call raw SQL through a barequery.
Fixed#
- Five default-on rules now skip test code (#198). SAFE101
function_length, SAFE203logging_on_error, SAFE302global_mutation, SAFE304side_effectsand SAFE401resource_lifecycleput the overwhelming majority of their findings in test files, where the pattern they flag is conventional:
# tests/test_requests.py
def test_session():
s = requests.Session() # SAFE401: a session scoped to one test
print(render(result)) # SAFE304: observing output IS the test
On Requests that shape was 91 of SAFE401's 94 findings, and the three in library code - one of them a genuine unclosed zipfile.ZipFile in utils.py - were buried under them. The status quo was not a conservative default but a loud one, and the loudness is what hid the true positives. safelint already applied this reasoning to its own test tree through per-file-ignores; these five simply never got it.
Controlled by skip_test_code (default true) and test_dirs, the latter being the key SAFE601 / SAFE701 / SAFE702 already read. A file is test code when it sits under a test_dirs entry or its filename uses a convention nothing but a test uses (foo.test.ts, foo_test.go, FooTest.java). Set skip_test_code = false per rule for the strict reading.
Two decisions inside that are worth stating, because both were wrong in a first draft:
test_dirsdefaults to four names,["tests", "test", "__tests__", "spec"], not justtests. A default oftestsalone missed Express entirely, where the directory istest(singular) and holds 161 of its 165 SAFE101 findings - and a default that needs per-project tuning before it works is not the useful default this issue asked for. The same widening applies to SAFE601 / SAFE701 / SAFE702, which read the same key and are strictly better for recognising more real test layouts.- A bare
test_prefix does not exclude a file. Reusing the existing test-file detection wholesale skipped all five rules inside safelint's ownsrc/safelint/rules/test_coverage.py, a rule implementation, and would do the same to any project'sTestDataFactory.javaundersrc/main/java. Finding tests and excluding production code are different risks and the looser signal is only safe for the former. safelint's own SAFE004unused_suppressioncaught this, by noticing the# nosafe: SAFE203annotations in that file had stopped suppressing anything. Python tests are unaffected, sincetests/test_foo.pymatches on the directory: re-measuring after the narrowing moved Django by 3 findings and nothing else at all. - A relative
test_dirsentry matches at any depth below the working directory, not only at the project root. A monorepo puts tests per package (services/api/tests/,packages/core/__tests__/), and anchoring at the root missed every one of them -conftest.pymatches no filename convention either, so a whole monorepo's test tree kept reporting. The working directory bounds the search, which is what stops the answer depending on where the repository is checked out: a clone living in~/tests/myprojmust not have all of its source treated as test code. An absolute entry stays anchored to exactly the path given. This is the same reasoning the Rusttests/detection applies to cargo workspaces. The file path is also normalised before matching, becausePath.absolute()prepends the working directory without collapsing..- sotests/../src/service.pykept atestscomponent and had all five rules skipped on it. The collapse is lexical, preserving this module's existing choice not to follow symlinks. The inclusion path (test_functions_only, SAFE701/702) deliberately does not normalise: leaving..in place is what contains atest_dirsentry that climbs out of the project root, which is security finding H3. Relative entries are anchored at the config root, discovered by walking up from each file rather than taken from the working directory:safelint check /abs/projectrun from elsewhere otherwise left every relative entry unmatched, so the feature silently did nothing for an ordinary CI invocation.skip_test_codeis validated as a boolean, so a quoted"false"fails loud instead of reading as truthy and ignoring the opt-out.
Measured across five languages, every project linted from its own root (test_dirs is project-root-relative):
| Project | Language | Before | After |
|---|---|---|---|
| Express | JavaScript | 200 | 27 (-87%) |
| Axios | JavaScript | 559 | 83 (-85%) |
| Requests | Python | 187 | 61 (-67%) |
| laravel/framework | PHP | 1074 | 349 (-68%) |
| Elysia | TypeScript | 309 | 104 (-66%) |
| Rich | Python | 352 | 139 (-61%) |
| Monolog | PHP | 99 | 41 (-59%) |
| Flask | Python | 104 | 50 (-52%) |
| Commons Lang | Java | 273 | 132 (-52%) |
| Zod | TypeScript | 460 | 259 (-44%) |
| Django | Python | 2336 | 1314 (-44%) |
| PetClinic | Java | 7 | 2 |
SAFE102 nesting_depth is deliberately not in the group. It was 37% test code in Python but 6% in JS/TS, and safelint relaxes it for its own tests only because its test helpers happen to nest - that is a property of this repo, not a general one.
- SAFE907
unvalidated_request_inputnow recognises Laravel's actual validation idioms (#157). The rule accepted$request->validate(...)and theValidatesRequeststrait form$this->validate($request, ...), and nothing else - soValidator::make($request->all(), $rules)was reported as unvalidated input on the line that validates it. That is not a corner: on FreeScoutValidator::makeoutnumbers$request->validateby 19 to 1, and the rule is switched on by thelaravelpreset, so users met this by opting into the preset rather than the rule. Four forms now clear a read: - the
Validatorfacade,Validator::make(...)/Validator::validate(...). The unqualified name (the aliased import every Laravel file writes, with or without a leading namespace separator) and the fully-qualifiedIlluminate\Support\Facades\Validatorare accepted; some other namespace'sValidatoris a different class and is not; - a validator built from the request data and then validated,
$this->validator($request->all())->validate()- which is how Laravel's ownRegistersUserstrait is written, and the one SAFE907 finding on laravel/framework itself; - a one-step local alias of the request data:
$post = $request->all();...Validator::make($post, $rules), the read-then-massage-then-validate shape named in the issue; - a Form Request parameter,
store(StoreUserRequest $request), which clears the whole method because the framework ran that class'srules()before the body was entered. Matched on the type's final name segment ending inRequestwhile not being the baseRequest/FormRequest, neither of which carries rules of its own.
Each still requires the request, and only the request: Validator::make($defaults, $rules) validates something else and does not clear a $request->all() elsewhere in the method; a variable never assigned a request read does not stand in for one, nor does one that has since been rebound to other data; and $foo->request is an ordinary property, not the framework request - every property read contains a bare request name node, so considering only whole variable and property expressions is what keeps an unrelated field from clearing a real finding.
The Form Request half is a name-based heuristic and cannot be more than that: confirming StoreUserRequest really extends FormRequest needs the other file. A BillingRequest parameter that is not a Form Request clears the method too. #157 specified this test; rename the parameter or ignore the rule for the file if the suppression is unwanted. Measured on FreeScout: 13 -> 2, the two remaining being genuine unvalidated bulk reads (one of them the MailboxesController site the issue names as its true positive). laravel/framework 1 -> 0.
- SAFE908
csrf_protection_disabled:$exceptis only CSRF-relevant inside the CSRF middleware (#162). The PHP side matched a$exceptproperty by name with no class context. Laravel shipsTrimStringsandEncryptCookieswith an$exceptof their own - one lists fields not to trim, the other cookies not to encrypt - so the rule fired twice on the contents of every unmodifiedapp/Http/Middleware/. The rule's own docstring had recorded the limitation as an accepted trade while it was opt-in; thelaravelpreset then turned it on, which made it a guaranteed false positive instead.
The class must now be named VerifyCsrfToken or extend it: a bare name, a namespace-qualified one, or the use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; alias Laravel's own scaffolding writes. The alias has to be resolved rather than matched, because TrimStrings and EncryptCookies alias their bases to the same name Middleware. A trait is not followed into the class that mixes it in, so an $except declared in a trait is not reported - the quiet side, since reporting every trait $except is the defect being fixed. Measured on FreeScout: 2 -> 0, with its own VerifyCsrfToken (an empty $except) correctly clean and a non-empty one still reported; laravel/framework clean across 734 files.
- SAFE208
result_unwrap_outside_tests: Cargo's test layouts count as test context (#172). Test detection searched for#[test]/#[cfg(test)] modon the item or an ancestor in the same file, which misses the two shapes Cargo makes idiomatic: - a file under a
tests/directory, where integration tests carry no#[cfg(test)]at all because the directory is the gate, so every.unwrap()in such a file was reported; - a module gated from its parent,
#[cfg(test)] mod helpers;inlib.rs, where the attribute lives in the parent file and the module's own file contains no marker.
A tests component under src does not count: src/tests/helpers.rs is ordinary crate source in a module called tests, and when it is gated the #[cfg(test)] mod tests; in its parent is what says so. Cargo's integration tests live in a tests/ that is a sibling of src, never inside it.
Both are whole-file answers, so they are resolved once per file and cached rather than re-derived per unwrap. The cache key carries a stat signature of the parent module files, because it is process-global and safelint also runs as a library inside long-lived hosts: keyed on the path alone, deleting a #[cfg(test)] from lib.rs would go on returning the stale "gated" answer for what is now production code. Measured: ripgrep 125 -> 99 (-21%), Ruff 1234 -> 1063 (-14%).
- SAFE207
unlogged_error_branch: two handler shapes that are not swallowing the error (#161). Both were reported as unlogged, and following the advice would have meant adding a message with nothing useful in it. -
Logging through a same-file helper. A body that calls a function defined in the same file whose own body contains a log call is routing the error, not dropping it:
Err(e) => self.fail(&object.name, e.to_string()), // was reported as unlogged fn fail(&mut self, object: &str, reason: String) { warn!(object, %reason, "object failed; continuing"); self.outcome.failed.push((object.to_string(), reason)); }The log call is the whole test: a helper that only records to a list and never logs is not credited, and such a branch still reports. One call hop, too - a transitive search over the file would eventually exempt anything. In the file the issue was found in, this shape was 6 of 9 findings. - An arm that enumerates a single error variant and binds nothing.
Err(store::Error::NotFound { .. }) => Ok(false)implements a documented "treat not-found as false" contract while the next arm propagates everything else, and it has no error value in scope to log. Binding, not syntax, is the test, so the wildcard formsErr(E::NotFound(_))andErr(E::Io { source: _ })are exempt too. An arm that actually binds part of the error (Err(E::Io(e)),Err(E::Io { source }),Err(E::Io { source: inner })), a plain binding (Err(other)) or a wildcard (Err(_)) still reports, because there the author either has a value to log or has not discriminated anything.
Measured: Ruff 211 -> 180 (-15%); ripgrep unchanged at 34, which has neither shape.
-
SAFE601
missing_assertions:assertion_calls_rustcovers the snapshot andmatches!macro families (#177). Snapshot testing is the dominant assertion idiom in modern Rust suites, and a test whose only assertion was a snapshot read as having none - the rule telling a passing, asserting test to add an assertion. Added the eleveninstamacros (assert_snapshot,assert_debug_snapshot,assert_json_snapshot,assert_yaml_snapshot,assert_ron_snapshot,assert_toml_snapshot,assert_csv_snapshot, the two compact forms,assert_binary_snapshot,assert_display_snapshot) plusassert_matches/debug_assert_matches. Measured on Ruff: 36925 -> 34505. ripgrep is unchanged at 2900, using no snapshot crate. -
The Django preset no longer narrows
nullable_methodsto a single name (SAFE803). The preset carriednullable_methods = ["first"]forQuerySet.first(), written when the rule OR'd aClassVarwith the configured list - so the entry addedfirstto the built-in names. Presets replace a key wholesale, and the single-owner change above moved those names intoDEFAULTS, which turned the entry into a subtraction: a Django project enablingnull_dereferencecheckedfirstalone and silently lostget,pop,find,next,one_or_none,scalar,scalar_one_or_noneandfetchone.firstis a shipped default in its own right, so the entry is deleted. A guard now asserts that no preset, for any language, drops a shipped default from any list-valued rule key. -
TypeScript falls back to the JavaScript default lists, not Python's. The TypeScript → JavaScript step existed only on the user's-TOML path.
DEFAULTSdeclares no_typescriptkey forsinks,sanitizers,sources,flagged_callsornullable_methods, so a rule falling back to a shipped default for a.tsfile skipped JavaScript and landed on the bare key - which is how Python is spelled there. A TypeScript caller got Python's lists and never sawFunction/spawn/writeFileSync/querySelector. The lookup order now has one owner (lang_config_key_chain) consulted by both paths. The bare key is deliberately not in that chain: in a user's TOML it is Python's key, and letting a.rsfile inherit a baresinks = [...]would silently widen every other language. -
SAFE208
result_unwrap_outside_testsis anchored at the crate root, not at a path component. Cargo's rule is that integration tests live in atests/directory that is a sibling ofsrcat the crate root, which is the directory holdingCargo.toml. Two lexical approximations both got this wrong: matching anytestscomponent suppressedsrc/tests/helpers.rs, ordinary crate source in a module namedtests; adding "nosrccomponent before it" made the answer depend on where the repository happened to be checked out, so a developer keeping work under~/srcsaw every integration test still reported (cancelling the fix for them) while a checkout under~/testshad its production code silently exempted. The crate root is now resolved by walking up to the nearestCargo.toml, and the decision is made on the path relative to it; a workspace member resolves to itself because it has its own manifest. NoCargo.tomlabove the file means the root is unknown and the finding is reported. Corpus counts are unchanged (ripgrep 99, Ruff 1063), which is the point: the fix removes the location dependence without moving the result. -
SAFE105
no_recursion: a comment in a Java argument list no longer hides recursion. tree-sitter-java declaresline_comment/block_commentas extras, and extras are named nodes, so a comment inside anargument_listorformal_parametersappears innamed_childrenand inflates every count taken from one.fact(n - 1 /* step */)insideint fact(int n)counted two arguments against one parameter, read as an arity mismatch, and dropped a genuine self-call. Named-argument comments are idiomatic Java and this is the losing direction: on Guava it was hiding real recursion atRegularImmutableMap.java:166, wherefromEntryArrayCheckingBucketOverflowcalls itself with a/* throwIfDuplicateKeys= */marker. Guava 475 -> 476; the five sites that count parameters or arguments now share one helper. -
SAFE501
unbounded_loops: three exits and boundaries that were missing. All three are the #170 / #179 invariants failing to hold in a language the issues did not sample. - C++
co_returnis an exit. A coroutine leaves viaco_return, a distinct grammar node, so a loop whose only exit wasco_returnstill reported. - A
returnin a nested PHP loop does not clear the outer loop. PHP has no break-boundary tuple - itsbreak Nhandling counts levels instead - so the return search was bounded by function types alone andwhile (true) { foreach ($rows as $r) { return $r; } }read as having an exit. The nested loop may run zero times, which is the invariant #170 documented and tested everywhere else. -
C++
for_range_loopis a boundary. The range-basedfor (auto x : v)is a distinct node fromfor_statementand was in neither the break nor the return boundary set, so a nested range-for bounded neither. Thebreakhalf of that predates #170. -
SAFE302
global_mutation: two JavaScript binding shapes. Avarinside aclass_static_blockwas credited as shadowing the global, butstatic { }is its own scope and thevardoes not hoist out of it - so a genuine write toselfwas suppressed. And a default-valued parameter (function f(self = {})) parses as anassignment_patternwith the identifier onleft, which the binding check did not unwrap, so the parameter bound nothing as far as the rule could see and a write to that ordinary local was reported as a global mutation. -
An interrupted atomic write no longer leaves a temp file behind. Both atomic-write helpers - the cache's
_atomic_write_jsonand the skill installer's_write_file_replace- cleaned up in anexcept OSError. AKeyboardInterruptis not anOSError, so Ctrl-C during a write skipped cleanup entirely and orphaned a.json.tmpin the cache directory or a.safelint-section-*.tmpin the user's skills directory. Both now clean up in afinally, which covers every exit path including interrupts and cancellation, and the error still propagates unchanged. The fd-leak guard aroundos.fdopengets the same treatment, so an interrupt in that window cannot leak the raw descriptor either. -
Rule default lists now have a single owner, so a hand-built config behaves like the shipped one. Five dataflow rule classes carried
ClassVarcopies of theirDEFAULTSentries, consulted when a caller constructs a rule directly with a config that omits the key. Being second copies they drifted, in both directions: flagged_callskept the pre-#156 sixteen names, so such a caller still hados.remove()andf.write()flagged after the default was trimmed;nullable_methodshad never matchedDEFAULTS, which held an empty list while the copy held the nine names the docs have always documented - and the Python branch OR'd the two, so settingnullable_methodsto narrow SAFE803 produced all nine regardless and there was no way to drop one. Every other language replaces; Python now does too;sinks/sanitizers/sourcesagreed withDEFAULTSbut were still duplicated, and spelledsubprocess.callas the Tree-sitter node-type constant_py.CALL, which equals the function name only by coincidence.
All five copies are deleted. The fallback is read from DEFAULTS through one accessor, which also gives every language the documented default rather than [] - the fallback had been Python-only, so a library caller linting Rust, Go, Java, PHP, C or C++ with a partial config received a silent clean bill of health. A drift test was written first and then removed as unnecessary: there is nothing left to drift.
-
SAFE802: a scalar
flagged_callsnow raises instead of matching single characters (Python). Python was the one language whose list bypassed_validated_string_list, soflagged_calls = "remove"became{'r','e','m','o','v'}-os.remove(...)stopped firing and an unrelatedr()started. The other languages have rejected this since the JS-family sites were converted; the Python site and the Pythonnullable_methodssite were never converted. Both now raiseConfigValueErrorlike the rest. This mattered more than usual because #156's own guidance tells users to edit that key. -
A rule built with a partial config no longer reports warning-severity findings as blocking.
BaseRule.__init__fell back to a blanket"error", which disagreed with every warning-severity rule - SAFE105, SAFE501, SAFE802 and the rest - so a direct library caller got findings marked blocking that the shipped config marks advisory. The fallback is now the rule's ownDEFAULTSseverity. -
SAFE501
unbounded_loops: areturnis an exit, in all nine languages (#170). The rule searched only forbreak, so an infinite loop whose exits arereturnread as having none:
fn poll(done: bool) -> u32 {
loop {
if done { return 1; } // was: "loop has no break - potential infinite loop"
}
}
A return ends the enclosing function and so leaves every loop inside it. In Rust it is the more common exit, because ?-propagation forces it - you cannot ? out of a loop with a break - and on ripgrep it accounted for 7 of 7 findings, the rule's entire output there. The issue reported Rust; the blind spot was in all nine languages the rule covers, confirmed by running the same shape through each.
A return inside a nested loop deliberately does not clear the outer one: the inner loop may run zero times, in which case the return is never reached and the outer loop really is unbounded. A return inside a nested function or closure belongs to that function and likewise does not count. Both are pinned by tests.
- SAFE501
unbounded_loops: abreakorreturninside a Rust macro body is now seen (#179). tree-sitter parses a macro's arguments as an opaquetoken_tree, so statements inside are never typed nodes - inloop { select! { .. break; .. } }thebreakexists only as an anonymous token and nobreak_expressionappears in the tree at all. Real instance: ty'scrates/ty_project/src/watch/watcher.rs:44, aloopwith three literalbreak;statements reported as having none.
The keyword tokens are present, just untyped, so the rule now looks for them directly. The issue's own preferred fix was the blunter "a body containing any token_tree cannot be claimed break-less"; that was implemented first and measured too broad - loop { println!("x"); } is a genuine infinite loop and stopped being reported, and a println! inside a loop is ordinary Rust. A macro carrying no exit keyword therefore still reports, and because a token tree is still tokenised, the word break inside a string literal does not count. continue is excluded: it re-enters the loop.
Both fixes are needed for that ty file, as the issue notes - its exit is a return and it sits inside the token tree.
Measured together:
A switch arm stops a break but not a return, so the return search uses the break boundaries minus the switch-like nodes. Reusing them wholesale kept reporting for (;;) { switch (x) { case 1: return 1; } } - the classic state-machine loop, and common enough that discounting switch arms is what takes Guava, fzf and LevelDB to zero.
Inside a macro body an exit keyword is credited only when the same body writes no nested loop and no closure. A token_tree has no structure to walk, so a break there cannot be told apart from one belonging to a for the macro itself writes, nor a return from one inside a closure. The unit of judgement is the whole macro invocation, not each token tree: one select! nests several, so judging them separately let an inner tree holding just the break look free of the for around it.
| project | before | after |
|---|---|---|
| Guava | 126 | 0 |
| Ruff | 174 | 134 |
| Django | 71 | 60 |
| fzf | 12 | 0 |
| Rich | 29 | 26 |
| curl | 9 | 5 |
| ripgrep | 7 | 0 |
| LevelDB | 3 | 0 |
| requests, Cobra, Axios | 2, 0, 0 | unchanged |
333 findings removed. ripgrep reaching zero is #170's own Verify condition.
- SAFE105
no_recursion: a Rustusenow binds only what it imports, not the segments of its path. The resolver swept every identifier under the declaration, so a path segment read as a bound name and silenced genuine recursion in a function called after it:
fn b(n: u32) -> u32 {
use a::b::{c}; // binds c only - NOT b
b(n - 1) // was: suppressed. Real recursion.
}
Three shapes were affected: a braced list (use a::b::{c} read as binding b), a wildcard (use a::b::*, likewise), and a braced list's own root (use a::{b::c, d} read as binding a). The walk is now structured by node kind rather than flat: a plain path binds its trailing segment, a wildcard binds nothing nameable, a braced list binds only its entries, self inside a list binds the path's trailing segment (use a::b::{self, c} does bind b), and an as clause binds only its alias. Unrecognised roots (crate, super) contribute no name, which leaves the call reported. Found by CodeRabbit reviewing #223's code while it looked at #216; shipped in 2.14.4rc1 through rc3.
-
CI: the fork-PR base guard re-reads the base before closing. The job condition evaluates against the triggering event's snapshot, which goes stale. If an author retargeted a fork PR to
developmentwhile an earlier run was still queued, that run would close the PR they had just corrected - andediteddoes not refresh an in-flight run's snapshot. The step now reads the current base from the API and exits quietly when it is alreadydevelopment, checked before the explanatory comment as well so a corrected PR gets neither a close nor a misleading notice. Workflow only. Found by CodeRabbit on #216, whose author had performed exactly that retarget. -
SAFE102
nesting_depth: anelse ifchain is no longer counted as nesting (#154). A flatif / else if / else ifchain branches once, but each continuation was counted as a further level, so a chain of N was over-counted by N-1:
function f(x) {
if (x === 1) { doA(); }
else if (x === 2) { doB(); }
else if (x === 3) { doC(); }
else if (x === 4) { doD(); } // was: SAFE102 nesting depth is 4 (max 2)
}
The issue reported this for JavaScript and TypeScript. It affected seven of the nine languages: JavaScript, TypeScript, Java, Rust, Go, C and C++ all scored the sample above at depth 4. Python and PHP were already correct, because their grammars give elif / elseif a node type of its own which was never in the depth set. nesting_depth is enabled by default, so any codebase in the other seven using the most ordinary branching idiom got findings out of the box.
The two grammar shapes are both handled: the continuation if either sits under an else_clause (JavaScript, TypeScript, Rust, C, C++) or is the alternative child of the enclosing if (Java, Go). Only if nodes are exempt, and only when they are the continuation itself, so three cases keep counting as they should: else { if (..) } written with braces (the inner if's parent is the block), else while (x); which is legal C and a real level, and a genuine nested if inside an else if body.
Measured: Guava 1121 -> 956, fzf 178 -> 158, Chart.js 62 -> 44, ripgrep 83 -> 70, Axios 49 -> 39, Zod 91 -> 82, Express 5 -> 4; 236 findings in total. Cobra and Spring PetClinic are unchanged, both being small enough to have no else if chain inside a function already near the depth cap.
- SAFE302
global_mutationno longer reports a write to a local that shadows a browser global (JavaScript) (#202). Every configured global namespace is also an ordinary variable name, and a local declaration shadows the global completely. The pre-arrow idiom for carryingthisinto a nested function was therefore reported as mutating a global:
function Headers() {
const self = this; // a LOCAL alias for `this`
return function set(key, value) {
self[key] = value; // was: SAFE302 writes to global "self"
};
}
Found in Axios, three times in lib/core/AxiosHeaders.js, which made a library's ordinary self-reference indistinguishable from a genuine window.XMLHttpRequest = null. A write is now skipped when its root name is bound by an enclosing declaration: a const / let / var declarator, a function parameter (including the TypeScript typed form and an arrow function's single unparenthesised parameter), or a catch binding, in any scope up to and including module scope. let / const are matched per block and var is matched anywhere in the enclosing function body, which is its real scope. A destructured binding (const { self } = x) is deliberately not recognised: failing to see a binding reports a write that is already reported today, whereas inventing one would silence a genuine global mutation. Axios 157 -> 154 SAFE302 findings; the remaining 154 are test files assigning window.XMLHttpRequest as mock setup, which is #198's mechanism.
- SAFE304 / SAFE303: Rust
write!/writeln!is checked against its target instead of assumed to be I/O (#171).write!is not an I/O function in Rust - it expands towrite_fmton its first argument, which may implementstd::io::Write(I/O) orstd::fmt::Write(a string buffer, no I/O). Both of these used to fire, and neither performs I/O:
impl fmt::Display for X {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "hello") // formatting, not I/O
}
}
let mut s = String::new();
write!(&mut s, "x").unwrap(); // string building
Where the first argument is a plain binding (a leading & / &mut is stripped), its own declaration decides: a parameter whose type's base name is String exactly, or ends in Formatter, or a local initialised from String::new / String::with_capacity / String::from / format!, is a non-I/O target. The base name is resolved by stripping generic arguments first, then references, lifetimes and mut / dyn, then path segments, so &mut fmt::Formatter<'_> and &mut TypeWriter<'_, '_, 'db> both resolve correctly. Matching is deliberately not a substring test (StringWriter may well implement std::io::Write) and deliberately not exact on Formatter either, since domain formatters follow the XFormatter convention and are the same thing semantically - Ruff's own PyFormatter is 82 of its write! sites. Anything else - a path expression, a call, an unknown binding - keeps reporting, so writeln!(std::io::stdout(), ..) is unaffected and the unresolved case stays a finding rather than being silently dropped. SAFE303 shares the matcher and so is fixed by the same change. ripgrep 83 -> 62 SAFE304 findings from this alone (-> 49 together with the defaults change above); Ruff 1410 -> 985 and SAFE303 74 -> 62. One of Ruff's comes from fixing a related defect found while scoping the check: the search returned on the first let whose name matched, so a non-String binding earlier in the function hid a later let s = String::new(). The nearest in-scope binding now decides.
- SAFE801
tainted_sink: invoking a local binding whose name collides with a Rust sink is no longer a sink call (#180). A barequery(nested)whose callee is a parameter or alet-bound closure invokes that local, not the configured free function:
fn visit(nested: u32, query: &impl Fn(u32) -> bool) -> bool {
query(nested) // a predicate closure; no database, no SQL
}
The guard is independent of the defaults change above and holds even when query is explicitly configured, which is the only way a bare identifier callee reaches the sink list now. Only a bare identifier callee is considered: a method or path call (conn.query(..), sqlx::query(..)) cannot name a local.
Scope is honoured on both sides, because a name-only check hides real findings: a let binds from the end of its declaration (so in let query = query(user_input) the right-hand call is still the free function, its initialiser running in the enclosing scope) to the end of its enclosing block (so a closure in an already-closed block cannot silence a later call). The same discipline applies to the write! target check above: a let s = String::new() in a sibling block, or one declared after the write, no longer describes the target. Ruff 72 -> 37 SAFE801 findings.
- SAFE105
no_recursionno longer asserts recursion it cannot prove (Java). A same-arity call to an overloaded method name may reach a sibling overload rather than recursing, and choosing between them needs the declared types of the arguments, which means a classpath. Such findings now carry a message that says the target is unresolvable instead of stating outright that the method calls itself:
SAFE105 Function "f" calls "f", which is overloaded in this type, so the target cannot be
resolved without type information; if it is this method, recursion has no guaranteed
stack bound (Power of Ten rule 1) - refactor to an explicit loop or worklist
The hedge is decided per call, from the argument count, not per method name: a type holding f(int) and f(int, int) has an overloaded name, but a one-argument call inside f(int) has only one candidate and keeps the unhedged message. A varargs sibling counts as a rival for any count from its fixed prefix upwards. On Commons Lang 16 of 224 findings now assert recursion outright rather than all 279 doing so; on Guava, 81 of 475.
Dropping the hedged ones instead was considered and rejected: genuine recursion passes plain identifiers and so carries none of the signals below, so suppressing on name ambiguity alone would have silenced real recursion in Commons Lang's ClassUtils.getAllInterfaces and walkInterfaces and in Guava's AbstractIteratorTester.recurse. The code and severity are unchanged, so no config or CI gate moves; only the message text differs, and only for Java.
Known limit: only declarations on the enclosing type are visible, so an unhedged message means "no rival in this type", not "no rival anywhere" - a same-named method inherited from a superclass can also win resolution. Seeing that needs the supertype's source.
- SAFE105
no_recursion: two more Java shapes that are not self-calls (#153). Each is a fact about overload resolution that the source text settles on its own, so neither can hide genuine recursion. Together they take Commons Lang 279 -> 224 and Guava 477 -> 475; ripgrep (23) and Ruff (612) are unaffected, having no Java. - An argument cast to
Objectwhere the parameter is notObject.remove((Object) array, index)insideremove(boolean[] array, int index):Objectis not assignable toboolean[]. Only this direction is decidable without a type hierarchy, since a cast to a subtype of the parameter type is still applicable; a parameter declared as a type variable is also exempt, because<T> T f(T a)really does acceptf((Object) a)withTinferred asObject.java.lang.ObjectandObjectare recognised as the same type, so the fully-qualified spelling does not read as a mismatch. - An element of the array parameter at that same position, by index (
append(lhs[i], rhs[i])insideappend(Object[] lhs, Object[] rhs)) or through a for-each variable (for (boolean e : array) append(e);insideappend(boolean[] array)). An element type is never assignable to its own array type. The for-each form is Commons Lang'sHashCodeBuilderfamily, six findings in one file, none of which carries a cast.
A third condition was implemented, measured and then withdrawn as unsound before release: "a varargs method loses to a same-named fixed-arity sibling at this argument count". JLS 15.12.2 does resolve phases 1 and 2 (no varargs) before phase 3, but a method is a candidate in those phases only if it is applicable, which needs compatible argument types and not merely a matching count. With an incompatible sibling - j(int, int, int) beside j(String, String...) calling j(a, "b", "c") - phases 1 and 2 find nothing, phase 3 selects the varargs method, and the call is genuine recursion that the condition silenced. It accounted for 17 Commons Lang and 31 Guava suppressions, which is why those totals are 224 / 475 rather than 207 / 444.
Performance: the overload table is built once per file, in the same tree walk that collects the functions, and the for-each map is resolved only for methods that declare an array parameter. End to end on Guava this costs about 3.5% (21.3s -> 22.0s); a first cut that re-derived both per call cost 17%.
- SAFE105
no_recursion: three shapes that are not self-calls are no longer reported as recursion. The rule resolved a bare call by name with no notion of what that name refers to at the call site. - Java overloads (#153). A call whose argument count differs from the enclosing method's parameter count cannot be a self-call, and deciding that needs no type information:
boolean[] add(boolean[], int, boolean)callingadd(a, i, Boolean.valueOf(e), Boolean.TYPE)is a different method. Varargs are exempt from the check, since a fixed-arity comparison proves nothing there. Measured: Commons Lang 655 -> 279 findings (-57%), Guava 2159 -> 477 (-78%). - Rust associated functions (#160). A bare
name(..)inside animplortraitbody can never reach the method - that requiresself.name()orType::name(..)- so it always resolves to a free function or an import. This is the same reasoning the existingis_methodflag already applied to Go and PHP methods. - Rust function-local
use(#173).use std::os::unix::fs::symlink;inside afn symlinkrebinds the name for the rest of the block, so the bare call is not recursion. Covers plain paths, brace lists andasaliases. The shape is in ripgrep'scrates/ignore/src/walk.rs.
Together on ripgrep: 32 -> 23 findings, removing exactly the 9 that #173 predicted. Self-qualified calls, genuine free-function recursion, matching-arity Java calls and unrelated local imports all still report - each pinned by a test, and each fix verified to be load-bearing by mutation.
Three ways the new suppressions could themselves have hidden genuine recursion were found in review and closed before release; all three were the dangerous direction for this rule, a missed finding rather than a false one. Counts on Commons Lang, Guava, ripgrep and Ruff are unchanged by the three, so none of the shapes occurs in that corpus - which is precisely why each needed a test rather than a measurement.
- Java explicit receiver parameters. void tick(Outer Outer.this, int n) parses the receiver as a receiver_parameter child of formal_parameters, but it is never passed at a call site, so counting it made the signature look like a two-parameter one and the one-argument self-call read as an arity mismatch. It is now discounted, and the arity check still fires on a genuine mismatch in such a method.
- Rust use scope. A use is an item, so it binds throughout its enclosing block and no further. Treating any import in the body as function-wide silenced a recursive call outside the block that shadowed the name. The check now carries the shadowing block's byte span and applies per call, so { use std::fs::walk; } followed by walk(n - 1) still reports, while a call inside that block does not.
- Rust as aliases. use other::bar as helper binds only helper. Collecting every identifier beneath the use also read bar as bound, which silenced a genuine bar() call in fn bar; the walk now stops at the as clause and takes its alias.
#153 is improved but not closed. What remains is 224 findings on Commons Lang and 476 on Guava, almost all same-arity overloads such as remove(boolean[], int) delegating to remove(Object, int). The issue anticipated that residue but expected it to be rare; it is in fact the dominant remaining class. Of those, 208 and 394 respectively now carry the hedged "target cannot be resolved" message rather than asserting recursion, leaving 16 and 82 stated outright - which is the value this release delivered on the issue: the rule's confidence, not its count.
An earlier draft of this entry claimed 81% of the residue states in the source text that it targets a different signature, and listed four reachable signals. Both were wrong and are corrected here. The 81% came from counting "the argument is itself a call" as proof of a different target, which it is not - f(new ArrayList()) against a List parameter is perfectly applicable - and re-classifying gives 279 -> 207, around a quarter rather than four fifths. The fourth signal, "a varargs method whose arity is claimed by a fixed-arity sibling", was implemented, measured and then withdrawn as unsound during this same release (see the note in the preceding entry): phases 1 and 2 of JLS 15.12.2 require applicability, which needs argument types, so arity cannot establish that a fixed-arity sibling wins.
Closing the issue therefore needs real type resolution - a classpath, the JDK and every dependency - which is a different kind of tool from a single-file syntactic analyser. The remaining syntactic signals are worth little on the evidence: on Guava they suppress 2 findings, because its dominant shape is expectContents(asList(elements)), where the argument's type comes from a call safelint cannot resolve. Narrowing further is deliberately not "stay quiet whenever the name is overloaded": genuine recursion passes plain identifiers and so carries none of those signals, which is why suppressing on name ambiguity alone would have silenced real recursion in ClassUtils.getAllInterfaces and Guava's AbstractIteratorTester.recurse.
2.14.3 - 2026-10-04#
Changed#
- CI / dev dependencies: bump
urllib3to 2.8.0,virtualenvto 21.14.5 andpython-discoveryto 1.6.1 (folded in from the Dependabot PR). Lockfile only - safelint's single runtime dependency istree-sitter, and all three reach the project through dev tooling (requests-> urllib3;pre-commit-> virtualenv -> python-discovery), so the published wheel is unaffected. urllib3 2.8.0 carries three security fixes, two rated High (HTTPS-proxy TLS configuration being ignored, and an unbounded chunk-size line buffered during streaming). Each proposed artefact hash was verified against the PyPI JSON API before applying.
Fixed#
- The
no files lintednote now reaches--format jsonand--format sarif, not onlypretty. It is the one signal that separates "safelint scanned nothing" from "safelint scanned your code and it is clean":summary.files_checkedreports that nothing was read, never why. Keeping it out of the machine-readable formats left every automated consumer unable to tell a skipped-by-exclusion target from a genuinely clean one. It was pretty-only to keep json / sarif stderr quiet for parsing pipelines, but pipelines parse stdout, so a line on stderr cannot break them - the same argument already accepted for the git-discovery notes beside it. The note stays on stderr with the usualsafelint: warning:prefix in every mode, soprettyoutput is unchanged; the missing-grammar warnings remain pretty-only, being install advice for a person rather than a description of the run. Closes #191. - SAFE110
needless_mutno longer advises dropping amutthat a closure CALL requires (Rust).let mut cb = || { n += 1; }; cb();was reported as needless, and following the advice giveserror[E0596]: cannot borrow 'cb' as mutable- calling aFnMutclosure goes throughcall_mut, which takes&mut self. The liveness scan recognised assignment,&mut, method-receiver, field and index uses, but a bare call of the binding matched none of them. Whether a closure isFnMutorFnneeds type information the rule does not have, so a call is now assumed to requiremut, the same conservative choice the method-receiver case already makes. Measured against the Ruff monorepo this removes 24 of 310 findings (ripgrep: 1 of 42) and adds none; every sampled removal is alet mut <name> = |...| {...}that is later called. Parentheses around the callee are stripped first, so(cb)()and((cb))()count too - their callee is aparenthesized_expression, which an identifier-only check missed. Same family as the 2.14.1 fix: a rule whose suggestion does not compile. Closes #186. - The harness now treats safelint's own
files_checked == 0as authoritative, rather than relying solely on its eligibility check. That check re-derives safelint's file-discovery rules, and five separate false-clean routes came from the re-derivation disagreeing with the scanner; this backstop mirrors nothing and so cannot drift - if safelint read no files there is no result to report, whatever the harness predicted, and the error quotes safelint's ownno files lintednote for the reason. Closes the drift risk for three of the five routes (#192); the remaining two need a per-language scan count safelint does not yet expose.
2.14.2 - 2026-10-03#
Changed#
- CI: bump
anthropics/claude-code-actionto v1.0.237 (folded in from the Dependabot PR). Still SHA-pinned; the new SHA was verified against its dereferenced tag object, sincev1.0.237is an annotated tag and the naive ref lookup returns the tag object rather than the commit. No packaged behaviour change.
Fixed#
- Validation harness: four robustness defects (
scripts/validate_real_world.py). Dev tooling only - nothing in the wheel changes. Found in review of the 2.14.1 release PR (#184), after that release had been cut. --includewas matched against the absolute path safelint echoes back, so the project root could satisfy it: a checkout at/tmp/crates/ty_rootmade--include crates/ty_match every file in the repository, silently widening the subtree the flag exists to narrow. Paths are now made relative to--projectfirst.- The eligibility check only ran when
--includewas given, so the wrong--lang- which needs no typo to reach - produced a confident committed zero-findings report for a project holding none of that language (--lang rustagainst a Python repository reportedscanned=1, findings=0). It now runs either way and names the likely cause. list-rulesentries missingname/languagesraisedKeyErroroutside the error guard, printing a traceback instead of the documentederror:line and exit 2.- The eligibility check knew only the harness's own exclusions, not safelint's, so a project whose only files of the target language sat under
.venv/ornode_modules/satisfied it while the scanner skipped every one -scanned=0, findings=0written up as a clean result, the exact false pass the check exists to prevent. The scanner's default exclusions are now mirrored alongside the harness-specific ones; the generatedextend_exclude_pathsstill names only what the harness adds. A symlinked source counted as eligible for the same reason -Path.is_file()follows links while safelint refuses to (its reject-all stance since 2.8.4) - so eligibility now mirrors that too. - The eligibility walk enumerated excluded trees instead of pruning them, and the measurement wrapper itself was unbounded. The walk now uses
os.walkwith the excluded directory names pruned before descending, which costs nothing on the success path (it returns on the first qualifying file) but takes the failure path from 0.47s to 0.00s against a project with 40k build artifacts, and stops at directory symlinks. The wrapper gained an outer bound of the scan timeout plus a minute, so a wedged wrapper is an error rather than an unbounded wait. - Neither the scan nor the metadata subprocesses were bounded, so a stalled scanner hung the harness indefinitely.
--timeout(default 1800s, deliberately generous) bounds the scan and 60s bounds the metadata calls; the scan's bound is applied inside the measurement wrapper, so the scanner is killed by its own parent rather than left running when the wrapper dies, and a timeout is an error rather than a zero-findings run. This reaches the direct child - the shape every real scan has, since--safelintnames an executable. A binary that is itself a shell wrapper can still leave a grandchild behind;subprocesstimeouts do not kill process groups.
2.14.1 - 2026-09-28#
Changed#
- CI: bump
astral-sh/setup-uvto v10.2.0 andanthropics/claude-code-actionto v1.0.231 (folded in from the Dependabot PR). Both remain SHA-pinned; each new SHA was verified against its dereferenced tag object before applying. No packaged behaviour change.
Fixed#
- SAFE110
needless_mutno longer advises dropping amutthat a closure reassigns (Rust). The scan for "is this binding ever mutated" reused the per-function metric skip set, which skips closure bodies. A Rust closure captures its enclosing scope, solet mut failed = false; xs.iter().for_each(|x| { failed = true; });was reported as needless - and dropping themutas advised makes rustc fail witherror[E0594]: cannot assign to 'failed', as it is not declared as mutable. The liveness scan now has its own skip set that excludes onlyfunction_item: a nestedfngenuinely cannot reach the binding (Rust has no capture forfnitems), while a closure can and routinely does. Measured against the Ruff monorepo, this removes 209 of 519 findings (40%; 126 of 285 inside the ty crates), every sampled one of which requiredmut- including method-receiver uses such asiter.next()inside a closure, whereIterator::nexttakes&mut self. Found by the real-world validation programme; seeplan/real-world-validation.md. - SAFE110 now respects closure-local shadowing (Rust). Descending into closures meant a closure's own
let mut failedcounted as a usage of a same-named outer binding, suppressing a valid finding. Shadowing is tracked positionally, because it begins at the shadowinglet: a mutation before it is still the outer binding's, so treating the whole closure as shadowed would reintroduce the E0594 advice the fix above removes. Closure parameters shadow the entire body. A shadowinglet's own initializer is excluded from the shadow, because it is evaluated in the enclosing scope:let failed = &mut failed;mutably borrows the OUTER binding, and cutting the scan off at thelet's start hid that borrow. Typed closure parameters (|mut failed: bool|) shadow as well; they are wrapped in aparameternode rather than being bare identifiers. Shapes that cannot be read unambiguously - a tuple-pattern binding, aletnested in an inner block - are not claimed as shadows, keeping the rule quiet rather than risking a wrong suggestion. No change in findings across 2113 real Rust files (Ruff 310, ripgrep 42, both unchanged), which is the evidence that it adds no false positives; the gap it closes is real but rare in practice. Raised in review of PR #184.
Added#
- Real-world validation harness (
scripts/validate_real_world.py). Runs one open-source project for one language against a given safelint binary - twice, with every rule enabled and then with stock defaults - and writes a committed summary toplan/real-world-results/with per-rule counts, the project's commit SHA, the safelint version, wall time and peak memory. It asks the binary under test for its rule registry (list-rules --format json) so config generation cannot drift from the version being validated, passes config via--configso asafelint.tomlinside the cloned project cannot silently override it, filters results to the language's extensions, and excludesvendor//target//third_party/on top of the built-in exclusions. Dev tooling only - nothing in the wheel changes. The programme it serves, and the fifteen rule defects its first pass found (#153-#166), are inplan/real-world-validation.md; the first committed result is the published 2.14.0 against Spring PetClinic.
Three harness defects found in review of PR #184 and fixed before the release: --preset plus --pydantic emitted two [python] tables, which TOML forbids, so the generated config was unparseable and every Django / Flask / FastAPI row of the matrix would have failed on it; a mistyped --include filtered away every finding while files_checked stayed positive from the rest of the project, so the harness wrote (and would have committed) a confident zero-findings report for a subtree it never validated, and an include selecting no source file of the target language is now an error; and naming a nonexistent --safelint binary raised a FileNotFoundError traceback instead of the documented error: line and exit 2, because version discovery ran ahead of the error guard. A binary that exits 0 with output that is not the expected list-rules JSON now takes that same path rather than raising JSONDecodeError, and the include-eligibility check counts files only, so a directory named like a source file cannot satisfy it.
2.14.0 - 2026-09-24#
Fixed#
- SAFE801: assignment-side sinks now cover parenthesised, chained and destructured targets.
(el.innerHTML) = tainted(a target JavaScript permits),el.innerHTML = x = tainted(the chain writes the terminal value, not the inner assignment) and[el.innerHTML, y] = [tainted, 1]were all missed. Destructured targets pair positionally, so[y, el.innerHTML] = [tainted, 1]stays clean. The same applies to Python's(o.sink) = t,o.sink = x = tando.sink, other = t, 0. The traversal is now shared across every tracker rather than copied into each, so a fix lands once. - SAFE801: write-sinks moved to their own
assignment_sinkslist (breaking change to the 2.14.0rc1 behaviour, not to any released version). The first cut matched assignment targets against the flatsinks_*list. Outside JavaScript those hold FUNCTION names, so with shipped defaultsc.args = u(Rust),p.Query = q(Go),$this->query = $_GET[...](PHP),obj.run = u(Python),this.load = u(Java) ands.system = argv[1](C) all reported as injections. Write-sinks now live inassignment_sinks_<lang>(bareassignment_sinksfor Python), which shipsinnerHTMLfor JavaScript and empty everywhere else, so a name must be declared to be treated as a write-sink.receiver_sinksandassignment_sinksare bundled into oneSinkKindsvalue object internally. - SAFE801: a computed subscript key is no longer matched as a property name.
results[key] = taintedand Javaarr[i] = taintedmatched the spelling of the index variable against the sink list, so any local calledrun/loadfired. Only a quoted key (o["danger"], which names the same property aso.danger) is matched now; Java array indices are not consulted at all. - SAFE801: restored taint through a nested f-string behind a non-propagating parent (Python). The 2.14.0rc1 traversal prune made
eval(f"x{(f"y{u}")}z")stop firing, because the inner string was then only reachable through a parent that is a taint dead-end. Replaced with a visited set in the worklist, which bounds the original 2^N blowup at its source without making anything unreachable - depth 150 stays under 0.01s. - SAFE801:
x, y = tainted, "k"no longer marksytainted. An unpack is now paired positionally, matching what the Go tracker already did; mismatched arity or an unpack from a call still falls back to the conservative whole-RHS status. - SAFE801
tainted_sink: assignment-side sinks are now detected (JavaScript / TypeScript).innerHTMLhas shipped in the defaultsinks_javascriptsince the rule existed, but hits were only ever recorded at a call - so the idiomaticelement.innerHTML = userInput, the canonical DOM-XSS shape, was never reported, and the default could fire only on aninnerHTML(...)call that does not occur in real code. Writing to the property IS the injection, so an assignment whose target names a configured sink is now checked like a call:el.innerHTML = tainted, theel["innerHTML"] = taintedsubscript spelling, andel.innerHTML += taintedall fire. This works for any name in the sinks list, soouterHTML/srcdoccan be opted in the same way, and it honours the same sanitiser and property-typed contract as the call path (el.innerHTML = escape(u)is clean; a sanitiser establishing a different property is not).textContentand other non-sink properties stay clean. Implemented in all seven trackers on each language's native member shape (obj.attr/obj["attr"]in Python,field_access/array_accessin Java, field expressions in Rust, Go, C and C++,$obj->propin PHP), so a project-specific setter can be declared as a sink in any language. Go pairs its sides positionally, matching its existing multi-assign handling.innerHTMLis the only shipped default of this shape; every other language's defaults are call-style and unaffected. Expect new findings if you havetainted_sinkenabled on a DOM codebase - they are real, and were being missed. - SAFE801
tainted_sink: a cleared safety property no longer survives an unknown call (all seven trackers). A property established by a property-typed sanitiser was carried through an intervening unknown call, sohtml_sink(html_unescape(escape(user_input)))read clean - an unknown call may transform or decode its input and cannot be trusted to preserve a safety property. The worklist now carries a per-node property and drops it when descending into an unknown call's arguments, so any taint reaching them re-taints the result for every property. Raw taint propagation is unchanged, and a direct clear (html_sink(escape(u))) still clears. Applied to Python, JavaScript/TypeScript, Java, Rust, Go, PHP, C and C++, with a parametrised cross-language parity test so the semantic cannot drift in one tracker. - SAFE801: C++ reference declarations bound no taint.
const std::string& r = tainted;(and theT&&form) silently lost taint: tree-sitter-cpp givesreference_declaratornodeclaratorfield, so the declarator descent bottomed out and bound nothing, leavingrclean at every later sink. - Explicitly instantiated C++ template calls now resolve to their bare name.
execute<int>(x)resolved to no name at all anddb.query<Row>(x)to the literal text"query<Row>", so neither ever matched a sink configured asexecute/query. This affected every name-filtered rule on C++, not just SAFE801. - SAFE801: Python tuple-unpacking assignment lost taint. The right-hand side of
x, y = user_input, "k"parses asexpression_list(nottuple), which was in no taint-propagating set, so both targets read clean. Go already handled its ownexpression_listpositionally and JS destructuring was already covered; this was Python-only. - SAFE801: exponential time and memory on nested f-strings / template literals. Collecting interpolations walked the entire string subtree at every nesting level, so each level re-enumerated every deeper one: N nested f-strings cost 2^N node visits whenever the walk had to exhaust (an untainted expression). Measured at 0.08s / 0.33s / 1.33s for N = 16 / 18 / 20. Because the worklist keeps no visited set, the re-pushed nodes also accumulated in the stack, so the blowup was 2^N in memory as well - roughly a million live node references at N = 20, and deep enough nesting exhausted system memory and was OOM-killed rather than merely slow. Nested strings are now pruned from the inner walk and handed to the worklist instead, which bounds both: the N = 20 case drops to 0.0001s, and N = 64 (previously an OOM) completes in 0.0002s with flat memory. Same fix in the Python and JavaScript trackers.
- SAFE801: taint lost through an untracked compound assignment target (Java). A chained assignment ending in a compound step against a non-identifier target (
a = obj.f += tainted) returned clean. Regression introduced by the 2.13.0 compound-chain change. - SAFE801: Python config lists were not validated.
sinks/sanitizers/sourcesskipped the string-list guard on the Python path only, so a mistyped scalar (sinks = "eval") silently became a set of single characters. Python now gets the same validation as every other language without losing its built-in fallback lists. - A mistyped config value is now an error message, not a traceback.
sinks = "eval"(missing brackets) escaped the CLI as an uncaughtTypeErrorand dumped a full Python traceback, which reads like a crash in safelint rather than a mistake in the user's config. It now prints onesafelint: error: sinks must be a list of strings, got strline and exits 2. The newConfigValueErrorsubclassesTypeError, so any caller catchingTypeErroris unaffected, and a genuineTypeErrorfrom a bug in safelint still raises with its traceback intact. PropertyContractwas hashable in name only and only shallowly frozen. Hashing any contract raisedTypeError(the generated__hash__hashed a mapping), andfrozen=Truedid not stop a caller mutating the dict it had passed in, under every tracker holding it. Both tables are now copied into read-only mappings and hashed by content.- SAFE801: dead work removed.
PropertyContract.all_propertiesreturned the union of declared sanitiser and sink properties, so any property no sink required cost a full extra tree traversal per assignment; it now intersects. The Go tracker regained a short-circuit for a value already safe for nothing, and a deadannotated_assignmentdispatch branch (no such tree-sitter-python node kind) was removed.
Added#
- SAFE801: warnings for property declarations that cannot take effect. The property tables fail open, so a declaration that does not line up with the rest of the config simply never fires - indistinguishable, from the outside, from the feature being broken. Four cases now surface on stderr as
safelint: warning:(visible, never failing the run, emitted once per language per engine -safelint checkbuilds one engine per target, so a multi-path run repeats them per target, which matches config being resolved per target): a name in both the flatsanitizerslist andsanitizer_properties(the flat list is universal and checked first, so adoption is a silent no-op); properties declared but no sink requiring any of them; asink_propertieskey naming no configured sink (typo guard, matching the other config layers); and a sanitiser declared with an empty property list (it establishes nothing, and if it is not also in the flat list it has silently stopped sanitising). A well-formed contract warns nothing.
Changed#
- Documentation corrections for the 2.13.0 property-typed sanitisers. The two new keys were documented only in a prose subsection: they are now rows in the canonical SAFE801 options table, and the Python, C and C++ language pages - which had no mention at all, the C++ page having no SAFE801 section whatsoever - now document them. The bundled AI-client skill addenda for all nine languages gained the same guidance, replacing advice they now supersede (the Java addendum's "SAFE801 has a single shared sanitizer set" and the PHP addendum's "add
htmlspecialcharsviasanitizers_php"). Fixed adocs/languages/java.mdlink that pointedreceiver_sinksat the property-typed section, and stale claims in the_c_check/_cpp_checkdocstrings (C++ uses a distinctCppTaintTrackersubclass, andscanf/read/recvare deliberately not default C sources).
2.13.0 - 2026-09-23#
Added#
- SAFE801
tainted_sink: property-typed sanitisers (sanitizer_properties/sink_properties). A sanitiser can now declare which safety property it establishes (e.g.escape = ["html_escaped"]) and a sink which it requires (e.g.RawSQL = "sql_escaped"); a property-typed sanitiser clears a sink only when it establishes that sink's required property. This fixes the class of false negative where an HTML escaper wrongly cleared a SQL sink (RawSQL(escape(user_input))). Clearing is path-sensitive: taint carries the properties it has been cleared for, so the clear survives an intermediate variable (safe = escape(x); html_render(safe)is clean whilerun_sql(safe)still fires). The mechanism is opt-in and backward compatible - both tables ship empty, and the flatsanitizerslist stays universal (clears every sink, as before), so no existing config changes meaning and no cost is added until a project opts in. Only the flatsanitizerslist clears a sink with no declared property; a property-typed sanitiser never does. Both keys are per-language (bare for Python,_<lang>suffix otherwise). Pydantic's validating entry points (model_validate/model_validate_json/parse_obj_as) are documented as aschema_validatedprovider to add when you declare aschema_validated-requiring sink (not a shipped default, and never in the flat list - a validated string is still injectable). Config docs (both TOML forms) indocs/configuration/rules.md.
Changed#
- Taint trackers refactored to a single iterative worklist. The six non-C trackers (Python + JavaScript/TypeScript, Java, Rust, Go, PHP) previously classified calls via an
_is_tainted↔_call_taintedmutual recursion; they now reduce each node to(is_tainted_here, children)in one worklist, matchingdataflow_c.py. Linting results are unchanged (every per-language suite is preserved); the refactor removes the recursion and unifies the trackers. Not purely internal, one public attribute changed type: each tracker'staintedattribute is nowdict[str, frozenset[str]](variable name to the set of safety properties it is already safe for) where it wasset[str]; absence from the dict still means clean. This is required by the property-typed sanitisers above, which have to record what a value has been cleared for rather than just that it is tainted. Code importing a tracker directly and reading.taintedmust be updated; the rule-level, CLI and config surfaces are unaffected. (Noted retrospectively in 2.14.0 - the original entry described this release as "behaviour unchanged, internal only", which was true of linting results but overlooked the attribute.)
2.12.1 - 2026-09-20#
Fixed#
- SAFE801
tainted_sinkno longer false-positives on a tainted receiver passed only constant arguments. The 2.11.0 method-receiver taint step reported an injection forconn.execute("SELECT 1")whenconnderived from user input, even though the query is a hard-coded constant and no attacker data reaches the sink. The receiver is now treated as the payload only when the sink call has no arguments (tainted.execute()); when the call takes arguments, the payload is the argument(s), so a tainted receiver with all-constant arguments does not report (a tainted argument still fires via the argument path). Applied consistently across all seven trackers - Python, JavaScript/TypeScript, Java, Rust, Go, PHP, and the C++ path indataflow_c.py; C remains excluded (its receiver step is off by design). In Java this also stops a tainted receiver being double-reported alongside a tainted argument. - Exception for receiver-payload sinks via a new
receiver_sinksconfig list (receiver_sinks_<lang>, barereceiver_sinksfor Python). Some sinks carry their payload in the receiver, not an argument -url.openConnection(proxy)is SSRF even whenproxyis clean. Sinks listed here fire on a tainted receiver regardless of arguments, so the no-arguments rule (which is correct for argument-consuming sinks likeexecute/query) does not miss them. Defaults ship Java's URL SSRF methods (openConnection,openStream); add your own project's receiver-payload sinks per language (they must also appear in the matchingsinks_<lang>list). Regression tests (constant-argument false-positive, receiver-as-payload true-positive, and the receiver-sink-with-auxiliary-argument case) added across the trackers. - SAFE908
csrf_protection_disabledno longer false-positives on acsrf_exemptkeyword-argument value.@register(handler=csrf_exempt)passescsrf_exemptas a keyword-argument value; it does not apply the@csrf_exemptdecorator. The guard previously excludedcsrf_exemptonly as a keyword-argument name (@foo(csrf_exempt=True)); it now also excludes an unrelated keyword-argument value whether bare (handler=csrf_exempt), dotted (handler=mod.csrf_exempt) or nested in a call (handler=wrapper(csrf_exempt)) - the enclosing keyword argument is detected structurally, so an interveningattributeorcallnode no longer defeats the check. The real decorator forms still fire: bare@csrf_exempt, called@csrf_exempt(), positional@method_decorator(csrf_exempt), and the@method_decorator(decorator=csrf_exempt)keyword form (including a dotteddecorator=mod.csrf_exemptvalue, and a module-levelmethod_decoratorimport alias), which genuinely applies the decorator to a class-based view. Thedecorator=keyword is only treated as applying when its enclosing call ismethod_decorator(or an alias of it), so an unrelated@register(decorator=csrf_exempt)does not fire.
Changed#
- CI: bump pinned GitHub Actions -
astral-sh/setup-uv9.0.0 -> 10.1.0 andanthropics/claude-code-action1.0.185 -> 1.0.226 (both SHA-pinned). No workflow behaviour change: setup-uv v10 only alters caching onpull_request_target/workflow_run/releaseevents, none of which trigger the setup-uv-using workflows here. - CI: type-check the test tree.
tynow runs againsttests/as well assrc//scripts/(CI and the pre-commit hook).tests/fixtures/**is excluded via[tool.ty.src](those files are deliberately non-compliant rule-triggers - undefined names, non-dependency imports - and are never imported or run), matching the existing safelint self-lint exemption for the same tree. Purely internal; no packaged behaviour change.
2.12.0 - 2026-08-12#
Added#
- SAFE601
missing_assertionsnow recognises Python assertion method calls, not just theassertkeyword. unittest / DjangoTestCasebodies assert viaself.assertEqual(...)/self.assertRaises(...)and pytest viapytest.raises(...)/pytest.warns(...), none of which the rule could previously see - so every unittest-style test read as assertion-less and forced a file-wide SAFE601 ignore (which also hid genuinely under-asserted production code). Python gains a configurableassertion_callslist (bare key, per the Python convention), counted in addition to theassertkeyword;call_namestrips the receiver soself.assertEqual/pytest.raisesmatch on the bareword. The default set covers the unittestassert*surface plus pytest'sraises/warns; extend it with project-specific assertion helpers. This closes the systemic false-positive class surfaced by the optimus-secure-fdn Django review. A mistyped scalar (assertion_calls = "assertEqual") fails loud rather than silently matching characters, matching the other per-language lists. - SAFE601 can now be scoped to test functions only via
test_functions_only = true(defaultfalse, so Holzmann rule 5's production-assertion intent is unchanged for existing configs). When on, the rule fires only for functions named for atest_function_prefixesentry (default["test"]) that live in a file safelint recognises as a test file (undertest_dirs, or matching the language's test-filename convention - the same definition SAFE701/702 use). This lets teams run SAFE601 as a "test must actually assert something" guard: production code that validates by raising, and fixtures /setUp/ helper methods that legitimately have no assertions, are skipped, while atest_*function that asserts nothing still fires. The shared test-file identification used by SAFE601/701/702 now lives in one place (rules/_test_files.py). - SAFE907
unvalidated_request_inputgains a configurable validator allowlist. The rule previously recognised only a hardcoded set of validating calls (Pythonis_valid/full_clean/validate/model_validate/parse_obj; PHP$request->validate), so a project that validates request input through its own helper (validate_export_request(), an allowlist filter builder) could only silence the rule with a file-level ignore - which then hid any genuinely-unvalidated read elsewhere in that file. Newrequest_validators(Python, bare key) /request_validators_php(PHP) lists are unioned with the built-in set; a read guarded by a listed helper no longer fires. Exact call-name match (receiver stripped), validated via the shared string-list guard so a mistyped scalar fails loud. Also surfaced by the optimus-secure-fdn Django review.
Fixed#
test_coupling(SAFE702): an explicit file target's changed-files context is now the repo-wide diff, and the rule only fires for a source that actually changed. Two coupled corrections. (1)safelint check foo.pygavefoo.pya changed set of just[foo.py], so an overlapping runsafelint check pkg/ pkg/foo.py(which dedups to the file target) could false-positive: a sibling test updated in the same commit was dropped from that single-file set, socheck pkg/foo.pyfired whilecheck pkg/stayed clean. A file target now carries the full repo-wide diff (falling back to the named file only when git is unavailable), so the verdict is identical however the file is named. (2)test_couplingnow gates on the source file being in the changed set, so a named-but-unmodified file (check foo.pyon a file you did not touch) no longer trips coupling - it did not change, so there is nothing to couple. Directory and pre-commit (safelint <file> ...) invocations are unaffected: every file they lint is already in the changed set. This supersedes the 2.11.0 "the named file is its own changed set" behaviour forcheck, which is git-aware (the positional pre-commit hook contract is unchanged).
2.11.1 - 2026-08-07#
Fixed#
safelint checknow defaults to the current directory when no PATH is given.safelint check --all-files(or a baresafelint check) previously exited witherror: the following arguments are required: PATH; the positional is now optional and defaults to., matchingsafelint check .. Explicit paths are unchanged.- A
checktarget path that does not exist is now a hard error, not a silent pass.safelint check <missing-path>previously printedAll checks passed.and exited0(and with--all-files, a confusing "no files linted … all excluded" note followed by success) - so a typo'd or wrong-cwd path read as green. It now emitssafelint: error: path does not exist: '<path>'on stderr and exits2, while still linting any valid sibling paths. An existing-but-empty or fully-excluded directory remains a legitimate clean pass (exit0) - only genuinely-missing paths error.
2.11.0 - 2026-08-05#
Added#
- Two new framework-preset security rules - SAFE908
csrf_protection_disabledand SAFE909hardcoded_secret(Python + PHP; SafeLint now ships 52 rules). They complete the shared cross-framework 9xx band (SAFE905-909) begun in v2.9.0, and like the others are disabled by default and switched on by the framework presets that scope them. - SAFE908
csrf_protection_disabled(error) - CSRF protection explicitly turned off in code: Django@csrf_exempt(bare, called, ormethod_decorator(csrf_exempt)), Laravel a non-empty$exceptroute allow-list on theVerifyCsrfTokenmiddleware (an empty$except = []is clean). Enabled by the Django and Laravel presets (Flask's CSRF is extension-provided and FastAPI has none, so neither enables it). - SAFE909
hardcoded_secret(error) - a secret key assigned a string literal: DjangoSECRET_KEY = "...", Flaskapp.secret_key = "...", Laravel a hardcoded'key' => 'base64:...'APP_KEYconfig entry. Reading from the environment (os.environ/env(...)) is a call, not a literal, and is clean. Enabled by the Django, Flask, and Laravel presets. - Both are more false-positive-prone than SAFE905-907 (a same-named decorator / property, or a placeholder literal in an example or test-settings file), so they stay opt-in even under vanilla and are documented as such. Bundled AI-client skill files (all 14) and the Python / PHP language pages / addenda document them.
Changed#
-
tainted_sink(SAFE801) now follows taint through attribute / subscript / method-receiver chains in Python, JavaScript / TypeScript, and C++ - closing a cross-language parity gap. Request-driven web code almost never passes a bare tainted parameter to a sink; the data arrives behind a projection of the request object (request.GET["q"],req.query.get("q"),$request->input('x')). Java, Rust, Go, PHP, and C already propagated taint through these projections; the gaps were narrower: Python dropped it at the first attribute access (it had none of the three steps), while JavaScript / TypeScript and C++ already handled attribute / subscript access and only lacked the method-call-on-a-tainted-receiver step. So a framework preset's injection sinks (DjangoRawSQL/mark_safe, Flaskrender_template_string, LaravelwhereRaw, ...) were largely inert on idiomatic request-driven code. Now, uniformly across all nine languages: an attribute / member access propagates its receiver's taint (request.data), a subscript / index propagates its base's taint (request.GET["q"]), and a method call on a tainted receiver stays tainted even with no tainted positional arguments (request.GET.get("q")). The method-receiver step rides on the existing conservativeassume_taint_preserving = truedefault (matching how Java / Rust / Go / PHP already behave), soassume_taint_preserving = falsestill turns it off, and the sanitizer check runs first soescape(request.data)still clears. This can surface new findings on existing code that has the opt-intainted_sinkrule enabled - which is the point: it is the difference between detecting onlyRawSQL(request)(rare) and detectingRawSQL(request.GET["q"])(idiomatic). No new config key. Relatedly, a sink invoked as a method on a tainted receiver now fires even with no tainted arguments (tainted.execute()), uniformly across Python / JS / TS / Go / Rust / PHP / C++ - previously only Java did this. When both an argument and the receiver are tainted, the call is reported once (the argument), not twice. In C specifically this receiver step is off:req->handler()is a function-pointer call whose result need not derive from the struct, so treating the struct as a taint input there would be a false positive (C++ member calls, which are true methods, keep it). -
Multi-path
check: the "nothing to lint here" notes are now emitted once, listing every affected target, instead of a near-identical line per target. Asafelint check src tests examplesrun with nothing modified previously printed the "No modified supported source files detected under target …" note three times (once per target); it now prints one line:… under targets 'src', 'tests', 'examples'. …. Likewise the--all-files"no files linted under ''" note and the git-unavailable "scanning all files" fallback note are each consolidated into a single line naming all affected targets. Single-target runs are unchanged (singular wording). The git-discovery notes ("no modified files" and the git-unavailable fallback) still reach every output mode - stdout in pretty, stderr in JSON / SARIF - so a CI operator still gets an explanation for an empty JSON document; the grammar and "no files linted" notes stay pretty-only. In a mixed run where some targets were linted and another was skipped for a missing grammar, the exit-2 diagnostic now reads "some targets were skipped …" instead of the contradictory "no files linted …" that followed the printed results.
Fixed#
- SAFE908
csrf_protection_disabledno longer fires on an unrelated keyword-argument namedcsrf_exempt.@some_decorator(csrf_exempt=True)configures that decorator; it does not apply Django'scsrf_exemptand so does not disable CSRF. The Python detector now ignorescsrf_exemptwhen it is a keyword-argument name, while still firing on the bare (@csrf_exempt), called (@csrf_exempt()), andmethod_decorator(csrf_exempt)forms. - SAFE909
hardcoded_secretno longer fires on an empty prefixed string placeholder (SECRET_KEY = r"",APP_KEY = f""). The Python empty-value check stripped only quote characters, so a string prefix (r/b/f/u) survived and read as non-empty content. Empty prefixed literals are now correctly treated as clean placeholders; non-empty prefixed literals (r"real-secret") still fire. safelint check <file>is now diff-aware likesafelint <file>. An explicit file target passed tocheckwas not treated as its own changed set, so diff-aware rules - notablytest_coupling(SAFE702) - silently did nothing, whereas the same file named in pre-commit style (safelint <file>) ran them. A named file is now its own changed set (the same contract as the pre-commit invocation), so the two forms behave identically.check <dir>(git-modified discovery) andcheck <file> --all-files(diff-awareness opted out) are unchanged.
2.10.0 - 2026-07-23#
Added#
safelint checkaccepts multiple paths (ruff / ty-style). You can now pass any number of files or directories in one run - e.g.safelint check src/ tests/ scripts/- instead of one target per invocation. safelint lints them all and emits a single aggregated violation list, summary, suppression breakdown, and exit code. A file reached via two overlapping paths (src/andsrc/foo.py) is reported once (deduped by resolved path). Config is resolved per path (each target walks up to its nearestsafelint.toml/pyproject.toml, so a monorepo with per-subtree config behaves correctly), and each path's violations are gated by its ownfail_onso bundling a stricter subtree with a laxer one never weakens the strict subtree's gate. Overlaps are processed most-specific-first, so a shared file is governed by the narrowest target's config independent of argument order, and a target whose only files have an uninstalled grammar still forces the exit-2 "install the grammar" signal even alongside a clean sibling. A single--config/--fail-on/--modeoverrides per-path resolution for the whole invocation;--all-files/--ignoreapply to every path. When a named path contributes zero files (all excluded, or empty / no supported files), pretty mode prints ano files linted under '<path>'note on stderr so a skipped-by-exclusion target is distinguishable from a clean one (informational; the exit code is unchanged). Single-path usage is unchanged. The CI self-lint step now lintssrc/andscripts/in one invocation.
Changed#
- safelint now lints its own test tree (repo hygiene; the
safelintpackage is unchanged).tests/was previously excluded wholesale viaextend_exclude_paths; it is now linted, and the CI self-lint step runssafelint check src/ scripts/ tests/ --all-files --fail-on=warningin one invocation (enabled by the new multi-path support). Twosafelint.tomlper-file-ignores keep it honest:tests/fixtures/**=["*"](the fixtures are deliberately non-compliant - they exist to make rules fire in the e2e tests, so they can never satisfy their own rules) andtests/**relaxes the structure/style rules that test scaffolding legitimately trips (function_length,nesting_depth,logging_on_error). Every other rule - complexity, no-recursion, dataflow, etc. - now applies to test code. - Release automation (internal tooling; the
safelintpackage is unchanged). Thedevelopment->mainpost-release sync now decides "is it safe to reset development?" by content (patch-id viagit cherry) instead of raw SHA commit count. A squash- or rebase-merged release leavesdevelopment's commits content-identical tomainbut with different SHAs; the old count-based check read those as "26 commits ahead" and refused every release (opening a tracking issue and requiring a manual reset), even though nothing was actually unmerged. The patch-id check reads that case as 0 in-flight commits and auto-resolves, while still refusing when genuinely unmerged content exists. Becausegit cherryis patch-id based and by construction skips merge commits, the guard also refuses when a merge commit exists inmain..development(whichgit cherrycannot patch-compare), so a merge whose conflict resolution held content unique todevelopmentcannot be silently clobbered - development is linear under the repo's squash/rebase flow, so this is normally zero and never blocks a routine release. Applied to both.github/workflows/sync-development.ymland the localbin/sync.shadvisor.
2.9.0 - 2026-07-21#
Added#
- Python and PHP framework presets - Django / Flask / FastAPI / Pydantic (Python) and Laravel (PHP). Mirroring the existing Java Spring Boot and JavaScript runtime presets, a
[tool.safelint.python] framework = "django" | "flask" | "fastapi"key (plus an orthogonal composablepydantic = true) and a[tool.safelint.php] framework = "laravel"key shift the rule defaults for the chosen framework. The parser and rule logic are unchanged; only the taint sink lists, nullable-method lists, and which structural rules are active shift. The default isvanillafor both, so existing projects with no[python]/[php]config see no behaviour change. Unknown framework names warn on stderr and fall back tovanilla; explicit per-rule TOML keys always win over the preset. - Three new shared cross-framework rules (SAFE905-907), disabled by default and enabled by the presets. They are the non-Java analogue of the Spring
SAFE9xxrules, each serving multiple frameworks:- SAFE905
debug_mode_enabled(warning) - a debug / reload flag hard-enabled in code: DjangoDEBUG = True, Flaskapp.debug = True/app.run(debug=True), FastAPIuvicorn.run(reload=True), Laravel'debug' => trueconfig entries. - SAFE906
mass_assignment(error) - unbounded attribute binding from request data: Djangofields = "__all__", Pydanticextra = "allow", Laravel Eloquent$guarded = []. - SAFE907
unvalidated_request_input(warning) - request data consumed whole with no validation layer: Django / Flask / FastAPI rawrequest.data/.json/.POSTwithout a serializer oris_valid, Laravel$request->all()withoutvalidate().
- SAFE905
- Preset coverage is mostly taint-list extension (zero new codes): the Django / Flask / FastAPI / Laravel presets add framework-specific sinks (e.g.
RawSQL/mark_safe,render_template_string,HTMLResponse,whereRaw/unprepared) to SAFE801tainted_sink, andpydantic = trueadditively addsmodel_construct/constructto the SAFE801 sinks. Django also treats.first()as nullable for SAFE803. Consistent with the Java Spring preset, these dataflow additions extend the lists but leave the multi-language dataflow rules (SAFE801/802/803) opt-in - enabletainted_sinkexplicitly to use them (so a Python framework selection never turns dataflow on for Go / JS / Rust files in a polyglot repo). Like every language's intra-procedural tracker, SAFE801 follows direct taint flows, notrequest.<attr>attribute chains. - Bundled AI-client skill files (all 14) and the Python / PHP language addenda document the new rules and presets.
- SafeLint now ships 50 rules (up from 47).
Changed#
- Release automation (internal tooling; the
safelintpackage is unchanged). A committed version bump now drives the release: merging a bumped version todevelopment(a pre-releaseX.Y.ZrcN) ormain(a finalX.Y.Z) automatically tags it, publishes to PyPI, and creates the GitHub release. On a final release the CHANGELOG is auto-dated ([Unreleased]->[X.Y.Z] - <date>) anddevelopmentis reset tomainso the two never diverge. New helpersscripts/changelog_section.py(release notes from the CHANGELOG) andscripts/date_changelog.py(the auto-date), plusbin/sync.shfor local branch sync.scripts/is now covered by ruff / ty / safelint.
[2.8.4] - 2026-07-15#
Security#
- safelint no longer follows symlinked source files out of the linted tree, in any mode.
os.walk(followlinks=False)blocks descent into symlinked directories, but a symlinked file was still admitted by theis_file()guard (which follows the link). A cloned repo could commitevil.py -> /etc/passwd(orkey.py -> ~/.ssh/id_rsa) and have that out-of-tree target read and even echoed a line at a time into the violation gutter. Symlinks are now handled follow-if-resolved-within-tree: a symlinked file (or a symlinked top-level directory target -os.walkfollows the top argument regardless offollowlinks=False) is followed only when its real path stays inside the repo root (the resolved cwd). So a monorepo's in-tree symlink (app/config.py -> ../shared/config.py,shared/under the repo) is still linted, while one escaping the tree is skipped with a warning. The check runs in both directory discovery and the central pre-read guard, so the pre-commit hook and single-file/explicit-path runs (which reachcheck_filedirectly, bypassing discovery) enforce the same boundary. An unresolvable symlink (loop or broken link, including Python 3.13+ whereresolve()returns a still-symlink path for a loop rather than raising) fails closed. - Terminal output now visualises control characters in attacker-controlled strings. The pretty renderer echoed the offending source line (plus the file path and rule message) verbatim to the TTY; a crafted line containing raw ANSI / OSC escapes could clear or redraw the terminal, spoof "All checks passed." output, set the window title, or drive OSC 52 clipboard writes when its violation was rendered. C0 (except tab), DEL, and C1 bytes are now shown as visible
\xNNescapes, matching how ruff / ripgrep / git sanitise terminal output, and Unicode bidi-override / zero-width code points (Trojan Source, CVE-2021-42574) become visible\uNNNNescapes so they cannot visually reorder or hide the flagged text. One shared sanitiser (in_diagnostics) now covers every output surface: the stdout violation gutter, the stderr diagnostic warnings (e.g. a symlink-skip warning echoing a crafted filename), and the JSON / SARIF string fields (message,filepath, suggestiondescription/replacement) -json.dumps(ensure_ascii=False)escapes C0 but passed C1 and bidi code points through verbatim, so those formatters are now sanitised too (SARIF URIs stay percent-encoded). test_dirscontainment now also rejects symlinked relative entries. The v2.7.1 (H3) lexical..containment stopped string-based escapes, but a committedtests -> /etcsymlink passed the lexical check and let the coverage-rulerglobfollow it out of the tree (a weak existence oracle, no content read). Relative entries whose real path escapes the project root are now dropped (and a symlink loop or an unreadable ancestor during that check is treated as "cannot prove containment" and dropped, rather than crashing discovery - including on Python 3.13+, whereresolve()no longer raises on a loop and a still-symlink result is rejected instead; the downstreamrglobis additionally guarded so an ancestor-level loop cannot crash discovery on any version); absolute entries remain honoured as the documented opt-in.- Third-party pre-commit hooks are pinned to full commit SHAs (
pre-commit-hooks,ruff-pre-commit), matching the H9 workflow-pinning convention, so a moved upstream tag cannot alter what runs on a contributor's machine.
[2.8.3] - 2026-07-13#
Changed#
- Internal refactor: the rules now reach Tree-sitter node-type / operator constants through module-access (
from safelint.languages import cpp as _cpp→_cpp.IF_STATEMENT) instead of ~1,350 per-constant aliased imports (from safelint.languages.cpp import IF_STATEMENT as _CPP_IF_STATEMENT). One module import per language per file replaces dozens of per-name imports, and the language is explicit at every call site. Follows the v2.8.2 constant sweep. No behaviour change - every rule's resolved node-type set is byte-identical (verified by a collections-only table snapshot showing zero real changes and the full suite passing unchanged), and thelanguages/<lang>.pymodules are untouched, so any downstream importer ofsafelint.languages.*stays compatible.
2.8.2 - 2026-07-13#
Changed#
- Internal refactor: the rules now import Tree-sitter node-type / operator constants from the
languages/<lang>.pymodules instead of hardcoding raw string literals. Each language module is the single source of truth for its node types, and every language's rule logic references its own module. No behaviour change - every rule's resolved node-type set is byte-identical to before (verified by a deterministic table snapshot), and no rule, code, config key, CLI flag, or output format is affected. Purely additive at the module level (new constants only; none removed or renamed), so any downstream importer ofsafelint.languages.*stays compatible.
2.8.1 - 2026-07-12#
Security#
- Skill-install and CI hardening (internal audit items H7-H9), all LOW / defence-in-depth. None is exploitable in the default no-flag flow; they close residual TOCTOU and supply-chain gaps around the
safelint skillcommand and the release pipeline. No change to lint behaviour or public API. - Secondary-file (
AGENTS.md) section writes are now atomic and symlink-safe: the merged text is written to an exclusive-create temp in the same directory andos.replaced over the target, so a symlink swapped into the check-then-write window is replaced as a directory entry rather than written through. The original file's permission bits are preserved. safelint skill remove --pathnow resolves its target a single time and removes that same validated path, so a symlinked ancestor swapped in after the shape check can no longer redirect the removal onto a different tree; a terminal-symlink install is still unlinked as the link itself.- Every third-party GitHub Action is pinned to a full commit SHA (most importantly the OIDC-privileged
pypa/gh-action-pypi-publishin the publish workflow), with a Dependabotgithub-actionsecosystem added to keep the pins current.
2.8.0 - 2026-07-10#
C++ is now a supported language. Building on the C support, .cpp / .cxx / .cc / .hpp / .hxx / .hh files are discovered, parsed via tree-sitter-cpp, and run against 26 rules: the cross-language ports, the five C-family rules (SAFE106 / SAFE310-313) widened to C and C++, the three try / catch / throw error-handling rules, and two new C++-only rules. Plain .h headers stay with C (documented). The additive language work is what justifies this release as a MINOR bump (per the project's semver rules: scope expansion is MINOR, never MAJOR).
Added#
- C++ language support via the opt-in
[cpp]extra (pip install 'safelint[cpp]').tree-sitter-cppis a superset oftree-sitter-c, so the C node types and the five C-family rules carry over unchanged. - SAFE315 (
raw_new_delete) - flags everynew/deleteexpression; preferstd::make_unique/std::make_sharedand RAII.make_unique/make_sharednever fire; a rawnewinside aunique_ptr<T>(new T)argument still does. Overlaps the widened SAFE310 by design. C++-only, disabled by default. - SAFE316 (
dangerous_casts) - flagsreinterpret_cast/const_cast;static_cast/dynamic_caststay clean. Configurable viadangerous_casts_cpp. C++-only, disabled by default. - SAFE201 (
bare_except) gains its first non-Python home: thecatch (...)catch-all. SAFE202 (empty_except) and SAFE203 (logging_on_error) also register for C++; SAFE203 recognisesstd::cerr << ...stream insertion andspdlog::error-style calls as logging, and a barethrow;/throw e;as a re-raise. - C++-specific behaviour on the widened rules: SAFE302 (
global_mutation) descends intonamespace_definitionbodies; SAFE310 (dynamic_allocation) also flagsnew/delete; SAFE313 (restricted_pointers) exempts smart pointers; SAFE105 (no_recursion) detectsthis->m()self-calls; SAFE801 (tainted_sink) seeds reference parameters and reuses the C taint tracker. - Per-language
_cpp-suffixed config defaults mirroring C (nonlocal_jump_calls_cpp,allocation_calls_cpp,dynamic_exec_calls_cpp,io_functions_cpp,assertion_calls_cpp,sinks_cpp/sources_cpp/sanitizers_cpp,flagged_calls_cpp,dangerous_casts_cpp). - A bundled
languages/cpp.mdskill addendum and a C++ language reference page; all fourteen client skill files, the CLI / SECURITY / TOML / contributing enumerations, and the pre-committypes_orlist updated for C++.
2.7.1 - 2026-07-06#
Post-release hardening of the v2.7.0 C support: one opt-in-rule bugfix (SAFE312 false positives on real-world include guards), documentation-fidelity corrections, and regression tests that backfill gaps found in the C post-release audit.
Fixed#
- SAFE312 (
conditional_compilation) no longer false-positives on real-world include guards. The exemption required#define Xto be the node immediately after#ifndef X, so a licence / SPDX comment or a belt-and-braces#pragma oncebetween the two - both widespread header idioms - made the guard fire spuriously. The first-substantive-statement check now skipscommentandpreproc_callnodes; an unrelated statement in that position still fires (the anti-disguise tightening is unchanged). Found by review on the 2.7.1 release PR. - Recorded two Power of Ten paper-fidelity gaps in the C rules so they read as deliberate decisions: SAFE311 (
complex_macro) does not detect mutually recursive macro definitions, and SAFE313 (restricted_pointers), a syntactic declarator check, does not see pointer levels hidden behind atypedefor macro. Both need analysis SafeLint does not do; documented in the Power of Ten page, the rules reference, and the C language page. - Corrected the stale rule-7 fidelity note to name C's literal
(void)cast (recognised by SAFE802); Go's blank identifier is described as the memory-managed-language analogue. - Swept lingering "seven languages" enumerations to the eight-language state (CONTRIBUTING, the JSON-schema page, the README pre-commit example, the bundled skill README, and the "all-language core" labels).
Added#
- C regression tests backfilling the post-release audit gaps: a Power of Ten behavioural pin (
tests/rules/test_c_power_of_ten_pin.py), an engine-level suite (tests/core/test_engine_c.py, covering both.cand.h), config-override tests for the SAFE106nonlocal_jump_calls_cand SAFE310allocation_calls_clist knobs, and a SAFE106 default-on / warning-severity contract lock.
2.7.0 - 2026-07-02#
C is now a supported language alongside Python, JavaScript, TypeScript, Java, Rust, Go, and PHP. .c and .h files are discovered, parsed via Tree-sitter (tree-sitter-c, shipped in the opt-in [c] extra), and run against 21 rules - the 16 cross-language ports plus 5 new C-only rules, the largest rule addition of any language. C is Holzmann's original "Power of Ten" target, so the new rules express clauses every other language adapts away, literally. safelint grows to 45 rules and 8 registered languages. Additive per the project's semver policy (a new language is MINOR); nothing renames, removes, or changes the meaning of any existing rule code, CLI flag, or config key.
Added#
- C as the 8th registered language.
.c/.hfiles dispatch to C-aware implementations of 16 cross-language rules: the 13 all-language core (SAFE101-105, SAFE303, SAFE304, SAFE501, SAFE603, SAFE701, SAFE702, SAFE801, SAFE802) plus SAFE302 (global_mutation, a file-scope declaration-site walk), SAFE309 (dynamic_code_execution,dlopen/dlsym), and SAFE601 (missing_assertions, the literalassertmacro)..hheaders are linted as C (a documented limitation for C++ projects sharing.hfiles). See the C language page for the full reference. - Five new C-only rules - the "Power of Ten homecoming". Clauses every other language adapts away apply literally to C: SAFE106
nonlocal_jumps(rule 1 - everygotoandsetjmp/longjmpfamily call; enabled at warning severity becausegoto errcleanup is idiomatic, annotate with// nosafe: SAFE106), SAFE310dynamic_allocation(rule 3 - themallocfamily), SAFE311complex_macroand SAFE312conditional_compilation(rule 8 - the preprocessor), and SAFE313restricted_pointers(rule 9 - multi-level and function pointers). All but SAFE106 are disabled by default. - C-specific rule adaptations. SAFE801 models the
argv/getenv->system/strcpy/sprintftaint flow (a newanalysis/dataflow_c.pyiterative tracker, withargvseeded via function parameters); SAFE501 handleswhile (1)/while (true)/for (;;)and treats agotoout of the loop as an exit (C has no labelled break); SAFE802's(void)f()cast correctly exempts an explicit discard; SAFE603 flags clang-tidy's bare// NOLINT; SAFE701 / SAFE702 use the<stem>_test.c/test_<stem>.cconventions. Seven rules are deliberately skipped for C (SAFE201/202/203, SAFE301, SAFE305 by language semantics; SAFE401resource_lifecycleand SAFE803null_dereferenceas documented flow-analysis gaps); the rationale is on the language page. - Bundled C skill addendum + per-client docs.
src/safelint/skill_files/languages/c.mdplus C rows in all 14 AI-client skill files, so every bundled agent knows safelint can lint.c/.hand how the C-specific rules behave.
2.6.1 - 2026-06-26#
Security-hardening release. Six findings (H1-H6) from the 2026-06-25 internal security audit, all LOW severity and none reachable in the default no-flag flow: symlink/TOCTOU defences across skill remove --path, skill install (copy), the result-cache temp write, and the OpenCode seed step, plus containment of the test_dirs config search to the project root and an os -> pathlib cleanup. No new rules, CLI flags, or config keys, and no change to how any existing rule evaluates code; the only behaviour changes are defensive - relative test_dirs entries that escape the project root are now dropped, and a few skill install / remove edge cases now fail closed. See plan/security-hardening.md for the full audit record.
Security#
- Contain
test_dirsfilesystem search to the project root (audit finding H3). A relativetest_dirsconfig value that climbs out of the project root via..(e.g.["../../etc"]) previously let SAFE701 / SAFE702'srglobprobe directories outside the tree (read/stat only - a single existence bit, no exfiltration). Relative entries are now collapsed lexically and dropped if they escape the root; absolutetest_dirsremain honoured (an explicit, supported config choice). LOW severity, opt-in rules; from the 2026-06-25 internal security audit (seeplan/security-hardening.md). First of the audit's hardening items. - Refuse
skill remove --pathwhen a symlinked ancestor redirects the delete (audit finding H1). The--pathguard matched only the lexical tail of the path against a registered install shape, so a path like~/x/.cursor/rules/safelint.mdcwhoserulescomponent is a symlink into an unrelated tree could pass the check and have_remove_existingdelete a file there. The guard now re-checks the install shape after resolving ancestor symlinks (Path.resolveon the parent): a redirect onto a non-install-shaped location is refused, while genuinely unusual real parents - and shape-preserving symlinks such as dotfile clones - keep working. LOW severity (requires an attacker-planted symlink under a path the user explicitly names). - Use exclusive create for skill-file copy installs (audit finding H2).
safelint skill install(copy mode) wrote the destination withshutil.copyfile, which follows symlinks and truncates the target - leaving a check-then-write window in which a symlink planted at the destination could redirect the write onto an unrelated file. The copy now writes via an exclusive create ("xb"mode,O_CREAT | O_EXCL, which POSIX makes fail on a symlink too), so a freshly-appeared target makes the install fail rather than clobber. LOW severity (local check-then-write race on the install destination). - Write the result cache through an exclusive-create temp file (audit finding H4).
LintCache.putwrote a deterministically-named<key>.json.tmpthen renamed it into place; in an attacker-writable cache directory a symlink pre-planted at that predictable name would be followed by the write. The temp file is now created viatempfile.mkstemp(O_CREAT | O_EXCL, plusO_NOFOLLOWwhere the platform provides it, under an unguessable random name) and written through its file descriptor, so a planted symlink / predictable tmp name can no longer be followed. LOW severity (requires write access to the cache dir, which already permits writing the cache files directly). - Don't follow a dangling
AGENTS.mdsymlink when seeding OpenCode integration (audit finding H5). The OpenCode auto-seed step guarded only onPath.exists(), which returns False for a dangling symlink, so a danglingAGENTS.mdsymlink would let the subsequenttouch()follow the link and create an empty file at the link target. The step now returns early onis_symlink()(lstat-based, true for dangling links) and, crucially, seeds via an exclusive create ("xb"/O_CREAT | O_EXCL) instead oftouch()- so even a symlink that appears in the check-then-write window is refused (the create fails and is treated as a no-op) rather than followed. LOW severity (needs an attacker-planted symlink, a project with.opencode/, and a project-scope install; creates only an empty file).
2.6.0 - 2026-06-25#
PHP is now a supported language alongside Python, JavaScript, TypeScript, Java, Rust, and Go. .php files are discovered, parsed via Tree-sitter (using the mixed HTML+PHP grammar so templated files parse), and run against 21 existing rules - the widest port of the rule set of any language so far. PHP adds NO new rule codes, so safelint stays at 40 rules; it becomes the 7th registered language. PHP support installs via the new [php] extra (pip install 'safelint[php]'); the base install still ships no grammars. Additive per the project's semver policy (a new language is MINOR, never MAJOR); nothing renames, removes, or changes the meaning of any existing rule code, CLI flag, or config key.
Added#
- PHP as the 7th registered language.
.phpfiles are dispatched to PHP-aware implementations of 21 cross-language rules: the 13 all-seven core (SAFE101-105, SAFE303, SAFE304, SAFE501, SAFE603, SAFE701, SAFE702, SAFE801, SAFE802) plus SAFE302 (global_mutation), SAFE309 (dynamic_code_execution), SAFE401 (resource_lifecycle), SAFE601 (missing_assertions), SAFE803 (null_dereference), SAFE202 (empty_except), SAFE203 (logging_on_error), and SAFE301 (global_state). See the PHP language page for the full reference. - SAFE301
global_stategains its first non-Python registration. PHP has a literalglobalkeyword; the rule now fires onglobal $x;inside PHP functions, and SAFE302 additionally flags$GLOBALS[...]superglobal writes. - PHP-specific rule adaptations. SAFE603's headline PHP target is the
@error-suppression operator (plus barephpcs:ignore/@phpstan-ignore-line/@psalm-suppress all); SAFE801 models the classic web-taint flow (superglobal$_GET/$_POST/ ... sources intoeval/exec/system/shell_exec/unserialize/->query/mysqli_querysinks and dynamicinclude/require, withintval/escapeshellargsanitizers); SAFE501 resolves numericbreak Nlevels and flagswhile (true)/for (;;)without an exiting break; SAFE401 uses thetry { } finally { }form (fopen/curl_init/ ...); SAFE701 / SAFE702 use the PHPUnit<ClassName>Test.phpconvention; SAFE803 recognises the nullsafe?->operator as the safe form. A newanalysis/dataflow_php.pytaint tracker (iterative worklists) backs SAFE801 (SAFE802 is a separate structural check). Two rules are deliberately skipped for PHP (SAFE201bare_except- PHP 7+ catches always carry a type; SAFE305wide_scope_declaration- novar/let/constdistinction); the rationale is in the language page's "Rules not registered" section. - Bundled PHP skill addendum + per-client docs.
src/safelint/skill_files/languages/php.mdplus PHP rows in all 14 AI-client skill files, so every bundled agent knows safelint can lint.phpand how the PHP rules behave.
2.5.0 - 2026-06-18#
Go is now a supported language alongside Python, JavaScript, TypeScript, Java, and Rust. .go files are discovered, parsed via Tree-sitter, and run against 16 cross-language rules plus two new Go-only rules (18 rules total for Go), bringing safelint to 40 rules (15 on by default, 25 opt-in). Go support installs via the new [go] extra (pip install 'safelint[go]'); the base install still ships no grammars. Additive per the project's semver policy (a new language is MINOR, never MAJOR); nothing renames, removes, or changes the meaning of any existing rule code, CLI flag, or config key.
Added#
- Go as the 6th registered language.
.gofiles are discovered, parsed via Tree-sitter (tree-sitter-go, shipped in the opt-in[go]extra), and dispatched to the Go-aware rule implementations. 16 cross-language rules apply: the 13 all-six core (SAFE101-105, SAFE303, SAFE304, SAFE501, SAFE603, SAFE701, SAFE702, SAFE801, SAFE802) plus SAFE302 (global_mutation), SAFE309 (dynamic_code_execution), and SAFE401 (resource_lifecycle), which Go shares with the JS family and Java. See the Go language page for the full reference. - SAFE209
empty_error_check(Go-only, disabled by default). Flagsif err != nil { }(or== nil) with an empty or comment-only body - the error was checked and then silently swallowed. The Go analogue of Rust's SAFE206; the error identifier is configurable viaerror_names_go(default["err"]). - SAFE211
panic_calls_outside_tests(Go-only, disabled by default). Flagspanic(...)calls in non-_test.gofiles; production paths should return anerrorrather than unwind the stack. The Go analogue of Rust's SAFE204; configurable viapanic_calls_go(default["panic"]). - Go-specific rule adaptations. SAFE501 flags the bare
for {}infinite loop (Go's only loop keyword) with labelled-break resolution; SAFE701 / SAFE702 use the siblingfoo_test.goconvention rather than atests/directory; SAFE802's explicit-discard exemption recognises Go's_ = f()andx, _ := f()forms; SAFE401 checks for adefer x.Close()in the same function body; SAFE105 recognises receiver-qualified self-recursion (s.Walk(...)). A newanalysis/dataflow_go.pytaint tracker (iterative worklists) backs SAFE801 / SAFE802. Seven rules are deliberately skipped for Go (SAFE201, SAFE202, SAFE203, SAFE301, SAFE305, SAFE601, SAFE803) because their semantics don't translate cleanly; the rationale is in the language page's "Rules not registered" section. - Bundled Go skill addendum + per-client docs.
src/safelint/skill_files/languages/go.mdplus Go rows in all 14 AI-client skill files, so every bundled agent knows safelint can lint.goand how the Go-specific rules behave.
Documentation#
- Development guidance is now version-controlled.
CLAUDE.md(the Claude Code project guide), theadd-language-supportdevelopment skill (.claude/skills/add-language-support/), and the language-expansion plans underplan/(plan/README.mdplus the per-language specs) are tracked, reversing the old keep-CLAUDE.md-local convention: the skill and the plans reference CLAUDE.md's checklists, so the three travel together. Machine-local Claude Code state (.claude/settings.local.json, the installed.claude/skills/safelint/copy) stays ignored. - Contributing guide: framework / runtime preset standard.
docs/contributing/adding-a-language.mdgains an "Adding a framework / runtime preset" section (config machinery shape, 9xx-band policy for framework rules, preset tests, and the full docs fan-out including both TOML forms), and its Step 8 client-file list is corrected from 12 to all 14 bundled skill files (warp and kiro were missing).
2.4.0 - 2026-06-10#
Power of Ten gap-closure: five new / widened rules. This release adds four new rules and widens one existing rule to close the most prominent gaps between SafeLint's rule set and Holzmann's ten rules, plus a new docs page mapping the ten rules onto the checks. Additive across the board (per the project's semver policy, new rules and widened language coverage are MINOR); nothing renames, removes, or changes the meaning of any existing rule code, CLI flag, or config key.
Added#
- SAFE105
no_recursion(Holzmann rule 1), all five languages, enabled by default atwarningseverity. Flags direct self-recursion, a function that calls its own name, either bare (fact(n - 1)) or self-qualified (self.walk(...)/this.walk(...)). A call on a different receiver (other.walk(...)) does not fire. Indirect / mutual recursion and anonymous-function recursion are documented out-of-scope blind spots. Annotate deliberate recursion with# nosafe: SAFE105(or the language's comment form). - SAFE307
interior_mutable_static(Holzmann rule 6), Rust-only, disabled by default. Flags astaticwhose type provides safe interior mutability (Mutex/RwLock/OnceLock/Atomic*/RefCell/Cell/Lazy*) andlazy_static!blocks, the safe-code global mutable state that SAFE602'sunsafegate never sees.constandstatic mutare not flagged. Configurable viainterior_mutable_types_rust. - SAFE309
dynamic_code_execution(Holzmann rule 8), Python / JS / TS / Java, disabled by default. Structural detection ofeval/exec/compile/__import__(Python),eval/new Function(JS/TS), andClass.forName/Method.invoke/defineClass/loadClass(Java). Complements the taint-gated SAFE801, both may fire on one line. Rust is excluded (its rule-8 analogue, macros, parses as opaque token trees). Per-language call lists viadynamic_exec_calls/dynamic_exec_calls_javascript/dynamic_exec_calls_java. - SAFE603
blanket_suppression(Holzmann rule 10), all five languages, disabled by default. Flags un-scoped suppressions of other analysers: bare flake8noqa,type: ignorewithout a code, rule-lesseslint-disable,@ts-nocheck/@ts-ignore,@SuppressWarnings("all"),#[allow(clippy::all)]/#[allow(warnings)]. Scoped suppressions are clean, and SafeLint's own# nosafedirectives are never flagged (SAFE004 polices those). - New docs page: The Power of Ten, adapted. Maps each of Holzmann's ten rules to the SafeLint rules that implement it, per language, and records the rationale for the adapted-away clauses (rule 3 dynamic allocation, rule 8 preprocessor for non-Rust languages), plus fidelity notes from a re-read of the paper: rule 2's non-terminating-loop exception (the justified
# nosafe: SAFE501analogue), rule 5's full clause set, rule 7's explicit-discard escape hatch (let _ =/_ =), rule 9's function-pointer adaptation, rule 10's rewrite-not-suppress policy, and the un-covered Rust#[cfg]conditional-compilation analogue. min_assertionsconfig knob on SAFE601missing_assertions. The rule now counts assertions per function instead of only detecting presence. Defaultmin_assertions = 1preserves the existing behaviour; setmin_assertions = 2for the assertion density Holzmann's rule 5 actually asks for. Configurable in[tool.safelint.rules.missing_assertions](pyproject.toml) or[rules.missing_assertions](safelint.toml); a non-integer value fails loud with aTypeError.
Changed#
- SAFE302
global_mutationnow covers Java (previously Python / JS / TS only). On Java it flags non-finalstaticfield declarations, Java's shared-mutable-state shape, at the declaration site.static finalfields are clean (interior mutability of afinalreferent is a documented exclusion needing type resolution); instance fields, locals, and interface fields never fire. This fulfils the Java SAFE302 work previously marked "deferred to a future release" in the language docs. Heads-up for existing Java users: because SAFE302 is enabled by default, projects with non-finalstaticfields will see new violations after upgrading; suppress per-line with// nosafe: SAFE302, per-file, or viaper_file_ignoresif this is not yet a policy you want to enforce. SAFE302 remains unported to Rust (static mutis SAFE602's territory; safe interior-mutable statics are the new SAFE307's).
Documentation#
- Removed the four repo-root redirect stubs (
AI_CLIENTS.md,CONFIGURATION.md,ADDING_AN_AI_CLIENT.md,ADDING_A_LANGUAGE.md). These were 7-line "this page has moved" placeholders left behind by the docs-site migration; the liveCONTRIBUTING.md/SUPPORT.mdpointers now link straight to the docs site (shelkesays.github.io/safelint/...) and code-comment references point atdocs/...paths. Themkdocsbuild is unaffected (the community-health copies resolve cross-references throughscripts/prepare_docs.py's rewrite map, not the stubs). - Doc accuracy pass for the new rule set. Refreshed rule and AI-client counts across
README.md,docs/index.md,docs/configuration/rules.md, and the per-language pages (38 rules total: 15 on by default, 23 opt-in; 14 supported AI clients), updated every per-language page, the bundled client skill files, and the language crib sheets to list SAFE105 / SAFE307 / SAFE309 / SAFE603 and the widened SAFE302, and fixed a brokencli.md#exit-code-2-silent-failure-triggersanchor referenced from three language pages.
Internal#
- SafeLint now passes its own rule set with no inline suppressions other than the documented
SAFE203logging exemptions. The newSAFE105 no_recursionrule fires on intra-procedural tree-walkers in the dataflow analysers,deep_merge, and a couple of parse-tree helpers; rather than annotate them, those were converted to explicit iterative worklists / loops (mirroring the existing iterativewalk()), and the remainingSAFE501worklist-drain annotations and oneSAFE304annotation were likewise refactored away. No behaviour change; recursion depth on the affected helpers was always bounded by source-construct nesting.
2.3.0 - 2026-06-09#
Kiro AI client; documentation accuracy pass. Kiro (kiro.dev, AWS's agentic IDE) joins the registry as the fourteenth supported AI client, additive, one ClientSpec. This release also folds in the post-2.2.0 documentation work: the per-client docs gaps for Warp and OpenCode are closed, docs/configuration/cli.md is restructured into a per-command reference, and the contributing "Adding an AI client" guide plus the AI client integration pages are corrected against the current single-file install architecture. No behaviour change for existing clients or languages.
Added#
- Kiro (
kiro.dev) added as a supported AI client. AWS's agentic IDE reads steering files under.kiro/steering/*.md;safelint skill install --client kirowrites.kiro/steering/safelint.mdat project scope (--project, recommended for team repos) or~/.kiro/steering/safelint.mdat user scope. Auto-detection picks up a.kiro/directory in the cwd (project) or home (user). OneClientSpecaddition plus the bundledskill_files/kiro/safelint.mdtemplate; the_CLIENT_SPECSregistry, drift-detection contract, and CLI choices all extend automatically. Kiro also honours theAGENTS.mdstandard as a fallback, but safelint installs to its first-class steering file rather than coupling on the sharedAGENTS.md(owned by the codex client).
Documentation#
- Warp added to the per-client docs. New
docs/ai-clients/clients/warp.mdpage covering the project-scope-only contract; row added to the client table indocs/ai-clients/index.md; mkdocs nav entry under Per-client guides. (Warp itself shipped as a client in 2.2.0; this just closes the docs gap.) - OpenCode auto-detection documented in
codex.md. New "OpenCode auto-detection" subsection covering the.opencode/marker piggyback, the AGENTS.md auto-create vs append cases, and a "Note on OpenClaw" explaining why that agent was evaluated and deliberately not added. - Per-client guides reordered by approximate real-world usage (mainstream / mid / lower / niche tiers) instead of "the order we added support".
_CLIENT_SPECSorder in_skill_install.pyis unchanged - the registry order drives auto-detection iteration and CLI output; only the docs ordering follows popularity. docs/configuration/cli.mdrestructured into a per-command reference (one section per command and subcommand, brief style: description + flags table + 1-2 examples). New dedicated sections forsafelint skill install,safelint skill path,safelint --stdin,safelint version, andsafelint help. Promoted from "Configuration → CLI flags and commands" to a top-level "CLI commands and flags" nav entry; URL.../configuration/cli/unchanged.docs/json-schema.mdclarifications. Reframed "stable since v1.5.0" to distinguish shape stability (v1.5.0) from rule-set growth (Java in v2.1.0, Rust in v2.2.0). Added a "Language coverage" note clarifying all five languages produce identical JSON structures.- Contributing and integration docs corrected against current code. The "Adding an AI client" guide dropped a non-existent install primitive and the obsolete
_PEER_CLIENT_DIRSstep, added the requireddocumentation_relpathsfield to its worked example, documented the project-scope-only client pattern, and refreshed its client / language counts.docs/ai-clients/lifecycle.mdandscope.mdnow describe the single-file install model (no directory-tree install) and the project-scope-only contract. Contributor pointers no longer instruct editing the moved repo-root redirect stubs (AI_CLIENTS.md/CONFIGURATION.md).
Bundled-skill drift after upgrade#
pip install --upgrade safelint past this release will cause safelint skill status to report DRIFT on every installed copy. That's because all 13 bundled skill files (the per-client templates under src/safelint/skill_files/) were edited to fix two issues:
- The JSON example violation was internally inconsistent (
SAFE101 / function_lengthpaired with abare_exceptsuggestion). Switched toSAFE201 / bare_exceptso code, rule, and suggestion describe the same defect. - The "stable since v1.5.0" schema-stability sentence was reworded to acknowledge rule-set expansion (matching
docs/json-schema.md).
Action for users running safelint skill install: after upgrading, run safelint skill update (idempotent; refreshes drifted installs to the new bundled content). Symlink-mode installs (safelint skill install --symlink) pick up the new bundle automatically with no action needed. See safelint skill status and safelint skill update in the CLI reference.
2.2.0 - 2026-06-01#
Rust support; rule-catalogue CLI; Warp + OpenCode agents. Promotion of the rc1 / rc2 / rc3 cycle to GA. Three additive bundles ship together: a fifth supported language, a CLI surface for catalogue introspection, and two more AI clients on the registry. Python / JavaScript / TypeScript / Java users see zero behaviour change beyond an additive grammar option, an additive CLI subcommand, and an additive --client=warp choice.
Install: pip install 'safelint[rust]' to add Rust to an existing setup (PyO3 / maturin polyglot: pip install 'safelint[python,rust]'); plain pip install safelint ships the engine only (no language grammars), so projects must use the [<lang>] extra matching their source files.
Release model#
The pyproject.toml version bump that lands on main for this release reads as 2.1.0 (the previous GA) to 2.2.0. That's the diff a reviewer sees against main. The full trajectory was tracked on the release/rust integration branch instead, so main is insulated from the in-flight RC churn:
| Step | Branch | Tag | PyPI |
|---|---|---|---|
2.1.0 (previous GA) |
main |
v2.1.0 |
live |
2.1.0 to 2.2.0rc1 |
release/rust |
v2.2.0rc1 |
live (pre-release) |
to 2.2.0rc2 |
release/rust |
v2.2.0rc2 |
live (pre-release) |
to 2.2.0rc3 |
release/rust |
v2.2.0rc3 |
live (pre-release) |
to 2.2.0 (this GA) |
merges to main |
v2.2.0 |
published on tag push |
The rc1 / rc2 / rc3 commits never landed on main directly; their content arrives wholesale through this GA merge. The detailed rc1 / rc2 / rc3 changelog entries below catalogue when each feature first shipped so anyone tracing a regression can find the originating RC.
Highlights#
- Rust as the 5th registered language (from rc1).
.rsfiles are discovered, parsed via Tree-sitter, and run against 13 of the cross-language rules (the all-five-languages set). 10 additional Rust-only rules cover Rust-idiom-specific patterns (panic placement, lock poisoning,unsafeblock documentation, truncatingascasts, silentErrarms, dangerousmem::*ops, needlessmut, unchecked arithmetic on integer params, broad.unwrap()outside tests, plus the empty-Err/ unlogged-ErrRust analogues ofempty_except/logging_on_error). Recognises both inline#[cfg(test)] mod testsand Cargotests/<stem>.rsintegration-test conventions. See the Rust language page and the rc1 entry below for the full per-rule rationale. safelint list-rulessubcommand (from rc2). Prints the rule catalogue so AI agents, CI dashboards, and docs pipelines can introspect what safelint will check. Filters:--language=python|javascript|typescript|java|rust,--enabled-only. Output formats:--format=text(default),--format=json,--format=markdown,--format=sarif. The--list-rulesflag form works as an alias when placed anywhere in argv. Categories derived from the leading digit of eachSAFExxxcode, matching the rule-numbering policy.- Warp as the 13th AI client (from rc2).
safelint skill install --client=warpwrites<cwd>/WARP.md(auto-discovered by Warp's terminal-native AI) or~/.warp/WARP.md(user-global). Auto-detection markers:WARP.mdand.warp/. - OpenCode auto-detection (from rc3).
safelint skill install --client=autonotices OpenCode (sst/opencode) projects via.opencode/in codex'scwd_markers. OpenCode readsAGENTS.mdfor project context, the same file codex's secondary install already populates with a delimited safelint section. No new client spec needed.
Cumulative scope vs 2.1.0#
Every change shipped via the three release candidates is in this GA. Pin to safelint==2.2.0 for a deterministic install; the rc1 / rc2 / rc3 entries below document the iteration history for anyone who needs to trace when a specific feature landed.
The detailed change lists, default configurations, deliberately-skipped rules, and per-rule rationale live in the rc1 / rc2 / rc3 sections immediately below. They are kept verbatim as historical record rather than reflowed here.
2.2.0rc3 - 2026-06-01#
OpenCode auto-detection. One-line addition to the codex spec's cwd_markers extends safelint skill install --client=auto to notice OpenCode (sst/opencode) projects. OpenCode reads AGENTS.md at the repo root for project context, the same file codex's secondary install populates with a delimited safelint section. An OpenCode-only project (.opencode/ directory present, no .codex/) now auto-detects and gets the safelint section in AGENTS.md transparently.
Added#
.opencodein codexcwd_markersandhome_markers- OpenCode users get the safelint AGENTS.md section through the existing codex spec machinery; no new client entry needed because both agents read the same shared file. The primary install still lands at.codex/instructions.md(a small Markdown file OpenCode itself ignores; users can gitignore it). New test (test_install_auto_detects_codex_via_opencode_dir) pins the contract.
Evaluated and skipped#
- OpenClaw (https://openclaw.ai) - chat-bridge agent (WhatsApp / Slack / Telegram / iMessage / Discord / Signal) with global-only configuration (
~/.openclaw/openclaw.jsonfor channel allowlists and mention rules). No project-level instructions / rules file convention, no per-workspace context. Installing a Markdown skill file would create a file nothing reads, so OpenClaw doesn't currently fit the safelint skill abstraction. Revisit when (if) the project adds a per-project rules-file feature.
2.2.0rc2 - 2026-05-29#
Two additive features on top of rc1 ahead of the 2.2.0 GA. Rust support stays exactly as it shipped in rc1 (no behaviour change for the existing language work); this RC adds a CLI rule-catalogue command and brings the AI-client roster to thirteen.
Added#
safelint list-rulessubcommand (and--list-rulesflag alias) - prints the full rule catalogue so AI agents, CI dashboards, and docs-generation pipelines can introspect what safelint will check without grepping the per-agent skill files. Filters:--language=python|javascript|typescript|java|rustto scope to a single language,--enabled-onlyto drop opt-in rules. Output formats:--format=text(default; aligned table grouped by category band),--format=json(programmatic catalogue withversion+ per-rule schema),--format=markdown(one table per category band, useful for piping into docs),--format=sarif(SARIF 2.1.0 catalogue with the rules underruns[0].tool.driver.rules[]and an emptyresults[]; consumable by GitHub Code Scanning catalogue UIs). Categories are derived from the leading digit of the rule code so the listing automatically picks up the SafeLint rule-numbering policy (1xx function shape, 2xx error handling, 3xx side effects / state, 4xx resource lifecycle, 5xx loop safety, 6xx documentation, 7xx test coverage, 8xx dataflow, 9xx framework-specific). Default scope shows every shipped rule with aDefaultcolumn marking enabled-by-default vs opt-in; the catalogue stays catalogue-only (severity / enabled defaults from the bundledDEFAULTS, not from the user's resolved config). Empty filter combinations exit 2 with a stderr error so a typo in a CI script (--language=pythn) can't silently produce an empty document.- Warp as a 13th AI client -
safelint skill install --client=warpwrites<cwd>/WARP.md(canonical, auto-discovered by Warp's AI) or~/.warp/WARP.md(user-global). The bundled skill file (src/safelint/skill_files/warp/WARP.md) mirrors the existing 12 client skill files: the same 8 steps, the same JSON parsing recipe, the same Power-of-Ten rationale crib sheet, plus Warp-specific touches (the AI is in the terminal, so all check / install commands land directly as terminal tasks). Auto-detection markers areWARP.md(the canonical project file) and.warp(Warp's user-config directory). Listed in the--clientchoices, thesafelint help skilloutput, and the_HELP_COMMANDSline.
Changed#
safelint list-rulesreferenced in every skill file's language-detection step - the new "to check the live rule list, runsafelint list-rules --format jsonand look at thelanguagesfield" hint replaces the longer Python-snippet fallback in the bundled WARP.md addendum (other agent skill files still carry the legacy form for backwards compatibility with already-installed copies). The Python snippet stays documented as the fallback.- Documentation roster updated -
README.md,SUPPORT.md,AI_CLIENTS.md,docs/index.md,docs/configuration/cli.md,docs/contributing/adding-an-ai-client.md, andsrc/safelint/skill_files/README.mdnow read "thirteen supported AI clients" and add Warp to every per-client install/usage table.
Internal#
src/safelint/_rule_listing.py- new module exposingiter_rule_specs(),filter_specs(), and four format renderers (format_text/format_json_listing/format_markdown_listing/format_sarif_listing). Pure-function design, no engine / config / parser dependencies, so the catalogue is cheap to render in any process the agent is running in.cli.py-_build_list_rules_parser+_run_list_rules+_print_rule_listingthread the subcommand through the existing argv-routing scanner._dispatch_subcommandrefactor moves the per-subcommand-token routing out ofmain()somain()stays under thefunction_length=60/complexity=10caps safelint enforces on itself._skill_install.py- one_WARP_SPECClientSpecentry plus its position in_CLIENT_SPECS; the rest of the install / detection / status / remove machinery picks it up automatically because all of those routes iterate over the registry.
2.2.0rc1 - 2026-05-27#
Rust is now a supported language. Second new language landing in the v2.x line. .rs files are discovered, parsed via Tree-sitter, and run against 17 of the 20 cross-language rules - plus 10 new Rust-only rules covering Rust-idiom-specific patterns. Python / JavaScript / TypeScript / Java users see zero behaviour change beyond an additive grammar option.
Install: pip install 'safelint[rust]' (PyO3 / maturin polyglot projects: pip install 'safelint[python,rust]'). Tagged as a release candidate so the new language can be exercised against real Rust codebases before promoting to GA.
Added#
- Rust as a registered language: 27 rules apply, with the engine's per-language dispatch routing
.rsfiles automatically. Source-language analysis (parser, AST walks, per-rule logic) is identical to the other registered languages; only language-idiom-specific detail (macro handling, attribute scanning, pattern matching) is per-language. - 17 cross-language rules ported to Rust:
SAFE101 function_length,SAFE102 nesting_depth,SAFE103 max_arguments,SAFE104 complexity,SAFE303 side_effects_hidden,SAFE304 side_effects,SAFE501 unbounded_loops,SAFE601 missing_assertions,SAFE701 test_existence,SAFE702 test_coupling,SAFE801 tainted_sink,SAFE802 return_value_ignored,SAFE803 null_dereference. Each rule'slanguagetuple was widened to include"rust"and per-language node-type tables grew a Rust entry. Rust-specific defaults shipped:io_functions_rust(covers macrosprintln/eprintln/write/writeln/dbgalongside fs / io / process / network calls),assertion_calls_rust(stdlibassert*macros, debug-only variants, proptest'sprop_assert*),sinks_rust/sources_rust/sanitizers_rust(taint defaults centred onCommandshell execution, raw-SQL crate verbs,LibraryFFI,openpaths; narrow sanitizer set),nullable_methods_rust(Map::get/Vec::get/Iterator::next/parse/var/ fs::read family / checked arithmetic),flagged_calls_rust(io::Write / io::Read / fs mutators / network send / process spawn). - 10 Rust-only rules slotted into existing category bands per the SafeLint rule-numbering policy (no new band created for the language):
SAFE110 needless_mut(1xx function-shape, warning, default-disabled):let mut x = ...wherexis never reassigned, never has&mut xtaken, and is never used as a method receiver / field-access / index target. Conservative skips on ambiguous usages to keep false-positive rate low. Mirrorsclippy::needless_mut. Holzmann rule 6 (smallest scope).SAFE112 unchecked_arithmetic_on_input(1xx, warning, default-disabled):+/-/*on integer-typed function parameters can overflow silently in release. Usechecked_*/wrapping_*/saturating_*to make the choice explicit. Static-only detection (parameter type annotations); locally-derived integers aren't tracked. Holzmann rule 7.SAFE204 panic_macros_outside_tests(2xx error-handling, warning, default-disabled):panic!/todo!/unimplemented!macros in non-test code.unreachable!()deliberately excluded from defaults (idiomatic for impossible-branch markers). Test code (#[test]or#[cfg(test)] mod) is exempt.SAFE205 lock_poisoning_ignored(2xx, warning, default-disabled):mutex.lock().unwrap()/rwlock.read().unwrap()/.write().unwrap()patterns silently cascadePoisonErrorpanics across threads. Match onPoisonResultor call.into_inner()explicitly.SAFE206 silent_result_discard(2xx, warning, default-disabled): emptyErr(_) => {}arms and emptyif let Err(_) = ... { }bodies. The Rust spiritual analogue ofSAFE202 empty_except.let _ = result;andresult.ok();do NOT fire (those are explicit auditable discards, not silent swallows).SAFE207 unlogged_error_branch(2xx, warning, default-disabled):Errarms /if let Err(...)bodies with non-empty bodies that contain no log call. Recognised log calls:error!/warn!/info!/debug!/trace!/log!/event!(log + tracing crates),eprintln!/eprint!/println!/print!/dbg!. Exempts bodies withreturn, panic-like macros, or tail-positionErr(...)re-raise. The Rust analogue ofSAFE203 logging_on_error.SAFE208 result_unwrap_outside_tests(2xx, warning, default-disabled): broad form, fires on any.unwrap()/.expect()/.unwrap_unchecked()outside test code. Catches bare-variable unwraps that the narrower SAFE205 / SAFE803 miss. Documented intentional overlap with those two; users pick strictness level by enabling subsets. Holzmann rule 7.SAFE306 dangerous_mem_ops(3xx side-effects, error, default-disabled):std::mem::transmute/transmute_copy/forget/zeroed/uninitializedcalls. Path-qualified detection (the function's scoped-identifier path must contain"mem") avoids firing on user-defined helpers of the same name. Baretransmute(x)(nomem::prefix) is NOT flagged.SAFE308 truncating_as_cast(3xx, warning, default-disabled):as u8/as u16/as u32/as i32/as f32casts silently truncate.TryFrom/try_into()is the checked alternative.isize/usize/i128/u128/f64are NOT flagged as targets (widest types). Configurable viatruncating_cast_targets_rust. Holzmann rule 1 + 7.SAFE602 undocumented_unsafe(6xx documentation, warning, default-disabled):unsafe { ... }blocks lacking a// SAFETY:comment (case-insensitive) on a preceding line. Mirrorsclippy::undocumented_unsafe_blocks.unsafe fndeclarations not covered (separate/// # Safetyconvention; future rule may extend).- Rust test-context detection: SAFE204 / SAFE208 / SAFE701 walk parent
function_item/mod_itemfor#[test]or#[cfg(test)]attributes (which parse as preceding-siblingattribute_items, the tree-sitter-rust convention). The detection is correctness-critical for SAFE701 in particular - without it every Rust source with the idiomatic inline#[cfg(test)] mod testswould falsely fire asking for an externaltests/<stem>.rspair the Rust ecosystem doesn't use. - Rust macro handling: SAFE303 / SAFE304 walk
macro_invocationnodes alongsidecall_expression(Rust's most common I/O entry points are macros likeprintln!/eprintln!/write!/writeln!/dbg!). Macro names render with the trailing!in violation messages. languages/rust.mdskill addendum: parallel to python.md / java.md / javascript.md / typescript.md - the Rust-specific addendum AI clients read when an agent's session is in a Rust project. Covers install nuance, macro handling, test-context detection, per-rule Rust phrasing for all 27 codes, deliberately-skipped rules, idiomatic fix patterns, integration with the Rust tool chain.- All 12 AI clients updated: each per-agent skill file (claude / cursor / copilot / gemini / windsurf / codex / continue / cline / aider / trae / antigravity / zed) gets the
pip install 'safelint[rust]'row in its install table, theRust→languages/rust.mdrow in its language addendum table, and 10 new SAFE10x / SAFE20x / SAFE30x / SAFE602 rule rows for the Rust-only rules. - docs site Rust reference page (
docs/languages/rust.md): mkdocs nav now includes Rust alongside the other four languages; the page mirrors the skill addendum content for site readers.
Cross-language rules deliberately skipped for Rust#
These 6 rules are NOT registered for Rust because the Python / JS-family / Java semantics don't translate cleanly:
SAFE201 bare_except: Rust has no try/catch. The panic-recovery primitive isstd::panic::catch_unwindwhich has its own auditable shape, no bare-catch hazard.SAFE202 empty_except: no try/catch. Spirit ("silently swallow an error") covered by SAFE206 instead.SAFE203 logging_on_error: no try/catch. Spirit ("handle the error without logging") covered by SAFE207 instead.SAFE301 global_state/SAFE302 global_mutation: Rust has noglobalkeyword.static mut FOOrequiresunsafe { }access, already audit-gated by SAFE602.SAFE401 resource_lifecycle: Rust's RAII (Drop trait) makes resource cleanup language-enforced. Nowithblock /try-finally/try-with-resourcesanalogue needed.
Numbering policy clarification#
The SafeLint rule-numbering policy is now explicit in CLAUDE.md: language-idiom rules slot into existing category bands by closest theme (1xx-8xx) rather than getting per-language bands. 9xx remains reserved for framework-specific rules (Spring today; future axum / actix / Django / Express / Rails framework rules will go here too). This commit's 10 Rust-only rules land in 1xx / 2xx / 3xx / 6xx accordingly, alongside their cross-language siblings.
2.1.0 - 2026-05-21#
v2.1.0 GA. The release candidate cycle is closed. The cumulative scope vs v2.1.0rc1 is a long list of rule-correctness fixes and doc / skill consistency fixes that landed during the RC review cycle; engine and rule behaviour on the headline Java + Spring Boot surface is now finalised for the 2.1.x line. Functionally v2.1.0 ships the rc1 feature set (Java as a registered language, the spring-boot framework preset, the four new SAFE901-904 rules, 16 cross-language rules ported to Java) plus the corrections below.
Install: RC pins and --pre flags are no longer required. pip install 'safelint[java]' resolves to 2.1.0 straight from PyPI.
Rule corrections (vs 2.1.0rc1)#
- SAFE401
resource_lifecyclefor Java's manualtry { ... } finally { ... }is now strict: the finally clause must contain a direct<acquired-var>.close()invocation. The previous heuristic accepted any try with a finally;try { in = new FileInputStream(p); } finally { audit(); }silently passed. Bare-expression acquirers (try { new FileInputStream(p); } finally { ... }) now always fire. Wrapped acquirers (br = new BufferedReader(new FileReader(path))) correctly inherit the outer variable name for cleanup tracking. Helper-pattern trade-off:IOUtils.closeQuietly(in),Try.run(() -> in.close())style closes are NOT recognised under the strict matcher and will fire; switch to try-with-resources or suppress with// nosafe: SAFE401. The strict path applies to Java only; JavaScript retains its documented heuristic. - SAFE801
tainted_sinklambda capture analysis: a Java lambda's tracker is now seeded with own-params plus the enclosing method's final tainted set (locals included), soString dirty = input; run(() -> exec(dirty));correctly fires. Compound assignments (sql += " suffix") preserve the LHS's existing taint. Chained assignments (a = b = source()) propagate the innermost-RHS taint through every LHS. Enhanced-for loops (for (String arg : args) { exec(arg); }) taint the loop variable from the iterable. Receiver-as-input now matches generic-type constructors viageneric_typeunwrap (new MyResource<Foo>(input)). - SAFE801 sanitizers_java defaults narrowed. Context-specific output encoders (OWASP
forHtml/forJavaScript/forCssString, Apache CommonsescapeHtml*/escapeXml/escapeJava/escapeJson, SpringhtmlEscape) and URL encoders (encode/encodeURIComponent) are no longer in defaults. They were creating cross-context false negatives (Encode.forHtml(name)beforejdbc.query(...)silently cleared the SQL-sink warning). Defaults are nowsanitize/validate/quote/escapeonly; opt back in via TOML if your project routes everything through a specific encoder. - SAFE801 spring-boot preset sinks: collision-prone bare verbs removed.
put/delete/update/exchangeare no longer in the preset'ssinks_java; they collided withHashMap.put/File.delete/CurrencyExchange.exchange/ project-local helpers under SAFE801's single-set design. Unambiguous Spring names (query/queryForObject/queryForList/queryForMap/queryForRowSet/batchUpdate/getForObject/getForEntity/postForObject/postForEntity/postForLocation/patchForObject) stay. Add the bare verbs explicitly via[tool.safelint.rules.tainted_sink] sinks_javaif your project needsrestTemplate.put(...)/jdbcTemplate.update(...)coverage. - SAFE902
spring_missing_transactionalreceiver-name guard. The rule now only counts repository-write method calls whose receiver name (lowercased) containsrepo/dao/jdbctemplate. Without this,call_name()stripped the receiver and unrelated calls likefile.delete()/cache.delete()/restTemplate.delete(...)were counted as Spring Data writes. Baretemplatewas tested but matched non-DB Spring templates (restTemplate,kafkaTemplate,redisTemplate);jdbctemplateis the correct narrower pattern. Recognisesthis.userRepo.save(...)field-access receivers too. - SAFE904
spring_async_checked_exceptionclass-level@Async. The rule now also fires when the enclosing class carries@Async(not only the method). Spring applies class-level@Asyncto every method in the class; the throws clause is just as misleading either way. Docs and rule docstring updated to reflect that the rule flags ANYthrowsclause (checked or unchecked) for simplicity; distinguishing checked vs unchecked needs type-inference safelint doesn't do. - SAFE103
max_argumentsuntyped Java lambda params.(a, b, c, d, e, f, g, h) -> ...anda -> ...shapes parse asinferred_parameters/ bareidentifierin tree-sitter-java; the rule's counter dispatched only onformal_parameter/spread_parameterand silently counted untyped lambdas as zero-arg. Added the lambda-specific dispatch so over-argument untyped lambdas in stream pipelines correctly fire. - SAFE202
empty_exceptJava catch-body shapes. Empty Java catch bodies with multiple comment children ({ // a\n // b\n }) now correctly classify as empty. tree-sitter-java emits each comment as a named block child. Empty-statement (;) inside Java catches is also recognised as a no-op. Python / JS / TS retain their single-statement check. - SAFE701 / SAFE702
Test-prefix Java false-positives removed. Production classes likeTestDataFactory.java/TestConfig.javaundersrc/main/javawere being classified as tests (silently skipping coverage enforcement). TheTest-prefix shortcut is gone; legitimate JUnit 3 tests under the configuredtest_dirsare still picked up via the path-component check. _node_utils._java_object_creation_namenow handlesgeneric_type.new MyResource<Foo>(...)parameterised constructors were silently invisible to SAFE401 tracked-acquirer / SAFE801 constructor-sink / SAFE303-304 I/O-constructor matchers. The unwrap recurses throughgeneric_typeto the innertype_identifier/scoped_type_identifier.- SAFE303 / 304 default
io_functions_javacleanups.HttpClientis replaced by the actual matched factory + send method names (newHttpClient/send/sendAsync); the class itself has no public constructor socall_name()never returned"HttpClient".formatremoved from SAFE303's set (collided withString.format/MessageFormat.format).FileChannelremoved from SAFE401'stracked_functions_javafor the same receiver-stripping reason.
Doc / skill alignment#
- All Java suppression examples switched from
# nosafeto// nosafe; Java's comment prefix is//. - SAFE801 docs now describe what's actually in
sanitizers_javadefaults (no HTML / URL encoders) and explain why. - README rule-count totals corrected: 24 rules total (was 20), 14 default-on, 10 opt-in (the four
SAFE9xxare opt-in under vanilla, default-enabled by thespring-bootpreset). - Per-language docs corrected: "16 cross-language rules" (was "17"); SAFE302 is Python / JS / TS only, not cross-all-four.
- SAFE902 / SAFE903 severity rows in the rule reference corrected from
"warning"to"error"(matches the implementation). - README and the docs landing page now list Java in the "Currently supported languages" table; PyPI keywords + description include
java/spring-boot. docs/configuration/rules.mdgot a fullSAFE901/SAFE902/SAFE903/SAFE904rule-detail section (was missing).- Project-wide writing-style sweep: em-dashes removed from all docs / skills / README / CHANGELOG re-introduced during the RC cycle.
Migration#
- From
v2.0.0: see the Migration table in the 2.1.0rc1 entry below; the only required change is bumping the install command to opt into the new[java]extra if you lint Java sources, and bumpingrev: v2.0.0torev: v2.1.0in pre-commit configs. - From
v2.1.0rc1: drop any==2.1.0rc1pin or--preflag;pip install -U 'safelint[<lang>]'is sufficient. Pre-commit users bumprev: v2.1.0rc1torev: v2.1.0.
2.1.0rc1 - 2026-05-16#
Java is now a supported language, with a dedicated Spring Boot framework preset. First MINOR release after v2.0.0; ships as a release candidate so the new language can be exercised against real Spring Boot codebases before promoting to GA. Source-language analysis works on every Java file; per-project tuning happens via the new [tool.safelint.java] framework = "spring-boot" selector that adds Spring-aware taint sinks, nullable methods, and four new structural rules (SAFE901-904) covering common Spring Boot misuses. Python / JavaScript / TypeScript users see zero behaviour change.
Install as a RC pre-release:
pip install 'safelint[java]'
# or, for a polyglot repo:
pip install 'safelint[python,java]'
# or the kitchen-sink:
pip install 'safelint[all]'
Pre-commit users update rev: v2.0.0 to rev: v2.1.0 and add 'safelint[java]==2.1.0rc1' to additional_dependencies (the RC pin is required until v2.1.0 GA so pre-commit's pip resolver does not fall back to v2.0.0 which lacks the [java] extra).
Added#
- Java as a fully-registered language,
.javafiles are now parsed, walked, and dispatched through the engine the same way as Python / JavaScript / TypeScript. Newsrc/safelint/languages/java.pyexports the per-grammar node-type constants (METHOD_DECLARATION/CONSTRUCTOR_DECLARATION/LAMBDA_EXPRESSION/CATCH_CLAUSE/TRY_WITH_RESOURCES_STATEMENT/METHOD_INVOCATION/OBJECT_CREATION_EXPRESSION/ etc.) plus theJAVALanguageDefinition. Registered insrc/safelint/languages/__init__.pywith the standard available / unavailable gating - missing the[java]extra surfaces the install hint on first run, same posture as JS / TS. - 16 cross-language rules ported to Java:
SAFE101 function_length,SAFE102 nesting_depth,SAFE103 max_arguments,SAFE104 complexity,SAFE202 empty_except,SAFE203 logging_on_error,SAFE303 side_effects_hidden,SAFE304 side_effects,SAFE401 resource_lifecycle,SAFE501 unbounded_loops,SAFE601 missing_assertions,SAFE701 test_existence,SAFE702 test_coupling,SAFE801 tainted_sink,SAFE802 return_value_ignored,SAFE803 null_dereference. Each rule'slanguagetuple was widened to include"java"and the per-language node-type tables grew a Java entry. Java-specific defaults shipped for the configurable rules:io_functions_java(println/print/FileInputStream/Files.readAllBytes/ ...),tracked_functions_java(file streams vianew+Filesfactory methods + JDBCgetConnection),assertion_calls_java(JUnit 5Assertions.*+ AssertJassertThat),sinks_java/sources_java(Servlet API for sources;Runtime.exec/executeQuery/ reflection / SSRF entry points for sinks) andsanitizers_java(limited to generic validators / wrappers:sanitize/validate/quote/escape. Context-specific encoders are deliberately NOT in the defaults: URL encodersencode/encodeURIComponentare URL-only, Apache Commons HTML/XML escapers and SpringhtmlEscapeare HTML-only, and the OWASP Java Encoder API is per-context; including any of those as universal sanitizers would suppress SAFE801 on cross-context flows likejdbc.query("... " + encode(input)). Users who route output through one of those encoders can opt them in via TOML),flagged_calls_java(Filemutators + immutable-type methods),nullable_methods_java(Map.get/getParameter/getHeader/ reflection getters). - Java framework presets via
[tool.safelint.java] framework = "<name>", mirroring the JS runtime-presets architecture from v1.13.0. Two presets ship today: vanilla(default) - plain Java stdlib defaults; the fourSAFE9xxSpring rules stay disabled. Existing v2.0.0 users picking up v2.1.0rc1 see no behaviour change unless they explicitly opt in.spring-boot- extendssinks_javawith unambiguous JdbcTemplate / RestTemplate methods:query/queryForObject/queryForList/queryForMap/queryForRowSet/batchUpdate, andgetForObject/getForEntity/postForObject/postForEntity/postForLocation/patchForObject. Bareput/delete/update/exchangeare deliberately excluded because they collide with HashMap / File / project-local helpers under SAFE801's single-set design (no receiver-aware matching); users who specifically wantrestTemplate.put/.delete/.exchangeSSRF detection orjdbcTemplate.updateSQLi detection can opt in via TOML. Extendsnullable_methods_javawithqueryForObject(RowMapper implementations and nullable column values can yield null; the zero-rows case raisesEmptyResultDataAccessExceptioninstead). Enables the fourSAFE9xxSpring-specific structural rules below. Source-language analysis is identical across presets - same parser, same AST walks - only the rule defaults shift.- Four new Spring Boot framework-aware rules (
SAFE9xxband, Java-only, default-disabled under vanilla, enabled by thespring-bootpreset): SAFE901 spring_field_injection(warning):@Autowiredon a field declaration. Spring's reference docs recommend constructor injection (immutable, testable, fail-fast on missing deps). Both bare@Autowiredand fully-qualified@org.springframework.beans.factory.annotation.Autowiredare recognised.SAFE902 spring_missing_transactional(error): service-layer method (@Service/@Componentclass) doing 2+ Spring Data writes (save/saveAll/saveAndFlush/delete/deleteAll/deleteAllInBatch/deleteAllById/deleteAllByIdInBatch/deleteById/update) without@Transactionalon the method or the class. Receiver-name guard constrains matching to receivers whose lowercased name containsrepo/dao/jdbctemplateso unrelated calls likefile.delete()/restTemplate.delete()don't count. Single-write methods are exempt.SAFE903 spring_unvalidated_input(error):@RestController/@Controllermethod parameter binds@RequestBodyor@ModelAttributewithout@Valid/@Validated.@PathVariableand@RequestParamare deliberately NOT covered (typically bind to primitives). ComplementsSAFE801structurally -SAFE801catches via dataflow,SAFE903catches at the input boundary.SAFE904 spring_async_checked_exception(warning):@Asyncmethod declares athrowsclause. Spring runs@Asyncon a separate thread and silently swallows exceptions; the caller never sees them, regardless of throws-clause declarations. Fix: catch inside the body and either swallow with logging or returnCompletableFuture.failedFuture(...).[java]PEP 621 extra inpyproject.toml, pullstree-sitter-java>=0.23.0. Folded into[all]alongside[python]/[javascript]/[typescript].pip install 'safelint[java]'is the typical Java-only invocation during the RC (drop--preand the pin once v2.1.0 GA ships); polyglot Python + Java monorepos compose extras via'safelint[python,java]==2.1.0rc1'.- Bundled skill addendum at
src/safelint/skill_files/languages/java.md(~250 lines) shipped in the wheel so every AI client (Claude Code, Cursor, GitHub Copilot, Gemini, Windsurf, codex, Continue.dev, Cline, aider, Trae, Antigravity, Zed) consults Java-specific guidance on demand viasafelint skill path. Covers install nuance, framework presets, per-rule notes for all 20 applicable rules, deliberately-skipped rules with rationale, idiomatic Java + Spring fix patterns, and integration-with-existing-tooling guidance. - mkdocs site page at
docs/languages/java.mdmirroring the skill addendum for the user-facing site. Wired into the Languages nav between TypeScript and Configuration; the landing page (docs/index.md) gains a Java row in the supported-languages table. - Pre-commit
types_orextended to[python, javascript, ts, tsx, java]in.pre-commit-hooks.yamlso the published hook automatically routes.javafiles to the engine without users needing to override the filter. The dedicated Pre-commit docs page (docs/pre-commit.md) and the root README gain the['safelint[java]']additional_dependenciesvariant.
Changed#
- Internal helper refactors to keep the engine surface clean as the per-language tables grew:
safelint.languages._node_utils.call_nameswitched to a per-call-node-type dispatch table (_CALL_NAME_DISPATCH) so adding Java'smethod_invocationandobject_creation_expressiondidn't push the function-return-count past SAFE104's limit. The public API is unchanged.CALL_TYPESin_node_utilsnow includes Java's two call shapes so cross-language rules walkingnode.type in CALL_TYPESautomatically catch Java method invocations andnew Foo()constructor calls without per-rule edits.- Per-rule drift-detection allow-list in
tests/core/test_engine.pyrestructured. A new_RULES_JAVA_ONLYbucket joins_RULES_WIDENED_FOR_JS_FAMILY/_RULES_WIDENED_FOR_JS_FAMILY_AND_JAVA/_RULES_JS_FAMILY_ONLY. The fourSAFE9xxrules live in the Java-only bucket; the previously-cross-language rules ported in this release graduated into the_AND_JAVAbucket as each port landed. Contributors adding a new per-language rule are pointed at the four buckets in the assertion error message. - Coverage threshold held at 97 in
pyproject.toml(unchanged from v2.0.0). The Java port temporarily dipped coverage to 95.84% during scaffolding; the defensive AST-guard branches that valid tree-sitter-java grammar doesn't reach were either pragma-annotated (# pragma: no coverwith a one-line rationale) or covered by targeted tests intests/analysis/test_dataflow_java.py(cast-unwrap / scoped-type / lambda-capture paths). End-to-end coverage of the cross-language Java rule branches is exercised through the integration suite (tests/integration/test_spring_boot_e2e.py) plus per-rule Java unit tests (tests/rules/test_resource_lifecycle_java.py,tests/rules/test_max_arguments_java.py,tests/rules/test_spring_rules.py). Final coverage: 97.01%.
Known limitations#
SAFE302 global_mutationis deliberately NOT registered for Java. Python'sglobalkeyword and JS'sglobalThis.x = ...patterns have no clean Java analogue. The natural Java equivalent (writes to non-final static fields from outside the declaring class's own static initialiser) needs class-scope analysis the rule doesn't yet do. Deferred to a future release pending user feedback.SAFE304 side_effectsdoes NOT exempt@Beanfactory methods under thespring-bootpreset. Spring@Beanfactory methods that legitimately create side-effectful resources (DB connections, HTTP clients) trigger the warning today. Suppress with// nosafe: SAFE304on each factory method until a futureskip_functions_annotated_withconfig knob lands. The preset's docstring spells this out explicitly so the limitation is auditable.- Java 21+ string templates are treated conservatively as untainted by the dataflow tracker. tree-sitter-java does not yet expose the template-substitution shape uniformly, so a
STR."Hello \{name}"form won't propagate taint through the template. A future grammar upgrade can lift this without re-architecting the rule.
Upgrading from v2.0.0#
For Python / JavaScript / TypeScript users, no action needed - v2.1.0rc1 is fully backward-compatible. The new [java] extra is opt-in, the Java rules are Java-only (no false positives on existing files), and the framework preset is gated on an explicit [tool.safelint.java] framework = "..." selector that defaults to vanilla.
For Java adopters, the minimal config is:
# safelint.toml (standalone) - no [tool.safelint] wrapper
[java]
framework = "spring-boot" # if you're using Spring Boot; omit for vanilla Java
[rules.tainted_sink]
enabled = true # dataflow rules are opt-in; flip on for security checks
[rules.test_existence]
test_dirs = ["src/test/java"] # Maven / Gradle convention
See docs/languages/java.md for the full per-rule reference and idiomatic fix patterns.
2.0.0 - 2026-05-15#
v2.0.0 GA. The release candidate cycle (rc1 / rc2 / rc3) is closed. RC validation surfaced no blocking issues, so the engine and rule behaviour of v2.0.0 is identical to v2.0.0rc3: every rule check, every Tree-sitter walk, every config-resolution path, every CLI flag, every JSON / SARIF emission produces byte-identical output for byte-identical input. The GA bump also folds in one deliberate skill-install refactor so the bundled-skill layout and the Claude install shape land symmetric with every peer client before 2.0.0 freezes that surface for the rest of the 2.x line, the change is internal to the install machinery (CLI surface unchanged; existing v1.x Claude installs continue to report fresh on safelint skill status because the destination SKILL.md path and its bytes both match). The release-time changes are:
pyproject.tomlversionbumped from2.0.0rc3to2.0.0.- The RC-pin comment block in
[project.optional-dependencies]removed;pip install 'safelint[<lang>]'now resolves to2.0.0straight from PyPI with no pin or--preflag needed. - Pre-release callouts removed from every install surface:
README.md,docs/index.md, the threedocs/languages/*.mdpages, the wheel-bundledsrc/safelint/skill_files/README.md, all 12 AI-client skill files (undersrc/safelint/skill_files/<client>/), and the three skill language addendums. - Install pins updated:
'safelint[<lang>]==2.0.0rc3'to bare'safelint[<lang>]'; pre-commitrev: v2.0.0rc3torev: v2.0.0. uv.lockregenerated.- Bundled skill-files layout symmetry. Claude Code's
SKILL.mdmoved from the top ofsrc/safelint/skill_files/into its own subdirectory atsrc/safelint/skill_files/claude/SKILL.md, joining the per-client siblings (cursor/,copilot/,gemini/,windsurf/,codex/,continue/,cline/,aider/,trae/,antigravity/,zed/). Every client now ships exactly one bundled file underskill_files/<client>/; the sharedlanguages/<lang>.mdaddendums andREADME.mdstay at the bundle root and are looked up on demand viasafelint skill pathfrom every client (Claude included). - Claude install destination simplified to a single file.
safelint skill install --client claudepreviously copied a directory tree (SKILL.md+languages/+README.md) to~/.claude/skills/safelint/; it now copies a single file to~/.claude/skills/safelint/SKILL.md, matching the one-file-in, one-file-out shape every other client already used. The CLI surface is unchanged (same--client claude, same--symlink/--force/--projectflags, sameupdate/remove/statussemantics). Internal Claude-special-case code paths (_install_symlink_directory_filtered,_is_symlink_managed_directory, the tree-hash freshness check,_PEER_CLIENT_DIRS) are gone, the install primitives become single-file across the board. Upgrading from a v1.x Claude install: the destination still hasSKILL.mdat the same path, sosafelint skill statusreports fresh as long as content matches; only the orphanlanguages/andREADME.mdnext to it stay behind on disk. Cleanest cleanup issafelint skill remove --client claude && safelint skill install --client claude, but it's optional, the orphans are harmless.
Cumulative scope since v1.13.0 (the last 1.x release): every supported language ships as an opt-in PEP 621 extra ([python] / [javascript] / [typescript] / [all]); TypeScript / TSX / AssemblyScript are first-class; the silent-failure guard exits with code 2 when a run lints zero files because of a missing grammar; hook mode emits one summary per pre-commit invocation rather than one per batch (see issue #52); skill files cover twelve AI clients; the writing-style baseline drops em-dashes from documentation, mkdocs, skills, code, and CLI output (one rule message text changed as documented in the rc3 entry below).
Upgrading from v1.x: see the Migration from v1.13.0 table in the 2.0.0rc1 entry below; the install-command swap from bare safelint to safelint[<lang>] is the only required change for most users.
Upgrading from a v2.0.0 RC: drop any ==2.0.0rcN pin or --pre flag; pip install -U 'safelint[<lang>]' is sufficient. Pre-commit users should bump their rev: pin to v2.0.0.
2.0.0rc3 - 2026-05-14#
Iteration on the v2.0.0 RC. Bug fixes and a project-wide writing-style cleanup found during testing of 2.0.0rc2. No feature changes; same packaging story, same extras, same rule coverage. Install with pip install 'safelint[<lang>]==2.0.0rc3' (or pass --pre); pre-commit users update rev: v2.0.0rc2 to rev: v2.0.0rc3.
Fixed#
- Issue #50: hook-mode summary line duplicated under pre-commit batching. A clean run with
# nosafesuppressions printedAll checks passed. (N suppressed); pre-commit batches files across multiple hook invocations, so that became one summary line per batch, each showing a misleading partial count. Hook and stdin mode now honoursilent_on_cleanfully: a clean run emits nothing at all, including the--statisticstable. The aggregated, language-agnostic suppression breakdown stays available viasafelint check(interactive) and in every--format json/--format sarifdocument. - Hook mode emitted two messages per invocation in the silent-failure case. When every passed file was skipped for a missing grammar, each batch printed both a per-extension warning and the silent-failure error, both carrying the same install hint.
_dispatch_hook_modenow detects the silent-failure case before emitting per-extension warnings: all-skipped runs get only the error; mixed runs still get the warning as context. - Issue #52: suppression summary scattered per file batch under pre-commit. Pre-commit ran the hook in parallel batches across files, so a
pre-commit run safelint --all-filesover a project with# nosafesuppressions produced one "Found N errors ... (M SAFE### suppressed)" summary block per batch, each carrying a partial count, with some batches missing the suppression mention entirely. Addedrequire_serial: trueto the published hook manifest in.pre-commit-hooks.yamlso pre-commit runs the hook as a single process and the summary aggregates across the whole run. On very large repos that exceed the OS argv limit pre-commit may still split into sequential invocations, but each batch's summary is then at least internally consistent. Downstream change of default: anyone consuming the publishedrepo: https://github.com/shelkesays/safelinthook will now see serialized execution (no parallel batches). Cost: no inter-batch parallelism, which is a non-issue in practice because the engine is fast per-file.
Changed#
- Project-wide writing-style cleanup: em-dashes removed. Em-dashes (
—) are gone from documentation, the mkdocs site, AI-client skill files, code comments, docstrings, and CLI output strings. Prose was restructured (comma, colon, parentheses, or a sentence split); a plain hyphen is used only where a dash is genuinely needed. Heads-up for downstream tooling that string-matches safelint output: two surfaces saw character-level changes and patterns may need updating. (1) CLI runtime strings (error / warning / install-hint lines from_diagnostics, the per-file summary line, the suggestions-available tail), and (2) one rule violation message:SAFE305 wide_scope_declarationnow reads"`var` declaration uses function-scope hoisting - replace with `let` or `const` for block scope"(previously the same text with an em-dash before "replace"). No other rule message strings changed.
2.0.0rc2 - 2026-05-13#
Iteration on the v2.0.0 RC, bug fixes and UX polish discovered during real-world testing of 2.0.0rc1. No feature changes; same packaging story, same extras, same rule coverage. Install with pip install 'safelint[<lang>]==2.0.0rc2' (or pass --pre); pre-commit users update rev: v2.0.0rc1 → rev: v2.0.0rc2.
Fixed#
- Pre-commit silent-failure noise. Hook mode emitted both a per-extension warning AND the silent-failure error per invocation, each carrying the same install hint. Pre-commit batches files across N invocations (one per ~120 KB of argv to stay under OS limits), so an
--all-filesrun against a large repo with a missing grammar produced 2 × N near-identical lines of stderr. The error already carries the actionable install hint, so the preceding warning is pure duplication in the silent-failure case._dispatch_hook_modenow detects the silent-failure case before emitting per-extension warnings, mixed runs (some files lint, others skipped) still get the warning as actionable context; all-skipped runs get only the error. Halves the noise per invocation. Note: the published hook now setsrequire_serial: trueby default (see issue #52 in the 2.0.0rc3 entry above), so multi-invocation runs are uncommon to begin with. _emit_hook_grammar_warningsnow respects--format. Hook mode unconditionally emitted per-extension stderr warnings even undersafelint --format json <files>. Editor plugins / CI driving safelint in hook mode and parsing JSON now get clean stderr. Symmetric with the directory-walk variant's existingsilentkwarg gating.- Missing-grammar pre-scan now honours user
exclude_paths/extend_exclude_paths. Previously the pre-scan ran before config load, so an excludedgenerated/**directory full of.tsfiles would either spuriously warn or (worse) trip the silent-failure guard into exit 2, for files safelint would never have linted anyway. Config is now loaded first and the resolved exclude list is threaded through_emit_missing_grammar_warnings/_scan_for_unavailable_extensions, mirroring the engine's_is_excluded/_is_excluded_dirsemantics. _filter_modified_under_targetno longer keeps deleted paths.git diff --name-only HEADreports deleted files; the helper was leaving them inconsidered_modified, so a setup like "deleted the only.tsfile insrc/python/, TS grammar unavailable" would trip exit 2 telling the user to install the TS grammar for a file they had just deleted. Mirrors the existence check_filter_supported_filesalready had.- Single-file unsupported runs now correctly exit 2.
safelint check foo.tswith the TS grammar missing returned[LintResult(path="foo.ts")], a 1-element list whose lone entry was an empty placeholder produced at language-lookup time. The silent-failure guard only fired whennot results, so the truthy 1-element list bypassed it and the run exited 0 with a "clean" verdict on a file safelint never actually linted. The guard now treats any result whose path-suffix is inunavailable_foundas skipped. _handle_no_targetsno longer over-fires on off-target diffs. The third tuple element of_get_git_modified_supported_fileswas the repo-wide raw git-modified set, sosafelint check src/python/would exit 2 because a.tsfile modified elsewhere in the repo had an unavailable grammar. Renamed toconsidered_modifiedand filtered to under-target via new_filter_modified_under_targethelper.- Dataflow string-list config typos now raise instead of silently matching per-character.
sinks_typescript = "eval"(note: bare string, not a list) was being coerced into{'e', 'v', 'a', 'l'}byfrozenset(...)and the rule silently stopped matchingeval. The three JS-family sites indataflow.py(sinks/sanitizers/sources,flagged_calls,nullable_methods) now route through the establishedresolve_lang_config_lookup+_validated_string_listpattern that names the offending key in theTypeError.
Changed#
- JSON schema docs path correction across skill files. The 11 per-client AI-client skill files plus the wheel-bundled
src/safelint/skill_files/README.mdreferenceddocs/JSON_SCHEMA.md; the file was renamed todocs/json-schema.mdfor the mkdocs site. URLs were 404s on GitHub. Now consistent. SKILL.md/skill_files/README.mdcross-doc links flipped from../../<doc>.md(which resolved tosrc/<doc>.md, wrong by one parent) to absolute GitHub URLs. Works in both source view AND wheel-installed locations (~/.claude/skills/safelint/).- CI gains a
safelint check src/ --all-files --fail-on=errorstep so a push that bypasses pre-commit can't merge with safelint violations. Matches the local pre-commit hook's args. - docs.yml triggers on
src/safelint/rules/**so rule add/rename/remove now redeploys the docs site automatically (the rules-at-a-glance snippet is generated fromALL_RULES). - CI matrix extends to Python 3.14 alongside 3.11 / 3.12 / 3.13, exercising the implicit support claim from
requires-python = ">=3.11". WideScopeDeclarationRuledocstring corrected to describe the rule as JS-family (JavaScript and TypeScript), matching the actuallanguage = ("javascript", "typescript")class attribute.- AssemblyScript pre-commit override recipe updated across
README.md,docs/languages/typescript.md, and.pre-commit-hooks.yaml, the originaltypes_or: []form silently never fired because pre-commit treats an empty tag list as "no tag matches" rather than "filter disabled". The working form istypes_or: [text]plusfiles: \.(ts|tsx|as)$.
Internal#
- Python grammar registration in
safelint.languages.__init__collapsed into a singleif/elseblock mirroring the JS / TS shape, reducing future-drift risk when adding a new language. - 12 new regression tests across
tests/test_cli.py,tests/test_main_routing.py, andtests/rules/test_dataflow_javascript.pycovering each of the bug fixes above. Total now 980 tests at 97.20% coverage.
2.0.0rc1 - 2026-05-12#
v2.0.0 ships TypeScript / AssemblyScript support and restructures packaging so every grammar is an opt-in extra. The TypeScript work that was prepped as 1.14.0rc1 ships here instead, bundled with the packaging change because both shift the install story. Net behaviour: pip install safelint alone installs only the engine, every language grammar (including Python) ships as a separate extra. Users opt in to whichever languages their project actually contains: pip install 'safelint[python]', pip install 'safelint[javascript]', pip install 'safelint[typescript]', pip install 'safelint[python,javascript]' for a monorepo, pip install 'safelint[all]' for the kitchen sink. Files whose grammar isn't installed are skipped at lint time with a one-line stderr install hint, no hard error as long as at least one other file gets linted. When every candidate file gets skipped (the typical TS-only or JS-only project against a base install), the silent-failure guard exits with code 2 so CI / pre-commit can't silently report clean.
This is a packaging-breaking release. Every v1.x user must update their install command, including Python-only users, who now need pip install 'safelint[python]'. The motivation: as v2.0.0 adds TypeScript and future versions add Go / Rust / Java / C / C++ / PHP, baking any one language into the core install means every project pays for languages it doesn't use. The symmetric opt-in model scales: each new language adds an extra and folds into [all]; the base install never grows.
The TypeScript / AssemblyScript work, originally drafted as v1.14.0rc1, never released to PyPI, folds into this entry below. Same rule coverage (18 rules on TS, 17 cross-language + 1 JS-family for var), same per-language config inheritance (_typescript keys with TS → JS fallback), same TS-specific rule handling for generics, as casts, non-null assertions, and declare global. Install with pip install 'safelint[typescript]'==2.0.0rc1 --pre.
Release candidate for v2.0.0, published as an RC so the packaging change can be validated against real-world install / pre-commit flows before promoting to stable. Same promotion path as 1.13.0: if real-world testing surfaces issues, fixes land in 2.0.0rc2; otherwise the RC promotes directly to GA. The --pre flag is required because pip install safelint without it keeps tracking the 1.x line.
Migration from v1.13.0#
While v2.0.0 is in RC, the "New command" column needs a pin or
--pre. Either append==2.0.0rc1(e.g.pip install 'safelint[python]==2.0.0rc1') or pass--preto any of the commands below. An unpinnedpip install 'safelint[python]'resolves to the latest 1.x release on PyPI, which doesn't define these per-language extras and would install only the engine with no grammar. Drop the pin once v2.0.0 GA ships.
| Your setup | Old command (v1.13.0) | New command (v2.0.0) |
|---|---|---|
| Python-only project | pip install safelint |
pip install 'safelint[python]' |
| JS / Node project | pip install safelint |
pip install 'safelint[javascript]' |
| TypeScript project (any flavour) | pip install safelint |
pip install 'safelint[typescript]' |
| Python + JS monorepo | pip install safelint |
pip install 'safelint[python,javascript]' |
| Anything-and-everything | pip install safelint |
pip install 'safelint[all]' |
| Pre-commit hook (any language) | additional_dependencies: [] |
additional_dependencies: ['safelint[<lang>]'] |
Forgetting to add the extra is usually a non-fatal mistake: safelint emits one stderr line per skipped file extension, e.g. safelint: warning: skipping .py files, install with: pip install 'safelint[python]', and continues with whatever files it CAN lint. If at least one file gets linted (mixed-language project, one extra installed), the run finishes normally and the skipped files surface only as warnings. If every candidate file is skipped because no matching grammar is installed, safelint fails the run with exit code 2 (the silent-failure guard, see the Silent-failure guards bullet below). That guard fires in pretty and JSON / SARIF modes, so a CI pipeline can't accidentally report green when no linting actually happened.
Added#
- Optional-grammar packaging via PEP 621 extras, new
pyproject.tomlextras:[python](addstree-sitter-python),[javascript](addstree-sitter-javascript),[typescript](addstree-sitter-javascriptandtree-sitter-typescript; the bundle handles the typical TS project shape where.jsconfigs and.tssource coexist), and[all](everything currently supported). Multiple extras compose,pip install 'safelint[python,javascript]'for monorepos. Adding a new language in the future appends one new extra and folds it into[all]; the base install never grows. safelint.languages.unavailable_extensions(), new public registry helper returning{ext: install_hint}for extensions whose grammar package isn't installed. Empty when every extra is installed. CLI uses it to surface the install hint at lint time.safelint.languages.install_hint_for(extension), convenience wrapper around the same map.- Per-grammar
GRAMMAR_INSTALL_HINTmodule-level strings onsafelint.languages.javascriptandsafelint.languages.typescript, the exactpip install ...command users should run. - CLI install-hint helpers (
_emit_missing_grammar_warnings,_emit_hook_grammar_warnings,_scan_for_unavailable_extensionsincli.py), fire one warning line per unique missing-grammar extension at the start ofsafelint check(directory walk) andsafelint <file>(hook mode). Pretty-mode only; JSON / SARIF stderr stays clean for tooling consumers. Walk excludes the usual vendored / generated dirs (.git,node_modules,.venv,.tox,__pycache__,dist,build,target,.pytest_cache,.mypy_cache,.ruff_cache,.safelint_cache) so node_modules / .venv don't trigger spurious hints. - Pre-commit-aware install hints. When safelint detects it's running under pre-commit (via the
PRE_COMMIT=1env var pre-commit sets at hook execution time), the missing-grammar hint message switches frominstall with: pip install 'safelint[python]'toadd 'safelint[python]' to additional_dependencies in your .pre-commit-config.yaml. Pre-commit users can't run pip directly because the hook environment is managed, the new hint points at the actual lever (additional_dependencies) they have. See_format_install_actionincli.py. safelint skill installnow auto-detects language grammars too. Symmetric with the existing AI-client auto-detection: after a successfulsafelint skill install, safelint walks the project tree for source-file extensions, compares them against the grammar extras currently installed, and emits one composed install line covering every missing grammar, e.g.safelint: warning: Detected source files for 2 languages (python, typescript) whose tree-sitter grammar isn't installed. Run: pip install 'safelint[python,typescript]'. Singlepip installcommand for the multi-language case. Silent (no nudge) when every needed grammar is already present. New module-level constants:EXTRA_NAMEon eachlanguages/<lang>.py; new public helpersafelint.languages.extra_name_for(ext); new CLI helpers_compose_extras_install_command,_emit_skill_install_grammar_hint.- Silent-failure guards for the two ways a missing-grammar run could exit 0 without actually linting anything:
- Directory mode (
safelint check src/), when file discovery finds files with unavailable-grammar extensions AND zero files actually get linted,safelintexits with code 2 (configuration error) and printssafelint: error: no files linted, every supported file was skipped because its grammar package isn't installed, install with: pip install 'safelint[<lang>]'. The install hint is embedded in the error itself so the failure is self-explanatory in JSON / SARIF mode (where per-extension stderr warnings are suppressed) and switches toadd 'safelint[<lang>]' to additional_dependencies in your .pre-commit-config.yamlunder pre-commit. - Hook mode (
safelint <files>invoked by pre-commit), when every file pre-commit passed had an extension whose grammar isn't installed,safelintexits with code 2 instead of 0. The error embeds the same install hint. This makes pre-commit show the hook as Failed (red) instead of Passed (green), without this guard, a pre-commit user withoutadditional_dependencieswould see a clean run while no linting actually happened, the worst kind of silent failure.
Changed (TypeScript work, originally drafted for v1.14.0rc1)#
- TypeScript (
.ts) and TSX (.tsx) as registered languages,tree-sitter-typescript>=0.23.0shipped as the[typescript]extra (not in core). Two grammars (typescriptandtsx) under one logical language name ("typescript"); both grammars share the same rule dispatch. - AssemblyScript (
.as) ride-along,.asfiles are parsed with the standard TypeScript grammar; no separate registration, zero parser-side work. AssemblyScript users get the full TypeScript rule suite via the same[typescript]extra. - TypeScript-specific rule handling for the AST shapes JS rules didn't recognise:
- SAFE103 (max_arguments), generic type parameters (
<T, U, V>) live in a separatetype_parametersAST node, NOT insideformal_parameters, so they correctly don't count toward the limit. New_TS_COUNTED_PARAM_TYPESset recognisesrequired_parameter/optional_parameter/rest_parameterwrappers. - SAFE302 (global_mutation), new
_PASSTHROUGH_WRAPPER_TYPESset extends paren-unwrapping with TS-onlyas_expression/satisfies_expression/non_null_expression.(globalThis as any).counter = 1now correctly resolves toglobalThisand fires.declare global { ... }ambient blocks correctly don't fire (no runtime assignments inside). - SAFE801 (tainted_sink),
_SPREADING_TYPESinJsTaintTrackerextends to TS pass-through wrappers; taint flows througheval(userInput as string)/eval(userInput satisfies T)/eval(userInput!). The same TS wrapper types (required_parameteretc.) are now recognised as parameter shapes, so TS function parameters get seeded into the tainted set. - SAFE803 (null_dereference), unwraps every pass-through TS wrapper (
parenthesized_expression,as_expression,satisfies_expression,non_null_expression) in a loop before checking whether the object is a nullable call.users.find()!.name,(users.find() as User).name,(users.find()).name, and(users.find() satisfies User).nameall fire correctly. - SAFE701 / SAFE702 (test_existence / test_coupling), generate TS test filename patterns (
foo.test.ts/foo.spec.ts/foo.test.tsx/foo.spec.tsx/foo.test.as/foo.spec.as). - Per-language config-key precedence with TS → JS fallback,
get_per_language_confighelper insafelint.core._validators. For TypeScript files, every_javascript-suffixed config key (sinks_javascript,tracked_functions_javascript,global_namespaces_javascript,io_functions_javascript,assertion_calls_javascript,nullable_methods_javascript,flagged_calls_javascript, plussanitizers_javascript/sources_javascript) is automatically inherited unless an explicit_typescript-suffixed key overrides it. The override door is open; most projects won't need to use it because TS and JS share the same runtime threat surface. resolve_lang_config_lookupsibling helper that also returns the actual source key the value came from, used by_validated_string_listcallers so TypeError diagnostics name the key the user actually set (was previouslyfoo_typescripteven when the bad value came fromfoo_javascriptvia TS → JS fallback).- 17 cross-language rules widened from
language = ("python", "javascript")to("python", "javascript", "typescript"). SAFE305 (wide_scope_declaration) widened from("javascript",)to("javascript", "typescript"),varis still hazardous in TypeScript. docs/languages/typescript.md, per-language nav page covering scope (TS / TSX / AS), the 18 rules that fire, TS-specific rule notes, config sharing with JS, the runtime preset story, and the new[typescript]install extra.src/safelint/skill_files/languages/typescript.md, bundled AI-client addendum with TS-specific rule notes; all 12 client skill files now reference it from their language registry table.
Breaking changes#
pip install safelintno longer bundles any tree-sitter grammar package. Every supported language is opt-in: install the matching extra(s) for the languages your project actually contains. Python is now on equal footing with JavaScript / TypeScript, including Python-only users, who must update their install command topip install 'safelint[python]'. The motivation is forward-looking: as Go / Rust / Java / C / C++ / PHP land in future versions, baking any single language into the base install means every project pays for languages it doesn't use; the symmetric opt-in model keeps the install minimal for every use case. Files whose grammar isn't installed are silently skipped with a clear install hint on stderr, see the Migration table above.
Fixed#
- SAFE803 silently bypassed by TS pass-through wrappers other than
!._javascript_deref_hitonly peelednon_null_expression;(call as Foo).bar,(call).bar, and(call satisfies Foo).barslipped past. The new loop unwraps all four pass-through wrappers, the rule now matches the taint tracker's wrapper handling. Regression tests cover bare-paren,as,satisfies, and stacked-wrapper combinations. - TypeError diagnostics named the wrong config key when the TS → JS fallback fired. A user setting
io_functions_javascript = "log"(bare string typo) on a TS file used to see aTypeErrornamingio_functions_typescript, a key they never set.resolve_lang_config_lookupthreads the actual source key through so the error message points at the key the user can fix. - SAFE303 / SAFE304 on TypeScript,
side_effects.py:_io_funcs_for_langbuilt its config key viaf"io_functions_{lang_name}", producingio_functions_typescriptfor TS files. That key wasn't inDEFAULTS(onlyio_functions_javascriptwas), so TS files silently got an empty I/O primitive list and SAFE303 / SAFE304 never fired on TypeScript. The new TS → JS config-key fallback (see Changed above) fixes this. Regression test added (test_ts_io_functions_inherits_javascript_default).
1.13.0 - 2026-05-12#
Previewed as 1.13.0rc1 (2026-05-11) and 1.13.0rc2 (2026-05-11). The RC validation window surfaced one real-world papercut, safelint check --all-files would trip over project virtualenvs at .venv/, which landed in 1.13.0rc2 (built-in vendor-dir defaults for exclude_paths, plus a new extend_exclude_paths config key for additive use). No further issues surfaced after rc2, so the GA ships with the same content. Install with pip install safelint (the --pre flag is no longer needed).
The two new rc2 entries fold in here:
Added (in the rc2 → GA window)#
- Built-in
exclude_pathsdefaults for common vendor / generated directories.safelint check(and--all-files) no longer walks into.venv/,venv/,.tox/,.nox/,__pycache__/,.pytest_cache/,.ruff_cache/,.mypy_cache/,.ty_cache/,build/,dist/,htmlcov/,node_modules/, orsite-packages/by default. Previously these were only excluded if the user listed them explicitly in their config, a--all-filesrun from a project root with a Python virtualenv at.venv/would lint thousands of third-party files. The defaults apply at the directory level (os.walkprunes descent), so the cost of having them excluded is essentially zero. - New
extend_exclude_pathsconfig key. Appends to the active exclude list rather than replacing it. Use this for project-specific excludes ("generated/**","vendor/**", etc.) when you want to keep the built-in vendor-dir defaults. Sister to the existingextend_tracked_functionspattern for SAFE401, same additive semantics, same shape.
Changed (in the rc2 → GA window)#
exclude_pathssemantics, settingexclude_pathsin your config still replaces the built-in defaults wholesale (existing semantics, backwards-compatible). Most projects should migrate toextend_exclude_pathsto keep the vendor-dir defaults active. See Default exclude paths for the migration guide.
The rest of this section describes the JavaScript support that landed in 1.13.0rc1 and is preserved unchanged in the GA.
JavaScript (Node) is now a supported language alongside Python. Registry-driven multi-language support: .js / .mjs / .cjs files are discovered, parsed via Tree-sitter, and run against 17 of the 19 existing rules, plus one new JS-only rule (SAFE305 wide_scope_declaration) for a total of 20 rules safelint now ships. Python users see no behaviour change beyond the v1.12.2 .pyw bugfix; the additive language work is what justifies this release as 1.13.0 (per the project's semver rules: scope expansion is MINOR, never MAJOR).
Added#
safelint.languages.javascript, new module registering JavaScript withLanguageDefinition(name="javascript", file_extensions=frozenset({".js", ".mjs", ".cjs"}), comment_node_type="comment", comment_prefix="//"). Plus the JS Tree-sitter node-type constants every rule needs (function/control-flow/expression/statement/pattern types).tree-sitter-javascript>=0.23.0runtime dependency. Peer of the existingtree-sitter-pythondep.safelint.analysis.dataflow_javascript, new module withJsTaintTracker, the JavaScript counterpart of the PythonTaintTracker. Same public surface; per-language node-type vocabulary internally. Handlesconst/let/vardeclarations,assignment_expression/augmented_assignment_expression, template-string interpolation (`${expr}`), destructuring (array / object / rest / pair patterns), spread elements, member / subscript propagation, and theassume_taint_preservingknob.- 17 rules now lint JavaScript with
language=("python", "javascript"): - Structural:
function_length(SAFE101),nesting_depth(SAFE102),max_arguments(SAFE103),complexity(SAFE104). - Error handling + side-effects:
empty_except(SAFE202, JS empty catch),logging_on_error(SAFE203, recognisesconsole.*and genericlogger.*plusthrow <id>;as re-raise),side_effects_hidden(SAFE303),side_effects(SAFE304). - State purity:
global_mutation(SAFE302, fires on function-body assignments toglobalThis.*/window.*/global.*/self.*/process.env.*and similar configurable namespaces; reading a global is fine; module-level assignments are exempt as legitimate setup). - Loop / tests / assertions:
unbounded_loops(SAFE501, only thewhile (true)no-break case fires on JS; the non-comparison-condition heuristic stays Python-only),missing_assertions(SAFE601, walks for calls toassert/expect/console.assert/ Node'sassert.*helpers),test_existence(SAFE701) andtest_coupling(SAFE702, pair Pythontest_<stem>.pyand JS<stem>.test.{js,mjs,cjs}/<stem>.spec.{js,mjs,cjs}). - Resource safety:
resource_lifecycle(SAFE401, fires on calls to configurable acquirer names,createReadStream,createWriteStream,openSync,createServer,connect, etc., that aren't enclosed in atry { ... } finally { ... }somewhere up the AST chain; heuristic-only, doesn't verify that the finally actually closes the resource). - Dataflow:
tainted_sink(SAFE801),return_value_ignored(SAFE802),null_dereference(SAFE803, recognises optional chainingfoo?.baras the safe form, exempt from the rule). - New JavaScript-only rule:
wide_scope_declaration(SAFE305) flags everyvardeclaration. Holzmann Power-of-Ten Rule 6 ("declare variables at the smallest possible scope") translated to JS's actual scope-control mechanism,varis function-scoped (hoisted across blocks),let/constare block-scoped (the narrower scope). Fires on top-levelvar, function-bodyvar, block-levelvar, multi-bindingvar x = 1, y = 2;(single violation per declaration node, the line is the unit of fix), andfor (var i = 0; ...). Python has novar/let/constdistinction; the rule is registered withlanguage = ("javascript",)and the engine's per-language dispatch correctly skips it on.py/.pywfiles. Default enabled, severitywarning. - JavaScript runtime presets, new
[tool.safelint.javascript] runtime = "<name>"config key selects which API surface the JS rule defaults assume. Five presets ship:node(default, current behaviour),browser(Web APIs / DOM /localStorage/ observers; drops Nodefs),deno(Deno.*APIs; dropsprocess/window),cloudflare-workers(Workers Runtime: KV / R2 / Durable Objects /Requestbody methods; minimal global-namespace list), andbun(Node-compatible plusBun.serve/Bun.spawn). Affects defaults for SAFE302 (global_namespaces_javascript), SAFE303 / SAFE304 (io_functions_javascript), SAFE401 (tracked_functions_javascript), SAFE801 (sinks_javascript/sources_javascript), SAFE802 (flagged_calls_javascript), and SAFE803 (nullable_methods_javascript). User-explicit_javascriptconfig keys still win over the preset. Unknown runtime names warn on stderr and fall back tonode. Source is the same JS regardless of runtime, only the rule defaults shift, not the parser or rule logic. - Per-language config keys (additive, existing user TOMLs unchanged):
[tool.safelint.rules.side_effects_hidden]and[...].side_effectsgetio_functions_javascript.[...].missing_assertions]getsassertion_calls_javascript.[...].tainted_sink]getssinks_javascript,sanitizers_javascript,sources_javascript.[...].return_value_ignored]getsflagged_calls_javascript.[...].null_dereference]getsnullable_methods_javascript.[...].global_mutation]getsglobal_namespaces_javascript.[...].resource_lifecycle]getstracked_functions_javascript.CALL_TYPESfrozenset andresolve_lang_namehelper insafelint.languages._node_utils, cross-language utilities used by the widened rules.- Bundled AI-client skills,
src/safelint/skill_files/languages/javascript.md(the JS shared addendum) ships a full per-rule notes table, idiomatic-fix patterns for each of the 15 ported rules, and the "rules that stay Python-only" reference. All 12 client docs (Claude Code'sSKILL.md, Cursor'scursor/safelint.mdc, GitHub Copilot'scopilot/copilot-instructions.md, Gemini'sgemini/GEMINI.md, Windsurf'swindsurf/safelint-rules.md, codex'scodex/instructions.md, Continue.dev'scontinue/safelint.md, Cline'scline/safelint.md, aider'saider/CONVENTIONS.md, Trae'strae/safelint.md, Antigravity'santigravity/safelint.md, Zed'szed/safelint.md) gained a JavaScript row in their Step 2, Identify the language(s) involved registry tables. - 115 new tests distributed across per-rule JS test files (
tests/rules/test_*_javascript.py) and the engine-level smoke test file (tests/core/test_engine_javascript.py). Total: 764 tests pass at 97.25% coverage.
Changed#
- Pre-commit hook spec (
.pre-commit-hooks.yaml) and the in-tree self-development hook (.pre-commit-config.yaml),types_or: [python]becomestypes_or: [python, javascript]. Downstream users with mixed Python + JS repos automatically have both filetypes routed to safelint after upgrade. Additionally the published.pre-commit-hooks.yamldrops itsfiles: ^src/filter, that filter was a leak from this repo's in-tree.pre-commit-config.yaml(where it's intentional, safelint lints itself only undersrc/) into the published hook spec, where it forced every downstream installer onto the same layout. Heads-up: this broadens the default scope for downstream consumers. With it gone, the hook honours onlytypes_or: [python, javascript]plus the consumer's ownfiles:/exclude:keys, so projects with sources at the repo root, inapp/, inlib/, etc. now get linted by default after upgrade. If you previously relied on the^src/default to scope safelint to one directory, add the equivalent filter to your local.pre-commit-config.yaml:
- repo: https://github.com/shelkesays/safelint
rev: <tag>
hooks:
- id: safelint
files: ^src/ # restore the previous default if needed
call_name in _node_utils.py extended to handle JavaScript member_expression (obj.method(...)) alongside Python attribute (obj.method(...)). Both foo(...) forms (bare identifier function calls) continue to resolve via the existing identifier branch.
Stays Python-only (by design)#
Two rules don't have a useful JavaScript translation and remain registered for Python only, they will not fire on .js / .mjs / .cjs files. The decision rationale lives in src/safelint/skill_files/languages/javascript.md "Rules that stay Python-only".
- SAFE201
bare_except, Pythonexcept:(no exception type) silently catchesKeyboardInterruptandSystemExit. JavaScripttry/catchalways catches every throw type by language design; the Python-specific process-signal hazard doesn't exist. SAFE202 (empty catch) + SAFE203 (catch must log) cover the related JS concerns. - SAFE301
global_state, Python rule fires on theglobalkeyword regardless of whether a write follows. JavaScript has no read-only-global declaration form; on JS the rule would always be a strict subset of SAFE302. JS users get the same protection from SAFE302 (global_mutation) alone.
Behaviour changes (heads-up)#
- JS-only projects, anyone who had
safelint checkrunning on a Python repo with stray.jsfiles: those files will now be discovered, parsed, and linted (most rules will fire). If that's not what you want, scope-suppress with[tool.safelint.per_file_ignores]keyed on the.jsglob, or setenabled = falseper rule. - Mixed Python + JS projects, both file types now flow through pre-commit and
safelint checkautomatically. The 17 widened rules apply to both languages with their per-language defaults. - Pure-Python projects, no intended default-behaviour change beyond the v1.12.2
.pywbugfix. Some Python codepaths did pick up correctness fixes during the v1.13.0 cycle (e.g. SAFE701/702 now skip test files themselves and gate the coupling check to changed paths undertest_dirs, SAFE102 now countsmatchblocks for Python 3.10+), but those only affect users who had explicitly enabled the relevant rules, defaults are unchanged.
Limitations documented for future enhancement#
- Block-style
nosafedirectives (/* nosafe */) are not recognised, only line-style// nosafeand// safelint: ignore. Documented in the JS shared addendum anddocs/contributing/adding-a-language.mdStep 4. - JSX (
.jsx) is not registered.tree-sitter-javascriptparses some JSX leniently as a superset, but flagging it as a separate language registration later avoids accidental drift in rule semantics. - TypeScript (
.ts/.tsx) is a separate language addition, not in this release. - Arrow-function naming via variable binding (
const getX = () => ...), this remains a limitation only for rules that still read function names solely viafunc_node.child_by_field_name("name")and therefore may report such functions as<anonymous>(e.g., SAFE101function_length). SAFE303 (side_effects_hidden) and SAFE304 (side_effects) already resolve JS arrow-function names through the parentvariable_declaratorvia the shared_func_display_namehelper, soconst getX = () => console.log(...)correctly reports asgetXfor those rules. Other rules can be enhanced the same way later.
1.12.2 - 2026-05-09#
Completion of the multi-language readiness work started in v1.12.1. The engine, cache, suppression parser, file discovery, and per-rule dispatch were already registry-driven, but three CLI helpers and the published pre-commit hook spec still hard-coded .py. With this release every supported-extension check reads from safelint.languages.supported_extensions(), so registering a new language is genuinely additive, drop a LanguageDefinition into languages/<lang>.py, append it to the registry loop, append the new filetype tag to types_or in .pre-commit-hooks.yaml, and the CLI discovers it everywhere automatically.
tuple(supported_extensions()) now contains .py and .pyw (the registry is a frozenset, so iteration order isn't guaranteed); types_or: [python] is identical in semantics to the previous types: [python] for downstream pre-commit users.
Fixed#
.pywfiles now picked up by git-modified mode and the pre-commit hook. The old CLI helpers usedstr.endswith(".py")for filtering, which silently dropped.pywfiles ("foo.pyw".endswith(".py")isFalse). The engine's--all-filesdiscovery loop already used the registry and handled.pywcorrectly, so this only affected git-modified runs (safelint check src/) and pre-commit hook mode. Existing.pywprojects that were getting clean runs in those modes may now see previously-hidden violations on those files; if that's unwelcome on a transitional codebase, scope-suppress with[tool.safelint.per_file_ignores]keyed on a*.pywglob.
Changed (internal: registry-driven)#
- CLI git-status filters now read from the registry.
_collect_all_py_filesand_filter_py_filesinsrc/safelint/cli.pyare renamed to_collect_all_supported_filesand_filter_supported_filesrespectively, and both now buildexts = tuple(supported_extensions())once per call to drive thestr.endswithcheck. The hook-mode pre-filter at the bottom ofmain()([f for f in args.files if f.endswith(".py")]) reads from the registry too. Sosafelintinvoked by pre-commit with mixed Python + (future) TypeScript files accepts both rather than silently dropping the non-Python ones. - Published pre-commit hook spec uses
types_or..pre-commit-hooks.yamlpreviously declaredtypes: [python]. Switched totypes_or: [python]so the add-a-language edit becomes a one-line append (- ts) instead of a schema change. Description generalised from "Python files" to "source files"; an inline comment markslanguage: pythonas the hook runtime (a real source of confusion in pre-commit configs), not the language being linted.
Changed (docs)#
docs/contributing/adding-a-language.mdgains an explicit Step 6, Update CLI / pre-commit plumbing that lists the surfaces reading from the registry vs. the one place still requiring a manual edit (thetypes_orline in.pre-commit-hooks.yaml). Old Step 6 (tests + docs) is now Step 7; old Step 7 (bundled AI-client skills) is now Step 8.
Behaviour changes (heads-up)#
.pywprojects, see Fixed above. The bugfix is genuine, but if your.pywfiles have been quietly accumulating violations because git-modified mode and the pre-commit hook were skipping them, you'll see those surface on the firstsafelint checkafter upgrade. Workaround if you need a transitional grace period: scope-suppress with[tool.safelint.per_file_ignores]keyed on**/*.pyw.- Pure-
.pyprojects, no change. The renamed CLI helpers are private (underscore-prefixed); thetypes_orchange is single-element today, so downstream pre-commit users see no difference until a second filetype tag lands.
1.12.1 - 2026-05-09#
A small follow-on to v1.12.0. One user-visible bug fix, one perf optimisation, an internal-API cleanup, and pre-emptive engine plumbing for the eventual second-language work. No behaviour change for current users beyond the bug fix.
Fixed#
per_file_ignores = ["*"]no longer triggers a spurious typo-guard warning. v1.12.0 added the"*"wildcard as a documented blanket-suppress mechanism in tomlper_file_ignores, but the validation pass in_parse_per_file_ignoresstill treated"*"as an unknown entry and emittedsafelint: warning: unknown entries in per_file_ignores...for the exact value the docs tell users to use. The validation now exempts"*"while preserving the typo guard for genuinely unknown codes/names. The pre-existing wildcard test was extended to capture stderr and assert the absence of the warning, so any future regression here surfaces in CI.
Changed (internal)#
- Single-pass directive parsing.
_parse_suppressions(line-level# nosafe) and_parse_file_level_ignores(file-level# safelint: ignore) used to walk the Tree-sitter tree independently, two full passes per file. New_parse_directiveshelper folds both into one O(N) pass; on a 5000-line generated file (a primary use case for file-level ignores), this halves the per-file walk cost. Behaviour is bit-for-bit identical to the two-pass version. The two original helpers are kept as thin wrappers so the existing unit tests intests/core/test_suppression.pycontinue to work without changes. _merge_in_file_directivessignature cleanup. The boolean parameter was forcing surrounding mandatory non-bool params into keyword-only territory unnecessarily. Reordered so only the boolean is keyword-only, matching Python convention (positional mandatory params first, then*, then keyword-only).
Added (pre-emptive: dormant until a second language lands)#
BaseRule.language: tuple[str, ...] = ("python",), new class attribute that the engine consults in_run_rulesbefore dispatchingcheck_file. Rules whoselanguagetuple doesn't include the active file'sLanguageDefinition.nameare skipped. Today every rule defaults to("python",)and Python is the only registered language, so the filter is a no-op for current usage. The plumbing is the engine half of the per-language dispatch contract documented inADDING_A_LANGUAGE.md; the per-rule audit (which existing rules port cross-language vs. stay Python-only) is per-rule work that ships with each new language. Adding TypeScript / Go / Rust now requires only registering a newLanguageDefinitionand wideninglanguageon the rules that port, no engine changes.- 4 new dispatch tests in
tests/core/test_engine.py: filter skips Python-only rules on a hypothetical-language file (via a monkeypatched fakeLanguageDefinition), filter doesn't accidentally skip Python rules on Python files (regression guard),BaseRule.languagedefault is pinned, every registered rule still inherits the default.
Behaviour changes (heads-up)#
- None for end-users. The
"*"typo-guard fix removes an erroneous warning; the perf and signature-cleanup work is invisible; the dispatch infrastructure is dormant. End-to-end behaviour forsafelint checkandsafelint skill *commands is identical to v1.12.0.
1.12.0 - 2026-05-08#
A focused feature release on top of v1.11.0. The suppression model grows from three layers to four with a new in-file # safelint: ignore directive that lets users silence rules for a whole file from inside the file itself, matching the established pattern from ruff (# ruff: noqa), flake8 (# flake8: noqa), pylint (# pylint: disable=), and mypy (# type: ignore).
Added#
-
In-file
# safelint: ignoredirective, file-scope suppression placed as a top-of-file (or anywhere alone-on-its-line) comment. Three forms:Best for the case "this whole file is intentionally violating", auto-generated code, fixtures, vendor adapters, where toml's# safelint: ignore # suppress every rule for this file # safelint: ignore: SAFE101 # suppress one code # safelint: ignore: SAFE101, SAFE304 # suppress multiple # safelint: ignore: function_length # by rule name (equivalent to the code form)per_file_ignoresis overkill (no glob pattern needed) and inline# nosafeis wrong (the violation isn't on a single line). -
Tree-sitter parsed, so
# safelint: ignoreliterals inside docstrings or string content are correctly ignored. - Comment must be alone on its line. Trailing comments after code are skipped, those are scope-local and use
# nosafeinstead. This prevents a per-line directive that's typed with the wrong prefix from silently extending to the whole file. - Typo-guarded. Unknown codes / rule names emit a
safelint: warning:line on stderr (matching the toml typo guard); the run continues. -
Auditable. Suppressed violations still land in
LintResult.suppressedand surface in the CLI's per-code breakdown at the end of a run. -
"*"wildcard support inper_file_ignores, falls out of the same machinery the bare file-level directive uses. You can now write[tool.safelint.per_file_ignores]with"some/path/**" = ["*"]to skip every rule for a path pattern, instead of having to enumerate every code.
Changed#
- Suppression model is now four layers, narrowest to widest. They compose, a violation is suppressed if any layer matches:
# nosafe(line scope), same as before.# safelint: ignore(file scope), new in 1.12.0.per_file_ignores(glob scope), same as before, plus"*"wildcard support.ignore(project scope), same as before.
Documentation#
- CONFIGURATION.md, new File-level suppression section with form table, placement rule, typo-guard behaviour, and a four-mechanism comparison table mapping each scope to its right use case.
- CLAUDE.md, Suppression model section updated from 3 layers to 4 with implementation pointers (
_parse_file_level_ignores,_merge_in_file_directives,_is_per_file_ignored's wildcard short-circuit).
Behaviour changes (heads-up)#
- None for existing files. Files without a
# safelint: ignoredirective behave identically to v1.11.0, the new code path is purely additive. The only observable difference is the new wildcard"*"interpretation inper_file_ignores; if any user was previously writing literal"*"as a rule code (would have been a no-op since no rule matches), they'll now find that entry blanket-suppresses every rule. We're not aware of any such usage in the wild.
1.11.0 - 2026-05-08#
Multi-client expansion, the AI-client skill registry grows from 2 supported clients to 12. The architecture from v1.6.0–v1.10.0 was built for this; each new client is one ClientSpec append plus a bundled artefact (and 10 install/lifecycle regression tests). Top-level safelint help gains dedicated Skill subcommands and Skill flags sections so the install / update / remove / status / path surface is discoverable without a second safelint help skill round-trip.
Added#
- Ten new AI-client integrations: GitHub Copilot, Gemini, Windsurf, codex, Continue.dev, Cline, aider, Trae, Antigravity, Zed. Every client follows the same install / update / remove / status / path surface and the same project-vs-user-scope semantics, with auto-detection wired into the existing
--client autoflow. Per-client install destinations: - GitHub Copilot,
.github/copilot-instructions.md(auto-loaded by VS Code Copilot Chat) - Gemini,
GEMINI.mdat repo root (auto-discovered by Gemini CLI) - Windsurf,
.windsurfrulesat repo root - codex,
.codex/instructions.md(primary) plus a delimited section inAGENTS.mdwhen that file exists (preserves user content; see Secondary install below) - Continue.dev,
.continue/rules/safelint.md - Cline,
.clinerules/safelint.md - aider,
CONVENTIONS.md(project or user); requires a one-lineread: [CONVENTIONS.md]entry in.aider.conf.ymlsince aider doesn't auto-load conventions files. The post-install message reminds users. - Trae,
.trae/rules/safelint.md - Antigravity,
.antigravity/rules/safelint.md - Zed,
.rulesat repo root ClientSpecsecondary-install architecture. New optional fieldssecondary_install_relpathandsecondary_install_section_markerslet a client write a delimited HTML-comment section into a shared cross-agent file (e.g.AGENTS.md) when that file already exists at the scope root. Used by codex; the architecture generalises to any future cross-agent shared file. Lifecycle parity: install writes the section, update re-renders on drift, status escalates to DIFFERS when section content drifts (even if the primary install is fresh), remove strips just the section (preserving other content; deletes the file only if it becomes empty after stripping). Section-based edits are always the contract for the secondary destination, never a full-file overwrite, so user content in shared files is safe.- Top-level
safelint helpgains Skill subcommands and Skill flags sections. All five lifecycle actions (install,update,remove,status,path) and the common flags (--client,--project,--symlink,--force, plus--pathand--dry-runforremove) are now visible at the top level, no secondsafelint help skillround-trip needed to find--forceetc.--forceis intentionally placed under Skill flags (not Global options) since it doesn't apply tocheck. run_updateperformance: hash/walk runs at most once per install per run. Previouslyrun_updateand_update_oneeach invoked_install_statusindependently per target, doubling the directory walk and content hash for Claude installs (the most file-heavy bundle)._update_onenow accepts an optionalstatusparameter;run_updatethreads its precomputed value through. Direct callers and tests are unaffected (defaultNonemeans "compute internally").run_updateno longer falsely prints "all up to date" when every target was OSError-skipped. Newany_processedflag gates_print_update_all_freshon at least one target having a readable status. Without the gate, an all-permission-denied run would silently report success.
Changed#
io_functionsin the bundledsafelint.toml([rules.side_effects_hidden]), removed the unmatchable"subprocess"entry (the rule walks bare callable names,subprocess.run(...)resolves to"run") and replaced it with the actual subprocess callable names (run,Popen,call,check_call,check_output).- Documentation fan-out for the multi-client expansion:
AI_CLIENTS.md(Supported clients table + Per-client guides + manual install examples),src/safelint/skill_files/README.md(clients list + layout tree + manual install examples),README.md(top-level integration block), andADDING_AN_AI_CLIENT.mdall enumerate the 12 supported clients. The Roadmap section inAI_CLIENTS.mdwas retired since the previously listed candidates (Copilot, codex, windsurf, antigravity) all shipped. - Test coverage threshold remains 97%; current coverage 97.24% across 628 tests. The 10 new client integrations add 100+ install/symlink/force/overwrite/auto-detect/CLI-routing/path-print/peer-exclusion tests plus 24 codex-specific tests for the secondary-install lifecycle and section helpers.
Behaviour changes (heads-up)#
safelint helpoutput changed shape, Skill subcommands and Skill flags sections now appear between Commands and Options. Existing users see a longer (more discoverable) help; no commands or flags removed.- Auto-detection now scans for 12 client markers, not 2. A project with markers for several clients gets installs for all of them in registry order. To install for a single client, pass
--client <name>explicitly. - codex's secondary install touches
AGENTS.mdwhen present. If you have an existingAGENTS.mdwith content for other agents,safelint skill install --client codex --projectwill append a delimited safelint section to it (your other content is preserved). The section sits between<!-- safelint:begin -->and<!-- safelint:end -->markers;safelint skill remove --client codexstrips it cleanly. If you don't want any AGENTS.md modification, install codex without--projectso it lands at user-scope only, or remove the AGENTS.md file before installing.
Security hardening#
safelint skill remove --path PATHnow validates that PATH's tail matches a registered install relpath before deleting. Without this guard, a typo or shell-expansion accident (--path ~/.configinstead of~/.cursor/..., or an unset env-var that expanded to a sensitive path) could triggershutil.rmtreeon the wrong directory. The check accepts every registered client's canonical install path (.cursor/rules/safelint.mdc,.codex/instructions.md,.continue/rules/safelint.md,.clinerules/safelint.md,.trae/rules/safelint.md,.antigravity/rules/safelint.md,.windsurfrules,GEMINI.md,.rules,CONVENTIONS.md,.claude/skills/safelint,.github/copilot-instructions.md) regardless of where the parent directories sit. Truly unrecognisable install locations should be removed manually withrmafter inspecting their contents.- codex secondary install (
AGENTS.md) refuses to follow symlinks. Without this guard, anAGENTS.mdset up as a symlink, intentionally by the user, or maliciously by an attacker with write access to the install scope (e.g. shared CI workspace), would have causedinstall/update/removeto read and write through the symlink, potentially corrupting any user-writable file the link pointed at (e.g.~/.ssh/authorized_keys, system files when running as root). All three lifecycle paths (_install_secondary,_remove_secondary,_secondary_status) now checktarget.is_symlink()and refuse with asafelint: warning: refusing to install/remove safelint section through symlink at ...line on stderr. The primary.codex/instructions.mdinstall is unaffected.
1.10.0 - 2026-05-06#
Round-out release for the skill-install lifecycle: update and remove complete the install / status / update / remove quartet so users have a full set of maintenance commands without falling back to manual rm / re-install cycles.
Added#
safelint skill update, refresh installed skills whose content has drifted from the bundled wheel. Idempotent by default (no-op when fresh), with--forceto re-install regardless of drift status (useful for reverting customised installs back to bundled). Inherits--client/--project/--symlink/--forcefrom install.--client autohere resolves via existing install paths, NOT marker files like install does, "what's installed?" vs "what client is the user using?" are separate questions.safelint skill remove, delete detected installs. Inherits--client/--projectfrom install, plus three remove-specific flags:--symlink, filter to symlink-shape installs only, leaving copy-mode installs intact ("delete only my symlink installs").--path PATH, remove one specific location, bypassing every other flag (useful for unusual / forgotten install locations).--dry-run, preview what would be removed without deleting anything.- Shared install-path auto-detection between
updateandremovevia new_detected_installed_clients(*, only_symlink)helper. Distinct from install's_detected_clients(directory, marker_attr)(marker-file scan).
1.9.0 - 2026-05-05#
A focused follow-on to v1.8.0 covering one practical question users asked: how do I know my installed AI-client skill is up to date after pip install --upgrade safelint? Two new surfaces answer it. Also lands a build-time drift-detection test pair that prevents bundled-doc rot for every registered AI client (and every future one, the tests parametrise over the registry).
Added#
safelint skill status, new subcommand that compares every detected installed AI-client skill (Claude Code at~/.claude/skills/safelint/, Cursor at~/.cursor/rules/safelint.mdc, project-scoped equivalents) against the bundled artefact in the active wheel. Reports per-location fresh / differs from bundled, exit 0 when every detected install matches, exit 1 when any differs. Pipe-friendly:safelint skill status || safelint skill install --forceis the canonical "refresh after upgrade" idiom. Symlink installs always report fresh by construction. Documented inAI_CLIENTS.md"Updating after a safelint upgrade" → "Checking whether your installed skill is current".safelint check --check-skill-freshness, opt-in flag that folds the same drift check into a normal lint run. Stale installs surface assafelint: warning: …lines on stderr through the diagnostics channel. Informational only, doesn't fail the lint. Off by default so day-to-daysafelint checkinvocations stay fast (no extra FS scan).ClientSpec.documentation_relpaths+ parametrised drift-detection tests. Each registered AI client declares which files underskill_files/collectively must mention every rule code/name inALL_RULESand every extension insupported_extensions(). Two parametrised tests (test_skill_documents_every_active_rule[<client>],test_skill_documents_every_supported_extension[<client>]) fail CI the moment a contributor adds a rule or language without updating each registered client's bundled docs. New clients added to_CLIENT_SPECSautomatically inherit both checks.- Bundled skill crib-sheets (
SKILL.md,cursor/safelint.mdc) backfilled with the eight rules previously absent from their rationale tables: SAFE203, SAFE401, SAFE601, SAFE701, SAFE702, SAFE801, SAFE802, SAFE803. The drift test now passes at 100% rule coverage.
Changed#
- Top-level
safelint --help"Commands" entry forskillnow listsstatusalongsideinstallandpath. Same change in theCONFIGURATION.mdembedded help example. - Documentation fan-out: the new commands and
--check-skill-freshnessflag are now mentioned in the top-levelREADME.md, the bundled-in-wheelsrc/safelint/skill_files/README.md, and theCONFIGURATION.mdsafelint checkflag table, not only inAI_CLIENTS.md.
1.8.0 - 2026-05-04#
This release bundles three internal milestones (originally tracked as 1.8.0 / 1.9.0 / 1.10.0 during development; only 1.7.0 was published to PyPI) into a single user-visible release. It closes the most-asked-about gaps versus ruff, incremental config, unused-suppression detection, per-rule statistics, broader resource-lifecycle coverage, smarter empty-except detection, configurable global-mutation strictness, configurable function-size counting, and tightens the SAFE801 (tainted_sink) dataflow analysis and introduces advisory suggestions on JSON / SARIF outputs alongside a ruff-style top-level CLI surface. SafeLint stays review-only, there is no --fix flag now or planned.
Added#
Configuration ergonomics#
extend_ignore/extend_per_file_ignoresconfig keys, grow the corresponding default lists instead of replacing them. Mirrors ruff'sextend-selectergonomics. Both are folded into the canonicalignore/per_file_ignoreskeys at config-load time and stripped from the resolved dict, so downstream consumers (engine, runner) only see the merged lists. Order-preserving dedupe means duplicates between the base and the extension collapse to a single entry.extend_tracked_functionsconfig key on theresource_lifecyclerule, appends to the (now-richer) default list instead of replacing it.strictconfig flag on theglobal_mutationrule,strict = truefires on anyglobaldeclaration even without a write, mirroring ruff'sPLW0603. Defaultstrict = falsekeeps the original Holzmann-aligned behaviour (only flag actual mutations). Useful for teams whose policy is to ban theglobalkeyword entirely.count_modeconfig option on thefunction_lengthrule, three counting strategies:"lines"(default), inclusive source-line span. Original behaviour."logical_lines", source lines minus blanks and pure-comment lines. Less game-able than the raw-lines metric."statements", count Python statement nodes. Equivalent to ruff'sPLR0915; fully formatting-independent. Skips nested function bodies so an inner helper doesn't inflate its outer's count.assume_taint_preservingconfig option on thetainted_sinkrule, controls how unknown function calls (those whose name is in neithersourcesnorsanitizers) propagate taint.true(default, preserves the historical behaviour) means an unknown call's result is tainted iff any argument is tainted.falsemeans unknown calls always drop taint, giving a less conservative analysis with fewer false positives but new false negatives where an internal helper does flow tainted data through to a sink. Set tofalsewhen your codebase has many "obviously safe" wrappers and you'd rather miss a flow than report a false positive.
New rules and detection improvements#
SAFE004(unused_suppression), emits a warning for any inline# nosafedirective that didn't actually suppress anything. Catches stale annotations after refactors. The engine tracks per-(line, code) usage during the rule run; unused entries are reported afterward. Globally disable viaignore = ["SAFE004"]if your workflow generates many transient suppressions. Self-referential directives (both# nosafe: SAFE004and# nosafe: unused_suppression, case-insensitive on the code form) are special-cased to avoid recursion.- Broader default tracked functions for SAFE401, covers
socket,mmap,Lock/RLock/Semaphore,Pool/ThreadPoolExecutor/ProcessPoolExecutor,TemporaryFile/NamedTemporaryFile/TemporaryDirectory,ZipFile/TarFile, plusSession(PEP-8-cased) alongside the existingopen/connect/session. Extended cleanup-pattern list addsreleaseandshutdown. Closes the most common ruff-vs-safelint coverage gap on real codebases. SAFE202now catches the canonicalexcept: passand other no-op idioms, previously the rule's check was so narrow it effectively never fired on real code (only on the malformed-AST case). Now flagspass/continue/.../ single-literal expression bodies (0,None,True,False, string-as-comment"TODO"/""etc.) when they're the entire body of an except clause. Multi-statement bodies are still allowed (solog_message; passdoesn't trip).- Splatted-arg taint propagation,
foo(*tainted_list)andfoo(**tainted_dict)now correctly flow the splat operand's taint into the call. Previouslylist_splatanddictionary_splatTree-sitter nodes weren't matched inTaintTracker._is_tainted, so calls likeeval(*user_args)slipped through without a violation.
Advisory suggestions (JSON / SARIF)#
suggestions[]array on every Violation, a list of advisorySuggestionobjects, each with a one-linedescriptionand zero or moreTextEditentries (range + replacement). Empty when the rule has no fix to offer. Surfaced in JSON output (--format json), in SARIF output (--format sarif→ nativefixes[]block, advisory by spec), and via the public Python API (Violation.suggestions: tuple[Suggestion, ...]).SAFE201 (bare_except)ships the first suggestion, replace bareexcept:withexcept Exception:. Validates the schema end-to-end with a real rule. More rules can attach suggestions in subsequent releases without further schema changes.docs/JSON_SCHEMA.mddocuments the newSuggestionandTextEditshapes and dedicates a section to the advisory only contract for editor / CI integrations.
CLI surface#
--statisticsCLI flag, prints a per-rule count summary at the end of a pretty-mode run (CODE RULE ACTIVE SUPPRESSED). Useful for "where do we stand?" snapshots in CI. Sorted by descending total count, ties broken alphabetically by code for deterministic output. Silent on a clean run.- Top-level CLI help and version, ruff-style. New
safelint helpandsafelint versioncommands plus the conventional-h/--help/-V/--versionshort and long flags. Help text uses a coloured layout matching ruff's (Commands / Options / Global options sections, bold headers, cyan command names, dim descriptions). Subcommand-level help is reachable via eithersafelint help checkorsafelint check --help. ANSI colour auto-disables when stdout is not a TTY. Documented inCONFIGURATION.mdunder "Top-level commands and flags".
AI-client integration#
- Cursor support alongside Claude Code.
safelint skill installgains a--clientflag acceptingauto/claude/cursor. Cursor installs deliver a single MDC project rule (safelint.mdc) to~/.cursor/rules/(user) or<cwd>/.cursor/rules/(project), matching Cursor's native Project Rules format. Both clients share the same step-by-step workflow because safelint's CLI surface is the same; the bundled language addendums remain accessible to either client viasafelint skill path. The Claude install excludes thecursor/subdirectory from the materialised skill folder so peer-client bundles don't leak into~/.claude/skills/safelint/(in both copy and symlink modes, symlink mode now per-entry-symlinks the directory contents instead of linking the whole tree). - Auto-detection is now the default.
safelint skill install(no--client) is--client autounder the hood. It scans cwd for client markers (CLAUDE.md/.claude//.cursor//.cursorrules); if found, installs each detected client's skill project-scoped. Otherwise it scans home (~/.claude//~/.cursor/) and installs user-scoped. If neither has any markers, it errors out with the exact--clientcommands the user can run instead. Multi-detection is supported, both Claude and Cursor present means both get installed in registry order.--client auto --projectskips the home fallback. Behaviour change for users running off the development branch: prior to 1.8.0 in this branch, baresafelint skill installalways installed Claude unconditionally. The new default may install Cursor or both in some environments. Pass--client claudeexplicitly to preserve the prior behaviour. (No PyPI users are affected, only 1.7.0 has shipped to PyPI.) ClientSpecregistry pattern. A frozen dataclass + tuple registry insafelint._skill_installdefines each supported client. Adding GitHub Copilot, codex, windsurf, etc. is oneClientSpecappend plus the bundled artefact, no control-flow changes elsewhere. CLI--clientchoices are derived from the registry so argparse stays in sync automatically.- New top-level user guide:
AI_CLIENTS.mddocuments auto-detection logic, per-client install / usage, project-vs-user scope, symlink mode, troubleshooting, and the developer guide for adding a new client. The bundled in-wheel reference atsrc/safelint/skill_files/README.mdstays as a short install-focused doc and links out.
Changed#
- Pretty-mode summary line updated from "No fixes available (safelint does not auto-fix violations)" to either "No suggestions available (safelint does not auto-fix)." (when no rule emitted suggestions) or "N advisory suggestion(s) available, view via --format json or --format sarif (safelint does not auto-apply fixes)" (when at least one rule did). Wording deliberately distinguishes "no auto-fix" (a permanent design choice) from "no suggestions available" (a per-run state). Test assertions updated accordingly.
- Cache schema version bumped from "1" to "2". The new
suggestions[]field onViolationrequires a richer reconstruction thanViolation(**dict), which the cache now handles via_dict_to_violation/_dict_to_suggestion/_dict_to_text_edit. Existing cache entries written by older safelint versions become unreachable automatically (the version is folded into the engine fingerprint, which is part of the cache key). - The taint-through-formatting paths (f-strings,
"…".format(tainted),"… %s …" % tainted) now have explicit regression tests covering each form. The behaviour itself was already in place since the original SAFE801 implementation; this release just locks the contract in so it can't silently regress.
Fixed#
SAFE202previously only matched empty-named-children blocks (which Tree-sitter doesn't actually produce for valid Python), so the rule was effectively dead code. The broadened detection above fixes this.ReturnValueIgnoredRulenow anchors violations on the call node rather than the wrappingexpression_statement, so column ranges match the offending call instead of including trailing newline / semicolon tokens.
Notes#
- The contract is permanent: SafeLint will never ship
--fix. This is documented as a project policy indocs/JSON_SCHEMA.md("Suggestions are advisory only" section). Editor integrations (Claude Code skill, VSCode plugin) may render suggestions as Quick Fix code actions, but every edit goes through user confirmation. The SARIFfixes[]block is natively advisory per the SARIF 2.1.0 spec, GitHub code scanning, IDE extensions, and other consumers already implement confirmation flows for it. - Helper-function inlining (cross-function taint analysis) was considered for the SAFE801 work in this release but deferred. Adding it would require a full call-graph walker bounded by depth limits and constitutes a larger rewrite of
TaintTracker. The current intra-procedural-only analysis remains the design contract; if a real-world need emerges for cross-function taint, it can be picked up in a future release. - Internal milestones 1.9.0 and 1.10.0 were never published to PyPI; their work is included in this 1.8.0 release. Those version numbers remain available for future use.
1.7.0 - 2026-05-04#
This release adds column-precise positioning to violations, the foundational change needed before a polished VSCode extension can underline the exact span of an offending construct rather than the whole line. No breaking changes; the new fields default to null for any consumer that doesn't read them.
Added#
- Fully-resolved range positions on every Violation:
end_lineno,column_start,column_end(in addition to the existing requiredlineno). All four are 1-based; the range is half-open[start, end), matching LSP / VSCodeRangeand SARIFregionsemantics.end_linenocorrectly anchorscolumn_endto the end-line of multi-line constructs (function definitions, except clauses, while loops), without it, editors would mis-applycolumn_endto the start line.linenoremains required (no default); the three additional fields default toNonefor synthetic violations without a Tree-sitter node (e.g.test_existenceagainst missing files), which editor consumers should treat as "underline the whole line". node_range(node)helper insafelint.languages._node_utils, returns(start_line, end_line, column_start, column_end)tuples directly from a Tree-sitter node, so rule code stays free of inlinestart_point[0] + 1/end_point[1] + 1plumbing.BaseRule._make_violation_for_node(filepath, node, message), convenience wrapper around_make_violationthat auto-extracts the full 4-coordinate position info from a Tree-sitter node. Most rules now use this; the lower-level_make_violationacceptscolumn_start/column_end/end_linenokwargs for the few cases (e.g. parse errors) where the node isn't available.
Changed#
- All built-in rules with a Tree-sitter node in scope now populate columns:
function_length,nesting_depth,max_arguments,complexity,bare_except,empty_except,logging_on_error,side_effects,side_effects_hidden,resource_lifecycle,unbounded_loops,missing_assertions,global_state,global_mutation,tainted_sink,return_value_ignored,null_dereference. Thetest_existence/test_couplingrules continue to emit file-level violations with no column data (the violation is about the file, not a span). TaintTracker.sink_hitsnow stores(call_node, var_name, sink_name)tuples instead of(lineno, var_name, sink_name)so the consuming rule can derive position info, including columns, from the node directly.- Parse-error violations (
SAFE000) now carry the column of the offending token as a zero-width caret (column_start == column_end), so editors can render a precise marker. - JSON output (
--format json) gainsend_lineno,column_start, andcolumn_endkeys on every violation. Existing consumers ignoring unknown keys are unaffected. - SARIF output (
--format sarif) populatesregion.startColumn,region.endColumn, and (for multi-line constructs only)region.endLine. Single-lineendLineis omitted because SARIF spec defaults absentendLinetostartLine.
1.6.0 - 2026-05-02#
This release ships the Claude Code skill inside the wheel and adds a one-line install command, plus a batch of correctness fixes from the v1.5.0 review cycle (caching, argv routing, SARIF URIs, CLI strictness, clean-run UX).
Added#
safelint skill installsubcommand, copies the bundled Claude Code skill into~/.claude/skills/safelint/(default) or<cwd>/.claude/skills/safelint/(with--project). Use--symlinkfor a live link to the bundled location,--forceto replace an existing install. New install flow ispip install safelint && safelint skill install.safelint skill pathsubcommand, prints the on-disk location of the bundled skill files. Useful for inspectingSKILL.mddirectly or debugging install issues.- Skill files are now bundled in the wheel at
safelint/skill_files/(mirroringsafelint/languages/one-to-one).safelint skill installfinds them viaimportlib.resources, so the same code path works forpip install,uv add, and editable installs from a checkout. docs/JSON_SCHEMA.md, the stable schema forsafelint check --format json. Documents top-level keys, the Violation object, severity / fail_on / blocking semantics, and example consumers in bash / Python / Node. Versioning policy: additions are non-breaking; removals require a major bump.
Changed#
- The Claude Code skill now lives at
src/safelint/skill_files/in the source tree (wasskills/safelint/). The skill itself is also more modular: a language-agnostic core (SKILL.md) plus per-language addendums underlanguages/<lang>.md, mirroringsrc/safelint/languages/<lang>.py. To add a new language, follow the new step 7 inADDING_A_LANGUAGE.md.
Fixed#
per_file_ignoresis now folded into the engine fingerprint, so adding/removing/editing a glob entry between runs invalidates the affected cache entries. Previously a cache hit carried the cachedsuppressedlist over unchanged, which meant removing aper_file_ignoresentry left previously suppressed violations stuck in the suppressed list, the user would loosen config and still see the silence applied. The post-hit re-filter (which only walked the active list and never the suppressed list) is now also redundant and has been removed.- Argv routing no longer breaks when a value-taking global flag precedes the
checksubcommand. Previouslysafelint --format json check srcsawjsonas the first non--token and fell into hook mode, silently no-oping (jsonandcheckaren't.py) with exit 0. The router now recognises the value-taking flags (--format,--fail-on,--mode,--ignore,--config,--stdin-filename) and skips their values when looking for the subcommand. - Cache key now includes the normalised filepath (in addition to source bytes and engine fingerprint), so two files with identical contents under different paths no longer share a cache entry. Without this, every emitted
Violationfrom the second-served file would carry the first file's path, and path-dependent rules (test_existence,test_coupling) would draw conclusions from the wrong file. - Cache directory now anchors to the discovered config root (where
safelint.tomlor[tool.safelint]was actually found while walking up), not to the directory the user happened to pass tosafelint check. Hook mode resolves the location the same way as check mode, so a single project can no longer end up with multiple.safelint_cache/directories scattered across subdirectories. safelint checkin pretty mode now prints theAll checks passed.summary on a clean run (matching ruff/ty's UX). Pre-commit hook mode and--stdinmode stay silent on success via a newsilent_on_cleanflag.- SARIF
artifactLocation.urinow emits a valid URI reference: backslash separators are normalised to forward slashes, absolute paths are made cwd-relative when possible, and special characters are percent-encoded. GitHub code scanning previously rejected SARIF docs produced on Windows hosts. - CLI now fails loudly on unknown flags.
--formta=jsonand similar typos used to be silently ignored (because hook/stdin parsing calledparse_known_args); they now surface aserror: unrecognized arguments: --formta=json. - In
--format json/--format sarif, status messages from the git-modified-files probe go to stderr instead of stdout, so machine-readable output stays a single parseable document. The "no modified Python files" early-return now also emits an empty JSON/SARIF doc on stdout in those modes.
Migration#
If you installed the v1.5.0 skill by symlinking skills/safelint/ from a git checkout, that path no longer exists in v1.6.0. To migrate:
rm ~/.claude/skills/safelint # remove the stale symlink
pip install --upgrade safelint
safelint skill install
1.5.0 - 2026-05-02#
This release adds the foundations needed by editor integrations and the upcoming Claude Code skill / VSCode plugin: structured output formats, an in-process stdin mode, and a content-addressed result cache. No breaking changes.
Added#
--formatflag with three choices:pretty(default, unchanged ruff/ty multi-line coloured output),json, andsarif. The JSON format emits a stable schema with aversion,summary(counts + suppressed breakdown), and flatviolations/suppressedlists. The SARIF format is SARIF 2.1.0 conformant and consumable by GitHub code scanning, Azure DevOps, and similar tools. The flag is available in bothsafelint checkand pre-commit hook modes.--stdin/--stdin-filename PATHflags read source from stdin instead of from disk and lint it as if it came fromPATH. Designed for editor integrations that need to lint un-saved buffers without round-tripping through a temp file. The pseudo-filename drives language detection by extension and shows up as the violation file path.SafetyEngine.check_source(filepath, source)public method runs the same rule pipeline ascheck_filebut on a caller-provided buffer. Used by stdin mode and available to library consumers building editor integrations.- Per-file lint-result cache keyed on
sha256(source + engine fingerprint)where the engine fingerprint folds in safelint version, an internal cache schema version, and the active rule set with per-rule config. The cache lives at<config-dir>/.safelint_cache/(next topyproject.toml/safelint.toml, mirroring.pytest_cache's convention) and stores one JSON file per key. Re-runs on unchanged files are essentially instant, important for editor "lint on save" loops. --no-cacheflag disables the cache for the current run (e.g. CI where every run is fresh anyway, or when debugging cache-related issues)..safelint_cache/added to the project's.gitignore.ADDING_A_LANGUAGE.mddeveloper guide: a concrete walkthrough of adding a new language (TypeScript, Go, Rust, …), with a per-rule audit of which Python rules are portable, language-agnostic, or Python-only.
Notes#
--stdinmode unconditionally bypasses the disk cache. Editor keystrokes produce a slightly different buffer every time; caching them would only churn the project tree without ever helping. The--no-cacheflag is therefore a no-op in stdin mode.- The new public
LintCacheclass acceptscache_dir=Noneto opt out of caching at the engine level, used by--no-cache, by stdin mode, and recommended for any tests / library callers that need isolation.
1.4.1 - 2026-05-01#
Added#
max_file_size_bytestop-level config option (default 5 MiB). Files larger than the bound are skipped with asafelint: warning: skipping <path> (<size> bytes exceeds max_file_size_bytes=…)diagnostic to stderr instead of being read into memory and parsed. Guards against OOM on accidentally-huge inputs (binary blobs masquerading as.py, very large generated files). To allow larger files, raise the bound explicitly,0is rejected as a likely typo (it would disable the OOM guard entirely) and falls back to the default with an init-time warning. Engine init validates the value: must be a non-negative integer, otherwiseTypeError/ValueErrorfires before any file is read. Closes #20.
Fixed#
- File discovery is now safe against symlink cycles.
SafetyEngine._discover_filesswitched fromPath.rglob('*')(which follows symlinks and can recurse forever on a cycle likea/sub -> ..) toos.walk(target, followlinks=False). Same single-pass O(number_of_files) cost, but safe by construction. Matches what ruff and flake8 do by default. Closes #19.
1.4.0 - 2026-05-01#
Heads-up, breaking library API change.
LintResult.suppressedis nowlist[Violation](wasint). Library consumers that read this field directly need to switch tolen(result.suppressed)for the count. CLI users are unaffected. See Changed below for details and migration notes.
Added#
- Standalone
safelint.tomlconfiguration file (top-level keys, no[tool.safelint]wrapper). When bothsafelint.tomlandpyproject.toml[tool.safelint]exist in the same directory,safelint.tomlwins, matchingruff.toml/pyproject.tomlprecedence. examples/sample.safelint.tomlreference covering every supported configuration key.- Public
safelint.languages.supported_extensions() -> frozenset[str]for callers that need to know which file extensions have a registered language. Use this instead of importing the private_REGISTRY. walk()insafelint.languages._node_utilsaccepts an optionalskip_typesparameter that prunes subtrees rooted at any matching node type (used by per-function rules to avoid descending into nesteddef/async defbodies).
Changed#
side_effects(SAFE304) andside_effects_hidden(SAFE303) now normalise both sides of the name comparison. Function names are lowercased for matching, and user-suppliedio_name_keywords/pure_prefixesare lowercased once at config load, so configurations likeio_name_keywords = ["Write", "Log"]orpure_prefixes = ["Get", "Calculate"]behave the same as their lowercase forms. Previously only the function name was lowered, leaving uppercase config entries silently unmatched.load_config()now returns a fresh deep copy of the merged config on every call. Mutating the result (e.g.config["ignore"].append(...)) no longer corrupts the module-globalDEFAULTS.- Removed YAML (
.safelint.yaml) configuration support and thesafelint[yaml]install extra. Migrate to[tool.safelint]inpyproject.tomlor to a standalonesafelint.toml. - CLI summary "All checks passed." is now bold green to match
ruff/ty. - The "No fixes available …" line is no longer printed on clean runs (with or without suppressions). It only appears when there are active violations a developer might wonder about auto-fixing.
- Suppressed-violation summary now shows a per-code breakdown, e.g.
(2 SAFE501, 1 SAFE304 suppressed), instead of a bare(N suppressed)count, so it is clear which rules were silenced. - Breaking (library API):
LintResult.suppressedis nowlist[Violation](wasint). Uselen(result.suppressed)for the count and iterate to inspect codes, rules, file paths, and line numbers of suppressed violations. - Replaced internal use of Python's
loggingmodule with a dedicated diagnostics channel that writes formatted single-line messages to stderr (safelint: warning: …,safelint: error: …). Configuration typos and malformed-TOML errors are now surfaced cleanly instead of leaking through Python'slastResortlogging handler. walk()now traverses onlynamed_children(skips Tree-sitter's anonymous punctuation/keyword tokens), reducing the number of nodes visited per traversal across every rule and the suppression parser.- Parse-error violations (
SAFE000) now include line, column (1-based), and a kind hint such asmissing ':'orsyntax error. The lineno on the violation now points at the offending location instead of being hardcoded to 0. MaxArgumentsRulenow counts*argsand**kwargsparameters, each as one argument. Previously they were silently ignored, allowing functions to exceedmax_argswithout triggering.- An empty
[tool.safelint]section inpyproject.toml(or an emptysafelint.toml) is now treated as a present-but-empty config. Previously the loader fell through to an ancestor directory's config, hiding unintentionally-blank sections. - Self-development pre-commit hook switched from
repo: https://github.com/shelkesays/safelint @ v1.3.2torepo: local, so contributors run the in-tree code rather than an outdated published release while iterating on safelint itself.
Fixed#
- Per-function rules no longer incorrectly aggregate metrics from nested
def/async defbodies into the enclosing function. Affectscomplexity,nesting_depth,missing_assertions,unbounded_loops,global_state,global_mutation,logging_on_error(a logging call inside a nested helper would have falsely satisfied the rule), and the dataflowTaintTracker. Each nested function is scored as its own unit, as the outer-walk loop already intended. state_purity(global_state,global_mutation) now also stops at nested class definitions, aglobal Xdeclared inside a nested class body lives in that class's scope, not the enclosing function's.function_length(SAFE101) reported counts that were off by one (a 60-line function showed59 lines). The calculation is now inclusive of thedefline.- Dataflow taint tracker now unwraps
keyword_argumentnodes,eval(code=user_input)is no longer missed because the tainted value was hidden behind a kwarg wrapper. - Dataflow taint tracker now propagates taint through tuple/list destructure targets (
a, b = tainted,[a, b] = tainted,(a, b) = tainted), starred destructures (a, *rest = tainted), and chained assignments (a = b = tainted). Previously the LHS shape was assumed to be a single bare identifier, so every other form silently dropped the taint. - Top-level
ignoreandper_file_ignoresentries now validate that every value is a string. Non-string elements (e.g.["SAFE101", 42]) and wrong-shape values (e.g.ignore = "SAFE101") are reported with a clearTypeErrorat engine init instead of crashing later on.upper(). - File discovery now does a single
rglob('*')pass and filters by suffix, instead of onerglob('*<ext>')per registered extension. Discovery is now O(number_of_files) rather than O(number_of_extensions * number_of_files). No behaviour change on a single-language registry, but matters as more languages are added.
1.3.1 - 2026-04-24#
Added#
ignoreconfig key and--ignoreCLI flag: suppress rules globally by code (SAFE101) or name (function_length); unknown entries log a warning at startup.per_file_ignoresconfig key: suppress specific rules for files matching a glob pattern (e.g."tests/**" = ["SAFE101", "SAFE103"]); multiple patterns union their ignore lists.# nosafe: RULE, CODEinline suppression: codes and rule names can now be mixed in the same comma-separated list on a single# nosafe:comment.- Suppressed violation count (from both
# nosafeandper_file_ignores) reported in the end-of-run summary so suppressions remain auditable.
Changed#
SafetyEngine.__init__extracted into two focused static methods (_build_active_rules,_parse_per_file_ignores) to keep complexity within bounds.- Pattern matching for
exclude_pathsandper_file_ignoresswitched frompathlib.Path.matchtofnmatch.fnmatchcase(path.as_posix(), pattern), fixing incorrect**handling on Python ≤ 3.12. --ignoreCLI flag changed fromnargs="+"toaction="append"so it can be repeated (--ignore SAFE101 --ignore SAFE103).- CLI summary now shows
(N suppressed)instead of(N suppressed via # nosafe)to cover all suppression mechanisms.
Fixed#
per_file_ignorespatterns with**(e.g.tests/**) now correctly match files in nested subdirectories on Python ≤ 3.12.- Pre-commit hook no longer shows a success message for files that were silently excluded.
1.3.0 - 2026-03-01#
Added#
- Initial public release with 16 built-in rules covering function length, nesting depth, cyclomatic complexity, error handling, global state, side effects, resource lifecycle, loop safety, and opt-in dataflow analysis.
- TOML (
pyproject.toml) and YAML (.safelint.yaml) configuration with deep-merge against built-in defaults. # nosafeinline suppression (bare and with specific codes).exclude_pathsglob patterns to skip directories entirely.fail_fastexecution option.- Pre-commit hook integration.
--mode=ciand--fail-onCLI flags.