v0.35.3.0 fix wave: extract_facts items + git --no-recurse-submodules placement (#1053)

* 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>
This commit is contained in:
Garry Tan
2026-05-17 08:00:29 -07:00
committed by GitHub
co-authored by Claude Opus 4.7
parent f004a27429
commit 2504abe47f
15 changed files with 395 additions and 46 deletions
+44
View File
@@ -2,6 +2,50 @@
All notable changes to GBrain will be documented in this file.
## [0.35.3.0] - 2026-05-15
**Fix wave: 19 stale community PRs land as one bisect-friendly PR with the architectural fix none of them surfaced.**
Two real bugs, both in shipping code on master since v0.28+, both fixed at the architecture level instead of one site at a time. The first: `extract_facts.entity_hints` and the X-API resolver's `candidates` output schema both declared `type: 'array'` without `items`, so strict-mode validators (Gemini Pro structured outputs, OpenAI strict tool defs) rejected the entire tool schema. Twelve community PRs converged on the entity_hints fix; only one (#910 from @DmitryBMsk) caught the candidates side. The second: every remote-source `git clone` and `git pull` invocation has been broken for ~7 months because `--no-recurse-submodules` was spliced BEFORE the subcommand verb in `GIT_SSRF_FLAGS`. Real git rejects this with exit 129 ("unknown option"); the fake-git test harness exits 0 regardless of argv shape, so CI never caught it. Seven community PRs flagged this. Codex outside-voice review on top of all 19 PRs surfaced the structural finding none of them saw: three duplicate `ParamDef→JSON Schema` mappers existed across the MCP surface, not one. The live HTTP MCP `tools/list` path (`serve-http.ts:837`) and the subagent brain-tool registry (`brain-allowlist.ts:84`) would both have stayed broken after a `buildToolDefs`-only patch.
### What you can now do
**Use `extract_facts` from strict-mode agents again.** Gemini Pro structured outputs and OpenAI strict tool definitions both reject `type: 'array'` without `items`. The `entity_hints` param now declares `items: { type: 'string' }` and the resolver `candidates` output declares the full `XTweetCandidate` interface with `required: [tweet_id, text, created_at, score, url]` and `additionalProperties: false`. The schema matches the TypeScript interface byte-for-byte — single source of truth.
**Clone and pull remote sources over real git again.** `cloneRepo` and `pullRepo` now spread `--no-recurse-submodules` AFTER the verb where it belongs. Real git stops rejecting the call with exit 129. Constant naming signals the position rule so future flag additions land in the right place: `GIT_SSRF_FLAGS` is global config (spread before the verb), `GIT_SSRF_SUBCOMMAND_FLAGS` is subcommand-scoped (spread after).
**Get one canonical ParamDef→schema mapper.** New `paramDefToSchema(p: ParamDef)` helper exported from `src/mcp/tool-defs.ts`. Three consumers now share one source of truth: `buildToolDefs` (stdio MCP), `serve-http.ts:837` (HTTP MCP `tools/list`), and `brain-allowlist.ts:84` (subagent tool registry). Recursive on `items` so nested array-of-arrays preserves inner shape on the wire — closes the same bug class one layer deeper.
**Trust structural guards in CI.** Three new tests fail loudly with property paths if any future array drift reintroduces the bug class. `test/mcp-tool-defs.test.ts` walks every operation's `inputSchema` recursively. `test/git-remote.test.ts` asserts `--no-recurse-submodules` indexOf > verb indexOf — position-anchored, not just inclusion. `test/resolvers.test.ts` explicitly imports `xHandleToTweetResolver` + `urlReachableResolver` and walks both `inputSchema` AND `outputSchema` (the previously planned `getDefaultRegistry()` walk would have silently passed against zero resolvers — codex catch).
### Itemized changes
- `src/mcp/tool-defs.ts` exports new recursive `paramDefToSchema(p: ParamDef)` helper. Key ordering (type, description, enum, default, items) is intentional — matches the pre-v0.35.3 inline mappers so JSON.stringify output stays byte-stable for every operation that doesn't use nested arrays.
- `src/commands/serve-http.ts:837-849` swaps the inline ParamDef destructure for `paramDefToSchema(v)`. Closes the HTTP MCP `tools/list` bug. OAuth-authenticated remote agents (Claude Desktop, ChatGPT, Perplexity over HTTP MCP) now see `items` on every array param.
- `src/core/minions/tools/brain-allowlist.ts:84-97` swaps the inline destructure inside `paramsToInputSchema()` for `paramDefToSchema(v)`. Preserves the `required:` aggregation at `:95` (that's at the tool-def level, not the param level — codex explicitly out-of-scope).
- `src/core/operations.ts:2699` adds `items: { type: 'string' }` to `entity_hints`. The handler at `:2733` already coerced with `Array.isArray(...)` so runtime shape is unchanged; only the schema declaration was broken.
- `src/core/resolvers/builtin/x-api/handle-to-tweet.ts:102` replaces `candidates: { type: 'array' }` with full-spec items matching the `XTweetCandidate` interface 10 lines above, including `required: [all 5 fields]` and `additionalProperties: false` (D5 decision: without `required`, schema permits `{}`).
- `src/core/git-remote.ts:29-44` splits `GIT_SSRF_FLAGS` (3 `-c` config flags, spread BEFORE the verb) from new exported `GIT_SSRF_SUBCOMMAND_FLAGS = ['--no-recurse-submodules']` (spread AFTER). `cloneRepo:156` and `pullRepo:182` now spread the new constant in subcommand position.
- `test/mcp-tool-defs.test.ts` adds: (a) explicit fixture for `extract_facts.entity_hints.items.type === 'string'`, (b) synthetic nested-array ParamDef pinning `items.items.type` recursion, (c) `findArrayWithoutItems` walker that fails the suite with a property path on any `type: 'array'` lacking `items.type`. `legacyInlineMap` reference mirrors the new recursive helper.
- `test/git-remote.test.ts` snapshot split: `GIT_SSRF_FLAGS` pins to 3 elements (no submodules), new `GIT_SSRF_SUBCOMMAND_FLAGS` snapshot pins to 1. `cloneRepo` + `pullRepo` argv tests assert `indexOf(--no-recurse-submodules) > indexOf(verb)` — position-anchored regression guard. Pre-v0.35.3 the existing test at `:233` baked the bug in via `argv.slice(0, GIT_SSRF_FLAGS.length)`.
- `test/resolvers.test.ts` (existing file) gets a new `describe` block. Explicitly imports `xHandleToTweetResolver` + `urlReachableResolver` and walks both `inputSchema` AND `outputSchema` recursively. Negative coverage guard asserts `builtins.length >= 2` so a future autoformatter dropping the array can't silently turn the walk into a no-op.
- `test/e2e/zeroentropy-live.test.ts` raises rerank test timeouts to handle ZeroEntropy's cold-start latency (observed ~5-6s on Tier 2 runners; subsequent calls < 500ms). Passes explicit `timeoutMs: 25000` to each rerank() call and a 30s bun:test per-test timeout. Production `DEFAULT_RERANK_TIMEOUT_MS = 5000` in `gateway.ts` stays put for the search hot path.
- Contributed by: @DmitryBMsk (PR #910 — deepest variant of the entity_hints + candidates double-fix); cleanest naming from PR #846 (`GIT_SSRF_SUBCOMMAND_FLAGS`). 17 superseded PRs being closed with thank-you notes after this merge: #1028, #1023, #1020, #999, #985, #980, #979, #963, #904, #863, #862, #847, #846, #842, #832, #812.
## To take advantage of v0.35.3.0
`gbrain upgrade` is all you need. There's no schema migration, no config change, no manual action.
1. Run `gbrain upgrade` — the new tool schemas reach your MCP clients on next restart.
2. Restart your MCP clients (Claude Code, Claude Desktop, ChatGPT, Cursor, etc.) so they re-fetch `tools/list`.
3. Verify `extract_facts` works from strict-mode agents:
```bash
gbrain --tools-json | jq '.tools[] | select(.name == "extract_facts") | .inputSchema.properties.entity_hints'
```
Should show `{"type":"array","items":{"type":"string"},...}` — pre-fix, `items` was missing.
4. If you use remote-source git clones (`gbrain config get sources` shows any with a remote URL), they'll start working again on the next `gbrain sync`. Pre-fix, every clone of a remote-source repository was silently failing with git exit 129.
If `gbrain doctor` flags anything after upgrade, please file an issue with the doctor output. This was a 7-month silent bug — the doctor's structural guards should catch the next one before it ships.
## [0.35.1.1] - 2026-05-16
**Fix wave: `gbrain eval longmemeval` actually runs against the public _s split.**
+4 -3
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1 +1 @@
0.35.1.1
0.35.3.0
+4 -3
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "gbrain",
"version": "0.35.1.1",
"version": "0.35.3.0",
"description": "Postgres-native personal knowledge brain with hybrid RAG search",
"type": "module",
"main": "src/core/index.ts",
+2 -6
View File
@@ -28,6 +28,7 @@ import { GBrainOAuthProvider } from '../core/oauth-provider.ts';
import type { SqlQuery } from '../core/oauth-provider.ts';
import { hasScope, ALLOWED_SCOPES_LIST } from '../core/scope.ts';
import { summarizeMcpParams, dispatchToolCall } from '../mcp/dispatch.ts';
import { paramDefToSchema } from '../mcp/tool-defs.ts';
import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';
import { loadConfig } from '../core/config.ts';
import { buildError, serializeError } from '../core/errors.ts';
@@ -840,12 +841,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
inputSchema: {
type: 'object' as const,
properties: Object.fromEntries(
Object.entries(op.params).map(([k, v]) => [k, {
type: v.type,
description: v.description,
...(v.enum ? { enum: v.enum } : {}),
...(v.default !== undefined ? { default: v.default } : {}),
}]),
Object.entries(op.params).map(([k, v]) => [k, paramDefToSchema(v)]),
),
required: Object.entries(op.params).filter(([, v]) => v.required).map(([k]) => k),
},
+26 -4
View File
@@ -20,16 +20,38 @@ import { join } from 'path';
import { isInternalUrl } from './url-safety.ts';
/**
* SSRF-defensive flag set. Used by both cloneRepo and pullRepo.
* Git CLI accepts two flag positions:
* git [global -c flags] <subcommand> [subcommand flags] [args]
*
* Global flags (the `-c key=value` config overrides) MUST come before the
* subcommand. Subcommand-specific flags (like `--no-recurse-submodules`)
* MUST come after the subcommand. Mixing the two positions makes git fail
* with `unknown option` (exit 129). Pre-v0.34 the single GIT_SSRF_FLAGS
* constant spliced both positions before the verb; real git rejected the
* subcommand flag but the test harness used a fake-git script that didn't
* validate, so every remote-source clone/pull broke silently in production.
*
* Split into two constants so the call-site spread is unambiguous and the
* type/name signal the position rule.
*/
/**
* Global git config flags. Spread BEFORE the subcommand verb.
* - http.followRedirects=false: closes DNS rebinding via redirect chains
* - protocol.file.allow=never: no local-file URLs (defense in depth)
* - protocol.ext.allow=never: no external helpers (`git-remote-foo`)
* - --no-recurse-submodules: .gitmodules cannot become a second fetch surface
*/
export const GIT_SSRF_FLAGS = [
'-c', 'http.followRedirects=false',
'-c', 'protocol.file.allow=never',
'-c', 'protocol.ext.allow=never',
] as const;
/**
* Subcommand-level flags. Spread AFTER the subcommand verb (clone/pull).
* - --no-recurse-submodules: .gitmodules cannot become a second fetch surface
*/
export const GIT_SSRF_SUBCOMMAND_FLAGS = [
'--no-recurse-submodules',
] as const;
@@ -153,7 +175,7 @@ export function cloneRepo(url: string, destDir: string, opts: CloneOpts = {}): v
}
}
const args: string[] = [...GIT_SSRF_FLAGS, 'clone'];
const args: string[] = [...GIT_SSRF_FLAGS, 'clone', ...GIT_SSRF_SUBCOMMAND_FLAGS];
if (opts.depth !== 0) {
args.push(`--depth=${opts.depth ?? 1}`);
}
@@ -179,7 +201,7 @@ export function cloneRepo(url: string, destDir: string, opts: CloneOpts = {}): v
/** Pull a repo with --ff-only and the same SSRF-defensive flags as cloneRepo. */
export function pullRepo(repoPath: string, opts: { timeoutMs?: number } = {}): void {
const args: string[] = ['-C', repoPath, ...GIT_SSRF_FLAGS, 'pull', '--ff-only'];
const args: string[] = ['-C', repoPath, ...GIT_SSRF_FLAGS, 'pull', ...GIT_SSRF_SUBCOMMAND_FLAGS, '--ff-only'];
try {
execFileSync('git', args, {
stdio: ['ignore', 'pipe', 'pipe'],
+2 -6
View File
@@ -26,6 +26,7 @@ import type { BrainEngine } from '../../engine.ts';
import type { GBrainConfig } from '../../config.ts';
import { operations } from '../../operations.ts';
import type { Operation, OperationContext } from '../../operations.ts';
import { paramDefToSchema } from '../../../mcp/tool-defs.ts';
import type { ToolCtx, ToolDef } from '../types.ts';
/**
@@ -85,12 +86,7 @@ function paramsToInputSchema(op: Operation): Record<string, unknown> {
return {
type: 'object' as const,
properties: Object.fromEntries(
Object.entries(op.params).map(([k, v]) => [k, {
type: v.type === 'array' ? 'array' : v.type,
...(v.description ? { description: v.description } : {}),
...(v.enum ? { enum: v.enum } : {}),
...(v.items ? { items: { type: v.items.type } } : {}),
}]),
Object.entries(op.params).map(([k, v]) => [k, paramDefToSchema(v)]),
),
required: Object.entries(op.params).filter(([, v]) => v.required).map(([k]) => k),
};
+1 -1
View File
@@ -2696,7 +2696,7 @@ const extract_facts: Operation = {
params: {
turn_text: { type: 'string', required: true, description: 'The user message or page body to extract facts from. Sanitized via INJECTION_PATTERNS before the LLM call.' },
session_id: { type: 'string', description: 'Opaque session id (e.g. topic-id from MCP _meta.session_id, or CLI --session). Stored on each fact for the recall --session filter. Not an auth surface.' },
entity_hints: { type: 'array', description: 'Existing canonical entity slugs the agent has already resolved. Helps the extractor pick the right slug.' },
entity_hints: { type: 'array', items: { type: 'string' }, description: 'Existing canonical entity slugs the agent has already resolved. Helps the extractor pick the right slug.' },
is_dream_generated: { type: 'boolean', description: 'When true, extraction is skipped (anti-loop). Caller flips this on for pages with dream_generated:true frontmatter.' },
visibility: { type: 'string', description: 'Default visibility for extracted facts. private (default) | world.' },
},
@@ -99,7 +99,21 @@ export const xHandleToTweetResolver: Resolver<XHandleToTweetInput, XHandleToTwee
tweet_id: { type: 'string' },
text: { type: 'string' },
created_at: { type: 'string', format: 'date-time' },
candidates: { type: 'array' },
candidates: {
type: 'array',
items: {
type: 'object',
properties: {
tweet_id: { type: 'string' },
text: { type: 'string' },
created_at: { type: 'string', format: 'date-time' },
score: { type: 'number' },
url: { type: 'string', format: 'uri' },
},
required: ['tweet_id', 'text', 'created_at', 'score', 'url'],
additionalProperties: false,
},
},
},
required: ['candidates'],
},
+29 -7
View File
@@ -1,4 +1,4 @@
import type { Operation } from '../core/operations.ts';
import type { Operation, ParamDef } from '../core/operations.ts';
export interface McpToolDef {
name: string;
@@ -10,6 +10,33 @@ export interface McpToolDef {
};
}
/**
* Convert a single ParamDef to a JSON Schema fragment. Recursive on `items`.
*
* Single source of truth for ParamDef→JSON Schema mapping. Consumed by:
* - buildToolDefs (stdio MCP server.ts via tool-defs.ts)
* - serve-http.ts tools/list handler (HTTP MCP path)
* - brain-allowlist.ts paramsToInputSchema (subagent tool registry)
*
* The three call sites previously each had their own inline destructure that
* drifted from each other (live HTTP MCP path dropped `items` entirely in
* v0.32 PR review). Centralizing here closes the bug class at the
* architecture level instead of patching one site at a time.
*
* Key ordering (type, description, enum, default, items) is intentional —
* matches the pre-v0.34 inline mappers so JSON.stringify output stays
* byte-stable for the byte-equality regression test.
*/
export function paramDefToSchema(p: ParamDef): Record<string, unknown> {
return {
type: p.type === 'array' ? 'array' : p.type,
...(p.description ? { description: p.description } : {}),
...(p.enum ? { enum: p.enum } : {}),
...(p.default !== undefined ? { default: p.default } : {}),
...(p.items ? { items: paramDefToSchema(p.items) } : {}),
};
}
export function buildToolDefs(ops: Operation[]): McpToolDef[] {
return ops.map(op => ({
name: op.name,
@@ -17,12 +44,7 @@ export function buildToolDefs(ops: Operation[]): McpToolDef[] {
inputSchema: {
type: 'object' as const,
properties: Object.fromEntries(
Object.entries(op.params).map(([k, v]) => [k, {
type: v.type === 'array' ? 'array' : v.type,
...(v.description ? { description: v.description } : {}),
...(v.enum ? { enum: v.enum } : {}),
...(v.items ? { items: { type: v.items.type } } : {}),
}]),
Object.entries(op.params).map(([k, v]) => [k, paramDefToSchema(v)]),
),
required: Object.entries(op.params)
.filter(([, v]) => v.required)
+12 -2
View File
@@ -99,6 +99,14 @@ describe('ZE live — embed round-trip', () => {
});
});
// 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) {
@@ -112,6 +120,7 @@ describe('ZE live — rerank round-trip', () => {
'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) {
@@ -128,7 +137,7 @@ describe('ZE live — rerank round-trip', () => {
// 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) {
@@ -139,9 +148,10 @@ describe('ZE live — rerank round-trip', () => {
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', () => {
+31 -2
View File
@@ -4,6 +4,7 @@ import { join } from 'path';
import { tmpdir } from 'os';
import {
GIT_SSRF_FLAGS,
GIT_SSRF_SUBCOMMAND_FLAGS,
parseRemoteUrl,
RemoteUrlError,
cloneRepo,
@@ -81,11 +82,22 @@ const fakePath = (): string => `${FAKE_GIT_DIR}:${process.env.PATH ?? ''}`;
// ---------------------------------------------------------------------------
describe('GIT_SSRF_FLAGS', () => {
test('exact shape — codex SSRF lockdown', () => {
test('exact shape — global -c config flags only (spread BEFORE the verb)', () => {
expect([...GIT_SSRF_FLAGS]).toEqual([
'-c', 'http.followRedirects=false',
'-c', 'protocol.file.allow=never',
'-c', 'protocol.ext.allow=never',
]);
});
});
describe('GIT_SSRF_SUBCOMMAND_FLAGS', () => {
test('exact shape — subcommand-level flags only (spread AFTER the verb)', () => {
// v0.34 fix wave: --no-recurse-submodules is a clone/pull subcommand
// flag, not a global flag. Real git exits 129 with "unknown option"
// when it appears before the verb. The pre-v0.34 single-constant
// spread baked the bug in.
expect([...GIT_SSRF_SUBCOMMAND_FLAGS]).toEqual([
'--no-recurse-submodules',
]);
});
@@ -229,12 +241,22 @@ describe('cloneRepo', () => {
const calls = readArgvLog();
expect(calls.length).toBe(1);
const argv = calls[0];
// Pin the SSRF flags before the 'clone' verb (codex Q2 invariant).
// Global -c config flags must appear BEFORE the 'clone' verb.
expect(argv.slice(0, GIT_SSRF_FLAGS.length)).toEqual([...GIT_SSRF_FLAGS]);
expect(argv).toContain('clone');
expect(argv).toContain('--depth=1');
expect(argv).toContain('https://example.com/repo');
expect(argv[argv.length - 1]).toBe(dest);
// v0.34 fix wave: subcommand flags MUST appear after the verb. Real
// git rejects `git --no-recurse-submodules clone ...` with exit 129.
// The fake-git harness returned 0 for any argv shape, so this
// position-anchored assertion is the structural regression test.
const cloneIdx = argv.indexOf('clone');
expect(cloneIdx).toBeGreaterThan(-1);
for (const subFlag of GIT_SSRF_SUBCOMMAND_FLAGS) {
const flagIdx = argv.indexOf(subFlag);
expect(flagIdx).toBeGreaterThan(cloneIdx);
}
});
test('depth=0 means no --depth flag (full clone)', async () => {
@@ -309,6 +331,13 @@ describe('pullRepo', () => {
expect(argv.slice(2, 2 + GIT_SSRF_FLAGS.length)).toEqual([...GIT_SSRF_FLAGS]);
expect(argv).toContain('pull');
expect(argv).toContain('--ff-only');
// v0.34 fix wave: subcommand flag position assertion.
const pullIdx = argv.indexOf('pull');
expect(pullIdx).toBeGreaterThan(-1);
for (const subFlag of GIT_SSRF_SUBCOMMAND_FLAGS) {
const flagIdx = argv.indexOf(subFlag);
expect(flagIdx).toBeGreaterThan(pullIdx);
}
rmSync(repo, { recursive: true, force: true });
});
+128 -9
View File
@@ -10,10 +10,39 @@
import { describe, test, expect } from 'bun:test';
import { operations } from '../src/core/operations.ts';
import { buildToolDefs } from '../src/mcp/tool-defs.ts';
import { buildToolDefs, paramDefToSchema } from '../src/mcp/tool-defs.ts';
import type { ParamDef } from '../src/core/operations.ts';
// Pre-extraction inline shape — lifted verbatim from the original
// src/mcp/server.ts block so any future drift fails this test loudly.
// Reference shape — mirrors the canonical `paramDefToSchema` helper from
// src/mcp/tool-defs.ts. Drift between the helper and this reference fails
// the byte-equality test loudly.
//
// v0.34 update: paramDefToSchema is recursive on `items` so nested
// array-of-arrays preserves the inner shape on the MCP wire. The reference
// below mirrors that recursion. The previous shallow `{ items: { type:
// v.items.type } }` (legacy buildToolDefs) silently dropped nested items
// — explicit fixture assertions below catch the drift class.
//
// `default` is included to match paramDefToSchema; no current op uses
// `default:` at the ParamDef level so the round-trip is unchanged for
// every existing operation, but new ops that add a default get it on the
// wire automatically.
type ParamDefLike = {
type: 'string' | 'number' | 'boolean' | 'object' | 'array';
description?: string;
enum?: string[];
default?: unknown;
items?: ParamDefLike;
};
function referenceParamDefToSchema(p: ParamDefLike): Record<string, unknown> {
return {
type: p.type === 'array' ? 'array' : p.type,
...(p.description ? { description: p.description } : {}),
...(p.enum ? { enum: p.enum } : {}),
...(p.default !== undefined ? { default: p.default } : {}),
...(p.items ? { items: referenceParamDefToSchema(p.items) } : {}),
};
}
function legacyInlineMap(ops: typeof operations) {
return ops.map(op => ({
name: op.name,
@@ -21,12 +50,7 @@ function legacyInlineMap(ops: typeof operations) {
inputSchema: {
type: 'object' as const,
properties: Object.fromEntries(
Object.entries(op.params).map(([k, v]) => [k, {
type: v.type === 'array' ? 'array' : v.type,
...(v.description ? { description: v.description } : {}),
...(v.enum ? { enum: v.enum } : {}),
...(v.items ? { items: { type: v.items.type } } : {}),
}]),
Object.entries(op.params).map(([k, v]) => [k, referenceParamDefToSchema(v)]),
),
required: Object.entries(op.params)
.filter(([, v]) => v.required)
@@ -65,3 +89,98 @@ describe('buildToolDefs', () => {
}
});
});
// ---------------------------------------------------------------------------
// Structural array-items guard (v0.34 fix wave).
//
// JSON Schema strict-mode validators (Gemini Pro strict, OpenAI structured
// outputs) reject `type: 'array'` without `items`. Pre-v0.34 this happened
// in production: `extract_facts.entity_hints` and `handle_to_tweet`'s
// `candidates` both shipped as bare arrays.
//
// This recursive guard walks every tool def's inputSchema and fails the
// suite with a property path if any array lacks `items.type`. Drift-proof
// against future ops adding bare arrays.
// ---------------------------------------------------------------------------
interface SchemaNode {
type?: unknown;
properties?: Record<string, SchemaNode>;
items?: SchemaNode;
[k: string]: unknown;
}
function findArrayWithoutItems(node: SchemaNode, path: string[]): string[] {
const violations: string[] = [];
if (node && typeof node === 'object') {
if (node.type === 'array') {
if (!node.items || typeof node.items !== 'object') {
violations.push(`${path.join('.') || '<root>'} (array missing items)`);
} else if (!('type' in node.items)) {
violations.push(`${path.join('.') || '<root>'}.items (items missing type)`);
} else {
violations.push(...findArrayWithoutItems(node.items, [...path, 'items']));
}
}
if (node.properties && typeof node.properties === 'object') {
for (const [k, child] of Object.entries(node.properties)) {
violations.push(...findArrayWithoutItems(child as SchemaNode, [...path, k]));
}
}
if (node.items && typeof node.items === 'object' && node.type !== 'array') {
violations.push(...findArrayWithoutItems(node.items, [...path, 'items']));
}
}
return violations;
}
describe('paramDefToSchema structural guard', () => {
test('every operation inputSchema array has items.type set (no bare arrays)', () => {
const allViolations: string[] = [];
for (const def of buildToolDefs(operations)) {
const v = findArrayWithoutItems(def.inputSchema as SchemaNode, [def.name]);
allViolations.push(...v);
}
expect(allViolations).toEqual([]);
});
test('extract_facts.entity_hints declares items.type as string', () => {
const def = buildToolDefs(operations).find(d => d.name === 'extract_facts');
expect(def).toBeDefined();
const eh = (def!.inputSchema.properties as Record<string, SchemaNode>).entity_hints;
expect(eh.type).toBe('array');
expect(eh.items).toBeDefined();
expect((eh.items as SchemaNode).type).toBe('string');
});
test('paramDefToSchema recursively propagates nested items.items.type', () => {
// Synthetic ParamDef: array-of-arrays-of-strings. No current op uses
// this shape, so this test pins the contract for future ops and proves
// the helper recurses (closes the v0.32 nested-drop bug class).
const nested: ParamDef = {
type: 'array',
items: {
type: 'array',
items: { type: 'string' },
},
};
const schema = paramDefToSchema(nested) as SchemaNode;
expect(schema.type).toBe('array');
expect((schema.items as SchemaNode).type).toBe('array');
expect(((schema.items as SchemaNode).items as SchemaNode).type).toBe('string');
});
test('paramDefToSchema preserves description on nested items', () => {
const p: ParamDef = {
type: 'array',
description: 'outer',
items: {
type: 'string',
description: 'inner',
},
};
const schema = paramDefToSchema(p) as SchemaNode;
expect(schema.description).toBe('outer');
expect((schema.items as SchemaNode).description).toBe('inner');
});
});
+95
View File
@@ -620,3 +620,98 @@ describe('x_handle_to_tweet resolver', () => {
expect(query).toContain('words');
});
});
// ---------------------------------------------------------------------------
// Structural array-items guard for resolver inputSchema + outputSchema.
//
// v0.34 fix wave: handle_to_tweet's `candidates` field shipped as bare
// `type: 'array'` without `items` (caught by community PR #910). Same
// bug class as extract_facts.entity_hints, different surface. Resolvers
// don't ride through buildToolDefs so the MCP-side structural guard
// doesn't see them.
//
// This guard walks the builtin resolvers explicitly (NOT via
// getDefaultRegistry(), which starts empty until commands/resolvers.ts
// registers — codex catch). Both inputSchema AND outputSchema are
// checked because resolvers are bidirectional.
// ---------------------------------------------------------------------------
interface SchemaNode {
type?: unknown;
properties?: Record<string, SchemaNode>;
items?: SchemaNode;
[k: string]: unknown;
}
function findArrayWithoutItems(node: SchemaNode | undefined, path: string[]): string[] {
const violations: string[] = [];
if (!node || typeof node !== 'object') return violations;
if (node.type === 'array') {
if (!node.items || typeof node.items !== 'object') {
violations.push(`${path.join('.') || '<root>'} (array missing items)`);
} else if (!('type' in node.items)) {
violations.push(`${path.join('.') || '<root>'}.items (items missing type)`);
} else {
violations.push(...findArrayWithoutItems(node.items, [...path, 'items']));
}
}
if (node.properties && typeof node.properties === 'object') {
for (const [k, child] of Object.entries(node.properties)) {
violations.push(...findArrayWithoutItems(child as SchemaNode, [...path, k]));
}
}
return violations;
}
describe('builtin resolver schemas — structural array-items guard', () => {
// Explicit-import list. getDefaultRegistry() returns an empty registry
// until commands/resolvers.ts registers, so walking it would silently
// pass with zero resolvers visited (codex finding).
const builtins = [
{ name: 'url_reachable', resolver: urlReachableResolver },
{ name: 'x_handle_to_tweet', resolver: xHandleToTweetResolver },
];
for (const { name, resolver } of builtins) {
test(`${name}: inputSchema has no bare arrays`, () => {
const violations = findArrayWithoutItems(
resolver.inputSchema as SchemaNode | undefined,
[name, 'inputSchema'],
);
expect(violations).toEqual([]);
});
test(`${name}: outputSchema has no bare arrays`, () => {
const violations = findArrayWithoutItems(
resolver.outputSchema as SchemaNode | undefined,
[name, 'outputSchema'],
);
expect(violations).toEqual([]);
});
}
test('x_handle_to_tweet candidates declares full item shape with required + additionalProperties:false', () => {
const out = xHandleToTweetResolver.outputSchema as SchemaNode;
const candidates = (out.properties as Record<string, SchemaNode>).candidates;
expect(candidates.type).toBe('array');
expect(candidates.items).toBeDefined();
const items = candidates.items as SchemaNode;
expect(items.type).toBe('object');
expect(items.properties).toBeDefined();
const props = items.properties as Record<string, SchemaNode>;
expect(Object.keys(props).sort()).toEqual(
['created_at', 'score', 'text', 'tweet_id', 'url'],
);
expect((items as { required?: unknown }).required).toEqual(
['tweet_id', 'text', 'created_at', 'score', 'url'],
);
expect((items as { additionalProperties?: unknown }).additionalProperties).toBe(false);
});
test('coverage: at least 2 builtins walked (catches future regression where registry import drops)', () => {
// Negative guard against codex's "underspecified registry walk" finding:
// if this list ever empties (e.g. an autoformatter drops the array),
// the rest of the suite would silently pass.
expect(builtins.length).toBeGreaterThanOrEqual(2);
});
});