Pure-Go port of mode.rs::execute's pass5 downgrade gate (Rust
2026-04-26). Adds POST /v1/matrix/downgrade endpoint via matrixd.
The gate captures the pass5 finding: composing matrix corpora into
codereview_lakehouse on a strong model LOST 5/5 head-to-head reps
against matrix-free codereview_isolation on grok-4.1-fast (p=0.031).
Strong models have enough native capacity that bug fingerprints +
adversarial framing + file content carry them; matrix chunks
displace depth-of-analysis.
Logic (matches Rust mode.rs:614-632):
if mode == codereview_lakehouse
&& !forced_mode
&& !LH_FORCE_FULL_ENRICHMENT
&& !is_weak_model(model)
→ flip to codereview_isolation, record downgraded_from
is_weak_model captures the empirical weak-list:
- `:free` suffix or `:free/` infix (OpenRouter free tier)
- qwen3.5:latest, qwen3:latest (local last-resort rungs)
- everything else → strong by default
Tests:
- 3 unit tests in internal/matrix/downgrade_test.go: IsWeakModel
coverage, MaybeDowngrade truth table (5 rows), forced-mode
precedence (forced beats every other bypass)
- scripts/downgrade_smoke.sh: 6 assertions through gateway covering
all 5 truth-table rows + empty-mode 400
14-smoke regression sweep all green (D1-D6, G1, G1P, G2,
storaged_cap, pathway, matrix, relevance, downgrade).
SPEC §3.4 progress: 4 of 5 components shipped (corpus builders,
multi-corpus retrieve+merge, relevance filter, downgrade gate).
Last component is learning-loop integration.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
186 lines
5.8 KiB
Go
186 lines
5.8 KiB
Go
// matrixd is the matrix indexer service. Wraps internal/matrix's
|
|
// Retriever with HTTP routes per docs/SPEC.md §3.4.
|
|
//
|
|
// Routes:
|
|
// POST /matrix/search — multi-corpus retrieve+merge
|
|
// GET /matrix/corpora — list known vectord indexes (proxy)
|
|
// POST /matrix/relevance — adjacency-pollution filter (CODE-aware;
|
|
// port of mcp-server/relevance.ts)
|
|
// POST /matrix/downgrade — strong-model auto-downgrade decision
|
|
// (port of mode.rs::execute pass5 gate)
|
|
//
|
|
// matrixd talks to embedd (for query-text embedding) and vectord
|
|
// (for per-corpus search) via HTTP. Both URLs come from
|
|
// [matrixd] config; gateway sets them to its own upstream URLs so
|
|
// matrixd inherits the same provider topology.
|
|
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"flag"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"git.agentview.dev/profit/golangLAKEHOUSE/internal/matrix"
|
|
"git.agentview.dev/profit/golangLAKEHOUSE/internal/shared"
|
|
)
|
|
|
|
const maxRequestBytes = 4 << 20 // 4 MiB cap on request bodies
|
|
|
|
func main() {
|
|
configPath := flag.String("config", "lakehouse.toml", "path to TOML config")
|
|
flag.Parse()
|
|
|
|
cfg, err := shared.LoadConfig(*configPath)
|
|
if err != nil {
|
|
slog.Error("config", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
if cfg.Matrixd.EmbeddURL == "" || cfg.Matrixd.VectordURL == "" {
|
|
slog.Error("matrixd: embedd_url and vectord_url required in [matrixd]")
|
|
os.Exit(1)
|
|
}
|
|
|
|
retriever := matrix.New(cfg.Matrixd.EmbeddURL, cfg.Matrixd.VectordURL)
|
|
h := &handlers{r: retriever}
|
|
|
|
if err := shared.Run("matrixd", cfg.Matrixd.Bind, h.register, cfg.Auth); err != nil {
|
|
slog.Error("server", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
type handlers struct {
|
|
r *matrix.Retriever
|
|
}
|
|
|
|
func (h *handlers) register(r chi.Router) {
|
|
r.Post("/matrix/search", h.handleSearch)
|
|
r.Get("/matrix/corpora", h.handleCorpora)
|
|
r.Post("/matrix/relevance", h.handleRelevance)
|
|
r.Post("/matrix/downgrade", h.handleDowngrade)
|
|
}
|
|
|
|
func (h *handlers) handleSearch(w http.ResponseWriter, r *http.Request) {
|
|
var req matrix.SearchRequest
|
|
if !decodeJSON(w, r, &req) {
|
|
return
|
|
}
|
|
resp, err := h.r.Search(r.Context(), req)
|
|
if err != nil {
|
|
writeMatrixError(w, err)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|
|
|
|
// relevanceRequest is the POST /matrix/relevance body. Threshold
|
|
// defaults to matrix.DefaultRelevanceThreshold when zero.
|
|
type relevanceRequest struct {
|
|
Focus matrix.FocusFile `json:"focus"`
|
|
Chunks []matrix.CandidateChunk `json:"chunks"`
|
|
Threshold float64 `json:"threshold,omitempty"`
|
|
}
|
|
|
|
func (h *handlers) handleRelevance(w http.ResponseWriter, r *http.Request) {
|
|
var req relevanceRequest
|
|
if !decodeJSON(w, r, &req) {
|
|
return
|
|
}
|
|
if len(req.Chunks) == 0 {
|
|
http.Error(w, "chunks must be non-empty", http.StatusBadRequest)
|
|
return
|
|
}
|
|
threshold := req.Threshold
|
|
if threshold == 0 {
|
|
threshold = matrix.DefaultRelevanceThreshold
|
|
}
|
|
res := matrix.FilterChunks(req.Focus, req.Chunks, threshold)
|
|
writeJSON(w, http.StatusOK, res)
|
|
}
|
|
|
|
// downgradeRequest is the POST /matrix/downgrade body. Mirrors
|
|
// matrix.DowngradeInput; ForceFullOverride is read from the
|
|
// LH_FORCE_FULL_ENRICHMENT env var when omitted from the body.
|
|
type downgradeRequest struct {
|
|
Mode string `json:"mode"`
|
|
Model string `json:"model"`
|
|
ForcedMode bool `json:"forced_mode,omitempty"`
|
|
ForceFullOverride *bool `json:"force_full_override,omitempty"`
|
|
}
|
|
|
|
func (h *handlers) handleDowngrade(w http.ResponseWriter, r *http.Request) {
|
|
var req downgradeRequest
|
|
if !decodeJSON(w, r, &req) {
|
|
return
|
|
}
|
|
if req.Mode == "" || req.Model == "" {
|
|
http.Error(w, "mode and model are required", http.StatusBadRequest)
|
|
return
|
|
}
|
|
in := matrix.NewDowngradeInputFromEnv(req.Mode, req.Model, req.ForcedMode)
|
|
if req.ForceFullOverride != nil {
|
|
// Explicit body override beats env, useful for tooling that
|
|
// wants to ask "what would the gate do under these conditions"
|
|
// without env pollution.
|
|
in.ForceFullOverride = *req.ForceFullOverride
|
|
}
|
|
writeJSON(w, http.StatusOK, matrix.MaybeDowngrade(in))
|
|
}
|
|
|
|
func (h *handlers) handleCorpora(w http.ResponseWriter, r *http.Request) {
|
|
names, err := h.r.Corpora(r.Context())
|
|
if err != nil {
|
|
slog.Error("matrix corpora", "err", err)
|
|
http.Error(w, "vectord unavailable", http.StatusBadGateway)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"corpora": names, "count": len(names)})
|
|
}
|
|
|
|
func decodeJSON(w http.ResponseWriter, r *http.Request, v any) bool {
|
|
defer r.Body.Close()
|
|
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBytes)
|
|
if err := json.NewDecoder(r.Body).Decode(v); err != nil {
|
|
var maxErr *http.MaxBytesError
|
|
if errors.As(err, &maxErr) || strings.Contains(err.Error(), "http: request body too large") {
|
|
http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
|
|
return false
|
|
}
|
|
http.Error(w, "decode body: "+err.Error(), http.StatusBadRequest)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, code int, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(code)
|
|
if err := json.NewEncoder(w).Encode(v); err != nil {
|
|
slog.Warn("matrix write json", "err", err)
|
|
}
|
|
}
|
|
|
|
// writeMatrixError maps internal/matrix sentinels to HTTP statuses.
|
|
// Corpus / embed failures bubble up as 502 (the upstream service is
|
|
// what's wrong); validation errors are 400.
|
|
func writeMatrixError(w http.ResponseWriter, err error) {
|
|
switch {
|
|
case errors.Is(err, matrix.ErrEmptyCorpora),
|
|
errors.Is(err, matrix.ErrEmptyQuery):
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
case errors.Is(err, matrix.ErrCorpus),
|
|
errors.Is(err, matrix.ErrEmbed):
|
|
slog.Warn("matrix upstream", "err", err)
|
|
http.Error(w, err.Error(), http.StatusBadGateway)
|
|
default:
|
|
slog.Error("matrix", "err", err)
|
|
http.Error(w, "internal", http.StatusInternalServerError)
|
|
}
|
|
}
|