Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Sourcecheck

Sourcecheck checks source code, explains findings, and runs native formatters. The CLI and call-path checker use Rust. Compiler adapters use each project's language and build settings.

cargo install --path . --locked
sourcecheck rules list
sourcecheck rules explain no-side-effects
sourcecheck check --language go --project .
sourcecheck check --language typescript --project tsconfig.json --format json
sourcecheck check --language rust --project Cargo.toml
sourcecheck check --language csharp --project App.csproj

Review a change

Run sourcecheck in a Git worktree. It compares the current files with HEAD, including staged, unstaged, and untracked files. Use --base to review a branch against its merge base with another ref.

sourcecheck
sourcecheck review --base origin/main --format json --summary sourcecheck-review.md
sourcecheck review --all

The analyzer still loads each full project. Changed review includes findings when their source, function range, call evidence, or related duplicate location intersects new lines. File-wide findings also match deletion-only changes in an existing file. New files and renamed files are reviewed in full. Strict diagnostics, compiler-reported dead code, and incomplete analysis stay visible across the project. Removing the last caller can make an unchanged declaration unused. Existing dead code can therefore appear on any review. Dependency evidence on Cargo manifests and C# project files matches edits anywhere in that file. Changes, including deletions, to the selected manifest, policy, or common project settings include findings across that project. Use --all when you need every finding.

The default gate blocks strictness and unsafe-code violations. Compiler diagnostics previously reported under strict also block and stay visible project-wide. These rules are implicit-file-truncation, await-holding-refcell-ref, rethrow-loses-stack, suspicious-iterator-map, ignored-io-amount, and incomplete-switch. Set their severity individually to change that policy. Other findings start as warnings. Use --deny-warnings to block warnings too. Review exits with 0 if it passes, 1 if it finds a blocking issue, and 2 if analysis is incomplete. Formatting is a separate command. Review never applies a fix.

Configure a repository

A repository can commit sourcecheck.json at its root. Without it, Sourcecheck discovers root Go, TypeScript, Rust, and C# manifests. Use configuration to include nested projects and to select the leaf configs in a TypeScript project-reference setup. Paths are relative to the configuration directory. Use --root to select a configuration directory explicitly.

{
  "projects": [
    {
      "name": "web",
      "language": "typescript",
      "path": "web/tsconfig.json",
      "policy": "web/effects.json"
    },
    {
      "name": "api",
      "language": "go",
      "path": "api",
      "packages": ["./internal/...", "./cmd/..."]
    }
  ],
  "severity": {
    "no-side-effects": "error",
    "duplicate-code": "warning",
    "too-many-functions": "off"
  }
}

Each project can select a rules array. An omitted or empty array uses the language defaults. Severity accepts error, warning, and off. Severity settings apply to review. The explicit single-project check command retains its existing behavior and schema.

Add a custom rule

Custom rules are repository-owned JSON files. The same file works with Go, TypeScript, Rust, and C#. Start with a new path and generate a working rule.

mkdir -p rules
sourcecheck rules template > rules/no-fixme.json
sourcecheck rules test rules/no-fixme.json

Edit the id, pattern, message, and solution. Keep the ID stable and start it with custom-. Add a snippet that should pass to pass and one that should trigger the rule to fail. Run rules test after each edit. It checks the examples without a compiler or project. It exits with code 2 and names the file when validation fails. Agents and editors can read the definition schema with sourcecheck rules schema. Example rule · JSON Schema

Register the rule in each project that should enforce it. Paths in customRules are relative to sourcecheck.json.

{
  "projects": [
    {
      "name": "api",
      "language": "go",
      "path": ".",
      "customRules": ["rules/no-fixme.json"]
    }
  ],
  "severity": { "custom-no-fixme": "error" }
}

Run sourcecheck review --all --format json to test against the whole project. Changed review includes findings on unchanged lines when the rule file changes. Review uses warning severity by default. Use error to block or off to disable reporting. To try a rule before registering it, run sourcecheck check --language go --custom-rule rules/no-fixme.json. Repeat --custom-rule to try several files.

A line pattern applies a Rust regular expression to each line in the adapter's source files, including comments and strings. It reports the first match on each matching line with a one-based UTF-8 byte column. Use it for text policies such as a retired configuration key or an issue marker. Rules that depend on resolved symbols, types, or control flow need a language analyzer.

Match code syntax

Generate a syntax rule when comments and string contents should be ignored. Supply a grammar with --language. Supported values are go, typescript, tsx, rust, and csharp.

