Compare commits

..
Author SHA1 Message Date
Garry TanandClaude Fable 5 5350bbc796 test(calibration): replace real-name holder fixture with charlie-example placeholder
Privacy iron rule: no real people's names in checked-in code. The sanctioned
placeholder mapping uses people/charlie-example.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 11:21:06 -07:00
8c27339c5c fix(calibration): resolve owner holder via config (default 'self'), fixes #2464
Takeover of #2467 (rebased onto master). consolidate writes owner takes
with holder='self' while calibration-profile, calibration CLI/op, think's
calibration block, emotional-weight, and doctor's calibration_freshness
all defaulted to a hardcoded 'garry' — so getScorecard returned 0
resolved and the calibration profile never built on non-upstream brains.

New src/core/owner-holder.ts is the single source of truth:
resolveOwnerHolder({override, configValue}) = override >
emotional_weight.user_holder config > 'self'. All six call sites route
through it; doctor's freshness SQL is parameterized ().

Upgrade note: upstream-owner brains with historical holder='garry'
profiles should `gbrain config set emotional_weight.user_holder garry`
to keep reading them.

Co-authored-by: devty <devty@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:19:58 -07:00
25 changed files with 191 additions and 303 deletions
+1
View File
@@ -457,6 +457,7 @@ unresolvable+true|false, pre-v80 NULL/NULL rows survive).
- `src/core/think/prompt.ts` extension — anti-bias rewrite. `withCalibration` option on `buildThinkSystemPrompt` adds anti-bias rules. `buildCalibrationBlock()` emits the `<calibration>` XML. `buildThinkUserMessage` has TWO shapes: default (question first), and with-calibration (retrieval → calibration → question) when opt-in. Wired into `runThink` via `opts.withCalibration` + `opts.calibrationHolder`.
- `src/commands/calibration.ts` — CLI: `gbrain calibration` (read + print), `--regenerate`, `--undo-wave <ver>`, `ab-report`. MCP op `get_calibration_profile` (scope: read) backs the same data path. Source-scoped via `sourceScopeOpts(ctx)`.
- `src/commands/serve-http.ts` extension — three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down).
- `src/core/owner-holder.ts` — single source of truth for "the brain owner" holder string. `DEFAULT_OWNER_HOLDER = 'self'` (matches the consolidate facts→takes writer + `docs/takes-vs-facts.md`); `resolveOwnerHolder({override, configValue})` returns override > `emotional_weight.user_holder` config > `'self'`. Consumed by the calibration_profile cycle phase, `gbrain calibration` CLI, the `get_calibration_profile` op, `think`'s calibration block, `emotional-weight`'s `DEFAULT_USER_HOLDER`, and doctor's `calibration_freshness`. Pure; unit-tested in `test/owner-holder.test.ts`. Does NOT unify owner-identity fragmentation (`self`/`brain`/`people-<owner>`) — tracked separately.
- `src/commands/takes.ts` extension — `gbrain takes revisit <slug>` opens $EDITOR on the source page with a `<!-- gbrain:revisit -->` cursor marker.
- `src/commands/doctor.ts` extension — 4 checks: `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` (mitigation surface; math ships later), `voice_gate_health`.
- `admin/src/pages/Calibration.tsx` — Calibration tab. Single-column layout. `<TrustedSVG>` wrapper handles `dangerouslySetInnerHTML` for the server-rendered SVG.
+15
View File
@@ -91,3 +91,18 @@ First full takes extraction run on a ~100K-page brain:
4. **Self-reported ≠ verified.** "Reports 7 figures" → holder=person, weight=0.75, NOT world/1.0
5. **No false precision.** Use 0.05 increments (0.35, 0.55, 0.75), not 0.74 or 0.82
6. **"So what" test.** Skip Twitter handles, follower counts, obvious metadata
## Owner-holder canonicalization
"The brain owner" is, by convention, the holder string **`self`** — the value the
dream `consolidate` phase stamps when it promotes the owner's hot facts into cold
takes. Calibration, `think`, and the `doctor` calibration check resolve the owner
holder through `resolveOwnerHolder` (`src/core/owner-holder.ts`): explicit override
> `emotional_weight.user_holder` config > `self`.
Known limitation (tracked in garrytan/gbrain#2465): the owner can also
appear under `brain` (a take the owner asserts, via `propose_takes`) and
`people/<owner>` (extraction that names the owner). The resolver selects the
*default* canonical owner string for reads; it does not merge those other
strings. Per-take attribution for other people (e.g. `people/george`) is
unaffected and correct.
+12 -5
View File
@@ -19,10 +19,11 @@
*/
import type { BrainEngine } from '../core/engine.ts';
import { resolveCalibrationHolder, runPhaseCalibrationProfile } from '../core/cycle/calibration-profile.ts';
import { 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';
import { resolveOwnerHolder } from '../core/owner-holder.ts';
export interface CalibrationProfileRow {
/** BIGSERIAL → string (postgres.js int8 wire shape; never Number() — int8
@@ -167,7 +168,10 @@ export async function runCalibration(
config: GBrainConfig,
): Promise<void> {
const { opts } = parseArgs(args);
const holder = await resolveCalibrationHolder(engine, opts.holder);
const holder = resolveOwnerHolder({
override: opts.holder,
configValue: await engine.getConfig('emotional_weight.user_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 +257,17 @@ export async function getCalibrationProfileOp(
ctx: OperationContext,
params: { holder?: string },
): Promise<CalibrationProfileRow | null> {
if (params.holder !== undefined && (typeof params.holder !== 'string' || params.holder.length === 0)) {
const holder = resolveOwnerHolder({
override: params.holder,
configValue: await ctx.engine.getConfig('emotional_weight.user_holder'),
});
if (typeof holder !== 'string' || 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 the calibration.user_holder config (then "garry")',
'pass holder="<slug>" or omit to default to the owner holder (config emotional_weight.user_holder, else "self")',
);
}
const holder = await resolveCalibrationHolder(ctx.engine, params.holder);
const scope = sourceScopeOpts(ctx);
return getLatestProfile(ctx.engine, { holder, ...scope });
}
+8 -2
View File
@@ -28,6 +28,7 @@ import type { DbUrlSource } from '../core/config.ts';
import { gbrainPath, loadConfig } from '../core/config.ts';
import { reflexEnabled } from '../core/context/reflex.ts';
import { resolveSocketPath } from '../core/context/resolve-ipc.ts';
import { resolveOwnerHolder } from '../core/owner-holder.ts';
import { homedir } from 'os';
import { dirname, isAbsolute, join, resolve as resolvePath } from 'path';
import { fileURLToPath } from 'url';
@@ -1287,14 +1288,19 @@ export async function checkAbandonedThreads(engine: BrainEngine): Promise<Check>
/**
* calibration_freshness: warns when the active calibration profile is
* older than 7 days (configurable). Default holder 'garry'. Multi-source
* older than 7 days (configurable). Default holder resolves via resolveOwnerHolder
* (config emotional_weight.user_holder, else 'self'). Multi-source
* brains see one row per source; this check uses the most recent across
* all sources.
*/
export async function checkCalibrationFreshness(engine: BrainEngine): Promise<Check> {
try {
const ownerHolder = resolveOwnerHolder({
configValue: await engine.getConfig('emotional_weight.user_holder'),
});
const rows = await engine.executeRaw<{ generated_at: Date | null }>(
`SELECT MAX(generated_at) AS generated_at FROM calibration_profiles WHERE holder = 'garry'`,
`SELECT MAX(generated_at) AS generated_at FROM calibration_profiles WHERE holder = $1`,
[ownerHolder],
);
const generated = rows[0]?.generated_at;
if (!generated) {
+4 -3
View File
@@ -45,6 +45,7 @@ import {
type IngestionContentType,
type IngestionEvent,
} from '../core/ingestion/types.ts';
import { resolveOwnerHolder } from '../core/owner-holder.ts';
/**
* /health endpoint timeout. 3s rather than 5s: Fly.io's default
@@ -1190,7 +1191,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
app.get('/admin/api/calibration/pattern/:id', requireAdmin, async (req: Request, res: Response) => {
try {
const { getLatestProfile } = await import('./calibration.ts');
const holder = (req.query.holder as string) || 'garry';
const holder = resolveOwnerHolder({ override: (req.query.holder as string) || undefined, configValue: await engine.getConfig('emotional_weight.user_holder') });
const profile = await getLatestProfile(engine, { holder });
if (!profile) {
res.status(404).json({ error: 'no_profile' });
@@ -1240,7 +1241,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
app.get('/admin/api/calibration/profile', requireAdmin, async (req: Request, res: Response) => {
try {
const { getLatestProfile } = await import('./calibration.ts');
const holder = (req.query.holder as string) || 'garry';
const holder = resolveOwnerHolder({ override: (req.query.holder as string) || undefined, configValue: await engine.getConfig('emotional_weight.user_holder') });
const profile = await getLatestProfile(engine, { holder });
res.json(profile);
} catch (err) {
@@ -1257,7 +1258,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
renderAbandonedThreadsCard,
renderPatternStatementsCard,
} = await import('../core/calibration/svg-renderer.ts');
const holder = (req.query.holder as string) || 'garry';
const holder = resolveOwnerHolder({ override: (req.query.holder as string) || undefined, configValue: await engine.getConfig('emotional_weight.user_holder') });
const type = req.params.type;
const profile = await getLatestProfile(engine, { holder });
+2 -1
View File
@@ -29,6 +29,7 @@ import {
} from '../core/takes-fence.ts';
import { withPageLock } from '../core/page-lock.ts';
import { resolveSourceId } from '../core/source-resolver.ts';
import { resolveOwnerHolder } from '../core/owner-holder.ts';
// --- Helpers ---
@@ -364,7 +365,7 @@ async function cmdResolve(engine: BrainEngine, args: string[], sourceId?: string
// --evidence is the v0.30.0 alias for --source on the resolve subcommand
// (semantic clarity: "what evidence resolved this bet?").
const source = flagValue(args, '--evidence') ?? flagValue(args, '--source');
const resolvedBy = flagValue(args, '--by') ?? 'garry';
const resolvedBy = flagValue(args, '--by') ?? resolveOwnerHolder({ configValue: await engine.getConfig('emotional_weight.user_holder') });
const dirArg = flagValue(args, '--dir');
const pageId = await getPageId(engine, slug, sourceId);
+3 -2
View File
@@ -68,6 +68,7 @@ import {
type BrainstormCheckpoint,
type CheckpointCross,
} from './checkpoint.ts';
import { resolveOwnerHolder } from '../owner-holder.ts';
export { BudgetExhausted };
@@ -139,7 +140,7 @@ export interface BrainstormOptions {
modelOverride?: string;
/** Skip the cost-preview TTY grace window. Required for non-interactive callers. */
skipCostPreview?: boolean;
/** When set, force the user holder for calibration profile lookup. Falls back to config (`emotional_weight.user_holder`) then `'garry'`. */
/** When set, force the user holder for calibration profile lookup. Falls back to config (`emotional_weight.user_holder`) then `'self'`. */
holderOverride?: string;
/** Source scope. */
sourceId?: string;
@@ -623,7 +624,7 @@ async function _runBrainstormInner(
}
// ---- Phase 3: calibration context (cold-start fallback) ----
const holder = opts.holderOverride ?? config.emotional_weight?.user_holder ?? 'garry';
const holder = resolveOwnerHolder({ override: opts.holderOverride, configValue: config.emotional_weight?.user_holder });
const calibContext = await loadCalibrationContext(engine, {
holder,
sourceId: opts.sourceId,
+1 -1
View File
@@ -25,7 +25,7 @@ import type { BrainEngine } from '../engine.ts';
export interface ABRunInput {
question: string;
/** Holder context for calibration. Default 'garry'. */
/** Holder context for calibration. Resolves via resolveOwnerHolder (config emotional_weight.user_holder, else 'self'). */
holder?: string;
/** Engine for DB write. */
engine: BrainEngine;
-4
View File
@@ -928,10 +928,6 @@ 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)
+6 -22
View File
@@ -26,6 +26,7 @@
*/
import { BaseCyclePhase, type ScopedReadOpts, type BasePhaseOpts } from './base-phase.ts';
import { resolveOwnerHolder } from '../owner-holder.ts';
import { chat as gatewayChat } from '../ai/gateway.ts';
import { TIER_DEFAULTS } from '../model-config.ts';
import { gateVoice, type VoiceGateGenerator, type VoiceGateJudge } from '../calibration/voice-gate.ts';
@@ -96,7 +97,7 @@ export type PatternStatementsGenerator = (input: {
export type BiasTagsGenerator = (patterns: string[]) => Promise<string[]>;
export interface CalibrationProfileOpts extends BasePhaseOpts {
/** Holder to generate the profile for. Default: `calibration.user_holder` config, then 'garry'. */
/** Holder to generate the profile for. Default resolves via resolveOwnerHolder (config emotional_weight.user_holder, else 'self'). */
holder?: string;
/** Inject the patterns generator (tests). */
patternsGenerator?: PatternStatementsGenerator;
@@ -194,26 +195,6 @@ 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) {
@@ -247,7 +228,10 @@ class CalibrationProfilePhase extends BaseCyclePhase {
_ctx: OperationContext,
opts: CalibrationProfileOpts,
): Promise<{ summary: string; details: Record<string, unknown>; status?: PhaseStatus }> {
const holder = await resolveCalibrationHolder(engine, opts.holder);
const holder = resolveOwnerHolder({
override: opts.holder,
configValue: await engine.getConfig('emotional_weight.user_holder'),
});
const promptVersion = opts.promptVersion ?? CALIBRATION_PROFILE_PROMPT_VERSION;
const modelId = opts.model ?? TIER_DEFAULTS.reasoning;
const gradeCompletion = opts.gradeCompletion ?? 1.0;
+7 -4
View File
@@ -14,6 +14,8 @@
* See `loadHighEmotionTags` for the resolution path.
*/
import { DEFAULT_OWNER_HOLDER } from '../owner-holder.ts';
/**
* Default high-emotion tag seed list. Pages with any tag in this set get the
* tag-emotion boost in the formula below. Override via config key
@@ -43,11 +45,12 @@ export const HIGH_EMOTION_TAGS: ReadonlySet<string> = new Set([
]);
/**
* Holder name treated as "the user" for the Garry-as-holder ratio. Configurable
* via the `emotional_weight.user_holder` config key (defaults to 'garry' to
* match the v0.28 schema's takes table convention).
* Holder name treated as "the user" for the user-as-holder ratio. Configurable
* via the `emotional_weight.user_holder` config key; defaults to the canonical
* owner holder ('self', DEFAULT_OWNER_HOLDER) so it matches the consolidate
* facts→takes writer instead of a hardcoded name.
*/
export const DEFAULT_USER_HOLDER = 'garry';
export const DEFAULT_USER_HOLDER = DEFAULT_OWNER_HOLDER;
export interface EmotionalWeightTake {
holder: string;
+2 -5
View File
@@ -68,14 +68,11 @@ 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' OR frontmatter ->> 'legacy_type' = 'meeting')
WHERE type = 'meeting'
AND deleted_at IS NULL
${sourceFilter}
ORDER BY effective_date DESC NULLS LAST, slug`,
@@ -97,7 +94,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' OR pf.frontmatter ->> 'legacy_type' = 'meeting')
AND pf.type = 'meeting'
AND pf.deleted_at IS NULL
AND pt.deleted_at IS NULL`,
);
+2 -5
View File
@@ -3289,7 +3289,7 @@ const get_calibration_profile: Operation = {
holder: {
type: 'string',
description:
"Holder slug, e.g. 'garry' or 'people/charlie-example'. Defaults to 'garry' when omitted.",
"Holder slug, e.g. 'self' or 'people/charlie-example'. Defaults to config emotional_weight.user_holder, else 'self', when omitted.",
},
},
handler: async (ctx, p) => {
@@ -4562,10 +4562,7 @@ const list_schema_packs: Operation = {
const { existsSync, readdirSync } = await import('node:fs');
const { join } = await import('node:path');
const { gbrainPath } = await import('./config.ts');
// #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 bundled = ['gbrain-base', 'gbrain-recommended'];
const installedDir = gbrainPath('schema-packs');
const installed: string[] = [];
if (existsSync(installedDir)) {
+24
View File
@@ -0,0 +1,24 @@
/**
* Canonical holder string for "the brain owner," resolved in ONE place so the
* calibration / think / doctor / emotional-weight defaults stop disagreeing.
*
* The default matches the consolidate facts→takes writer
* (src/core/cycle/phases/consolidate.ts: holder:'self') and docs/takes-vs-facts.md.
* Do NOT introduce a fourth literal — three already exist historically
* ('garry', 'system', 'self'); this is the source of truth.
*
* NORMALIZATION NOTE: the brain owner may also appear under other holder
* strings — 'brain' (propose_takes when the author asserts a claim) and
* people/<owner> (extraction that names the owner). This resolver only selects
* the *default* canonical owner string for reads; it does NOT merge those other
* strings. Unifying them is owner-identity entity-resolution, tracked separately
* (see garrytan/gbrain#2465). Until then, historical owner takes
* under 'brain'/people-<owner> are not folded into the default profile.
*/
export const DEFAULT_OWNER_HOLDER = 'self';
export function resolveOwnerHolder(
opts: { override?: string | null; configValue?: string | null },
): string {
return opts.override ?? opts.configValue ?? DEFAULT_OWNER_HOLDER;
}
@@ -41,12 +41,6 @@ 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
@@ -325,10 +319,6 @@ 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
@@ -338,24 +328,14 @@ 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
+22 -26
View File
@@ -91,33 +91,29 @@ 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 {
if (BUNDLED_PACKS.includes(name)) {
// 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)) {
// 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));
+7 -3
View File
@@ -23,6 +23,7 @@ import { runGather, renderPagesBlock, takesHitToTakeForPrompt } from './gather.t
import { renderTakesBlock } from './sanitize.ts';
import { buildThinkSystemPrompt, buildThinkUserMessage } from './prompt.ts';
import { resolveCitations, type ParsedCitation } from './cite-render.ts';
import { resolveOwnerHolder } from '../owner-holder.ts';
import { resolveModel } from '../model-config.ts';
import { chat as gatewayChat, probeChatModel, type ChatResult } from '../ai/gateway.ts';
import { AIConfigError } from '../ai/errors.ts';
@@ -76,8 +77,8 @@ export interface RunThinkOpts {
*/
withCalibration?: boolean;
/**
* Holder to retrieve the calibration profile for. Default 'garry'. Only
* consulted when withCalibration=true.
* Holder to retrieve the calibration profile for. Resolves via resolveOwnerHolder
* (config emotional_weight.user_holder, else 'self'). Only consulted when withCalibration=true.
*/
calibrationHolder?: string;
/**
@@ -308,7 +309,10 @@ export async function runThink(
try {
const { getLatestProfile } = await import('../../commands/calibration.ts');
const profile = await getLatestProfile(engine, {
holder: opts.calibrationHolder ?? 'garry',
holder: resolveOwnerHolder({
override: opts.calibrationHolder,
configValue: await engine.getConfig('emotional_weight.user_holder'),
}),
});
if (profile) {
calibrationBlockOpts = {
+13 -7
View File
@@ -27,6 +27,12 @@ function buildMockEngine(opts: { rows: CalibrationProfileRow[] }): {
const capturedParams: unknown[][] = [];
const engine = {
kind: 'pglite',
// #2464: getCalibrationProfileOp resolves the owner holder via
// resolveOwnerHolder(config emotional_weight.user_holder, else 'self'), so the
// mock must implement getConfig. null = key unset → resolver falls back to 'self'.
async getConfig(): Promise<string | null> {
return null;
},
async executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]> {
capturedSql.push(sql);
capturedParams.push(params ?? []);
@@ -211,17 +217,17 @@ describe('formatProfileText', () => {
// ─── getCalibrationProfileOp ────────────────────────────────────────
describe('getCalibrationProfileOp (MCP)', () => {
test('defaults holder to "garry" when omitted', async () => {
const { engine } = buildMockEngine({ rows: [buildProfile({ holder: 'garry' })] });
test('defaults holder to "self" when omitted (config emotional_weight.user_holder unset)', async () => {
const { engine } = buildMockEngine({ rows: [buildProfile({ holder: 'self' })] });
const ctx = buildCtx(engine);
const result = await getCalibrationProfileOp(ctx, {});
expect(result?.holder).toBe('garry');
expect(result?.holder).toBe('self');
});
test('routes through sourceScopeOpts: scalar source-bound client gets source-scoped result', async () => {
const rows = [
buildProfile({ holder: 'garry', source_id: 'default' }),
buildProfile({ holder: 'garry', source_id: 'tenant-b' }),
buildProfile({ holder: 'self', source_id: 'default' }),
buildProfile({ holder: 'self', source_id: 'tenant-b' }),
];
const { engine } = buildMockEngine({ rows });
const ctx = buildCtx(engine, { sourceId: 'tenant-b' });
@@ -231,8 +237,8 @@ describe('getCalibrationProfileOp (MCP)', () => {
test('federated read scope sees the union of allowed sources', async () => {
const rows = [
buildProfile({ holder: 'garry', source_id: 'tenant-a' }),
buildProfile({ holder: 'garry', source_id: 'tenant-z' }),
buildProfile({ holder: 'self', source_id: 'tenant-a' }),
buildProfile({ holder: 'self', source_id: 'tenant-z' }),
];
const { engine } = buildMockEngine({ rows });
const ctx = buildCtx(engine, { allowedSources: ['tenant-a', 'tenant-b'] });
+25 -34
View File
@@ -32,7 +32,7 @@ interface CapturedSql {
params: unknown[];
}
function buildMockEngine(opts: { scorecard: TakesScorecard; config?: Record<string, string> }): {
function buildMockEngine(opts: { scorecard: TakesScorecard; userHolder?: string | null }): {
engine: BrainEngine;
captured: CapturedSql[];
} {
@@ -42,8 +42,9 @@ function buildMockEngine(opts: { scorecard: TakesScorecard; config?: Record<stri
async getScorecard() {
return opts.scorecard;
},
async getConfig(key: string) {
return opts.config?.[key] ?? null;
async getConfig(key: string): Promise<string | null> {
if (key === 'emotional_weight.user_holder') return opts.userHolder ?? null;
return null;
},
async executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]> {
captured.push({ sql, params: params ?? [] });
@@ -237,43 +238,13 @@ describe('runPhaseCalibrationProfile — phase integration', () => {
// grade_completion, domain_scorecards_json, patterns[], voice_passed, voice_attempts,
// bias_tags[], model_id
expect(insert!.params[0]).toBe('default'); // source_id
expect(insert!.params[1]).toBe('garry'); // holder
expect(insert!.params[1]).toBe('self'); // holder (resolved via resolveOwnerHolder, no override)
expect(insert!.params[2]).toBe(12); // total_resolved
expect(insert!.params[9]).toBe(true); // voice_gate_passed
expect(insert!.params[10]).toBe(1); // voice_gate_attempts
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 () => [
@@ -363,4 +334,24 @@ describe('runPhaseCalibrationProfile — phase integration', () => {
const insert = captured.find(c => c.sql.includes('INSERT INTO calibration_profiles'));
expect(insert!.params[0]).toBe('tenant-b');
});
test('cold-brain summary uses resolved owner holder self when user_holder unset', async () => {
const { engine } = buildMockEngine({
scorecard: { total_bets: 0, resolved: 0, correct: 0, incorrect: 0, partial: 0,
accuracy: null, brier: null, partial_rate: null, unresolvable_count: 0, unresolvable_rate: null },
});
const result = await runPhaseCalibrationProfile(buildCtx(engine), {});
expect(result.summary).toContain('holder=self');
expect(result.summary).not.toContain('holder=garry');
});
test('configured user_holder overrides the default in the cold-brain summary', async () => {
const { engine } = buildMockEngine({
scorecard: { total_bets: 0, resolved: 0, correct: 0, incorrect: 0, partial: 0,
accuracy: null, brier: null, partial_rate: null, unresolvable_count: 0, unresolvable_rate: null },
userHolder: 'people/charlie-example',
});
const result = await runPhaseCalibrationProfile(buildCtx(engine), {});
expect(result.summary).toContain('holder=people/charlie-example');
});
});
+6
View File
@@ -32,6 +32,12 @@ function buildMockEngine(opts: {
}): BrainEngine {
return {
kind: 'pglite',
// #2464: checkCalibrationFreshness resolves the owner holder via
// resolveOwnerHolder(config emotional_weight.user_holder, else 'self'), so the
// mock must implement getConfig. null = key unset → resolver falls back to 'self'.
async getConfig(): Promise<string | null> {
return null;
},
async executeRaw<T>(sql: string): Promise<T[]> {
if (opts.throwOn && opts.throwOn.test(sql)) {
throw new Error('mock engine error: ' + sql.slice(0, 50));
+4
View File
@@ -112,3 +112,7 @@ describe('computeEmotionalWeight', () => {
expect(HIGH_EMOTION_TAGS.has('mental-health')).toBe(true);
});
});
test('DEFAULT_USER_HOLDER is the canonical owner holder self', () => {
expect(DEFAULT_USER_HOLDER).toBe('self');
});
-106
View File
@@ -1,106 +0,0 @@
// #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);
});
});
-13
View File
@@ -152,19 +152,6 @@ 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 ───────────────────────────────────────────────────────
+27
View File
@@ -0,0 +1,27 @@
import { describe, test, expect } from 'bun:test';
import { resolveOwnerHolder, DEFAULT_OWNER_HOLDER } from '../src/core/owner-holder.ts';
describe('owner-holder', () => {
test('DEFAULT_OWNER_HOLDER is self', () => {
expect(DEFAULT_OWNER_HOLDER).toBe('self');
});
test('defaults to self when nothing provided', () => {
expect(resolveOwnerHolder({})).toBe('self');
});
test('null/undefined config falls back to self', () => {
expect(resolveOwnerHolder({ configValue: null })).toBe('self');
expect(resolveOwnerHolder({ configValue: undefined })).toBe('self');
});
test('uses config value when set and no override', () => {
expect(resolveOwnerHolder({ configValue: 'people/charlie-example' }))
.toBe('people/charlie-example');
});
test('override beats config and default', () => {
expect(resolveOwnerHolder({ override: 'world', configValue: 'people/charlie-example' }))
.toBe('world');
});
});
@@ -1,40 +0,0 @@
// #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([]);
});
});