Skip to content

feat: external analyzer protocol (JSON-RPC over stdin/stdout) for multi-language support #95

Closed

Description

@jflowers

Why

Gaze currently analyzes Go code exclusively, but its core value proposition — side effect detection, contract classification, CRAP scoring, test quality assessment — is language-agnostic. The taxonomy, scoring formulas, classification engine, reporting, TUI, and AI pipeline all work on abstract data structures that have no inherent dependency on Go.

There is active demand for Python analysis (the snake-eyes project), and the same architecture would support TypeScript, Rust, and other languages in the future.

Rather than reimplementing the entire gaze stack per language, gaze should become a universal core that delegates language-specific analysis to external analyzer processes via a well-defined protocol.

What Changes

New Capability: External Analyzer Protocol

Gaze gains the ability to spawn an external language analyzer process and communicate via JSON-RPC 2.0 over stdin/stdout — the same transport pattern used by the Language Server Protocol (LSP), but with gaze-specific methods.

Lifecycle:

gaze analyze --analyzer snake-eyes ./src
│
├─ 1. Find analyzer binary in PATH (or from .gaze.yaml config)
├─ 2. Spawn: snake-eyes --stdio
├─ 3. initialize → capabilities handshake
├─ 4. discover → find source + test files
├─ 5. analyze → detect side effects per function
├─ 6. complexity → cyclomatic complexity per function
├─ 7. coverage → parse language-specific coverage data
├─ 8. test_mapping → map assertions to effects (optional)
├─ 9. classify_signals → language-specific classification signals (optional)
├─ 10. shutdown → clean exit
└─ 11. Gaze computes CRAP, GazeCRAP, quadrants, fix strategies, renders reports

Protocol methods:

Method Required Direction Purpose
initialize Yes gaze → analyzer Handshake: root path, config, capabilities
discover Yes gaze → analyzer Find source files, test files, framework
analyze Yes gaze → analyzer Detect side effects per function
complexity Yes gaze → analyzer Cyclomatic complexity per function
coverage Yes gaze → analyzer Parse coverage data
test_mapping No gaze → analyzer Map test assertions to side effects
classify_signals No gaze → analyzer Language-specific classification signals
shutdown Yes gaze → analyzer Clean process exit

Capability negotiation: The initialize response declares which optional methods the analyzer supports. Gaze adapts its pipeline accordingly (e.g., skips test quality assessment if test_mapping is not supported).

New Capability: Analyzer Discovery

Analyzers are discovered via:

  1. CLI flag: --analyzer <name> explicitly names the binary
  2. Config: .gaze.yaml maps languages to analyzer binaries
  3. PATH convention: gaze-analyzer-<language> naming convention (fallback)

Example .gaze.yaml:

analyzers:
  python:
    command: snake-eyes
    args: ["--stdio"]

Internal Refactoring Required

To support external analyzers, several internal packages need their language-specific logic separated from their universal logic:

Package Universal (keep) Language-specific (extract)
taxonomy Effect types, tiers, priorities — (already universal)
classify Score computation, tier boosts, thresholds Signal detection (interface, visibility, callers, naming, godoc)
crap Formula, quadrants, fix strategies Coverage parsing (Go coverage format)
quality Contract coverage, over-spec scoring Assertion detection, assertion mapping, test pairing
analysis AnalysisResult assembly AST walking, SSA analysis

The Go-specific analysis becomes the built-in analyzer — gaze's existing behavior is preserved as the default when no external analyzer is specified. External analyzers provide the same data through the JSON-RPC protocol.

Impact

  • New packages: internal/protocol (JSON-RPC client), internal/adapter (external analyzer adapter)
  • Modified packages: cmd/gaze (CLI flags, analyzer dispatch), classify (separate scoring from signal detection), crap (separate formula from coverage parsing), quality (separate scoring from assertion detection)
  • New config options: analyzers section in .gaze.yaml
  • CLI changes: New --analyzer and --language flags on analyze, crap, quality, report commands
  • Backward compatible: When no external analyzer is configured, gaze behaves exactly as it does today (built-in Go analysis)

Constitution Alignment

I. Accuracy

Assessment: PASS — The protocol transmits raw analysis data (effects, coverage, complexity) to gaze's existing scoring engine. Accuracy of the universal scoring is preserved. Language-specific accuracy depends on the quality of the external analyzer, which is tested independently.

II. Minimal Assumptions

Assessment: PASS — The protocol makes minimal assumptions about the analyzer's language or implementation. Analyzers report standardized effect types, coverage data, and complexity metrics. No language-specific knowledge is required in gaze's core.

III. Actionable Output

Assessment: PASS — Reports produced from external analyzer data use the same formatting, fix strategies, and quadrant classification as Go analysis. The output is equally actionable regardless of source language.

IV. Testability

Assessment: PASS — The JSON-RPC protocol is inherently testable: mock analyzers can be written as simple scripts that emit canned responses. Each protocol method can be tested in isolation. The adapter layer can be tested without spawning real analyzer processes.

Open Questions

  1. Taxonomy evolution: Should the side effect taxonomy be generalized to accommodate language-specific effect types? (See related issue on taxonomy.)
  2. Protocol versioning: How should protocol versions be negotiated? Semantic versioning in the initialize handshake?
  3. Error handling: How should analyzer crashes, malformed responses, and partial results be handled? Graceful degradation (like SSA failures today) or hard errors?
  4. Streaming: Should analyze support streaming results (one function at a time) for large codebases, or batch response only?

