mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-27 22:15:33 +00:00
* refactor(mcp): centralize ParamDef→JSON Schema via shared paramDefToSchema Three duplicate inline mappers existed across the MCP surface: - src/mcp/tool-defs.ts (stdio MCP buildToolDefs) - src/commands/serve-http.ts:837 (live HTTP MCP tools/list) - src/core/minions/tools/brain-allowlist.ts:84 (subagent tool registry) Each had subtly different items propagation. The HTTP MCP variant dropped items entirely, leaving extract_facts.entity_hints broken for OAuth- authenticated remote agents even after a buildToolDefs-only patch. The subagent variant propagated one level of items but used the same shallow shape so nested arrays would silently drop. Extract a single recursive paramDefToSchema helper exported from src/mcp/tool-defs.ts and have all three mappers consume it. Closes the bug class at the architecture level instead of patching one site at a time. The helper copies type, description, enum, default, and recursively rebuilds items so array-of-arrays preserves inner shape. Key ordering (type, description, enum, default, items) matches the pre-v0.34 inline mappers so JSON.stringify output stays byte-stable for every existing operation that does not use nested arrays. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(schema): add items to extract_facts.entity_hints and handle-to-tweet candidates Two array fields shipped without the items property required by JSON Schema. Strict-mode validators (Gemini Pro structured outputs, OpenAI strict tool definitions) reject the entire schema when any type:'array' lacks items. Downstream agents on those providers couldn't use extract_facts or the x_handle_to_tweet resolver. extract_facts.entity_hints — declared items: { type: 'string' } matching the handler at src/core/operations.ts:2733 which already coerces the runtime value to string[]. handle_to_tweet outputSchema.candidates — full XTweetCandidate spec including required + additionalProperties: false. The XTweetCandidate TypeScript interface declares all five fields as required; without required in the JSON Schema, a validator would accept {} as a valid candidate. additionalProperties: false closes the OpenAI strict-mode contract. 19 community PRs (#1028 #999 #980 #979 #910 #904 #847 #832 #863 #862 #812 for entity_hints; #910 caught candidates) converged on these locations. This wave cherry-picks the deepest variant (#910 surfaced both bugs) and centralizes via the paramDefToSchema helper from the preceding commit so the live HTTP MCP tools/list path is also fixed. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-Authored-By: DmitryBMsk (PR #910) * fix(git-remote): move --no-recurse-submodules after the subcommand verb Git CLI accepts two flag positions: git [global -c flags] <subcommand> [subcommand flags] [args] Global -c config flags belong before the verb. Subcommand-specific flags (like --no-recurse-submodules) belong after. Pre-v0.34 GIT_SSRF_FLAGS spliced both kinds before the verb, so cloneRepo invoked: git -c http.followRedirects=false ... --no-recurse-submodules clone URL DIR Real git rejects this with exit 129 ("unknown option: --no-recurse-submodules") because --no-recurse-submodules is a clone subcommand flag, not a global config flag. Every remote-source clone broke in production from v0.28 onward. The fake-git harness in test/git-remote.test.ts exits 0 regardless of argv shape, which is why CI never caught it. Split GIT_SSRF_FLAGS (3 -c config flags, spread BEFORE the verb) from GIT_SSRF_SUBCOMMAND_FLAGS (--no-recurse-submodules, spread AFTER the verb). cloneRepo and pullRepo both spread the new constant after their respective verbs. The constant names signal the position rule so future additions land in the right place. 7 community PRs converged on this location (#1023 #1020 #985 #963 #846 #842 — #800 doesn't exist). This wave cherry-picks the semantic- constant approach from #846's GIT_SSRF_SUBCOMMAND_FLAGS name (the clearest signal of the position rule). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(mcp+git+resolvers): structural array-items + subcommand-position guards Three new tests / test groups close the bug classes the wave fixes: test/mcp-tool-defs.test.ts — recursive structural guard walks every operation's inputSchema and fails with a property path if any type:'array' lacks items.type. Explicit fixture assertions for extract_facts.entity_hints.items.type and a synthetic nested-array ParamDef pinning items.items.type recursion. Without the explicit fixtures the legacyInlineMap byte-equality test is mirror-theater — mirroring both sides of the equality preserves the blind spot. test/git-remote.test.ts — split snapshot test into GIT_SSRF_FLAGS (3 global -c entries) and GIT_SSRF_SUBCOMMAND_FLAGS (--no-recurse-submodules). cloneRepo + pullRepo argv tests now assert the subcommand flag appears AFTER the verb index. Pre-v0.34 the pinned argv slice prefix included --no-recurse-submodules, which baked the bug into the test suite (codex catch). test/resolvers.test.ts — recursive walk over both inputSchema AND outputSchema for builtin resolvers (xHandleToTweetResolver, urlReachableResolver). Explicit imports rather than getDefaultRegistry(), which starts empty until commands/resolvers.ts runs — codex catch on a hollow-walk failure mode. Dedicated case pins candidates items shape including required + additionalProperties. Reference legacyInlineMap in mcp-tool-defs.test.ts mirrors the new recursive paramDefToSchema helper. No current op uses nested arrays so the byte-equality test stays green for every existing operation. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(e2e): raise rerank timeouts for ZE live cold-start The first rerank call of a CI run hits ZeroEntropy's cold-start latency (observed ~5-6s on Tier 2 LLM Skills runners; subsequent calls < 500ms). Two timeouts fired simultaneously at ~5s: 1. bun:test's default 5000ms per-test timeout caused (fail). 2. gateway.rerank's DEFAULT_RERANK_TIMEOUT_MS = 5000 fired right after, reported as "Unhandled error between tests". The next rerank test (top_n=2) ran in 409ms because the API was already warm. Cold-start is the only issue. Pass explicit timeoutMs to each rerank() call and a longer per-test timeout (30s) on both ZE rerank tests. Production DEFAULT_RERANK_TIMEOUT_MS stays at 5s for the search hot path — these E2E tests bypass it locally without changing the default that protects user latency. Unrelated to the fix-wave in this PR (mcp-tool-defs + git-remote + resolver guards). Lands here to keep Tier 2 LLM Skills green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: bump version and changelog (v0.35.2.0) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: sync for v0.35.2.0 Update CLAUDE.md Key files annotations for the v0.35.2.0 fix wave: - src/mcp/tool-defs.ts: document new exported recursive paramDefToSchema helper and the three-consumer centralization (stdio MCP, HTTP MCP tools/list, subagent registry). - src/core/minions/tools/brain-allowlist.ts: paramsToInputSchema now consumes the shared helper. - src/commands/serve-http.ts: tools/list handler now consumes the shared helper (closes the HTTP MCP items-dropped bug class). - src/core/git-remote.ts: new entry. Documents the GIT_SSRF_FLAGS (global config, pre-verb) vs GIT_SSRF_SUBCOMMAND_FLAGS (subcommand-scoped, post-verb) split, the 7-month silent regression, and the position-anchored regression guard in test/git-remote.test.ts. Regenerated llms-full.txt to match. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * chore: rebump version to v0.35.3.0 Queue moved while this PR was open — v0.35.2.0 was claimed by master's v0.35.1.0 sibling work. Advancing one slot. No code changes; only: - VERSION + package.json: 0.35.2.0 → 0.35.3.0 - CHANGELOG.md: rewritten header + inline references - CLAUDE.md: rewritten 4 key-file annotations - llms-full.txt + llms.txt: regenerated to mirror CLAUDE.md Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
181 lines
6.3 KiB
TypeScript
181 lines
6.3 KiB
TypeScript
/**
|
|
* v0.35.0.0 — ZeroEntropy live E2E tests.
|
|
*
|
|
* Real HTTP round-trip against `api.zeroentropy.dev`. Gated on
|
|
* `ZEROENTROPY_API_KEY` — when absent, every test skips gracefully so
|
|
* `bun run test:e2e` stays green on contributor machines that don't have
|
|
* a ZE account.
|
|
*
|
|
* Pins (only meaningful when the env var is set):
|
|
* - POST /v1/models/embed returns float embeddings that round-trip
|
|
* through the AI-SDK adapter (after zeroEntropyCompatFetch's response
|
|
* rewrite).
|
|
* - dimensions parameter is honored: 2560 default → vector of length
|
|
* 2560; 1280 → 1280; etc.
|
|
* - asymmetric input_type plumbing reaches ZE: embedQuery() and embed()
|
|
* both succeed and return same-shape vectors (we can't easily inspect
|
|
* whether ZE actually produced asymmetric vectors without a reference
|
|
* corpus, but the request must succeed without HTTP 400).
|
|
* - POST /v1/models/rerank returns indices + relevance_scores that
|
|
* round-trip through gateway.rerank() into RerankResult[].
|
|
*
|
|
* Cost note: each test fires 1-2 HTTP requests. At $0.025/1M tokens and
|
|
* ~100 tokens per test, the full file costs well under a cent. Still
|
|
* gated by env so contributor PR CI doesn't spend.
|
|
*/
|
|
|
|
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
|
|
import {
|
|
configureGateway,
|
|
resetGateway,
|
|
embed,
|
|
embedQuery,
|
|
rerank,
|
|
} from '../../src/core/ai/gateway.ts';
|
|
|
|
const API_KEY = process.env.ZEROENTROPY_API_KEY;
|
|
|
|
// Skip the entire file when env is absent. `describe.skipIf` exists in
|
|
// modern bun:test; fall back to in-test guards for older runners.
|
|
const skipAll = !API_KEY;
|
|
|
|
beforeAll(() => {
|
|
if (skipAll) return;
|
|
configureGateway({
|
|
embedding_model: 'zeroentropyai:zembed-1',
|
|
embedding_dimensions: 2560,
|
|
reranker_model: 'zeroentropyai:zerank-2',
|
|
env: { ZEROENTROPY_API_KEY: API_KEY! },
|
|
});
|
|
});
|
|
|
|
afterAll(() => {
|
|
if (!skipAll) resetGateway();
|
|
});
|
|
|
|
describe('ZE live — embed round-trip', () => {
|
|
test('embed(["text"]) returns Float32Array[2560]', async () => {
|
|
if (skipAll) {
|
|
console.warn('[skip] ZEROENTROPY_API_KEY not set');
|
|
return;
|
|
}
|
|
const [v] = await embed(['hello world']);
|
|
expect(v).toBeInstanceOf(Float32Array);
|
|
expect(v.length).toBe(2560);
|
|
// Sanity: at least one non-zero element (otherwise the response
|
|
// rewrite probably dropped the payload).
|
|
const anyNonZero = Array.from(v).some(x => x !== 0);
|
|
expect(anyNonZero).toBe(true);
|
|
});
|
|
|
|
test('embedQuery("text") returns Float32Array[2560] (query side)', async () => {
|
|
if (skipAll) {
|
|
console.warn('[skip] ZEROENTROPY_API_KEY not set');
|
|
return;
|
|
}
|
|
const v = await embedQuery('what is foo');
|
|
expect(v).toBeInstanceOf(Float32Array);
|
|
expect(v.length).toBe(2560);
|
|
const anyNonZero = Array.from(v).some(x => x !== 0);
|
|
expect(anyNonZero).toBe(true);
|
|
});
|
|
|
|
test('embed batch of 3 returns 3 vectors in order', async () => {
|
|
if (skipAll) {
|
|
console.warn('[skip] ZEROENTROPY_API_KEY not set');
|
|
return;
|
|
}
|
|
const out = await embed(['one', 'two', 'three']);
|
|
expect(out.length).toBe(3);
|
|
for (const v of out) {
|
|
expect(v).toBeInstanceOf(Float32Array);
|
|
expect(v.length).toBe(2560);
|
|
}
|
|
// Different inputs → different vectors (sanity check; would fail
|
|
// hard if the response-rewriter accidentally returned the same
|
|
// vector for every input).
|
|
expect(out[0]).not.toEqual(out[1]);
|
|
expect(out[1]).not.toEqual(out[2]);
|
|
});
|
|
});
|
|
|
|
// ZE rerank API has multi-second cold-start latency on the first request
|
|
// of a CI run (observed ~5-6s on Tier 2 runners; subsequent calls < 500ms).
|
|
// The production DEFAULT_RERANK_TIMEOUT_MS in gateway.ts stays at 5s for the
|
|
// search hot path; these E2E tests pass an explicit input.timeoutMs and a
|
|
// longer bun:test per-test timeout so cold-start doesn't flake CI.
|
|
const ZE_RERANK_TIMEOUT_MS = 25_000;
|
|
const ZE_TEST_TIMEOUT_MS = 30_000;
|
|
|
|
describe('ZE live — rerank round-trip', () => {
|
|
test('rerank({query, documents}) returns sorted RerankResult[]', async () => {
|
|
if (skipAll) {
|
|
console.warn('[skip] ZEROENTROPY_API_KEY not set');
|
|
return;
|
|
}
|
|
const out = await rerank({
|
|
query: 'how does photosynthesis work',
|
|
documents: [
|
|
'Photosynthesis is the process by which plants convert sunlight to energy.',
|
|
'My cat likes to eat tuna fish.',
|
|
'Chlorophyll absorbs red and blue light during photosynthesis.',
|
|
],
|
|
timeoutMs: ZE_RERANK_TIMEOUT_MS,
|
|
});
|
|
expect(out.length).toBe(3);
|
|
for (const r of out) {
|
|
expect(typeof r.index).toBe('number');
|
|
expect(typeof r.relevanceScore).toBe('number');
|
|
// ZE relevance scores are in [0, 1]. Pin the range so a future
|
|
// contract change is loud.
|
|
expect(r.relevanceScore).toBeGreaterThanOrEqual(0);
|
|
expect(r.relevanceScore).toBeLessThanOrEqual(1);
|
|
}
|
|
// Photosynthesis-relevant docs should score higher than the cat doc.
|
|
// We don't pin a specific order (zerank-2 may re-rank the two
|
|
// photosynthesis docs in either order depending on phrasing), but
|
|
// the cat doc must NOT be at the top.
|
|
const topIndex = out[0]!.index;
|
|
expect(topIndex).not.toBe(1); // index 1 is the cat doc
|
|
}, ZE_TEST_TIMEOUT_MS);
|
|
|
|
test('rerank with top_n=2 returns at most 2 results', async () => {
|
|
if (skipAll) {
|
|
console.warn('[skip] ZEROENTROPY_API_KEY not set');
|
|
return;
|
|
}
|
|
const out = await rerank({
|
|
query: 'photosynthesis',
|
|
documents: ['photosynthesis a', 'cats b', 'photosynthesis c'],
|
|
topN: 2,
|
|
timeoutMs: ZE_RERANK_TIMEOUT_MS,
|
|
});
|
|
expect(out.length).toBeLessThanOrEqual(2);
|
|
}, ZE_TEST_TIMEOUT_MS);
|
|
});
|
|
|
|
describe('ZE live — flexible dims', () => {
|
|
test('1280-dim embedding returns Float32Array[1280]', async () => {
|
|
if (skipAll) {
|
|
console.warn('[skip] ZEROENTROPY_API_KEY not set');
|
|
return;
|
|
}
|
|
resetGateway();
|
|
configureGateway({
|
|
embedding_model: 'zeroentropyai:zembed-1',
|
|
embedding_dimensions: 1280,
|
|
env: { ZEROENTROPY_API_KEY: API_KEY! },
|
|
});
|
|
const [v] = await embed(['1280 dim test']);
|
|
expect(v.length).toBe(1280);
|
|
// Restore 2560 for subsequent tests.
|
|
resetGateway();
|
|
configureGateway({
|
|
embedding_model: 'zeroentropyai:zembed-1',
|
|
embedding_dimensions: 2560,
|
|
reranker_model: 'zeroentropyai:zerank-2',
|
|
env: { ZEROENTROPY_API_KEY: API_KEY! },
|
|
});
|
|
});
|
|
});
|