mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-15 17:32:37 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58683eb9ac |
@@ -19,7 +19,7 @@
|
||||
*/
|
||||
|
||||
import type { BrainEngine } from '../core/engine.ts';
|
||||
import { runPhaseCalibrationProfile } from '../core/cycle/calibration-profile.ts';
|
||||
import { resolveCalibrationHolder, runPhaseCalibrationProfile } from '../core/cycle/calibration-profile.ts';
|
||||
import { sourceScopeOpts, type OperationContext } from '../core/operations.ts';
|
||||
import type { GBrainConfig } from '../core/config.ts';
|
||||
import { GBrainError } from '../core/types.ts';
|
||||
@@ -167,7 +167,7 @@ export async function runCalibration(
|
||||
config: GBrainConfig,
|
||||
): Promise<void> {
|
||||
const { opts } = parseArgs(args);
|
||||
const holder = opts.holder ?? 'garry';
|
||||
const holder = await resolveCalibrationHolder(engine, opts.holder);
|
||||
// Resolve --source / GBRAIN_SOURCE / .gbrain-source so the (now reachable, #2035)
|
||||
// calibration command targets the right source in a multi-source brain instead
|
||||
// of always reading `default`. No signal → 'default' (prior behavior).
|
||||
@@ -253,14 +253,14 @@ export async function getCalibrationProfileOp(
|
||||
ctx: OperationContext,
|
||||
params: { holder?: string },
|
||||
): Promise<CalibrationProfileRow | null> {
|
||||
const holder = params.holder ?? 'garry';
|
||||
if (typeof holder !== 'string' || holder.length === 0) {
|
||||
if (params.holder !== undefined && (typeof params.holder !== 'string' || params.holder.length === 0)) {
|
||||
throw new GBrainError(
|
||||
'INVALID_HOLDER',
|
||||
'get_calibration_profile.holder must be a non-empty string',
|
||||
'pass holder="<slug>" or omit to default to "garry"',
|
||||
'pass holder="<slug>" or omit to default to the calibration.user_holder config (then "garry")',
|
||||
);
|
||||
}
|
||||
const holder = await resolveCalibrationHolder(ctx.engine, params.holder);
|
||||
const scope = sourceScopeOpts(ctx);
|
||||
return getLatestProfile(ctx.engine, { holder, ...scope });
|
||||
}
|
||||
|
||||
+1
-14
@@ -1,5 +1,5 @@
|
||||
import type { BrainEngine } from '../core/engine.ts';
|
||||
import { embedBatch, currentEmbeddingSignature, resolveEmbeddingModelLabel } from '../core/embedding.ts';
|
||||
import { embedBatch, currentEmbeddingSignature } from '../core/embedding.ts';
|
||||
import type { ChunkInput } from '../core/types.ts';
|
||||
import { chunkText } from '../core/chunkers/recursive.ts';
|
||||
import { createProgress, type ProgressReporter } from '../core/progress.ts';
|
||||
@@ -581,16 +581,11 @@ async function embedPage(
|
||||
for (let j = 0; j < toEmbed.length; j++) {
|
||||
embeddingMap.set(toEmbed[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
// #1717: label each (re)embedded chunk with the model that actually
|
||||
// produced its vector. Preserved chunks (not re-embedded this pass) keep
|
||||
// their existing model so a mixed-model page isn't relabeled wholesale.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
const updated: ChunkInput[] = chunks.map(c => ({
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
embedding: embeddingMap.get(c.chunk_index),
|
||||
model: embeddingMap.has(c.chunk_index) && embedModelLabel ? embedModelLabel : c.model,
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
}));
|
||||
|
||||
@@ -722,16 +717,12 @@ async function embedAll(
|
||||
for (let j = 0; j < toEmbed.length; j++) {
|
||||
embeddingMap.set(toEmbed[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
// #1717: stamp the resolved embedding model on (re)embedded chunks;
|
||||
// preserve the existing model on chunks left untouched.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
// Preserve ALL chunks, only update embeddings for stale ones
|
||||
const updated: ChunkInput[] = chunks.map(c => ({
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
embedding: embeddingMap.get(c.chunk_index) ?? undefined,
|
||||
model: embeddingMap.has(c.chunk_index) && embedModelLabel ? embedModelLabel : c.model,
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
}));
|
||||
await observed(pacer, () => engine.upsertChunks(page.slug, updated, pageOpts));
|
||||
@@ -1021,15 +1012,11 @@ async function embedAllStale(
|
||||
for (let j = 0; j < stale.length; j++) {
|
||||
staleIdxToEmbedding.set(stale[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
// #1717: label the re-embedded (stale) chunks with the resolved
|
||||
// model; preserve the existing model on the non-stale chunks.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
const merged: ChunkInput[] = existing.map(c => ({
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
embedding: staleIdxToEmbedding.get(c.chunk_index) ?? undefined,
|
||||
model: staleIdxToEmbedding.has(c.chunk_index) && embedModelLabel ? embedModelLabel : c.model,
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
}));
|
||||
await observed(pacer, () => engine.upsertChunks(slug, merged, { sourceId: keySourceId }));
|
||||
|
||||
@@ -928,6 +928,10 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
|
||||
// Emotional weight (v0.29)
|
||||
'emotional_weight.high_tags',
|
||||
'emotional_weight.user_holder',
|
||||
// Calibration holder (#1726): persistent default for the nightly
|
||||
// calibration_profile phase + `gbrain calibration`, symmetric with
|
||||
// emotional_weight.user_holder. Falls back to 'garry' when unset.
|
||||
'calibration.user_holder',
|
||||
// Cycle phase config
|
||||
'cycle.grade_takes.write_gstack_learnings',
|
||||
// Content sanity (v0.41)
|
||||
|
||||
@@ -96,7 +96,7 @@ export type PatternStatementsGenerator = (input: {
|
||||
export type BiasTagsGenerator = (patterns: string[]) => Promise<string[]>;
|
||||
|
||||
export interface CalibrationProfileOpts extends BasePhaseOpts {
|
||||
/** Holder to generate the profile for. Default 'garry'. */
|
||||
/** Holder to generate the profile for. Default: `calibration.user_holder` config, then 'garry'. */
|
||||
holder?: string;
|
||||
/** Inject the patterns generator (tests). */
|
||||
patternsGenerator?: PatternStatementsGenerator;
|
||||
@@ -194,6 +194,26 @@ export function parseBiasTagsOutput(raw: string): string[] {
|
||||
.slice(0, 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* #1726: resolve the calibration holder. Explicit param wins, then the
|
||||
* persistent `calibration.user_holder` config key (symmetric with
|
||||
* emotional_weight.user_holder), then the legacy 'garry' default. Fail-open:
|
||||
* a missing config table / mock engine without getConfig falls through.
|
||||
*/
|
||||
export async function resolveCalibrationHolder(
|
||||
engine: BrainEngine,
|
||||
explicit?: string,
|
||||
): Promise<string> {
|
||||
if (explicit) return explicit;
|
||||
try {
|
||||
const configured = await engine.getConfig('calibration.user_holder');
|
||||
if (configured && configured.trim().length > 0) return configured.trim();
|
||||
} catch {
|
||||
// Config unavailable — use the legacy default.
|
||||
}
|
||||
return 'garry';
|
||||
}
|
||||
|
||||
/** Pick the "loudest" pattern slot for the template fallback. */
|
||||
function pickFallbackSlots(scorecard: TakesScorecard): PatternStatementSlots {
|
||||
if (!scorecard || scorecard.resolved === 0) {
|
||||
@@ -227,7 +247,7 @@ class CalibrationProfilePhase extends BaseCyclePhase {
|
||||
_ctx: OperationContext,
|
||||
opts: CalibrationProfileOpts,
|
||||
): Promise<{ summary: string; details: Record<string, unknown>; status?: PhaseStatus }> {
|
||||
const holder = opts.holder ?? 'garry';
|
||||
const holder = await resolveCalibrationHolder(engine, opts.holder);
|
||||
const promptVersion = opts.promptVersion ?? CALIBRATION_PROFILE_PROMPT_VERSION;
|
||||
const modelId = opts.model ?? TIER_DEFAULTS.reasoning;
|
||||
const gradeCompletion = opts.gradeCompletion ?? 1.0;
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
import type { BrainEngine } from './engine.ts';
|
||||
import type { ChunkInput } from './types.ts';
|
||||
import { embedBatchWithBackoff } from '../commands/embed.ts';
|
||||
import { resolveEmbeddingModelLabel } from './embedding.ts';
|
||||
import { type DbPacer, createNoopPacer, observed } from './db-pacer.ts';
|
||||
import { AbortError } from './abort-check.ts';
|
||||
|
||||
@@ -201,17 +200,11 @@ export async function embedStaleForSource(
|
||||
for (let j = 0; j < stale.length; j++) {
|
||||
staleIdxToEmbedding.set(stale[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
// #1717: label re-embedded chunks with the model that produced the
|
||||
// vector; preserved chunks keep their existing model. Without this,
|
||||
// upsertChunks falls back to DEFAULT_EMBEDDING_MODEL for every chunk
|
||||
// (the same mislabel the embed.ts paths fixed).
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
const merged: ChunkInput[] = existing.map((c) => ({
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
embedding: staleIdxToEmbedding.get(c.chunk_index) ?? undefined,
|
||||
model: staleIdxToEmbedding.has(c.chunk_index) && embedModelLabel ? embedModelLabel : c.model,
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
// Carry through per-chunk metadata. upsertChunks writes these as
|
||||
// EXCLUDED.<col> (not COALESCE), so omitting them here resets image
|
||||
|
||||
@@ -113,21 +113,6 @@ export async function embedBatch(
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the embedding model label (`provider:model`) to stamp onto
|
||||
* `content_chunks.model`, so each chunk records the model that actually
|
||||
* produced its vector instead of the engine's hardcoded default (#1717).
|
||||
* Returns undefined if the gateway is unconfigured; callers then fall back
|
||||
* to the chunk's existing model rather than mislabeling it.
|
||||
*/
|
||||
export function resolveEmbeddingModelLabel(): string | undefined {
|
||||
try {
|
||||
return gatewayGetModel();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Currently-configured embedding model (short form without provider prefix). */
|
||||
export function getEmbeddingModelName(): string {
|
||||
return gatewayGetModel().split(':').slice(1).join(':') || 'text-embedding-3-large';
|
||||
|
||||
@@ -68,11 +68,14 @@ export async function extractTimelineFromMeetings(
|
||||
// 1. Fetch all meeting pages (one round-trip).
|
||||
const sourceFilter = opts.sourceIdFilter ? `AND source_id = $1` : '';
|
||||
const meetingParams = opts.sourceIdFilter ? [opts.sourceIdFilter] : [];
|
||||
// #2109: gbrain-base-v2's unify-types catch-all retypes meeting pages to
|
||||
// `note` with frontmatter.legacy_type = 'meeting'. Match both spellings so
|
||||
// the extractor keeps working on migrated (v2) brains, not just v1 ones.
|
||||
const meetings = await engine.executeRaw<MeetingRow>(
|
||||
`SELECT slug, source_id, title, effective_date, updated_at,
|
||||
compiled_truth, COALESCE(timeline, '') AS timeline
|
||||
FROM pages
|
||||
WHERE type = 'meeting'
|
||||
WHERE (type = 'meeting' OR frontmatter ->> 'legacy_type' = 'meeting')
|
||||
AND deleted_at IS NULL
|
||||
${sourceFilter}
|
||||
ORDER BY effective_date DESC NULLS LAST, slug`,
|
||||
@@ -94,7 +97,7 @@ export async function extractTimelineFromMeetings(
|
||||
JOIN pages pf ON pf.id = l.from_page_id
|
||||
JOIN pages pt ON pt.id = l.to_page_id
|
||||
WHERE l.link_type = 'attended'
|
||||
AND pf.type = 'meeting'
|
||||
AND (pf.type = 'meeting' OR pf.frontmatter ->> 'legacy_type' = 'meeting')
|
||||
AND pf.deleted_at IS NULL
|
||||
AND pt.deleted_at IS NULL`,
|
||||
);
|
||||
|
||||
+1
-11
@@ -8,7 +8,7 @@ import { chunkText } from './chunkers/recursive.ts';
|
||||
import { chunkCodeText, chunkCodeTextFull, detectCodeLanguage, CHUNKER_VERSION } from './chunkers/code.ts';
|
||||
import { findChunkForOffset } from './chunkers/edge-extractor.ts';
|
||||
import { extractCodeRefs, imageOfCandidates } from './link-extraction.ts';
|
||||
import { embedBatch, embedMultimodal, currentEmbeddingSignature, resolveEmbeddingModelLabel } from './embedding.ts';
|
||||
import { embedBatch, embedMultimodal, currentEmbeddingSignature } from './embedding.ts';
|
||||
import { slugifyPath, slugifyCodePath, isCodeFilePath } from './sync.ts';
|
||||
import type { ChunkInput, PageInput, PageType } from './types.ts';
|
||||
import { computeEffectiveDate } from './effective-date.ts';
|
||||
@@ -716,12 +716,8 @@ export async function importFromContent(
|
||||
? chunks.map((c) => wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source))
|
||||
: chunks.map((c) => c.chunk_text);
|
||||
const embeddings = await embedBatch(wrappedTexts);
|
||||
// #1717: label each chunk with the model that actually produced its
|
||||
// vector, not the engine's hardcoded default.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
chunks[i].embedding = embeddings[i];
|
||||
if (embedModelLabel) chunks[i].model = embedModelLabel;
|
||||
// token_count tracks the wrapped string length so cost reporting
|
||||
// reflects what we actually sent to the embedder.
|
||||
chunks[i].token_count = Math.ceil(wrappedTexts[i].length / 4);
|
||||
@@ -1145,10 +1141,7 @@ export async function importCodeFile(
|
||||
const matched = existingByKey.get(key);
|
||||
if (matched && matched.embedding) {
|
||||
// Reuse the existing embedding verbatim. No API call, no cost.
|
||||
// #1717: carry the existing model label along with the reused vector
|
||||
// so the upsert doesn't relabel it with the engine default.
|
||||
chunks[i]!.embedding = matched.embedding as Float32Array;
|
||||
chunks[i]!.model = matched.model ?? undefined;
|
||||
chunks[i]!.token_count = matched.token_count ?? undefined;
|
||||
} else {
|
||||
needsEmbedIndexes.push(i);
|
||||
@@ -1160,12 +1153,9 @@ export async function importCodeFile(
|
||||
try {
|
||||
const textsToEmbed = needsEmbedIndexes.map((i) => chunks[i]!.chunk_text);
|
||||
const embeddings = await embedBatch(textsToEmbed);
|
||||
// #1717: stamp the model that produced these vectors.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
for (let j = 0; j < needsEmbedIndexes.length; j++) {
|
||||
const i = needsEmbedIndexes[j]!;
|
||||
chunks[i]!.embedding = embeddings[j]!;
|
||||
if (embedModelLabel) chunks[i]!.model = embedModelLabel;
|
||||
chunks[i]!.token_count = Math.ceil(chunks[i]!.chunk_text.length / 4);
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
|
||||
@@ -4562,7 +4562,10 @@ const list_schema_packs: Operation = {
|
||||
const { existsSync, readdirSync } = await import('node:fs');
|
||||
const { join } = await import('node:path');
|
||||
const { gbrainPath } = await import('./config.ts');
|
||||
const bundled = ['gbrain-base', 'gbrain-recommended'];
|
||||
// #1726: derive from the locator's registry instead of a hand-copied
|
||||
// subset (which had frozen at 2 of 7 bundled packs).
|
||||
const { BUNDLED_PACKS } = await import('./schema-pack/load-active.ts');
|
||||
const bundled = [...BUNDLED_PACKS];
|
||||
const installedDir = gbrainPath('schema-packs');
|
||||
const installed: string[] = [];
|
||||
if (existsSync(installedDir)) {
|
||||
|
||||
@@ -41,6 +41,12 @@ migration_from:
|
||||
pack: gbrain-base
|
||||
version: "1.x"
|
||||
|
||||
# #2117 — cycle-phase participation. `phases:` is additive and pack-gated;
|
||||
# without this key extract_atoms is silently off on v2 brains even though
|
||||
# onboard + doctor recommend it (v2 declares the `atom` type it writes).
|
||||
phases:
|
||||
- extract_atoms
|
||||
|
||||
page_types:
|
||||
- name: person
|
||||
primitive: entity
|
||||
@@ -319,6 +325,10 @@ page_types:
|
||||
extractable: false
|
||||
expert_routing: false
|
||||
|
||||
# #2117 — inference rules ported from gbrain-base v1 so extract-ner keeps
|
||||
# working on v2 brains (it hard-skips with pack_unavailable when no
|
||||
# link_type declares an inference.regex). Same ReDoS-guarded sketch
|
||||
# regexes v1 ships; production matchers in link-extraction.ts still apply.
|
||||
link_types:
|
||||
- name: partner_of
|
||||
inverse: partner_of
|
||||
@@ -328,14 +338,24 @@ link_types:
|
||||
- name: discusses
|
||||
- name: founded
|
||||
inverse: founded_by
|
||||
inference:
|
||||
regex: \b(founded|founder of|co-?founded|started)\b
|
||||
- name: works_at
|
||||
inverse: employs
|
||||
inference:
|
||||
regex: \b(works? at|employed by|works? for|joined|hired by|ceo of|cto of|cmo of)\b
|
||||
- name: invested_in
|
||||
inverse: investor_of
|
||||
inference:
|
||||
regex: \b(invested in|backed|seeded|funded|wrote a check)\b
|
||||
- name: sourced_from
|
||||
- name: derived_from
|
||||
- name: supersedes
|
||||
- name: redirects_to
|
||||
# NOTE: v1's `attended` inference is page_type-bound to `meeting`, which
|
||||
# v2 does not declare (lint: link_types_undeclared_page_type). Meeting
|
||||
# pages retyped by unify-types are matched via frontmatter.legacy_type
|
||||
# in extract-timeline-from-meetings (#2109) instead.
|
||||
- name: attended
|
||||
inverse: attended_by
|
||||
- name: authored
|
||||
|
||||
@@ -91,29 +91,33 @@ export function _resetPackLocatorForTests(): void {
|
||||
* Returns null when the pack is not found. Callers handle null by
|
||||
* throwing UnknownPackError with a paste-ready install hint.
|
||||
*/
|
||||
// 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.
|
||||
//
|
||||
// #1726: exported so reporting surfaces (list_schema_packs) derive from the
|
||||
// same list the locator resolves — no more hand-copied 2-of-7 subsets.
|
||||
export const BUNDLED_PACKS: 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',
|
||||
];
|
||||
|
||||
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)) {
|
||||
if (BUNDLED_PACKS.includes(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));
|
||||
|
||||
@@ -32,7 +32,7 @@ interface CapturedSql {
|
||||
params: unknown[];
|
||||
}
|
||||
|
||||
function buildMockEngine(opts: { scorecard: TakesScorecard }): {
|
||||
function buildMockEngine(opts: { scorecard: TakesScorecard; config?: Record<string, string> }): {
|
||||
engine: BrainEngine;
|
||||
captured: CapturedSql[];
|
||||
} {
|
||||
@@ -42,6 +42,9 @@ function buildMockEngine(opts: { scorecard: TakesScorecard }): {
|
||||
async getScorecard() {
|
||||
return opts.scorecard;
|
||||
},
|
||||
async getConfig(key: string) {
|
||||
return opts.config?.[key] ?? null;
|
||||
},
|
||||
async executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]> {
|
||||
captured.push({ sql, params: params ?? [] });
|
||||
return [];
|
||||
@@ -241,6 +244,36 @@ describe('runPhaseCalibrationProfile — phase integration', () => {
|
||||
expect(insert!.params[11]).toEqual(['over-confident-geography']); // active_bias_tags
|
||||
});
|
||||
|
||||
test('#1726: calibration.user_holder config drives the holder when no explicit opt', async () => {
|
||||
const { engine, captured } = buildMockEngine({
|
||||
scorecard: ENOUGH_RESOLVED_SCORECARD,
|
||||
config: { 'calibration.user_holder': 'alice-example' },
|
||||
});
|
||||
await runPhaseCalibrationProfile(buildCtx(engine), {
|
||||
patternsGenerator: async () => ['You call early-stage tactics well — 8 of 10 held up.'],
|
||||
biasTagsGenerator: async () => [],
|
||||
voiceGateJudge: passJudge,
|
||||
});
|
||||
const insert = captured.find(c => c.sql.includes('INSERT INTO calibration_profiles'));
|
||||
expect(insert).toBeDefined();
|
||||
expect(insert!.params[1]).toBe('alice-example'); // holder from config
|
||||
});
|
||||
|
||||
test('#1726: explicit holder opt wins over calibration.user_holder config', async () => {
|
||||
const { engine, captured } = buildMockEngine({
|
||||
scorecard: ENOUGH_RESOLVED_SCORECARD,
|
||||
config: { 'calibration.user_holder': 'alice-example' },
|
||||
});
|
||||
await runPhaseCalibrationProfile(buildCtx(engine), {
|
||||
holder: 'charlie-example',
|
||||
patternsGenerator: async () => ['You call early-stage tactics well — 8 of 10 held up.'],
|
||||
biasTagsGenerator: async () => [],
|
||||
voiceGateJudge: passJudge,
|
||||
});
|
||||
const insert = captured.find(c => c.sql.includes('INSERT INTO calibration_profiles'));
|
||||
expect(insert!.params[1]).toBe('charlie-example');
|
||||
});
|
||||
|
||||
test('default model is a provider-prefixed id, persisted to model_id (#2451)', async () => {
|
||||
const { engine, captured } = buildMockEngine({ scorecard: ENOUGH_RESOLVED_SCORECARD });
|
||||
const patternsGenerator: PatternStatementsGenerator = async () => [
|
||||
|
||||
@@ -15,7 +15,6 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:tes
|
||||
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
||||
import { resetPgliteState } from './helpers/reset-pglite.ts';
|
||||
import { embedStaleForSource } from '../src/core/embed-stale.ts';
|
||||
import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
|
||||
import type { ChunkInput } from '../src/core/types.ts';
|
||||
|
||||
let engine: PGLiteEngine;
|
||||
@@ -277,49 +276,4 @@ describe('embedStaleForSource', () => {
|
||||
// The stale text row actually got its embedding.
|
||||
expect(txtRow.embedded_at).not.toBeNull();
|
||||
});
|
||||
|
||||
// #1717: the backfill path must label re-embedded chunks with the model
|
||||
// that produced the vector, and preserve the existing label on chunks it
|
||||
// did not touch (before the fix, both were reset to the engine default).
|
||||
test('labels re-embedded chunks with the gateway model, preserves untouched labels (#1717)', async () => {
|
||||
configureGateway({
|
||||
embedding_model: 'openai:text-embedding-3-large',
|
||||
env: { OPENAI_API_KEY: 'sk-test-embed-stale-1717' },
|
||||
});
|
||||
try {
|
||||
await engine.putPage('notes/model-label', {
|
||||
type: 'note',
|
||||
title: 'model-label',
|
||||
compiled_truth: '# model-label\n\nseeded',
|
||||
});
|
||||
await engine.upsertChunks('notes/model-label', [
|
||||
{
|
||||
chunk_index: 0,
|
||||
chunk_text: 'already embedded elsewhere',
|
||||
chunk_source: 'compiled_truth',
|
||||
embedding: new Float32Array(1536).fill(0.01),
|
||||
model: 'voyage:voyage-3',
|
||||
token_count: 4,
|
||||
},
|
||||
{
|
||||
chunk_index: 1,
|
||||
chunk_text: 'stale chunk needing embed',
|
||||
chunk_source: 'compiled_truth',
|
||||
token_count: 5,
|
||||
embedding: undefined, // stale
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await embedStaleForSource(engine, 'default', { embedFn: fakeEmbedFn });
|
||||
expect(result.embedded).toBe(1);
|
||||
|
||||
const after = await engine.getChunks('notes/model-label');
|
||||
const preserved = after.find((c) => c.chunk_index === 0)!;
|
||||
const reembedded = after.find((c) => c.chunk_index === 1)!;
|
||||
expect(reembedded.model).toBe('openai:text-embedding-3-large');
|
||||
expect(preserved.model).toBe('voyage:voyage-3');
|
||||
} finally {
|
||||
resetGateway();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -37,8 +37,6 @@ mock.module('../src/core/embedding.ts', () => ({
|
||||
// setPageEmbeddingSignature / invalidateStaleSignatureEmbeddings resolve to
|
||||
// null via the Proxy default, so the signature value is inert here.
|
||||
currentEmbeddingSignature: () => 'test:model:1536',
|
||||
// #1717: embed paths stamp this label on (re)embedded chunks.
|
||||
resolveEmbeddingModelLabel: () => 'openai:text-embedding-3-large',
|
||||
}));
|
||||
|
||||
// Import AFTER mocking.
|
||||
@@ -805,34 +803,3 @@ describe('embedAllStale --source threading (D7)', () => {
|
||||
expect((firstCallOpts as { sourceId?: string }).sourceId).toBe('media-corpus');
|
||||
});
|
||||
});
|
||||
|
||||
// #1717: content_chunks.model must record the model that actually produced
|
||||
// each vector, not the gateway/engine default.
|
||||
describe('content_chunks.model labeling (#1717)', () => {
|
||||
test('stamps the resolved embedding model on re-embedded chunks, preserves it on untouched chunks', async () => {
|
||||
let upserted: any[] | undefined;
|
||||
// Chunk 0 is stale (no embedded_at) → gets re-embedded this pass.
|
||||
// Chunk 1 is already embedded with a DIFFERENT model → must be preserved,
|
||||
// not relabeled to the current model.
|
||||
const chunks = [
|
||||
{ chunk_index: 0, chunk_text: 'a', chunk_source: 'compiled_truth', embedded_at: null, model: 'zeroentropyai:zembed-1', token_count: 1 },
|
||||
{ chunk_index: 1, chunk_text: 'b', chunk_source: 'compiled_truth', embedded_at: '2026-01-01', embedding: new Float32Array(1536), model: 'voyage:voyage-3', token_count: 1 },
|
||||
];
|
||||
const engine = mockEngine({
|
||||
getPage: async () => ({ slug: 'notes/x', compiled_truth: 'a', timeline: '', source_id: 'default' }),
|
||||
getChunks: async () => chunks,
|
||||
upsertChunks: async (_slug: string, c: any[]) => { upserted = c; },
|
||||
setPageEmbeddingSignature: async () => null,
|
||||
});
|
||||
|
||||
await runEmbedCore(engine, { slugs: ['notes/x'] });
|
||||
|
||||
expect(upserted).toBeDefined();
|
||||
const byIdx = Object.fromEntries(upserted!.map(c => [c.chunk_index, c]));
|
||||
// Re-embedded chunk carries the model that produced its vector (was
|
||||
// mislabeled with the default before the fix).
|
||||
expect(byIdx[0].model).toBe('openai:text-embedding-3-large');
|
||||
// Untouched chunk keeps its original model — no wholesale relabel.
|
||||
expect(byIdx[1].model).toBe('voyage:voyage-3');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// #2109 — gbrain-base-v2's unify-types retypes meeting pages to `note`
|
||||
// with frontmatter.legacy_type='meeting'. extract-timeline-from-meetings
|
||||
// used to hardcode type='meeting' and silently scan 0 meetings on migrated
|
||||
// brains. These tests fail without the legacy_type fallback in both SQL
|
||||
// sites (meeting walk + attended-edge join).
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
|
||||
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
||||
import { resetPgliteState } from './helpers/reset-pglite.ts';
|
||||
import { extractTimelineFromMeetings } from '../src/core/extract-timeline-from-meetings.ts';
|
||||
|
||||
let engine: PGLiteEngine;
|
||||
|
||||
beforeAll(async () => {
|
||||
engine = new PGLiteEngine();
|
||||
await engine.connect({});
|
||||
await engine.initSchema();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await engine.disconnect();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetPgliteState(engine);
|
||||
});
|
||||
|
||||
async function insertPage(opts: {
|
||||
slug: string;
|
||||
type: string;
|
||||
title: string;
|
||||
effectiveDate?: string;
|
||||
legacyType?: string;
|
||||
}): Promise<number> {
|
||||
const frontmatterLiteral = opts.legacyType
|
||||
? `'{"legacy_type": "${opts.legacyType}"}'::jsonb`
|
||||
: `'{}'::jsonb`;
|
||||
const rows = await engine.executeRaw<{ id: number }>(
|
||||
`INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline, effective_date, frontmatter)
|
||||
VALUES ($1, 'default', $2, $3, '', '', $4, ${frontmatterLiteral})
|
||||
RETURNING id`,
|
||||
[opts.slug, opts.type, opts.title, opts.effectiveDate ?? null],
|
||||
);
|
||||
return rows[0]!.id;
|
||||
}
|
||||
|
||||
describe('extractTimelineFromMeetings — legacy_type fallback (#2109)', () => {
|
||||
it('scans pages retyped to note with legacy_type=meeting and walks their attended edges', async () => {
|
||||
const meetingId = await insertPage({
|
||||
slug: 'meetings/2026-01-05',
|
||||
type: 'note', // post-unify-types shape on a gbrain-base-v2 brain
|
||||
legacyType: 'meeting',
|
||||
title: 'Weekly sync',
|
||||
effectiveDate: '2026-01-05',
|
||||
});
|
||||
const personId = await insertPage({
|
||||
slug: 'people/alice-example',
|
||||
type: 'person',
|
||||
title: 'Alice Example',
|
||||
});
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO links (from_page_id, to_page_id, link_type) VALUES ($1, $2, 'attended')`,
|
||||
[meetingId, personId],
|
||||
);
|
||||
|
||||
const result = await extractTimelineFromMeetings(engine);
|
||||
expect(result.meetings_scanned).toBe(1);
|
||||
expect(result.entries_created).toBe(1);
|
||||
expect(result.entities_touched).toBe(1);
|
||||
expect(result.batch_errors).toBe(0);
|
||||
});
|
||||
|
||||
it('still scans pre-unify pages with type=meeting (v1 behavior preserved)', async () => {
|
||||
const meetingId = await insertPage({
|
||||
slug: 'meetings/2026-02-01',
|
||||
type: 'meeting',
|
||||
title: 'Board prep',
|
||||
effectiveDate: '2026-02-01',
|
||||
});
|
||||
const personId = await insertPage({
|
||||
slug: 'people/charlie-example',
|
||||
type: 'person',
|
||||
title: 'Charlie Example',
|
||||
});
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO links (from_page_id, to_page_id, link_type) VALUES ($1, $2, 'attended')`,
|
||||
[meetingId, personId],
|
||||
);
|
||||
|
||||
const result = await extractTimelineFromMeetings(engine);
|
||||
expect(result.meetings_scanned).toBe(1);
|
||||
expect(result.entries_created).toBe(1);
|
||||
});
|
||||
|
||||
it('does not scan unrelated note pages without legacy_type=meeting', async () => {
|
||||
await insertPage({
|
||||
slug: 'notes/random',
|
||||
type: 'note',
|
||||
title: 'Random note',
|
||||
effectiveDate: '2026-03-01',
|
||||
});
|
||||
const result = await extractTimelineFromMeetings(engine);
|
||||
expect(result.meetings_scanned).toBe(0);
|
||||
expect(result.entries_created).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -73,21 +73,4 @@ describe('importFromContent embedding_signature stamping (F1)', () => {
|
||||
await importFromContent(engine, 'concepts/unstamped', '# Unstamped\n\nbody content.', { noEmbed: true });
|
||||
expect(await signatureOf('concepts/unstamped')).toBeNull();
|
||||
});
|
||||
|
||||
// #1717: content_chunks.model must record the model that produced the
|
||||
// vector (the configured gateway model), not the engine's hardcoded
|
||||
// default. The gateway here is configured to openai:text-embedding-3-large,
|
||||
// which differs from DEFAULT_EMBEDDING_MODEL — so this fails without the
|
||||
// import-path model stamping.
|
||||
test('inline embed labels content_chunks.model with the configured model (#1717)', async () => {
|
||||
await importFromContent(engine, 'concepts/labeled', '# Labeled\n\nsome body content to chunk and embed.', {});
|
||||
const rows = await engine.executeRaw<{ model: string }>(
|
||||
`SELECT cc.model FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE p.slug = $1 AND p.source_id = 'default'`,
|
||||
['concepts/labeled'],
|
||||
);
|
||||
expect(rows.length).toBeGreaterThan(0);
|
||||
for (const r of rows) expect(r.model).toBe('openai:text-embedding-3-large');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -152,6 +152,19 @@ describe('list_schema_packs', () => {
|
||||
expect(result.installed).toContain('mine');
|
||||
});
|
||||
});
|
||||
|
||||
it('reports the full bundled registry, not a hand-copied subset (#1726)', async () => {
|
||||
await withEnv({ GBRAIN_HOME: tmpDir }, async () => {
|
||||
const { BUNDLED_PACKS } = await import('../src/core/schema-pack/load-active.ts');
|
||||
const result = await operationsByName.list_schema_packs!.handler(ctxOf(), {}) as { bundled: string[] };
|
||||
expect(result.bundled.slice().sort()).toEqual([...BUNDLED_PACKS].sort());
|
||||
// The lens packs that declare extract_atoms/synthesize_concepts phases
|
||||
// were the ones dropped by the frozen 2-pack literal.
|
||||
for (const name of ['gbrain-creator', 'gbrain-everything', 'gbrain-base-v2']) {
|
||||
expect(result.bundled).toContain(name);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ── schema_stats ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
// #2117 — gbrain-base-v2 shipped with no `phases:` declaration and zero
|
||||
// link_types[].inference regexes, so extract_atoms was silently pack-gated
|
||||
// off and extract-ner returned pack_unavailable on the bundled default pack.
|
||||
// These assertions fail against the pre-fix yaml.
|
||||
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { join } from 'node:path';
|
||||
import { loadPackFromFile } from '../src/core/schema-pack/loader.ts';
|
||||
import { linkTypesUndeclared } from '../src/core/schema-pack/lint-rules.ts';
|
||||
|
||||
const V2_PATH = join(import.meta.dir, '..', 'src', 'core', 'schema-pack', 'base', 'gbrain-base-v2.yaml');
|
||||
|
||||
describe('gbrain-base-v2 capability parity (#2117)', () => {
|
||||
const manifest = loadPackFromFile(V2_PATH);
|
||||
|
||||
it('declares the extract_atoms cycle phase', () => {
|
||||
expect(manifest.phases ?? []).toContain('extract_atoms');
|
||||
});
|
||||
|
||||
it('ships at least one link_type inference regex so extract-ner is not pack_unavailable', () => {
|
||||
// Mirrors the extract-ner hasRegex predicate exactly.
|
||||
const hasRegex = manifest.link_types.some(
|
||||
(lt) => lt.inference && typeof lt.inference === 'object' && 'regex' in lt.inference,
|
||||
);
|
||||
expect(hasRegex).toBe(true);
|
||||
});
|
||||
|
||||
it('ports the v1 inference verbs it declares link types for', () => {
|
||||
const withRegex = manifest.link_types
|
||||
.filter((lt) => lt.inference?.regex)
|
||||
.map((lt) => lt.name)
|
||||
.sort();
|
||||
expect(withRegex).toEqual(['founded', 'invested_in', 'works_at']);
|
||||
});
|
||||
|
||||
it('inference rules pass the undeclared-page-type lint (no meeting-bound inference)', async () => {
|
||||
const issues = await linkTypesUndeclared(manifest);
|
||||
expect(issues).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user