react-doctor icon indicating copy to clipboard operation
react-doctor copied to clipboard

refactor(runtime): full Effect v4 runtime — services, streaming pipeline, tagged errors

Open aidenybai opened this issue 6 months ago • 2 comments

What this is

react-doctor runs on a small Effect v4 runtime layer. The two public entry points (inspect() for the CLI, diagnose() for the programmatic API) share one orchestration Effect (runInspect) and one Service vocabulary. The diagnostic pipeline is genuinely streaming end-to-end, every error is a tagged ReactDoctorError with a reason union, every file IO crosses one Files service boundary, and the layer set is complete enough that adding a second linter backend, an LSP host, an NDJSON cache, or a SARIF reporter is "one new layer" rather than "rewrite the orchestration."

Rebased onto current main (which added a --dead-code feature in aae328cc and a score-payload gzip fix in d16d2c7b). The dead-code feature is integrated through the runtime as a new DeadCode Context.Service; the gzip fix is internal to calculateScore and the runtime's Score.layerHttp picks it up transparently.

All 1,202 react-doctor tests pass (1,198 pre---dead-code + 4 new for that feature). 31 new runtime tests cover the foundation, orchestration, streaming pipeline, file-IO service, dead-code service, spinner service, ndjson reporter, composite linter, and tagged-error contracts.

Architecture

Services (one Context.Service per orthogonal axis)

Service Purpose Live layer Test surface
Project Discover the React project at a directory layerNode (wraps discoverProject) layerOf(projectInfo)
Config Load react-doctor.config.json + rootDir redirect, cached via Cache.make (capacity 16, TTL 5min) layerNode layerOf({ config, resolvedDirectory })
Files All filesystem reads / lists / stats the pipeline needs layerNode layerInMemory(Map<absolutePath, content>)
Linter Stream diagnostics for an input layerOxlint, layerComposite([...]) layerNoop, layerOf(diagnostics)
DeadCode Whole-project reachability analysis layerNode (wraps checkDeadCode / deslop-js) layerNoop, layerOf(diagnostics)
Reporter emit(diagnostic) + finalize layerNdjson(path) (Schema-encoded NDJSON), layerCapture layerNoop, layerCapture
Score Compute the score layerHttp layerOffline, layerOf(result)
Spinner Terminal feedback during long phases layerOra(factory) layerNoop, layerCapture (records events)
LintPartialFailures Per-batch soft-failure messages from linters layerLive (Ref) (replaceable in tests)

