Compare commits

...
Author SHA1 Message Date
Garry TanandClaude Fable 5 4b972dea0b fix(test): assert lens packs against BUNDLED_PACK_NAMES registry, not load-active.ts source text
The bundled-pack registry moved from load-active.ts into mutate.ts
(BUNDLED_PACK_NAMES) in this branch; the source-text grep in
lens-pack-manifests.test.ts still pointed at load-active.ts. Assert
membership in the real exported registry instead — stronger and
refactor-proof.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 10:48:59 -07:00
4e5c09eef6 fix(facts): probe the effective facts model + merge DB-plane provider_base_urls (takeover of #2233)
Two salvaged fixes from #2233:

- extractFactsFromTurn probed isAvailable('chat') with no model, silently
  no-oping extraction whenever the facts model routes through a different
  provider than the global chat model. It now probes the effective
  (per-call/config) facts model.
- 'gbrain config set provider_base_urls.<id> <url>' writes DB plane (the
  prefix is advertised in KNOWN_CONFIG_KEY_PREFIXES) but loadConfigWithEngine
  never merged it back, so the gateway never saw the configured proxy. Merged
  with file-plane winning, fail-open for engine shims without listConfigKeys.

Dropped from the original PR: the openrouter_api_key plumbing (already on
master) and the hardcoded personal-name normalization + regex turn
pre-filter + kind normalizer (privacy-rule violation; fork-specific
heuristics that belong in per-install config, not the shared extractor).

Co-authored-by: sene1337 <sene1337@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:51:05 -07:00
2307a827d8 fix(budget): price non-Anthropic chat models via the canonical table (takeover of #2127)
lookupPricing consulted only ANTHROPIC_PRICING for chat/rerank, so any
openai:/google:/deepseek: model hit BudgetExhausted(no_pricing) BEFORE the
provider call whenever a cost cap was set. Fall through to canonicalLookup,
per the one-canonical-pricing-table invariant. The original PR's $0
CANONICAL_PRICING entries for openrouter: ids are dropped — openrouter-
prefixed ids intentionally MISS (markup != native pricing), and a $0
canonical entry would zero cost accounting for everyone routing those
models; free-route pricing belongs in per-install config.

Co-authored-by: troyhoffman-oss <troyhoffman-oss@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:50:54 -07:00
2de65136c5 fix(subagent): bound per-tool execution with timeout + idempotent retry (takeover of #2086)
toolLoop and the legacy Anthropic subagent path ran handler.execute()
unbounded — a wedged pooler or half-open client socket squatted the worker
slot until the JOB-level wall-clock timeout reaped the whole job. Every tool
call is now bounded by GBRAIN_SUBAGENT_TOOL_TIMEOUT_MS (default 60s) and
idempotent tools retry transient/timeout failures up to
GBRAIN_SUBAGENT_TOOL_MAX_ATTEMPTS (default 2, parsed as a count — not through
resolveAiTimeoutMs). Retries emit a typed tool_retry heartbeat (no casts).

The original PR's queue.ts retryJob hunk is dropped: master already resets
started_at/attempts on retry.

Co-authored-by: JiraiyaETH <JiraiyaETH@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:50:43 -07:00
beeb73932d fix(schema): register all 7 bundled packs in one shared registry (takeover of #2017)
BUNDLED_PACK_NAMES in mutate.ts listed only 3 packs while load-active.ts's
locator bundled 7, so 'gbrain schema show/use gbrain-creator|investor|
engineer|everything' missed. The registry now lives once in mutate.ts and
the locator consumes it, so the two can't drift again. A test asserts every
registry entry ships a real YAML in base/.

Co-authored-by: arisgysel-design <arisgysel-design@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:50:34 -07:00
15 changed files with 538 additions and 50 deletions
+141 -2
View File
@@ -80,6 +80,20 @@ const AI_CHAT_TIMEOUT_MS = resolveAiTimeoutMs('GBRAIN_AI_CHAT_TIMEOUT_MS', 300_0
const AI_EMBED_TIMEOUT_MS = resolveAiTimeoutMs('GBRAIN_AI_EMBED_TIMEOUT_MS', 60_000);
/** multimodal per request. */
const AI_MULTIMODAL_TIMEOUT_MS = resolveAiTimeoutMs('GBRAIN_AI_MULTIMODAL_TIMEOUT_MS', 60_000);
/** Per tool execution inside the tool loop. A hung DB/pooler/client call must
* settle as a failed tool result instead of squatting a worker slot until the
* job's wall-clock timeout expires. */
const AI_TOOL_TIMEOUT_MS = resolveAiTimeoutMs('GBRAIN_SUBAGENT_TOOL_TIMEOUT_MS', 60_000);
/** Max attempts for idempotent transient/timeout tool failures. A COUNT, not a
* timeout — parsed by its own resolver, not resolveAiTimeoutMs. */
const AI_TOOL_MAX_ATTEMPTS = resolveAiCount('GBRAIN_SUBAGENT_TOOL_MAX_ATTEMPTS', 2);
function resolveAiCount(envVar: string, fallback: number): number {
const raw = process.env[envVar];
if (raw === undefined) return fallback;
const n = Number(raw);
return Number.isFinite(n) && n >= 1 ? Math.floor(n) : fallback;
}
/**
* Compose a caller signal with a default wall-clock timeout. When the caller
@@ -3260,6 +3274,10 @@ export interface ToolLoopOpts {
abortSignal?: AbortSignal;
/** Apply Anthropic cache_control to system + last tool. Silently ignored elsewhere. */
cacheSystem?: boolean;
/** Per-tool wall-clock timeout. Defaults to GBRAIN_SUBAGENT_TOOL_TIMEOUT_MS or 60s. */
toolTimeoutMs?: number;
/** Max attempts for idempotent transient/timeout tool failures. Defaults to GBRAIN_SUBAGENT_TOOL_MAX_ATTEMPTS or 2. */
toolMaxAttempts?: number;
/** Crash-replay state. When set, the loop resumes from the recorded position. */
replayState?: ToolLoopReplayState;
@@ -3334,6 +3352,8 @@ export async function toolLoop(opts: ToolLoopOpts): Promise<ToolLoopResult> {
const maxTurns = opts.maxTurns ?? 20;
const maxTokens = opts.maxTokens ?? defaultMaxOutputTokens(opts.model ?? getChatModel());
const handlers = opts.toolHandlers;
const toolTimeoutMs = opts.toolTimeoutMs ?? AI_TOOL_TIMEOUT_MS;
const toolMaxAttempts = Math.max(1, Math.floor(opts.toolMaxAttempts ?? AI_TOOL_MAX_ATTEMPTS));
const totalUsage: ChatResult['usage'] = {
input_tokens: 0,
output_tokens: 0,
@@ -3492,10 +3512,25 @@ export async function toolLoop(opts: ToolLoopOpts): Promise<ToolLoopResult> {
);
}
// Step 3: execute (side effect).
// Step 3: execute (side effect). Bound every call: DB/pooler/client
// hangs must settle as failed tool results instead of squatting a worker
// slot until the whole job timeout expires. Only idempotent tools retry.
opts.onHeartbeat?.('tool_called', { turn_idx: turnIdx, tool_name: call.toolName });
try {
const output = await handler.execute(call.input, opts.abortSignal ?? new AbortController().signal);
const output = await executeToolWithTimeoutAndRetry({
toolName: call.toolName,
baseSignal: opts.abortSignal,
timeoutMs: toolTimeoutMs,
maxAttempts: toolMaxAttempts,
idempotent: handler.idempotent === true,
execute: signal => handler.execute(call.input, signal),
onRetry: (attempt, error) => opts.onHeartbeat?.('tool_retry', {
turn_idx: turnIdx,
tool_name: call.toolName,
attempt,
error: error instanceof Error ? error.message : String(error),
}),
});
// Step 4: settle complete.
await opts.onToolCallComplete?.(gbrainToolUseId, output);
toolResultBlocks.push({
@@ -3538,6 +3573,110 @@ export async function toolLoop(opts: ToolLoopOpts): Promise<ToolLoopResult> {
return { finalText, totalTurns: turnIdx, totalUsage, stopReason, messages };
}
// ---- Per-tool timeout + retry (subagent tool loop) ----
/** Thrown when a single tool execution exceeds its wall-clock timeout. */
export class ToolCallTimeoutError extends Error {
constructor(public toolName: string, public timeoutMs: number) {
super(`tool "${toolName}" timed out after ${timeoutMs}ms`);
this.name = 'ToolCallTimeoutError';
}
}
export interface ExecuteToolWithTimeoutAndRetryOpts {
toolName: string;
/** Caller abort (job cancel / worker shutdown). Composed with the per-attempt timeout. */
baseSignal?: AbortSignal;
/** Per-attempt wall-clock timeout in ms. */
timeoutMs: number;
/** Total attempts allowed for idempotent tools; non-idempotent tools always run once. */
maxAttempts: number;
idempotent: boolean;
execute: (signal: AbortSignal) => Promise<unknown>;
/** Fires before each retry with the 1-based attempt number about to run. */
onRetry?: (attempt: number, error: unknown) => void;
}
/**
* Run one tool call bounded by a wall-clock timeout, retrying transient
* failures (timeouts + connection-class errors) for IDEMPOTENT tools only.
* The timeout wins even when the tool ignores its abort signal — the race
* settles and the loop feeds a failed tool result back to the model instead
* of wedging the worker until the job-level timeout reaps it.
*/
export async function executeToolWithTimeoutAndRetry(
opts: ExecuteToolWithTimeoutAndRetryOpts,
): Promise<unknown> {
const maxAttempts = opts.idempotent ? Math.max(1, opts.maxAttempts) : 1;
let lastErr: unknown;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await executeSingleToolAttempt(opts);
} catch (err) {
lastErr = err;
if (opts.baseSignal?.aborted) throw err;
if (attempt >= maxAttempts || !isRetryableToolError(err)) throw err;
opts.onRetry?.(attempt + 1, err);
await abortableSleep(Math.min(1000 * attempt, 3000), opts.baseSignal);
}
}
throw lastErr;
}
async function executeSingleToolAttempt(opts: ExecuteToolWithTimeoutAndRetryOpts): Promise<unknown> {
const timeoutController = new AbortController();
const timer = setTimeout(() => {
timeoutController.abort(new ToolCallTimeoutError(opts.toolName, opts.timeoutMs));
}, opts.timeoutMs);
const signal = opts.baseSignal
? AbortSignal.any([opts.baseSignal, timeoutController.signal])
: timeoutController.signal;
let abortListener: (() => void) | undefined;
const abortPromise = new Promise<never>((_, reject) => {
abortListener = () => {
const reason = signal.reason;
reject(reason instanceof Error ? reason : new Error('tool call aborted'));
};
if (signal.aborted) abortListener();
else signal.addEventListener('abort', abortListener, { once: true });
});
const workPromise = Promise.resolve().then(() => opts.execute(signal));
// Promise.race may settle via timeout first; keep the abandoned work's
// eventual rejection from becoming an unhandledRejection.
workPromise.catch(() => {});
try {
return await Promise.race([workPromise, abortPromise]);
} finally {
clearTimeout(timer);
if (abortListener) signal.removeEventListener('abort', abortListener);
}
}
function isRetryableToolError(err: unknown): boolean {
if (err instanceof ToolCallTimeoutError) return true;
const name = err && typeof err === 'object' ? String((err as { name?: unknown }).name ?? '') : '';
if (name === 'TimeoutError') return true;
const message = err instanceof Error ? err.message : String(err);
return /CONNECT_TIMEOUT|connect timeout|Cannot connect|ECONNRESET|ECONNREFUSED|ETIMEDOUT|connection terminated|server closed the connection|pooler/i.test(message);
}
function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
if (signal?.aborted) return Promise.reject(signal.reason ?? new Error('aborted'));
return new Promise((resolve, reject) => {
const onAbort = () => {
clearTimeout(timer);
reject(signal?.reason ?? new Error('aborted'));
};
const timer = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve();
}, ms);
signal?.addEventListener('abort', onAbort, { once: true });
});
}
// ---- Reranker (v0.35.0.0+) ----
/** Tagged error class for gateway.rerank() failures. `reason` classifies into the
+10
View File
@@ -32,6 +32,7 @@ import { mkdirSync, appendFileSync } from 'node:fs';
import { dirname } from 'node:path';
import { gbrainPath } from '../config.ts';
import { ANTHROPIC_PRICING, type ModelPricing } from '../anthropic-pricing.ts';
import { canonicalLookup } from '../model-pricing.ts';
import { EMBEDDING_PRICING, lookupEmbeddingPrice } from '../embedding-pricing.ts';
import { splitProviderModelId } from '../model-id.ts';
import { isoWeekFilename, resolveAuditDir } from '../audit-week-file.ts';
@@ -194,6 +195,15 @@ function lookupPricing(modelId: string, kind: BudgetKind): ModelPricing | null {
const tailHit = ANTHROPIC_PRICING[modelTail];
if (tailHit) return tailHit;
}
// Non-Anthropic chat models (openai:, google:, deepseek:, ...) live in the
// canonical pricing table, not the Anthropic-only ANTHROPIC_PRICING view.
// Without this fall-through every non-Anthropic chat model returns null,
// and under a cost cap reserve() throws BudgetExhausted(no_pricing) BEFORE
// the provider call — silently zeroing extraction for those providers.
// OpenRouter-prefixed ids still MISS by design (canonicalLookup's contract:
// OpenRouter markup ≠ native pricing).
const canonical = canonicalLookup(modelId);
if (canonical) return canonical;
// v0.40.6.1: zero-price local-inference rerank providers so the budget
// tracker's TX2 hard-fail doesn't trip on `llama-server-reranker:<model>`
// under `--max-cost`. Only the rerank kind — chat/embed already have
+30 -1
View File
@@ -620,7 +620,10 @@ export function loadConfig(): GBrainConfig | null {
* size the schema and must be stable across engine connect.
*/
export async function loadConfigWithEngine(
engine: { getConfig(key: string): Promise<string | null | undefined> },
engine: {
getConfig(key: string): Promise<string | null | undefined>;
listConfigKeys?(prefix: string): Promise<string[]>;
},
base?: GBrainConfig | null,
): Promise<GBrainConfig | null> {
// Codex /ship finding #3: when there's no file config AND no env DB URL,
@@ -669,10 +672,36 @@ export async function loadConfigWithEngine(
const dbEmbeddingColumns = await dbStr('embedding_columns');
const dbSearchEmbeddingColumn = await dbStr('search_embedding_column');
// `gbrain config set provider_base_urls.<id> <url>` writes DB plane (the
// prefix is advertised in KNOWN_CONFIG_KEY_PREFIXES) but pre-fix nothing
// ever merged it back, so the gateway never saw the configured proxy.
const dbProviderBaseUrls: Record<string, string> = {};
if (typeof engine.listConfigKeys === 'function') {
try {
const keys = await engine.listConfigKeys('provider_base_urls.');
for (const key of keys) {
const provider = key.slice('provider_base_urls.'.length).trim();
if (!provider) continue;
const value = await dbStr(key);
if (value !== undefined && value.trim()) dbProviderBaseUrls[provider] = value.trim();
}
} catch {
// Minimal engine shims (tests) may not support prefix listing; keep
// file/env behavior.
}
}
// DB applies only when env did NOT win. Env presence is detected by the
// sync loadConfig() already setting the field. For each flag, prefer the
// existing fileConfig value when defined; otherwise fall through to DB.
const merged: GBrainConfig = { ...fileConfig };
if (Object.keys(dbProviderBaseUrls).length > 0) {
// File-plane entries win over DB values per the documented precedence.
merged.provider_base_urls = {
...dbProviderBaseUrls,
...(merged.provider_base_urls ?? {}),
};
}
if (merged.embedding_multimodal === undefined && dbMultimodal !== undefined) {
merged.embedding_multimodal = dbMultimodal;
}
+9 -6
View File
@@ -173,16 +173,19 @@ export async function extractFactsFromTurn(input: ExtractInput): Promise<Extract
cleaned = cleaned.trim();
if (!cleaned) return [];
if (!isAvailable('chat')) {
// No chat gateway → no extraction. Caller still inserts facts via direct
// `gbrain take add` paths.
return [];
}
const cap = Math.max(1, Math.min(input.maxFactsPerTurn ?? 10, 25));
const defaultModel = await getFactsExtractionModel(input.engine);
const maxTokens = await getFactsExtractionMaxTokens(input.engine);
const model = input.model ?? defaultModel;
if (!isAvailable('chat', model)) {
// No chat gateway for the EFFECTIVE facts-extraction model → no
// extraction. Probing the global chat model here silently no-ops
// extraction whenever facts route through a different provider than
// chat (e.g. chat on Anthropic, facts on a private openai-compatible
// endpoint). Caller still inserts facts via direct `gbrain take add`.
return [];
}
const userContent = `<turn>\n${cleaned}\n</turn>\n\nExtract up to ${cap} facts.${
input.entityHints && input.entityHints.length
? ` Known entity slugs the user already mentioned: ${input.entityHints.slice(0, 5).join(', ')}.`
+3 -1
View File
@@ -37,8 +37,10 @@ export interface SubagentHeartbeatEvent {
ts: string;
type: 'heartbeat';
job_id: number;
event: 'llm_call_started' | 'llm_call_completed' | 'tool_called' | 'tool_result' | 'tool_failed';
event: 'llm_call_started' | 'llm_call_completed' | 'tool_called' | 'tool_result' | 'tool_failed' | 'tool_retry';
turn_idx: number;
/** 1-based attempt number about to run, for tool_retry. */
attempt?: number;
/** Tool name for tool_* events. Never the input — that may contain secrets. */
tool_name?: string;
/** ms elapsed for *_completed / tool_result / tool_failed. */
+45 -8
View File
@@ -49,7 +49,7 @@ import {
} from './subagent-audit.ts';
import { resolveModel, isAnthropicProvider, TIER_DEFAULTS } from '../../model-config.ts';
import { buildSystemPrompt, DEFAULT_SUBAGENT_SYSTEM } from '../system-prompt.ts';
import { toolLoop as gatewayToolLoop } from '../../ai/gateway.ts';
import { executeToolWithTimeoutAndRetry, toolLoop as gatewayToolLoop } from '../../ai/gateway.ts';
import type { ChatToolDef, ChatMessage, ChatBlock, ChatResult, ToolHandler } from '../../ai/gateway.ts';
import { classifyCapabilities } from '../../ai/capabilities.ts';
import { randomUUIDv7 } from 'bun';
@@ -419,8 +419,15 @@ export function makeSubagentHandler(deps: SubagentDeps) {
}
await persistToolExecPending(engine, ctx.id, last.message_idx, use.id, use.name, use.input);
try {
const output = await toolDef.execute(use.input, {
engine, jobId: ctx.id, remote: true, signal: ctx.signal,
const output = await executeToolWithTimeoutAndRetry({
toolName: use.name,
baseSignal: mergeSignals(ctx.signal, ctx.shutdownSignal),
timeoutMs: subagentToolTimeoutMs(),
maxAttempts: subagentToolMaxAttempts(),
idempotent: toolDef.idempotent === true,
execute: signal => toolDef.execute(use.input, {
engine, jobId: ctx.id, remote: true, signal,
}),
});
await persistToolExecComplete(engine, ctx.id, use.id, output);
synthesizedResults.push({
@@ -732,11 +739,26 @@ export function makeSubagentHandler(deps: SubagentDeps) {
const toolStart = Date.now();
try {
const output = await toolDef.execute(use.input, {
engine,
jobId: ctx.id,
remote: true,
signal: ctx.signal,
const output = await executeToolWithTimeoutAndRetry({
toolName,
baseSignal: mergeSignals(ctx.signal, ctx.shutdownSignal),
timeoutMs: subagentToolTimeoutMs(),
maxAttempts: subagentToolMaxAttempts(),
idempotent: toolDef.idempotent === true,
execute: signal => toolDef.execute(use.input, {
engine,
jobId: ctx.id,
remote: true,
signal,
}),
onRetry: (attempt, error) => logSubagentHeartbeat({
job_id: ctx.id,
event: 'tool_retry',
turn_idx: turnIdx,
tool_name: toolName,
attempt,
error: error instanceof Error ? error.message : String(error),
}),
});
await persistToolExecComplete(engine, ctx.id, use.id, output);
logSubagentHeartbeat({
@@ -1493,6 +1515,21 @@ async function persistToolExecFailed(
// ── Internal: helpers ───────────────────────────────────────
/** Per-tool wall-clock timeout for the legacy Anthropic path. Read at call
* time (not module load) so operators can tune it per worker restart. Same
* env vars as the gateway toolLoop defaults. */
function subagentToolTimeoutMs(): number {
const raw = process.env.GBRAIN_SUBAGENT_TOOL_TIMEOUT_MS;
const n = raw === undefined ? 60_000 : Number(raw);
return Number.isFinite(n) && n > 0 ? n : 60_000;
}
function subagentToolMaxAttempts(): number {
const raw = process.env.GBRAIN_SUBAGENT_TOOL_MAX_ATTEMPTS;
const n = raw === undefined ? 2 : Number(raw);
return Number.isFinite(n) && n >= 1 ? Math.floor(n) : 2;
}
function asStringIfNotObject(value: unknown): string {
if (typeof value === 'string') return value;
try {
+4 -23
View File
@@ -28,6 +28,7 @@ import type { GBrainConfig } from '../config.ts';
import { gbrainPath } from '../config.ts';
import type { SchemaPackManifest } from './manifest-v1.ts';
import { loadPackFromFile } from './loader.ts';
import { BUNDLED_PACK_NAMES } from './mutate.ts';
import {
resolveActivePackName,
resolvePack,
@@ -92,28 +93,9 @@ export function _resetPackLocatorForTests(): void {
* throwing UnknownPackError with a paste-ready install hint.
*/
function defaultPackLocator(name: string): string | null {
// v0.39 T8 — bundled packs registry. gbrain-base + gbrain-recommended
// ship in src/core/schema-pack/base/. Add a new entry here to bundle
// additional canonical packs.
//
// v0.41 T4 — lens packs join the bundle: creator (atoms + concepts +
// extract_atoms/synthesize_concepts phases), investor (theses + bet
// resolution + 3 calibration domains), engineer (gstack-learnings bridge
// + 3 calibration domains), everything (meta-pack stacking all three
// via extends + borrow_from). Each ships as a real YAML at base/<name>.yaml.
const BUNDLED: ReadonlyArray<string> = [
'gbrain-base',
'gbrain-recommended',
'gbrain-creator',
'gbrain-investor',
'gbrain-engineer',
'gbrain-everything',
// v0.42 type-unification: 15-type canonical successor to gbrain-base.
// Ships as install default (Lane E T17) + via gbrain onboard pack
// upgrade flow (the unify-types Minion handler).
'gbrain-base-v2',
];
if (BUNDLED.includes(name)) {
// Bundled packs registry lives ONCE in mutate.ts (BUNDLED_PACK_NAMES) so
// the locator, the schema CLI, and the mutation guard can't drift.
if (BUNDLED_PACK_NAMES.has(name)) {
// Resolve bundled YAML relative to this source file. Works in both
// direct-bun execution and bun --compile binaries.
const here = dirname(fileURLToPath(import.meta.url));
@@ -209,7 +191,6 @@ export async function findPackSuccessors(
packName: string,
packVersion: string,
): Promise<ResolvedPack[]> {
const { BUNDLED_PACK_NAMES } = await import('./mutate.ts');
const candidates: string[] = [];
for (const name of BUNDLED_PACK_NAMES) {
if (name !== packName) candidates.push(name);
+16 -1
View File
@@ -93,7 +93,22 @@ export class SchemaPackMutationError extends Error {
}
}
export const BUNDLED_PACK_NAMES = new Set(['gbrain-base', 'gbrain-recommended', 'gbrain-base-v2']);
/**
* Single registry of bundled packs. Every entry ships a real YAML at
* src/core/schema-pack/base/<name>.yaml. load-active.ts's pack locator and
* the schema CLI both consume this set add a new bundled pack HERE only.
*/
export const BUNDLED_PACK_NAMES = new Set([
'gbrain-base',
'gbrain-recommended',
// v0.41 T4 — lens packs: creator, investor, engineer, everything.
'gbrain-creator',
'gbrain-investor',
'gbrain-engineer',
'gbrain-everything',
// v0.42 type-unification: 15-type canonical successor to gbrain-base.
'gbrain-base-v2',
]);
export interface MutateResult {
/** Pack name that was mutated. */
+31
View File
@@ -170,6 +170,37 @@ describe('BudgetTracker.reserve', () => {
).not.toThrow();
});
test('non-Anthropic chat model under --max-cost prices via the canonical table (no no_pricing throw)', () => {
// Pre-fix: chat lookup consulted only ANTHROPIC_PRICING, so any
// openai:/google:/deepseek: chat model hit TX2 no_pricing BEFORE the
// provider call whenever a cost cap was set (takeover of #2127).
const t = new BudgetTracker({ maxCostUsd: 10.0, label: 'test', auditPath });
for (const modelId of ['openai:gpt-5', 'google:gemini-2.0-flash', 'deepseek:deepseek-chat']) {
expect(() =>
t.reserve({
modelId,
estimatedInputTokens: 100,
maxOutputTokens: 100,
kind: 'chat',
}),
).not.toThrow();
}
});
test('openrouter-prefixed chat model still TX2 no_pricing-fails under cap (canonical MISS contract)', () => {
// canonicalLookup intentionally misses openrouter:* ids (markup != native
// pricing); the budget gate must stay fail-closed for them.
const t = new BudgetTracker({ maxCostUsd: 10.0, label: 'test', auditPath });
expect(() =>
t.reserve({
modelId: 'openrouter:anthropic/claude-sonnet-4-6',
estimatedInputTokens: 100,
maxOutputTokens: 100,
kind: 'chat',
}),
).toThrow(BudgetExhausted);
});
test('no cap + unknown pricing: warns once per process, no throw', () => {
const t = new BudgetTracker({ label: 'test', auditPath });
expect(() =>
+43
View File
@@ -24,6 +24,7 @@ import {
isAvailable,
resetGateway,
__setChatTransportForTests,
__setGenerateTextTransportForTests,
getChatModel,
} from '../src/core/ai/gateway.ts';
import { extractFactsFromTurn } from '../src/core/facts/extract.ts';
@@ -116,6 +117,48 @@ describe('facts extract — silent-no-op regression (v0.31.6 bug class)', () =>
expect(facts).toEqual([]);
});
test('facts model override availability is independent of the global chat model', () => {
// A brain can leave the global chat model on Anthropic while routing only
// facts extraction through an OpenAI-compatible/private endpoint. The
// extractor must probe the EFFECTIVE facts model, not the global chat model.
configureGateway({
chat_model: 'anthropic:claude-sonnet-4-6',
base_urls: { openrouter: 'http://127.0.0.1:8806/v1' },
env: { OPENROUTER_API_KEY: 'unused' },
});
expect(isAvailable('chat')).toBe(false); // no ANTHROPIC_API_KEY
expect(isAvailable('chat', 'openrouter:private/gemma4-31b')).toBe(true);
});
test('extractFactsFromTurn extracts via the per-call facts model even when the global chat model is unavailable', async () => {
// Pre-fix, extract probed isAvailable('chat') with NO model — so a brain
// whose facts model differed from the (unavailable) global chat model
// silently extracted zero facts (takeover of #2233).
configureGateway({
chat_model: 'anthropic:claude-sonnet-4-6',
base_urls: { openrouter: 'http://127.0.0.1:8806/v1' },
env: { OPENROUTER_API_KEY: 'unused' },
});
expect(isAvailable('chat')).toBe(false);
__setGenerateTextTransportForTests(async () => ({
content: [{ type: 'text', text: JSON.stringify({ facts: [
{ fact: 'The user prefers short answers', kind: 'preference', confidence: 0.9, notability: 'medium' },
] }) }],
finishReason: 'stop',
usage: { inputTokens: 1, outputTokens: 1 },
}) as any);
try {
const facts = await extractFactsFromTurn({
turnText: 'I prefer short answers, always.',
source: 'test:facts-model-override',
model: 'openrouter:private/gemma4-31b',
});
expect(facts.length).toBeGreaterThan(0);
} finally {
__setGenerateTextTransportForTests(null);
}
});
test('extractFactsFromTurn USES the chat transport when available — does NOT silently return []', async () => {
// The smoking-gun test: when chat IS available, extract MUST actually call
// the chat transport. If it silently returns [] without calling chat, the
+5 -6
View File
@@ -20,6 +20,7 @@ import {
parseSchemaPackManifest,
parseYamlMini,
AGGREGATOR_KINDS,
BUNDLED_PACK_NAMES,
type SchemaPackManifest,
} from '../src/core/schema-pack/index.ts';
@@ -55,13 +56,11 @@ describe('v0.41 T4: all 4 bundled lens packs parse cleanly', () => {
});
describe('v0.41 T4: bundled registry includes lens packs', () => {
test('load-active.ts BUNDLED array source includes the 4 lens pack names', () => {
const loadActiveSrc = readFileSync(
join(here, '..', 'src', 'core', 'schema-pack', 'load-active.ts'),
'utf-8',
);
test('BUNDLED_PACK_NAMES registry includes the 4 lens pack names', () => {
// Registry lives ONCE in mutate.ts (BUNDLED_PACK_NAMES); assert against
// the real export instead of grepping load-active.ts source text.
for (const name of PACK_NAMES) {
expect(loadActiveSrc).toContain(`'${name}'`);
expect(BUNDLED_PACK_NAMES.has(name)).toBe(true);
}
});
});
+38
View File
@@ -9,6 +9,7 @@ import { loadConfigWithEngine, type GBrainConfig } from '../src/core/config.ts';
interface FakeEngine {
getConfig(key: string): Promise<string | null | undefined>;
listConfigKeys?(prefix: string): Promise<string[]>;
}
function makeEngine(map: Record<string, string | null | undefined>): FakeEngine {
@@ -16,6 +17,9 @@ function makeEngine(map: Record<string, string | null | undefined>): FakeEngine
async getConfig(key: string) {
return map[key];
},
async listConfigKeys(prefix: string) {
return Object.keys(map).filter(k => k.startsWith(prefix));
},
};
}
@@ -47,6 +51,40 @@ describe('loadConfigWithEngine (Phase 4 / F3)', () => {
expect(merged?.embedding_columns?.embedding_voyage?.dimensions).toBe(1024);
});
test('DB-plane provider_base_urls.<provider> merge reaches runtime config', async () => {
// `gbrain config set provider_base_urls.openrouter <url>` writes DB plane
// (KNOWN_CONFIG_KEY_PREFIXES advertises it) — pre-fix nothing merged it
// back, so the gateway never saw the configured proxy.
const base: GBrainConfig = { engine: 'pglite' };
const engine = makeEngine({
'provider_base_urls.openrouter': 'http://127.0.0.1:8806/v1',
'provider_base_urls.llama-server': 'http://127.0.0.1:8081/v1',
});
const merged = await loadConfigWithEngine(engine, base);
expect(merged?.provider_base_urls?.openrouter).toBe('http://127.0.0.1:8806/v1');
expect(merged?.provider_base_urls?.['llama-server']).toBe('http://127.0.0.1:8081/v1');
});
test('file-plane provider_base_urls win over DB-plane provider overrides', async () => {
const base: GBrainConfig = {
engine: 'pglite',
provider_base_urls: { openrouter: 'http://file-plane/v1' },
};
const engine = makeEngine({
'provider_base_urls.openrouter': 'http://db-plane/v1',
});
const merged = await loadConfigWithEngine(engine, base);
expect(merged?.provider_base_urls?.openrouter).toBe('http://file-plane/v1');
});
test('engine without listConfigKeys keeps working (older shims)', async () => {
const base: GBrainConfig = { engine: 'pglite' };
const engine = { async getConfig() { return undefined; } };
const merged = await loadConfigWithEngine(engine, base);
expect(merged?.engine).toBe('pglite');
expect(merged?.provider_base_urls).toBeUndefined();
});
test('DB flag fills in when file/env did not set it', async () => {
const base: GBrainConfig = { engine: 'pglite' };
const engine = makeEngine({
+13 -1
View File
@@ -64,11 +64,23 @@ describe('gbrain schema CLI (Phase C)', () => {
expect(r.stdout + r.stderr).toMatch(/schema|active|list|show|validate|use/i);
});
test('schema list shows gbrain-base bundled', () => {
test('schema list shows all bundled packs', () => {
const r = gbrain(['schema', 'list']);
expect(r.code).toBe(0);
expect(r.stdout).toContain('Bundled packs:');
expect(r.stdout).toContain('gbrain-base');
expect(r.stdout).toContain('gbrain-recommended');
expect(r.stdout).toContain('gbrain-creator');
expect(r.stdout).toContain('gbrain-investor');
expect(r.stdout).toContain('gbrain-engineer');
expect(r.stdout).toContain('gbrain-everything');
expect(r.stdout).toContain('gbrain-base-v2');
});
test('schema show gbrain-creator resolves a lens pack manifest', () => {
const r = gbrain(['schema', 'show', 'gbrain-creator']);
expect(r.code).toBe(0);
expect(r.stdout).toContain('gbrain-creator');
});
test('schema show gbrain-base prints manifest details', () => {
+12 -1
View File
@@ -101,9 +101,20 @@ describe('locateMutablePackFile — bundled guard', () => {
it('BUNDLED_PACK_NAMES export contains all bundled packs', () => {
expect(BUNDLED_PACK_NAMES.has('gbrain-base')).toBe(true);
expect(BUNDLED_PACK_NAMES.has('gbrain-recommended')).toBe(true);
expect(BUNDLED_PACK_NAMES.has('gbrain-creator')).toBe(true);
expect(BUNDLED_PACK_NAMES.has('gbrain-investor')).toBe(true);
expect(BUNDLED_PACK_NAMES.has('gbrain-engineer')).toBe(true);
expect(BUNDLED_PACK_NAMES.has('gbrain-everything')).toBe(true);
// v0.42 (T22): gbrain-base-v2 joins the bundled set.
expect(BUNDLED_PACK_NAMES.has('gbrain-base-v2')).toBe(true);
expect(BUNDLED_PACK_NAMES.size).toBe(3);
expect(BUNDLED_PACK_NAMES.size).toBe(7);
});
it('every BUNDLED_PACK_NAMES entry ships a real YAML in base/', () => {
const baseDir = join(import.meta.dir, '..', 'src', 'core', 'schema-pack', 'base');
for (const name of BUNDLED_PACK_NAMES) {
expect(existsSync(join(baseDir, `${name}.yaml`))).toBe(true);
}
});
it('rejects gbrain-base-v2 with PACK_READONLY (bundled guard)', () => {
+138
View File
@@ -0,0 +1,138 @@
// Per-tool timeout + retry inside the tool loop (takeover of #2086).
//
// Pre-fix, `toolLoop` ran `handler.execute()` unbounded: a wedged pooler or
// half-open client socket squatted the worker slot until the JOB-level
// wall-clock timeout reaped the whole job. These pin:
// - a hung tool settles as ToolCallTimeoutError even when it ignores abort
// - idempotent transient failures retry (bounded) and feed the successful
// result back into the loop
// - non-idempotent tools never retry
import { afterEach, describe, expect, test } from 'bun:test';
import {
__setChatTransportForTests,
executeToolWithTimeoutAndRetry,
toolLoop,
type ChatResult,
} from '../src/core/ai/gateway.ts';
afterEach(() => {
__setChatTransportForTests(null);
});
const usage = {
input_tokens: 1,
output_tokens: 1,
cache_read_tokens: 0,
cache_creation_tokens: 0,
};
describe('subagent tool execution timeout/retry', () => {
test('executeToolWithTimeoutAndRetry bounds a hung tool even if it ignores the abort signal', async () => {
const started = Date.now();
await expect(executeToolWithTimeoutAndRetry({
toolName: 'brain_search',
timeoutMs: 20,
maxAttempts: 1,
idempotent: true,
execute: async () => new Promise(() => {}),
})).rejects.toThrow('tool "brain_search" timed out after 20ms');
expect(Date.now() - started).toBeLessThan(500);
});
test('caller abort (baseSignal) wins over the timeout and is NOT retried', async () => {
const ctl = new AbortController();
const pending = executeToolWithTimeoutAndRetry({
toolName: 'brain_search',
baseSignal: ctl.signal,
timeoutMs: 60_000,
maxAttempts: 3,
idempotent: true,
execute: async () => new Promise(() => {}),
});
ctl.abort(new Error('job cancelled'));
await expect(pending).rejects.toThrow('job cancelled');
});
test('idempotent transient tool failures retry and feed the successful result back into the loop', async () => {
let chatCalls = 0;
__setChatTransportForTests(async (): Promise<ChatResult> => {
chatCalls += 1;
if (chatCalls === 1) {
return {
text: '',
blocks: [{ type: 'tool-call', toolCallId: 'call-1', toolName: 'brain_search', input: { query: 'supabase' } }],
stopReason: 'tool_calls',
usage,
model: 'test:model',
providerId: 'test',
};
}
return {
text: 'done',
blocks: [{ type: 'text', text: 'done' }],
stopReason: 'end',
usage,
model: 'test:model',
providerId: 'test',
};
});
let attempts = 0;
const retries: number[] = [];
const result = await toolLoop({
model: 'test:model',
initialMessages: [{ role: 'user', content: 'search' }],
tools: [{ name: 'brain_search', description: 'Search', inputSchema: { type: 'object' } }],
toolHandlers: new Map([['brain_search', {
idempotent: true,
async execute() {
attempts += 1;
if (attempts === 1) throw new Error('Cannot connect to database: CONNECT_TIMEOUT');
return { ok: true };
},
}]]),
toolTimeoutMs: 1000,
toolMaxAttempts: 2,
onHeartbeat(event, data) {
if (event === 'tool_retry') retries.push(data.attempt as number);
},
});
expect(result.stopReason).toBe('end');
expect(result.finalText).toBe('done');
expect(attempts).toBe(2);
expect(retries).toEqual([2]);
expect(chatCalls).toBe(2);
});
test('non-idempotent transient tool failures do not retry', async () => {
let attempts = 0;
await expect(executeToolWithTimeoutAndRetry({
toolName: 'write_side_effect',
timeoutMs: 1000,
maxAttempts: 3,
idempotent: false,
execute: async () => {
attempts += 1;
throw new Error('Cannot connect to database: CONNECT_TIMEOUT');
},
})).rejects.toThrow('Cannot connect');
expect(attempts).toBe(1);
});
test('non-retryable errors surface immediately even for idempotent tools', async () => {
let attempts = 0;
await expect(executeToolWithTimeoutAndRetry({
toolName: 'brain_search',
timeoutMs: 1000,
maxAttempts: 3,
idempotent: true,
execute: async () => {
attempts += 1;
throw new Error('page not found');
},
})).rejects.toThrow('page not found');
expect(attempts).toBe(1);
});
});