mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-16 09:52:22 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa45398d83 |
-64
@@ -24,7 +24,6 @@ import type { GBrainConfig } from './core/config.ts';
|
||||
import type { AIGatewayConfig } from './core/ai/types.ts';
|
||||
import type { BrainEngine } from './core/engine.ts';
|
||||
import { operations, OperationError } from './core/operations.ts';
|
||||
import { resolveSourceIdEngineFree } from './core/source-resolver.ts';
|
||||
import { formatVolunteeredPage } from './core/context/volunteer.ts';
|
||||
import type { Operation, OperationContext } from './core/operations.ts';
|
||||
import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict } from './core/cli-force-exit.ts';
|
||||
@@ -383,15 +382,6 @@ async function main() {
|
||||
if (op.localOnly) {
|
||||
refuseThinClient(command, cfgPre!.remote_mcp!.mcp_url);
|
||||
}
|
||||
// #2098: the local path resolves --source / GBRAIN_SOURCE / .gbrain-source
|
||||
// inside makeContext (ctx.sourceId), which this route never reaches — so
|
||||
// scope must be mapped onto the op's source_id wire param before the call.
|
||||
try {
|
||||
applyThinClientSourceScope(op, params);
|
||||
} catch (e: unknown) {
|
||||
console.error(e instanceof Error ? e.message : String(e));
|
||||
process.exit(1);
|
||||
}
|
||||
await runThinClientRouted(op, params, cfgPre!, cliOpts);
|
||||
return;
|
||||
}
|
||||
@@ -812,60 +802,6 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* #2098: thin-client source scoping. Locally, --source / GBRAIN_SOURCE /
|
||||
* .gbrain-source resolve to ctx.sourceId in makeContext; the thin-client
|
||||
* route short-circuits before that, so `gbrain query --source X` against a
|
||||
* remote brain silently searched unscoped. This runs the engine-free tiers
|
||||
* (flag → env → dotfile; the DB-backed tiers can't run without an engine —
|
||||
* the server's grant scoping covers the rest) and maps the result onto the
|
||||
* op's `source_id` wire param.
|
||||
*
|
||||
* Ops that declare their OWN `source` param (facts add, etc.) are left
|
||||
* untouched — their --source is an op param, not scope. An explicit --source
|
||||
* on an op with no source_id wire param throws (loud beats silent drop);
|
||||
* ambient env/dotfile scope with nowhere to send it is ignored, matching the
|
||||
* pre-fix behavior for non-scopeable ops. Exported for tests.
|
||||
*/
|
||||
// Ops whose `source_id` wire param is NOT read-scope semantics: get_skill's
|
||||
// source_id flips the lookup from host catalog to brain-resident-pack
|
||||
// (getResidentSkillDetail). Ambient env/dotfile scope must never leak into
|
||||
// these; an explicit --source-id still passes through untouched above.
|
||||
const NON_SCOPE_SOURCE_ID_OPS = new Set(['get_skill']);
|
||||
|
||||
export function applyThinClientSourceScope(
|
||||
op: Operation,
|
||||
params: Record<string, unknown>,
|
||||
cwd?: string,
|
||||
): void {
|
||||
if ('source' in op.params) return; // the op owns --source; not a scope flag
|
||||
const explicit = typeof params.source === 'string' && params.source.length > 0
|
||||
? (params.source as string)
|
||||
: null;
|
||||
delete params.source; // never a wire param on these ops — don't leak it
|
||||
// Explicit per-call scope already on the wire wins over ambient tiers.
|
||||
if (params.source_id !== undefined || params.all_sources === true) {
|
||||
if (explicit) {
|
||||
throw new Error('Pass either --source or --source-id/--all-sources, not both.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
const resolved = resolveSourceIdEngineFree(explicit, cwd);
|
||||
if (!resolved) return;
|
||||
if (!('source_id' in op.params) || NON_SCOPE_SOURCE_ID_OPS.has(op.name)) {
|
||||
if (explicit) {
|
||||
const hint = NON_SCOPE_SOURCE_ID_OPS.has(op.name)
|
||||
? `(its source_id parameter is not a scope filter; pass --source-id explicitly if you mean it)`
|
||||
: `(the remote op has no source_id parameter; the server scopes it to your grant)`;
|
||||
throw new Error(
|
||||
`gbrain ${op.cliHints?.name || op.name} does not accept --source on a thin-client install ${hint}.`,
|
||||
);
|
||||
}
|
||||
return; // ambient env/dotfile scope with nowhere to send it
|
||||
}
|
||||
params.source_id = resolved;
|
||||
}
|
||||
|
||||
async function makeContext(engine: BrainEngine, params: Record<string, unknown>): Promise<OperationContext> {
|
||||
// v0.31.8 (D11): resolve sourceId via the canonical 6-tier chain. Honors
|
||||
// --source / GBRAIN_SOURCE / .gbrain-source / path-match / brain default /
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
*/
|
||||
|
||||
import type { BrainEngine } from './engine.ts';
|
||||
import { PGVECTOR_HNSW_VECTOR_MAX_DIMS } from './vector-index.ts';
|
||||
import { PGVECTOR_HNSW_VECTOR_MAX_DIMS, hnswMaxDimsForType } from './vector-index.ts';
|
||||
import { gbrainPath } from './config.ts';
|
||||
import { resolveRecipe } from './ai/model-resolver.ts';
|
||||
import type { Recipe } from './ai/types.ts';
|
||||
@@ -609,6 +609,17 @@ export function buildFactsAlterRecipe(
|
||||
const opclass = columnType === 'halfvec' ? 'halfvec_cosine_ops' : 'vector_cosine_ops';
|
||||
const targetType = columnType === 'halfvec' ? `halfvec(${configuredDims})` : `vector(${configuredDims})`;
|
||||
const dimsChanged = columnDims !== configuredDims;
|
||||
const hnswMaxDims = hnswMaxDimsForType(columnType);
|
||||
const indexLines = configuredDims <= hnswMaxDims
|
||||
? [
|
||||
`CREATE INDEX idx_facts_embedding_hnsw`,
|
||||
` ON facts USING hnsw (embedding ${opclass})`,
|
||||
` WHERE embedding IS NOT NULL AND expired_at IS NULL;`,
|
||||
]
|
||||
: [
|
||||
`-- Skip reindex. ${columnType}(${configuredDims}) exceeds pgvector's HNSW cap of ${hnswMaxDims};`,
|
||||
`-- fact similarity falls back to exact scans.`,
|
||||
];
|
||||
return [
|
||||
`-- ALTER ${columnType}(${columnDims}) → ${columnType}(${configuredDims}) on indexed column.`,
|
||||
`-- HOLD a maintenance window: this rewrites every row's embedding.`,
|
||||
@@ -629,9 +640,7 @@ export function buildFactsAlterRecipe(
|
||||
: []),
|
||||
`ALTER TABLE facts ALTER COLUMN embedding TYPE ${targetType}`,
|
||||
` USING embedding::${targetType};`,
|
||||
`CREATE INDEX idx_facts_embedding_hnsw`,
|
||||
` ON facts USING hnsw (embedding ${opclass})`,
|
||||
` WHERE embedding IS NOT NULL AND expired_at IS NULL;`,
|
||||
...indexLines,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
|
||||
+21
-8
@@ -1,6 +1,7 @@
|
||||
import type { BrainEngine } from './engine.ts';
|
||||
import { slugifyPath } from './sync.ts';
|
||||
import { getFtsLanguage } from './fts-language.ts';
|
||||
import { hnswMaxDimsForType } from './vector-index.ts';
|
||||
|
||||
/**
|
||||
* Schema migrations — run automatically on initSchema().
|
||||
@@ -2276,11 +2277,19 @@ export const MIGRATIONS: Migration[] = [
|
||||
useHalfvec = true;
|
||||
}
|
||||
|
||||
const vecType = useHalfvec ? 'HALFVEC' : 'VECTOR';
|
||||
const columnType = useHalfvec ? 'halfvec' : 'vector';
|
||||
const vecType = columnType.toUpperCase();
|
||||
// HNSW operator class must match the column type:
|
||||
// VECTOR(n) → vector_cosine_ops
|
||||
// HALFVEC(n) → halfvec_cosine_ops
|
||||
const opclass = useHalfvec ? 'halfvec_cosine_ops' : 'vector_cosine_ops';
|
||||
const hnswMaxDims = hnswMaxDimsForType(columnType);
|
||||
const factsEmbeddingIndexSql = embeddingDim <= hnswMaxDims
|
||||
? `CREATE INDEX IF NOT EXISTS idx_facts_embedding_hnsw
|
||||
ON facts USING hnsw (embedding ${opclass})
|
||||
WHERE embedding IS NOT NULL AND expired_at IS NULL;`
|
||||
: `-- idx_facts_embedding_hnsw skipped: pgvector HNSW ${columnType} indexes support
|
||||
-- at most ${hnswMaxDims} dimensions; exact vector scans remain available.`;
|
||||
// FK to sources is added in a separate ALTER TABLE rather than inline
|
||||
// on the column. Inline `REFERENCES` worked on PGLite but silently
|
||||
// got dropped by postgres.js's `unsafe()` multi-statement path on
|
||||
@@ -2354,9 +2363,7 @@ export const MIGRATIONS: Migration[] = [
|
||||
ON facts(source_id, entity_slug)
|
||||
WHERE consolidated_at IS NULL AND expired_at IS NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_facts_embedding_hnsw
|
||||
ON facts USING hnsw (embedding ${opclass})
|
||||
WHERE embedding IS NOT NULL AND expired_at IS NULL;
|
||||
${factsEmbeddingIndexSql}
|
||||
`;
|
||||
|
||||
await engine.runMigration(40, factsDDL);
|
||||
@@ -2870,8 +2877,16 @@ export const MIGRATIONS: Migration[] = [
|
||||
useHalfvec = true;
|
||||
}
|
||||
|
||||
const vecType = useHalfvec ? 'HALFVEC' : 'VECTOR';
|
||||
const columnType = useHalfvec ? 'halfvec' : 'vector';
|
||||
const vecType = columnType.toUpperCase();
|
||||
const opclass = useHalfvec ? 'halfvec_cosine_ops' : 'vector_cosine_ops';
|
||||
const hnswMaxDims = hnswMaxDimsForType(columnType);
|
||||
const queryCacheEmbeddingIndexSql = embeddingDim <= hnswMaxDims
|
||||
? `CREATE INDEX IF NOT EXISTS idx_query_cache_embedding_hnsw
|
||||
ON query_cache USING hnsw (embedding ${opclass})
|
||||
WHERE embedding IS NOT NULL;`
|
||||
: `-- idx_query_cache_embedding_hnsw skipped: pgvector HNSW ${columnType} indexes support
|
||||
-- at most ${hnswMaxDims} dimensions; exact vector scans remain available.`;
|
||||
|
||||
const ddl = `
|
||||
CREATE TABLE IF NOT EXISTS query_cache (
|
||||
@@ -2890,9 +2905,7 @@ export const MIGRATIONS: Migration[] = [
|
||||
CREATE INDEX IF NOT EXISTS idx_query_cache_source_created
|
||||
ON query_cache(source_id, created_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_query_cache_embedding_hnsw
|
||||
ON query_cache USING hnsw (embedding ${opclass})
|
||||
WHERE embedding IS NOT NULL;
|
||||
${queryCacheEmbeddingIndexSql}
|
||||
`;
|
||||
|
||||
await engine.runMigration(55, ddl);
|
||||
|
||||
@@ -160,33 +160,6 @@ export async function resolveSourceId(
|
||||
return 'default';
|
||||
}
|
||||
|
||||
/**
|
||||
* Engine-free tiers (1-3) of the resolution chain: explicit flag →
|
||||
* GBRAIN_SOURCE env → .gbrain-source dotfile walk. Used by the thin-client
|
||||
* CLI path (#2098), which has no local engine to run tiers 4-6 or
|
||||
* assertSourceExists against — the remote server enforces existence + grant.
|
||||
* Returns null when no engine-free tier fires.
|
||||
*/
|
||||
export function resolveSourceIdEngineFree(
|
||||
explicit: string | null | undefined,
|
||||
cwd: string = process.cwd(),
|
||||
): string | null {
|
||||
if (explicit) {
|
||||
if (!SOURCE_ID_RE.test(explicit)) {
|
||||
throw new Error(`Invalid --source value "${explicit}". Must match [a-z0-9-]{1,32}.`);
|
||||
}
|
||||
return explicit;
|
||||
}
|
||||
const env = process.env.GBRAIN_SOURCE;
|
||||
if (env && env.length > 0) {
|
||||
if (!SOURCE_ID_RE.test(env)) {
|
||||
throw new Error(`Invalid GBRAIN_SOURCE value "${env}". Must match [a-z0-9-]{1,32}.`);
|
||||
}
|
||||
return env;
|
||||
}
|
||||
return readDotfileWalk(cwd);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the id of the SINGLE registered non-default source with a
|
||||
* local_path, when exactly one such row exists. Returns null when:
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
import type { BrainEngine } from './engine.ts';
|
||||
|
||||
export const PGVECTOR_HNSW_VECTOR_MAX_DIMS = 2000;
|
||||
export const PGVECTOR_HNSW_HALFVEC_MAX_DIMS = 4000;
|
||||
|
||||
const CHUNK_EMBEDDING_HNSW_INDEX =
|
||||
'CREATE INDEX IF NOT EXISTS idx_chunks_embedding ON content_chunks USING hnsw (embedding vector_cosine_ops);';
|
||||
@@ -29,6 +30,10 @@ export function chunkEmbeddingIndexSql(dims: number): string {
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
export function hnswMaxDimsForType(columnType: 'vector' | 'halfvec'): number {
|
||||
return columnType === 'halfvec' ? PGVECTOR_HNSW_HALFVEC_MAX_DIMS : PGVECTOR_HNSW_VECTOR_MAX_DIMS;
|
||||
}
|
||||
|
||||
export function applyChunkEmbeddingIndexPolicy(sql: string, dims: number): string {
|
||||
return sql.replaceAll(CHUNK_EMBEDDING_HNSW_INDEX, chunkEmbeddingIndexSql(dims));
|
||||
}
|
||||
|
||||
@@ -122,9 +122,9 @@ describe('buildFactsAlterRecipe', () => {
|
||||
});
|
||||
|
||||
test('vector recipe uses vector_cosine_ops + vector(N) USING cast', () => {
|
||||
const recipe = buildFactsAlterRecipe(1024, 2048, 'vector');
|
||||
expect(recipe).toContain('vector(2048)');
|
||||
expect(recipe).toContain('USING embedding::vector(2048)');
|
||||
const recipe = buildFactsAlterRecipe(1024, 1536, 'vector');
|
||||
expect(recipe).toContain('vector(1536)');
|
||||
expect(recipe).toContain('USING embedding::vector(1536)');
|
||||
expect(recipe).toContain('vector_cosine_ops');
|
||||
expect(recipe).not.toContain('halfvec_cosine_ops');
|
||||
});
|
||||
@@ -163,6 +163,14 @@ describe('buildFactsAlterRecipe', () => {
|
||||
expect(recipe).not.toContain('UPDATE facts SET embedding = NULL');
|
||||
expect(recipe).toContain('USING embedding::vector(1536)');
|
||||
});
|
||||
|
||||
test('halfvec recipe skips HNSW rebuild above pgvector cap', () => {
|
||||
const recipe = buildFactsAlterRecipe(1536, 4096, 'halfvec');
|
||||
expect(recipe).toContain('halfvec(4096)');
|
||||
expect(recipe).toContain('Skip reindex');
|
||||
expect(recipe).toContain("exceeds pgvector's HNSW cap of 4000");
|
||||
expect(recipe).not.toMatch(/CREATE INDEX idx_facts_embedding_hnsw[\s\S]*USING hnsw/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('FactsEmbeddingDimMismatchError', () => {
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
|
||||
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
||||
import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
|
||||
|
||||
let engine: PGLiteEngine;
|
||||
|
||||
@@ -93,4 +94,60 @@ describe('migration v45 facts column shape', () => {
|
||||
);
|
||||
expect(after[0].udt_name).toBe(before[0].udt_name);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('migration v45/v55 large-dim HNSW policy', () => {
|
||||
let largeDimEngine: PGLiteEngine;
|
||||
|
||||
beforeAll(async () => {
|
||||
configureGateway({
|
||||
embedding_model: 'litellm:custom-4096d',
|
||||
embedding_dimensions: 4096,
|
||||
env: { ...process.env },
|
||||
});
|
||||
|
||||
largeDimEngine = new PGLiteEngine();
|
||||
await largeDimEngine.connect({});
|
||||
await largeDimEngine.initSchema();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await largeDimEngine.disconnect();
|
||||
resetGateway();
|
||||
});
|
||||
|
||||
test('4096d init skips unsupported HNSW indexes but keeps vector columns', async () => {
|
||||
const formatRows = await largeDimEngine.executeRaw<{ format_type: string }>(
|
||||
`SELECT format_type(atttypid, atttypmod) AS format_type
|
||||
FROM pg_attribute
|
||||
WHERE attrelid = 'facts'::regclass AND attname = 'embedding'`,
|
||||
);
|
||||
expect(formatRows[0]?.format_type).toMatch(/(halfvec|vector)\(4096\)/);
|
||||
|
||||
const indexRows = await largeDimEngine.executeRaw<{ exists: boolean }>(
|
||||
`SELECT EXISTS (
|
||||
SELECT 1 FROM pg_indexes
|
||||
WHERE tablename = 'facts'
|
||||
AND indexname = 'idx_facts_embedding_hnsw'
|
||||
) AS exists`,
|
||||
);
|
||||
expect(indexRows[0]?.exists).toBe(false);
|
||||
|
||||
const queryCacheFormatRows = await largeDimEngine.executeRaw<{ format_type: string }>(
|
||||
`SELECT format_type(atttypid, atttypmod) AS format_type
|
||||
FROM pg_attribute
|
||||
WHERE attrelid = 'query_cache'::regclass AND attname = 'embedding'`,
|
||||
);
|
||||
expect(queryCacheFormatRows[0]?.format_type).toMatch(/(halfvec|vector)\(4096\)/);
|
||||
|
||||
const queryCacheIndexRows = await largeDimEngine.executeRaw<{ exists: boolean }>(
|
||||
`SELECT EXISTS (
|
||||
SELECT 1 FROM pg_indexes
|
||||
WHERE tablename = 'query_cache'
|
||||
AND indexname = 'idx_query_cache_embedding_hnsw'
|
||||
) AS exists`,
|
||||
);
|
||||
expect(queryCacheIndexRows[0]?.exists).toBe(false);
|
||||
}, 60000);
|
||||
});
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
/**
|
||||
* #2098: thin-client routing dropped --source / GBRAIN_SOURCE / .gbrain-source.
|
||||
*
|
||||
* The local CLI path resolves source scope in makeContext (ctx.sourceId); the
|
||||
* thin-client route short-circuits before that and sent params verbatim, so
|
||||
* `gbrain query --source X` against a remote brain silently searched unscoped
|
||||
* (the server op ignores the unknown `source` key).
|
||||
*
|
||||
* applyThinClientSourceScope runs the engine-free tiers (flag → env → dotfile)
|
||||
* and maps the result onto the op's `source_id` wire param. These tests fail
|
||||
* without the fix (params.source_id stays undefined / params.source leaks).
|
||||
*/
|
||||
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { tmpdir } from 'os';
|
||||
import { applyThinClientSourceScope, parseOpArgs } from '../src/cli.ts';
|
||||
import { operationsByName } from '../src/core/operations.ts';
|
||||
import { withEnv } from './helpers/with-env.ts';
|
||||
|
||||
const queryOp = operationsByName.query;
|
||||
|
||||
describe('applyThinClientSourceScope (#2098)', () => {
|
||||
test('--source maps onto the query op wire param source_id', async () => {
|
||||
await withEnv({ GBRAIN_SOURCE: undefined }, () => {
|
||||
const params = parseOpArgs(queryOp, ['find things', '--source', 'wiki']);
|
||||
expect(params.source).toBe('wiki'); // pre-fix state: wrong key
|
||||
applyThinClientSourceScope(queryOp, params, '/');
|
||||
expect(params.source_id).toBe('wiki');
|
||||
expect('source' in params).toBe(false); // never leaks the unknown key
|
||||
});
|
||||
});
|
||||
|
||||
test('GBRAIN_SOURCE env tier fires when no flag is passed', async () => {
|
||||
await withEnv({ GBRAIN_SOURCE: 'gstack' }, () => {
|
||||
const params = parseOpArgs(queryOp, ['find things']);
|
||||
applyThinClientSourceScope(queryOp, params, '/');
|
||||
expect(params.source_id).toBe('gstack');
|
||||
});
|
||||
});
|
||||
|
||||
test('.gbrain-source dotfile tier fires when flag and env are absent', async () => {
|
||||
await withEnv({ GBRAIN_SOURCE: undefined }, () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), 'gbrain-thin-scope-'));
|
||||
try {
|
||||
writeFileSync(join(tmp, '.gbrain-source'), 'essays\n');
|
||||
const params = parseOpArgs(queryOp, ['find things']);
|
||||
applyThinClientSourceScope(queryOp, params, tmp);
|
||||
expect(params.source_id).toBe('essays');
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('explicit --source-id on the wire wins over ambient env scope', async () => {
|
||||
await withEnv({ GBRAIN_SOURCE: 'gstack' }, () => {
|
||||
const params = parseOpArgs(queryOp, ['find things', '--source-id', 'wiki']);
|
||||
applyThinClientSourceScope(queryOp, params, '/');
|
||||
expect(params.source_id).toBe('wiki');
|
||||
});
|
||||
});
|
||||
|
||||
test('--source together with --source-id is rejected loudly', async () => {
|
||||
await withEnv({ GBRAIN_SOURCE: undefined }, () => {
|
||||
const params = parseOpArgs(queryOp, ['q', '--source', 'a', '--source-id', 'b']);
|
||||
expect(() => applyThinClientSourceScope(queryOp, params, '/')).toThrow(/not both/);
|
||||
});
|
||||
});
|
||||
|
||||
test('invalid --source value is rejected loudly', async () => {
|
||||
await withEnv({ GBRAIN_SOURCE: undefined }, () => {
|
||||
const params = parseOpArgs(queryOp, ['q', '--source', 'Bad_Value!']);
|
||||
expect(() => applyThinClientSourceScope(queryOp, params, '/')).toThrow(/Invalid --source/);
|
||||
});
|
||||
});
|
||||
|
||||
test('--source on an op with no source_id wire param errors instead of silently dropping', async () => {
|
||||
await withEnv({ GBRAIN_SOURCE: undefined }, () => {
|
||||
const op = operationsByName.add_tag;
|
||||
expect('source_id' in op.params).toBe(false);
|
||||
const params = { slug: 'x', tag: 'y', source: 'wiki' };
|
||||
expect(() => applyThinClientSourceScope(op, params, '/')).toThrow(/--source/);
|
||||
});
|
||||
});
|
||||
|
||||
test('ambient env scope on an op with no source_id wire param is ignored (no throw)', async () => {
|
||||
await withEnv({ GBRAIN_SOURCE: 'wiki' }, () => {
|
||||
const op = operationsByName.add_tag;
|
||||
const params: Record<string, unknown> = { slug: 'x', tag: 'y' };
|
||||
applyThinClientSourceScope(op, params, '/');
|
||||
expect(params.source_id).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
test('ops that declare their OWN source param are left untouched', async () => {
|
||||
await withEnv({ GBRAIN_SOURCE: undefined }, () => {
|
||||
const op = operationsByName.put_raw_data;
|
||||
expect('source' in op.params).toBe(true);
|
||||
const params: Record<string, unknown> = { slug: 'x', source: 'crustdata', data: {} };
|
||||
applyThinClientSourceScope(op, params, '/');
|
||||
expect(params.source).toBe('crustdata');
|
||||
expect(params.source_id).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
test('get_skill: ambient scope never leaks into its non-scope source_id param', async () => {
|
||||
await withEnv({ GBRAIN_SOURCE: 'wiki' }, () => {
|
||||
const op = operationsByName.get_skill;
|
||||
expect('source_id' in op.params).toBe(true); // has the param, but it is a mode switch
|
||||
const params: Record<string, unknown> = { name: 'ingest' };
|
||||
applyThinClientSourceScope(op, params, '/');
|
||||
expect(params.source_id).toBeUndefined(); // would flip host catalog → brain-pack lookup
|
||||
});
|
||||
});
|
||||
|
||||
test('get_skill: explicit --source errors instead of masquerading as --source-id', async () => {
|
||||
await withEnv({ GBRAIN_SOURCE: undefined }, () => {
|
||||
const op = operationsByName.get_skill;
|
||||
const params: Record<string, unknown> = { name: 'ingest', source: 'wiki' };
|
||||
expect(() => applyThinClientSourceScope(op, params, '/')).toThrow(/--source-id/);
|
||||
});
|
||||
});
|
||||
|
||||
test('get_skill: explicit --source-id passes through untouched', async () => {
|
||||
await withEnv({ GBRAIN_SOURCE: 'gstack' }, () => {
|
||||
const op = operationsByName.get_skill;
|
||||
const params: Record<string, unknown> = { name: 'ingest', source_id: 'wiki' };
|
||||
applyThinClientSourceScope(op, params, '/');
|
||||
expect(params.source_id).toBe('wiki');
|
||||
});
|
||||
});
|
||||
|
||||
test('no scope from any tier leaves params unchanged', async () => {
|
||||
await withEnv({ GBRAIN_SOURCE: undefined }, () => {
|
||||
const params = parseOpArgs(queryOp, ['find things']);
|
||||
applyThinClientSourceScope(queryOp, params, '/');
|
||||
expect(params.source_id).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user