mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-15 17:32:37 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ba6b5d4690 | ||
|
|
827c1619ac |
@@ -3,7 +3,11 @@
|
||||
*
|
||||
* Usage:
|
||||
* gbrain migrate --to supabase [--url <connection_string>]
|
||||
* (--url is persisted to config.json, mode 0600, so the migrated brain
|
||||
* works without env — #1271)
|
||||
* gbrain migrate --to pglite [--path <db_path>]
|
||||
* (an explicit --path destination is bootstrapped with its own
|
||||
* <path>/.gbrain/config.json so GBRAIN_HOME=<path> just works — #1271)
|
||||
* gbrain migrate --to <engine> --force (overwrite non-empty target)
|
||||
*/
|
||||
|
||||
@@ -11,9 +15,9 @@ import { createEngine } from '../core/engine-factory.ts';
|
||||
import { loadConfig, saveConfig, toEngineConfig, gbrainPath, effectiveEnvDatabaseUrl, type GBrainConfig } from '../core/config.ts';
|
||||
import type { BrainEngine } from '../core/engine.ts';
|
||||
import type { EngineConfig } from '../core/types.ts';
|
||||
import { writeFileSync, readFileSync, existsSync, unlinkSync } from 'fs';
|
||||
import { writeFileSync, readFileSync, existsSync, unlinkSync, mkdirSync, chmodSync } from 'fs';
|
||||
import { createHash } from 'crypto';
|
||||
import { resolve } from 'path';
|
||||
import { resolve, join } from 'path';
|
||||
import { createProgress } from '../core/progress.ts';
|
||||
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
|
||||
|
||||
@@ -59,6 +63,31 @@ export interface MigrateManifest {
|
||||
started_at: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* #1271 Finding 1: make an explicit `--to pglite --path P` destination usable
|
||||
* as a standalone brain. Writes `P/.gbrain/config.json` (mode 0600, plus a
|
||||
* `*` .gitignore) so `GBRAIN_HOME=P` resolves without a manual `gbrain init`.
|
||||
* Never clobbers an existing config at the destination. Returns the written
|
||||
* config path, or null when skipped.
|
||||
*/
|
||||
export function bootstrapDestinationConfig(dbPath: string): string | null {
|
||||
const abs = resolve(dbPath);
|
||||
const dir = join(abs, '.gbrain');
|
||||
const file = join(dir, 'config.json');
|
||||
if (existsSync(file)) return null;
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const cfg: GBrainConfig = { engine: 'pglite', database_path: abs };
|
||||
writeFileSync(file, JSON.stringify(cfg, null, 2) + '\n', { mode: 0o600 });
|
||||
try { chmodSync(file, 0o600); } catch { /* platform-specific */ }
|
||||
// Same worktree-safety pattern as saveConfig()'s ensureGitignore, scoped
|
||||
// to the destination home. Don't clobber a user-customized .gitignore.
|
||||
const gitignore = join(dir, '.gitignore');
|
||||
if (!existsSync(gitignore)) {
|
||||
writeFileSync(gitignore, '*\n', { mode: 0o600 });
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
export function migrationTargetId(config: EngineConfig): string {
|
||||
const locator = config.engine === 'postgres'
|
||||
? config.database_url ?? ''
|
||||
@@ -352,6 +381,25 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]
|
||||
};
|
||||
saveConfig(newConfig);
|
||||
|
||||
// #1271 Finding 2 (by design, but say it out loud): the connection string
|
||||
// is persisted so the migrated brain works without env. Mode 0600.
|
||||
if (opts.targetEngine === 'postgres' && opts.targetUrl) {
|
||||
console.error('Note: the --url connection string (including credentials) is persisted to config.json (mode 0600).');
|
||||
}
|
||||
|
||||
// #1271 Finding 1: an explicit --path destination doubles as a standalone
|
||||
// GBRAIN_HOME. Best-effort — never fail a completed migration over it.
|
||||
if (opts.targetEngine === 'pglite' && opts.targetPath) {
|
||||
try {
|
||||
const written = bootstrapDestinationConfig(opts.targetPath);
|
||||
if (written) {
|
||||
console.log(`Destination bootstrapped: ${written} (usable via GBRAIN_HOME=${resolve(opts.targetPath)})`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn(` WARN could not bootstrap destination config: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up
|
||||
clearManifest();
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
*/
|
||||
|
||||
import { resolveRecipe } from './model-resolver.ts';
|
||||
import { listRecipes } from './recipes/index.ts';
|
||||
import { AIConfigError } from './errors.ts';
|
||||
|
||||
export interface ProviderCapabilities {
|
||||
@@ -78,10 +77,7 @@ export function getProviderCapabilities(modelString: string): ProviderCapabiliti
|
||||
if (!chat) {
|
||||
throw new AIConfigError(
|
||||
`Provider "${recipe.id}" does not offer a chat touchpoint.`,
|
||||
// Computed from the registry so the hint can't drift into listing
|
||||
// chat-less providers (the pre-fix list falsely included embedding-only
|
||||
// recipes, sending users in circles — #1157).
|
||||
`Known providers with chat: ${listRecipes().filter(r => r.touchpoints.chat).map(r => r.id).join(', ')}. Pick one for models.tier.subagent.`,
|
||||
`Known providers with chat: openai, anthropic, google, openrouter, litellm-proxy, deepseek, groq, together, azure-openai, dashscope, minimax, zhipu, ollama, llama-server. Pick one for models.tier.subagent.`,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import type { Recipe } from '../types.ts';
|
||||
|
||||
/**
|
||||
* Zhipu AI (智谱AI) BigModel Open Platform. OpenAI-compatible /embeddings and
|
||||
* /chat/completions endpoints at open.bigmodel.cn. Hosts embedding-2 (1024d),
|
||||
* embedding-3 (Matryoshka up to 2048d), and the GLM chat family (glm-5.1 etc.)
|
||||
* with native tool calling — usable for models.tier.subagent (#1157).
|
||||
* Zhipu AI (智谱AI) BigModel Open Platform. OpenAI-compatible /embeddings
|
||||
* endpoint at open.bigmodel.cn. Hosts embedding-2 (1024d) and embedding-3
|
||||
* (Matryoshka up to 2048d).
|
||||
*
|
||||
* embedding-3 at 2048 dims exceeds pgvector's HNSW cap of 2000 — those
|
||||
* brains fall back to exact vector scans (see
|
||||
@@ -26,20 +25,6 @@ export const zhipu: Recipe = {
|
||||
setup_url: 'https://open.bigmodel.cn/',
|
||||
},
|
||||
touchpoints: {
|
||||
chat: {
|
||||
// Informational list (openai-compat tier: assertTouchpoint doesn't
|
||||
// enforce it), so newer GLM ids pass without a recipe edit.
|
||||
models: ['glm-5.1', 'glm-4.6', 'glm-4.5'],
|
||||
supports_tools: true,
|
||||
// gbrain-side stable tool ids (v0.38 D11) decoupled the loop from
|
||||
// Anthropic response formats; GLM tool calling is stable through the
|
||||
// OpenAI-compat path, same as deepseek/groq.
|
||||
supports_subagent_loop: true,
|
||||
// Anthropic-style cache_control markers are not honored on the
|
||||
// OpenAI-compat path — the loop runs hot (degraded:no_caching warn).
|
||||
supports_prompt_cache: false,
|
||||
max_context_tokens: 128000,
|
||||
},
|
||||
embedding: {
|
||||
models: ['embedding-3', 'embedding-2'],
|
||||
default_dims: 1024,
|
||||
@@ -51,5 +36,5 @@ export const zhipu: Recipe = {
|
||||
},
|
||||
},
|
||||
setup_hint:
|
||||
'Get an API key at https://open.bigmodel.cn/, then `export ZHIPUAI_API_KEY=...`. Chat/subagent: use `zhipu:glm-5.1`.',
|
||||
'Get an API key at https://open.bigmodel.cn/, then `export ZHIPUAI_API_KEY=...`',
|
||||
};
|
||||
|
||||
@@ -69,45 +69,6 @@ describe('recipe: zhipu', () => {
|
||||
expect(sql.toLowerCase()).toContain('hnsw');
|
||||
});
|
||||
|
||||
test('chat touchpoint declares GLM models with tool + subagent-loop support (#1157)', () => {
|
||||
const r = getRecipe('zhipu')!;
|
||||
expect(r.touchpoints.chat).toBeDefined();
|
||||
expect(r.touchpoints.chat!.models).toContain('glm-5.1');
|
||||
expect(r.touchpoints.chat!.supports_tools).toBe(true);
|
||||
expect(r.touchpoints.chat!.supports_subagent_loop).toBe(true);
|
||||
expect(r.touchpoints.chat!.supports_prompt_cache).toBe(false);
|
||||
});
|
||||
|
||||
test('zhipu:glm-5.1 passes the subagent capability gate (degraded:no_caching, not refused)', async () => {
|
||||
// Pre-fix: getProviderCapabilities threw "does not offer a chat touchpoint"
|
||||
// and classifyCapabilities returned 'unknown' → subagent submit refused.
|
||||
const { getProviderCapabilities, classifyCapabilities } =
|
||||
await import('../../src/core/ai/capabilities.ts');
|
||||
const caps = getProviderCapabilities('zhipu:glm-5.1');
|
||||
expect(caps.supportsToolCalling).toBe(true);
|
||||
expect(classifyCapabilities('zhipu:glm-5.1')).toBe('degraded:no_caching');
|
||||
});
|
||||
|
||||
test('no-chat-touchpoint error hint lists only providers that actually have chat', async () => {
|
||||
// The hint is computed from the registry; every provider it names must
|
||||
// really carry a chat touchpoint (pre-fix it hardcoded zhipu/dashscope/
|
||||
// minimax, all embedding-only at the time).
|
||||
const { getProviderCapabilities } = await import('../../src/core/ai/capabilities.ts');
|
||||
const { listRecipes } = await import('../../src/core/ai/recipes/index.ts');
|
||||
let hint = '';
|
||||
try {
|
||||
getProviderCapabilities('voyage:voyage-3');
|
||||
throw new Error('expected AIConfigError for embedding-only provider');
|
||||
} catch (e) {
|
||||
hint = (e as { fix?: string }).fix ?? String(e);
|
||||
}
|
||||
const listed = hint.match(/chat: ([^.]+)\./)?.[1]?.split(', ') ?? [];
|
||||
expect(listed.length).toBeGreaterThan(0);
|
||||
const withChat = new Set(listRecipes().filter(r => r.touchpoints.chat).map(r => r.id));
|
||||
for (const id of listed) expect(withChat.has(id)).toBe(true);
|
||||
expect(listed).toContain('zhipu');
|
||||
});
|
||||
|
||||
test('dimsProviderOptions threads dimensions for embedding-3 (Matryoshka)', async () => {
|
||||
// Codex finding #1: Zhipu embedding-3 is Matryoshka 256-2048. Without
|
||||
// `dimensions` on the wire, user-selected non-default dims are
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { mkdtempSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { join, resolve } from 'path';
|
||||
import { bootstrapDestinationConfig } from '../src/commands/migrate-engine.ts';
|
||||
import { loadConfigFileOnly } from '../src/core/config.ts';
|
||||
import { withEnv } from './helpers/with-env.ts';
|
||||
|
||||
describe('migrate --to pglite destination bootstrap (#1271)', () => {
|
||||
test('writes <path>/.gbrain/config.json so GBRAIN_HOME=<path> resolves a brain', async () => {
|
||||
const dest = mkdtempSync(join(tmpdir(), 'gbrain-dest-'));
|
||||
const written = bootstrapDestinationConfig(dest);
|
||||
const file = join(dest, '.gbrain', 'config.json');
|
||||
expect(written).toBe(file);
|
||||
|
||||
const cfg = JSON.parse(readFileSync(file, 'utf-8'));
|
||||
expect(cfg.engine).toBe('pglite');
|
||||
expect(cfg.database_path).toBe(resolve(dest));
|
||||
expect(statSync(file).mode & 0o777).toBe(0o600);
|
||||
// worktree safety: destination home is git-ignored like saveConfig()'s home
|
||||
expect(readFileSync(join(dest, '.gbrain', '.gitignore'), 'utf-8')).toBe('*\n');
|
||||
|
||||
// The exact failure mode from #1271: config resolution under
|
||||
// GBRAIN_HOME=<path> used to find nothing ("No brain configured").
|
||||
await withEnv({ GBRAIN_HOME: dest }, () => {
|
||||
const loaded = loadConfigFileOnly();
|
||||
expect(loaded?.engine).toBe('pglite');
|
||||
expect(loaded?.database_path).toBe(resolve(dest));
|
||||
});
|
||||
});
|
||||
|
||||
test('never clobbers an existing destination config', () => {
|
||||
const dest = mkdtempSync(join(tmpdir(), 'gbrain-dest-'));
|
||||
mkdirSync(join(dest, '.gbrain'), { recursive: true });
|
||||
writeFileSync(join(dest, '.gbrain', 'config.json'), '{"engine":"postgres"}\n');
|
||||
|
||||
expect(bootstrapDestinationConfig(dest)).toBe(null);
|
||||
expect(JSON.parse(readFileSync(join(dest, '.gbrain', 'config.json'), 'utf-8')).engine).toBe('postgres');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user