sourcecheck rules template --language rust > rules/no-legacy-call.json
sourcecheck rules tree --language rust src/lib.rs
sourcecheck rules test rules/no-legacy-call.json

The tree command prints the named nodes and fields for the file. Edit syntax.query to match those nodes. Capture the node to report with @finding. The template matches a direct call named legacy. Its predicate checks the identifier text. A comment containing legacy() passes. A method call such as client.legacy() also passes because it has a different syntax tree.

Provide complete, parseable source snippets in pass and fail. Use the same customRules registration and severity settings as for line patterns. In a TypeScript project the tsx grammar checks .tsx and .jsx files. The typescript grammar checks the other source files supplied by the adapter. A syntax rule operates on one grammar. Give separate rules distinct IDs when checking both grammars.

Assess code quality

Review reports correctness, safety, architecture, maintainability, and readability separately. Each JSON assessment names the rules that contributed and counts visible errors and warnings. The status shows whether that aspect is clear, advisory, blocking, incomplete, or outside the selected rules. Use --all for a project-wide assessment. Changed review measures only findings in the review scope.

Review changed-code test coverage

Run your tests with coverage enabled and export an LCOV report for the same working tree. Pass its path to changed review.

sourcecheck review --base origin/main --coverage coverage/lcov.info
sourcecheck review --base origin/main --coverage coverage/lcov.info --format json

Use source paths relative to the Git root or absolute paths inside the checkout. Sourcecheck counts instrumented lines that intersect the repository diff, including files outside the configured analyzer projects. For a new file, it checks the whole file. A zero hit count identifies an uncovered line.

When the LCOV report includes branch records, the review also counts changed branches and identifies missed branches by file, line, block, and branch ID. Repeated test records count each line or branch once. A changed Go, TypeScript, JavaScript, Rust, or C# source file without line coverage data is listed separately. Coverage is informational. A report that cannot be read or parsed makes the review incomplete.

Use it in CI

Run sourcecheck review --base "$BASE_SHA" --format json --summary sourcecheck-review.md for a pull request. Fetch enough Git history to compute the merge base. Publish the Markdown summary for reviewers and keep the JSON report for agents. This repository includes a GitHub Actions workflow that runs both Sourcecheck and the native tests. Keep the project's test suite in CI. The review result includes each project's rule IDs, package selection, findings, and incomplete status. Review report schema

Audit dependencies for known vulnerabilities

Install OSV-Scanner v2 on PATH. Sourcecheck uses its ecosystem-specific package parsers and the OSV advisory database. The following version was tested.

go install github.com/google/osv-scanner/v2/cmd/osv-scanner@v2.7.1
export PATH="$(go env GOPATH)/bin:$PATH"
sourcecheck audit --project .
sourcecheck audit --project Cargo.lock --format json

Give --project a directory for recursive discovery or a single dependency file. Tested inputs include npm's package-lock.json, Cargo.lock, Go's go.mod, and NuGet's packages.lock.json. Run the audit separately in CI. Online mode uses external services to check package information. For offline use, populate OSV-Scanner's database cache first, then pass --offline. Database freshness affects the result. OSV-Scanner documentation

Text output lists affected versions, advisory IDs, and fix versions when available. JSON keeps the scanner's inventory and advisory records in scannerReport.results, including CVE aliases where assigned. Use the advisory for the affected package and version when choosing an upgrade. Refresh the lockfile, rerun the audit, and run the project's tests. A version match establishes exposure to a published advisory. Runtime reachability requires separate analysis.

Exit code 0 means the scanner completed with no reportable issues. Code 1 means the scanner found issues. Code 2 means the audit was incomplete, including a missing scanner, unavailable database, or no recognized package sources. Read complete before using a JSON result as a gate. Audit report schema

Tools and scope

Language Check Format
Go Go 1.26 or later and the Go compiler API. Checks packages matching ./... by default. Repeat --package to select other patterns. Uses the active build tags and platform. gofmt on explicit files.
TypeScript Node.js and the project's TypeScript package. Uses one tsconfig.json, its effective options, and source files in its compiler program. Tested with TypeScript 5.9. A solution config with only project references requires separate checks for its leaf projects. The project's Prettier CLI on explicit files. Tested with Prettier 3.
Rust Cargo and Clippy. Checks Cargo's default targets for the selected packages and uses the default features. Repeat --package to select packages. cargo fmt on the manifest's default formatting scope.
C# .NET SDK 8 or later. Evaluates one single-target .csproj, checks its nullable settings, and runs its build with warnings as errors. dotnet format whitespace on one project.