Activity

  1. added
    enhancement
    on May 17, 2026
  2. moved this from Ready 🚀 to In Progress 📋 in Unbound Force Planningon Jun 22, 2026
  3. em-redhat commented on Jun 23, 2026

    @em-redhat
    Contributor

    Implementation Progress

    Phase 1: Provider Interface Extraction (PR #165) -- MERGED

    • Define 4 provider interfaces in internal/crap/provider.go (ComplexityProvider, LineCoverageProvider, SideEffectAnalyzer, ContractCoverageProvider)
    • Add FunctionComplexity type replacing gocyclo.Stat
    • Create Go adapters in internal/provider/goprovider/ (complexity, coverage, sideeffect, contract)
    • Refactor computeScores and lookupCoverage to accept FunctionComplexity
    • Refactor crap.Analyze to use provider interfaces from Options
    • Wire callers (cmd/gaze/main.go, internal/aireport/runner.go) to construct providers at call sites
    • Create mock providers in internal/provider/mockprovider/ (13 tests)
    • E2E self-check passes (byte-identical output)
    • Spec review passed (5 Divisor agents)
    • Code review passed (3 Divisor agents)
    • Fix CI: migrate coverageFunc test injection from deprecated ContractCoverageFunc to ContractCoverageProvider
    • Fix CI: update TestSC002 to use GoContractCoverageProvider instead of BuildContractCoverageFunc + deprecated field
    • Fix CI: single nolint on precedence test (intentionally tests deprecated fallback path)
    • Fix CI: add goprovider behavioral tests + decompose generateCoverProfile to reduce CRAPload from 41 to <=38
    • Fix review feedback: propagate SSA degradation from CRAP step to payload summary (bug: SSA degradation data from CRAP step not propagated to report payload summary #168)
    • CI green, PR merged

    Phase 2: JSON-RPC Protocol + External Adapters (PR #178) -- MERGED

    • JSON-RPC 2.0 client (internal/protocol/) — subprocess spawn, stdin/stdout communication, request/response matching
    • Protocol types — request/response schemas for all 8 methods (initialize, discover, analyze, complexity, coverage, test_mapping, classify_signals, shutdown)
    • Fake analyzer binary (internal/protocol/testdata/fake_analyzer/) for testing
    • External provider adapters (internal/adapter/) — 4 types implementing Phase 1 interfaces via protocol translation
    • Session manager — full lifecycle: spawn → initialize → analyze → shutdown
    • Capability negotiation — initialize response declares optional methods, adapters skip unsupported methods
    • Analyzer discovery — CLI flag → .gaze.yaml config → gaze-analyzer-<language> PATH convention
    • .gaze.yaml analyzers config section
    • CLI flags: --analyzer and --language on crap, quality, report commands
    • Error handling: graceful degradation for optional methods, hard error for required methods
    • Protocol specification document (docs/protocol.md) for analyzer authors
    • E2E test with fake analyzer: gaze crap --analyzer fake_analyzer
    • Website documentation issue for multi-language support
    • Fix review feedback: ContractCoverageInfo parity, Error.Error() dead branch, language validation, trust model docs
    • Fix review feedback: Close() shutdown state ordering bug, hide quality analyzer flags
    • CI green, PR merged

    Phase 3: Cleanup + Taxonomy Generalization + Streaming (PR #180) -- MERGED

    • Remove deprecated ContractCoverageFunc and SSADegradedPackages from crap.Options
    • Remove backward-compat fallback path in crap.Analyze
    • Update internal tests to use ContractCoverageProvider exclusively
    • Remove precedence test (TestMockProviders_ProviderPrecedence) — no longer has a subject
    • Deduplicate isMainPkg in goprovider/sideeffect.go — use loader.IsMainPkg
    • Move BuildContractCoverageFunc and helpers from internal/crap/contract.go to internal/provider/goprovider/contract.go
    • Verify internal/crap/ has zero Go-specific analysis imports
    • Taxonomy generalization: rename Metadata.GoVersion → LanguageVersion, add Language field, update JSON schemas
    • Add 7 language-neutral SideEffectType aliases (AsyncTaskSpawn, AsyncMessageSend, AsyncChannelClose, BarrierOp, PanicRecovery, FFICall, ObjectPoolOp)
    • Add LanguageVersion to protocol.InitializeResult and adapter.Providers
    • Streaming protocol: Streaming capability flag, analyze/stream method, CallStream on protocol client, JSONL support in ExternalSideEffectAnalyzer, fake analyzer --hang-stream mode
    • Update docs/protocol.md with streaming method and neutral type aliases
    • CI green, PR merged

    Status: All 3 phases complete

    All planned work for the external analyzer protocol is implemented and merged. The open questions from the original issue:

    1. Taxonomy evolution → Partially addressed in Phase 3 (language-neutral aliases, Language/LanguageVersion fields). Full universal taxonomy overhaul tracked separately in feat: generalize side effect taxonomy for multi-language support #96.
    2. Protocol versioning → Implemented via protocol_version field in initialize response.
    3. Error handling → Graceful degradation for optional methods, hard error for required methods, SSA degradation tracking.
    4. Streaming → Implemented as optional analyze/stream method with JSONL format (Phase 3).

    This issue can be closed. Remaining taxonomy work (universal abstract types, detail field) is tracked in #96.

  4. 4 remaining items

  5. added a commit that references this issue on Jun 30, 2026
  6. em-redhat commented on Jul 2, 2026

    @em-redhat
    Contributor

    All 3 phases merged: Phase 1 (PR #165 — provider interfaces), Phase 2 (PR #178 — JSON-RPC protocol + adapters), Phase 3 (PR #180 — cleanup, taxonomy generalization, streaming). Remaining taxonomy work (universal abstract types, detail field) tracked in #96.

  7. moved this from In Progress 📋 to Done ✔️ in Unbound Force Planningon Jul 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancement

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions