TypeScript analyzer backend for Gaze.
Reading Stone is a Gaze-spawned subprocess. It speaks JSON-RPC 2.0 over stdin/stdout (protocol v1.2.0). Gaze owns the CLI, scoring, and reports.
| Method | Status |
|---|---|
initialize |
Implemented |
shutdown |
Implemented |
discover |
Implemented (params {root_path}; result {source_files, test_files, framework}) |
analyze |
Implemented (params {root_path, patterns}; result {"functions": [...]} — FunctionRecords with side_effects arrays, every effect carrying classification: {label, confidence}) |
analyze/stream |
Not implemented (-32601) |
complexity |
Implemented (params {root_path, patterns}; result {"functions": [...]} — ComplexityEntry records) |
coverage |
Implemented (params {root_path, patterns}; result {"functions": [...]} — CoverageEntry records) |
classify_signals |
Implemented (params {root_path, patterns}; result {"signals": [...]} — the raw classification signal feed) |
test_mapping |
Implemented (params {root_path, patterns}; result {"mappings": [...]} — test-to-assertion MappingRows with pairing confidences and side_effect_type inference) |
doc_coverage |
Implemented (params {root_path, patterns}; result {"symbols": [...]} — SymbolRows with the closed kind set `function |
cognitive_complexity |
Implemented (params {root_path, patterns}; result {"functions": [...]} — CognitiveRows with SonarSource cognitive complexity scores) |
discover is implemented and advertised via capabilities.discover: true.
analyze, complexity, and coverage are implemented as core protocol
methods — not gated behind a capability flag — and share one params surface:
root_path plus an optional patterns array of path-prefix strings.
classify_signals is implemented and advertised via
capabilities.classify_signals: true; Gaze calls it only when that flag is
true, with the same params surface. test_mapping is implemented and
advertised via capabilities.test_mapping: true the same way.
doc_coverage and cognitive_complexity are implemented and advertised
via capabilities.doc_coverage: true and
capabilities.cognitive_complexity: true the same way. The remaining
capability flag (streaming) is false at handshake, with
analyze/stream the sole reserved method (-32601).
The side effects analyze reports are governed by the disposition table:
for each of the 48 canonical taxonomy types it records the tier, the
disposition (how completely Reading Stone detects it), the TypeScript
constructs detected, and the rationale for N/A rows — see
docs/effect-disposition.md.
Every effect in an analyze response carries a
classification: {label, confidence} computed by a deterministic signal
pipeline that runs per (function, effect-type) pair. Six signal sources
produce the evidence — five extractors plus one synthesized penalty:
interface— the function satisfies a declared interface member (+30)visibility— exported function (+8), exported return type (+6), exported receiver (+6), clamped at +20caller_count— 1, 2–3, or 4+ distinct modules calling the function (+5/+10/+15; zero callers emits no signal)naming_convention— contractual or incidental name prefixes (±10), plus anErr-prefixed name on aSentinelErroreffect (+30)docstring— JSDoc@returns/@throwstags (+15), indirect prose verbs (+5), incidental verbs (−15)contradiction— synthesized (−20) when a pair's evidence mixes positive and negative weights
Confidence is 50 + tier_boost + Σ(signal weights) − 20 when a
contradiction is present (tier_boost: +25 for P0, +10 for P1, +0 for
P2–P4), clamped to [0, 100]. Labels derive from the clamped confidence:
contractual ≥ 80, ambiguous [50, 80), incidental < 50. An effect with
no matching signals is never dropped — it classifies at the ambiguous floor
(50 + tier_boost).
Without a usable tsconfig.json (parse-only mode), the three
checker-dependent components — the interface signal, the caller_count
signal, and the exported-return-type (+6) component of visibility — are
absent, so classifications drift toward ambiguous; every effect is still
classified (degradation reduces precision, never availability).
The classify_signals method returns the raw feed behind those
classifications: one signal per matched (function, effect-type, source)
triple — function, package, side_effect_type, source, integer
weight, and a short reasoning — deterministically ordered by
(package, function, side_effect_type, source). Both methods share one
pipeline: summing a pair's emitted signal weights (the contradiction row
included) back into 50 + tier_boost reproduces the confidence analyze
reports.
Requires Node.js 22+.
npm i -g reading-stoneThe package's only runtime dependency is typescript, pinned exactly
(currently 7.0.2): Reading Stone uses the compiler's
typescript/unstable/* API, which carries no semver stability
guarantee, so the pin moves only in a Reading Stone release. It is
independent of the TypeScript version the analyzed project uses.
npm install
npm run build
node dist/main.js --stdioThe package installs two bin entry points that both launch the JSON-RPC analyzer over stdin/stdout:
reading-stone— the primary entry point.gaze-analyzer-typescript— an alias that Gaze's tier-3 PATH auto-discovery looks for; either name works in.gaze.yaml.
Gaze auto-discovers external analyzers by PATH naming convention:
run gaze with --language typescript (e.g.
gaze quality --language typescript ./src) and any
gaze-analyzer-typescript on PATH is used automatically — no
.gaze.yaml needed. Gaze does not infer the project language, so
without the flag it falls back to its built-in Go analysis. The
global install puts the alias on PATH alongside reading-stone.
To name the analyzer explicitly in .gaze.yaml, point it at the
convention binary:
analyzers:
typescript:
command: gaze-analyzer-typescript
args: ["--stdio"]Gaze spawns a .gaze.yaml entry with exactly the configured args —
the args: ["--stdio"] line is required. The other two discovery
tiers, the --analyzer CLI flag and the gaze-analyzer-typescript
PATH convention, get --stdio passed automatically by Gaze.
To dogfood from a checkout: npm install && npm run build && npm link
puts the same two bins on PATH.
reading-stone/
├── src/
│ ├── index.ts # Package surface (VERSION + taxonomy/model/signal/mapping/doc-coverage/cognitive re-exports)
│ ├── main.ts # Entry point (reading-stone --stdio)
│ ├── server.ts # JSON-RPC server (stdin/stdout)
│ ├── protocol.ts # Request/response types
│ ├── taxonomy.ts # Side-effect taxonomy (48 types, tiers, aliases)
│ ├── models.ts # Effect/FunctionRecord/classification records, serializers, derivePackage
│ ├── safeio.ts # Bounded safe file reader with skip diagnostics
│ ├── discovery.ts # Project walking, file classification, framework detection, discover()
│ ├── analysis.ts # Pattern rules + shared prepareAnalysis pipeline; analyze() and classifySignals() entries
│ ├── program.ts # TypeScript analysis context (program mode with type checker; parse-only fallback)
│ ├── extract.ts # Table-driven function extraction (ExtractionRecord set)
│ ├── detector.ts # Side-effect detection rules + FunctionRecord assembly
│ ├── complexity.ts # Cyclomatic complexity engine (ComplexityEntry)
│ ├── cognitive.ts # SonarSource cognitive complexity engine (CognitiveRow)
│ ├── coverage.ts # Coverage artifact parser: Istanbul coverage-final.json or lcov.info (CoverageEntry)
│ ├── lcov.ts # lcov tracefile parser (SF/DA/end_of_record records)
│ ├── doc-coverage.ts # Exported-symbol documentation coverage (SymbolRow, symbol-surface walk)
│ ├── quality/ # Test-mapping pipeline (test_mapping method)
│ │ ├── assertions.ts # Assertion detection (vitest/jest expect chains, node:assert forms)
│ │ ├── collect.ts # Test-function collection (it/test/describe walk, qualified titles)
│ │ ├── inference.ts # Assertion-to-effect inference (fallback chains + four provenance passes)
│ │ ├── matchers.ts # Normative matcher tables + classification lookups
│ │ ├── pairing.ts # Test-target pairing strategies (naming 90/70, calls 80, imports 75)
│ │ ├── pipeline.ts # testMapping() orchestration over the shared prepareAnalysis test arm
│ │ └── types.ts # MappingRow wire record + serializer (closed assertion-kind set)
│ └── signals/ # Classification signal pipeline (classify_signals + analyze wiring)
│ ├── adapter.ts # Pair fan-out, contradiction synthesis, confidence formula (classifyPairs)
│ ├── caller-index.ts # Import-graph caller index (distinct-module counts via the type checker)
│ ├── caller.ts # caller_count bucket rule (+5/+10/+15)
│ ├── evidence.ts # RecordEvidence snapshot (exportedness, JSDoc, interface, callers)
│ ├── interface.ts # interface signal (+30)
│ ├── jsdoc.ts # docstring signal (+15 tags / +5 indirect / -15 incidental)
│ ├── naming.ts # naming_convention signal (prefix rules + Err sentinel case)
│ ├── routing.ts # Effect-type routing table (48 types → agreeing vocabulary)
│ ├── types.ts # Signal wire record + serializer (closed source set)
│ └── visibility.ts # visibility signal (exported components, clamp +20)
├── tests/
├── docs/
│ └── effect-disposition.md # 48-type disposition table (tier, disposition, TypeScript mapping, rationale)
├── openspec/
├── package.json
├── tsconfig.json
├── biome.json
└── NOTICE
Reading Stone performs static analysis only on untrusted source and enforces fixed transport bounds (not configurable in v1):
- Line size cap — request lines longer than 16 MiB (
MAX_LINE_CHARS) are rejected with-32600before parsing. - Method echo cap — the method name echoed in
-32601responses is truncated to 64 characters. - Coverage semantics — the
coveragemethod reads one pre-existing artifact at a fixed location: the Istanbul document<root>/coverage/coverage-final.jsonwhen it exists, otherwise the lcov tracefile<root>/coverage/lcov.info(spec 006). Istanbul always wins when present, even if it is invalid — there is no fallback to lcov. From lcov, functions are the same recordscomplexityreports, andcovered_stmts/total_stmtscount executable lines (DArecords); a line shared by a function and a nested one counts for both. When no usable artifact exists,coveragereturns{"functions": []}and never errors (FR-025). It never runs the project's tests. - Per-request pipeline cost — each
analyze,complexity,classify_signals,test_mapping,doc_coverage, orcognitive_complexityrequest boots a fresh TypeScript compiler context (tree walk, pre-read, bootstrap, extraction) and disposes it before responding; no pipeline state is reused across requests.coveragefrom Istanbul reads a pre-existing artifact and is cheap;coveragefrom lcov also runs the analysis pipeline to find function boundaries, at about the cost ofcomplexity. - Assertion-library scope — the
test_mappingmethod collects assertions from vitest/jestexpect(...)chains andnode:assertforms only; chai, should.js, and other assertion libraries are never collected (fixed scope, v1). - Doc-surface scope — the
doc_coveragemethod walks the exported module surface plus public members of exported classes; non-exported declarations, private/protected/#privatemembers, re-exports, namespaces, and interface members are out of scope, and overload documentation counts only on the implementation signature.doc_snippetis omitted when absent, never empty (fixed scope, v1). - Cognitive-complexity scope — the
cognitive_complexitymethod scores SonarSource cognitive complexity with the documented divergences from Gaze's Go port: conditions are walked, ternaries are scored, labeled breaks are counted, and nesting resets at anonymous function boundaries; the SonarJS lint carve-outs are not applied (fixed scope, v1). - Parse-only pairing degradation — without a usable
tsconfig.json,test_mappingpairs through lexical import/call matching: barrel re-exports are uncrossed and same-named bindings can collide, so pairing precision drops while rows and confidences stay available (degradation reduces precision, never availability). - Same-titled sibling tests — two tests sharing one title inside a
describeblock share the identicaltest_functionvalue; their rows stay distinct throughassertion_location. - Wire-key pair collapse — same-named targets in one file, or in
different files whose paths derive one package (for example
pkg.tsvspkg/index.ts), are wire-indistinguishable (target_package+target_function); rows emit only for the first record in analyze record order — a documented conservative imprecision, never duplicate rows.
Empty coverage results usually mean no artifact exists yet: run the
project's own test command with coverage first, then request coverage.
vitest and jest need an Istanbul JSON reporter writing
coverage/coverage-final.json; Bun writes lcov with
bun test --coverage --coverage-reporter=lcov; node:test writes lcov with
node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=coverage/lcov.info. With neither artifact,
Reading Stone writes one stderr line naming both paths. When the
document parses but no file entry matches the Istanbul shape, or entries
are skipped for size (per-file record caps, or the document-level
attribution work budget), Reading Stone says so on stderr — one line per
skipped document or file — while stdout still carries only the JSON-RPC
response. The same holds for lcov: a tracefile with no conforming record,
or one whose last record lacks end_of_record (the complete records
still report), gets one stderr line.
The read-don't-run coverage behavior is a deliberate, recorded divergence from the Gaze analyzer protocol (FR-025), which frames coverage as the analyzer being responsible for running the project's tests. Reading Stone is static-analysis-only (Constitution Principle V — analyzed code is never executed), so it consumes the artifact — Istanbul JSON or lcov — the project's own test run produced instead of producing one itself.
When input is malformed, Reading Stone emits a one-line diagnostic to stderr and continues. stdout carries only the JSON-RPC response.
Releases are tagged, staged, and given a GitHub release by CI, and
published to npm by a maintainer.
Release tags are created by the release workflow and can't be deleted
or moved afterward (the release-tag-protection ruleset). Nothing
reaches npm without a human 2FA approval.
The version comes from the tag alone. package.json on main holds
the placeholder 0.0.0-development; nothing is bumped by hand.
- Run the
releaseworkflow frommainwith the new tag (Actions → release → Run workflow, orgh workflow run release.yml -f tag=vX.Y.Z). It calls the shared npm pipeline injflowers/ship, which runs the release preflight (semver, uniqueness, ordering, CI status, unreleased commits) and creates the annotated tag. The stage job then checks out the tag, reruns the CI gates, sets the package version toX.Y.Z(not committed), and runsnpm stage publish --provenancethrough npm trusted publishing (OIDC, no tokens). Last, it creates the GitHub release with generated notes. Prerelease tags stage under thenextdist-tag and get a GitHub prerelease. - Approve the staged version on npmjs.com (Staged Packages) or with
npm stage approve <stage-id>(npm 11.15.0 or newer, e.g.npx -y [email protected] stage approve <stage-id>). Both require 2FA. The version goes public at this step; it is the only approval.
Re-running the workflow is safe: a version already on npm is not
restaged, and an existing GitHub release is left unchanged. If you
reject a staged version (npm stage reject <stage-id>), delete its
GitHub release by hand (gh release delete vX.Y.Z); the tag stays.
Apache 2.0 -- see LICENSE. The JSON-RPC protocol layer, the classification signal pipeline design, the test-mapping pipeline design (pairing strategies and pinned confidences, matcher classification semantics, fallback chains, provenance boundaries), and the doc-coverage symbol-surface design (the exported-surface walk) are ported from snake-eyes (zero-dot-force, Apache 2.0); see NOTICE for attribution. The cognitive-complexity algorithm follows SonarSource cognitive complexity, with eslint-plugin-sonarjs as the normative TypeScript/JavaScript reference implementation.