The Rust CLI requires Rust 1.85 or later. Its crates forbid unsafe code. Cargo dependencies and external toolchains have their own code policies. The Go adapter may download its pinned compiler API dependency on the first run. Cargo and MSBuild can run build scripts and write build outputs.

Rules

Rule Scope What to review
strict All four languages Go syntax and types, TypeScript strict settings and compiler errors, Rust compiler and Clippy warnings, or C# nullable settings and build warnings.
no-side-effects Go, TypeScript, Rust Go and TypeScript report call paths to configured effects. Rust reports Clippy's dbg! lint.
no-unsafe Rust Reject unsafe Rust in the checked crate targets.
long-function Go, TypeScript, Rust Go function or method declarations and TypeScript named functions, const-bound functions, class methods, constructors, and immediately invoked functions over 60 physical lines. Rust uses Clippy's too_many_lines and the project's Clippy configuration.
complex-function All four languages Go, TypeScript, and C# flag cyclomatic complexity above 10. Rust uses Clippy's cognitive_complexity and honors cognitive-complexity-threshold in the project's Clippy configuration.
panicking-unwrap Rust Opt-in. Clippy detects unwrap calls on Option and Result. Propagate recoverable errors with ? or handle the missing value explicitly.
await-holding-refcell-ref Rust A RefCell borrow stays live across an await. Limit the borrow to a shorter block before suspending.
implicit-file-truncation Rust A file is opened for writing with create enabled and no explicit truncation policy. Choose truncate, append, or preservation according to how existing contents should be handled.
async-array-foreach TypeScript An array forEach call ignores the promise returned by an inline async callback. Await each iteration with for...of, or collect promises in an array and await Promise.all for parallel work.
context-key-built-in Go A context.WithValue key uses a built-in basic type that can collide across packages. Use a private named key type and expose typed accessors.
rethrow-loses-stack C# Roslyn CA2200 reports a rethrow that loses the original stack trace. Use a bare throw inside the catch block to preserve the original failure location.
discarded-cancel Go An assignment discards the cancellation function returned by a standard context constructor. Keep the cancel function and call it when the operation ends.
unawaited-promise TypeScript Opt-in. A standalone call leaves a built-in Promise unobserved. Await or return the promise, or attach an explicit rejection handler.
async-array-predicate TypeScript An inline async array predicate returns a promise, which a synchronous predicate method treats as truthy. Await the decisions first, then select or test the elements using those resolved values.
non-pointer-json-destination Go Decoding JSON into a non-pointer value or nil cannot populate the destination. Pass a non-nil pointer to the value that should receive the data.
unused-array-concat TypeScript A standalone built-in array concat call discards the new array. Return or assign the new array if the elements should be retained.
suspicious-iterator-map Rust Calling count after map ignores the mapped values. Remove the map if only the count matters, or consume the transformed values explicitly.
ignored-io-amount Rust A read or write handles the error but ignores the number of bytes transferred. Use read_exact or write_all for a complete buffer, or handle the returned byte count.
incomplete-switch C# Roslyn CS8509 identifies a switch expression with an uncovered input. Add a case for the missing input or define explicit behavior for unexpected values.
return-in-finally TypeScript A return inside finally overrides a pending return or exception. Keep cleanup in finally and return after the try statement when the operation succeeds.
duplicate-condition TypeScript, C# An else-if chain repeats a simple condition. Compare the two locations and correct the later condition or remove its branch.
async-void C# Opt-in. An async void method gives callers no task to await. Return Task when the signature permits it. For a required void callback, handle failures in a Task-returning helper.
empty-catch TypeScript, C# A catch body with no handling or explanatory comment. Handle the expected exception, propagate it, or document intentional recovery.
defer-in-loop Go A loop registers deferred work on its enclosing function. For per-iteration cleanup, close the resource before the next iteration or move the iteration into a helper.
discarded-error Go A standalone call to the standard library's errors.New or fmt.Errorf discards its result. Return or handle the error.
async-promise-executor TypeScript An inline async executor passed to the built-in Promise constructor can reject a promise that the constructor ignores. Use an async function directly or a synchronous executor.
await-holding-lock Rust Clippy identifies a synchronous lock guard held across an await. Finish the critical section before awaiting.
discarded-future Rust Clippy identifies a nonbinding let on a future. Await the work or schedule it and observe completion.
unawaited-task C# Compiler diagnostic CS4014 identifies an unawaited call. Await the task or return it to a caller that observes exceptions.
prefer-early-return All four languages Flags an else after a branch that ends in an explicit return. Shows the return location. Keep the return as a guard and place the normal path after it. Preserve the block when moving local declarations.
deep-nesting All four languages More than four nested control-flow levels.
naming-convention All four languages Language-specific casing for declarations.
long-line All four languages Source lines over 120 Unicode characters.
dependency-boundary All four languages Direct dependencies that match a deny rule in the project policy.
dependency-cycle All four languages A dependency path that returns to its starting point.
large-file Go and TypeScript Files over 300 physical lines.
too-many-functions Go and TypeScript Files with more than 15 function or method declarations. TypeScript counts top-level named functions, top-level const-bound functions, and class methods with bodies.
dead-code All four languages Go reports unreachable statements. TypeScript reports unused local declarations and parameters and unreachable statements. Rust reports compiler dead-code, unused-import, and unreachable-code lints. C# reports selected unused and unreachable-code diagnostics from the build.
duplicate-code Go and TypeScript Identical function bodies with at least 30 tokens. Whitespaces and comments outside literals are ignored. The finding links to the first matching body.

By default, Sourcecheck runs the rules available for the chosen language. Use --rules strict,long-function or another comma-separated list to narrow a run. A rule requested for an unsupported language makes the run incomplete.

Go counts conditionals, loops, non-default switch and select clauses, and short-circuit operators. TypeScript counts conditionals, loops, non-default switch cases, catch clauses, conditional expressions, and short-circuit or nullish coalescing operators.

Nesting counts conditionals, loops, and switch statements. It also counts Go select statements and TypeScript catch clauses. An else if continues the same level. Plain blocks and separate function scopes do not add to the enclosing function's depth. Rust and C# use Tree-sitter for nesting. C# also uses it for complexity. Rust source checks scan Cargo target files and their source directories. This can include inactive Rust source files. C# source checks use the project's evaluated Compile items.

The size rules give you a place to start a review. For a large file, identify groups of declarations that operate on the same data or belong to the same operation. Extract a group into a named file or module. Keep the entry points easy to find. For a long function, extract a named step with clear inputs and outputs. Run the existing tests to check that the split preserves behavior.

Check naming conventions

Run sourcecheck check --language typescript --project tsconfig.json --rules naming-convention to inspect naming alone. The rule is enabled by default and advisory in review. It reports declarations and suggests a rename. It does not edit source.

Language Naming checked
TypeScript camelCase for named functions, variables, and parameters. PascalCase for types and functions that directly return JSX. Non-function const bindings may use UPPER_SNAKE_CASE. Object property names, imported names, and method names are outside this rule.
Go mixedCaps or MixedCaps for functions, variables, constants, and types. It checks underscores and common initialisms such as userID, ParseURL, and httpServer. Suggested names preserve whether the declaration is exported. It skips generated files and struct fields.
Rust rustc's nonstandard-style checks, including snake_case for functions and variables, UpperCamelCase for types, and UPPER_SNAKE_CASE for globals. Rust lint allowances still apply.
C# PascalCase for named methods, local functions, types, and properties. camelCase for named parameters and local variables. Fields are outside this rule.

Set dependency boundaries

Dependency cycles run by default. Add a policy to enable the boundary rule. Use --boundaries boundaries.json for a single check, or set "boundaries": "boundaries.json" on a project in sourcecheck.json.

{
  "deny": [
    { "from": "src/domain", "to": "src/infrastructure" }
  ]
}

Add "transitive": true to a deny rule to reject indirect dependencies. Sourcecheck reports one shortest path per matching source for that rule. For example, it can show a domain file importing a shared helper that imports infrastructure. Use "exceptFrom": ["src/domain/tests"] for an explicit source exception. An exception applies to that rule alone. Other sources can still violate the rule through an excepted file.

Prefixes match complete names or slash-delimited path segments. That rule matches src/domain/model.ts but leaves src/domain-test/model.ts outside its scope.

Language Dependency graph and policy names
TypeScript Resolved source paths relative to the tsconfig directory. Includes imports, re-exports, and string-literal dynamic imports. Unresolved and external module names use the external/ prefix.
Go Import paths between selected packages. Build tags and package selection control which source files contribute imports.
Rust Cargo workspace crate names and declared normal and build dependencies. Dependencies outside the workspace use the external/ prefix. Optional and target-specific declarations contribute to this graph.
C# Evaluated MSBuild project references. Use paths relative to the selected project directory, such as App.csproj and ../Data/Data.csproj.

Go and TypeScript findings point to the import. Rust and C# findings point to the manifest or project file. Package and project cycles can prevent the compiler from completing. In that case the report includes the cycle evidence and marks the run incomplete.

