Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .codex-plugin/mcp.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
"PERPLEXITY_API_KEY",
"PPLX_API_KEY",
"TOGETHER_API_KEY",
"TYPESAFE_API_KEY",
"VOYAGE_API_KEY",
"ZEROENTROPY_API_KEY",
"ZHIPUAI_API_KEY"
Expand Down
114 changes: 114 additions & 0 deletions docs/ai-providers/typesafe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# TypeSafe (Jev) reranking

TypeSafe is an optional reranking provider. Jev returns typed relevance judgments
through the native System One API. It does not supply chat, synthesis, or embeddings.
Select it using GBrain's existing reranker configuration.

## Setup

Get a key from [TypeSafe](https://console.typesafe.ai). Add it to the existing
GBrain home environment file (`~/.gbrain/.env`, or `$GBRAIN_HOME/.env`):

```dotenv
TYPESAFE_API_KEY=<your-key>
```

The process environment is also supported and takes precedence over the home
environment file. Choose the model and enable reranking:

```bash
gbrain config set search.reranker.model typesafe:jev-1.13.0
gbrain config set search.reranker.enabled true
gbrain search modes
```

`typesafe:jev-latest` is also accepted; the alias may change after a TypeSafe
release. Pin the version for reproducible evaluations. Existing installations
keep their selected provider and default model. A TypeSafe key does not change
the selection automatically. No new environment selector is required.

## Behavior

The gateway sends a Score question for each candidate with four concrete levels:
unrelated, same topic without answer evidence, partial answer evidence, and direct
answer evidence. Scores are normalized to 0..1; ties preserve incoming rank.
This is relevance, not a probability that a stored fact is true.
The query is shared state. Each independent Score question carries only its own
candidate in a structured `instructions.candidate` field, with an explicit task
to treat candidate content as data. This avoids unrelated candidates in shared
state and positional lookup. Question IDs map answers back to code; they are not
model instructions. The layout was validated with native regression and bounded
performance controls; API-supported object instructions do not themselves prove
resistance to every adversarial input.

Each request packs as many candidates as fit both documented context budgets:
32k tokens for state plus the longest question and 64k for state plus all questions.
There is no fixed question-count cap. Independent Score questions in the same
request use Jev's internal parallelism; splitting adds requests only when an
estimated context budget is full. Source query and document text are preserved.

The estimate uses GBrain's existing cl100k tokenizer with a 2x margin, an
individual-digit floor, fragment-boundary reserves, and 2,048 tokens of headroom.
This is not Jev's tokenizer or an exact proof of the minimum request count;
provider validation remains authoritative. The payload byte ceiling is checked
separately from context tokens. Up to 16 batches run concurrently using a worker queue under one overall
timeout; a finished worker starts queued work without waiting for slower batches.
There is no automatic retry that can extend the search deadline.

Authentication, model allowlists, cancellation, cost admission, and usage remain
in the existing gateway. Input tokens from all started batches are metered;
missing usage uses a conservative estimate. Missing keys, rejected requests,
oversized pairs, incomplete scores, and timeouts preserve original search order
through existing skip reporting and failure auditing. There is no automatic second provider call.

The current keyword-only/no-vector search branches return before reranking.
Setting only a TypeSafe key does not enable embeddings or change those branches.
Jev's relevance scale also needs evaluation with existing autocut/CRAG thresholds;
normalizing a score does not calibrate those thresholds automatically.

## Say to your agent

> Configure TypeSafe Jev as my reranker using the existing GBrain settings. Keep
> my current search mode and embedding provider, and check that reranking is ready.

Provide the key through the existing home environment file or process
configuration; avoid putting credentials in chat.

## Evaluation

The [completed free-account pilot](../eval/typesafe-rerank/README.md) includes the
frozen-input generator, protocol, final receipt and individual HTTP table/CSV.
It uses the production Jev planner/executor. Voyage rerank-3 selection, chunking,
rolling quota scheduling and `truncation:false` are evaluation-only adaptations
for a 3 RPM / 10K TPM account. They do not change the production Voyage adapter
or the default model. Its larger-profile results are an account-constrained
collector comparison, not a native single-request production baseline.

The rank-only harness compares identical capped candidate text/order, alternates
provider order, preflights readiness and cost, validates complete coverage, and
records native input usage, nominal cost and measured per-HTTP timings. Failed
calls make the campaign incomplete. Missing native usage is null in evidence;
gateway budget estimates are not substituted as actual measured costs. Dry runs
perform no provider calls and never report candidate-model quality.

```bash
# Reproduce the frozen synthetic inputs without opening the operator's brain.
bun scripts/fixtures/jev-rerank-workloads.ts .context/jev-workloads.jsonl
bun scripts/typesafe-rerank-ab.ts --pools .context/jev-workloads.jsonl --baseline voyage:rerank-3 --dry-run --out .context/jev-preflight.json

# Known isolated NamedThing regression fixture; requires both provider keys.
# Set account-specific quota flags as in the pilot protocol before a live run.
bun scripts/typesafe-rerank-ab.ts --namedthing --baseline voyage:rerank-3 --baseline-rpm 3 --baseline-tpm 10000 --repeats 1 --out .context/jev-namedthing.json
```

Independent question-local evidence is an evaluated inference from API-supported
object instructions, not an official cookbook recommendation. The twelve known
relevance cases and NamedThing are developer regression fixtures. They do not
establish held-out quality or calibrated autocut/CRAG confidence. Native gateway
integration tests verify these existing mechanisms accept the normalized scores;
no production threshold or downstream behavior is changed.

References: [API](https://docs.typesafe.ai/api),
[models and pricing](https://docs.typesafe.ai/models),
[Score](https://docs.typesafe.ai/primitives/score), and
[reranking cookbook](https://docs.typesafe.ai/cookbooks/rerank_typesafe).
10 changes: 10 additions & 0 deletions docs/architecture/KEY_FILES.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@
On-demand reference. CLAUDE.md (the always-loaded orientation file) routes here
via its Reference map. **Read a file's entry before editing that file.**

- `src/core/ai/rerank-typesafe.ts` — native System One relevance adapter: shared query state and structured independent Score questions carrying only their own candidate, explicit data boundaries and stable answer IDs. Packs questions within estimated 32k state/longest-question and 64k total-input budgets, without a fixed question-count cap. Cl100k estimates include tokenizer, digit, boundary and serialization margins; provider validation remains authoritative. Complete bounded score validation, stable ties, global index merging, bounded concurrency (default 16; evaluation can lower it), and input usage settlement. HTTP/auth, admission, and the overall deadline belong to the existing gateway. Only an explicitly selected TypeSafe recipe uses this wire format.
- `src/core/ai/rerank-typesafe-gateway.ts` — TypeSafe-only native lifecycle, context/payload preflight, cost admission/settlement, one deadline and private error suppression. Takes the gateway-resolved model and invocation transport. Existing standard/Voyage request, response, budget and failure code remains unchanged; only the selected native recipe enters this module.
- `scripts/typesafe-rerank-ab.ts` — paired rank-only evaluation on identical frozen candidate pools. Preflights all provider plans, disables evaluation Voyage truncation, records provider usage, latency, costs, per-query outcomes, shortlist fingerprints, and clustered Hit@1 uncertainty. Receipts and a completion-appended JSONL audit include individual HTTP measurements with start-order IDs, profile/sample/batch coverage, response usage and overlapping timings. Provider-specific request counts may differ; complete per-chunk results merge globally with stable ties. Incomplete calls cannot produce a complete quality comparison. NamedThing is an isolated synthetic regression fixture; dry runs never report candidate model quality. Setup and limits: `docs/ai-providers/typesafe.md`.
- `scripts/fixtures/jev-rerank-workloads.ts` — reconstructs the completed synthetic free-account workload text, candidate IDs/order and relevance labels without a large duplicated fixture. Canonical fingerprints and captured native Jev payload hashes are checked in `test/typesafe-rerank-evidence.test.ts`. The public protocol, receipt and HTTP table/CSV live in `docs/eval/typesafe-rerank/`; account-constrained Voyage evaluation is distinct from the unchanged production adapter.
- `test/search/typesafe-reranker-integration.serial.test.ts` — isolated PGLite retrieval through the real native Jev gateway transport seam, proving config selection, score stamping, existing autocut overrides, CRAG score-floor consumption, private failure audit/pass-through and relational evidence pinning. Hermetic judgments test wiring, not real-world score calibration.
- `scripts/lib/rerank-request-telemetry.ts` — evaluation-only HTTP recorder with stable start-order IDs across concurrent completion, operation-relative starts, client response duration, in-flight counts and actual provider input usage/list-price cost. Persists an explicit metadata allowlist without credentials, source evidence, response bodies or raw errors. Missing usage is null rather than estimated; overlapping request durations are not elapsed operation time.
- `scripts/lib/rerank-quota.ts` — evaluation-only rolling RPM/TPM window shared by in-flight calls. Atomically reserves estimated input, settles to native usage, and wakes dispatch on settlement or expiry. Abortable waits stop queued work after failure; optional idle draining isolates profile quota windows. The 61-second window adds boundary headroom. No provider retries or production configuration changes; native admission estimates may differ from billed usage.
- `scripts/lib/rerank-concurrent.ts` — evaluation-only bounded chunk dispatcher with one document/quota allocator, complete score validation, global index mapping and stable ties. Cancels pending admission after failure and drains every started call for usage settlement. Active elapsed time is the union of gateway-call intervals plus merging, not the sum of overlapping durations.
- `scripts/lib/rerank-batch-plan.ts` — evaluation-only Voyage token planning: repeated query tokens per document, individual pair checks, aggregate operating budget and 1,000-document cap. Accepts a token counter; the default is a conservative cl100k estimate, not the Voyage tokenizer. Query/aggregate evaluation ceilings are not asserted native rerank-3 limits. Production configuration and wire behavior stay in the existing gateway.

Entries describe CURRENT behavior + load-bearing invariants only. Release history
lives in `CHANGELOG.md` + `git log` / `git blame`, NOT here. Do not append
per-release `**vX.Y.Z:**` narration — CI enforces this
Expand Down
128 changes: 128 additions & 0 deletions docs/eval/typesafe-rerank/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# TypeSafe reranking: free-account pilot

This completed development evaluation compares Jev 1.13.0 with Voyage rerank-3
on identical frozen synthetic evidence. Both returned every candidate and ranked
the expected approved policy first in all four profiles. It measures reranking,
not final second-brain answers or independently established quality equivalence.
Each provider/profile has **one execution**. All profiles ask the same question;
the fifty-short-document pool repeats nine background documents.

## Results

Captured 2026-09-17T17:08:27.791Z. Only the final selected Jev layout is shown.
Costs sum native reported input across every HTTP call at list prices, excluding
free credits: Voyage USD 0.05/M input; Jev USD 0.042/M input, with free output.
These are nominal costs, not account invoices.

| Documents × characters | Calls Voyage / Jev | Wall ms Voyage / Jev | Active ms Voyage / Jev | Total USD Voyage / Jev |
| --- | --- | --- | --- | --- |
| 10 × 1,000 | 1 / 1 | 768.12 / 977.05 | 768.01 / 977.02 | 0.000086950 / 0.000129108 |
| 5 × 6,000 | 1 / 1 | 388.20 / 585.98 | 388.17 / 585.94 | 0.000250150 / 0.000260736 |
| 50 × 1,000 | 3 / 1 | 1421.50 / 1069.65 | 1420.67 / 1069.64 | 0.000434950 / 0.000599508 |
| 50 × 6,000 | 21 / 2 | 367340.25 / 1582.17 | 7438.43 / 1582.17 | 0.002502400 / 0.002515716 |

Voyage was faster and cheaper on the two smaller profiles. On fifty long
documents, Jev's active elapsed time was 78.7% lower in this execution and
nominal cost was 0.53% higher. Voyage's USD 0.002502400 covers **all 21 calls**;
Jev's USD 0.002515716 covers **both calls**. These points do not establish a
universal winner or latency distributions.

[Individual HTTP table](requests.md), [CSV](requests.csv),
[unaltered receipt](receipt.json), [capture source manifest](source-manifest.json).
All 31 HTTP calls are included. Missing native usage would remain null; request
durations were measured individually, not inferred by dividing totals.

A separate [100-document extension](hundred-document-report.md) captured the
same selected Jev layout on the updated gateway/base, with one execution per
provider/profile and all 54 individual HTTP records. Jev remained 36.50% more
expensive on short documents and 0.53% more expensive on long documents at list
prices. Its active elapsed time on 100 long documents was 86.81% lower in that
single account-constrained execution. The extension preserves the initial
receipt and distinguishes cost per document from total cost.

## Why this differs from the production Voyage adapter

The evaluation selected `voyage:rerank-3` to use this account's free allowance.
GBrain's production default remains `voyage:rerank-2.5`. This account had 3 RPM
and 10,000 TPM. The final campaign did not complete native single-request
comparisons on the fifty-document pools. **Only the evaluation harness** divided
Voyage candidate pools,
scheduled chunks with a shared rolling quota ledger, and added `truncation:false`
to compare the same untrimmed evidence. It permitted up to three concurrent
Voyage calls; native usage settlement and scarce RPM slots determined dispatch.
The production Voyage recipe, wire translation, accounting and failures remain
unchanged. The chunked results are not measurements of that unchanged adapter
receiving the whole large pool in one call. Splitting the fifty-short pool
followed conservative preflight estimates: its 8,699 billed input tokens do not
prove the API admission count, and the pilot did not test whether one full native
request would fit. Necessary chunk counts and optimal scheduling are unproved.

Jev used the proposed production planner/executor: query-only shared state and
one structured Score question per candidate. Fifty short documents fit one
internally parallel request. Fifty long documents packed into 28/22 candidates
and two concurrent requests under one gateway deadline. Conservative context
estimates do not prove these are the smallest possible native request counts.

Wall time runs from first dispatch through complete merged ranking and includes
between-chunk quota gaps. Active time counts the union of gateway intervals plus
planning/merging, excluding idle quota gaps. Initial profile isolation waits are
excluded from both; per-request waits include that preparation. Overlapping
request durations and waits must not be summed as elapsed operation time.

This is an account-constrained collector comparison. Active time still includes
batching, client processing, network and concurrency effects; it does not measure
unconstrained provider inference. Voyage paid-account throughput, maximum Jev
capacity, held-out quality and score-threshold calibration were not established.
Matching gold first does not imply identical rankings or score semantics.

Separate [known-case results](known-case-results.json) retain only the selected
Jev layout's twelve developer-labeled native regression cases, including false
premises, partial/multiple evidence and injected instructions. All predefined
pair checks passed. Current adapter payload hashes reproduce those requests too.
This is a selected-layout extraction of existing evidence, without timing-control
results, held-out labels or a Voyage quality comparison.

## Reproduce

From the repository root, reconstruct the exact evidence, IDs, order and labels:

```bash
bun scripts/fixtures/jev-rerank-workloads.ts .context/jev-workloads.jsonl
bun scripts/typesafe-rerank-ab.ts \
--pools .context/jev-workloads.jsonl \
--baseline voyage:rerank-3 --candidate typesafe:jev-1.13.0 \
--baseline-rpm 3 --baseline-tpm 10000 --baseline-concurrency 3 \
--baseline-token-margin 1.8 --baseline-max-input-tokens 9040 \
--baseline-isolate-profiles --repeats 1 --timeout-ms 5000 --max-usd 0.03 \
--out .context/jev-free-account-ab.json
```

Live execution requires both existing provider environment keys. Add `--dry-run`
for zero-provider-call preflight; it does not report model quality. Quota/token
estimates are recorded heuristics calibrated on development inputs, not provider
tokenizers or guarantees of successful account admission. Use your account's
limits for a different campaign. No retries or equal request-count requirement.
No other native probes or repository checks ran during the captured campaign.

The canonical capped-pool SHA-256 is
`942d24c8eec1b5a70f17a9a0e80a0e5e602e5e7ae4b019e59e6bfc0a968f30a8`.
`test/typesafe-rerank-evidence.test.ts` checks it, complete coverage, native
usage/cost reconciliation and every Jev payload hash against the current adapter.

## Provenance and scope

The unaltered receipt and manifest retain their original local filenames and
capture-base hashes (`668b9bac3`). The generator replaces the original large
JSONL file; the resulting evidence and canonical fingerprint are identical.
The pure Jev planner/executor is unchanged from the captured source. Subsequent
gateway isolation moved only Jev's lifecycle into its own module so the existing
Voyage path could remain intact; the capture is not a fresh timing measurement
on the updated upstream base. Behavioral gateway/search tests cover that wiring.

Primary documentation, checked via curl on 2026-09-17:
[Voyage pricing](https://docs.voyageai.com/docs/pricing),
[Voyage rate limits](https://docs.voyageai.com/docs/rate-limits),
[trial guidance](https://www.mongodb.com/docs/voyageai/api-reference/overview/),
[TypeSafe models](https://docs.typesafe.ai/models),
[System One API](https://docs.typesafe.ai/api),
[Score](https://docs.typesafe.ai/primitives/score).
Loading