The only production linter today is Linter.layerOxlint — layerComposite([...]) is the layer slot a future second backend would plug into without changing the orchestrator. Direct consumers of these services today are exactly two: inspect() (the CLI's entry point) and diagnose() (the programmatic API).

Tagged errors with a reason union — end to end

ReactDoctorError { reason: Schema.Union([...]) } lives in @react-doctor/core (the runtime re-exports without a circular dep). Every leaf failure is a Schema.TaggedErrorClass:

OxlintBinaryNotFound, OxlintNativeBindingFailed, OxlintSpawnFailed, OxlintTimedOut, OxlintOutputTooLarge, OxlintOutOfMemory, OxlintKilled, OxlintOutputUnparseable, ConfigParseFailed, ProjectNotFound, NoReactDependency, AmbiguousProject.

runOxlint raises tagged errors directly. Every error.message.includes(...) site across the lint boundary is gone.

Public API entry points (inspect(), diagnose()) translate runtime tagged errors back into the legacy classes (NoReactDependencyError, ProjectNotFoundError, AmbiguousProjectError) at the boundary using a structural _tag check.

Schema is the wire

  • runtime/diagnostic-schema.ts — Diagnostic + Severity + buildDiagnosticIdentity.
  • runtime/json-report-schema.ts — JsonReport as Schema.Union([JsonReportV1]).
  • Reporter.layerNdjson Schema-encodes every diagnostic at the wire boundary.

Streaming pipeline — actually streaming

runInspect's diagnostic flow is Stream-driven end to end with no intermediate array materialization:

  1. Stream.fromIterable(checkReducedMotion(scanDirectory)) prepends environment-side diagnostics (skipped in --diff mode).
  2. Stream.concat(Linter.lint(...)) appends the lint stream, with Stream.catchTag("ReactDoctorError", ...) folding mid-stream linter failures into didLintFail.
  3. Stream.concat(deadCodeStream) appends dead-code diagnostics (skipped in --diff / --staged mode since reachability is whole-project; failure folds into didDeadCodeFail via Effect.matchEffect).
  4. Stream.filterMap(filterMapNullable(transform.apply)) applies the per-element auto-suppress / severity / ignore / inline-suppression chain.
  5. Stream.tap(reporter.emit) pushes survivors to the Reporter as they emerge.
  6. Stream.runCollect produces the final array for the score / surface filter / public API.

The per-element transform lives in core/build-diagnostic-pipeline.ts and is shared with mergeAndFilterDiagnostics — there is no second copy of the chain.

runInspect orchestration

runInspect(input, hooks): Effect<RunInspectOutput, ReactDoctorError, Project | Config | DeadCode | Files | Linter | LintPartialFailures | Reporter | Score | HooksR>:

  1. Config.resolve(directory) → { config, resolvedDirectory }
  2. Project.discover(resolvedDirectory) → ProjectInfo (raises NoReactDependency when reactVersion === null)
  3. buildDiagnosticPipeline({ files: Files, ... }) → per-element transform
  4. Linter.lint(...) and DeadCode.compute(...) streams → Stream.tap(Reporter.emit) → folded counts
  5. Score.compute(...) over the surface-filtered subset
  6. Returns RunInspectOutput with project, userConfig, diagnostics, score, didLintFail, lintFailureReason, lintFailureReasonTag, lintPartialFailures, didDeadCodeFail, deadCodeFailureReason

RunInspectHooks<HooksR> is parametric on the hook environment so a caller can yield* AnyService from a hook (the CLI does this for Spinner).

Public API rewires

inspect.ts (CLI) — Loads config + merges options, then runs the runtime via Effect.runPromise. CLI-tailored layer stack: Linter.layerNoop for --no-lint / missing oxlint native binding, Linter.layerOxlint otherwise; Score.layerOffline for --offline; DeadCode.layerNode when options.deadCode is true, DeadCode.layerNoop otherwise; Spinner.layerNoop for --silent / --score / --json, Spinner.layerOra(oraFactory) otherwise. beforeLint / afterLint hooks drive the existing project-detection rendering and the lint spinner; a separate dead-code spinner line renders after lint finalizes.

index.ts (diagnose) — Preserves resolveDiagnoseTarget auto-fallback to nested React subprojects and resolveConfigRootDir redirect; AmbiguousProjectError still throws as itself. Wires DeadCode.layerNode / layerNoop based on options.deadCode. Returns skippedChecks + skippedCheckReasons to match the post-#291 public type.

Tests (31 new in runtime, all 1,202 react-doctor tests green)

  • diagnostic-schema.test.ts, json-report-schema.test.ts, errors.test.ts, pipeline.test.ts, tagged-errors.test.ts — schemas + tagged errors
  • run-inspect.test.ts — full orchestration with all-layerOf services + Files.layerInMemory + DeadCode.layerOf([]); mid-stream Stream.fail folds into didLintFail; missing React yields NoReactDependency; beforeLint / afterLint hooks fire in order
  • files.test.ts — layerInMemory exposes the four primitives
  • dead-code.test.ts — layerOf returns the supplied diagnostics; layerNoop returns []; service exposes Error-typed failure channel
  • spinner.test.ts — layerCapture / layerNoop / layerOra
  • reporter-ndjson.test.ts — Schema-encoded NDJSON line per emit
  • linter-composite.test.ts — backends concatenate; backends share the LintPartialFailures Ref via the runtime context

Verification

pnpm typecheck   # 12 packages green
pnpm test        # 1,233 tests pass (1,202 react-doctor + 31 runtime)
pnpm lint        # 0 warnings, 0 errors
pnpm format:check
pnpm build       # all packages, including website

CLI smoke test on tests/fixtures/basic-react:

$ node packages/react-doctor/dist/cli.js packages/react-doctor/tests/fixtures/basic-react --offline --no-lint
...
Dead Code 23 issues
  ⚠ Unused file ×22
  ⚠ Unused dependency
  React Doctor (www.react.doctor)
  Score unavailable in offline mode.
  23 issues across 23/22 files in 201ms

Dead-code diagnostics flow end-to-end through the streaming pipeline.

Commits on the branch (after rebase)

  1. chore: ignore .repos/ scratch directory for cloned reference repos
  2. feat(runtime): introduce @react-doctor/runtime — Effect v4 foundation
  3. feat(runtime): add Project, Config, Score services + runInspect orchestrator + LintPartialFailures
  4. refactor(react-doctor): rewire inspect() and diagnose() through the Effect runtime
  5. refactor: kill magic-string error sniffing across the lint boundary
  6. refactor(handle-error): render tagged ReactDoctorError via formatReactDoctorError
  7. feat(runtime): Files service + end-to-end streaming diagnostic pipeline
  8. feat(runtime): Cache.make config, Spinner / NDJSON / Composite layers + structural tag matching
  9. docs(runtime): drop Biome as the canonical Linter-swap example
  10. fix(runtime): scrub overstated and stale claims across docs and comments
  11. feat(runtime): integrate dead-code analysis as a Context.Service — new commit on top of the rebase

Packaging

  • @react-doctor/runtime is private (workspace, not published).
  • @react-doctor/core has [email protected] as a runtime dependency.
  • [email protected] is react-doctor's dependencies and neverBundle in vite.config.ts.
  • pnpm test runs --filter=react-doctor --filter=@react-doctor/runtime.

Out of scope (sensible follow-ups)

  • A real second linter backend (an in-process ESLint worker pool covering rules oxlint can't yet express, or a sandboxed runner for untrusted user config).
  • LSP host that replaces Reporter.layerCapture with a Reporter.layerLsp calling connection.sendDiagnostics per emit.
  • SARIF reporter for the GitHub Code Scanning integration.
  • Watch mode that uses Reporter.layerNdjson keyed by (filePath, contentHash) for incremental scans, with Stream cancellation per project.
  • Replace vi.mock("ora", …) in inspect.test.ts with a Spinner.layerCapture-driven test once inspect() exposes a layer-injection seam.
Open in Web Open in Cursor 

aidenybai avatar May 20 '26 19:05 aidenybai

0 score

Copy as prompt
Check if these React Review issues are valid. If so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.

Run this before and after your changes to verify the result:
npx react-doctor@latest --verbose --diff

Do not modify the react-doctor configuration unless explicitly asked.
Fix the underlying code issues instead of changing or suppressing the rules.

React Review found 0 errors and 2 warnings. This PR leaves the React health score unchanged.

<file name="packages/core/src/build-diagnostic-pipeline.ts">

<violation number="1" location="packages/core/src/build-diagnostic-pipeline.ts:59">
Severity: Warning

array.includes() in a loop is O(n) per call — convert to a Set for O(1) lookups

Use a `Set` or `Map` for repeated membership tests / keyed lookups — `Array.includes`/`find` is O(n) per call

Rule: `js-set-map-lookups`
</violation>

<violation number="2" location="packages/core/src/build-diagnostic-pipeline.ts:84">
Severity: Warning

array.includes() in a loop is O(n) per call — convert to a Set for O(1) lookups

Use a `Set` or `Map` for repeated membership tests / keyed lookups — `Array.includes`/`find` is O(n) per call

Rule: `js-set-map-lookups`
</violation>

</file>

Reviewed by reactreview for commit 2605bd6ed204a2f5ecb8b77d9187ea450e359cbf. Configure here.

react-doctor[bot] avatar May 20 '26 19:05 react-doctor[bot]

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
react-doctor-website Ready Ready Preview, Comment May 20, 2026 10:55pm

vercel[bot] avatar May 20 '26 19:05 vercel[bot]

Superseded by the merged Effect v4 stack: #421, #426, #427, #431, #432, #433, #434. The full Effect v4 runtime is now on main with the canonical v4 patterns (Context.Service, Schema.TaggedErrorClass union, ChildProcess via @effect/platform-node, Effect.catchReasons, Effect.Console-based renderers, NodeResolver / StagedFiles / Git / Files / Project / Config / Linter / DeadCode / Score / Reporter / Progress services). See AGENTS.md → Effect v4 Conventions for the current shape.

aidenybai avatar May 23 '26 02:05 aidenybai