Files
gbrain/test/ai/config-no-env-mutation.test.ts
T
ee9ceb327a feat: v0.27 pluggable embedding providers — Vercel AI SDK (#257)
* feat: AI gateway + 6 provider recipes + silent-drop fix (v0.15.0)

Unified AI layer: src/core/ai/gateway.ts routes every AI call through
Vercel AI SDK. Per-touchpoint provider selection via provider:model
config strings. Six typed recipes (OpenAI, Google, Anthropic, Ollama,
Voyage, LiteLLM-proxy template).

Fixes the silent-drop bug at all three sites (operations.ts:237,
hybrid.ts:81, import-file.ts:112): !process.env.OPENAI_API_KEY →
gateway.isAvailable('embedding'). Non-OpenAI brains now actually
embed. Embedding failures propagate as AIConfigError instead of
quietly writing chunks with no vectors.

Schema templating: getPGLiteSchema(dims, model) substitutes
__EMBEDDING_DIMS__ + __EMBEDDING_MODEL__. Postgres initSchema
runtime-replaces vector(1536) + 'text-embedding-3-large' based on
gateway config. Preserves existing 1536-dim brains via explicit
providerOptions.openai.dimensions passthrough (OpenAI API default
is 3072; without this, existing brains break).

Three-class error hierarchy: AIServiceError (base) + AIConfigError
(user fix) + AITransientError (retry). No process.env mutation —
gateway reads from GatewayContext passed in from engine.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: gbrain providers CLI + init flags + config (v0.15.0)

New command: gbrain providers [list|test|env|explain]. Explain emits
a schema_version:1 JSON matrix (agent-friendly). Auto-detects env
keys + probes localhost:11434 /v1/models (validates JSON shape, not
just port-open). Recommends the best provider with one-line reasoning.

gbrain init flags: --embedding-model provider:model (verbose) or
--model provider (shorthand, picks recipe default). Plus
--embedding-dimensions and --expansion-model. AI config flows into
saved GBrainConfig; engine.connect() configures gateway before
initSchema so vector column gets right dim.

config.ts: adds embedding_model, embedding_dimensions, expansion_model,
provider_base_urls. loadConfig() reads env vars but NEVER mutates
process.env — global-state leakage would break MCP, multi-brain, and
long-running workers.

cli.ts: routes 'providers' subcommand (CLI_ONLY, no engine needed);
connectEngine() calls configureGateway() before engine.connect().

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test: AI gateway + silent-drop + schema templating + no-env-mutation (v0.15.0)

28 new unit tests across 4 files:

- test/ai/gateway.test.ts — 13 tests covering isAvailable() matrix
  for the silent-drop regression surface. Critical case: Gemini
  available when GOOGLE_GENERATIVE_AI_API_KEY set AND OPENAI_API_KEY
  absent. Pre-v0.15 brains silently dropped vectors in this config.
- test/ai/silent-drop-regression.test.ts — 3 source-level grep tests
  enforcing !process.env.OPENAI_API_KEY cannot re-enter the codebase
  at any of the three known sites.
- test/ai/schema-templating.test.ts — 4 tests for dim/model
  substitution in getPGLiteSchema() + PGLITE_SCHEMA_SQL back-compat.
- test/ai/config-no-env-mutation.test.ts — regression guard ensuring
  loadConfig() does not mutate process.env (Codex review C3).

All 28 pass locally. Existing unit suite (1397) + Tier 1 E2E (129)
+ Tier 2 skills E2E (3) all green against real Postgres+pgvector
and real OpenAI/Anthropic/openclaw.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: bump version and changelog (v0.15.0)

Adds AI SDK deps (ai, @ai-sdk/openai, @ai-sdk/google,
@ai-sdk/anthropic, @ai-sdk/openai-compatible, zod, gray-matter,
eventsource-parser).

Note: Version jumped from 0.13.0 to 0.15.0 because upstream master
shipped 0.14.x (doctor DRY detection, Knowledge Runtime) while this
branch was in development. Keeping 0.15.0 as the natural next
release number for the AI providers cathedral.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: silent-drop regression test uses relative paths

CI failure: test hardcoded /Users/garrytan/... absolute paths that obviously
don't exist outside my machine. Resolve paths relative to import.meta.dir
so the test works on any checkout + in GitHub Actions.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: bump version to 0.17.0

Locked to 0.17.0 since other PRs (v0.15.x, v0.16.x) may land first.
Also removes the "v0.15" comment in gateway.ts — the v0.15 label belongs
to whatever ships next on master, not this branch.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: bump version to 0.19.0

Re-locked to 0.19.0 (from 0.17.0) to leave room for other PRs landing first.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: bump version to 0.21.0

Re-locked to 0.21.0 (from 0.19.0) to leave room for other PRs landing first.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Bump version to v0.23.0

* Bump version to v0.27.0

* feat(ai): add chat touchpoint with 6 chat-capable recipes

Foundation for multi-provider Minions. Purely additive — no behavior change
to existing embedding/expansion paths or to subagent.ts.

- types.ts: 'chat' added to TouchpointKind. New ChatTouchpoint shape with
  supports_subagent_loop separate from supports_tools (Codex F-OV-2: some
  chat-capable models are bad at durable tool loops). supports_prompt_cache
  gates Anthropic-specific cacheControl. AIGatewayConfig gains chat_model
  + chat_fallback_chain.
- Recipe.aliases?: Record<string,string> (Codex F-OV-5). Friendly undated
  forms like 'anthropic:claude-sonnet-4-6' resolve to the dated canonical
  at parse time.
- recipes/anthropic.ts, openai.ts, google.ts: each gains a chat touchpoint.
  Only Anthropic claims supports_prompt_cache=true.
- recipes/deepseek.ts, groq.ts, together.ts: NEW openai-compat recipes.
  DeepSeek powers refusal-fallback + cheap-research. Groq is the speed
  tier. Together is the open-weights house (Qwen, Llama-3.3-70B-Turbo).
- gateway.ts: chat() function wraps Vercel AI SDK's generateText. Returns
  a provider-neutral ChatResult with normalized usage (input/output +
  cache_read/cache_creation pulled from providerMetadata.anthropic per
  D7 review decision). cacheSystem: ephemeral marker only when
  recipe.supports_prompt_cache===true. Stop-reason mapping is
  structural-signal-first per D8 (Anthropic stop_reason='refusal',
  OpenAI finish_reason='content_filter') — refusal regex layer ships
  in commit 3.
- config.ts: GBrainConfig adds chat_model + chat_fallback_chain. Env
  overrides GBRAIN_CHAT_MODEL + GBRAIN_CHAT_FALLBACK_CHAIN.
- cli.ts: connectEngine plumbs chat config into configureGateway.
- providers.ts: --touchpoint chat smoke harness. List shows EMBED/EXPAND/
  CHAT columns. Explain matrix surfaces chat options with input/output
  cost. Recipe alias forms accepted in --model.
- init.ts: --chat-model PROVIDER:MODEL flag.
- test/ai/gateway-chat.test.ts: 21 cases covering recipe registry,
  resolver alias resolution, config plumbing, isAvailable('chat')
  semantics for chat-only/embedding-only providers.

49/49 ai/* tests pass. Typecheck clean.

* feat(schema): provider-neutral subagent persistence (migration v34)

D11 cross-model resolution. Codex F-OV-1 noted that subagent_messages and
subagent_tool_executions store Anthropic-shaped tool_use / tool_result
blocks as JSONB. When a worker resumes mid-loop and the live model is
OpenAI/DeepSeek, the persisted shape becomes the runtime contract —
read-side translation is lossy.

Mechanical schema-only migration. No code uses these columns yet; commit 2
(subagent refactor onto gateway.chat()) starts writing schema_version=2
with provider-neutral ChatBlock[] in content_blocks.

- migrate.ts: v34 ALTERs subagent_messages + subagent_tool_executions to
  add schema_version (DEFAULT 1) and provider_id (TEXT). All ALTERs use
  ADD COLUMN IF NOT EXISTS so re-runs are idempotent.
- src/schema.sql + pglite-schema.ts: fresh-install DDL gains the same
  columns. New idx_subagent_messages_provider for cost rollups + per-
  provider replay diagnostics.
- schema-embedded.ts: regenerated via bun run build:schema.
- test/migrate.test.ts: 7 new cases pin the migration shape — column
  names + types, idempotency, fresh-install schema parity, embedded
  schema parity. 75/75 migrate tests pass.

Existing rows backfill to schema_version=1 via DEFAULT, tagging them as
legacy Anthropic shape. Subagent.ts read path (commit 2) checks the
version and dispatches the right block mapper.

* fix(ai): drop Wintermute reference from deepseek recipe comment

CI's check:privacy gate caught a banned name in src/core/ai/recipes/deepseek.ts:5.
CLAUDE.md (per the privacy rule) bans the private OpenClaw fork name in any
checked-in code. Replaces it with neutral language describing the same
capability ("second hop in a refusal-fallback chain and cheap-research
delegation").

bun run verify now passes locally.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 21:21:31 -07:00

28 lines
931 B
TypeScript

/**
* Regression (Codex C3): loadConfig() must NOT mutate process.env.
*
* The plan initially proposed "loadConfig() propagates config fields to env",
* which is global-state leakage. Codex pushed back. loadConfig() now READS env
* vars but never writes them — the gateway receives a config object directly.
*/
import { test, expect } from 'bun:test';
import { loadConfig } from '../../src/core/config.ts';
test('loadConfig does not mutate process.env', () => {
const before = { ...process.env };
try {
loadConfig();
} catch {
// may return null if no config file / no DB URL — that's fine
}
const after = { ...process.env };
// Every key present before must still be present and unchanged.
for (const k of Object.keys(before)) {
expect(after[k]).toBe(before[k]);
}
// No new keys added.
const newKeys = Object.keys(after).filter(k => !(k in before));
expect(newKeys).toEqual([]);
});