Set an effect policy

The Go and TypeScript defaults cover a small set of logging, file, and network calls. Supply a JSON file with --policy to replace the defaults.

{
  "roots": ["src/invoice.ts#calculateInvoice"],
  "effects": ["console.log", "fetch"]
}

Omit roots to check every function the adapter models. A configured root must exist in the checked scope. Go uses symbols such as example.com/project.CalculateInvoice, example.com/project.Store.Save, and os.WriteFile. TypeScript uses paths relative to the config directory, such as src/invoice.ts#calculateInvoice, and library names such as console.log. Nested TypeScript declarations add an offset to distinguish declarations with the same name. The text and JSON evidence show the exact IDs used in a run.

The Rust checker verifies every reported edge and both endpoints against the adapter facts and the selected policy. A path is evidence that the code contains those calls. This rule does not model branch feasibility, indirect calls through function values, interface dispatch, arbitrary mutations, or calls in module initializers. Go and TypeScript follow calls to immediately invoked function expressions. TypeScript also follows explicit constructors, resolved static methods, and instance methods on direct new expressions. It does not establish purity or test coverage. The checker validates the supplied facts at runtime. It does not require Lean.

Format, review, and verify

Run format first to see which files need changes. Add --write to apply the native formatter.

sourcecheck format --language go --project . internal/invoice.go
sourcecheck format --language typescript --project . src/invoice.ts
sourcecheck format --language rust --project Cargo.toml
sourcecheck format --language csharp --project App.csproj

Review the diff after a formatter write or a manual fix. Rerun the same check command and run the project's tests. Each finding gives a suggested fix. Call findings include the source location for each step so a reviewer can check the reported path.

Check exit codes are 0 for a completed run with no findings, 1 for a completed run with findings, and 2 for an incomplete run. Format uses 0 for success, 1 for formatting differences in check mode, and 2 if the formatter fails.

Agents can use --format json. Read schemaVersion and complete before interpreting findings. Each finding has a ruleId, message, and solution. It can also have a source location, ordered call evidence, and related locations for duplicate code. Source lines and UTF-8 byte columns start at 1. Paths are relative to the project where available. Check report schema

Analysis boundaries

The dead-code rule uses the selected project's compiler context. It covers the diagnostics in the rule table. Framework routes, dynamic imports, unused exports across projects, and unused dependencies need a model of the application's entry points. Fallow documents how it builds that graph, including framework conventions. Fallow

The duplicate rule compares whole function bodies. It keeps identifier names and literal values, so it finds identical implementations after formatting changes. Fallow's clone groups are a reference for showing repeated code together. Fallow duplication

For unused code, Sourcecheck uses the compiler's rules for each language. ESLint documents cases where a declaration can be written but never read, as well as exceptions for intentional unused parameters. Oxlint documents structured diagnostics for humans and agents. Sourcecheck gives each finding a stable rule ID, a source location when available, and a proposed fix. ESLint no-unused-vars · Oxlint

Verify Sourcecheck

cargo fmt --all -- --check
cargo clippy --locked --all-targets -- -D warnings
cargo test --locked
(cd adapters && go test ./... && go vet ./...)

Run the compiler-backed TypeScript fixtures with Node.js and npm available.

export SOURCECHECK_TYPESCRIPT_TEST_ROOT="$(mktemp -d)"
npm install --prefix "$SOURCECHECK_TYPESCRIPT_TEST_ROOT" --no-audit --no-fund typescript@5.9.3
cargo test --locked --test typescript_cli -- --ignored

Run the compiler-backed C# fixture with the .NET 9 SDK on PATH.

cargo test --locked --test native_practices -- --ignored

React and test quality

Add "react": true and "testQuality": true to a TypeScript project in sourcecheck.json to include these checks in review. For a single check, run:

sourcecheck check --language typescript --project tsconfig.json --react --test-quality

The React profile checks hook order, effect dependencies, React Compiler diagnostics, JSX keys, array index keys, and rendering mistakes. Install the lint packages in the React project with its package manager. For pnpm, run pnpm add -D eslint@9 @typescript-eslint/parser@8 eslint-plugin-react@7 eslint-plugin-react-hooks@7. Sourcecheck reads the project's installed React version.

The test profile checks Jest and Vitest for focused, skipped, and empty tests. It reports discarded expectations and supported literal assertions that always pass. Go checks empty test functions and a skip at the start of a test. Rust and C# inspect test attributes and bodies for skipped or empty tests. Each finding includes a proposed fix. These checks inspect source code. Use the project's test runner to verify behavior.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages