Skip to content

feat: JSON-RPC external analyzer protocol for multi-language support (Phase 2 of #95) - #178

Merged
em-redhat merged 19 commits into
unbound-force:mainfrom
em-redhat:opsx/external-analyzer-protocol
Jun 30, 2026
Merged

em-redhat merged 19 commits into
unbound-force:mainfrom
em-redhat:opsx/external-analyzer-protocol

Conversation

@em-redhat

Copy link
Copy Markdown
Contributor

Summary

Phase 2 of Issue #95. Adds a JSON-RPC 2.0 over stdin/stdout protocol that lets gaze spawn external language analyzer binaries and produce CRAP scores, GazeCRAP, quadrants, and fix strategies for any language.

Builds on Phase 1 (PR #165) which extracted four provider interfaces from the scoring pipeline.

What Changed

New: JSON-RPC Protocol Client (internal/protocol/)

  • Client struct managing subprocess lifecycle (spawn, stdin/stdout communication, shutdown)
  • Call(ctx, method, params) with context.Context timeout support
  • 8 protocol methods: initialize, discover, analyze, complexity, coverage, test_mapping, classify_signals, shutdown
  • Capability negotiation via initialize response
  • Fake analyzer binary at testdata/fake_analyzer/ for testing

New: External Provider Adapters (internal/adapter/)

  • ExternalComplexityProvider — translates complexity responses to []FunctionComplexity
  • ExternalLineCoverageProvider — translates coverage responses to []FuncCoverage
  • ExternalSideEffectAnalyzer — translates analyze responses to []AnalysisResult with classification
  • ExternalContractCoverageProvider — uses test_mapping + ComputeContractCoverage for GazeCRAP
  • Session — manages full protocol lifecycle, returns constructed adapters
  • Discover — three-tier analyzer discovery (CLI flag → .gaze.yaml → PATH convention)

New: CLI Flags

  • --analyzer <binary> on crap, quality, report commands
  • --language <lang> for config/PATH-based discovery
  • When --analyzer is set, external adapters are used; when not set, behavior is identical to today

New: Configuration

# .gaze.yaml
analyzers:
  python:
    command: snake-eyes
    args: ["--stdio"]

New: Protocol Specification

docs/protocol.md — full reference for external analyzer authors

Backward Compatibility

  • Zero changes when --analyzer is not specified
  • All 16 packages pass tests
  • E2E self-check path unchanged
  • No new required dependencies

Testing

  • 16 protocol client tests (session, errors, timeout, crash recovery)
  • 11 adapter tests (translation, session lifecycle, capability negotiation)
  • 6 discovery tests (CLI flag, config, PATH, edge cases)
  • 3 CLI integration tests with fake analyzer
  • All existing tests pass (zero regression)

OpenSpec Artifacts

openspec/changes/external-analyzer-protocol/ — proposal, design, specs, tasks (27/27 complete)

Ref: #95

yvonnedevlinrh
yvonnedevlinrh previously approved these changes Jun 25, 2026

@yvonnedevlinrh yvonnedevlinrh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM — well-architected feature that cleanly adds multi-language support via JSON-RPC 2.0 protocol. The layering (protocol → adapter → provider interface) maintains clean separation of concerns, and the external path is properly isolated from the Go-native path. 36+ tests cover protocol lifecycle, adapter translation, discovery tiers, and CLI integration. Fully backward-compatible — no behavior change when --analyzer is not set.

One MEDIUM observation: buildContractLookup in internal/adapter/contract.go constructs ContractCoverageInfo with only Percentage, leaving Reason, MinConfidence, and MaxConfidence as zero values. The Go-native path populates these with diagnostic data (e.g., "all effects ambiguous, confidence 78-79"). External analyzer users will see contract coverage percentages but no explanation when coverage is 0%. Worth tracking for a follow-up to bring external output parity with Go-native output.

Three LOW observations (non-blocking):

  • Error.Error() in internal/protocol/types.go has a dead if branch — Data is checked but never included in the output (both branches return e.Message)
  • language parameter in internal/adapter/discovery.go is concatenated into exec.LookPath without validating it contains only [a-z0-9-] characters (theoretical, not exploitable — input comes from CLI flag or config)
  • Trust model for config-sourced binary execution (analyzers..command in .gaze.yaml) is not documented — same trust model as Makefile/goreleaser, but a comment would improve transparency

APPROVE

Reviewed-by: yvonnedevlinrh
Assisted-by: OpenCode (claude-opus-4-6)

em-redhat added a commit to em-redhat/gaze that referenced this pull request Jun 25, 2026
1. ContractCoverageInfo parity: buildContractLookup now populates
   Reason, MinConfidence, MaxConfidence via deriveCoverageReason
   helper, matching Go-native output diagnostics.

2. Error.Error() dead branch: include Data field in error string
   when non-nil (was returning e.Message in both branches).

3. Language validation: add regex check for [a-z0-9-] before using
   language parameter in exec.LookPath binary name construction.

4. Trust model documentation: add GoDoc comment to Discover
   explaining the subprocess trust model (same as Makefile/goreleaser).

Addresses PR unbound-force#178 review feedback from @yvonnedevlinrh.
@em-redhat

Copy link
Copy Markdown
Contributor Author

All four findings addressed in 131cd1f:

  1. ContractCoverageInfo parity — buildContractLookup now populates Reason, MinConfidence, MaxConfidence via deriveCoverageReason helper. Detects all_effects_ambiguous (with confidence range) and no_effects_detected cases, matching Go-native output.

  2. Error.Error() dead branch — Data field now included in error string when non-nil: fmt.Sprintf("%s: %v", e.Message, e.Data).

  3. Language validation — Added validLanguage regex (^[a-z0-9][a-z0-9-]*$) check before exec.LookPath construction.

  4. Trust model — Added GoDoc comment to Discover documenting the subprocess trust model (same as Makefile/goreleaser — user-configured binary, user permissions, no sandbox).

@em-redhat
em-redhat requested a review from yvonnedevlinrh June 25, 2026 12:03
jflowers
jflowers previously approved these changes Jun 26, 2026

@jflowers jflowers left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

APPROVE — Well-architected feature that cleanly adds multi-language support via JSON-RPC 2.0 protocol.

The layering (protocol → adapter → provider interface) maintains clean separation of concerns, and the external path is properly isolated from the Go-native path. 36+ tests cover protocol lifecycle, adapter translation, discovery tiers, and CLI integration. Fully backward-compatible — no behavior change when --analyzer is not set.

Prior reviewer's four findings (ContractCoverageInfo parity, Error.Error() dead branch, language validation, trust model docs) have all been addressed in commit 131cd1f.

One LOW inline comment on the quality command's --analyzer flag visibility.

This review was generated by /review-pr (AI-assisted).

Comment thread cmd/gaze/main.go Resolved
jflowers
jflowers previously approved these changes Jun 26, 2026

@jflowers jflowers left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

APPROVE — Post-merge-resolution re-review.

The merge conflict resolution (integrating analyze-multi-package from upstream) is clean and correct. The --analyzer rejection guard in runQuality fires before the multi-package logic. The test was correctly updated to use the new patterns field. All local checks pass (build, vet, lint, 16 packages with -race -count=1 -short).

The core feature (JSON-RPC external analyzer protocol) was reviewed in the previous cycle. Prior reviewer's four findings were all addressed. One LOW finding carried forward (see inline comment).

This review was generated by /review-pr (AI-assisted).

Comment thread cmd/gaze/main.go
"AI backend for assertion mapping fallback: claude, gemini, ollama, or opencode")
cmd.Flags().StringVar(&aiMapperModel, "ai-mapper-model", "",
"model name for AI mapper (required for ollama)")
cmd.Flags().StringVar(&analyzerFlag, "analyzer", "",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW] Consider hiding --analyzer on quality until supported.

The --analyzer and --language flags are registered on the quality command but immediately error when used (deferred per D12). Consider adding _ = cmd.Flags().MarkHidden("analyzer") and _ = cmd.Flags().MarkHidden("language") after registration to avoid confusing users browsing --help.

Non-blocking — the error message is clear and informative. Previously raised in the dismissed review.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 936fa98 alongside @gxmiranda's equivalent finding. Both flags now hidden via MarkHidden.

@gxmiranda gxmiranda left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

COMMENT — Well-architected feature that cleanly adds multi-language support via JSON-RPC 2.0 protocol.

The layering (protocol → adapter → provider interface) maintains clean separation of concerns, and the external path is properly isolated from the Go-native path. 36+ tests cover protocol lifecycle, adapter translation, discovery tiers, and CLI integration. Fully backward-compatible — no behavior change when --analyzer is not set.

All 4 constitution principles verified (Accuracy, Minimal Assumptions, Actionable Output, Testability) — PASS on all. Prior reviewer findings (ContractCoverageInfo parity, Error.Error() dead branch, language validation, trust model docs) were all addressed.

Findings: 1 HIGH, 2 MEDIUM, 2 LOW.

  • [HIGH] Close() never sends shutdown request due to state ordering bug (see inline comment on client.go:228)
  • [MEDIUM] --analyzer flag visible on quality --help but immediately errors (see inline comment on main.go:1452; previously raised by @jflowers)
  • [MEDIUM] Discover() Tier 1 skips language validation for CLI flag path — low-risk since value is user-controlled, and goes through exec.LookPath in NewClient(). Trust model GoDoc on Discover() is thorough.
  • [LOW] SideEffectAnalyzer not wired through crap.Options — consistent with D12 deferral, noted for Phase 3
  • [LOW] Missing trailing newline in proposal.md and spec.md

This review was generated by /review-pr (AI-assisted).

Comment thread internal/protocol/client.go Resolved
Comment thread cmd/gaze/main.go Resolved
em-redhat added a commit to em-redhat/gaze that referenced this pull request Jun 29, 2026
1. ContractCoverageInfo parity: buildContractLookup now populates
   Reason, MinConfidence, MaxConfidence via deriveCoverageReason
   helper, matching Go-native output diagnostics.

2. Error.Error() dead branch: include Data field in error string
   when non-nil (was returning e.Message in both branches).

3. Language validation: add regex check for [a-z0-9-] before using
   language parameter in exec.LookPath binary name construction.

4. Trust model documentation: add GoDoc comment to Discover
   explaining the subprocess trust model (same as Makefile/goreleaser).

Addresses PR unbound-force#178 review feedback from @yvonnedevlinrh.
@em-redhat
em-redhat force-pushed the opsx/external-analyzer-protocol branch from 852881b to 562a232 Compare June 29, 2026 10:12
em-redhat added a commit to em-redhat/gaze that referenced this pull request Jun 29, 2026
…lyzer flags

1. Close() shutdown bug (HIGH from @gxmiranda): Close() set
   closed=true before calling Call(), causing the shutdown request
   to be silently rejected. Added sendShutdown() method that
   bypasses the closed-state guard, allowing Close() to send the
   final shutdown JSON-RPC message before closing stdin.

2. Quality flag hiding (MEDIUM from @gxmiranda, LOW from @jflowers):
   --analyzer and --language flags on gaze quality are deferred per
   D12 but were visible in --help. Added MarkHidden() calls.

Addresses PR unbound-force#178 review feedback.
@em-redhat
em-redhat requested review from gxmiranda and jflowers June 29, 2026 10:53

@gxmiranda gxmiranda left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

APPROVE — Well-architected feature that cleanly adds multi-language support via JSON-RPC 2.0 protocol.

The layering (protocol → adapter → provider interface) maintains clean separation of concerns, and the external path is properly isolated from the Go-native path. 36+ tests cover protocol lifecycle, adapter translation, discovery tiers, and CLI integration. Fully backward-compatible — no behavior change when --analyzer is not set.

All prior reviewer findings (Close() shutdown bug, ContractCoverageInfo parity, Error.Error() dead branch, language validation, trust model docs, hidden quality flags) have been addressed in subsequent commits.

Constitution compliance verified: Accuracy (scoring engine unchanged), Minimal Assumptions (protocol is language-agnostic), Actionable Output (same formatting/fix strategies), Testability (fake binary + DI throughout).

3 LOW observations (non-blocking): missing trailing newlines in spec artifacts, SideEffectAnalyzer not wired to crap.Options (consistent with D12 deferral), verbose containsAll helper in tests.

This review was generated by /review-pr (AI-assisted).

@marcusburghardt marcusburghardt left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nice work @em-redhat

config.Load accepted out-of-range and inverted classification
thresholds from .gaze.yaml without error, silently degrading
classification output. The [1,99] range check and coherence
check existed only in the CLI layer, bypassed by config-file
and non-CLI callers (loadGazeConfigBestEffort).

- Add contractual/incidental range validation [1, 99]
- Add coherence check (contractual > incidental)
- Add 10 unit tests with dedicated YAML fixtures
- Update CLI test assertion for new error path

Closes unbound-force#114
… 2 of unbound-force#95)

JSON-RPC 2.0 over stdin/stdout protocol for multi-language support.
Builds on provider-interfaces (Phase 1, PR unbound-force#165) which extracted
four provider interfaces from the CRAP scoring pipeline.

Phase 2 adds:
- internal/protocol/ — JSON-RPC client for analyzer subprocess
- internal/adapter/ — external provider adapters bridging protocol
  responses to Phase 1 interfaces
- --analyzer and --language CLI flags
- .gaze.yaml analyzers configuration section
- Protocol specification for external analyzer authors

8 task groups, 30 tasks total.

Ref: unbound-force#95
Implement the protocol layer for communicating with external analyzer
binaries over stdin/stdout (design decisions D1, D8, D10):

- internal/protocol/types.go: JSON-RPC 2.0 message types (Request,
  Response, Error), protocol method constants for all 8 methods,
  InitializeParams/Result, Capabilities with Discover/TestMapping/
  ClassifySignals booleans, and all response types (AnalyzeResult,
  ComplexityResult, CoverageResult, DiscoverResult, TestMappingResult,
  ClassifySignalsResult) with full JSON tags.

- internal/protocol/client.go: Client struct managing subprocess
  lifecycle (exec.Cmd, stdin writer, stdout scanner, stderr buffer).
  NewClient spawns the binary via exec.LookPath. Call sends JSON-RPC
  requests and reads responses with context.Context timeout support.
  Close sends shutdown and waits for process exit. Atomic request ID
  counter and mutex for sequential request/response.

- internal/protocol/testdata/fake_analyzer/main.go: Test double that
  reads JSON-RPC from stdin, writes canned responses to stdout.
  Supports all 8 methods with deterministic data (add/2, multiply/3,
  divide/5 complexity; add/90%, multiply/60%, divide/0% coverage;
  divide has ReturnValue+ErrorReturn effects). Flags: --stdio,
  --crash-after, --hang, --malformed-json, --error-response.

- internal/protocol/client_test.go: 7 tests covering successful
  full session, binary not found, crash mid-session, malformed JSON,
  JSON-RPC error propagation, timeout, and optional methods. All
  pass with -race -count=1.

Tasks 1.1-1.4 complete.
Add types_test.go with 9 round-trip tests verifying marshal/unmarshal
fidelity for all protocol types:

- TestRoundTrip_InitializeResult: capabilities, version, name, language
- TestRoundTrip_AnalyzeResult: functions with side effects and
  classification (including nil classification for add)
- TestRoundTrip_ComplexityResult: 3 functions with complexity values
- TestRoundTrip_CoverageResult: 3 functions with coverage percentages,
  covered/total stmts
- TestRoundTrip_DiscoverResult: source files, test files, framework
- TestRoundTrip_TestMappingResult: assertion-to-effect mappings
- TestRoundTrip_ClassifySignalsResult: classification signals
- TestRoundTrip_Request: JSON field presence verification
- TestRoundTrip_Response: success and error variants

All 16 tests pass with -race -count=1. Mark tasks 1.1-1.4 and
2.1-2.2 complete in tasks.md.
em-redhat added 13 commits June 30, 2026 10:51
Implement four provider adapters in internal/adapter/ that translate
JSON-RPC protocol responses into Phase 1 provider interface types:

- ExternalComplexityProvider (crap.ComplexityProvider)
- ExternalLineCoverageProvider (crap.LineCoverageProvider)
- ExternalSideEffectAnalyzer (crap.SideEffectAnalyzer)
- ExternalContractCoverageProvider (crap.ContractCoverageProvider)

Add Session struct managing full protocol lifecycle: spawn binary,
initialize handshake, construct provider adapters, shutdown.

Side effect adapter caches whole-project results and filters by
pkgPath. Contract coverage adapter uses quality.ComputeContractCoverage
when test_mapping capability is true; returns no-op lookup when false.

Tests use the fake analyzer binary from internal/protocol/testdata/
to validate: adapter output correctness, session lifecycle, optional
method skipping, and error propagation.
Add three-tier analyzer discovery in internal/adapter/discovery.go:
1. CLI flag (--analyzer <name>) overrides everything
2. Config (.gaze.yaml analyzers.<language>.command)
3. PATH convention (gaze-analyzer-<language>)

Add AnalyzersConfig and AnalyzerEntry types to internal/config/config.go
for mapping languages to analyzer binaries in .gaze.yaml:

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

Tests cover: CLI flag override, config lookup, PATH fallback,
no analyzer found (Go default), no language provided, and
CLI flag without language.

Mark tasks 3.1-3.6 and 4.1-4.3 complete in tasks.md.
…rt (Phase 5)

Add --analyzer and --language CLI flags to crap, quality, and report
commands. When --analyzer is set, Gaze spawns the external analyzer
binary, performs the JSON-RPC initialize handshake, and uses external
provider adapters for complexity, coverage, and contract coverage
instead of Go-specific providers.

- runCrapWithExternalAnalyzer: new function for external analyzer path
- buildExternalReportAnalyzeFunc: creates AnalyzeFunc override for
  gaze report with external providers
- runQuality with --analyzer: returns informative error (deferred per D12)
- TestCrapWithExternalAnalyzer: integration test with fake analyzer binary
  verifying CRAP scores match expected values from canned data
- TestCrapWithExternalAnalyzer_NotFound: error path test
- TestQualityWithExternalAnalyzer_Rejected: deferred feature test

Closes unbound-force#95 (Phase 5)
…se 7)

- README.md: add Multi-Language Support section with --analyzer usage,
  .gaze.yaml config examples, and three-tier discovery explanation
- AGENTS.md: add internal/protocol/ and internal/adapter/ to architecture
  diagram and key patterns; add external-analyzer-protocol to Recent Changes
- docs/protocol.md: full protocol specification for external analyzer
  authors covering JSON-RPC message format, 8 methods with request/response
  schemas, capability negotiation, error handling, lifecycle diagram,
  side effect type mapping table, and minimal Python example
- Created GitHub issue unbound-force/website#165 for website docs updates
- session.Close(): wrap in defer func with blank identifier
- fmt.Fprintf warnings: assign returns to _, _
- os.RemoveAll in test: replace with t.TempDir()
- README.md: rename duplicate 'Configuration' heading to
  'Analyzer Configuration' (MD024)
- client.Close() in protocol tests: 6 occurrences wrapped
- client.Close() in adapter tests: 7 occurrences wrapped
- Remove unused timeout field from ExternalComplexityProvider
- Fix unchecked fmt.Fprintf in fake_analyzer test binary
Decompose high-complexity external analyzer functions to bring
CRAPload from 41 to <=38:

- Extract initExternalSession, wireExternalProviders,
  emitExternalCrapNotes, finishExternalCrapReport,
  runExternalReportCRAP from runCrapWithExternalAnalyzer and
  buildExternalReportAnalyzeFunc
- Extract fetchTestMappings, noopLookup, warn from
  ExternalContractCoverageProvider.Build
- Remove testing.Short guard from TestCrapWithExternalAnalyzer
  (runs in 1.2s with fake binary, safe for -short mode)
1. ContractCoverageInfo parity: buildContractLookup now populates
   Reason, MinConfidence, MaxConfidence via deriveCoverageReason
   helper, matching Go-native output diagnostics.

2. Error.Error() dead branch: include Data field in error string
   when non-nil (was returning e.Message in both branches).

3. Language validation: add regex check for [a-z0-9-] before using
   language parameter in exec.LookPath binary name construction.

4. Trust model documentation: add GoDoc comment to Discover
   explaining the subprocess trust model (same as Makefile/goreleaser).

Addresses PR unbound-force#178 review feedback from @yvonnedevlinrh.
Extract confidenceRange helper and use min/max builtins to reduce
branch count. deriveCoverageReason: complexity 7→3,
confidenceRange: complexity 3 (below CRAP 15 at 0% coverage).
…lyzer flags

1. Close() shutdown bug (HIGH from @gxmiranda): Close() set
   closed=true before calling Call(), causing the shutdown request
   to be silently rejected. Added sendShutdown() method that
   bypasses the closed-state guard, allowing Close() to send the
   final shutdown JSON-RPC message before closing stdin.

2. Quality flag hiding (MEDIUM from @gxmiranda, LOW from @jflowers):
   --analyzer and --language flags on gaze quality are deferred per
   D12 but were visible in --help. Added MarkHidden() calls.

Addresses PR unbound-force#178 review feedback.
sendShutdown() writes directly without a context timeout,
making the shutdownTimeout const unused. Fixes golangci-lint
unused error.
@em-redhat
em-redhat force-pushed the opsx/external-analyzer-protocol branch from f0f9cce to 6ecd602 Compare June 30, 2026 09:51
@em-redhat
em-redhat merged commit 105eb12 into unbound-force:main Jun 30, 2026
5 checks passed
@em-redhat
em-redhat deleted the opsx/external-analyzer-protocol branch June 30, 2026 10:23
sonupreetam pushed a commit to sonupreetam/gaze that referenced this pull request Aug 12, 2026
1. ContractCoverageInfo parity: buildContractLookup now populates
   Reason, MinConfidence, MaxConfidence via deriveCoverageReason
   helper, matching Go-native output diagnostics.

2. Error.Error() dead branch: include Data field in error string
   when non-nil (was returning e.Message in both branches).

3. Language validation: add regex check for [a-z0-9-] before using
   language parameter in exec.LookPath binary name construction.

4. Trust model documentation: add GoDoc comment to Discover
   explaining the subprocess trust model (same as Makefile/goreleaser).

Addresses PR unbound-force#178 review feedback from @yvonnedevlinrh.

Signed-off-by: sonupreetam <[email protected]>
sonupreetam pushed a commit to sonupreetam/gaze that referenced this pull request Aug 12, 2026
…lyzer flags

1. Close() shutdown bug (HIGH from @gxmiranda): Close() set
   closed=true before calling Call(), causing the shutdown request
   to be silently rejected. Added sendShutdown() method that
   bypasses the closed-state guard, allowing Close() to send the
   final shutdown JSON-RPC message before closing stdin.

2. Quality flag hiding (MEDIUM from @gxmiranda, LOW from @jflowers):
   --analyzer and --language flags on gaze quality are deferred per
   D12 but were visible in --help. Added MarkHidden() calls.

Addresses PR unbound-force#178 review feedback.

Signed-off-by: sonupreetam <[email protected]>
@yvonnedevlinrh yvonnedevlinrh moved this from In Review 🏁 to Done ✔️ in Unbound Force Planning Aug 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done ✔️

Development

Successfully merging this pull request may close these issues.

5 participants