diff --git a/.env.example b/.env.example index 6d1bf67..61cd613 100644 --- a/.env.example +++ b/.env.example @@ -113,6 +113,33 @@ GENERATION_SHUTDOWN_TIMEOUT=5m # iterations. GENERATION_MAX_ITERS=60 +# ----- Embeddings (optional; enables RAG over the saved-build library) ----- +# Unset EMBEDDING_BASE_URL = recency-only retrieval, no pgvector required. +# Set it to an OpenAI-compatible /v1 root to enable semantic seeding. +# +# Local default: LM Studio (Developer tab -> load an embedding model -> start +# server). Ollama and llama.cpp expose the same /v1/embeddings shape; only the +# port and model id differ: +# LM Studio: EMBEDDING_BASE_URL=http://localhost:1234/v1 +# Ollama: EMBEDDING_BASE_URL=http://localhost:11434/v1 (ollama pull nomic-embed-text) +# llama.cpp: EMBEDDING_BASE_URL=http://localhost:8080/v1 +# +# EMBEDDING_DIM must match the model's output width or the API refuses to +# start (nomic-embed-text is 768). +EMBEDDING_BASE_URL= +EMBEDDING_MODEL=text-embedding-nomic-embed-text-v1.5@q8_0 +EMBEDDING_DIM=768 +# EMBEDDING_API_KEY= # cloud embedders only (e.g. OpenAI, Voyage) +# +# Retrieval tuning (see the README "Tuning retrieval" runbooks). Distances are +# cosine (0 = identical, 2 = opposite); good values are model-specific, so +# re-tune after any model change. +# EMBEDDING_SEED_MAX_DISTANCE=0.15 # Tier A: proactively inject the top match when within this. Tuned: 0.25-0.30. +# EMBEDDING_SIMILAR_MAX_DISTANCE=0.5 # Tier B: drop get_similar_past_builds rows beyond this. Tuned: 0.35-0.40. +# EMBEDDING_HNSW_M=16 # HNSW graph degree (build-time; reindex to change). +# EMBEDDING_HNSW_EF_CONSTRUCTION=64 # HNSW build candidate list (build-time; reindex to change). +# EMBEDDING_HNSW_EF_SEARCH=40 # HNSW query candidate list (query-time; higher = better recall, slower). + # ----- Logging ----- # Log level: debug | info | warn | error (default info). LOG_LEVEL=info diff --git a/README.md b/README.md index 4d145a7..d013b04 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ authored for them. │ └──────────────┘ │ ↪ LLM provider (Claude / OpenAI) │ │ │ │ ↪ Tool registry │ │ │ │ ↪ Build library (PostgreSQL) │ │ +│ │ ↪ Embedding provider (optional) │ │ │ │ ↪ Scoring client → ─────┐ │ │ │ └───────────────────────────│──────────┘ │ └─────────────────────────────────────────────────│────────────┘ @@ -48,6 +49,19 @@ authored for them. Two deployable units. Both can be run natively, via `docker compose`, or via Helm/Tilt on Kubernetes. +**Embedding provider and RAG.** The build library optionally uses an OpenAI-compatible embedding endpoint (a local LM +Studio, Ollama, or llama.cpp server, or any hosted `/v1/embeddings` API) to enable semantic retrieval over saved +builds. When configured, the orchestrator embeds the incoming +request, searches the pgvector-backed library for semantically similar past builds, and proactively injects the closest +match as a warm-start for the LLM (Tier A seeding). The LLM can also pull ranked candidates on demand through the +`get_similar_past_builds` and `get_saved_build` tools (Tier B). When no embedder is configured, retrieval falls back to +recency ordering and pgvector is not required. + +Retrieval only surfaces builds the user has explicitly **accepted**. A generation that passes quality gates is saved and +fetchable immediately, but it does not seed future generations until you `POST /builds/{id}/accept` — passing gates is +not the same as being the build you wanted. Un-accepted builds are visible only through the user-facing `GET /builds` +(filterable with `?accepted=`) and `GET /builds/{id}`, never through the RAG tools. + Directory map: ``` @@ -57,6 +71,8 @@ cmd/ one Go binary per directory build-rocalc-mapping/ rocalc-id ↔ iRO-id table (one-shot) enrich-mapping-rms/ ratemyserver.net lookup helper verify-mapping/ spot-check tool + backfill-embeddings/ re-embed every saved build after a model change (one-shot) + embedding-recall/ HNSW recall quality probe: approx-vs-exact KNN internal/ api/ HTTP handlers, OpenAPI types buildlibrary/ PostgreSQL persistence @@ -89,6 +105,65 @@ scripts/ e2e.sh, generate.sh, docker-e2e.sh, ... api/openapi.yaml the public HTTP contract ``` +### EMBEDDING_* configuration + +| Variable | Meaning | +|---|---| +| `EMBEDDING_BASE_URL` | OpenAI-compatible `/v1` root; presence enables the feature. Local default: `http://localhost:1234/v1` (LM Studio); Ollama is `http://localhost:11434/v1`. | +| `EMBEDDING_MODEL` | Model id, e.g. `text-embedding-nomic-embed-text-v1.5@q8_0` (LM Studio), `nomic-embed-text` (Ollama), `text-embedding-3-large` (OpenAI). | +| `EMBEDDING_API_KEY` | Optional bearer token (cloud embedders); ignored by local servers. | +| `EMBEDDING_DIM` | Required when `EMBEDDING_BASE_URL` is set (default 768). Sets the vector column width; must match the model's output dimension. | +| `EMBEDDING_SEED_MAX_DISTANCE` | Tier A proactive-seed cosine-distance ceiling (default 0.15). Inject the closest saved build only when it is this close to the request. | +| `EMBEDDING_SIMILAR_MAX_DISTANCE` | Tier B list floor (default 0.5). Drop `get_similar_past_builds` results beyond this cosine distance. | +| `EMBEDDING_HNSW_M` / `EMBEDDING_HNSW_EF_CONSTRUCTION` | HNSW index build parameters (default pgvector 16 / 64). Baked into the index; changing them needs a reindex. | +| `EMBEDDING_HNSW_EF_SEARCH` | HNSW query-time candidate-list size (default pgvector 40). Higher = better recall, slower. Applied per query. | + +Unset `EMBEDDING_BASE_URL` means recency-only retrieval, no pgvector required. + +### Tuning runbooks + +**Threshold tuning (after a populated corpus exists).** Enable the per-firing log; each proactive seed records the +seed `id` and its cosine `distance`. Collect a sample of real requests, read the generated build alongside the log to +judge usefulness, and look at where genuinely useful matches cluster versus the noise tail. Then set +`EMBEDDING_SEED_MAX_DISTANCE` just inside the good band (tight enough to avoid seeding bad matches). The Tier B list +floor `EMBEDDING_SIMILAR_MAX_DISTANCE` (which bounds what `get_similar_past_builds` returns) is set looser than the +seed ceiling using the same observations. Re-deploy and re-observe. Distances are model-specific and do not transfer +across a model or dimension change; redo this step after any `EMBEDDING_MODEL`/`EMBEDDING_DIM` swap. + +**Model and HNSW index tuning.** Pick a model and dimension (`EMBEDDING_MODEL` / `EMBEDDING_DIM`), then run: + +```bash +# 1. (Re-)embed every saved build with the chosen model. +# If EMBEDDING_MODEL or EMBEDDING_DIM changed on a non-empty corpus, clear +# existing embeddings first so backfill does not exit early with an error: +# UPDATE saved_trajectories SET embedding = NULL; +# Then run backfill: +go run ./cmd/backfill-embeddings + +# 2. Check HNSW index recall against exact KNN. +go run ./cmd/embedding-recall --k 10 --sample 50 + +# 3a. Recall is low (< 0.95): measure a higher query-time ef_search first, then set it +# on the serving path. +go run ./cmd/embedding-recall --k 10 --sample 50 --ef-search 80 +# If that helps, set EMBEDDING_HNSW_EF_SEARCH=80 on the API. It is applied per query +# (SET LOCAL inside the retrieval transaction); no reindex needed. + +# 3b. Still low: raise the build parameters and rebuild the index. Set EMBEDDING_HNSW_M +# and/or EMBEDDING_HNSW_EF_CONSTRUCTION on the API, then force a fresh index (the +# bootstrap's CREATE INDEX IF NOT EXISTS will not rebuild an existing one): +# DROP INDEX saved_trajectories_embedding_idx; +# and restart the API. The bootstrap recreates the index WITH (m, ef_construction). + +# 4. To switch models entirely: change EMBEDDING_MODEL/EMBEDDING_DIM, clear embeddings +# (step 1 above), re-run backfill-embeddings, re-run embedding-recall, then +# re-tune the thresholds from the previous runbook. +``` + +`cmd/embedding-recall` reports `recall@k` = `|approx_topk intersect exact_topk| / k`. A value >= 0.98 means +the defaults are fine; below 0.85 means the index parameters need raising. Run it against a populated corpus +only; an empty corpus always returns perfect recall. + --- ## Capabilities @@ -242,8 +317,9 @@ Full OpenAPI 3.0 contract: [`api/openapi.yaml`](api/openapi.yaml). Bruno collect | POST | `/score` | Direct calc; fully-specified Build → derived stats + optional combat sim | | POST | `/generate` | LLM-driven; enqueue a generation job; returns `202 + {id}` | | GET | `/generations/{id}` | Poll status of an enqueued generation | -| GET | `/builds` | Paginated list of saved trajectories | +| GET | `/builds` | Paginated list of saved trajectories (filter with `?accepted=true\|false`) | | GET | `/builds/{id}` | One full saved trajectory with item / skill names resolved | +| POST | `/builds/{id}/accept` | Accept a build so RAG retrieval can seed future generations from it | ### Score a build directly @@ -280,8 +356,11 @@ while :; do sleep 30 done -# 3. Fetch enriched build +# 3. Fetch enriched build and review it curl -s "http://localhost:8080/builds/$ID" | jq . + +# 4. Accept it so future generations can seed from it (RAG only sees accepted builds) +curl -s -X POST "http://localhost:8080/builds/$ID/accept" | jq . ``` Or use the convenience wrapper: @@ -439,9 +518,10 @@ Not yet done, roughly in priority order: - [x] Add self-buffs to calc - [ ] Add self-buffs to scoring - [x] Include skill usage/damage in calc and scoring -- [ ] Vector search over saved trajectories' reasoning text. Today's `get_similar_past_builds` uses class+scenario - lookup. -- [ ] Add RAG with injecting get_similar_past_builds into initial system prompt +- [x] Vector search (pgvector) over saved trajectories. `get_similar_past_builds` ranks by cosine distance to the + embedded request when an embedder is configured; falls back to recency otherwise. +- [x] RAG seeding: the orchestrator embeds the incoming request, finds the closest saved build, and injects it as a + warm-start when within `EMBEDDING_SEED_MAX_DISTANCE`. - [x] Postgres migration for the build library. The API is now stateless; horizontal scaling is supported via the lease-based generation queue (SKIP LOCKED claim, requeue with cap), configurable replicas, and HPA/PDB in the Helm chart. - [ ] General prompt tuning - less tokens, more progress. diff --git a/api/openapi.yaml b/api/openapi.yaml index 3f7b8c4..bcae048 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -6,12 +6,13 @@ info: description: | Ragnarok Online (pre-renewal) build optimizer. - Four endpoints: - - POST /score direct calc; fully-specified Build → derived stats + optional combat sim - - POST /generate LLM-driven; enqueue a generation job; returns 202 + {id} - - GET /generations/{id} poll status of an enqueued generation - - GET /builds paginated list of saved trajectories - - GET /builds/{id} one full saved trajectory with item/skill names resolved + Six endpoints: + - POST /score direct calc; fully-specified Build → derived stats + optional combat sim + - POST /generate LLM-driven; enqueue a generation job; returns 202 + {id} + - GET /generations/{id} poll status of an enqueued generation + - GET /builds paginated list of saved trajectories (filter with ?accepted=) + - GET /builds/{id} one full saved trajectory with item/skill names resolved + - POST /builds/{id}/accept mark a build user-accepted so RAG retrieval can seed from it The /generate endpoint requires LLM_API_KEY at the API process. Without it, /generate returns 503 (Service Unavailable); /score continues to work. @@ -164,6 +165,14 @@ paths: minimum: 1 maximum: 50 description: cap results (default 5, max 50) + - name: accepted + in: query + required: false + schema: + type: boolean + description: > + filter by acceptance state; true = accepted only, false = pending + (not yet accepted) only, omitted = all responses: "200": description: List of trajectory summaries @@ -221,6 +230,43 @@ paths: schema: $ref: "#/components/schemas/ErrorBody" + /builds/{id}/accept: + post: + operationId: acceptBuild + summary: Accept a saved trajectory, making it visible to RAG retrieval + description: > + Marks the build as user-accepted. Until accepted, a saved build is + fetchable via GET /builds/{id} but is NOT surfaced by the retrieval + tools (proactive seed injection, get_similar_past_builds, + get_saved_build). Idempotent: re-accepting keeps the original + timestamp. + parameters: + - name: id + in: path + required: true + schema: + type: string + description: id of the saved build to accept + responses: + "200": + description: Build accepted (or already accepted) + content: + application/json: + schema: + $ref: "#/components/schemas/AcceptBuildResponse" + "404": + description: No trajectory with that id + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorBody" + "500": + description: Library failure + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorBody" + components: schemas: @@ -559,6 +605,10 @@ components: playstyle: { type: string } description: { type: string } gate_summary: { $ref: "#/components/schemas/GateSummary" } + accepted_at: + type: string + format: date-time + description: when the build was user-accepted; absent = pending (not RAG-visible) ListBuildsResponse: type: object @@ -568,6 +618,13 @@ components: type: array items: { $ref: "#/components/schemas/BuildSummary" } + AcceptBuildResponse: + type: object + required: [ id, accepted_at ] + properties: + id: { type: string } + accepted_at: { type: string, format: date-time } + EnrichedBuild: type: object required: [ id, created_at, class, server, playstyle, mode, primary, gate_summary ] @@ -587,3 +644,7 @@ components: gate_summary: { $ref: "#/components/schemas/GateSummary" } calc_version: { type: string } catalog_version: { type: integer } + accepted_at: + type: string + format: date-time + description: when the build was user-accepted; absent = pending (not RAG-visible) diff --git a/bruno/accept-build.bru b/bruno/accept-build.bru new file mode 100644 index 0000000..36b39f5 --- /dev/null +++ b/bruno/accept-build.bru @@ -0,0 +1,48 @@ +meta { + name: accept-build + type: http + seq: 5 +} + +post { + url: {{baseUrl}}/builds/{{savedBuildId}}/accept + body: none + auth: inherit +} + +docs { + Accept a saved trajectory so the RAG retrieval surface can seed future + generations from it. Until accepted, a build that passed quality gates + is fetchable via `get-saved-build` but is invisible to proactive seed + injection, `get_similar_past_builds`, and `get_saved_build` -- passing + the quality gates is not the same as being the build you wanted. + + `savedBuildId` is set by the `generate` request's post-response script; + run this after reviewing the build with `get-saved-build`. Idempotent: + accepting an already-accepted build returns the original `accepted_at`. + 404 if no build has that id. + + Typical flow: generate -> generation-status -> get-saved-build (review) + -> accept-build. +} + +tests { + test("status is 200", function() { + expect(res.getStatus()).to.equal(200); + }); + test("id present", function() { + expect(res.getBody().id).to.be.a("string").and.not.empty; + }); + test("accepted_at present", function() { + expect(res.getBody().accepted_at).to.be.a("string").and.not.empty; + }); +} + +script:post-response { + const data = res.getBody() || {}; + console.log(""); + console.log("Build accepted: " + (data.id || "?")); + console.log(" accepted_at: " + (data.accepted_at || "?")); + console.log(""); + console.log("It is now visible to RAG retrieval and can seed future generations."); +} diff --git a/bruno/list-builds.bru b/bruno/list-builds.bru index 97bec9a..e5d7c6c 100644 --- a/bruno/list-builds.bru +++ b/bruno/list-builds.bru @@ -1,7 +1,7 @@ meta { name: list-builds type: http - seq: 5 + seq: 6 } get { @@ -14,6 +14,7 @@ params:query { limit: 10 ~class: taekwon_kid ~server: uaro + ~accepted: true } docs { @@ -22,6 +23,9 @@ docs { - `class`; restrict to one class - `server`; restrict to one server profile - `limit`; 1..50, default 5 + - `accepted`; `true` = user-accepted (RAG-visible) only, `false` = + pending review only, omitted = all. Each row carries `accepted_at` + (absent = pending). See `accept-build`. } tests { diff --git a/cmd/api/main.go b/cmd/api/main.go index 9484f5a..d874c3f 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -28,6 +28,15 @@ // GENERATION_LEASE_TTL - job lease duration (default 90s) // GENERATION_LEASE_SWEEP_INTERVAL - expired-lease sweep cadence (default 30s) // GENERATION_MAX_ATTEMPTS - requeue cap; 0 disables retry (default 0) +// EMBEDDING_BASE_URL - OpenAI-compatible /v1 root; presence +// enables RAG over saved builds (pgvector). +// Unset = recency-only, no pgvector needed. +// EMBEDDING_MODEL / EMBEDDING_DIM - embedder model id + vector dimension +// (required when EMBEDDING_BASE_URL is set) +// EMBEDDING_API_KEY - optional bearer for cloud embedders +// EMBEDDING_SEED_MAX_DISTANCE - Tier A proactive-seed ceiling (default 0.15) +// EMBEDDING_SIMILAR_MAX_DISTANCE - Tier B list floor for get_similar_past_builds (default 0.5) +// EMBEDDING_HNSW_M / _EF_CONSTRUCTION / _EF_SEARCH - HNSW index tuning (0 = pgvector default) // LOG_LEVEL - debug|info|warn|error (default info) // LOG_FORMAT - text|json (default text) package main @@ -42,6 +51,7 @@ import ( "os" "os/signal" "strconv" + "strings" "syscall" "time" @@ -50,8 +60,10 @@ import ( "github.com/levonn-dev/ro-builder/internal/buildlibrary" "github.com/levonn-dev/ro-builder/internal/catalog" "github.com/levonn-dev/ro-builder/internal/domain" + "github.com/levonn-dev/ro-builder/internal/embedding" "github.com/levonn-dev/ro-builder/internal/llm" "github.com/levonn-dev/ro-builder/internal/llm/tools" + "github.com/levonn-dev/ro-builder/internal/logging" "github.com/levonn-dev/ro-builder/internal/orchestrator" "github.com/levonn-dev/ro-builder/internal/scoring" "github.com/levonn-dev/ro-builder/internal/workers" @@ -108,11 +120,46 @@ func run() error { } logger.Info("server profiles loaded", slog.Any("profiles", profileKeys)) - lib, err := buildlibrary.Open(context.Background(), dsn) + embCfg := embedding.LoadConfigFromEnv() + if err := embCfg.Validate(); err != nil { + return fmt.Errorf("embedding config: %w", err) + } + var embedder *embedding.Client + modelID := embCfg.Model + "@" + strconv.Itoa(embCfg.Dim) + if embCfg.Enabled() { + embedder = embedding.New(embCfg) + logger.Info("embeddings enabled", slog.String("model_id", modelID), slog.Int("dim", embedder.Dimensions())) + } else { + logger.Info("embeddings disabled (EMBEDDING_BASE_URL unset); retrieval is recency-only") + } + + // Retrieval tuning knobs (semantic mode only). similarMaxDist is the + // Tier B list floor for get_similar_past_builds; the HNSW knobs tune the + // index (0 = pgvector default: m=16, ef_construction=64, ef_search=40). + similarMaxDist := envFloat("EMBEDDING_SIMILAR_MAX_DISTANCE", 0.5) + hnswM := envInt("EMBEDDING_HNSW_M", 0) + hnswEfConstruction := envInt("EMBEDDING_HNSW_EF_CONSTRUCTION", 0) + hnswEfSearch := envInt("EMBEDDING_HNSW_EF_SEARCH", 0) + + var openOpts []buildlibrary.Option + if embCfg.Enabled() { + openOpts = append(openOpts, buildlibrary.WithEmbedding(embCfg.Dim, modelID)) + if hnswM > 0 || hnswEfConstruction > 0 || hnswEfSearch > 0 { + openOpts = append(openOpts, buildlibrary.WithHNSW(hnswM, hnswEfConstruction, hnswEfSearch)) + } + } + lib, err := buildlibrary.Open(context.Background(), dsn, openOpts...) if err != nil { return fmt.Errorf("buildlibrary open: %w", err) } defer func() { _ = lib.Close() }() + if embCfg.Enabled() { + if lib.SemanticEnabled() { + logger.Info("semantic retrieval active", slog.String("model_id", modelID), slog.Int("dim", lib.EmbeddingDim())) + } else { + logger.Warn("semantic retrieval degraded to recency-only (EMBEDDING_BASE_URL set but the pgvector bootstrap did not complete; see earlier embedding errors)", slog.String("model_id", modelID)) + } + } maxAttempts := envInt("GENERATION_MAX_ATTEMPTS", 0) rq, fl, err := lib.RecoverExpiredLeases(context.Background(), maxAttempts) @@ -153,7 +200,8 @@ func run() error { registry.Register(tools.NewLookupSkill(cat)) registry.Register(tools.NewListClassSkills(cat)) registry.Register(tools.NewListClassBuffs(cat)) - registry.Register(tools.NewGetSimilarPastBuilds(lib)) + registry.Register(tools.NewGetSimilarPastBuilds(lib, similarMaxDist)) + registry.Register(tools.NewGetSavedBuild(lib)) // submit_trajectory is intentionally NOT registered here; the // orchestrator constructs a per-request overlay version via // Registry.WithTool, wiring in the per-request Scoring / EvaluateGates / @@ -164,6 +212,10 @@ func run() error { WithScoringClient(scoringClient). WithCatalog(cat). WithMaxIters(maxIters) + if embedder != nil { + orch = orch.WithEmbedder(embedder).WithSeeder(lib). + WithSeedMaxDistance(envFloat("EMBEDDING_SEED_MAX_DISTANCE", 0.15)) + } leaseTTL := envDuration("GENERATION_LEASE_TTL", 90*time.Second) sweepInterval := envDuration("GENERATION_LEASE_SWEEP_INTERVAL", 30*time.Second) @@ -171,7 +223,7 @@ func run() error { pool = workers.New(workers.Config{ Library: lib, Runner: orchestratorRunner{orch: orch}, - Save: makeSaveCallback(lib, cat), + Save: makeSaveCallback(lib, cat, embedder), Workers: numWorkers, PollInterval: pollInterval, LeaseTTL: leaseTTL, @@ -278,8 +330,10 @@ func (e *apiEnqueuer) ShutdownTimeoutSeconds() int { return int(e.shutdownTimeou // makeSaveCallback returns a workers.SaveCallback that persists a // successful generation to the saved_trajectories table keyed to the -// generation's id. -func makeSaveCallback(lib *buildlibrary.Library, cat *catalog.Catalog) workers.SaveCallback { +// generation's id. When embedder is non-nil the request+answer document is +// embedded best-effort: a failure is logged and the save continues without a +// vector rather than blocking persistence. +func makeSaveCallback(lib *buildlibrary.Library, cat *catalog.Catalog, embedder *embedding.Client) workers.SaveCallback { return func(ctx context.Context, id, owner string, req orchestrator.GenerateRequest, res *orchestrator.GenerateResult) error { if res == nil || res.Primary == nil { return errors.New("nil result; nothing to save") @@ -298,8 +352,27 @@ func makeSaveCallback(lib *buildlibrary.Library, cat *catalog.Catalog) workers.S CalcVersion: extractCalcVersion(res.Primary), CatalogVersion: cat.Version(), } - _, err := lib.SaveAndComplete(ctx, in) - return err + if embedder != nil && lib.SemanticEnabled() { + doc := strings.TrimSpace(req.Playstyle + "\n" + req.Description + "\n" + res.Final) + if vecs, err := embedder.Embed(ctx, []string{doc}); err != nil { + logging.From(ctx).Warn("save: document embed failed; storing without vector", slog.Any("err", err)) + } else if len(vecs) > 0 { + in.Embedding = vecs[0] + logging.From(ctx).Info("save: document embedded", + slog.Int("dim", len(vecs[0])), slog.Int("doc_chars", len(doc))) + } + } + if _, err := lib.SaveAndComplete(ctx, in); err != nil { + return err + } + logging.From(ctx).Info("build saved to library", + slog.String("id", id), + slog.Bool("embedded", in.Embedding != nil), + slog.Int("embedding_dim", len(in.Embedding)), + slog.String("class", req.Class), + slog.String("server", req.Server), + slog.Int("snapshots", len(res.Primary.Snapshots))) + return nil } } @@ -388,6 +461,15 @@ func envDuration(k string, d time.Duration) time.Duration { return d } +func envFloat(k string, def float64) float64 { + if v := os.Getenv(k); v != "" { + if f, err := strconv.ParseFloat(v, 64); err == nil { + return f + } + } + return def +} + func envLevel(k string, d slog.Level) slog.Level { switch envOr(k, "") { case "debug": diff --git a/cmd/backfill-embeddings/main.go b/cmd/backfill-embeddings/main.go new file mode 100644 index 0000000..3a38196 --- /dev/null +++ b/cmd/backfill-embeddings/main.go @@ -0,0 +1,71 @@ +// Command backfill-embeddings (re-)embeds every saved trajectory under the +// currently configured EMBEDDING_* model and re-stamps embedding_config. +// Run it after a model/tier change, or to populate rows saved while the +// embedder was unavailable. It opens the library with WithEmbedding, which +// runs the bootstrap (recreating the column at the new dimension when the +// corpus is empty); for a model change against a non-empty corpus, TRUNCATE +// or accept that mixed vectors are overwritten in place here. +package main + +import ( + "context" + "fmt" + "os" + "strconv" + + "github.com/levonn-dev/ro-builder/internal/buildlibrary" + "github.com/levonn-dev/ro-builder/internal/embedding" +) + +func main() { + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, "backfill-embeddings:", err) + os.Exit(1) + } +} + +func run() error { + dsn := os.Getenv("DATABASE_URL") + if dsn == "" { + return fmt.Errorf("DATABASE_URL is required") + } + cfg := embedding.LoadConfigFromEnv() + if err := cfg.Validate(); err != nil { + return err + } + if !cfg.Enabled() { + return fmt.Errorf("EMBEDDING_BASE_URL must be set to backfill") + } + modelID := cfg.Model + "@" + strconv.Itoa(cfg.Dim) + ctx := context.Background() + lib, err := buildlibrary.Open(ctx, dsn, buildlibrary.WithEmbedding(cfg.Dim, modelID)) + if err != nil { + return err + } + defer func() { _ = lib.Close() }() + if !lib.SemanticEnabled() { + return fmt.Errorf("library is recency-only after open (mismatch vs existing corpus). " + + "To change models, TRUNCATE saved_trajectories.embedding first or run against an empty corpus") + } + emb := embedding.New(cfg) + ids, err := lib.AllIDs(ctx) + if err != nil { + return err + } + for i, id := range ids { + doc, err := lib.DocumentText(ctx, id) + if err != nil { + return fmt.Errorf("document %s: %w", id, err) + } + vecs, err := emb.Embed(ctx, []string{doc}) + if err != nil { + return fmt.Errorf("embed %s: %w", id, err) + } + if err := lib.SetEmbedding(ctx, id, vecs[0]); err != nil { + return fmt.Errorf("store %s: %w", id, err) + } + fmt.Printf("[%d/%d] %s\n", i+1, len(ids), id) + } + fmt.Printf("backfilled %d rows for %s\n", len(ids), modelID) + return nil +} diff --git a/cmd/embedding-recall/main.go b/cmd/embedding-recall/main.go new file mode 100644 index 0000000..83349f2 --- /dev/null +++ b/cmd/embedding-recall/main.go @@ -0,0 +1,57 @@ +// Command embedding-recall reports mean recall@k of the HNSW index vs exact +// KNN over a sample of stored vectors. 0.98 => leave the index defaults; +// 0.85 => raise EMBEDDING_HNSW_M / EF_CONSTRUCTION (then re-backfill) or +// EMBEDDING_HNSW_EF_SEARCH (--ef-search; no rebuild). Run after a backfill. +package main + +import ( + "context" + "flag" + "fmt" + "os" + "strconv" + + "github.com/levonn-dev/ro-builder/internal/buildlibrary" + "github.com/levonn-dev/ro-builder/internal/embedding" +) + +func main() { + k := flag.Int("k", 10, "neighbors per query") + sample := flag.Int("sample", 50, "number of probe vectors") + efSearch := flag.Int("ef-search", 0, "hnsw.ef_search override (0 = server default)") + flag.Parse() + if err := run(*k, *sample, *efSearch); err != nil { + fmt.Fprintln(os.Stderr, "embedding-recall:", err) + os.Exit(1) + } +} + +func run(k, sample, efSearch int) error { + dsn := os.Getenv("DATABASE_URL") + cfg := embedding.LoadConfigFromEnv() + if dsn == "" { + return fmt.Errorf("DATABASE_URL must be set") + } + if !cfg.Enabled() { + return fmt.Errorf("embedding not configured: EMBEDDING_* env vars must be set") + } + ctx := context.Background() + lib, err := buildlibrary.Open(ctx, dsn, buildlibrary.WithEmbedding(cfg.Dim, cfg.Model+"@"+strconv.Itoa(cfg.Dim))) + if err != nil { + return err + } + defer func() { _ = lib.Close() }() + if !lib.SemanticEnabled() { + return fmt.Errorf("library is recency-only; nothing to measure") + } + probes, err := lib.SampleVectors(ctx, sample) + if err != nil { + return err + } + r, err := lib.RecallAtK(ctx, probes, k, efSearch) + if err != nil { + return err + } + fmt.Printf("recall@%d over %d probes (ef_search=%d): %.4f\n", k, len(probes), efSearch, r) + return nil +} diff --git a/deploy/helm/ro-builder/README.md b/deploy/helm/ro-builder/README.md index 185c4ce..29f7176 100644 --- a/deploy/helm/ro-builder/README.md +++ b/deploy/helm/ro-builder/README.md @@ -61,6 +61,34 @@ See `values.yaml` for the full schema and defaults. Key sections: The API is stateless and connects to Postgres via `DATABASE_URL`, read from the `ro-builder-env` Secret. `postgresql.enabled` (default `true`) -deploys a bundled in-cluster Postgres StatefulSet. To use a managed -Postgres instead, set `postgresql.enabled: false` and point `DATABASE_URL` -at the external host in your sealed secret. +deploys a bundled in-cluster Postgres StatefulSet using the +`pgvector/pgvector:pg17` image. To use a managed Postgres instead, set +`postgresql.enabled: false` and point `DATABASE_URL` at the external host +in your sealed secret. + +## Embeddings (optional) + +Semantic retrieval over the saved-build library is optional and off by +default. When disabled, no pgvector extension is required and no pgvector +DDL is run. When enabled, the bootstrap creates the vector column and HNSW +index at startup; pgvector must be installed in the database. The bundled +`pgvector/pgvector:pg17` image already satisfies this requirement for +in-cluster Postgres. For managed Postgres, enable the pgvector extension +through your provider's platform settings before starting the API. + +Configure via the `env` ConfigMap block in `values.yaml`: + +| Variable | Purpose | +|---|---| +| `EMBEDDING_BASE_URL` | OpenAI-compatible embeddings endpoint; presence enables the feature. | +| `EMBEDDING_MODEL` | Model id (e.g. `text-embedding-nomic-embed-text-v1.5@q8_0`, `nomic-embed-text`, `text-embedding-3-large`). | +| `EMBEDDING_DIM` | Required when `EMBEDDING_BASE_URL` is set (default 768). Must match the model's output dimension; a mismatch causes a startup failure in `Config.Validate`. | +| `EMBEDDING_SEED_MAX_DISTANCE` | Tier A proactive-seed cosine-distance ceiling (default 0.15). | +| `EMBEDDING_SIMILAR_MAX_DISTANCE` | Tier B `get_similar_past_builds` list floor (default 0.5). | +| `EMBEDDING_HNSW_M` / `EMBEDDING_HNSW_EF_CONSTRUCTION` | HNSW index build params (default 16 / 64; reindex to change). | +| `EMBEDDING_HNSW_EF_SEARCH` | HNSW query-time candidate list (default 40; higher = better recall, slower). | + +`EMBEDDING_API_KEY` (cloud embedders only) goes in the `ro-builder-env` +Secret alongside `LLM_API_KEY`. See `deploy/k8s/sealed-secrets/`. A pod +reaching a localhost embedder must use the node/host address, not +`localhost` (which resolves to the pod itself). diff --git a/deploy/helm/ro-builder/values.local.yaml b/deploy/helm/ro-builder/values.local.yaml index d664ac3..121cf0c 100644 --- a/deploy/helm/ro-builder/values.local.yaml +++ b/deploy/helm/ro-builder/values.local.yaml @@ -23,3 +23,13 @@ env: GENERATION_MAX_ITERS: "80" LLM_MODEL: claude-opus-4-7 LLM_PROVIDER: anthropic + # Embeddings / RAG (local LM Studio nomic). "localhost" is the pod itself, + # not your machine, so a pod reaches an embedder running on the + # docker-desktop host via host.docker.internal (Docker Desktop injects it + # into pods). This is committed, so it carries no machine-specific LAN IP; + # if your embedder runs on a different box, override EMBEDDING_BASE_URL in an + # uncommitted local values file. Optional knobs (EMBEDDING_SIMILAR_MAX_DISTANCE, + # EMBEDDING_HNSW_*) keep built-in defaults; see the root README. + EMBEDDING_BASE_URL: http://host.docker.internal:1234/v1 + EMBEDDING_MODEL: text-embedding-nomic-embed-text-v1.5@q8_0 + EMBEDDING_DIM: "768" diff --git a/deploy/helm/ro-builder/values.yaml b/deploy/helm/ro-builder/values.yaml index 7bd9966..3b3128f 100644 --- a/deploy/helm/ro-builder/values.yaml +++ b/deploy/helm/ro-builder/values.yaml @@ -96,6 +96,18 @@ env: GENERATION_LEASE_TTL: "" GENERATION_LEASE_SWEEP_INTERVAL: "" GENERATION_MAX_ATTEMPTS: "" + # Embeddings (optional; enables RAG over the saved-build library). + # Unset EMBEDDING_BASE_URL = recency-only retrieval, no pgvector required. + # A cloud embedder's EMBEDDING_API_KEY goes in the Secret (see + # deploy/k8s/sealed-secrets/), not here; local servers need no key. + # EMBEDDING_BASE_URL: "" # OpenAI-compatible /v1 root; presence enables the feature + # EMBEDDING_MODEL: "nomic-embed-text" # e.g. text-embedding-nomic-embed-text-v1.5@q8_0 (LM Studio) + # EMBEDDING_DIM: "768" # required when EMBEDDING_BASE_URL is set; must match model output dim + # EMBEDDING_SEED_MAX_DISTANCE: "" # Tier A proactive-seed ceiling (default 0.15) + # EMBEDDING_SIMILAR_MAX_DISTANCE: "" # Tier B get_similar_past_builds floor (default 0.5) + # EMBEDDING_HNSW_M: "" # HNSW build param (default 16; reindex to change) + # EMBEDDING_HNSW_EF_CONSTRUCTION: "" # HNSW build param (default 64; reindex to change) + # EMBEDDING_HNSW_EF_SEARCH: "" # HNSW query param (default 40; higher recall, slower) postgresql: # When true, the chart runs an in-cluster Postgres StatefulSet. Set false diff --git a/deploy/k8s/sealed-secrets/README.md b/deploy/k8s/sealed-secrets/README.md index 5881903..4fc9767 100644 --- a/deploy/k8s/sealed-secrets/README.md +++ b/deploy/k8s/sealed-secrets/README.md @@ -8,20 +8,31 @@ Encrypted secrets for ro-builder. Decrypted in-cluster by the - `local.sealed-secret.yaml.example`: committed placeholder for the local (docker-desktop) cluster's sealed secret. - `local.sealed-secret.yaml`: gitignored. Produced by `task tilt:seal`, - contains the real encrypted `LLM_API_KEY`, `POSTGRES_PASSWORD`, and - `DATABASE_URL` from your `.env`. + contains the real encrypted `LLM_API_KEY`, `POSTGRES_PASSWORD`, + `DATABASE_URL`, and optionally `EMBEDDING_API_KEY` from your `.env`. - `prod.sealed-secret.yaml.example`: committed template for a prod cluster. Sealing for prod is operator-only and happens out of band. +## Secret keys + +| Key | Required | Purpose | +|---|---|---| +| `LLM_API_KEY` | For `/generate` | LLM provider credential | +| `POSTGRES_PASSWORD` | Yes | Database password | +| `DATABASE_URL` | Yes | Full connection string | +| `EMBEDDING_API_KEY` | Optional | Cloud embedding provider (omit for a local embedder) | + ## How sealing works (local) 1. `task tilt:bootstrap` installs the sealed-secrets controller in `kube-system`. The controller generates a cluster-bound RSA key pair on first start. 2. `task tilt:seal` reads your local `.env`, builds an in-memory Secret - manifest with `LLM_API_KEY`, `POSTGRES_PASSWORD`, and `DATABASE_URL`, - pipes it through `kubeseal` (which fetches the controller's public key), - and writes the encrypted `SealedSecret` to `local.sealed-secret.yaml`. + manifest with `LLM_API_KEY`, `POSTGRES_PASSWORD`, `DATABASE_URL`, and + optionally `EMBEDDING_API_KEY` (cloud embedders only; omit for a local + embedder), pipes it through `kubeseal` (which fetches the controller's + public key), and writes the encrypted `SealedSecret` to + `local.sealed-secret.yaml`. 3. Tilt applies `local.sealed-secret.yaml` alongside the Helm chart. The controller decrypts it into a normal `Secret` named `ro-builder-env` that the api Deployment mounts via `envFrom`. diff --git a/deploy/tilt/README.md b/deploy/tilt/README.md index e770690..a177036 100644 --- a/deploy/tilt/README.md +++ b/deploy/tilt/README.md @@ -9,3 +9,24 @@ extension wiring in the root `Tiltfile`. The sidecar's calc backend is selected via the chart's `sidecar.calcBackend` value (default `rocalc`). For local work that doesn't need real calc numbers, override it via `deploy/helm/ro-builder/values.local.yaml`. + +## Embeddings (optional) + +Embedding-based RAG is off by default in the Tilt dev environment. To exercise the full embedding pipeline locally, +run an OpenAI-compatible embeddings endpoint (LM Studio, Ollama, llama.cpp, ...) and set the following in your `.env` +before `task tilt:up`: + +``` +# LM Studio (default): load an embedding model in the Developer tab, then +EMBEDDING_BASE_URL=http://localhost:1234/v1 +EMBEDDING_MODEL=text-embedding-nomic-embed-text-v1.5@q8_0 +EMBEDDING_DIM=768 +# Ollama alternative: EMBEDDING_BASE_URL=http://localhost:11434/v1, EMBEDDING_MODEL=nomic-embed-text +``` + +Then add those keys to the `env` block in `deploy/helm/ro-builder/values.local.yaml`. A pod cannot reach the embedder +via `localhost`; point `EMBEDDING_BASE_URL` at the host address the cluster can route to (on docker-desktop k8s, +`http://host.docker.internal:1234/v1`). The optional retrieval knobs (`EMBEDDING_SIMILAR_MAX_DISTANCE`, +`EMBEDDING_HNSW_*`) are documented in the root `README.md`. The bundled `pgvector/pgvector:pg17` Postgres image already +has the extension available; the bootstrap creates the vector column and HNSW index on first startup when +`EMBEDDING_BASE_URL` is set. diff --git a/docker-compose.yml b/docker-compose.yml index 958c783..49c7e5a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -96,6 +96,18 @@ services: GENERATION_LEASE_TTL: ${GENERATION_LEASE_TTL:-} GENERATION_LEASE_SWEEP_INTERVAL: ${GENERATION_LEASE_SWEEP_INTERVAL:-} GENERATION_MAX_ATTEMPTS: ${GENERATION_MAX_ATTEMPTS:-} + # Embeddings / RAG (optional). EMBEDDING_BASE_URL unset = recency-only. + # A localhost embedder must be reachable from inside the container + # (use host.docker.internal, not localhost/127.0.0.1). + EMBEDDING_BASE_URL: ${EMBEDDING_BASE_URL:-} + EMBEDDING_MODEL: ${EMBEDDING_MODEL:-} + EMBEDDING_DIM: ${EMBEDDING_DIM:-} + EMBEDDING_API_KEY: ${EMBEDDING_API_KEY:-} + EMBEDDING_SEED_MAX_DISTANCE: ${EMBEDDING_SEED_MAX_DISTANCE:-} + EMBEDDING_SIMILAR_MAX_DISTANCE: ${EMBEDDING_SIMILAR_MAX_DISTANCE:-} + EMBEDDING_HNSW_M: ${EMBEDDING_HNSW_M:-} + EMBEDDING_HNSW_EF_CONSTRUCTION: ${EMBEDDING_HNSW_EF_CONSTRUCTION:-} + EMBEDDING_HNSW_EF_SEARCH: ${EMBEDDING_HNSW_EF_SEARCH:-} LOG_LEVEL: ${LOG_LEVEL:-} LOG_FORMAT: ${LOG_FORMAT:-} diff --git a/docs/architecture/ro-builder.excalidraw b/docs/architecture/ro-builder.excalidraw old mode 100644 new mode 100755 index 5f9ef6d..0553dc6 --- a/docs/architecture/ro-builder.excalidraw +++ b/docs/architecture/ro-builder.excalidraw @@ -9,7 +9,7 @@ "x": 0, "y": 0, "width": 1710, - "height": 1340, + "height": 1436, "angle": 0, "strokeColor": "#bbbbbb", "backgroundColor": "transparent", @@ -38,7 +38,7 @@ "x": 60, "y": 44, "width": 230, - "height": 1272, + "height": 1368, "angle": 0, "strokeColor": "transparent", "backgroundColor": "#f1f3f5", @@ -66,7 +66,7 @@ "x": 290, "y": 44, "width": 230, - "height": 1272, + "height": 1368, "angle": 0, "strokeColor": "transparent", "backgroundColor": "#a5d8ff", @@ -94,7 +94,7 @@ "x": 520, "y": 44, "width": 230, - "height": 1272, + "height": 1368, "angle": 0, "strokeColor": "transparent", "backgroundColor": "#d0bfff", @@ -122,7 +122,7 @@ "x": 750, "y": 44, "width": 230, - "height": 1272, + "height": 1368, "angle": 0, "strokeColor": "transparent", "backgroundColor": "#b2f2bb", @@ -150,7 +150,7 @@ "x": 980, "y": 44, "width": 230, - "height": 1272, + "height": 1368, "angle": 0, "strokeColor": "transparent", "backgroundColor": "#ffd8a8", @@ -178,7 +178,7 @@ "x": 1210, "y": 44, "width": 230, - "height": 1272, + "height": 1368, "angle": 0, "strokeColor": "transparent", "backgroundColor": "#ffec99", @@ -206,7 +206,7 @@ "x": 1440, "y": 44, "width": 230, - "height": 1272, + "height": 1368, "angle": 0, "strokeColor": "transparent", "backgroundColor": "#fcc2d7", @@ -775,7 +775,7 @@ "x": 541, "y": 120, "width": 188, - "height": 752, + "height": 824, "angle": 0, "strokeColor": "#1e1e1e", "backgroundColor": "#d0bfff", @@ -821,6 +821,14 @@ { "type": "arrow", "id": "arrow_2o" + }, + { + "type": "arrow", + "id": "arrow_accept_2" + }, + { + "type": "arrow", + "id": "arrow_seed" } ], "updated": 1780289515342, @@ -1305,6 +1313,10 @@ { "type": "arrow", "id": "arrow_1w" + }, + { + "type": "arrow", + "id": "arrow_seed" } ], "updated": 1780289515342, @@ -2212,16 +2224,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_s", + "mode": "orbit", "fixedPoint": [ 0.5737218280042354, 0.4262781719957651 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_u", + "mode": "orbit", "fixedPoint": [ 0.39995576348287265, 0.3999557634828728 @@ -2312,16 +2324,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_u", + "mode": "orbit", "fixedPoint": [ 1, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_o", + "mode": "orbit", "fixedPoint": [ 0.03989317696216899, 0.039893176962169596 @@ -2412,16 +2424,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_u", + "mode": "orbit", "fixedPoint": [ 0.17873625669908494, 0.17873625669908505 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_w", + "mode": "orbit", "fixedPoint": [ 1, 0.5001 @@ -2507,16 +2519,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_u", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_y", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -2570,16 +2582,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_y", + "mode": "orbit", "fixedPoint": [ 1, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_o", + "mode": "orbit", "fixedPoint": [ 0.1515940724562435, 0.15159407245624434 @@ -2665,16 +2677,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_y", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_10", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -2728,16 +2740,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_10", + "mode": "orbit", "fixedPoint": [ 0.5137185207190681, 0.4862814792809331 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_12", + "mode": "orbit", "fixedPoint": [ 0.3797417007544054, 0.37974170075440516 @@ -2828,16 +2840,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_12", + "mode": "orbit", "fixedPoint": [ 0.433132331930019, 0.43313233193001793 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_14", + "mode": "orbit", "fixedPoint": [ 1, 0.5001 @@ -2928,16 +2940,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_14", + "mode": "orbit", "fixedPoint": [ 0.7585564262909847, 0.2414435737090166 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_q", + "mode": "orbit", "fixedPoint": [ 0.3670200731894287, 0.3670200731894281 @@ -3028,16 +3040,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_14", + "mode": "orbit", "fixedPoint": [ 0.8711894389939127, 0.1288105610060898 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_o", + "mode": "orbit", "fixedPoint": [ 0.36701803775357117, 0.3670180377535716 @@ -3076,11 +3088,11 @@ "locked": false, "fontSize": 11, "fontFamily": 2, - "text": "get_similar_past_builds", + "text": "get_similar_past_builds (accepted)", "textAlign": "center", "verticalAlign": "middle", "containerId": "arrow_22", - "originalText": "get_similar_past_builds", + "originalText": "get_similar_past_builds (accepted)", "lineHeight": 1.25, "autoResize": false, "index": "b0C" @@ -3128,16 +3140,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_14", + "mode": "orbit", "fixedPoint": [ 0.685823816186107, 0.3141761838138943 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_16", + "mode": "orbit", "fixedPoint": [ 0.26371112801901636, 0.2637111280190178 @@ -3228,16 +3240,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_16", + "mode": "orbit", "fixedPoint": [ 0.5898358979319833, 0.41016410206801673 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_18", + "mode": "orbit", "fixedPoint": [ 0.3797069649411658, 0.37970696494116574 @@ -3328,16 +3340,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_14", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_1a", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -3428,16 +3440,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_1a", + "mode": "orbit", "fixedPoint": [ 0.6629869571770454, 0.6629869571770466 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_16", + "mode": "orbit", "fixedPoint": [ 0.2681973116063057, 0.7318026883936947 @@ -3530,16 +3542,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_1a", + "mode": "orbit", "fixedPoint": [ 0.7131777350486203, 0.7131777350486194 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_12", + "mode": "orbit", "fixedPoint": [ 0.25218433011942226, 0.7478156698805825 @@ -3630,16 +3642,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_1a", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_1c", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -3730,16 +3742,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_1c", + "mode": "orbit", "fixedPoint": [ 0.9107945844756846, 0.9107945844756836 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_o", + "mode": "orbit", "fixedPoint": [ 0.2872365773439772, 0.7127634226560227 @@ -3830,16 +3842,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_1g", + "mode": "orbit", "fixedPoint": [ 0.5606734616781872, 0.5606734616781864 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_1e", + "mode": "orbit", "fixedPoint": [ 0.3750648179544067, 0.6249351820455923 @@ -3930,16 +3942,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_1e", + "mode": "orbit", "fixedPoint": [ 1, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_o", + "mode": "orbit", "fixedPoint": [ 0.15957587630220932, 0.8404241236977905 @@ -4030,16 +4042,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_1k", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_1i", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -4130,16 +4142,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_1i", + "mode": "orbit", "fixedPoint": [ 1, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_o", + "mode": "orbit", "fixedPoint": [ 0.04787276289066286, 0.9521272371093371 @@ -4230,16 +4242,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_1i", + "mode": "orbit", "fixedPoint": [ 0.892181938523534, 0.8921819385235329 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_q", + "mode": "orbit", "fixedPoint": [ 0.047872497392602256, 0.9521275026073974 @@ -4291,7 +4303,7 @@ "id": "line_2s", "type": "line", "x": 60, - "y": 890, + "y": 986, "width": 1610, "height": 0, "angle": 0, @@ -4335,7 +4347,7 @@ "id": "text_2t", "type": "text", "x": 60, - "y": 900, + "y": 996, "width": 600, "height": 20, "angle": 0, @@ -4372,7 +4384,7 @@ "id": "rectangle_2u", "type": "rectangle", "x": 81, - "y": 928, + "y": 1024, "width": 188, "height": 60, "angle": 0, @@ -4411,7 +4423,7 @@ "id": "text_2v", "type": "text", "x": 86, - "y": 940.5, + "y": 1036.5, "width": 178, "height": 35, "angle": 0, @@ -4448,7 +4460,7 @@ "id": "rectangle_2w", "type": "rectangle", "x": 311, - "y": 928, + "y": 1024, "width": 188, "height": 60, "angle": 0, @@ -4495,7 +4507,7 @@ "id": "text_2x", "type": "text", "x": 316, - "y": 940.5, + "y": 1036.5, "width": 178, "height": 35, "angle": 0, @@ -4532,7 +4544,7 @@ "id": "rectangle_2y", "type": "rectangle", "x": 1001, - "y": 928, + "y": 1024, "width": 188, "height": 60, "angle": 0, @@ -4575,7 +4587,7 @@ "id": "text_2z", "type": "text", "x": 1006, - "y": 940.5, + "y": 1036.5, "width": 178, "height": 35, "angle": 0, @@ -4612,7 +4624,7 @@ "id": "rectangle_30", "type": "rectangle", "x": 1231, - "y": 928, + "y": 1024, "width": 188, "height": 60, "angle": 0, @@ -4651,7 +4663,7 @@ "id": "text_31", "type": "text", "x": 1236, - "y": 940.5, + "y": 1036.5, "width": 178, "height": 35, "angle": 0, @@ -4688,7 +4700,7 @@ "id": "rectangle_32", "type": "rectangle", "x": 81, - "y": 1024, + "y": 1120, "width": 188, "height": 60, "angle": 0, @@ -4727,7 +4739,7 @@ "id": "text_33", "type": "text", "x": 86, - "y": 1036.5, + "y": 1132.5, "width": 178, "height": 35, "angle": 0, @@ -4764,7 +4776,7 @@ "id": "arrow_34", "type": "arrow", "x": 269, - "y": 958, + "y": 1054, "width": 42, "height": 0, "angle": 0, @@ -4803,16 +4815,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_2u", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_2w", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -4827,7 +4839,7 @@ "id": "text_35", "type": "text", "x": 257, - "y": 950, + "y": 1046, "width": 66, "height": 16, "angle": 0, @@ -4864,7 +4876,7 @@ "id": "arrow_36", "type": "arrow", "x": 499, - "y": 958, + "y": 1054, "width": 502, "height": 0, "angle": 0, @@ -4903,16 +4915,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_2w", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_2y", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -4927,7 +4939,7 @@ "id": "text_37", "type": "text", "x": 735, - "y": 950, + "y": 1046, "width": 30, "height": 16, "angle": 0, @@ -4964,7 +4976,7 @@ "id": "arrow_38", "type": "arrow", "x": 1189, - "y": 958, + "y": 1054, "width": 42, "height": 0, "angle": 0, @@ -5003,16 +5015,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_2y", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_30", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -5027,7 +5039,7 @@ "id": "text_39", "type": "text", "x": 1180, - "y": 950, + "y": 1046, "width": 60, "height": 16, "angle": 0, @@ -5064,7 +5076,7 @@ "id": "arrow_3a", "type": "arrow", "x": 311, - "y": 958, + "y": 1054, "width": 42, "height": 76, "angle": 0, @@ -5103,16 +5115,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_2w", + "mode": "orbit", "fixedPoint": [ 0.15565613553115706, 0.1556561355311563 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_32", + "mode": "orbit", "fixedPoint": [ 0.6970358161083617, 0.6970358161083595 @@ -5127,7 +5139,7 @@ "id": "text_3b", "type": "text", "x": 251, - "y": 988, + "y": 1084, "width": 78, "height": 16, "angle": 0, @@ -5164,7 +5176,7 @@ "id": "line_3c", "type": "line", "x": 58.33333333333326, - "y": 1096, + "y": 1192, "width": 1610, "height": 0, "angle": 0, @@ -5208,7 +5220,7 @@ "id": "text_3d", "type": "text", "x": 60, - "y": 1086, + "y": 1182, "width": 600, "height": 20, "angle": 0, @@ -5245,7 +5257,7 @@ "id": "rectangle_3e", "type": "rectangle", "x": 81, - "y": 1114, + "y": 1210, "width": 188, "height": 48, "angle": 0, @@ -5284,7 +5296,7 @@ "id": "text_3f", "type": "text", "x": 86, - "y": 1129.25, + "y": 1225.25, "width": 178, "height": 17.5, "angle": 0, @@ -5321,7 +5333,7 @@ "id": "rectangle_3g", "type": "rectangle", "x": 311, - "y": 1114, + "y": 1210, "width": 188, "height": 60, "angle": 0, @@ -5372,7 +5384,7 @@ "id": "text_3h", "type": "text", "x": 316, - "y": 1126.5, + "y": 1222.5, "width": 178, "height": 35, "angle": 0, @@ -5409,7 +5421,7 @@ "id": "rectangle_3i", "type": "rectangle", "x": 541, - "y": 1114, + "y": 1210, "width": 188, "height": 48, "angle": 0, @@ -5448,7 +5460,7 @@ "id": "text_3j", "type": "text", "x": 546, - "y": 1129.25, + "y": 1225.25, "width": 178, "height": 17.5, "angle": 0, @@ -5485,7 +5497,7 @@ "id": "rectangle_3k", "type": "rectangle", "x": 771, - "y": 1114, + "y": 1210, "width": 188, "height": 60, "angle": 0, @@ -5524,7 +5536,7 @@ "id": "text_3l", "type": "text", "x": 776, - "y": 1126.5, + "y": 1222.5, "width": 178, "height": 35, "angle": 0, @@ -5561,7 +5573,7 @@ "id": "rectangle_3m", "type": "rectangle", "x": 81, - "y": 1210, + "y": 1306, "width": 188, "height": 60, "angle": 0, @@ -5600,7 +5612,7 @@ "id": "text_3n", "type": "text", "x": 86, - "y": 1222.5, + "y": 1318.5, "width": 178, "height": 35, "angle": 0, @@ -5637,7 +5649,7 @@ "id": "arrow_3o", "type": "arrow", "x": 269, - "y": 1138, + "y": 1234, "width": 42, "height": 0, "angle": 0, @@ -5676,16 +5688,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_3e", + "mode": "orbit", "fixedPoint": [ 0.5737218280042359, 0.4262781719957663 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_3g", + "mode": "orbit", "fixedPoint": [ 0.3999557634828705, 0.39995576348286854 @@ -5700,7 +5712,7 @@ "id": "text_3p", "type": "text", "x": 257, - "y": 1130, + "y": 1226, "width": 66, "height": 16, "angle": 0, @@ -5737,7 +5749,7 @@ "id": "arrow_3q", "type": "arrow", "x": 499, - "y": 1144, + "y": 1240, "width": 42, "height": 0, "angle": 0, @@ -5776,16 +5788,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_3g", + "mode": "orbit", "fixedPoint": [ 0.5606734616781839, 0.5606734616781789 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_3i", + "mode": "orbit", "fixedPoint": [ 0.3750648179544125, 0.62493518204559 @@ -5800,7 +5812,7 @@ "id": "text_3r", "type": "text", "x": 508, - "y": 1136, + "y": 1232, "width": 24, "height": 16, "angle": 0, @@ -5837,7 +5849,7 @@ "id": "arrow_3s", "type": "arrow", "x": 499, - "y": 1144, + "y": 1240, "width": 272, "height": 0, "angle": 0, @@ -5876,16 +5888,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_3g", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_3k", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -5900,7 +5912,7 @@ "id": "text_3t", "type": "text", "x": 617, - "y": 1136, + "y": 1232, "width": 36, "height": 16, "angle": 0, @@ -5937,7 +5949,7 @@ "id": "arrow_3u", "type": "arrow", "x": 311, - "y": 1144, + "y": 1240, "width": 42, "height": 76, "angle": 0, @@ -5976,16 +5988,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_3g", + "mode": "orbit", "fixedPoint": [ 0.15565613553117882, 0.15565613553117524 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_3m", + "mode": "orbit", "fixedPoint": [ 0.6970358161083121, 0.6970358161083141 @@ -6000,7 +6012,7 @@ "id": "text_3v", "type": "text", "x": 260, - "y": 1174, + "y": 1270, "width": 60, "height": 16, "angle": 0, @@ -6033,35 +6045,6 @@ "autoResize": false, "index": "b1E" }, - { - "id": "frame_3w", - "type": "frame", - "x": 1850, - "y": 0, - "width": 980, - "height": 1080, - "angle": 0, - "strokeColor": "#bbbbbb", - "backgroundColor": "transparent", - "fillStyle": "solid", - "strokeWidth": 2, - "strokeStyle": "solid", - "roughness": 1, - "opacity": 100, - "groupIds": [], - "frameId": null, - "roundness": null, - "seed": 1304035654, - "version": 2, - "versionNonce": 1942757401, - "isDeleted": false, - "boundElements": [], - "updated": 1780289515342, - "link": null, - "locked": false, - "name": "2 · High-level architecture", - "index": "b1F" - }, { "id": "rectangle_3x", "type": "rectangle", @@ -6083,14 +6066,14 @@ "type": 3 }, "seed": 14690408, - "version": 2, - "versionNonce": 379079159, + "version": 7, + "versionNonce": 36693375, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1G" + "index": "b1E0V" }, { "id": "text_3y", @@ -6111,11 +6094,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 2559587802, - "version": 2, - "versionNonce": 1969403129, + "version": 7, + "versionNonce": 1699378673, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 17, @@ -6127,7 +6110,7 @@ "originalText": "Go API · cmd/api (deployable unit)", "lineHeight": 1.25, "autoResize": true, - "index": "b1H" + "index": "b1E1" }, { "id": "rectangle_3z", @@ -6150,8 +6133,8 @@ "type": 3 }, "seed": 797838876, - "version": 2, - "versionNonce": 252310295, + "version": 7, + "versionNonce": 1127538079, "isDeleted": false, "boundElements": [ { @@ -6167,10 +6150,10 @@ "id": "arrow_4j" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1I" + "index": "b1E2" }, { "id": "text_40", @@ -6191,11 +6174,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 1397328302, - "version": 2, - "versionNonce": 890482137, + "version": 7, + "versionNonce": 1565036497, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -6207,7 +6190,7 @@ "originalText": "HTTP handlers", "lineHeight": 1.25, "autoResize": false, - "index": "b1J" + "index": "b1E3" }, { "id": "rectangle_41", @@ -6230,8 +6213,8 @@ "type": 3 }, "seed": 1885771024, - "version": 2, - "versionNonce": 430536759, + "version": 7, + "versionNonce": 1696977343, "isDeleted": false, "boundElements": [ { @@ -6247,10 +6230,10 @@ "id": "arrow_4i" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1K" + "index": "b1E4" }, { "id": "text_42", @@ -6271,11 +6254,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 1679446210, - "version": 2, - "versionNonce": 1240631993, + "version": 7, + "versionNonce": 1177054641, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -6287,7 +6270,7 @@ "originalText": "Worker pool\n(async /generate)", "lineHeight": 1.25, "autoResize": false, - "index": "b1L" + "index": "b1E5" }, { "id": "rectangle_43", @@ -6310,8 +6293,8 @@ "type": 3 }, "seed": 3928305988, - "version": 2, - "versionNonce": 1817925975, + "version": 7, + "versionNonce": 1629700575, "isDeleted": false, "boundElements": [ { @@ -6335,10 +6318,10 @@ "id": "arrow_4t" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1M" + "index": "b1E6" }, { "id": "text_44", @@ -6359,11 +6342,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 443686678, - "version": 2, - "versionNonce": 480431001, + "version": 7, + "versionNonce": 655462289, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -6375,7 +6358,7 @@ "originalText": "Orchestrator\n(LLM tool-loop)", "lineHeight": 1.25, "autoResize": false, - "index": "b1N" + "index": "b1E7" }, { "id": "rectangle_45", @@ -6398,8 +6381,8 @@ "type": 3 }, "seed": 2258802360, - "version": 2, - "versionNonce": 208934519, + "version": 7, + "versionNonce": 943566335, "isDeleted": false, "boundElements": [ { @@ -6423,10 +6406,10 @@ "id": "arrow_4r" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1O" + "index": "b1E8" }, { "id": "text_46", @@ -6447,11 +6430,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 386910378, - "version": 2, - "versionNonce": 894955641, + "version": 7, + "versionNonce": 909866353, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -6463,7 +6446,7 @@ "originalText": "Tool registry", "lineHeight": 1.25, "autoResize": false, - "index": "b1P" + "index": "b1E8V" }, { "id": "rectangle_47", @@ -6486,8 +6469,8 @@ "type": 3 }, "seed": 1476966764, - "version": 2, - "versionNonce": 1622683543, + "version": 7, + "versionNonce": 1970640415, "isDeleted": false, "boundElements": [ { @@ -6507,10 +6490,10 @@ "id": "arrow_5j" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1Q" + "index": "b1E9" }, { "id": "text_48", @@ -6531,11 +6514,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 3411370366, - "version": 2, - "versionNonce": 1238727001, + "version": 7, + "versionNonce": 1995284305, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -6547,7 +6530,7 @@ "originalText": "LLM provider\n(Anthropic / OpenAI)", "lineHeight": 1.25, "autoResize": false, - "index": "b1R" + "index": "b1EA" }, { "id": "rectangle_49", @@ -6570,8 +6553,8 @@ "type": 3 }, "seed": 3611741536, - "version": 2, - "versionNonce": 56370359, + "version": 7, + "versionNonce": 1874557503, "isDeleted": false, "boundElements": [ { @@ -6591,10 +6574,10 @@ "id": "arrow_5f" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1S" + "index": "b1EB" }, { "id": "text_4a", @@ -6615,11 +6598,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 1675378066, - "version": 2, - "versionNonce": 191817273, + "version": 7, + "versionNonce": 394235185, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -6631,7 +6614,7 @@ "originalText": "Scoring client", "lineHeight": 1.25, "autoResize": false, - "index": "b1T" + "index": "b1EC" }, { "id": "rectangle_4b", @@ -6654,8 +6637,8 @@ "type": 3 }, "seed": 4022683284, - "version": 2, - "versionNonce": 1409578455, + "version": 7, + "versionNonce": 1274010207, "isDeleted": false, "boundElements": [ { @@ -6669,12 +6652,16 @@ { "type": "arrow", "id": "arrow_4t" + }, + { + "type": "arrow", + "id": "embed_arrow_bl" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1U" + "index": "b1ED" }, { "id": "text_4c", @@ -6695,23 +6682,23 @@ "frameId": "frame_3w", "roundness": null, "seed": 843641062, - "version": 2, - "versionNonce": 889698073, + "version": 7, + "versionNonce": 257474321, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, "fontFamily": 2, - "text": "Build library\n(PostgreSQL)", + "text": "Build library\n(PostgreSQL + pgvector)", "textAlign": "center", "verticalAlign": "middle", "containerId": "rectangle_4b", - "originalText": "Build library\n(PostgreSQL)", + "originalText": "Build library\n(PostgreSQL + pgvector)", "lineHeight": 1.25, "autoResize": false, - "index": "b1V" + "index": "b1EE" }, { "id": "rectangle_4d", @@ -6734,8 +6721,8 @@ "type": 3 }, "seed": 207214856, - "version": 2, - "versionNonce": 1237689079, + "version": 7, + "versionNonce": 1055078015, "isDeleted": false, "boundElements": [ { @@ -6751,10 +6738,10 @@ "id": "arrow_5n" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1W" + "index": "b1EF" }, { "id": "text_4e", @@ -6775,11 +6762,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 3932114810, - "version": 2, - "versionNonce": 1494445049, + "version": 7, + "versionNonce": 2096149745, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -6791,7 +6778,7 @@ "originalText": "Embedded catalog\n(//go:embed)", "lineHeight": 1.25, "autoResize": false, - "index": "b1X" + "index": "b1EG" }, { "id": "rectangle_4f", @@ -6814,8 +6801,8 @@ "type": 3 }, "seed": 2575005884, - "version": 2, - "versionNonce": 86256663, + "version": 7, + "versionNonce": 257298079, "isDeleted": false, "boundElements": [ { @@ -6827,10 +6814,10 @@ "id": "arrow_4v" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1Y" + "index": "b1EGV" }, { "id": "text_4g", @@ -6851,11 +6838,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 1180069198, - "version": 2, - "versionNonce": 1872069849, + "version": 7, + "versionNonce": 1137635025, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -6867,7 +6854,7 @@ "originalText": "Server profiles\n(YAML, embedded)", "lineHeight": 1.25, "autoResize": false, - "index": "b1Z" + "index": "b1EH" }, { "id": "arrow_4h", @@ -6888,11 +6875,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 2964740528, - "version": 2, - "versionNonce": 571773239, + "version": 7, + "versionNonce": 1475928767, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -6907,16 +6894,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_3z", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_41", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -6925,7 +6912,7 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b1a" + "index": "b1EI" }, { "id": "arrow_4i", @@ -6946,11 +6933,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 3865878114, - "version": 2, - "versionNonce": 606175673, + "version": 7, + "versionNonce": 1787489457, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -6965,16 +6952,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_41", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_43", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -6983,7 +6970,7 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b1b" + "index": "b1EJ" }, { "id": "arrow_4j", @@ -7004,8 +6991,8 @@ "frameId": "frame_3w", "roundness": null, "seed": 3781160932, - "version": 2, - "versionNonce": 1241207383, + "version": 7, + "versionNonce": 158085855, "isDeleted": false, "boundElements": [ { @@ -7013,7 +7000,7 @@ "id": "text_4k" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -7028,16 +7015,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_3z", + "mode": "orbit", "fixedPoint": [ 0.9387230311385167, 0.061276968861485495 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_49", + "mode": "orbit", "fixedPoint": [ 0.10525274873902125, 0.8947472512609764 @@ -7046,7 +7033,7 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b1c" + "index": "b1EK" }, { "id": "text_4k", @@ -7067,11 +7054,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 2142992054, - "version": 2, - "versionNonce": 1675289241, + "version": 7, + "versionNonce": 952905361, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 11, @@ -7083,7 +7070,7 @@ "originalText": "/score", "lineHeight": 1.25, "autoResize": false, - "index": "b1d" + "index": "b1EL" }, { "id": "arrow_4l", @@ -7104,11 +7091,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 1250619224, - "version": 2, - "versionNonce": 95219575, + "version": 7, + "versionNonce": 742424319, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -7123,16 +7110,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_43", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_47", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -7141,7 +7128,7 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b1e" + "index": "b1EM" }, { "id": "arrow_4m", @@ -7162,11 +7149,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 2924202570, - "version": 2, - "versionNonce": 729098105, + "version": 7, + "versionNonce": 357184625, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -7181,16 +7168,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_43", + "mode": "orbit", "fixedPoint": [ 0.8479533191081771, 0.8479533191081762 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_45", + "mode": "orbit", "fixedPoint": [ 0.26083354545355064, 0.26083354545355064 @@ -7199,7 +7186,7 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b1f" + "index": "b1EN" }, { "id": "arrow_4n", @@ -7220,8 +7207,8 @@ "frameId": "frame_3w", "roundness": null, "seed": 2050706444, - "version": 2, - "versionNonce": 1332603031, + "version": 7, + "versionNonce": 1660307231, "isDeleted": false, "boundElements": [ { @@ -7229,7 +7216,7 @@ "id": "text_4o" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -7244,16 +7231,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_45", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_49", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -7262,7 +7249,7 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b1g" + "index": "b1EO" }, { "id": "text_4o", @@ -7283,11 +7270,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 4268338462, - "version": 2, - "versionNonce": 355717209, + "version": 7, + "versionNonce": 600604241, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 11, @@ -7299,7 +7286,7 @@ "originalText": "score_build", "lineHeight": 1.25, "autoResize": false, - "index": "b1h" + "index": "b1EOV" }, { "id": "arrow_4p", @@ -7320,8 +7307,8 @@ "frameId": "frame_3w", "roundness": null, "seed": 3319413248, - "version": 2, - "versionNonce": 1693629879, + "version": 7, + "versionNonce": 738069311, "isDeleted": false, "boundElements": [ { @@ -7329,7 +7316,7 @@ "id": "text_4q" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -7344,16 +7331,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_45", + "mode": "orbit", "fixedPoint": [ 0.07987081687379222, 0.07987081687379369 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_4b", + "mode": "orbit", "fixedPoint": [ 0.8424163636562109, 0.8424163636562109 @@ -7362,7 +7349,7 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b1i" + "index": "b1EP" }, { "id": "text_4q", @@ -7383,11 +7370,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 20476722, - "version": 2, - "versionNonce": 652893497, + "version": 7, + "versionNonce": 589990961, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 11, @@ -7399,7 +7386,7 @@ "originalText": "similar builds", "lineHeight": 1.25, "autoResize": false, - "index": "b1j" + "index": "b1EQ" }, { "id": "arrow_4r", @@ -7420,8 +7407,8 @@ "frameId": "frame_3w", "roundness": null, "seed": 267005236, - "version": 2, - "versionNonce": 1499459287, + "version": 7, + "versionNonce": 1673022303, "isDeleted": false, "boundElements": [ { @@ -7429,7 +7416,7 @@ "id": "text_4s" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -7444,16 +7431,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_45", + "mode": "orbit", "fixedPoint": [ 0, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_4d", + "mode": "orbit", "fixedPoint": [ 0.8979771251932467, 0.8979771251932473 @@ -7462,7 +7449,7 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b1k" + "index": "b1ER" }, { "id": "text_4s", @@ -7483,11 +7470,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 2156310662, - "version": 2, - "versionNonce": 1610370585, + "version": 7, + "versionNonce": 189521425, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 11, @@ -7499,7 +7486,7 @@ "originalText": "lookups", "lineHeight": 1.25, "autoResize": false, - "index": "b1l" + "index": "b1ES" }, { "id": "arrow_4t", @@ -7520,8 +7507,8 @@ "frameId": "frame_3w", "roundness": null, "seed": 788191656, - "version": 2, - "versionNonce": 1732901879, + "version": 7, + "versionNonce": 108365695, "isDeleted": false, "boundElements": [ { @@ -7529,7 +7516,7 @@ "id": "text_4u" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -7544,16 +7531,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_43", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_4b", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -7562,7 +7549,7 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b1m" + "index": "b1ET" }, { "id": "text_4u", @@ -7583,11 +7570,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 635582746, - "version": 2, - "versionNonce": 123544313, + "version": 7, + "versionNonce": 1797780465, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 11, @@ -7599,7 +7586,7 @@ "originalText": "save / load", "lineHeight": 1.25, "autoResize": false, - "index": "b1n" + "index": "b1EU" }, { "id": "arrow_4v", @@ -7620,11 +7607,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 1776104284, - "version": 2, - "versionNonce": 45442327, + "version": 7, + "versionNonce": 846610335, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -7639,16 +7626,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_47", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_4f", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -7657,15 +7644,15 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b1o" + "index": "b1EUV" }, { "id": "rectangle_4w", "type": "rectangle", - "x": 1890, + "x": 1878.75, "y": 730, - "width": 600, - "height": 300, + "width": 888.7500000000002, + "height": 233.75, "angle": 0, "strokeColor": "#495057", "backgroundColor": "transparent", @@ -7680,14 +7667,14 @@ "type": 3 }, "seed": 686563566, - "version": 2, - "versionNonce": 965762009, + "version": 92, + "versionNonce": 113659345, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1p" + "index": "b1EV" }, { "id": "text_4x", @@ -7708,11 +7695,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 3172429392, - "version": 2, - "versionNonce": 722905655, + "version": 7, + "versionNonce": 1777005503, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 17, @@ -7724,7 +7711,7 @@ "originalText": "Calc sidecar · Node (deployable unit)", "lineHeight": 1.25, "autoResize": true, - "index": "b1q" + "index": "b1EVV" }, { "id": "rectangle_4y", @@ -7747,8 +7734,8 @@ "type": 3 }, "seed": 3639393282, - "version": 2, - "versionNonce": 917076153, + "version": 7, + "versionNonce": 893283249, "isDeleted": false, "boundElements": [ { @@ -7764,10 +7751,10 @@ "id": "arrow_5f" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1r" + "index": "b1EW" }, { "id": "text_4z", @@ -7788,11 +7775,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 3717791364, - "version": 2, - "versionNonce": 2102545239, + "version": 7, + "versionNonce": 351544287, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -7804,7 +7791,7 @@ "originalText": "server.ts\nPOST /score", "lineHeight": 1.25, "autoResize": false, - "index": "b1s" + "index": "b1EX" }, { "id": "rectangle_50", @@ -7827,8 +7814,8 @@ "type": 3 }, "seed": 363306582, - "version": 2, - "versionNonce": 1884027289, + "version": 9, + "versionNonce": 2125974929, "isDeleted": false, "boundElements": [ { @@ -7840,14 +7827,14 @@ "id": "arrow_58" }, { - "type": "arrow", - "id": "arrow_59" + "id": "arrow_59", + "type": "arrow" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1t" + "index": "b1EY" }, { "id": "text_51", @@ -7868,11 +7855,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 749639672, - "version": 2, - "versionNonce": 96258167, + "version": 8, + "versionNonce": 1134710783, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -7884,13 +7871,13 @@ "originalText": "ShimPool\n(SIDECAR_WORKERS)", "lineHeight": 1.25, "autoResize": false, - "index": "b1u" + "index": "b1EZ" }, { "id": "rectangle_52", "type": "rectangle", - "x": 2220, - "y": 880, + "x": 2227.5, + "y": 877.5, "width": 240, "height": 60, "angle": 0, @@ -7907,8 +7894,8 @@ "type": 3 }, "seed": 191863786, - "version": 2, - "versionNonce": 1470848633, + "version": 206, + "versionNonce": 2053763953, "isDeleted": false, "boundElements": [ { @@ -7917,23 +7904,23 @@ }, { "type": "arrow", - "id": "arrow_59" + "id": "arrow_5b" }, { - "type": "arrow", - "id": "arrow_5b" + "id": "arrow_59", + "type": "arrow" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1v" + "index": "b1Ea" }, { "id": "text_53", "type": "text", - "x": 2225, - "y": 892.5, + "x": 2232.5, + "y": 890, "width": 230, "height": 35, "angle": 0, @@ -7948,11 +7935,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 288763564, - "version": 2, - "versionNonce": 1377477015, + "version": 205, + "versionNonce": 804648991, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -7964,7 +7951,7 @@ "originalText": "Worker threads\nJSDOM + backend", "lineHeight": 1.25, "autoResize": false, - "index": "b1w" + "index": "b1Eb" }, { "id": "rectangle_54", @@ -7987,8 +7974,8 @@ "type": 3 }, "seed": 3329935550, - "version": 2, - "versionNonce": 1804281689, + "version": 7, + "versionNonce": 1822186833, "isDeleted": false, "boundElements": [ { @@ -8004,10 +7991,10 @@ "id": "arrow_5d" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1x" + "index": "b1Ec" }, { "id": "text_55", @@ -8028,11 +8015,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 1779627680, - "version": 2, - "versionNonce": 1134581431, + "version": 7, + "versionNonce": 2145360959, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -8044,13 +8031,13 @@ "originalText": "Backend registry\n(rocalc / stub)", "lineHeight": 1.25, "autoResize": false, - "index": "b1y" + "index": "b1Ed" }, { "id": "rectangle_56", "type": "rectangle", - "x": 2220, - "y": 960, + "x": 2498.75, + "y": 887.25, "width": 240, "height": 44, "angle": 0, @@ -8067,8 +8054,8 @@ "type": 3 }, "seed": 1903589586, - "version": 2, - "versionNonce": 104780857, + "version": 81, + "versionNonce": 614894385, "isDeleted": false, "boundElements": [ { @@ -8080,16 +8067,16 @@ "id": "arrow_5d" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b1z" + "index": "b1EdV" }, { "id": "text_57", "type": "text", - "x": 2225, - "y": 973.25, + "x": 2503.75, + "y": 900.5, "width": 230, "height": 17.5, "angle": 0, @@ -8104,11 +8091,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 232874964, - "version": 2, - "versionNonce": 552757207, + "version": 81, + "versionNonce": 1195359327, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -8120,7 +8107,7 @@ "originalText": "mapping.json", "lineHeight": 1.25, "autoResize": false, - "index": "b20" + "index": "b1Ee" }, { "id": "arrow_58", @@ -8141,11 +8128,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 1398489126, - "version": 2, - "versionNonce": 1806296345, + "version": 7, + "versionNonce": 451935505, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -8160,16 +8147,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_4y", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_50", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -8178,15 +8165,15 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b21" + "index": "b1Ef" }, { "id": "arrow_59", "type": "arrow", - "x": 2160, - "y": 907, - "width": 60, - "height": 0, + "x": 2166, + "y": 907.0498977777778, + "width": 55.5, + "height": 0.4116044444444924, "angle": 0, "strokeColor": "#343a40", "backgroundColor": "transparent", @@ -8199,8 +8186,8 @@ "frameId": "frame_3w", "roundness": null, "seed": 2347444808, - "version": 2, - "versionNonce": 1747277047, + "version": 98, + "versionNonce": 1239865471, "isDeleted": false, "boundElements": [ { @@ -8208,7 +8195,7 @@ "id": "text_5a" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -8217,39 +8204,39 @@ 0 ], [ - 60, - 0 + 55.5, + 0.4116044444444924 ] ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_50", + "mode": "orbit", "fixedPoint": [ - 0.5345426715757242, - 0.46545732842427395 + 1, + 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_52", + "mode": "orbit", "fixedPoint": [ - 0.44994599927998896, - 0.44994599927999274 + 0, + 0.5001 ] }, "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b22" + "index": "b1Eg" }, { "id": "text_5a", "type": "text", "x": 2166, - "y": 899, - "width": 48, - "height": 16, + "y": 995, + "width": 40.96666717529297, + "height": 13.75, "angle": 0, "strokeColor": "#495057", "backgroundColor": "transparent", @@ -8262,11 +8249,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 3766547130, - "version": 2, - "versionNonce": 390060537, + "version": 8, + "versionNonce": 1324364529, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 11, @@ -8278,15 +8265,15 @@ "originalText": "dispatch", "lineHeight": 1.25, "autoResize": false, - "index": "b23" + "index": "b1Eh" }, { "id": "arrow_5b", "type": "arrow", - "x": 2340, - "y": 880, - "width": 0, - "height": 36, + "x": 2346.18071641791, + "y": 871.5, + "width": 4.813432835820549, + "height": 21.5, "angle": 0, "strokeColor": "#343a40", "backgroundColor": "transparent", @@ -8299,8 +8286,8 @@ "frameId": "frame_3w", "roundness": null, "seed": 2723888636, - "version": 2, - "versionNonce": 1623039511, + "version": 204, + "versionNonce": 2106945695, "isDeleted": false, "boundElements": [ { @@ -8308,7 +8295,7 @@ "id": "text_5c" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -8317,22 +8304,22 @@ 0 ], [ - 0, - -36 + -4.813432835820549, + -21.5 ] ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_52", + "mode": "orbit", "fixedPoint": [ 0.5001, 0 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_54", + "mode": "orbit", "fixedPoint": [ 0.5001, 1 @@ -8341,15 +8328,16 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b24" + "index": "b1Ei", + "moveMidPointsWithElement": false }, { "id": "text_5c", "type": "text", "x": 2310, "y": 854, - "width": 60, - "height": 16, + "width": 55.63333511352539, + "height": 13.75, "angle": 0, "strokeColor": "#495057", "backgroundColor": "transparent", @@ -8362,11 +8350,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 1928504462, - "version": 2, - "versionNonce": 1241789145, + "version": 8, + "versionNonce": 1697557713, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 11, @@ -8378,15 +8366,15 @@ "originalText": "createShim", "lineHeight": 1.25, "autoResize": false, - "index": "b25" + "index": "b1Ej" }, { "id": "arrow_5d", "type": "arrow", - "x": 2340, - "y": 844, - "width": 0, - "height": 116, + "x": 2439.724210842394, + "y": 850.0000000000001, + "width": 94.42853039057309, + "height": 31.249999999999773, "angle": 0, "strokeColor": "#343a40", "backgroundColor": "transparent", @@ -8399,8 +8387,8 @@ "frameId": "frame_3w", "roundness": null, "seed": 498193136, - "version": 2, - "versionNonce": 1840235319, + "version": 81, + "versionNonce": 1274807487, "isDeleted": false, "boundElements": [ { @@ -8408,7 +8396,7 @@ "id": "text_5e" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -8417,22 +8405,22 @@ 0 ], [ - 0, - 116 + 94.42853039057309, + 31.249999999999773 ] ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_54", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_56", + "mode": "orbit", "fixedPoint": [ 0.5001, 0.5001 @@ -8441,15 +8429,16 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b26" + "index": "b1Ek", + "moveMidPointsWithElement": false }, { "id": "text_5e", "type": "text", "x": 2304, - "y": 894, - "width": 72, - "height": 16, + "y": 990, + "width": 65.4000015258789, + "height": 13.75, "angle": 0, "strokeColor": "#495057", "backgroundColor": "transparent", @@ -8462,11 +8451,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 2114103714, - "version": 2, - "versionNonce": 1485467577, + "version": 8, + "versionNonce": 88271537, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 11, @@ -8478,7 +8467,7 @@ "originalText": "iRO ↔ rocalc", "lineHeight": 1.25, "autoResize": false, - "index": "b27" + "index": "b1El" }, { "id": "arrow_5f", @@ -8501,8 +8490,8 @@ "type": 2 }, "seed": 360209700, - "version": 2, - "versionNonce": 526402647, + "version": 7, + "versionNonce": 347804895, "isDeleted": false, "boundElements": [ { @@ -8510,7 +8499,7 @@ "id": "text_5g" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -8525,16 +8514,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_49", + "mode": "orbit", "fixedPoint": [ 0, 0.5001 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_4y", + "mode": "orbit", "fixedPoint": [ 0.9010362818591015, 0.9010362818591005 @@ -8543,7 +8532,7 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b28" + "index": "b1ElV" }, { "id": "text_5g", @@ -8564,11 +8553,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 1360958966, - "version": 2, - "versionNonce": 955650201, + "version": 7, + "versionNonce": 2010410129, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 11, @@ -8580,7 +8569,7 @@ "originalText": "HTTP /score", "lineHeight": 1.25, "autoResize": false, - "index": "b29" + "index": "b1Em" }, { "id": "rectangle_5h", @@ -8603,8 +8592,8 @@ "type": 3 }, "seed": 3124072600, - "version": 2, - "versionNonce": 94609783, + "version": 7, + "versionNonce": 1868767487, "isDeleted": false, "boundElements": [ { @@ -8616,10 +8605,10 @@ "id": "arrow_5j" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b2A" + "index": "b1En" }, { "id": "text_5i", @@ -8640,11 +8629,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 3185786250, - "version": 2, - "versionNonce": 1358599545, + "version": 7, + "versionNonce": 77247089, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -8656,7 +8645,7 @@ "originalText": "LLM API\n(Anthropic /\nOpenAI-compatible)", "lineHeight": 1.25, "autoResize": false, - "index": "b2B" + "index": "b1Eo" }, { "id": "arrow_5j", @@ -8677,8 +8666,8 @@ "frameId": "frame_3w", "roundness": null, "seed": 681664844, - "version": 2, - "versionNonce": 1102994071, + "version": 7, + "versionNonce": 762620191, "isDeleted": false, "boundElements": [ { @@ -8686,7 +8675,7 @@ "id": "text_5k" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -8701,16 +8690,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_47", + "mode": "orbit", "fixedPoint": [ 0.5188351390246188, 0.48116486097538125 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_5h", + "mode": "orbit", "fixedPoint": [ 0.46870186886097975, 0.4687018688609781 @@ -8719,7 +8708,7 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b2C" + "index": "b1Ep" }, { "id": "text_5k", @@ -8740,11 +8729,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 896578654, - "version": 2, - "versionNonce": 64716377, + "version": 7, + "versionNonce": 274545745, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 11, @@ -8756,7 +8745,7 @@ "originalText": "HTTPS", "lineHeight": 1.25, "autoResize": false, - "index": "b2D" + "index": "b1Eq" }, { "id": "rectangle_5l", @@ -8779,8 +8768,8 @@ "type": 3 }, "seed": 4128834368, - "version": 2, - "versionNonce": 1483009975, + "version": 7, + "versionNonce": 476065087, "isDeleted": false, "boundElements": [ { @@ -8792,10 +8781,10 @@ "id": "arrow_5n" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, - "index": "b2E" + "index": "b1Er" }, { "id": "text_5m", @@ -8816,11 +8805,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 821972594, - "version": 2, - "versionNonce": 7097145, + "version": 7, + "versionNonce": 2062780977, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 14, @@ -8832,7 +8821,7 @@ "originalText": "Emulator db (Hercules / rAthena)", "lineHeight": 1.25, "autoResize": false, - "index": "b2F" + "index": "b1Es" }, { "id": "arrow_5n", @@ -8855,8 +8844,8 @@ "type": 2 }, "seed": 1783818868, - "version": 2, - "versionNonce": 1136386263, + "version": 7, + "versionNonce": 126233951, "isDeleted": false, "boundElements": [ { @@ -8864,7 +8853,7 @@ "id": "text_5o" } ], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "points": [ @@ -8879,16 +8868,16 @@ ], "lastCommittedPoint": null, "startBinding": { - "mode": "orbit", "elementId": "rectangle_5l", + "mode": "orbit", "fixedPoint": [ 0.5048223807889175, 0.5048223807889175 ] }, "endBinding": { - "mode": "orbit", "elementId": "rectangle_4d", + "mode": "orbit", "fixedPoint": [ 0.6249950463635912, 0.3750049536364128 @@ -8897,7 +8886,7 @@ "startArrowhead": null, "endArrowhead": "arrow", "elbowed": false, - "index": "b2G" + "index": "b1Et" }, { "id": "text_5o", @@ -8918,11 +8907,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 4188970950, - "version": 2, - "versionNonce": 1326480409, + "version": 7, + "versionNonce": 1027939345, "isDeleted": false, "boundElements": [], - "updated": 1780289515342, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 11, @@ -8934,7 +8923,7 @@ "originalText": "cmd/build-catalog (build-time)", "lineHeight": 1.25, "autoResize": false, - "index": "b2H" + "index": "b1Eu" }, { "id": "text_5p", @@ -8955,11 +8944,11 @@ "frameId": "frame_3w", "roundness": null, "seed": 2589117160, - "version": 201, - "versionNonce": 1486498297, + "version": 206, + "versionNonce": 2050435455, "isDeleted": true, "boundElements": [], - "updated": 1780290157737, + "updated": 1782952675769, "link": null, "locked": false, "fontSize": 12.333333333333293, @@ -8971,15 +8960,54 @@ "originalText": "Legend\n■ Go ■ data store ■ calc/Node ■ external", "lineHeight": 1.25, "autoResize": true, - "index": "b2I" + "index": "b1Ev" }, { - "id": "vORFZUQJeVYwney0STtQ2", + "id": "embed_rag_rect_1", + "type": "rectangle", + "x": 2530, + "y": 560, + "width": 270, + "height": 90, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "#d3f9d8", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_3w", + "roundness": { + "type": 3 + }, + "seed": 1234567890, + "version": 6, + "versionNonce": 1195995633, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "embed_rag_text_1" + }, + { + "type": "arrow", + "id": "embed_arrow_bl" + } + ], + "updated": 1782952675769, + "link": null, + "locked": false, + "index": "b1Ew" + }, + { + "id": "embed_rag_text_1", "type": "text", - "x": 281.16666666666714, - "y": -33.99999999999943, - "width": 8, - "height": 25, + "x": 2540, + "y": 575, + "width": 250, + "height": 60, "angle": 0, "strokeColor": "#1e1e1e", "backgroundColor": "transparent", @@ -8989,26 +9017,710 @@ "roughness": 1, "opacity": 100, "groupIds": [], - "frameId": null, - "index": "b2J", + "frameId": "frame_3w", "roundness": null, - "seed": 783076695, - "version": 3, - "versionNonce": 2015507001, - "isDeleted": true, - "boundElements": null, - "updated": 1780290104728, + "seed": 987654321, + "version": 6, + "versionNonce": 1102291359, + "isDeleted": false, + "boundElements": [], + "updated": 1782952675769, "link": null, "locked": false, - "text": "", - "fontSize": 20, - "fontFamily": 5, + "fontSize": 14, + "fontFamily": 2, + "text": "Embedding provider (OpenAI-compatible: LM Studio / Ollama / ...)\nquery-embed -> semantic-search -> proactive-seed", + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "embed_rag_rect_1", + "originalText": "Embedding provider (OpenAI-compatible: LM Studio / Ollama / ...)\nquery-embed -> semantic-search -> proactive-seed", + "lineHeight": 1.25, + "autoResize": false, + "index": "b1Ex" + }, + { + "id": "embed_rag_text_2", + "type": "text", + "x": 2500, + "y": 668, + "width": 320, + "height": 48, + "angle": 0, + "strokeColor": "#868e96", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_3w", + "roundness": null, + "seed": 111222333, + "version": 6, + "versionNonce": 503843793, + "isDeleted": false, + "boundElements": [], + "updated": 1782952675769, + "link": null, + "locked": false, + "fontSize": 12, + "fontFamily": 2, + "text": "Build library (PostgreSQL + pgvector): enabled => semantic retrieve (accepted only) -> seed; disabled => recency only", "textAlign": "left", "verticalAlign": "top", "containerId": null, - "originalText": "", + "originalText": "Build library (PostgreSQL + pgvector): enabled => semantic retrieve (accepted only) -> seed; disabled => recency only", + "lineHeight": 1.25, "autoResize": true, - "lineHeight": 1.25 + "index": "b1Ey" + }, + { + "id": "embed_arrow_bl", + "type": "arrow", + "x": 2160, + "y": 520, + "width": 370, + "height": 85, + "angle": 0, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "dashed", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_3w", + "roundness": null, + "seed": 918273645, + "version": 7, + "versionNonce": 791418303, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "embed_arrow_bl_label" + } + ], + "updated": 1782952675769, + "link": null, + "locked": false, + "points": [ + [ + 0, + 0 + ], + [ + 370, + 85 + ] + ], + "lastCommittedPoint": null, + "startBinding": { + "elementId": "rectangle_4b", + "mode": "orbit", + "fixedPoint": [ + 1, + 0.5001 + ] + }, + "endBinding": { + "elementId": "embed_rag_rect_1", + "mode": "orbit", + "fixedPoint": [ + 0, + 0.5001 + ] + }, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false, + "index": "b1Ez" + }, + { + "id": "embed_arrow_bl_label", + "type": "text", + "x": 2250, + "y": 552, + "width": 190, + "height": 20, + "angle": 0, + "strokeColor": "#495057", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_3w", + "roundness": null, + "seed": 564738291, + "version": 7, + "versionNonce": 966289841, + "isDeleted": false, + "boundElements": [], + "updated": 1782952675769, + "link": null, + "locked": false, + "fontSize": 11, + "fontFamily": 2, + "text": "embed + vector search", + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "embed_arrow_bl", + "originalText": "embed + vector search", + "lineHeight": 1.25, + "autoResize": false, + "index": "b1EzV" + }, + { + "id": "frame_3w", + "type": "frame", + "x": 1850, + "y": 0, + "width": 980, + "height": 992.5, + "angle": 0, + "strokeColor": "#bbbbbb", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "seed": 1304035654, + "version": 40, + "versionNonce": 331389183, + "isDeleted": false, + "boundElements": [], + "updated": 1782952674623, + "link": null, + "locked": false, + "name": "2 · High-level architecture", + "index": "b1F" + }, + { + "id": "vORFZUQJeVYwney0STtQ2", + "type": "text", + "x": 281.16666666666714, + "y": -33.99999999999943, + "width": 8, + "height": 25, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "b2J", + "roundness": null, + "seed": 783076695, + "version": 3, + "versionNonce": 2015507001, + "isDeleted": true, + "boundElements": [], + "updated": 1780290104728, + "link": null, + "locked": false, + "text": "", + "fontSize": 20, + "fontFamily": 5, + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "originalText": "", + "autoResize": true, + "lineHeight": 1.25 + }, + { + "id": "rect_accept_user", + "type": "rectangle", + "x": 81, + "y": 884, + "width": 188, + "height": 48, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "#f1f3f5", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_1", + "roundness": { + "type": 3 + }, + "seed": 347708293, + "version": 2, + "versionNonce": 2040925553, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "text_accept_user" + } + ], + "updated": 1782952528463, + "link": null, + "locked": false, + "index": "b2P" + }, + { + "id": "text_accept_user", + "type": "text", + "x": 86, + "y": 899.25, + "width": 178, + "height": 17.5, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_1", + "roundness": null, + "seed": 831311280, + "version": 2, + "versionNonce": 1705016863, + "isDeleted": false, + "boundElements": [], + "updated": 1782952528463, + "link": null, + "locked": false, + "fontSize": 14, + "fontFamily": 2, + "text": "POST /builds/{id}/accept", + "textAlign": "center", + "verticalAlign": "middle", + "originalText": "POST /builds/{id}/accept", + "lineHeight": 1.25, + "autoResize": false, + "index": "b2Q", + "containerId": "rect_accept_user" + }, + { + "id": "rect_accept_api", + "type": "rectangle", + "x": 311, + "y": 884, + "width": 188, + "height": 48, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "#a5d8ff", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_1", + "roundness": { + "type": 3 + }, + "seed": 1403294483, + "version": 2, + "versionNonce": 558184273, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "text_accept_api" + } + ], + "updated": 1782952528463, + "link": null, + "locked": false, + "index": "b2R" + }, + { + "id": "text_accept_api", + "type": "text", + "x": 316, + "y": 890.5, + "width": 178, + "height": 35, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_1", + "roundness": null, + "seed": 1491501858, + "version": 2, + "versionNonce": 1783194175, + "isDeleted": false, + "boundElements": [], + "updated": 1782952528463, + "link": null, + "locked": false, + "fontSize": 14, + "fontFamily": 2, + "text": "stamp accepted_at\n(now RAG-visible)", + "textAlign": "center", + "verticalAlign": "middle", + "originalText": "stamp accepted_at\n(now RAG-visible)", + "lineHeight": 1.25, + "autoResize": false, + "index": "b2S", + "containerId": "rect_accept_api" + }, + { + "id": "arrow_accept_1", + "type": "arrow", + "x": 269, + "y": 908, + "width": 42, + "height": 0, + "angle": 0, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_1", + "roundness": null, + "seed": 179710743, + "version": 2, + "versionNonce": 1126442289, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "text_accept_arr1" + } + ], + "updated": 1782952528463, + "link": null, + "locked": false, + "points": [ + [ + 0, + 0 + ], + [ + 42, + 0 + ] + ], + "lastCommittedPoint": null, + "startBinding": { + "elementId": "rect_accept_user", + "mode": "orbit", + "fixedPoint": [ + 1, + 0.5001 + ] + }, + "endBinding": { + "elementId": "rect_accept_api", + "mode": "orbit", + "fixedPoint": [ + 0, + 0.5001 + ] + }, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false, + "index": "b2T" + }, + { + "id": "text_accept_arr1", + "type": "text", + "x": 273, + "y": 900, + "width": 36, + "height": 16, + "angle": 0, + "strokeColor": "#495057", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_1", + "roundness": null, + "seed": 1871971977, + "version": 2, + "versionNonce": 209764959, + "isDeleted": false, + "boundElements": [], + "updated": 1782952528463, + "link": null, + "locked": false, + "fontSize": 11, + "fontFamily": 2, + "text": "accept", + "textAlign": "center", + "verticalAlign": "middle", + "originalText": "accept", + "lineHeight": 1.25, + "autoResize": false, + "index": "b2U", + "containerId": "arrow_accept_1" + }, + { + "id": "arrow_accept_2", + "type": "arrow", + "x": 499, + "y": 908, + "width": 42, + "height": 0, + "angle": 0, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_1", + "roundness": null, + "seed": 1400601240, + "version": 2, + "versionNonce": 178935569, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "text_accept_arr2" + } + ], + "updated": 1782952528463, + "link": null, + "locked": false, + "points": [ + [ + 0, + 0 + ], + [ + 42, + 0 + ] + ], + "lastCommittedPoint": null, + "startBinding": { + "elementId": "rect_accept_api", + "mode": "orbit", + "fixedPoint": [ + 1, + 0.5001 + ] + }, + "endBinding": { + "elementId": "rectangle_o", + "mode": "orbit", + "fixedPoint": [ + 0.05, + 0.956 + ] + }, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false, + "index": "b2V" + }, + { + "id": "text_accept_arr2", + "type": "text", + "x": 503, + "y": 900, + "width": 108, + "height": 16, + "angle": 0, + "strokeColor": "#495057", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_1", + "roundness": null, + "seed": 1242791612, + "version": 2, + "versionNonce": 219618943, + "isDeleted": false, + "boundElements": [], + "updated": 1782952528463, + "link": null, + "locked": false, + "fontSize": 11, + "fontFamily": 2, + "text": "UPDATE accepted_at", + "textAlign": "center", + "verticalAlign": "middle", + "originalText": "UPDATE accepted_at", + "lineHeight": 1.25, + "autoResize": false, + "index": "b2W", + "containerId": "arrow_accept_2" + }, + { + "id": "text_accept_note", + "type": "text", + "x": 765, + "y": 890, + "width": 210, + "height": 35, + "angle": 0, + "strokeColor": "#7048e8", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_1", + "roundness": null, + "seed": 2057618736, + "version": 2, + "versionNonce": 1246711025, + "isDeleted": false, + "boundElements": [], + "updated": 1782952528463, + "link": null, + "locked": false, + "fontSize": 12, + "fontFamily": 2, + "text": "Acceptance gate: only accepted\nbuilds seed future /generate (RAG)", + "textAlign": "left", + "verticalAlign": "middle", + "originalText": "Acceptance gate: only accepted\nbuilds seed future /generate (RAG)", + "lineHeight": 1.25, + "autoResize": false, + "index": "b2X", + "containerId": null + }, + { + "id": "arrow_seed", + "type": "arrow", + "x": 499, + "y": 300, + "width": 42, + "height": 0, + "angle": 0, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_1", + "roundness": null, + "seed": 1672848789, + "version": 2, + "versionNonce": 1053619871, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "text_seed_arr" + } + ], + "updated": 1782952528463, + "link": null, + "locked": false, + "points": [ + [ + 0, + 0 + ], + [ + 42, + 0 + ] + ], + "lastCommittedPoint": null, + "startBinding": { + "elementId": "rectangle_10", + "mode": "orbit", + "fixedPoint": [ + 1, + 0.2 + ] + }, + "endBinding": { + "elementId": "rectangle_o", + "mode": "orbit", + "fixedPoint": [ + 0.05, + 0.218 + ] + }, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false, + "index": "b2Y" + }, + { + "id": "text_seed_arr", + "type": "text", + "x": 503, + "y": 292, + "width": 120, + "height": 32, + "angle": 0, + "strokeColor": "#495057", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": "frame_1", + "roundness": null, + "seed": 55084389, + "version": 2, + "versionNonce": 429557457, + "isDeleted": false, + "boundElements": [], + "updated": 1782952528463, + "link": null, + "locked": false, + "fontSize": 11, + "fontFamily": 2, + "text": "embed req -> similar\n(accepted) -> seed", + "textAlign": "center", + "verticalAlign": "middle", + "originalText": "embed req -> similar\n(accepted) -> seed", + "lineHeight": 1.25, + "autoResize": false, + "index": "b2Z", + "containerId": "arrow_seed" } ], "appState": { diff --git a/go.mod b/go.mod index 375dbdf..1df4f25 100644 --- a/go.mod +++ b/go.mod @@ -16,6 +16,7 @@ require ( github.com/golang-migrate/migrate/v4 v4.19.1 github.com/jackc/pgx/v5 v5.10.0 github.com/oapi-codegen/runtime v1.4.0 + github.com/pgvector/pgvector-go v0.4.0 github.com/testcontainers/testcontainers-go v0.43.0 github.com/testcontainers/testcontainers-go/modules/postgres v0.43.0 ) diff --git a/go.sum b/go.sum index 80d73ea..9b3225a 100644 --- a/go.sum +++ b/go.sum @@ -189,6 +189,8 @@ github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJw github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s= github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw= +github.com/pgvector/pgvector-go v0.4.0 h1:879hQCnuix1bkfa5TQISnnK9ik4Fo+cHj2vuZSgW5v4= +github.com/pgvector/pgvector-go v0.4.0/go.mod h1:4fSXyjl1TYAIdByAql6JazKWRr2s7J0g4hcRY5cBFCk= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= diff --git a/internal/api/builds_test.go b/internal/api/builds_test.go index 4bcff43..4af0943 100644 --- a/internal/api/builds_test.go +++ b/internal/api/builds_test.go @@ -417,3 +417,118 @@ func TestBuildLibrary_NotFoundSentinelMatches(t *testing.T) { t.Errorf("expected ErrNotFound from missing Get; got %v", err) } } + +func TestAcceptBuild_StampsAndIsIdempotent(t *testing.T) { + lib := openTempLibrary(t) + cat := loadCatalog(t) + id := seedSavedBuild(t, lib) + srv := buildsServer(t, lib, cat) + + // Before acceptance, GET /builds/{id} carries no accepted_at. + var before map[string]any + getListOrBuild(t, srv.URL+"/builds/"+id, &before) + if before["accepted_at"] != nil { + t.Fatalf("pending build should have null accepted_at, got %v", before["accepted_at"]) + } + + resp, err := http.Post(srv.URL+"/builds/"+id+"/accept", "application/json", nil) + if err != nil { + t.Fatalf("POST accept: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("accept status: got %d want 200", resp.StatusCode) + } + var acc struct { + ID string `json:"id"` + AcceptedAt string `json:"accepted_at"` + } + if err := json.NewDecoder(resp.Body).Decode(&acc); err != nil { + t.Fatalf("decode accept: %v", err) + } + if acc.ID != id || acc.AcceptedAt == "" { + t.Fatalf("accept body: %+v", acc) + } + + // GET now reflects acceptance. + var after map[string]any + getListOrBuild(t, srv.URL+"/builds/"+id, &after) + if after["accepted_at"] == nil { + t.Fatal("expected accepted_at on the build after accept") + } + + // Idempotent: a second accept returns the same timestamp. + resp2, err := http.Post(srv.URL+"/builds/"+id+"/accept", "application/json", nil) + if err != nil { + t.Fatalf("POST accept 2: %v", err) + } + defer resp2.Body.Close() + var acc2 struct { + AcceptedAt string `json:"accepted_at"` + } + if err := json.NewDecoder(resp2.Body).Decode(&acc2); err != nil { + t.Fatalf("decode accept2: %v", err) + } + if acc2.AcceptedAt != acc.AcceptedAt { + t.Fatalf("re-accept changed the timestamp: %q -> %q", acc.AcceptedAt, acc2.AcceptedAt) + } +} + +func TestAcceptBuild_NotFound(t *testing.T) { + lib := openTempLibrary(t) + cat := loadCatalog(t) + srv := buildsServer(t, lib, cat) + resp, err := http.Post(srv.URL+"/builds/does-not-exist/accept", "application/json", nil) + if err != nil { + t.Fatalf("POST: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("status: got %d want 404", resp.StatusCode) + } +} + +func TestListBuilds_AcceptedFilter(t *testing.T) { + lib := openTempLibrary(t) + cat := loadCatalog(t) + acceptedID := seedSavedBuild(t, lib) + pendingID := seedSavedBuild(t, lib) + if _, err := lib.Accept(context.Background(), acceptedID); err != nil { + t.Fatalf("Accept: %v", err) + } + srv := buildsServer(t, lib, cat) + + list := func(url string) []map[string]any { + var body struct { + Builds []map[string]any `json:"builds"` + } + getListOrBuild(t, url, &body) + return body.Builds + } + if got := list(srv.URL + "/builds?accepted=true"); len(got) != 1 || got[0]["id"] != acceptedID { + t.Fatalf("accepted=true should return only the accepted build; got %d: %+v", len(got), got) + } + if got := list(srv.URL + "/builds?accepted=false"); len(got) != 1 || got[0]["id"] != pendingID { + t.Fatalf("accepted=false should return only the pending build; got %d: %+v", len(got), got) + } + if got := list(srv.URL + "/builds"); len(got) != 2 { + t.Fatalf("no filter should return both; got %d", len(got)) + } +} + +// getListOrBuild issues a GET and decodes the JSON body into out, failing the +// test on transport, status, or decode errors. +func getListOrBuild(t *testing.T, url string, out any) { + t.Helper() + resp, err := http.Get(url) + if err != nil { + t.Fatalf("GET %s: %v", url, err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("GET %s: status %d", url, resp.StatusCode) + } + if err := json.NewDecoder(resp.Body).Decode(out); err != nil { + t.Fatalf("decode %s: %v", url, err) + } +} diff --git a/internal/api/enrich.go b/internal/api/enrich.go index dc4ae4d..12b211b 100644 --- a/internal/api/enrich.go +++ b/internal/api/enrich.go @@ -78,6 +78,7 @@ type EnrichedBuild struct { GateSummary buildlibrary.GateSummary `json:"gate_summary"` CalcVersion string `json:"calc_version,omitempty"` CatalogVersion int `json:"catalog_version,omitempty"` + AcceptedAt *time.Time `json:"accepted_at,omitempty"` } // enrichSavedTrajectory transforms a SavedTrajectory into its wire form @@ -99,6 +100,7 @@ func enrichSavedTrajectory(st *buildlibrary.SavedTrajectory, cat *catalog.Catalo GateSummary: st.GateSummary, CalcVersion: st.CalcVersion, CatalogVersion: st.CatalogVersion, + AcceptedAt: st.AcceptedAt, Primary: enrichTrajectory(st.Primary, cat), } if len(st.Alternatives) > 0 { diff --git a/internal/api/oapi/oapi.gen.go b/internal/api/oapi/oapi.gen.go index 158471b..a3db270 100644 --- a/internal/api/oapi/oapi.gen.go +++ b/internal/api/oapi/oapi.gen.go @@ -194,6 +194,12 @@ func (e SlotKey) Valid() bool { } } +// AcceptBuildResponse defines model for AcceptBuildResponse. +type AcceptBuildResponse struct { + AcceptedAt time.Time `json:"accepted_at"` + Id string `json:"id"` +} + // BasePlus defines model for BasePlus. type BasePlus struct { Base int `json:"base"` @@ -224,6 +230,8 @@ type BuildTier string // BuildSummary defines model for BuildSummary. type BuildSummary struct { + // AcceptedAt when the build was user-accepted; absent = pending (not RAG-visible) + AcceptedAt *time.Time `json:"accepted_at,omitempty"` Class string `json:"class"` CreatedAt time.Time `json:"created_at"` Description *string `json:"description,omitempty"` @@ -293,6 +301,8 @@ type DerivedStats struct { // EnrichedBuild defines model for EnrichedBuild. type EnrichedBuild struct { + // AcceptedAt when the build was user-accepted; absent = pending (not RAG-visible) + AcceptedAt *time.Time `json:"accepted_at,omitempty"` Alternatives *[]EnrichedTrajectory `json:"alternatives,omitempty"` CalcVersion *string `json:"calc_version,omitempty"` CatalogVersion *int `json:"catalog_version,omitempty"` @@ -518,6 +528,9 @@ type ListBuildsParams struct { // Limit cap results (default 5, max 50) Limit *int `form:"limit,omitempty" json:"limit,omitempty"` + + // Accepted filter by acceptance state; true = accepted only, false = pending (not yet accepted) only, omitted = all + Accepted *bool `form:"accepted,omitempty" json:"accepted,omitempty"` } // GenerateJSONRequestBody defines body for Generate for application/json ContentType. @@ -534,6 +547,9 @@ type ServerInterface interface { // Fetch one saved trajectory with catalog names resolved // (GET /builds/{id}) GetBuild(w http.ResponseWriter, r *http.Request, id string) + // Accept a saved trajectory, making it visible to RAG retrieval + // (POST /builds/{id}/accept) + AcceptBuild(w http.ResponseWriter, r *http.Request, id string) // Enqueue an asynchronous build-generation job // (POST /generate) Generate(w http.ResponseWriter, r *http.Request) @@ -602,6 +618,19 @@ func (siw *ServerInterfaceWrapper) ListBuilds(w http.ResponseWriter, r *http.Req return } + // ------------- Optional query parameter "accepted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "accepted", r.URL.Query(), ¶ms.Accepted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + var requiredError *runtime.RequiredParameterError + if errors.As(err, &requiredError) { + siw.ErrorHandlerFunc(w, r, &RequiredParamError{ParamName: "accepted"}) + } else { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "accepted", Err: err}) + } + return + } + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.ListBuilds(w, r, params) })) @@ -639,6 +668,32 @@ func (siw *ServerInterfaceWrapper) GetBuild(w http.ResponseWriter, r *http.Reque handler.ServeHTTP(w, r) } +// AcceptBuild operation middleware +func (siw *ServerInterfaceWrapper) AcceptBuild(w http.ResponseWriter, r *http.Request) { + + var err error + _ = err + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", r.PathValue("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.AcceptBuild(w, r, id) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + // Generate operation middleware func (siw *ServerInterfaceWrapper) Generate(w http.ResponseWriter, r *http.Request) { @@ -815,6 +870,7 @@ func HandlerWithOptions(si ServerInterface, options StdHTTPServerOptions) http.H m.HandleFunc(http.MethodGet+" "+options.BaseURL+"/builds", wrapper.ListBuilds) m.HandleFunc(http.MethodGet+" "+options.BaseURL+"/builds/{id}", wrapper.GetBuild) + m.HandleFunc(http.MethodPost+" "+options.BaseURL+"/builds/{id}/accept", wrapper.AcceptBuild) m.HandleFunc(http.MethodPost+" "+options.BaseURL+"/generate", wrapper.Generate) m.HandleFunc(http.MethodGet+" "+options.BaseURL+"/generations/{id}", wrapper.GetGeneration) m.HandleFunc(http.MethodPost+" "+options.BaseURL+"/score", wrapper.Score) @@ -936,6 +992,56 @@ func (response GetBuild500JSONResponse) VisitGetBuildResponse(w http.ResponseWri return err } +type AcceptBuildRequestObject struct { + Id string `json:"id"` +} + +type AcceptBuildResponseObject interface { + VisitAcceptBuildResponse(w http.ResponseWriter) error +} + +type AcceptBuild200JSONResponse AcceptBuildResponse + +func (response AcceptBuild200JSONResponse) VisitAcceptBuildResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + _, err := buf.WriteTo(w) + return err +} + +type AcceptBuild404JSONResponse ErrorBody + +func (response AcceptBuild404JSONResponse) VisitAcceptBuildResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + _, err := buf.WriteTo(w) + return err +} + +type AcceptBuild500JSONResponse ErrorBody + +func (response AcceptBuild500JSONResponse) VisitAcceptBuildResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(500) + _, err := buf.WriteTo(w) + return err +} + type GenerateRequestObject struct { Body *GenerateJSONRequestBody } @@ -1132,6 +1238,9 @@ type StrictServerInterface interface { // Fetch one saved trajectory with catalog names resolved // (GET /builds/{id}) GetBuild(ctx context.Context, request GetBuildRequestObject) (GetBuildResponseObject, error) + // Accept a saved trajectory, making it visible to RAG retrieval + // (POST /builds/{id}/accept) + AcceptBuild(ctx context.Context, request AcceptBuildRequestObject) (AcceptBuildResponseObject, error) // Enqueue an asynchronous build-generation job // (POST /generate) Generate(ctx context.Context, request GenerateRequestObject) (GenerateResponseObject, error) @@ -1224,6 +1333,32 @@ func (sh *strictHandler) GetBuild(w http.ResponseWriter, r *http.Request, id str } } +// AcceptBuild operation middleware +func (sh *strictHandler) AcceptBuild(w http.ResponseWriter, r *http.Request, id string) { + var request AcceptBuildRequestObject + + request.Id = id + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.AcceptBuild(ctx, request.(AcceptBuildRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "AcceptBuild") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(AcceptBuildResponseObject); ok { + if err := validResponse.VisitAcceptBuildResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + // Generate operation middleware func (sh *strictHandler) Generate(w http.ResponseWriter, r *http.Request) { var request GenerateRequestObject @@ -1317,62 +1452,68 @@ func (sh *strictHandler) Score(w http.ResponseWriter, r *http.Request) { // const string: with thousands of chunks the chained `+` fold is several // times slower for the Go compiler than parsing a slice literal. var swaggerSpec = []string{ - "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", + "VWenp5IGFNq6s7/M/jLLHn56+N8AAAD//w==", } // decodeSpec returns the embedded OpenAPI spec as raw JSON bytes, diff --git a/internal/api/server.go b/internal/api/server.go index f0f3ea7..29ae1fa 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -344,6 +344,8 @@ func (s *Server) ListBuilds(ctx context.Context, req oapi.ListBuildsRequestObjec // param parser; passing through is enough. p.Limit = *req.Params.Limit } + // nil = all builds; true = accepted only; false = pending (not yet accepted). + p.Accepted = req.Params.Accepted builds, err := s.library.Find(ctx, p) if err != nil { @@ -395,6 +397,35 @@ func (s *Server) GetBuild(ctx context.Context, req oapi.GetBuildRequestObject) ( return oapi.GetBuild200JSONResponse(out), nil } +// --- AcceptBuild --- + +// AcceptBuild marks a saved trajectory as user-accepted, making it visible to +// the RAG retrieval surface (proactive seed injection, get_similar_past_builds, +// get_saved_build). Until accepted, a saved build is fetchable via +// GET /builds/{id} but never seeds a future generation. Idempotent: accepting +// an already-accepted build returns its original timestamp. +// +// Status codes: +// +// 200 - accepted (or already accepted); body {id, accepted_at} +// 404 - no trajectory with that id +// 500 - library not configured, or an unexpected library failure +func (s *Server) AcceptBuild(ctx context.Context, req oapi.AcceptBuildRequestObject) (oapi.AcceptBuildResponseObject, error) { + if s.library == nil { + return oapi.AcceptBuild500JSONResponse{Error: "build library not configured"}, nil + } + at, err := s.library.Accept(ctx, req.Id) + if errors.Is(err, buildlibrary.ErrNotFound) { + return oapi.AcceptBuild404JSONResponse{Error: "no trajectory with id " + req.Id}, nil + } + if err != nil { + logging.From(ctx).Error("AcceptBuild: library accept failed", + slog.String("id", req.Id), slog.String("error", err.Error())) + return oapi.AcceptBuild500JSONResponse{Error: genericInternalError}, nil + } + return oapi.AcceptBuild200JSONResponse{Id: req.Id, AcceptedAt: at}, nil +} + // convertJSON moves data between two JSON-shape-compatible Go types // (e.g., scoring.ScoreResponse and oapi.ScoreResponse) by round-tripping // through json.Marshal/Unmarshal. The spec was designed so each oapi diff --git a/internal/buildlibrary/accept.go b/internal/buildlibrary/accept.go new file mode 100644 index 0000000..b165974 --- /dev/null +++ b/internal/buildlibrary/accept.go @@ -0,0 +1,31 @@ +package buildlibrary + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" +) + +// Accept marks a saved trajectory as user-accepted, making it visible to the +// RAG retrieval surface (proactive seed, get_similar_past_builds, +// get_saved_build). Idempotent: re-accepting keeps the original timestamp via +// COALESCE. Returns the accepted-at time, or ErrNotFound if no trajectory has +// the given id. +func (l *Library) Accept(ctx context.Context, id string) (time.Time, error) { + if l == nil || l.db == nil { + return time.Time{}, errors.New("buildlibrary.Accept: nil library") + } + var at time.Time + err := l.db.QueryRowContext(ctx, + `UPDATE saved_trajectories SET accepted_at = COALESCE(accepted_at, now()) WHERE id = $1 RETURNING accepted_at`, + id).Scan(&at) + if errors.Is(err, sql.ErrNoRows) { + return time.Time{}, ErrNotFound + } + if err != nil { + return time.Time{}, fmt.Errorf("accept: %w", err) + } + return at, nil +} diff --git a/internal/buildlibrary/accept_test.go b/internal/buildlibrary/accept_test.go new file mode 100644 index 0000000..c814d43 --- /dev/null +++ b/internal/buildlibrary/accept_test.go @@ -0,0 +1,114 @@ +package buildlibrary + +import ( + "context" + "errors" + "testing" +) + +func TestAccept_StampsAndIsIdempotent(t *testing.T) { + lib := openWithEmbedding(t, 4, "acc@4") + id := saveEmbeddedPending(t, lib, "taekwon_kid", "uaro", []float32{1, 0, 0, 0}) + + at1, err := lib.Accept(context.Background(), id) + if err != nil { + t.Fatalf("Accept: %v", err) + } + if at1.IsZero() { + t.Fatal("accepted_at should be set") + } + // Re-accepting keeps the original timestamp (COALESCE). + at2, err := lib.Accept(context.Background(), id) + if err != nil { + t.Fatalf("Accept (2nd): %v", err) + } + if !at2.Equal(at1) { + t.Fatalf("re-accept changed the timestamp: %v -> %v", at1, at2) + } +} + +func TestAccept_NotFound(t *testing.T) { + lib := openWithEmbedding(t, 4, "acc@4") + if _, err := lib.Accept(context.Background(), "does-not-exist"); !errors.Is(err, ErrNotFound) { + t.Fatalf("want ErrNotFound, got %v", err) + } +} + +func TestFindSimilar_AcceptedOnlyHidesPending(t *testing.T) { + lib := openWithEmbedding(t, 4, "acc@4") + // A pending build CLOSER to the query than the accepted one; the filter + // must still hide it. + _ = saveEmbeddedPending(t, lib, "taekwon_kid", "uaro", []float32{1, 0, 0, 0}) + accepted := saveWithEmbedding(t, lib, "taekwon_kid", "uaro", []float32{0, 1, 0, 0}) + + acceptedOnly := true + got, err := lib.FindSimilar(context.Background(), []float32{1, 0, 0, 0}, + FindParams{Class: "taekwon_kid", Server: "uaro", Limit: 5, Accepted: &acceptedOnly}) + if err != nil { + t.Fatalf("FindSimilar: %v", err) + } + if len(got) != 1 || got[0].ID != accepted { + t.Fatalf("accepted-only should return just the accepted build; got %d rows", len(got)) + } + // Without the filter (nil), both are visible. + all, err := lib.FindSimilar(context.Background(), []float32{1, 0, 0, 0}, + FindParams{Class: "taekwon_kid", Server: "uaro", Limit: 5}) + if err != nil { + t.Fatalf("FindSimilar (all): %v", err) + } + if len(all) != 2 { + t.Fatalf("no filter should return both; got %d", len(all)) + } +} + +func TestSimilarTop_SkipsPending(t *testing.T) { + lib := openWithEmbedding(t, 4, "acc@4") + // The closer build is pending; SimilarTop (RAG) must skip it. + _ = saveEmbeddedPending(t, lib, "taekwon_kid", "uaro", []float32{1, 0, 0, 0}) + accepted := saveWithEmbedding(t, lib, "taekwon_kid", "uaro", []float32{0, 1, 0, 0}) + st, _, ok, err := lib.SimilarTop(context.Background(), []float32{1, 0, 0, 0}, "taekwon_kid", "uaro") + if err != nil { + t.Fatalf("SimilarTop: %v", err) + } + if !ok || st.ID != accepted { + t.Fatalf("SimilarTop should return the accepted build, not the closer pending one; ok=%v", ok) + } +} + +func TestFind_AcceptedFilter(t *testing.T) { + lib := openWithEmbedding(t, 4, "acc@4") + pending := saveEmbeddedPending(t, lib, "taekwon_kid", "uaro", nil) + accepted := saveWithEmbedding(t, lib, "taekwon_kid", "uaro", nil) + + yes, no := true, false + acc, err := lib.Find(context.Background(), FindParams{Class: "taekwon_kid", Server: "uaro", Accepted: &yes}) + if err != nil { + t.Fatal(err) + } + if len(acc) != 1 || acc[0].ID != accepted { + t.Fatalf("Accepted=true should return only the accepted build; got %d", len(acc)) + } + pend, err := lib.Find(context.Background(), FindParams{Class: "taekwon_kid", Server: "uaro", Accepted: &no}) + if err != nil { + t.Fatal(err) + } + if len(pend) != 1 || pend[0].ID != pending { + t.Fatalf("Accepted=false should return only the pending build; got %d", len(pend)) + } + all, err := lib.Find(context.Background(), FindParams{Class: "taekwon_kid", Server: "uaro"}) + if err != nil { + t.Fatal(err) + } + if len(all) != 2 { + t.Fatalf("no filter should return both; got %d", len(all)) + } + // accepted_at is surfaced on the summary so the user can see state. + for _, s := range all { + if s.ID == accepted && s.AcceptedAt == nil { + t.Error("accepted build summary should carry accepted_at") + } + if s.ID == pending && s.AcceptedAt != nil { + t.Error("pending build summary should have nil accepted_at") + } + } +} diff --git a/internal/buildlibrary/backfill.go b/internal/buildlibrary/backfill.go new file mode 100644 index 0000000..d509912 --- /dev/null +++ b/internal/buildlibrary/backfill.go @@ -0,0 +1,147 @@ +package buildlibrary + +import ( + "context" + "errors" + "fmt" + "strings" + + pgvector "github.com/pgvector/pgvector-go" +) + +// AllIDs returns every saved trajectory id (for backfill). +func (l *Library) AllIDs(ctx context.Context) ([]string, error) { + rows, err := l.db.QueryContext(ctx, `SELECT id FROM saved_trajectories ORDER BY created_at`) + if err != nil { + return nil, err + } + defer rows.Close() + var ids []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + return nil, err + } + ids = append(ids, id) + } + return ids, rows.Err() +} + +// SetEmbedding writes a row's vector (used by backfill). Requires semantic. +func (l *Library) SetEmbedding(ctx context.Context, id string, vec []float32) error { + if !l.semanticEnabled { + return errors.New("buildlibrary.SetEmbedding: semantic disabled") + } + _, err := l.db.ExecContext(ctx, `UPDATE saved_trajectories SET embedding=$1 WHERE id=$2`, pgvector.NewVector(vec), id) + return err +} + +// DocumentText reconstructs the embedding document for a saved row: +// playstyle + description + final_text. Mirrors the save-path composer. +func (l *Library) DocumentText(ctx context.Context, id string) (string, error) { + st, err := l.Get(ctx, id) + if err != nil { + return "", err + } + return strings.TrimSpace(st.Playstyle + "\n" + st.Description + "\n" + st.FinalText), nil +} + +// SampleVectors returns up to n stored embeddings (as query probes). +func (l *Library) SampleVectors(ctx context.Context, n int) ([][]float32, error) { + rows, err := l.db.QueryContext(ctx, + `SELECT embedding FROM saved_trajectories WHERE embedding IS NOT NULL ORDER BY id LIMIT $1`, n) + if err != nil { + return nil, err + } + defer rows.Close() + var out [][]float32 + for rows.Next() { + var v pgvector.Vector + if err := rows.Scan(&v); err != nil { + return nil, err + } + out = append(out, v.Slice()) + } + return out, rows.Err() +} + +// neighbors returns the ids of the k nearest rows to vec. exact=true forces +// a sequential scan (true KNN ground truth); exact=false uses the HNSW +// index at the given efSearch. The planner settings are applied with SET LOCAL +// inside an explicit transaction so they are transaction-scoped: rollback +// resets them automatically. This prevents settings from leaking to the next +// caller that borrows the same idle connection from the pool (database/sql +// does NOT reset session state on conn return). +func (l *Library) neighbors(ctx context.Context, vec []float32, k, efSearch int, exact bool) ([]string, error) { + conn, err := l.db.Conn(ctx) + if err != nil { + return nil, err + } + defer func() { _ = conn.Close() }() + tx, err := conn.BeginTx(ctx, nil) + if err != nil { + return nil, err + } + defer func() { _ = tx.Rollback() }() // discards the SET LOCAL settings; read-only tx + if exact { + if _, err := tx.ExecContext(ctx, `SET LOCAL enable_indexscan = off`); err != nil { + return nil, err + } + if _, err := tx.ExecContext(ctx, `SET LOCAL enable_bitmapscan = off`); err != nil { + return nil, err + } + } else if efSearch > 0 { + if _, err := tx.ExecContext(ctx, fmt.Sprintf(`SET LOCAL hnsw.ef_search = %d`, efSearch)); err != nil { + return nil, err + } + } + rows, err := tx.QueryContext(ctx, + `SELECT id FROM saved_trajectories WHERE embedding IS NOT NULL ORDER BY embedding <=> $1, id LIMIT $2`, + pgvector.NewVector(vec), k) + if err != nil { + return nil, err + } + defer rows.Close() + var ids []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + return nil, err + } + ids = append(ids, id) + } + return ids, rows.Err() +} + +// RecallAtK returns mean recall@k of the HNSW index vs exact KNN over the +// sampled probes. +func (l *Library) RecallAtK(ctx context.Context, probes [][]float32, k, efSearch int) (float64, error) { + if len(probes) == 0 { + return 0, fmt.Errorf("no probes (empty corpus?)") + } + var sum float64 + for _, p := range probes { + exact, err := l.neighbors(ctx, p, k, 0, true) + if err != nil { + return 0, err + } + approx, err := l.neighbors(ctx, p, k, efSearch, false) + if err != nil { + return 0, err + } + set := make(map[string]struct{}, len(exact)) + for _, id := range exact { + set[id] = struct{}{} + } + hit := 0 + for _, id := range approx { + if _, ok := set[id]; ok { + hit++ + } + } + if len(exact) > 0 { + sum += float64(hit) / float64(len(exact)) + } + } + return sum / float64(len(probes)), nil +} diff --git a/internal/buildlibrary/backfill_test.go b/internal/buildlibrary/backfill_test.go new file mode 100644 index 0000000..79ce315 --- /dev/null +++ b/internal/buildlibrary/backfill_test.go @@ -0,0 +1,105 @@ +package buildlibrary + +import ( + "context" + "testing" +) + +func TestSetEmbedding_RoundTrip(t *testing.T) { + lib := openWithEmbedding(t, 4, "test-model@4") + ctx := context.Background() + + // Seed a row with a NULL embedding. + id := saveWithEmbedding(t, lib, "taekwon_kid", "uaro", nil) + + // Confirm embedding is NULL before we write it. + var nonNull bool + if err := lib.db.QueryRowContext(ctx, + `SELECT embedding IS NOT NULL FROM saved_trajectories WHERE id=$1`, id).Scan(&nonNull); err != nil { + t.Fatalf("query pre-write: %v", err) + } + if nonNull { + t.Fatal("expected NULL embedding before SetEmbedding") + } + + // Write a known vector via SetEmbedding. + vec := []float32{1, 0, 0, 0} + if err := lib.SetEmbedding(ctx, id, vec); err != nil { + t.Fatalf("SetEmbedding: %v", err) + } + + // Confirm embedding is now non-NULL. + if err := lib.db.QueryRowContext(ctx, + `SELECT embedding IS NOT NULL FROM saved_trajectories WHERE id=$1`, id).Scan(&nonNull); err != nil { + t.Fatalf("query post-write: %v", err) + } + if !nonNull { + t.Fatal("embedding should be non-NULL after SetEmbedding") + } + + // SimilarTop with the same vector should return distance ~0 (identical). + st, dist, ok, err := lib.SimilarTop(ctx, vec, "taekwon_kid", "uaro") + if err != nil || !ok { + t.Fatalf("SimilarTop ok=%v err=%v", ok, err) + } + if st.ID != id { + t.Fatalf("SimilarTop returned wrong id: got %s want %s", st.ID, id) + } + if dist > 0.001 { + t.Fatalf("cosine distance for identical vector should be ~0, got %v", dist) + } +} + +func TestSetEmbedding_ErrorWhenSemanticDisabled(t *testing.T) { + lib := newTestLibrary(t) // no WithEmbedding + err := lib.SetEmbedding(context.Background(), "any-id", []float32{1, 0, 0, 0}) + if err == nil { + t.Fatal("expected error from SetEmbedding when semantic disabled") + } +} + +func TestAllIDs_ReturnsAllInOrder(t *testing.T) { + lib := openWithEmbedding(t, 4, "test-model@4") + ctx := context.Background() + + // Save two rows; AllIDs should return both. + id1 := saveWithEmbedding(t, lib, "taekwon_kid", "uaro", nil) + id2 := saveWithEmbedding(t, lib, "knight", "uaro", nil) + + ids, err := lib.AllIDs(ctx) + if err != nil { + t.Fatalf("AllIDs: %v", err) + } + if len(ids) != 2 { + t.Fatalf("AllIDs: want 2, got %d", len(ids)) + } + // ORDER BY created_at: id1 first. + if ids[0] != id1 || ids[1] != id2 { + t.Fatalf("AllIDs order: got %v want [%s %s]", ids, id1, id2) + } +} + +func TestDocumentText_MatchesSaveOrder(t *testing.T) { + lib := openWithEmbedding(t, 4, "test-model@4") + ctx := context.Background() + + id := seedGeneration(t, lib) + in := validSaveInput(t, id, "w1") + in.Playstyle = "pvm" + in.Description = "fast leveling build" + in.FinalText = "use kicks to farm" + saved, err := lib.SaveAndComplete(ctx, in) + if err != nil { + t.Fatalf("SaveAndComplete: %v", err) + } + + doc, err := lib.DocumentText(ctx, saved) + if err != nil { + t.Fatalf("DocumentText: %v", err) + } + // Mirrors strings.TrimSpace(playstyle + "\n" + description + "\n" + final_text). + want := "pvm\nfast leveling build\nuse kicks to farm" + if doc != want { + t.Fatalf("DocumentText = %q, want %q", doc, want) + } +} diff --git a/internal/buildlibrary/embedding_bootstrap.go b/internal/buildlibrary/embedding_bootstrap.go new file mode 100644 index 0000000..86122f8 --- /dev/null +++ b/internal/buildlibrary/embedding_bootstrap.go @@ -0,0 +1,150 @@ +package buildlibrary + +import ( + "context" + "database/sql" + "errors" + "fmt" + "log/slog" +) + +// embeddingBootstrapAdvisoryKey serializes the config-driven bootstrap +// across concurrently-booting replicas. golang-migrate holds its own +// advisory lock only across m.Up(); this covers the post-migration DDL. +// Value is ASCII "ro_embed"; distinct from migrate's DB-name-derived key. +const embeddingBootstrapAdvisoryKey int64 = 0x726F5F656D626564 + +// bootstrapEmbedding materializes the model-dependent schema (pgvector +// extension, vector column, HNSW index) and reconciles the singleton +// embedding_config stamp, all under a Postgres advisory lock so N replicas +// booting together serialize. It NEVER returns an error for a recoverable +// condition (missing extension privilege, model mismatch on a non-empty +// corpus); those drop to recency mode with a loud log and leave +// l.semanticEnabled = false. It returns an error only for unexpected DB +// failures. +func (l *Library) bootstrapEmbedding(ctx context.Context) error { + conn, err := l.db.Conn(ctx) // pin one connection; advisory locks are session-scoped + if err != nil { + return fmt.Errorf("acquire conn: %w", err) + } + defer func() { _ = conn.Close() }() + if _, err := conn.ExecContext(ctx, `SELECT pg_advisory_lock($1)`, embeddingBootstrapAdvisoryKey); err != nil { + return fmt.Errorf("advisory lock: %w", err) + } + defer func() { _, _ = conn.ExecContext(ctx, `SELECT pg_advisory_unlock($1)`, embeddingBootstrapAdvisoryKey) }() + + // 1. Ensure the pgvector extension, tolerantly. + if _, err := conn.ExecContext(ctx, `CREATE EXTENSION IF NOT EXISTS vector`); err != nil { + var present bool + _ = conn.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM pg_extension WHERE extname='vector')`).Scan(&present) + if !present { + slog.Error("embedding: pgvector extension is unavailable and could not be created; "+ + "running RECENCY-ONLY. Have a superuser run `CREATE EXTENSION vector` (or enable it via your "+ + "platform) and restart to enable semantic retrieval.", slog.String("create_error", err.Error())) + l.semanticEnabled = false + return nil + } + } + + // 2. Read the current stamp. + var haveStamp bool + var stampedModel string + var stampedDim int + err = conn.QueryRowContext(ctx, `SELECT model_id, dimensions FROM embedding_config WHERE id=1`).Scan(&stampedModel, &stampedDim) + switch { + case err == nil: + haveStamp = true + case errors.Is(err, sql.ErrNoRows): + haveStamp = false + default: + return fmt.Errorf("read embedding_config: %w", err) + } + + // 3. Does the column already exist, and is the corpus non-empty? + var columnExists bool + _ = conn.QueryRowContext(ctx, + `SELECT EXISTS(SELECT 1 FROM information_schema.columns WHERE table_name='saved_trajectories' AND column_name='embedding')`).Scan(&columnExists) + hasEmbeddings := false + if columnExists { + if err := conn.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM saved_trajectories WHERE embedding IS NOT NULL)`).Scan(&hasEmbeddings); err != nil { + // Fail safe: an unreadable corpus must NOT be treated as empty, or + // the dim-change re-key below could DROP a populated column. Assume + // non-empty so the mismatch branch degrades to recency. + slog.Error("embedding: could not probe corpus for existing embeddings; assuming non-empty to avoid a destructive re-key", slog.String("err", err.Error())) + hasEmbeddings = true + } + } + + matches := haveStamp && stampedModel == l.embeddingModelID && stampedDim == l.embeddingDim + + // Mismatch against a non-empty corpus: degrade, do not alter/stamp. + if haveStamp && !matches && hasEmbeddings { + slog.Error("embedding: configured model/dim does not match the embedded corpus; running RECENCY-ONLY. "+ + "Re-embed with cmd/backfill-embeddings to restore semantic retrieval.", + slog.String("corpus_model", stampedModel), slog.Int("corpus_dim", stampedDim), + slog.String("configured_model", l.embeddingModelID), slog.Int("configured_dim", l.embeddingDim)) + l.semanticEnabled = false + return nil + } + + // degradeMaterialize logs and sets recency-only mode when a column/index + // DDL step fails. pgvector installed but older than 0.5 (no HNSW support) + // is the canonical trigger: CREATE EXTENSION succeeds but CREATE INDEX + // USING hnsw hard-errors. Self-heals on next boot after an upgrade. + degradeMaterialize := func(step string, err error) { + slog.Error("embedding: vector column/HNSW index could not be materialized (pgvector may be older than 0.5); "+ + "running RECENCY-ONLY. Upgrade pgvector and restart to enable semantic retrieval.", + slog.String("step", step), slog.String("err", err.Error())) + l.semanticEnabled = false + } + + // Safe to (re)materialize: first run, exact match, or mismatch with an + // empty corpus. If the column exists at a different dimension, drop and + // recreate (only reachable with no embeddings present). + if columnExists && haveStamp && stampedDim != l.embeddingDim { + if _, err := conn.ExecContext(ctx, `DROP INDEX IF EXISTS saved_trajectories_embedding_idx`); err != nil { + degradeMaterialize("drop stale index", err) + return nil + } + if _, err := conn.ExecContext(ctx, `ALTER TABLE saved_trajectories DROP COLUMN IF EXISTS embedding`); err != nil { + degradeMaterialize("drop stale column", err) + return nil + } + columnExists = false + } + if !columnExists { + if _, err := conn.ExecContext(ctx, fmt.Sprintf(`ALTER TABLE saved_trajectories ADD COLUMN IF NOT EXISTS embedding vector(%d)`, l.embeddingDim)); err != nil { + degradeMaterialize("add embedding column", err) + return nil + } + } + // CREATE INDEX IF NOT EXISTS won't rebuild an index that already exists, + // so changing m/ef_construction on a live deployment needs a manual + // reindex (documented as a tuning-runbook step). On a fresh build the + // WITH clause bakes in the configured graph parameters. + idxSQL := `CREATE INDEX IF NOT EXISTS saved_trajectories_embedding_idx ON saved_trajectories USING hnsw (embedding vector_cosine_ops)` + if l.hnswM > 0 || l.hnswEfConstruction > 0 { + m := l.hnswM + if m <= 0 { + m = 16 // pgvector default + } + efc := l.hnswEfConstruction + if efc <= 0 { + efc = 64 // pgvector default + } + idxSQL += fmt.Sprintf(" WITH (m = %d, ef_construction = %d)", m, efc) + } + if _, err := conn.ExecContext(ctx, idxSQL); err != nil { + degradeMaterialize("create hnsw index", err) + return nil + } + if _, err := conn.ExecContext(ctx, ` + INSERT INTO embedding_config (id, model_id, dimensions, updated_at) + VALUES (1, $1, $2, now()) + ON CONFLICT (id) DO UPDATE SET model_id=EXCLUDED.model_id, dimensions=EXCLUDED.dimensions, updated_at=now()`, + l.embeddingModelID, l.embeddingDim); err != nil { + return fmt.Errorf("stamp embedding_config: %w", err) + } + l.semanticEnabled = true + return nil +} diff --git a/internal/buildlibrary/embedding_bootstrap_test.go b/internal/buildlibrary/embedding_bootstrap_test.go new file mode 100644 index 0000000..85efcc7 --- /dev/null +++ b/internal/buildlibrary/embedding_bootstrap_test.go @@ -0,0 +1,184 @@ +package buildlibrary + +import ( + "context" + "database/sql" + "encoding/json" + "strings" + "testing" + "time" + + "github.com/levonn-dev/ro-builder/internal/domain" +) + +// seedGeneration enqueues a job and updates it to status='running' with +// lease_owner='w1', returning its ID. Used by embedding tests that need a +// valid parent generation row for SaveAndComplete. +func seedGeneration(t *testing.T, lib *Library) string { + t.Helper() + id, err := lib.Enqueue(context.Background(), json.RawMessage(`{}`)) + if err != nil { + t.Fatalf("seedGeneration Enqueue: %v", err) + } + if _, err := lib.db.ExecContext(context.Background(), + `UPDATE generations SET status='running', lease_owner='w1', started_at=$1 WHERE id=$2`, + time.Now().UTC(), id); err != nil { + t.Fatalf("seedGeneration set running: %v", err) + } + return id +} + +// validSaveInput returns a SaveInput with one scored, gate-passing snapshot +// so summarizeAndGuard accepts it and SaveAndComplete's completion UPDATE +// matches (owner='w1'). +func validSaveInput(t *testing.T, id, owner string) SaveInput { + t.Helper() + return SaveInput{ + ID: id, + Owner: owner, + Class: "taekwon_kid", + Server: "uaro", + Playstyle: "pvm", + Mode: "pre-renewal", + Primary: domain.Trajectory{ + Class: "taekwon_kid", + Snapshots: []domain.Snapshot{ + scoredSnapshot("taekwon_kid", nil), + }, + }, + } +} + +func openWithEmbedding(t *testing.T, dim int, modelID string, extra ...Option) *Library { + t.Helper() + if testing.Short() { + t.Skip("requires Postgres (testcontainers); skipped under -short") + } + // Pre-truncate before the main Open so that bootstrapEmbedding sees an + // empty corpus. Without this, a prior test that saved an embedding could + // leave a non-empty saved_trajectories and cause the bootstrap to degrade + // on a model mismatch, since Open calls bootstrapEmbedding before Truncate + // would run. + pre, preErr := Open(context.Background(), testDSN) + if preErr != nil { + t.Fatalf("openWithEmbedding pre-open: %v", preErr) + } + if err := pre.Truncate(context.Background()); err != nil { + t.Fatalf("openWithEmbedding pre-truncate: %v", err) + } + _ = pre.Close() + + opts := append([]Option{WithEmbedding(dim, modelID)}, extra...) + lib, err := Open(context.Background(), testDSN, opts...) + if err != nil { + t.Fatalf("Open: %v", err) + } + t.Cleanup(func() { _ = lib.Close() }) + return lib +} + +func TestBootstrap_FirstRunCreatesColumnAndStamps(t *testing.T) { + lib := openWithEmbedding(t, 8, "test-model@8") + if !lib.SemanticEnabled() { + t.Fatal("semantic should be enabled after first-run bootstrap") + } + // vector column exists + var n int + if err := lib.db.QueryRowContext(context.Background(), + `SELECT count(*) FROM information_schema.columns WHERE table_name='saved_trajectories' AND column_name='embedding'`).Scan(&n); err != nil { + t.Fatalf("query column: %v", err) + } + if n != 1 { + t.Fatal("embedding column not created") + } + // config stamped + var model string + var dim int + if err := lib.db.QueryRowContext(context.Background(), + `SELECT model_id, dimensions FROM embedding_config WHERE id=1`).Scan(&model, &dim); err != nil { + t.Fatalf("query config: %v", err) + } + if model != "test-model@8" || dim != 8 { + t.Fatalf("stamp = %q/%d", model, dim) + } +} + +func TestBootstrap_SecondOpenSameModelIsNoop(t *testing.T) { + _ = openWithEmbedding(t, 8, "test-model@8") + lib2, err := Open(context.Background(), testDSN, WithEmbedding(8, "test-model@8")) + if err != nil { + t.Fatalf("second Open: %v", err) + } + defer lib2.Close() + if !lib2.SemanticEnabled() { + t.Fatal("second open with matching model should stay enabled") + } +} + +func TestBootstrap_DisabledWhenNoOption(t *testing.T) { + lib := newTestLibrary(t) // Open without WithEmbedding + if lib.SemanticEnabled() { + t.Fatal("semantic must be disabled with no embedding option") + } +} + +func TestBootstrap_HNSWParamsBakedIntoIndex(t *testing.T) { + if testing.Short() { + t.Skip("requires Postgres (testcontainers); skipped under -short") + } + // Force a clean slate: drop the column/index/stamp so the bootstrap's + // CREATE INDEX IF NOT EXISTS actually builds a fresh index with our + // params (a leftover default-param index from a prior test would + // otherwise satisfy IF NOT EXISTS and mask the WITH clause). + pre, err := Open(context.Background(), testDSN) + if err != nil { + t.Fatalf("pre-open: %v", err) + } + for _, stmt := range []string{ + `DROP INDEX IF EXISTS saved_trajectories_embedding_idx`, + `ALTER TABLE saved_trajectories DROP COLUMN IF EXISTS embedding`, + `DELETE FROM embedding_config`, + } { + if _, err := pre.db.ExecContext(context.Background(), stmt); err != nil { + t.Fatalf("clean-slate %q: %v", stmt, err) + } + } + _ = pre.Close() + + lib, err := Open(context.Background(), testDSN, WithEmbedding(8, "hnsw-test@8"), WithHNSW(8, 32, 0)) + if err != nil { + t.Fatalf("Open: %v", err) + } + t.Cleanup(func() { _ = lib.Close() }) + if !lib.SemanticEnabled() { + t.Fatal("semantic should be enabled") + } + + var opts sql.NullString + if err := lib.db.QueryRowContext(context.Background(), + `SELECT array_to_string(reloptions, ',') FROM pg_class WHERE relname='saved_trajectories_embedding_idx'`).Scan(&opts); err != nil { + t.Fatalf("read index reloptions: %v", err) + } + if !strings.Contains(opts.String, "m=8") || !strings.Contains(opts.String, "ef_construction=32") { + t.Fatalf("index reloptions = %q; want m=8 and ef_construction=32", opts.String) + } +} + +func TestBootstrap_MismatchNonEmptyCorpusDegrades(t *testing.T) { + lib := openWithEmbedding(t, 4, "model-A@4") + id := seedGeneration(t, lib) + in := validSaveInput(t, id, "w1") + in.Embedding = []float32{1, 0, 0, 0} + if _, err := lib.SaveAndComplete(context.Background(), in); err != nil { + t.Fatalf("save: %v", err) + } + // Re-open with a different model at the SAME dim and a non-empty corpus. + lib2, err := Open(context.Background(), testDSN, WithEmbedding(4, "model-B@4")) + if err != nil { + t.Fatalf("reopen: %v", err) + } + defer lib2.Close() + if lib2.SemanticEnabled() { + t.Fatal("expected recency mode (semantic disabled) on model mismatch vs non-empty corpus") + } +} diff --git a/internal/buildlibrary/embedding_config_test.go b/internal/buildlibrary/embedding_config_test.go new file mode 100644 index 0000000..388d9f9 --- /dev/null +++ b/internal/buildlibrary/embedding_config_test.go @@ -0,0 +1,19 @@ +package buildlibrary + +import ( + "context" + "testing" +) + +func TestMigration_EmbeddingConfigTableExists(t *testing.T) { + lib := newTestLibrary(t) + var n int + err := lib.db.QueryRowContext(context.Background(), + `SELECT count(*) FROM information_schema.tables WHERE table_name = 'embedding_config'`).Scan(&n) + if err != nil { + t.Fatalf("query: %v", err) + } + if n != 1 { + t.Fatalf("embedding_config table missing (got %d)", n) + } +} diff --git a/internal/buildlibrary/embedding_find_test.go b/internal/buildlibrary/embedding_find_test.go new file mode 100644 index 0000000..30aa6dc --- /dev/null +++ b/internal/buildlibrary/embedding_find_test.go @@ -0,0 +1,113 @@ +package buildlibrary + +import ( + "context" + "testing" +) + +// saveWithEmbedding seeds a generation, builds a valid SaveInput with the +// given class/server, sets Embedding=vec, calls SaveAndComplete, and +// returns the saved id. +func saveWithEmbedding(t *testing.T, lib *Library, class, server string, vec []float32) string { + t.Helper() + saved := saveEmbeddedPending(t, lib, class, server, vec) + // A normal saved-and-usable build is user-accepted, so it appears on the + // RAG retrieval surface (SimilarTop / get_similar_past_builds). + if _, err := lib.Accept(context.Background(), saved); err != nil { + t.Fatalf("saveWithEmbedding accept: %v", err) + } + return saved +} + +// saveEmbeddedPending saves a build WITHOUT accepting it, so it is fetchable +// but not yet visible to the RAG retrieval surface. Used by the acceptance- +// gate tests. +func saveEmbeddedPending(t *testing.T, lib *Library, class, server string, vec []float32) string { + t.Helper() + id := seedGeneration(t, lib) + in := validSaveInput(t, id, "w1") + in.Class = class + in.Server = server + in.Embedding = vec + saved, err := lib.SaveAndComplete(context.Background(), in) + if err != nil { + t.Fatalf("saveEmbeddedPending: %v", err) + } + return saved +} + +func TestFindSimilar_OrdersByCosineDistance(t *testing.T) { + lib := openWithEmbedding(t, 4, "m@4") + // Two saved builds, same class/server, different vectors. + near := saveWithEmbedding(t, lib, "taekwon_kid", "uaro", []float32{1, 0, 0, 0}) + _ = saveWithEmbedding(t, lib, "taekwon_kid", "uaro", []float32{0, 1, 0, 0}) + got, err := lib.FindSimilar(context.Background(), []float32{0.9, 0.1, 0, 0}, + FindParams{Class: "taekwon_kid", Server: "uaro", Limit: 5}) + if err != nil { + t.Fatalf("FindSimilar: %v", err) + } + if len(got) != 2 { + t.Fatalf("want 2 results, got %d", len(got)) + } + if got[0].ID != near { + t.Fatalf("closest first: got %s want %s", got[0].ID, near) + } + if got[0].Distance > got[1].Distance { + t.Fatalf("distances not ascending: %v", got) + } +} + +func TestFindSimilar_MaxDistanceFiltersFarRows(t *testing.T) { + lib := openWithEmbedding(t, 4, "md@4") + near := saveWithEmbedding(t, lib, "taekwon_kid", "uaro", []float32{1, 0, 0, 0}) + // Orthogonal vector: cosine distance to the query below is ~1.0. + _ = saveWithEmbedding(t, lib, "taekwon_kid", "uaro", []float32{0, 1, 0, 0}) + + // Query identical to `near` (distance ~0); the orthogonal row sits at + // ~1.0. A 0.5 floor must keep only `near`. + got, err := lib.FindSimilar(context.Background(), []float32{1, 0, 0, 0}, + FindParams{Class: "taekwon_kid", Server: "uaro", Limit: 5, MaxDistance: 0.5}) + if err != nil { + t.Fatalf("FindSimilar: %v", err) + } + if len(got) != 1 { + t.Fatalf("MaxDistance 0.5 should keep only the near row; got %d results", len(got)) + } + if got[0].ID != near { + t.Fatalf("kept row = %s; want %s", got[0].ID, near) + } +} + +func TestFindSimilar_EfSearchPathReturnsResults(t *testing.T) { + // WithHNSW ef_search > 0 routes FindSimilar through the SET LOCAL + // transaction path; results must still be correct. + lib := openWithEmbedding(t, 4, "efs@4", WithHNSW(0, 0, 64)) + near := saveWithEmbedding(t, lib, "taekwon_kid", "uaro", []float32{1, 0, 0, 0}) + _ = saveWithEmbedding(t, lib, "taekwon_kid", "uaro", []float32{0, 1, 0, 0}) + got, err := lib.FindSimilar(context.Background(), []float32{0.9, 0.1, 0, 0}, + FindParams{Class: "taekwon_kid", Server: "uaro", Limit: 5}) + if err != nil { + t.Fatalf("FindSimilar (ef_search path): %v", err) + } + if len(got) != 2 { + t.Fatalf("want 2 results, got %d", len(got)) + } + if got[0].ID != near { + t.Fatalf("closest first: got %s want %s", got[0].ID, near) + } +} + +func TestSimilarTop_ReturnsFullTrajectory(t *testing.T) { + lib := openWithEmbedding(t, 4, "m@4") + id := saveWithEmbedding(t, lib, "taekwon_kid", "uaro", []float32{1, 0, 0, 0}) + st, dist, ok, err := lib.SimilarTop(context.Background(), []float32{1, 0, 0, 0}, "taekwon_kid", "uaro") + if err != nil || !ok { + t.Fatalf("SimilarTop ok=%v err=%v", ok, err) + } + if st.ID != id { + t.Fatalf("got %s want %s", st.ID, id) + } + if dist > 0.001 { + t.Fatalf("identical vector distance should be ~0, got %v", dist) + } +} diff --git a/internal/buildlibrary/embedding_recall_test.go b/internal/buildlibrary/embedding_recall_test.go new file mode 100644 index 0000000..c13e965 --- /dev/null +++ b/internal/buildlibrary/embedding_recall_test.go @@ -0,0 +1,42 @@ +package buildlibrary + +import ( + "context" + "testing" +) + +func TestRecallAtK(t *testing.T) { + lib := openWithEmbedding(t, 4, "test-model@4") + ctx := context.Background() + + // Seed five rows with distinct unit-ish vectors so the cosine ordering + // is deterministic. At tiny corpus size exact KNN and HNSW agree, so + // recall must be 1.0. + vecs := [][]float32{ + {1, 0, 0, 0}, + {0, 1, 0, 0}, + {0, 0, 1, 0}, + {0, 0, 0, 1}, + {0.7071, 0.7071, 0, 0}, + } + classes := []string{"taekwon_kid", "knight", "wizard", "hunter", "monk"} + for i, v := range vecs { + saveWithEmbedding(t, lib, classes[i], "uaro", v) + } + + probes, err := lib.SampleVectors(ctx, 10) + if err != nil { + t.Fatalf("SampleVectors: %v", err) + } + if len(probes) != len(vecs) { + t.Fatalf("SampleVectors: want %d probes, got %d", len(vecs), len(probes)) + } + + recall, err := lib.RecallAtK(ctx, probes, 3, 0) + if err != nil { + t.Fatalf("RecallAtK: %v", err) + } + if recall != 1.0 { + t.Fatalf("RecallAtK = %.4f, want 1.0 (HNSW and exact should agree at tiny corpus)", recall) + } +} diff --git a/internal/buildlibrary/embedding_save_test.go b/internal/buildlibrary/embedding_save_test.go new file mode 100644 index 0000000..eb77019 --- /dev/null +++ b/internal/buildlibrary/embedding_save_test.go @@ -0,0 +1,39 @@ +package buildlibrary + +import ( + "context" + "testing" +) + +func TestSave_WritesEmbeddingWhenEnabled(t *testing.T) { + lib := openWithEmbedding(t, 4, "test-model@4") + id := seedGeneration(t, lib) + in := validSaveInput(t, id, "w1") + in.Embedding = []float32{0.1, 0.2, 0.3, 0.4} + if _, err := lib.SaveAndComplete(context.Background(), in); err != nil { + t.Fatalf("SaveAndComplete: %v", err) + } + var nonNull bool + if err := lib.db.QueryRowContext(context.Background(), + `SELECT embedding IS NOT NULL FROM saved_trajectories WHERE id=$1`, id).Scan(&nonNull); err != nil { + t.Fatalf("query: %v", err) + } + if !nonNull { + t.Fatal("embedding column is NULL; expected the supplied vector") + } +} + +func TestSave_NullEmbeddingWhenNotSupplied(t *testing.T) { + lib := openWithEmbedding(t, 4, "test-model@4") + id := seedGeneration(t, lib) + in := validSaveInput(t, id, "w1") // no Embedding + if _, err := lib.SaveAndComplete(context.Background(), in); err != nil { + t.Fatalf("SaveAndComplete: %v", err) + } + var nonNull bool + _ = lib.db.QueryRowContext(context.Background(), + `SELECT embedding IS NOT NULL FROM saved_trajectories WHERE id=$1`, id).Scan(&nonNull) + if nonNull { + t.Fatal("embedding should be NULL when not supplied") + } +} diff --git a/internal/buildlibrary/find.go b/internal/buildlibrary/find.go index 972a523..85d957f 100644 --- a/internal/buildlibrary/find.go +++ b/internal/buildlibrary/find.go @@ -6,6 +6,8 @@ import ( "encoding/json" "errors" "fmt" + + pgvector "github.com/pgvector/pgvector-go" ) // FindParams narrows a Find call. @@ -13,6 +15,27 @@ type FindParams struct { Class string Server string Limit int + // MaxDistance, when > 0, drops rows whose cosine distance to the query + // vector exceeds it (the Tier B list floor). 0 = no distance filter. + // Applies to FindSimilar only; Find is recency-ordered and ignores it. + MaxDistance float64 + // Accepted filters by acceptance state: nil = all, true = accepted only + // (the RAG retrieval surface), false = pending only. RAG callers set true; + // the user-facing list leaves it nil (or honours the ?accepted= param). + Accepted *bool +} + +// acceptedClause returns the SQL predicate for p.Accepted (empty when nil). +// The predicate binds no parameter (IS [NOT] NULL), so callers append it +// without consuming a placeholder index. +func (p FindParams) acceptedClause() string { + if p.Accepted == nil { + return "" + } + if *p.Accepted { + return " AND accepted_at IS NOT NULL" + } + return " AND accepted_at IS NULL" } const ( @@ -34,7 +57,7 @@ func (l *Library) Find(ctx context.Context, p FindParams) ([]Summary, error) { } q := ` -SELECT id, created_at, class, server, playstyle, description, gate_summary +SELECT id, created_at, class, server, playstyle, description, gate_summary, accepted_at FROM saved_trajectories WHERE 1=1 ` @@ -50,6 +73,7 @@ WHERE 1=1 q += fmt.Sprintf(" AND server = $%d", n) args = append(args, p.Server) } + q += p.acceptedClause() n++ q += fmt.Sprintf(" ORDER BY created_at DESC LIMIT $%d", n) args = append(args, limit) @@ -64,9 +88,13 @@ WHERE 1=1 for rows.Next() { var s Summary var gateJSON string - if err := rows.Scan(&s.ID, &s.CreatedAt, &s.Class, &s.Server, &s.Playstyle, &s.Description, &gateJSON); err != nil { + var acceptedAt sql.NullTime + if err := rows.Scan(&s.ID, &s.CreatedAt, &s.Class, &s.Server, &s.Playstyle, &s.Description, &gateJSON, &acceptedAt); err != nil { return nil, fmt.Errorf("scan: %w", err) } + if acceptedAt.Valid { + s.AcceptedAt = &acceptedAt.Time + } if gateJSON != "" { if err := json.Unmarshal([]byte(gateJSON), &s.GateSummary); err != nil { return nil, fmt.Errorf("unmarshal gate_summary for %s: %w", s.ID, err) @@ -88,18 +116,19 @@ func (l *Library) Get(ctx context.Context, id string) (*SavedTrajectory, error) const q = ` SELECT id, created_at, class, server, playstyle, mode, description, primary_json, alternatives_json, final_text, gate_summary, - calc_version, catalog_version + calc_version, catalog_version, accepted_at FROM saved_trajectories WHERE id = $1 ` var ( - st SavedTrajectory - primaryJS string - altsJS sql.NullString - gateJS string + st SavedTrajectory + primaryJS string + altsJS sql.NullString + gateJS string + acceptedAt sql.NullTime ) err := l.db.QueryRowContext(ctx, q, id).Scan( &st.ID, &st.CreatedAt, &st.Class, &st.Server, &st.Playstyle, &st.Mode, &st.Description, - &primaryJS, &altsJS, &st.FinalText, &gateJS, &st.CalcVersion, &st.CatalogVersion, + &primaryJS, &altsJS, &st.FinalText, &gateJS, &st.CalcVersion, &st.CatalogVersion, &acceptedAt, ) if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound @@ -120,12 +149,140 @@ FROM saved_trajectories WHERE id = $1 return nil, fmt.Errorf("unmarshal gate_summary: %w", err) } } + if acceptedAt.Valid { + st.AcceptedAt = &acceptedAt.Time + } return &st, nil } // ErrNotFound is returned by Get when no trajectory with the given id exists. var ErrNotFound = errors.New("buildlibrary: trajectory not found") +// SimilarSummary is a Find summary plus its cosine distance to the query +// (0 = identical, 2 = opposite). Lower is closer. +type SimilarSummary struct { + Summary + Distance float64 `json:"distance"` +} + +// FindSimilar returns saved trajectories matching p.Class/p.Server that +// carry an embedding, ordered nearest-first by cosine distance to queryVec. +// When p.MaxDistance > 0, rows beyond that cosine distance are dropped. When +// the deployment configured a query-time hnsw.ef_search (WithHNSW), the query +// runs inside a read-only transaction that SET LOCALs it, so the recall/speed +// setting applies without leaking to other callers that later borrow the same +// pooled connection (database/sql does not reset session state on return). +// Returns nil (no error) when the library is recency-only. +func (l *Library) FindSimilar(ctx context.Context, queryVec []float32, p FindParams) ([]SimilarSummary, error) { + if l == nil || l.db == nil { + return nil, errors.New("buildlibrary.FindSimilar: nil library") + } + if !l.semanticEnabled || len(queryVec) == 0 { + return nil, nil + } + limit := p.Limit + if limit <= 0 { + limit = defaultFindLimit + } + if limit > maxFindLimit { + limit = maxFindLimit + } + q, args := buildSimilarQuery(queryVec, p, limit) + + if l.hnswEfSearch > 0 { + conn, err := l.db.Conn(ctx) + if err != nil { + return nil, fmt.Errorf("acquire conn: %w", err) + } + defer func() { _ = conn.Close() }() + tx, err := conn.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin tx: %w", err) + } + defer func() { _ = tx.Rollback() }() // read-only; discards the SET LOCAL + if _, err := tx.ExecContext(ctx, fmt.Sprintf(`SET LOCAL hnsw.ef_search = %d`, l.hnswEfSearch)); err != nil { + return nil, fmt.Errorf("set ef_search: %w", err) + } + return scanSimilarRows(tx.QueryContext(ctx, q, args...)) + } + return scanSimilarRows(l.db.QueryContext(ctx, q, args...)) +} + +// buildSimilarQuery assembles the nearest-neighbour SELECT and its bound args. +func buildSimilarQuery(queryVec []float32, p FindParams, limit int) (string, []any) { + q := ` +SELECT id, created_at, class, server, playstyle, description, gate_summary, + accepted_at, embedding <=> $1 AS distance +FROM saved_trajectories +WHERE embedding IS NOT NULL +` + args := []any{pgvector.NewVector(queryVec)} + n := 1 + if p.MaxDistance > 0 { + n++ + q += fmt.Sprintf(" AND (embedding <=> $1) <= $%d", n) + args = append(args, p.MaxDistance) + } + if p.Class != "" { + n++ + q += fmt.Sprintf(" AND class = $%d", n) + args = append(args, p.Class) + } + if p.Server != "" { + n++ + q += fmt.Sprintf(" AND server = $%d", n) + args = append(args, p.Server) + } + q += p.acceptedClause() + n++ + q += fmt.Sprintf(" ORDER BY distance ASC LIMIT $%d", n) + args = append(args, limit) + return q, args +} + +// scanSimilarRows drains a similar-query result set. It accepts (rows, err) +// so callers can hand it a QueryContext result directly. +func scanSimilarRows(rows *sql.Rows, err error) ([]SimilarSummary, error) { + if err != nil { + return nil, fmt.Errorf("query: %w", err) + } + defer rows.Close() + var out []SimilarSummary + for rows.Next() { + var s SimilarSummary + var gateJSON string + var acceptedAt sql.NullTime + if err := rows.Scan(&s.ID, &s.CreatedAt, &s.Class, &s.Server, &s.Playstyle, &s.Description, &gateJSON, &acceptedAt, &s.Distance); err != nil { + return nil, fmt.Errorf("scan: %w", err) + } + if acceptedAt.Valid { + s.AcceptedAt = &acceptedAt.Time + } + if gateJSON != "" { + if err := json.Unmarshal([]byte(gateJSON), &s.GateSummary); err != nil { + return nil, fmt.Errorf("unmarshal gate_summary for %s: %w", s.ID, err) + } + } + out = append(out, s) + } + return out, rows.Err() +} + +// SimilarTop returns the single closest saved trajectory (full record) plus +// its distance. ok=false when recency-only or no embedded match exists. +func (l *Library) SimilarTop(ctx context.Context, queryVec []float32, class, server string) (*SavedTrajectory, float64, bool, error) { + acceptedOnly := true + sims, err := l.FindSimilar(ctx, queryVec, FindParams{Class: class, Server: server, Limit: 1, Accepted: &acceptedOnly}) + if err != nil || len(sims) == 0 { + return nil, 0, false, err + } + st, err := l.Get(ctx, sims[0].ID) + if err != nil { + return nil, 0, false, err + } + return st, sims[0].Distance, true, nil +} + // Count returns the total number of saved trajectories. func (l *Library) Count(ctx context.Context) (int, error) { if l == nil || l.db == nil { diff --git a/internal/buildlibrary/library.go b/internal/buildlibrary/library.go index 78d897f..cb43057 100644 --- a/internal/buildlibrary/library.go +++ b/internal/buildlibrary/library.go @@ -34,15 +34,76 @@ var migrationsFS embed.FS // with Close. Methods are safe for concurrent use. type Library struct { db *sql.DB + + // embedding config resolved at Open; semanticEnabled gates all vector + // reads/writes. embeddingDim is the column dimension. embeddingModelID + // is the (model@tier) identity compared against the stamped config. + semanticEnabled bool + embeddingDim int + embeddingModelID string + + // HNSW tuning knobs (0 = pgvector default). hnswM / hnswEfConstruction + // are build-time (baked into the index at bootstrap); hnswEfSearch is + // query-time (SET LOCAL per FindSimilar call). + hnswM int + hnswEfConstruction int + hnswEfSearch int +} + +// Option configures Open. +type Option func(*openOptions) + +type openOptions struct { + embeddingDim int + embeddingModelID string + hnswM int + hnswEfConstruction int + hnswEfSearch int +} + +// WithEmbedding declares the embedding dimension and model identity for +// this deployment. When set (dim>0 and modelID!=""), Open runs the +// config-driven bootstrap that materializes the pgvector column + index. +// Omit it for recency-only deployments. +func WithEmbedding(dim int, modelID string) Option { + return func(o *openOptions) { + o.embeddingDim = dim + o.embeddingModelID = modelID + } } +// WithHNSW overrides the HNSW index tuning knobs. Any argument <= 0 keeps +// pgvector's default (m=16, ef_construction=64, ef_search=40). m and +// efConstruction are baked into the index at bootstrap and only take effect +// on a fresh build (changing them on an existing index requires a reindex). +// efSearch is applied per query via SET LOCAL. Effective only alongside +// WithEmbedding. +func WithHNSW(m, efConstruction, efSearch int) Option { + return func(o *openOptions) { + o.hnswM = m + o.hnswEfConstruction = efConstruction + o.hnswEfSearch = efSearch + } +} + +// SemanticEnabled reports whether vector storage/retrieval is active. +func (l *Library) SemanticEnabled() bool { return l != nil && l.semanticEnabled } + +// EmbeddingDim is the configured vector dimension (0 when disabled). +func (l *Library) EmbeddingDim() int { return l.embeddingDim } + // Open connects to the Postgres database at dsn, verifies the connection, // and applies embedded migrations. dsn "" is rejected; callers must supply -// an explicit connection string. -func Open(ctx context.Context, dsn string) (*Library, error) { +// an explicit connection string. Variadic opts configure optional features; +// callers that pass no opts get a recency-only library (no vector search). +func Open(ctx context.Context, dsn string, opts ...Option) (*Library, error) { if dsn == "" { return nil, fmt.Errorf("buildlibrary.Open: dsn is required") } + var o openOptions + for _, opt := range opts { + opt(&o) + } db, err := sql.Open("pgx", dsn) if err != nil { return nil, fmt.Errorf("open postgres: %w", err) @@ -58,7 +119,21 @@ func Open(ctx context.Context, dsn string) (*Library, error) { _ = db.Close() return nil, fmt.Errorf("migrate: %w", err) } - return &Library{db: db}, nil + lib := &Library{ + db: db, + embeddingDim: o.embeddingDim, + embeddingModelID: o.embeddingModelID, + hnswM: o.hnswM, + hnswEfConstruction: o.hnswEfConstruction, + hnswEfSearch: o.hnswEfSearch, + } + if o.embeddingDim > 0 && o.embeddingModelID != "" { + if err := lib.bootstrapEmbedding(ctx); err != nil { + _ = db.Close() + return nil, fmt.Errorf("embedding bootstrap: %w", err) + } + } + return lib, nil } // runMigrations applies embedded migrations using the app's *sql.DB. @@ -128,6 +203,9 @@ type SavedTrajectory struct { GateSummary GateSummary `json:"gate_summary"` CalcVersion string `json:"calc_version,omitempty"` CatalogVersion int `json:"catalog_version,omitempty"` + // AcceptedAt is nil until the user accepts the build. RAG retrieval only + // surfaces accepted builds; the user-facing GET /builds paths show all. + AcceptedAt *time.Time `json:"accepted_at,omitempty"` } // GateSummary aggregates per-snapshot gate counts so retrieval queries @@ -151,4 +229,5 @@ type Summary struct { Playstyle string `json:"playstyle"` Description string `json:"description,omitempty"` GateSummary GateSummary `json:"gate_summary"` + AcceptedAt *time.Time `json:"accepted_at,omitempty"` } diff --git a/internal/buildlibrary/migrations/000002_embedding.down.sql b/internal/buildlibrary/migrations/000002_embedding.down.sql new file mode 100644 index 0000000..be30ab6 --- /dev/null +++ b/internal/buildlibrary/migrations/000002_embedding.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS embedding_config; diff --git a/internal/buildlibrary/migrations/000002_embedding.up.sql b/internal/buildlibrary/migrations/000002_embedding.up.sql new file mode 100644 index 0000000..5adc9f8 --- /dev/null +++ b/internal/buildlibrary/migrations/000002_embedding.up.sql @@ -0,0 +1,11 @@ +-- Singleton config row stamping which embedding model+tier produced the +-- corpus. Model-agnostic and pgvector-free: the vector column + extension +-- are created by the app's config-driven bootstrap, not here, because +-- CREATE EXTENSION for non-trusted pgvector needs privileges the migration +-- role should not require. +CREATE TABLE embedding_config ( + id smallint PRIMARY KEY DEFAULT 1 CHECK (id = 1), + model_id text NOT NULL, + dimensions integer NOT NULL, + updated_at timestamptz NOT NULL DEFAULT now() +); diff --git a/internal/buildlibrary/migrations/000003_accepted.down.sql b/internal/buildlibrary/migrations/000003_accepted.down.sql new file mode 100644 index 0000000..e8cd6d1 --- /dev/null +++ b/internal/buildlibrary/migrations/000003_accepted.down.sql @@ -0,0 +1 @@ +ALTER TABLE saved_trajectories DROP COLUMN IF EXISTS accepted_at; diff --git a/internal/buildlibrary/migrations/000003_accepted.up.sql b/internal/buildlibrary/migrations/000003_accepted.up.sql new file mode 100644 index 0000000..1bcfefd --- /dev/null +++ b/internal/buildlibrary/migrations/000003_accepted.up.sql @@ -0,0 +1 @@ +ALTER TABLE saved_trajectories ADD COLUMN accepted_at timestamptz; diff --git a/internal/buildlibrary/save.go b/internal/buildlibrary/save.go index fd9b78f..1f50689 100644 --- a/internal/buildlibrary/save.go +++ b/internal/buildlibrary/save.go @@ -8,6 +8,8 @@ import ( "fmt" "time" + pgvector "github.com/pgvector/pgvector-go" + "github.com/levonn-dev/ro-builder/internal/domain" ) @@ -33,9 +35,14 @@ type SaveInput struct { FinalText string CalcVersion string CatalogVersion int + + // Embedding is the request+answer document vector for semantic + // retrieval. Optional: nil/empty stores NULL (the row is then invisible + // to FindSimilar). Ignored entirely when the library is recency-only. + Embedding []float32 } -// insertSavedTrajectory is the shared INSERT used by Save and SaveAndComplete. +// insertSavedTrajectory is the recency-only INSERT (no embedding column). const insertSavedTrajectory = ` INSERT INTO saved_trajectories (id, created_at, class, server, playstyle, mode, description, @@ -44,6 +51,24 @@ INSERT INTO saved_trajectories VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9::jsonb, $10, $11::jsonb, $12, $13) ` +const insertSavedTrajectoryWithEmbedding = ` +INSERT INTO saved_trajectories + (id, created_at, class, server, playstyle, mode, description, + primary_json, alternatives_json, final_text, gate_summary, + calc_version, catalog_version, embedding) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9::jsonb, $10, $11::jsonb, $12, $13, $14) +` + +// embeddingArg returns the $14 bind value for the with-embedding INSERT: +// a pgvector.Vector when a vector is supplied, or nil (SQL NULL) otherwise. +func embeddingArg(emb []float32) any { + if len(emb) == 0 { + return nil + } + v := pgvector.NewVector(emb) + return v +} + // ErrFailingGates is returned by Save when at least one scored snapshot // in Primary or Alternatives carries a fail / fail_hard gate result. // The library rejects rather than persisting junk. @@ -103,12 +128,20 @@ func (l *Library) Save(ctx context.Context, in SaveInput) (string, error) { return "", fmt.Errorf("marshal gate_summary: %w", err) } - if _, err := l.db.ExecContext(ctx, insertSavedTrajectory, - in.ID, time.Now().UTC(), - in.Class, in.Server, in.Playstyle, in.Mode, in.Description, - string(primaryJSON), nullableJSON(altsJSON), in.FinalText, string(summaryJSON), - in.CalcVersion, in.CatalogVersion, - ); err != nil { + if l.semanticEnabled { + _, err = l.db.ExecContext(ctx, insertSavedTrajectoryWithEmbedding, + in.ID, time.Now().UTC(), + in.Class, in.Server, in.Playstyle, in.Mode, in.Description, + string(primaryJSON), nullableJSON(altsJSON), in.FinalText, string(summaryJSON), + in.CalcVersion, in.CatalogVersion, embeddingArg(in.Embedding)) + } else { + _, err = l.db.ExecContext(ctx, insertSavedTrajectory, + in.ID, time.Now().UTC(), + in.Class, in.Server, in.Playstyle, in.Mode, in.Description, + string(primaryJSON), nullableJSON(altsJSON), in.FinalText, string(summaryJSON), + in.CalcVersion, in.CatalogVersion) + } + if err != nil { return "", fmt.Errorf("insert: %w", err) } return in.ID, nil @@ -162,13 +195,22 @@ func (l *Library) SaveAndComplete(ctx context.Context, in SaveInput) (string, er } }() - if _, err := tx.ExecContext(ctx, insertSavedTrajectory, - in.ID, time.Now().UTC(), - in.Class, in.Server, in.Playstyle, in.Mode, in.Description, - string(primaryJSON), nullableJSON(altsJSON), in.FinalText, string(summaryJSON), - in.CalcVersion, in.CatalogVersion, - ); err != nil { - return "", fmt.Errorf("insert: %w", err) + var insertErr error + if l.semanticEnabled { + _, insertErr = tx.ExecContext(ctx, insertSavedTrajectoryWithEmbedding, + in.ID, time.Now().UTC(), + in.Class, in.Server, in.Playstyle, in.Mode, in.Description, + string(primaryJSON), nullableJSON(altsJSON), in.FinalText, string(summaryJSON), + in.CalcVersion, in.CatalogVersion, embeddingArg(in.Embedding)) + } else { + _, insertErr = tx.ExecContext(ctx, insertSavedTrajectory, + in.ID, time.Now().UTC(), + in.Class, in.Server, in.Playstyle, in.Mode, in.Description, + string(primaryJSON), nullableJSON(altsJSON), in.FinalText, string(summaryJSON), + in.CalcVersion, in.CatalogVersion) + } + if insertErr != nil { + return "", fmt.Errorf("insert: %w", insertErr) } res, err := tx.ExecContext(ctx, ` diff --git a/internal/domain/query_embedding_context.go b/internal/domain/query_embedding_context.go new file mode 100644 index 0000000..7005438 --- /dev/null +++ b/internal/domain/query_embedding_context.go @@ -0,0 +1,18 @@ +package domain + +import "context" + +type queryEmbeddingKey struct{} + +// WithQueryEmbedding stamps the request's query vector on the context so +// retrieval tools can rank semantically without re-embedding. The +// orchestrator computes it once per request. +func WithQueryEmbedding(ctx context.Context, vec []float32) context.Context { + return context.WithValue(ctx, queryEmbeddingKey{}, vec) +} + +// QueryEmbeddingFromContext returns the stamped query vector, if any. +func QueryEmbeddingFromContext(ctx context.Context) ([]float32, bool) { + v, ok := ctx.Value(queryEmbeddingKey{}).([]float32) + return v, ok && len(v) > 0 +} diff --git a/internal/domain/query_embedding_context_test.go b/internal/domain/query_embedding_context_test.go new file mode 100644 index 0000000..b9da150 --- /dev/null +++ b/internal/domain/query_embedding_context_test.go @@ -0,0 +1,17 @@ +package domain + +import ( + "context" + "testing" +) + +func TestQueryEmbeddingContext(t *testing.T) { + if _, ok := QueryEmbeddingFromContext(context.Background()); ok { + t.Error("empty context should have no query embedding") + } + ctx := WithQueryEmbedding(context.Background(), []float32{1, 2, 3}) + v, ok := QueryEmbeddingFromContext(ctx) + if !ok || len(v) != 3 || v[2] != 3 { + t.Fatalf("got %v %v", v, ok) + } +} diff --git a/internal/embedding/config.go b/internal/embedding/config.go new file mode 100644 index 0000000..7bec95d --- /dev/null +++ b/internal/embedding/config.go @@ -0,0 +1,56 @@ +package embedding + +import ( + "fmt" + "os" + "strconv" +) + +// Config is populated from EMBEDDING_* env vars by LoadConfigFromEnv. +// BaseURL presence is the on/off switch; when set, Model and Dim are +// required (Dim is both the request "dimensions" and the storage column N). +type Config struct { + BaseURL string + Model string + APIKey string + Dim int +} + +// Enabled reports whether embeddings are configured at all. +func (c Config) Enabled() bool { return c.BaseURL != "" } + +// Validate returns an error if the config is enabled but incomplete. A +// disabled config (no BaseURL) is always valid. +func (c Config) Validate() error { + if !c.Enabled() { + return nil + } + if c.Model == "" { + return fmt.Errorf("embedding: EMBEDDING_MODEL is required when EMBEDDING_BASE_URL is set") + } + if c.Dim <= 0 { + return fmt.Errorf("embedding: EMBEDDING_DIM (>0) is required when EMBEDDING_BASE_URL is set") + } + return nil +} + +// LoadConfigFromEnv reads EMBEDDING_* into a Config. +// +// EMBEDDING_BASE_URL OpenAI-compatible /v1 root; presence enables the feature +// EMBEDDING_MODEL model id (e.g. nomic-embed-text, text-embedding-3-large) +// EMBEDDING_API_KEY optional bearer (cloud); ignored by local servers +// EMBEDDING_DIM vector dimension / tier; required when enabled +func LoadConfigFromEnv() Config { + dim := 0 + if v := os.Getenv("EMBEDDING_DIM"); v != "" { + if n, err := strconv.Atoi(v); err == nil { + dim = n + } + } + return Config{ + BaseURL: os.Getenv("EMBEDDING_BASE_URL"), + Model: os.Getenv("EMBEDDING_MODEL"), + APIKey: os.Getenv("EMBEDDING_API_KEY"), + Dim: dim, + } +} diff --git a/internal/embedding/config_test.go b/internal/embedding/config_test.go new file mode 100644 index 0000000..f826f3b --- /dev/null +++ b/internal/embedding/config_test.go @@ -0,0 +1,36 @@ +package embedding + +import "testing" + +func TestConfig_EnabledAndValidate(t *testing.T) { + if (Config{}).Enabled() { + t.Error("empty config should be disabled") + } + c := Config{BaseURL: "http://x/v1", Model: "nomic-embed-text", Dim: 768} + if !c.Enabled() { + t.Error("config with BaseURL should be enabled") + } + if err := c.Validate(); err != nil { + t.Errorf("valid config: %v", err) + } + if err := (Config{BaseURL: "http://x/v1", Model: "m"}).Validate(); err == nil { + t.Error("enabled config with Dim=0 must fail Validate") + } + if err := (Config{BaseURL: "http://x/v1", Dim: 768}).Validate(); err == nil { + t.Error("enabled config with empty Model must fail Validate") + } + if err := (Config{}).Validate(); err != nil { + t.Errorf("disabled config is always valid: %v", err) + } +} + +func TestLoadConfigFromEnv(t *testing.T) { + t.Setenv("EMBEDDING_BASE_URL", "http://localhost:11434/v1") + t.Setenv("EMBEDDING_MODEL", "nomic-embed-text") + t.Setenv("EMBEDDING_DIM", "768") + t.Setenv("EMBEDDING_API_KEY", "sk-x") + c := LoadConfigFromEnv() + if c.BaseURL != "http://localhost:11434/v1" || c.Model != "nomic-embed-text" || c.Dim != 768 || c.APIKey != "sk-x" { + t.Fatalf("unexpected config: %+v", c) + } +} diff --git a/internal/embedding/embedding.go b/internal/embedding/embedding.go new file mode 100644 index 0000000..b369ea6 --- /dev/null +++ b/internal/embedding/embedding.go @@ -0,0 +1,28 @@ +// Package embedding produces vector embeddings of text via an +// OpenAI-compatible /v1/embeddings endpoint. It mirrors internal/llm/openai: +// one net/http client, no SDK, selected entirely by config (EMBEDDING_*), +// so the same code reaches local Ollama, OpenAI cloud, or Voyage's +// OpenAI-shaped HTTP API. Anthropic (the default LLM) has no embeddings +// API, so an embedder is a genuine separate dependency. +// +// The provider is OPTIONAL: when EMBEDDING_BASE_URL is unset the caller +// constructs no provider and the build library runs recency-only. +package embedding + +import "context" + +// Provider is the embedding gateway. Dimensions() and ModelID() are the +// two facts the storage layer needs at bootstrap (the column dimension) +// and at the guard (which model+tier produced the corpus). One active +// impl per process. +type Provider interface { + // Embed returns one vector per input string, in order. Vectors have + // length Dimensions(). + Embed(ctx context.Context, texts []string) ([][]float32, error) + // Dimensions is the vector length, fixed by the configured model+tier. + Dimensions() int + // ModelID uniquely identifies the model+tier (e.g. "nomic-embed-text@768"). + // Stored in embedding_config and compared at startup to detect a model + // swap against an existing corpus. + ModelID() string +} diff --git a/internal/embedding/openai.go b/internal/embedding/openai.go new file mode 100644 index 0000000..2548e08 --- /dev/null +++ b/internal/embedding/openai.go @@ -0,0 +1,122 @@ +package embedding + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "time" +) + +const defaultHTTPTimeout = 60 * time.Second + +// Client is an OpenAI-compatible /v1/embeddings provider. Construct with New. +type Client struct { + baseURL string + model string + apiKey string + dim int + httpC *http.Client +} + +type Option func(*Client) + +// WithHTTPClient overrides the default timeout-bounded client. +func WithHTTPClient(h *http.Client) Option { return func(c *Client) { c.httpC = h } } + +// New constructs the client. cfg.Dim is authoritative for Dimensions(). +func New(cfg Config, opts ...Option) *Client { + c := &Client{ + baseURL: strings.TrimRight(cfg.BaseURL, "/"), + model: cfg.Model, + apiKey: cfg.APIKey, + dim: cfg.Dim, + httpC: &http.Client{Timeout: defaultHTTPTimeout}, + } + for _, o := range opts { + o(c) + } + return c +} + +func (c *Client) Dimensions() int { return c.dim } +func (c *Client) ModelID() string { return c.model + "@" + strconv.Itoa(c.dim) } + +type embedRequest struct { + Input []string `json:"input"` + Model string `json:"model"` + Dimensions int `json:"dimensions,omitempty"` +} + +type embedResponse struct { + Data []struct { + Embedding []float32 `json:"embedding"` + Index int `json:"index"` + } `json:"data"` +} + +type embedErrEnvelope struct { + Error struct { + Message string `json:"message"` + Type string `json:"type"` + } `json:"error"` +} + +// Embed posts texts to {baseURL}/embeddings and returns one vector per +// input, ordered by the response index. Each vector is validated to have +// length Dimensions(); a mismatch is a configuration error surfaced loudly. +func (c *Client) Embed(ctx context.Context, texts []string) ([][]float32, error) { + if len(texts) == 0 { + return nil, nil + } + body, err := json.Marshal(embedRequest{Input: texts, Model: c.model, Dimensions: c.dim}) + if err != nil { + return nil, fmt.Errorf("marshal embed request: %w", err) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/embeddings", bytes.NewReader(body)) + if err != nil { + return nil, fmt.Errorf("build embed request: %w", err) + } + req.Header.Set("content-type", "application/json") + if c.apiKey != "" { + req.Header.Set("authorization", "Bearer "+c.apiKey) + } + resp, err := c.httpC.Do(req) + if err != nil { + return nil, fmt.Errorf("call embeddings: %w", err) + } + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("read embeddings response: %w", err) + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + var env embedErrEnvelope + if json.Unmarshal(raw, &env) == nil && env.Error.Message != "" { + return nil, fmt.Errorf("embeddings HTTP %d (%s): %s", resp.StatusCode, env.Error.Type, env.Error.Message) + } + return nil, fmt.Errorf("embeddings HTTP %d: %s", resp.StatusCode, string(raw)) + } + var out embedResponse + if err := json.Unmarshal(raw, &out); err != nil { + return nil, fmt.Errorf("decode embeddings response: %w", err) + } + if len(out.Data) != len(texts) { + return nil, fmt.Errorf("embeddings: got %d vectors for %d inputs", len(out.Data), len(texts)) + } + vecs := make([][]float32, len(out.Data)) + for _, d := range out.Data { + if d.Index < 0 || d.Index >= len(vecs) { + return nil, fmt.Errorf("embeddings: out-of-range index %d", d.Index) + } + if len(d.Embedding) != c.dim { + return nil, fmt.Errorf("embeddings: model returned %d dims, configured EMBEDDING_DIM=%d (pick a matching model/tier)", len(d.Embedding), c.dim) + } + vecs[d.Index] = d.Embedding + } + return vecs, nil +} diff --git a/internal/embedding/openai_test.go b/internal/embedding/openai_test.go new file mode 100644 index 0000000..10bd7a7 --- /dev/null +++ b/internal/embedding/openai_test.go @@ -0,0 +1,67 @@ +package embedding + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "testing" +) + +func fakeEmbeddings(t *testing.T, status int, body string) (string, *map[string]any, *http.Header) { + t.Helper() + var captured map[string]any + var hdr http.Header + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hdr = r.Header.Clone() + b, _ := io.ReadAll(r.Body) + _ = json.Unmarshal(b, &captured) + if status != http.StatusOK { + w.WriteHeader(status) + } + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + return srv.URL, &captured, &hdr +} + +func TestClient_Embed_OK(t *testing.T) { + url, captured, hdr := fakeEmbeddings(t, 200, `{"data":[{"embedding":[0.1,0.2,0.3],"index":0},{"embedding":[0.4,0.5,0.6],"index":1}],"model":"m"}`) + c := New(Config{BaseURL: url, Model: "m", Dim: 3, APIKey: "sk-x"}) + vecs, err := c.Embed(context.Background(), []string{"a", "b"}) + if err != nil { + t.Fatalf("Embed: %v", err) + } + if len(vecs) != 2 || len(vecs[0]) != 3 || vecs[1][2] != 0.6 { + t.Fatalf("bad vectors: %v", vecs) + } + if hdr.Get("authorization") != "Bearer sk-x" { + t.Errorf("authorization: %q", hdr.Get("authorization")) + } + if (*captured)["model"] != "m" { + t.Errorf("model not sent: %v", *captured) + } + if (*captured)["dimensions"].(float64) != 3 { + t.Errorf("dimensions not sent: %v", *captured) + } + if c.Dimensions() != 3 || c.ModelID() != "m@3" { + t.Errorf("Dimensions/ModelID: %d %q", c.Dimensions(), c.ModelID()) + } +} + +func TestClient_Embed_DimMismatch(t *testing.T) { + url, _, _ := fakeEmbeddings(t, 200, `{"data":[{"embedding":[0.1,0.2],"index":0}]}`) + c := New(Config{BaseURL: url, Model: "m", Dim: 3}) + if _, err := c.Embed(context.Background(), []string{"a"}); err == nil { + t.Fatal("expected dimension-mismatch error") + } +} + +func TestClient_Embed_HTTPError(t *testing.T) { + url, _, _ := fakeEmbeddings(t, 500, `{"error":{"message":"boom"}}`) + c := New(Config{BaseURL: url, Model: "m", Dim: 3}) + if _, err := c.Embed(context.Background(), []string{"a"}); err == nil { + t.Fatal("expected HTTP error") + } +} diff --git a/internal/llm/openai/client.go b/internal/llm/openai/client.go index c10b6f0..ba3cba5 100644 --- a/internal/llm/openai/client.go +++ b/internal/llm/openai/client.go @@ -29,11 +29,14 @@ import ( "errors" "fmt" "io" + "log/slog" "net/http" + "regexp" "strings" "time" "github.com/levonn-dev/ro-builder/internal/llm" + "github.com/levonn-dev/ro-builder/internal/logging" ) func init() { @@ -180,7 +183,42 @@ func (c *Client) Complete(ctx context.Context, system string, messages []llm.Mes if err := json.Unmarshal(respBytes, &apiResp); err != nil { return llm.Response{}, fmt.Errorf("decode response: %w", err) } - return fromAPIResponse(apiResp) + llmResp, err := fromAPIResponse(apiResp) + if err != nil { + return llm.Response{}, err + } + // When the server returned no structured tool_calls, some reasoning + // backends (Qwen3, DeepSeek-R1 via LM Studio/llama.cpp) still emitted the + // call as / markup inside content or + // reasoning_content. Recover it so the tool loop can proceed; otherwise the + // turn looks empty and the orchestrator fails with no_submission. + if !hasToolUse(llmResp.Content) { + msg := apiResp.Choices[0].Message + scan := derefStr(msg.Content) + "\n" + msg.ReasoningContent + if recovered := recoverToolCalls(scan, apiResp.ID); len(recovered) > 0 { + for _, tc := range recovered { + llmResp.Content = append(llmResp.Content, llm.ContentBlock{ + Type: llm.BlockToolUse, + ToolUseID: tc.ID, + ToolName: tc.Function.Name, + ToolInput: json.RawMessage(tc.Function.Arguments), + }) + } + llmResp.StopReason = llm.StopToolUse // finish_reason was "stop"; the recovered calls make it a tool turn + logging.From(ctx).Warn("recovered tool call(s) the server left unparsed in content/reasoning_content; a local reasoning model likely buried them in its thinking -- disable thinking mode or fix the tool-call parser for reliability", + slog.Int("recovered", len(recovered)), + slog.Int("reasoning_chars", len(msg.ReasoningContent))) + } else if len(llmResp.Content) == 0 { + hint := "" + if strings.TrimSpace(msg.ReasoningContent) != "" { + hint = "; the model put output in reasoning_content, which suggests a local reasoning model whose tool call was not parsed into tool_calls -- disable thinking mode or fix the server's tool-call parser/template" + } + logging.From(ctx).Warn("llm returned an empty turn (no text, no tool calls)"+hint, + slog.String("finish_reason", apiResp.Choices[0].FinishReason), + slog.Int("reasoning_chars", len(msg.ReasoningContent))) + } + } + return llmResp, nil } // --- Wire types --- @@ -203,6 +241,12 @@ type apiMessage struct { ToolCalls []apiToolCall `json:"tool_calls,omitempty"` ToolCallID string `json:"tool_call_id,omitempty"` // role=tool only Name string `json:"name,omitempty"` // tool name on role=tool (optional but some backends want it) + // ReasoningContent is the thinking channel some backends (LM Studio, + // vLLM) expose for reasoning models (Qwen3, DeepSeek-R1). We never send it + // (omitempty keeps it out of requests); on responses it lets us diagnose + // the case where a model buried its tool call in reasoning instead of + // emitting structured tool_calls. See the empty-turn check in Complete. + ReasoningContent string `json:"reasoning_content,omitempty"` } type apiToolCall struct { @@ -396,6 +440,97 @@ func fromAPIResponse(r apiResponse) (llm.Response, error) { return resp, nil } +func hasToolUse(blocks []llm.ContentBlock) bool { + for _, b := range blocks { + if b.Type == llm.BlockToolUse { + return true + } + } + return false +} + +func derefStr(s *string) string { + if s == nil { + return "" + } + return *s +} + +// Tool-call recovery for non-compliant servers. +// +// Some OpenAI-compatible backends (LM Studio, llama.cpp) serving reasoning +// models (Qwen3, DeepSeek-R1) fail to hoist a model's tool call into the +// structured tool_calls array, leaving it as markup in content or +// reasoning_content while tool_calls stays empty. recoverToolCalls salvages +// those so the orchestrator's tool loop proceeds. It runs only on the +// already-broken path (no structured tool_calls), so compliant servers are +// untouched. Two markup dialects are handled: +// +// Qwen XML: VALUE... +// Hermes: {"name":"NAME","arguments":{...}} +var ( + reRecoverFunc = regexp.MustCompile(`(?s)\s]+)\s*>(.*?)`) + reRecoverParam = regexp.MustCompile(`(?s)\s]+)\s*>(.*?)`) + reRecoverHermes = regexp.MustCompile(`(?s)\s*(\{.*?\})\s*`) +) + +func recoverToolCalls(text, idPrefix string) []apiToolCall { + if idPrefix == "" { + idPrefix = "recovered" + } + var calls []apiToolCall + // Qwen XML function/parameter form. + for _, fm := range reRecoverFunc.FindAllStringSubmatch(text, -1) { + args := map[string]json.RawMessage{} + for _, pm := range reRecoverParam.FindAllStringSubmatch(fm[2], -1) { + args[pm[1]] = jsonValueOrString(strings.TrimSpace(pm[2])) + } + argsJSON, err := json.Marshal(args) + if err != nil { + continue + } + calls = append(calls, apiToolCall{ + ID: fmt.Sprintf("%s_rtc_%d", idPrefix, len(calls)), + Type: "function", + Function: apiToolCallFunc{Name: fm[1], Arguments: string(argsJSON)}, + }) + } + if len(calls) > 0 { + return calls + } + // Hermes JSON form. + for _, hm := range reRecoverHermes.FindAllStringSubmatch(text, -1) { + var h struct { + Name string `json:"name"` + Arguments json.RawMessage `json:"arguments"` + } + if json.Unmarshal([]byte(hm[1]), &h) != nil || h.Name == "" { + continue + } + args := string(h.Arguments) + if args == "" { + args = "{}" + } + calls = append(calls, apiToolCall{ + ID: fmt.Sprintf("%s_rtc_%d", idPrefix, len(calls)), + Type: "function", + Function: apiToolCallFunc{Name: h.Name, Arguments: args}, + }) + } + return calls +} + +// jsonValueOrString returns v as raw JSON when it already is valid JSON (an +// object, array, number, bool, or quoted string), else JSON-encodes it as a +// string so a bare parameter value like `roundhouse` becomes "roundhouse". +func jsonValueOrString(v string) json.RawMessage { + if v != "" && json.Valid([]byte(v)) { + return json.RawMessage(v) + } + b, _ := json.Marshal(v) + return json.RawMessage(b) +} + func mapFinishReason(r string) llm.StopReason { switch r { case "tool_calls", "function_call": diff --git a/internal/llm/openai/client_test.go b/internal/llm/openai/client_test.go index c647bb8..4b70ad6 100644 --- a/internal/llm/openai/client_test.go +++ b/internal/llm/openai/client_test.go @@ -251,3 +251,114 @@ func TestClient_Complete_FinishReasonLengthMapsToMaxTokens(t *testing.T) { t.Errorf("stop: got %q want max_tokens", resp.StopReason) } } + +func TestRecoverToolCalls_QwenXMLFormat(t *testing.T) { + // Exact shape observed from Qwen3 via LM Studio: the tool call lands in + // reasoning_content as markup while + // tool_calls stays empty. The build parameter's value is a JSON object. + reasoning := "thinking...\n\n\n\n\n\n{\"class\": \"taekwon_kid\", \"stats\": {\"str\": 30}}\n\n\n" + calls := recoverToolCalls(reasoning, "resp1") + if len(calls) != 1 { + t.Fatalf("want 1 recovered call, got %d", len(calls)) + } + if calls[0].Function.Name != "score_build" { + t.Errorf("name: %q", calls[0].Function.Name) + } + var args map[string]json.RawMessage + if err := json.Unmarshal([]byte(calls[0].Function.Arguments), &args); err != nil { + t.Fatalf("arguments not valid JSON: %v (%s)", err, calls[0].Function.Arguments) + } + if _, ok := args["build"]; !ok { + t.Fatalf("expected a build param, got %s", calls[0].Function.Arguments) + } + // The build value must be preserved as a nested object, not a string. + if !strings.HasPrefix(strings.TrimSpace(string(args["build"])), "{") || + !strings.Contains(string(args["build"]), `"taekwon_kid"`) { + t.Errorf("build value not preserved as object: %s", args["build"]) + } +} + +func TestRecoverToolCalls_MultipleAndTypedParams(t *testing.T) { + xml := "1\n" + + "hi" + got := recoverToolCalls(xml, "r") + if len(got) != 2 { + t.Fatalf("want 2, got %d", len(got)) + } + if got[0].Function.Name != "a" || got[1].Function.Name != "b" { + t.Errorf("names: %q %q", got[0].Function.Name, got[1].Function.Name) + } + // numeric stays numeric; bare word becomes a quoted string + if !strings.Contains(got[0].Function.Arguments, `"x":1`) { + t.Errorf("x arg not numeric: %s", got[0].Function.Arguments) + } + if !strings.Contains(got[1].Function.Arguments, `"y":"hi"`) { + t.Errorf("y arg not string-quoted: %s", got[1].Function.Arguments) + } + if got[0].ID == got[1].ID { + t.Errorf("recovered ids must be unique, both %q", got[0].ID) + } +} + +func TestRecoverToolCalls_HermesJSONForm(t *testing.T) { + hermes := `{"name":"score_build","arguments":{"build":{"class":"knight"}}}` + got := recoverToolCalls(hermes, "r") + if len(got) != 1 || got[0].Function.Name != "score_build" { + t.Fatalf("hermes recovery: %+v", got) + } + if !strings.Contains(got[0].Function.Arguments, `"knight"`) { + t.Errorf("hermes args: %s", got[0].Function.Arguments) + } +} + +func TestRecoverToolCalls_NoMarkersReturnsNil(t *testing.T) { + if got := recoverToolCalls("just reasoning, no tool call markup here", ""); len(got) != 0 { + t.Errorf("expected no recovery, got %d", len(got)) + } +} + +func TestClient_Complete_RecoversBuriedToolCall(t *testing.T) { + // Qwen3-via-LM-Studio failure mode end to end: empty content + empty + // tool_calls, the real call buried in reasoning_content. Complete must + // recover it and report a tool turn, not an empty end_turn. + reasoning := "let me think\n\n\n\n\n1201\n\n\n" + body, err := json.Marshal(map[string]any{ + "id": "cmpl-x", "model": "qwen", + "choices": []any{map[string]any{ + "index": 0, "finish_reason": "stop", + "message": map[string]any{ + "role": "assistant", + "content": "", + "reasoning_content": reasoning, + "tool_calls": []any{}, + }, + }}, + }) + if err != nil { + t.Fatal(err) + } + url, _, _ := fakeOpenAI(t, http.StatusOK, string(body)) + c := NewClient("", WithBaseURL(url)) + resp, err := c.Complete(context.Background(), "", nil, nil) + if err != nil { + t.Fatal(err) + } + if resp.StopReason != llm.StopToolUse { + t.Errorf("stop: got %q want tool_use (recovered)", resp.StopReason) + } + if !hasToolUse(resp.Content) { + t.Fatalf("expected a recovered tool_use block, got %+v", resp.Content) + } + var tb llm.ContentBlock + for _, b := range resp.Content { + if b.Type == llm.BlockToolUse { + tb = b + } + } + if tb.ToolName != "lookup_item" { + t.Errorf("tool name: %q", tb.ToolName) + } + if !strings.Contains(string(tb.ToolInput), `"id_or_name"`) { + t.Errorf("tool input: %s", string(tb.ToolInput)) + } +} diff --git a/internal/llm/tools/get_saved_build.go b/internal/llm/tools/get_saved_build.go new file mode 100644 index 0000000..b4d4495 --- /dev/null +++ b/internal/llm/tools/get_saved_build.go @@ -0,0 +1,62 @@ +package tools + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + "github.com/levonn-dev/ro-builder/internal/buildlibrary" + "github.com/levonn-dev/ro-builder/internal/llm" +) + +const getSavedBuildSchema = `{ + "type": "object", + "properties": { + "id": {"type": "string", "description": "The saved trajectory id to load in full (from get_similar_past_builds results)."} + }, + "required": ["id"] +}` + +type getSavedBuildTool struct{ lib *buildlibrary.Library } + +// NewGetSavedBuild constructs the get_saved_build tool. lib is required. +func NewGetSavedBuild(lib *buildlibrary.Library) Tool { return &getSavedBuildTool{lib: lib} } + +func (t *getSavedBuildTool) Definition() llm.Tool { + return llm.Tool{ + Name: "get_saved_build", + Description: "Load the FULL saved trajectory (stats, skills, gear, leveling targets, scoring) for a given id. " + + "Use after get_similar_past_builds returns a promising summary you want to study or adapt. " + + "A reference point, not a template; design the active build from the current request and diverge when the reasoning supports it.", + InputSchema: json.RawMessage(getSavedBuildSchema), + } +} + +type getSavedBuildInput struct { + ID string `json:"id"` +} + +func (t *getSavedBuildTool) Execute(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) { + var in getSavedBuildInput + if err := json.Unmarshal(raw, &in); err != nil { + return nil, fmt.Errorf("decode get_saved_build input: %w", err) + } + if in.ID == "" { + return nil, errors.New("get_saved_build: id is required") + } + st, err := t.lib.Get(ctx, in.ID) + if errors.Is(err, buildlibrary.ErrNotFound) { + return json.Marshal(map[string]string{"error": "no saved build with id " + in.ID}) + } + if err != nil { + return nil, fmt.Errorf("get saved build: %w", err) + } + // The RAG surface only exposes user-accepted builds. A build that passed + // gates but has not been accepted is treated as absent here, matching the + // retrieval tools that never surfaced its id in the first place. + if st.AcceptedAt == nil { + return json.Marshal(map[string]string{"error": "no saved build with id " + in.ID}) + } + return json.Marshal(st) +} diff --git a/internal/llm/tools/get_saved_build_test.go b/internal/llm/tools/get_saved_build_test.go new file mode 100644 index 0000000..20a8ca7 --- /dev/null +++ b/internal/llm/tools/get_saved_build_test.go @@ -0,0 +1,28 @@ +package tools + +import ( + "encoding/json" + "testing" +) + +func TestGetSavedBuild_Definition(t *testing.T) { + def := NewGetSavedBuild(nil).Definition() + if def.Name != "get_saved_build" { + t.Errorf("Name = %q, want get_saved_build", def.Name) + } + var schema struct { + Required []string `json:"required"` + } + if err := json.Unmarshal(def.InputSchema, &schema); err != nil { + t.Fatalf("InputSchema not valid JSON: %v", err) + } + found := false + for _, r := range schema.Required { + if r == "id" { + found = true + } + } + if !found { + t.Errorf("schema must require 'id'; got required=%v", schema.Required) + } +} diff --git a/internal/llm/tools/get_similar_past_builds.go b/internal/llm/tools/get_similar_past_builds.go index 05bb347..b6c2781 100644 --- a/internal/llm/tools/get_similar_past_builds.go +++ b/internal/llm/tools/get_similar_past_builds.go @@ -21,24 +21,29 @@ const getSimilarPastBuildsSchema = `{ type getSimilarPastBuildsTool struct { lib *buildlibrary.Library + // maxDistance is the Tier B list floor: semantic results beyond this + // cosine distance are dropped so the LLM never sees far-off matches. + // 0 = no floor (return the nearest `limit` regardless of distance). + maxDistance float64 } // NewGetSimilarPastBuilds constructs the get_similar_past_builds tool. // lib is required; a nil library here would mean a deployment without // persistent build storage, which we treat as a programming error -// rather than a graceful "no results." -func NewGetSimilarPastBuilds(lib *buildlibrary.Library) Tool { +// rather than a graceful "no results." maxDistance is the semantic list +// floor (EMBEDDING_SIMILAR_MAX_DISTANCE); ignored in recency mode. +func NewGetSimilarPastBuilds(lib *buildlibrary.Library, maxDistance float64) Tool { if lib == nil { panic("tools.NewGetSimilarPastBuilds: library is required") } - return &getSimilarPastBuildsTool{lib: lib} + return &getSimilarPastBuildsTool{lib: lib, maxDistance: maxDistance} } func (t *getSimilarPastBuildsTool) Definition() llm.Tool { return llm.Tool{ Name: "get_similar_past_builds", Description: "Retrieve summaries of previously generated and quality-gate-validated trajectories matching the given class + server. " + - "Returns lightweight records (id, class, server, playstyle, description, gate counts) sorted by recency; at most `limit` (default 5). " + + "Returns lightweight records (id, class, server, playstyle, description, gate counts) ranked by similarity to the active request when embeddings are available, otherwise sorted by recency; at most `limit` (default 5). " + "USE THESE AS REFERENCE POINTS, NOT TEMPLATES. Past builds are signals about what's worked under similar constraints; the active build should still be designed from scratch given the current request's class definition, gear pool, scenario, and server profile. Diverging from a past build's choices is fine when the reasoning supports it. " + "Calling without args defaults to filtering by the request's active class + server, which is usually what you want.", InputSchema: json.RawMessage(getSimilarPastBuildsSchema), @@ -71,10 +76,29 @@ func (t *getSimilarPastBuildsTool) Execute(ctx context.Context, raw json.RawMess // cross-class results from the same server. } + // RAG retrieval only surfaces user-accepted builds; builds that merely + // passed quality gates are not seedable until the user accepts them. + acceptedOnly := true + + // Prefer semantic ranking when the orchestrator stamped a query vector + // and the library has embeddings; otherwise fall back to recency. + if vec, ok := domain.QueryEmbeddingFromContext(ctx); ok && t.lib.SemanticEnabled() { + sims, err := t.lib.FindSimilar(ctx, vec, buildlibrary.FindParams{Class: in.Class, Server: in.Server, Limit: in.Limit, MaxDistance: t.maxDistance, Accepted: &acceptedOnly}) + if err != nil { + return nil, fmt.Errorf("library find similar: %w", err) + } + out, err := json.Marshal(sims) + if err != nil { + return nil, fmt.Errorf("encode get_similar_past_builds output: %w", err) + } + return out, nil + } + summaries, err := t.lib.Find(ctx, buildlibrary.FindParams{ - Class: in.Class, - Server: in.Server, - Limit: in.Limit, + Class: in.Class, + Server: in.Server, + Limit: in.Limit, + Accepted: &acceptedOnly, }) if err != nil { return nil, fmt.Errorf("library find: %w", err) diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go index b5ca6c7..f540443 100644 --- a/internal/orchestrator/orchestrator.go +++ b/internal/orchestrator/orchestrator.go @@ -52,6 +52,12 @@ import ( // loop if the model gets confused. const defaultMaxIters = 60 +// defaultSeedMaxDistance is the cosine-distance ceiling below which a +// saved build is injected as a warm-start reference. 0.15 is tight enough +// to avoid injecting unrelated builds while still catching near-identical +// requests (same class/playstyle/scenario). +const defaultSeedMaxDistance = 0.15 + // systemPrompt is the briefing the LLM receives once per request. Kept // short and direct; verbose system prompts encourage the model to ramble // in their responses. The "never fabricate numbers" instruction is the @@ -215,19 +221,23 @@ type ScoringClient interface { // for every snapshot); useful in tests that don't need it. Production // wiring sets it via WithScoringClient. type Orchestrator struct { - provider llm.Provider - registry *tools.Registry - maxIters int - profiles map[string]*domain.ServerProfile - scoringClient ScoringClient - catalog *catalog.Catalog + provider llm.Provider + registry *tools.Registry + maxIters int + profiles map[string]*domain.ServerProfile + scoringClient ScoringClient + catalog *catalog.Catalog + embedder QueryEmbedder + seeder BuildSeeder + seedMaxDistance float64 } func New(provider llm.Provider, registry *tools.Registry) *Orchestrator { return &Orchestrator{ - provider: provider, - registry: registry, - maxIters: defaultMaxIters, + provider: provider, + registry: registry, + maxIters: defaultMaxIters, + seedMaxDistance: defaultSeedMaxDistance, } } @@ -267,6 +277,23 @@ func (o *Orchestrator) WithCatalog(cat *catalog.Catalog) *Orchestrator { return o } +// WithEmbedder enables query embedding for proactive seeding and semantic +// retrieval. nil leaves the orchestrator recency-only. +func (o *Orchestrator) WithEmbedder(e QueryEmbedder) *Orchestrator { o.embedder = e; return o } + +// WithSeeder supplies the saved-build similarity source (production: the +// *buildlibrary.Library). Required alongside WithEmbedder for Tier-A seeding. +func (o *Orchestrator) WithSeeder(s BuildSeeder) *Orchestrator { o.seeder = s; return o } + +// WithSeedMaxDistance overrides the proactive-seed cosine-distance ceiling. +// Values <= 0 are ignored; the default ceiling is retained. +func (o *Orchestrator) WithSeedMaxDistance(d float64) *Orchestrator { + if d > 0 { + o.seedMaxDistance = d + } + return o +} + // Generate runs the full tool-use loop for one request. // // Returns (*GenerateResult, nil) on success: end_turn with an accepted @@ -293,6 +320,8 @@ func (o *Orchestrator) Generate(ctx context.Context, req GenerateRequest) (*Gene sess := &Session{} ctx = WithSession(ctx, sess) + ctx, seedBlock := o.maybeSeed(ctx, req) + // Build a per-request submit_trajectory tool: it closes over the // session's Accept callback, the resolved profile, and the request's // gate overrides + playstyle. The shared registry stays untouched; @@ -350,10 +379,11 @@ func (o *Orchestrator) Generate(ctx context.Context, req GenerateRequest) (*Gene baseLevel, jobLevel, _ := o.fetchClassMaxLevelsForPrompt(profile, req.Class) skillBudget := o.fetchSkillPointBudget(req.Class) - messages := []llm.Message{{ - Role: llm.RoleUser, - Content: []llm.ContentBlock{{Type: llm.BlockText, Text: formatUserPrompt(req, profile, classSkills, classBuffs, baseLevel, jobLevel, skillBudget)}}, - }} + userBlocks := []llm.ContentBlock{{Type: llm.BlockText, Text: formatUserPrompt(req, profile, classSkills, classBuffs, baseLevel, jobLevel, skillBudget)}} + if seedBlock != "" { + userBlocks = append(userBlocks, llm.ContentBlock{Type: llm.BlockText, Text: seedBlock}) + } + messages := []llm.Message{{Role: llm.RoleUser, Content: userBlocks}} toolDefs := reg.Definitions() logger.Info("generation started", diff --git a/internal/orchestrator/seed.go b/internal/orchestrator/seed.go new file mode 100644 index 0000000..1cfb135 --- /dev/null +++ b/internal/orchestrator/seed.go @@ -0,0 +1,90 @@ +package orchestrator + +import ( + "context" + "fmt" + "log/slog" + "strings" + + "github.com/levonn-dev/ro-builder/internal/buildlibrary" + "github.com/levonn-dev/ro-builder/internal/domain" + "github.com/levonn-dev/ro-builder/internal/logging" +) + +// QueryEmbedder embeds the request's query text. Satisfied by +// *embedding.Client; a local interface keeps the orchestrator decoupled +// from the embedding package and trivially fakeable. +type QueryEmbedder interface { + Embed(ctx context.Context, texts []string) ([][]float32, error) +} + +// BuildSeeder finds the single closest saved build. Satisfied by +// *buildlibrary.Library. +type BuildSeeder interface { + SemanticEnabled() bool + SimilarTop(ctx context.Context, queryVec []float32, class, server string) (*buildlibrary.SavedTrajectory, float64, bool, error) +} + +// composeQuery builds the query text embedded at generate time: the +// request's intent, mirroring the document side (which also includes the +// answer's final_text). Deterministic. +func composeQuery(req GenerateRequest) string { + // Class intentionally omitted: the seeder hard-filters by class/server, so class carries no extra retrieval signal here. + return strings.TrimSpace(req.Playstyle + "\n" + req.Description) +} + +// maybeSeed embeds the request, stamps the vector on the context (so +// get_similar_past_builds can rank semantically), and returns a warm-start +// block when the closest saved build is within the seed threshold. Returns +// the (possibly augmented) context and the seed text ("" when none). +// Never fails the request: embedder/seeder errors degrade to no seed. +func (o *Orchestrator) maybeSeed(ctx context.Context, req GenerateRequest) (context.Context, string) { + if o.embedder == nil || o.seeder == nil { + return ctx, "" + } + if !o.seeder.SemanticEnabled() { + return ctx, "" + } + logger := logging.From(ctx) + vecs, err := o.embedder.Embed(ctx, []string{composeQuery(req)}) + if err != nil || len(vecs) == 0 { + logger.Warn("seed: query embed failed; skipping semantic retrieval", slog.Any("err", err)) + return ctx, "" + } + qv := vecs[0] + ctx = domain.WithQueryEmbedding(ctx, qv) + + st, dist, ok, err := o.seeder.SimilarTop(ctx, qv, req.Class, req.Server) + if err != nil { + logger.Warn("seed: similar lookup failed", slog.Any("err", err)) + return ctx, "" + } + if !ok || st == nil { + logger.Debug("seed: no embedded candidates for this class/server; proceeding without a seed") + return ctx, "" + } + if dist > o.seedMaxDistance { + logger.Info("seed: closest saved build beyond threshold; not seeding", + slog.String("id", st.ID), slog.Float64("distance", dist), slog.Float64("threshold", o.seedMaxDistance)) + return ctx, "" + } + logger.Info("seed: injecting closest saved build", + slog.String("id", st.ID), slog.Float64("distance", dist)) + return ctx, renderSeed(st) +} + +// renderSeed turns a saved build into a labelled warm-start block. A +// reference point, not a template; the prompt frames it as such. +func renderSeed(st *buildlibrary.SavedTrajectory) string { + var b strings.Builder + fmt.Fprintf(&b, "## Reference: a previously validated build closely matching this request\n") + fmt.Fprintf(&b, "(id %s; use get_saved_build(%q) for its full trajectory.)\n", st.ID, st.ID) + fmt.Fprintf(&b, "Treat this as a reference point, NOT a template: adopt what fits, diverge where the current request differs.\n\n") + if st.Description != "" { + fmt.Fprintf(&b, "Original request: %s\n", st.Description) + } + if st.FinalText != "" { + fmt.Fprintf(&b, "\nReasoning from that build:\n%s\n", st.FinalText) + } + return b.String() +} diff --git a/internal/orchestrator/seed_test.go b/internal/orchestrator/seed_test.go new file mode 100644 index 0000000..978cc0d --- /dev/null +++ b/internal/orchestrator/seed_test.go @@ -0,0 +1,99 @@ +package orchestrator + +import ( + "context" + "strings" + "testing" + + "github.com/levonn-dev/ro-builder/internal/buildlibrary" + "github.com/levonn-dev/ro-builder/internal/domain" +) + +type fakeEmbedder struct{ vec []float32 } + +func (f fakeEmbedder) Embed(_ context.Context, texts []string) ([][]float32, error) { + out := make([][]float32, len(texts)) + for i := range texts { + out[i] = f.vec + } + return out, nil +} + +type countingEmbedder struct { + calls int + vec []float32 +} + +func (c *countingEmbedder) Embed(_ context.Context, texts []string) ([][]float32, error) { + c.calls++ + out := make([][]float32, len(texts)) + for i := range texts { + out[i] = c.vec + } + return out, nil +} + +type fakeSeeder struct { + st *buildlibrary.SavedTrajectory + dist float64 + ok bool + semanticEnabled bool +} + +func (f fakeSeeder) SemanticEnabled() bool { return f.semanticEnabled } +func (f fakeSeeder) SimilarTop(_ context.Context, _ []float32, _, _ string) (*buildlibrary.SavedTrajectory, float64, bool, error) { + return f.st, f.dist, f.ok, nil +} + +func TestMaybeSeed_InjectsWithinThreshold(t *testing.T) { + st := &buildlibrary.SavedTrajectory{ID: "abc", Description: "agi crit", FinalText: "use jur + crit"} + o := New(nil, nil).WithEmbedder(fakeEmbedder{vec: []float32{1}}). + WithSeeder(fakeSeeder{st: st, dist: 0.10, ok: true, semanticEnabled: true}).WithSeedMaxDistance(0.15) + ctx, seed := o.maybeSeed(context.Background(), GenerateRequest{Class: "taekwon_kid", Server: "uaro", Description: "agi crit tk"}) + if seed == "" || !strings.Contains(seed, "abc") { + t.Fatalf("expected seed text referencing the build, got %q", seed) + } + if _, ok := domain.QueryEmbeddingFromContext(ctx); !ok { + t.Fatal("query embedding should be stamped on the context") + } +} + +func TestMaybeSeed_SkipsBeyondThreshold(t *testing.T) { + st := &buildlibrary.SavedTrajectory{ID: "abc"} + o := New(nil, nil).WithEmbedder(fakeEmbedder{vec: []float32{1}}). + WithSeeder(fakeSeeder{st: st, dist: 0.90, ok: true, semanticEnabled: true}).WithSeedMaxDistance(0.15) + ctx, seed := o.maybeSeed(context.Background(), GenerateRequest{}) + if seed != "" { + t.Fatalf("expected no seed beyond threshold, got %q", seed) + } + if _, ok := domain.QueryEmbeddingFromContext(ctx); !ok { + t.Fatal("embed succeeded: vector should be stamped even when the seed block is suppressed") + } +} + +func TestMaybeSeed_NoEmbedderNoop(t *testing.T) { + o := New(nil, nil) + ctx, seed := o.maybeSeed(context.Background(), GenerateRequest{}) + if seed != "" { + t.Fatal("no embedder => no seed") + } + if _, ok := domain.QueryEmbeddingFromContext(ctx); ok { + t.Fatal("no embedder => no stamped vector") + } +} + +func TestMaybeSeed_SkipsWhenSemanticDisabled(t *testing.T) { + emb := &countingEmbedder{vec: []float32{1}} + o := New(nil, nil).WithEmbedder(emb). + WithSeeder(fakeSeeder{semanticEnabled: false}).WithSeedMaxDistance(0.15) + ctx, seed := o.maybeSeed(context.Background(), GenerateRequest{}) + if seed != "" { + t.Fatalf("semantic disabled => no seed, got %q", seed) + } + if _, ok := domain.QueryEmbeddingFromContext(ctx); ok { + t.Fatal("semantic disabled => no stamped vector") + } + if emb.calls != 0 { + t.Fatalf("semantic disabled => embedder must not be called, got %d call(s)", emb.calls) + } +} diff --git a/internal/workers/pool.go b/internal/workers/pool.go index 15ac34a..f5ff490 100644 --- a/internal/workers/pool.go +++ b/internal/workers/pool.go @@ -294,6 +294,7 @@ func (p *Pool) runJob(logger *slog.Logger, g *buildlibrary.Generation, owner str // MarkCompleted separately; the transaction already did it. saveCtx, saveCfn := detachedCtx() defer saveCfn() + saveCtx = logging.WithLogger(saveCtx, jobLog) // carry worker_id/generation_id into the save+embed logs if err := p.cfg.Save(saveCtx, g.ID, owner, req, res); err != nil { ctx, cfn := detachedCtx() defer cfn() diff --git a/scripts/e2e.sh b/scripts/e2e.sh index 308d80f..4cb0ebf 100755 --- a/scripts/e2e.sh +++ b/scripts/e2e.sh @@ -71,7 +71,7 @@ cleanup() { if (( code != 0 )); then echo echo "[e2e] FAILED (exit $code); diagnostics follow:" - for f in score-response.json enqueue-response.json gen-status.json build-response.json sidecar.log api.log; do + for f in score-response.json enqueue-response.json gen-status.json build-response.json sidecar.log api.log api-embedding.log; do if [[ -f "$TMP/$f" ]]; then echo "--- $f (tail) ---" tail -40 "$TMP/$f" @@ -364,4 +364,205 @@ else echo "[e2e] /generate 503 confirmed (score-only mode)" fi +# --- embedding scenario (opt-in; skipped by default) --- +# +# Enable with E2E_EMBEDDING=1 and a reachable EMBEDDING_BASE_URL pointing +# at an OpenAI-compatible /v1 root (e.g. http://localhost:11434/v1 for +# Ollama). Skipped silently when E2E_EMBEDDING is unset so the default +# `task e2e` / CI path is unchanged. +# +# Example invocation: +# +# E2E_EMBEDDING=1 \ +# EMBEDDING_BASE_URL=http://localhost:11434/v1 \ +# EMBEDDING_MODEL=nomic-embed-text \ +# EMBEDDING_DIM=768 \ +# task e2e +# +# What this scenario proves: +# 1. API boots with EMBEDDING_* configured; pgvector extension is created; +# logs "embeddings enabled". +# 2. First /generate saves a trajectory WITH an embedding vector; it is then +# accepted (POST /builds/{id}/accept) so the RAG surface can see it. +# 3. Second /generate (similar description) retrieves the accepted build as +# the nearest neighbor and the API logs "seed: injecting closest saved +# build" -- proves the Tier A seeding pipeline end-to-end. +# +# Degradation scenarios (manual; not wired into default CI): +# +# pgvector-uninstallable: set EMBEDDING_* but point DATABASE_URL at a +# plain Postgres without pgvector and without superuser rights to +# CREATE EXTENSION. The API should boot and serve /score and /generate, +# logging "embedding: pgvector extension is unavailable ... running +# RECENCY-ONLY". Verify: no panic; /score returns 200; /generate returns +# 202 (LLM key required). +# +# Model mismatch: run once with MODEL_A/DIM_A to build a corpus, then +# restart with MODEL_B/DIM_B. Bootstrap detects the mismatch and logs +# "embedding: configured model/dim does not match the embedded corpus; +# running RECENCY-ONLY". Verify: second boot succeeds; retrieval falls +# back to recency; use cmd/backfill-embeddings to re-embed and restore +# semantic mode. +if [[ "${E2E_EMBEDDING:-0}" == "1" ]]; then + if [[ -z "${EMBEDDING_BASE_URL:-}" ]]; then + echo "[e2e] WARNING: E2E_EMBEDDING=1 but EMBEDDING_BASE_URL is unset; skipping embedding scenario" >&2 + else + EMBASE="${EMBEDDING_BASE_URL}" + EMMODEL="${EMBEDDING_MODEL:-nomic-embed-text}" + EMDIM="${EMBEDDING_DIM:-768}" + + echo "[e2e] embedding scenario: checking $EMBASE reachability" + if ! curl -sf -o /dev/null --max-time 5 "${EMBASE}/models" 2>/dev/null; then + echo "[e2e] WARNING: EMBEDDING_BASE_URL $EMBASE not reachable; skipping embedding scenario" >&2 + else + echo "[e2e] embedding scenario: restarting API with embedding enabled" + kill "$API_PID" 2>/dev/null || true + wait "$API_PID" 2>/dev/null || true + + # EMBEDDING_SEED_MAX_DISTANCE raised to 0.5 so the seed assertion + # is reliable across models; the default 0.15 is intentionally + # tight for production but would make this test flaky. + ( + ADDR=":$E2E_API_PORT" \ + SIDECAR_URL="$SIDECAR_URL" \ + DATABASE_URL="$E2E_DATABASE_URL" \ + EMBEDDING_BASE_URL="$EMBASE" \ + EMBEDDING_MODEL="$EMMODEL" \ + EMBEDDING_DIM="$EMDIM" \ + EMBEDDING_SEED_MAX_DISTANCE="0.5" \ + exec "$TMP/api" + ) >"$TMP/api-embedding.log" 2>&1 & + API_PID=$! + + for _ in $(seq 1 120); do + if ! kill -0 "$API_PID" 2>/dev/null; then + echo "[e2e] embedding-API process exited before becoming ready; check api-embedding.log" >&2 + tail -20 "$TMP/api-embedding.log" >&2 + exit 1 + fi + if curl -sf -o /dev/null -X POST "$API_URL/score" \ + -H 'content-type: application/json' -d '{}' 2>/dev/null; then + break + fi + sleep 0.5 + done + if ! curl -sf -o /dev/null -X POST "$API_URL/score" \ + -H 'content-type: application/json' -d '{}' 2>/dev/null; then + echo "[e2e] embedding-API did not become ready within 60s" >&2 + exit 1 + fi + + if grep -q "embeddings enabled" "$TMP/api-embedding.log" 2>/dev/null; then + EMB_MODEL_LOG=$(grep "embeddings enabled" "$TMP/api-embedding.log" | tail -1 || true) + echo "[e2e] embedding scenario: confirmed -- $EMB_MODEL_LOG" + else + echo "[e2e] WARNING: 'embeddings enabled' not found in api-embedding.log; semantic may have degraded to recency-only" + fi + + if [[ -z "${LLM_API_KEY:-}" ]]; then + echo "[e2e] embedding scenario: LLM_API_KEY not set; /generate pair skipped (boot + enabled check only)" + else + echo "[e2e] embedding scenario: run 1/2 /generate" + EMB_BODY_1='{ + "class": "taekwon_kid", + "server": "uaro", + "playstyle": "pvm", + "description": "e2e embedding test: taekwon kid star gladiator kick build AGI PvM leveling" + }' + HTTP_CODE=$(curl -s -o "$TMP/emb-enq-1.json" -w '%{http_code}' \ + --max-time 30 \ + -X POST "$API_URL/generate" \ + -H 'content-type: application/json' \ + -d "$EMB_BODY_1") + if [[ "$HTTP_CODE" != "202" ]]; then + echo "[e2e] embedding run 1: /generate returned HTTP $HTTP_CODE (expected 202)" >&2 + exit 1 + fi + EMB_ID_1="$(jq -r '.id' "$TMP/emb-enq-1.json")" + + EMB_WAIT=900 + EMB_START=$(date +%s) + while :; do + curl -sf -o "$TMP/emb-st-1.json" "$API_URL/generations/$EMB_ID_1" 2>/dev/null || true + EMB_S1="$(jq -r '.status // "unknown"' "$TMP/emb-st-1.json" 2>/dev/null)" + case "$EMB_S1" in + completed) break ;; + failed) + echo "[e2e] embedding run 1 failed: $(jq -r '.error // "(none)"' "$TMP/emb-st-1.json")" >&2 + exit 1 ;; + *) + NOW=$(date +%s) + if (( NOW - EMB_START >= EMB_WAIT )); then + echo "[e2e] embedding run 1 timed out after ${EMB_WAIT}s" >&2 + exit 1 + fi + sleep 10 ;; + esac + done + echo "[e2e] embedding scenario run 1 completed ($EMB_ID_1)" + + # The RAG surface only sees ACCEPTED builds, so accept run 1 + # before run 2 (this also exercises POST /builds/{id}/accept). + ACC_CODE=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 \ + -X POST "$API_URL/builds/$EMB_ID_1/accept") + if [[ "$ACC_CODE" != "200" ]]; then + echo "[e2e] accept of run 1 ($EMB_ID_1) returned HTTP $ACC_CODE (expected 200)" >&2 + exit 1 + fi + echo "[e2e] embedding scenario: accepted run 1 ($EMB_ID_1)" + + echo "[e2e] embedding scenario: run 2/2 /generate (similar description)" + EMB_BODY_2='{ + "class": "taekwon_kid", + "server": "uaro", + "playstyle": "pvm", + "description": "e2e embedding test: taekwon kid star gladiator kick skills AGI-focused PvM farmer" + }' + HTTP_CODE=$(curl -s -o "$TMP/emb-enq-2.json" -w '%{http_code}' \ + --max-time 30 \ + -X POST "$API_URL/generate" \ + -H 'content-type: application/json' \ + -d "$EMB_BODY_2") + if [[ "$HTTP_CODE" != "202" ]]; then + echo "[e2e] embedding run 2: /generate returned HTTP $HTTP_CODE (expected 202)" >&2 + exit 1 + fi + EMB_ID_2="$(jq -r '.id' "$TMP/emb-enq-2.json")" + + EMB_START=$(date +%s) + while :; do + curl -sf -o "$TMP/emb-st-2.json" "$API_URL/generations/$EMB_ID_2" 2>/dev/null || true + EMB_S2="$(jq -r '.status // "unknown"' "$TMP/emb-st-2.json" 2>/dev/null)" + case "$EMB_S2" in + completed) break ;; + failed) + echo "[e2e] embedding run 2 failed: $(jq -r '.error // "(none)"' "$TMP/emb-st-2.json")" >&2 + exit 1 ;; + *) + NOW=$(date +%s) + if (( NOW - EMB_START >= EMB_WAIT )); then + echo "[e2e] embedding run 2 timed out after ${EMB_WAIT}s" >&2 + exit 1 + fi + sleep 10 ;; + esac + done + echo "[e2e] embedding scenario run 2 completed ($EMB_ID_2)" + + # Assert seed injection: run 2 should find run 1 as the nearest + # neighbor (distance threshold raised to 0.5 above). + if grep -q "seed: injecting closest saved build" "$TMP/api-embedding.log" 2>/dev/null; then + echo "[e2e] embedding scenario: seed injection confirmed in API log" + else + echo "[e2e] FAIL: 'seed: injecting closest saved build' not found in api-embedding.log" >&2 + echo " Run 2 did not seed from run 1. Descriptions may be too dissimilar," >&2 + echo " or the embedding server returned unexpected vectors." >&2 + exit 1 + fi + fi + echo "[e2e] embedding scenario complete" + fi + fi +fi + echo "[e2e] all checks passed"