Repository navigation
feat: JSON-RPC external analyzer protocol for multi-language support (Phase 2 of #95) - #178
Conversation
yvonnedevlinrh
left a comment
There was a problem hiding this comment.
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)
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.
|
All four findings addressed in
|
jflowers
left a comment
There was a problem hiding this comment.
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).
jflowers
left a comment
There was a problem hiding this comment.
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).
| "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", "", |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
Addressed in 936fa98 alongside @gxmiranda's equivalent finding. Both flags now hidden via MarkHidden.
gxmiranda
left a comment
There was a problem hiding this comment.
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 onclient.go:228) - [MEDIUM]
--analyzerflag visible onquality --helpbut immediately errors (see inline comment onmain.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 throughexec.LookPathinNewClient(). Trust model GoDoc onDiscover()is thorough. - [LOW]
SideEffectAnalyzernot wired throughcrap.Options— consistent with D12 deferral, noted for Phase 3 - [LOW] Missing trailing newline in
proposal.mdandspec.md
This review was generated by /review-pr (AI-assisted).
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.
852881b to
562a232
Compare
…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.
gxmiranda
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
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.
f0f9cce to
6ecd602
Compare
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]>
…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]>
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/)Clientstruct managing subprocess lifecycle (spawn, stdin/stdout communication, shutdown)Call(ctx, method, params)withcontext.Contexttimeout supportinitialize,discover,analyze,complexity,coverage,test_mapping,classify_signals,shutdowninitializeresponsetestdata/fake_analyzer/for testingNew: External Provider Adapters (
internal/adapter/)ExternalComplexityProvider— translatescomplexityresponses to[]FunctionComplexityExternalLineCoverageProvider— translatescoverageresponses to[]FuncCoverageExternalSideEffectAnalyzer— translatesanalyzeresponses to[]AnalysisResultwith classificationExternalContractCoverageProvider— usestest_mapping+ComputeContractCoveragefor GazeCRAPSession— manages full protocol lifecycle, returns constructed adaptersDiscover— three-tier analyzer discovery (CLI flag →.gaze.yaml→ PATH convention)New: CLI Flags
--analyzer <binary>oncrap,quality,reportcommands--language <lang>for config/PATH-based discovery--analyzeris set, external adapters are used; when not set, behavior is identical to todayNew: Configuration
New: Protocol Specification
docs/protocol.md— full reference for external analyzer authorsBackward Compatibility
--analyzeris not specifiedTesting
OpenSpec Artifacts
openspec/changes/external-analyzer-protocol/— proposal, design, specs, tasks (27/27 complete)Ref: #95