mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-15 17:32:37 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78cc6d1e84 |
@@ -1551,24 +1551,6 @@ export async function checkRerankerHealth(engine: BrainEngine): Promise<Check> {
|
||||
};
|
||||
}
|
||||
|
||||
// Historical #2059 rows were logged as `unknown` before missing reranker
|
||||
// auth was classified at the gateway. Surface repeated unknowns instead of
|
||||
// reporting "ok" while every rerank fails open.
|
||||
const unknownFails = failures.filter((f) => f.reason === 'unknown');
|
||||
if (unknownFails.length >= 3) {
|
||||
const setupHint = unknownFails.some((f) => {
|
||||
const summary = String(f.error_summary ?? '');
|
||||
return summary.includes('ZEROENTROPY_API_KEY') || summary.toLowerCase().includes('api key');
|
||||
})
|
||||
? ' Fix: verify ZEROENTROPY_API_KEY and run `gbrain models doctor`.'
|
||||
: '';
|
||||
return {
|
||||
name: 'reranker_health',
|
||||
status: 'warn',
|
||||
message: `${unknownFails.length} unknown reranker failure(s) in last 7 days.${setupHint}`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
name: 'reranker_health',
|
||||
status: 'ok',
|
||||
|
||||
@@ -3656,15 +3656,7 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {
|
||||
// whose request/response shape differs from ZE/llama.cpp (e.g. Voyage with
|
||||
// `top_k` / `data[]`) needs separate adapter hooks in a follow-up plan.
|
||||
const url = `${compat.baseURL.replace(/\/$/, '')}${tp.path ?? '/models/rerank'}`;
|
||||
let auth: { apiKey?: string; headers?: Record<string, string> };
|
||||
try {
|
||||
auth = applyResolveAuth(recipe, cfg, 'reranker');
|
||||
} catch (err) {
|
||||
if (err instanceof AIConfigError) {
|
||||
throw new RerankError(err.message, 'auth');
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
const auth = applyResolveAuth(recipe, cfg, 'reranker');
|
||||
// applyResolveAuth returns { apiKey } for Bearer-style auth (SDK's native
|
||||
// path) or { headers } for custom-header providers (Azure). v0.37.6.0:
|
||||
// recipes can ALSO declare default_headers (attribution etc.) which flow
|
||||
|
||||
@@ -20,6 +20,14 @@ export const CJK_SLUG_CHARS = '一-鿿-ゟ゠-ヿ가-';
|
||||
|
||||
export const CJK_RANGES_REGEX = new RegExp(`[${CJK_SLUG_CHARS}]`);
|
||||
|
||||
/**
|
||||
* Page-slug segment grammar (no anchors): alnum-or-CJK lead char, then
|
||||
* alnum/CJK/hyphen continuation. Single source for validatePageSlug
|
||||
* (operations.ts), SlugRegistry's SLUG_RE, and the dream-cycle
|
||||
* SUMMARY_SLUG_RE so every slug validator shares one grammar (#738).
|
||||
*/
|
||||
export const PAGE_SLUG_SEG = `[a-z0-9${CJK_SLUG_CHARS}][a-z0-9${CJK_SLUG_CHARS}\\-]*`;
|
||||
|
||||
export const CJK_SENTENCE_DELIMITERS = ['。', '!', '?']; // 。!?
|
||||
export const CJK_CLAUSE_DELIMITERS = [';', ':', ',', '、']; // ;:,、
|
||||
|
||||
|
||||
@@ -43,10 +43,11 @@ import { serializeMarkdown, serializePageToMarkdown } from '../markdown.ts';
|
||||
import type { Page, PageType } from '../types.ts';
|
||||
import { validateSourceId } from '../utils.ts';
|
||||
import { safeSplitIndex } from '../text-safe.ts';
|
||||
import { PAGE_SLUG_SEG } from '../cjk.ts';
|
||||
|
||||
// Slug regex from validatePageSlug — kept in sync.
|
||||
// Slug grammar from validatePageSlug — shared via PAGE_SLUG_SEG (#738).
|
||||
// Used for the orchestrator-written summary index slug.
|
||||
const SUMMARY_SLUG_RE = /^[a-z0-9][a-z0-9\-]*(\/[a-z0-9][a-z0-9\-]*)*$/;
|
||||
const SUMMARY_SLUG_RE = new RegExp(`^${PAGE_SLUG_SEG}(\\/${PAGE_SLUG_SEG})*$`);
|
||||
|
||||
// ── Model context budget (D1, D5, D7, D9) ─────────────────────────────
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ import { bumpLastRetrievedAt } from './last-retrieved.ts';
|
||||
import { isSearchMode } from './search/mode.ts';
|
||||
import { stampEvidence } from './search/evidence.ts';
|
||||
import type { SearchResult } from './types.ts';
|
||||
import { CJK_SLUG_CHARS } from './cjk.ts';
|
||||
import { CJK_SLUG_CHARS, PAGE_SLUG_SEG } from './cjk.ts';
|
||||
import * as db from './db.ts';
|
||||
import { VERSION } from '../version.ts';
|
||||
import {
|
||||
@@ -162,7 +162,6 @@ export function validatePageSlug(slug: string): void {
|
||||
}
|
||||
// v0.32.7: CJK ranges (Han / Hiragana / Katakana / Hangul Syllables) allowed
|
||||
// in segments. ASCII shape rules (lead char, hyphen continuation) preserved.
|
||||
const PAGE_SLUG_SEG = `[a-z0-9${CJK_SLUG_CHARS}][a-z0-9${CJK_SLUG_CHARS}\\-]*`;
|
||||
if (!new RegExp(`^${PAGE_SLUG_SEG}(\\/${PAGE_SLUG_SEG})*$`, 'i').test(slug)) {
|
||||
throw new OperationError('invalid_params', `Invalid page_slug: ${slug} (allowed: alphanumeric, CJK, hyphens, forward-slash separated segments)`);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
import type { BrainEngine } from '../engine.ts';
|
||||
import type { PageType } from '../types.ts';
|
||||
import { PAGE_SLUG_SEG } from '../cjk.ts';
|
||||
|
||||
export interface CreateSlugInput {
|
||||
/**
|
||||
@@ -71,7 +72,9 @@ export class SlugRegistryError extends Error {
|
||||
// SlugRegistry
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const SLUG_RE = /^[a-z0-9][a-z0-9\-]*(\/[a-z0-9][a-z0-9\-]*)+$/;
|
||||
// Shares the page-slug segment grammar (incl. CJK ranges, #738) with
|
||||
// validatePageSlug; keeps this site's dir/name shape (>= 2 segments).
|
||||
const SLUG_RE = new RegExp(`^${PAGE_SLUG_SEG}(\\/${PAGE_SLUG_SEG})+$`);
|
||||
|
||||
export class SlugRegistry {
|
||||
constructor(private engine: BrainEngine) {}
|
||||
|
||||
@@ -154,28 +154,6 @@ describe('gateway.rerank() — happy path', () => {
|
||||
describe('gateway.rerank() — error classification', () => {
|
||||
beforeEach(() => configureZE());
|
||||
|
||||
test('missing required reranker API key → RerankError(auth) before HTTP call', async () => {
|
||||
configureGateway({
|
||||
reranker_model: 'zeroentropyai:zerank-2',
|
||||
env: {},
|
||||
});
|
||||
let called = false;
|
||||
__setRerankTransportForTests(async () => {
|
||||
called = true;
|
||||
return mockResp({ results: [{ index: 0, relevance_score: 0.5 }] });
|
||||
});
|
||||
|
||||
try {
|
||||
await rerank({ query: 'q', documents: ['d'] });
|
||||
throw new Error('should have thrown');
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(RerankError);
|
||||
expect((err as RerankError).reason).toBe('auth');
|
||||
expect((err as Error).message).toContain('ZEROENTROPY_API_KEY');
|
||||
expect(called).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test('401 → auth', async () => {
|
||||
__setRerankTransportForTests(async () => new Response('Unauthorized', { status: 401 }));
|
||||
try {
|
||||
|
||||
@@ -86,6 +86,12 @@ describe('#2415: loadOutputRoot validation + patterns gather scope', () => {
|
||||
expect(await loadOutputRoot(engine)).toBe('wiki');
|
||||
});
|
||||
|
||||
test('CJK root passes the slug grammar (#738)', async () => {
|
||||
await engine.setConfig('dream.synthesize.output_root', '知识/笔记');
|
||||
expect(await loadOutputRoot(engine)).toBe('知识/笔记');
|
||||
await engine.setConfig('dream.synthesize.output_root', '');
|
||||
});
|
||||
|
||||
test('patterns phase gathers reflections under the configured root', async () => {
|
||||
await engine.setConfig('dream.synthesize.output_root', 'notes');
|
||||
for (let i = 0; i < 3; i++) {
|
||||
|
||||
@@ -2,11 +2,6 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:tes
|
||||
import { mkdirSync, rmSync, writeFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { tmpdir } from 'os';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { withEnv } from './helpers/with-env.ts';
|
||||
import { logRerankFailure } from '../src/core/rerank-audit.ts';
|
||||
|
||||
describe('doctor command', () => {
|
||||
test('doctor module exports runDoctor', async () => {
|
||||
@@ -52,34 +47,6 @@ describe('doctor command', () => {
|
||||
expect(check.issues![0].action).toContain('trigger');
|
||||
});
|
||||
|
||||
test('reranker_health warns on repeated unknown rerank failures', async () => {
|
||||
const { checkRerankerHealth } = await import('../src/commands/doctor.ts');
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-rerank-doctor-'));
|
||||
try {
|
||||
await withEnv({ GBRAIN_AUDIT_DIR: tmpDir }, async () => {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
logRerankFailure({
|
||||
model: 'zeroentropyai:zerank-2',
|
||||
reason: 'unknown',
|
||||
query_hash: `unknown${i}`,
|
||||
doc_count: 30,
|
||||
error_summary: 'ZeroEntropy reranker requires ZEROENTROPY_API_KEY.',
|
||||
});
|
||||
}
|
||||
const check = await checkRerankerHealth({
|
||||
async getConfig(key: string): Promise<string | null> {
|
||||
return key === 'search.reranker.enabled' ? 'true' : null;
|
||||
},
|
||||
} as any);
|
||||
expect(check.status).toBe('warn');
|
||||
expect(check.message).toContain('unknown');
|
||||
expect(check.message).toContain('ZEROENTROPY_API_KEY');
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('runDoctor accepts null engine for filesystem-only mode', async () => {
|
||||
const { runDoctor } = await import('../src/commands/doctor.ts');
|
||||
// runDoctor should accept null engine — it runs filesystem checks only.
|
||||
|
||||
@@ -12,14 +12,9 @@
|
||||
*/
|
||||
|
||||
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { applyReranker, type RerankerOpts } from '../../src/core/search/rerank.ts';
|
||||
import { RerankError, type RerankResult } from '../../src/core/ai/gateway.ts';
|
||||
import { readRecentRerankFailures } from '../../src/core/rerank-audit.ts';
|
||||
import type { SearchResult } from '../../src/core/types.ts';
|
||||
import { withEnv } from '../helpers/with-env.ts';
|
||||
|
||||
function makeResult(slug: string, score: number, chunk: string): SearchResult {
|
||||
return {
|
||||
@@ -165,36 +160,6 @@ describe('applyReranker — fail-open on every RerankError reason', () => {
|
||||
expect(out).toEqual(results);
|
||||
});
|
||||
|
||||
test('missing gateway reranker API key fail-opens and audits auth', async () => {
|
||||
const { configureGateway } = await import('../../src/core/ai/gateway.ts');
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-rerank-search-'));
|
||||
try {
|
||||
await withEnv({ GBRAIN_AUDIT_DIR: tmpDir }, async () => {
|
||||
configureGateway({
|
||||
reranker_model: 'zeroentropyai:zerank-2',
|
||||
env: {},
|
||||
});
|
||||
|
||||
const results = [makeResult('a', 1.0, 'doc a')];
|
||||
const out = await applyReranker('q', results, {
|
||||
enabled: true,
|
||||
topNIn: 1,
|
||||
topNOut: null,
|
||||
model: 'zeroentropyai:zerank-2',
|
||||
});
|
||||
|
||||
expect(out).toEqual(results);
|
||||
const failures = readRecentRerankFailures(1);
|
||||
expect(failures).toHaveLength(1);
|
||||
expect(failures[0]!.reason).toBe('auth');
|
||||
expect(failures[0]!.error_summary).toContain('ZEROENTROPY_API_KEY');
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
configureGateway({ env: { ZEROENTROPY_API_KEY: 'test-key' } });
|
||||
}
|
||||
});
|
||||
|
||||
test('fail-open on non-RerankError throw too', async () => {
|
||||
const results = [makeResult('a', 1.0, 'a')];
|
||||
const opts: RerankerOpts = {
|
||||
|
||||
@@ -203,6 +203,17 @@ describe('SlugRegistry', () => {
|
||||
})).rejects.toThrow(SlugRegistryError);
|
||||
});
|
||||
|
||||
test('create accepts CJK slugs (#738)', async () => {
|
||||
const reg = new SlugRegistry(engine);
|
||||
const r = await reg.create({
|
||||
desiredSlug: '知识/品牌圣经',
|
||||
displayName: '品牌圣经',
|
||||
type: 'note',
|
||||
});
|
||||
expect(r.slug).toBe('知识/品牌圣经');
|
||||
expect(r.exact).toBe(true);
|
||||
});
|
||||
|
||||
test('create throws on invalid slug', async () => {
|
||||
const reg = new SlugRegistry(engine);
|
||||
await expect(reg.create({
|
||||
|
||||
Reference in New Issue
Block a user