Compare commits

..
Author SHA1 Message Date
Garry TanandClaude Fable 5 62bd7fb3b7 fix(schema): block scalars keep '#' as literal content
Inside a YAML block scalar '#' is content, not a comment; parseBlockScalar
was routing lines through stripComment/isBlank, truncating descriptions
like 'see issue #2029' and blanking comment-looking lines. Use the raw
line inside the scalar. Adds a pinning test.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 12:01:58 -07:00
Garry TanandClaude Fable 5 733fcd633a test(schema): point bundled-registry test at bundled.ts source of truth
The bundled pack list moved from load-active.ts to bundled.ts in the
truthful-inspection refactor; the T4 registry test still grepped
load-active.ts source. Assert BUNDLED_PACK_NAMES directly instead.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 10:55:16 -07:00
97e716b01f fix(minions): subagent default client resolves config-stored Anthropic key (#2048)
The legacy subagent path constructed a bare new Anthropic() (env-only), so
launchd/MCP workers whose key lives in gbrain config (anthropic_api_key)
failed auth. anthropic-key.ts now exports resolveAnthropicKey() (env first,
then config; hasAnthropicKey delegates) and makeSubagentHandler passes it as
apiKey.

Partial takeover of #2048 — only the auth patch; the path patches were
superseded by the outputRoot mechanism (#2415).

Co-authored-by: JiraiyaETH <JiraiyaETH@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:31:37 -07:00
ff737e4345 fix(schema): make bundled pack inspection truthful (#2029)
Two live bugs:
- parseYamlMini had no block-scalar support, so a 'description: |' swallowed
  every following top-level key — the active gbrain-recommended pack loaded
  with 0 page types. Add parseBlockScalar for |/|-/|+ and >/>-/>+ in both
  mapping and sequence-sibling positions.
- The bundled-pack list was hand-copied in three places (operations.ts had 2
  names, mutate.ts had 3, load-active.ts had 7). New single registry
  src/core/schema-pack/bundled.ts carries all 7 shipped packs; every
  consumer derives from it.

Takeover of #2029, rebased onto master (schema.ts hunks already landed).

Co-authored-by: JiraiyaETH <JiraiyaETH@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:31:37 -07:00
30 changed files with 243 additions and 202 deletions
-1
View File
@@ -457,7 +457,6 @@ 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,18 +91,3 @@ 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.
+3 -10
View File
@@ -23,7 +23,6 @@ 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
@@ -168,10 +167,7 @@ export async function runCalibration(
config: GBrainConfig,
): Promise<void> {
const { opts } = parseArgs(args);
const holder = resolveOwnerHolder({
override: opts.holder,
configValue: await engine.getConfig('emotional_weight.user_holder'),
});
const holder = opts.holder ?? 'garry';
// 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).
@@ -257,15 +253,12 @@ export async function getCalibrationProfileOp(
ctx: OperationContext,
params: { holder?: string },
): Promise<CalibrationProfileRow | null> {
const holder = resolveOwnerHolder({
override: params.holder,
configValue: await ctx.engine.getConfig('emotional_weight.user_holder'),
});
const holder = params.holder ?? 'garry';
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 owner holder (config emotional_weight.user_holder, else "self")',
'pass holder="<slug>" or omit to default to "garry"',
);
}
const scope = sourceScopeOpts(ctx);
+2 -8
View File
@@ -28,7 +28,6 @@ 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';
@@ -1288,19 +1287,14 @@ export async function checkAbandonedThreads(engine: BrainEngine): Promise<Check>
/**
* calibration_freshness: warns when the active calibration profile is
* older than 7 days (configurable). Default holder resolves via resolveOwnerHolder
* (config emotional_weight.user_holder, else 'self'). Multi-source
* older than 7 days (configurable). Default holder 'garry'. 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 = $1`,
[ownerHolder],
`SELECT MAX(generated_at) AS generated_at FROM calibration_profiles WHERE holder = 'garry'`,
);
const generated = rows[0]?.generated_at;
if (!generated) {
+3 -4
View File
@@ -45,7 +45,6 @@ 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
@@ -1191,7 +1190,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 = resolveOwnerHolder({ override: (req.query.holder as string) || undefined, configValue: await engine.getConfig('emotional_weight.user_holder') });
const holder = (req.query.holder as string) || 'garry';
const profile = await getLatestProfile(engine, { holder });
if (!profile) {
res.status(404).json({ error: 'no_profile' });
@@ -1241,7 +1240,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 = resolveOwnerHolder({ override: (req.query.holder as string) || undefined, configValue: await engine.getConfig('emotional_weight.user_holder') });
const holder = (req.query.holder as string) || 'garry';
const profile = await getLatestProfile(engine, { holder });
res.json(profile);
} catch (err) {
@@ -1258,7 +1257,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
renderAbandonedThreadsCard,
renderPatternStatementsCard,
} = await import('../core/calibration/svg-renderer.ts');
const holder = resolveOwnerHolder({ override: (req.query.holder as string) || undefined, configValue: await engine.getConfig('emotional_weight.user_holder') });
const holder = (req.query.holder as string) || 'garry';
const type = req.params.type;
const profile = await getLatestProfile(engine, { holder });
+1 -2
View File
@@ -29,7 +29,6 @@ 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 ---
@@ -365,7 +364,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') ?? resolveOwnerHolder({ configValue: await engine.getConfig('emotional_weight.user_holder') });
const resolvedBy = flagValue(args, '--by') ?? 'garry';
const dirArg = flagValue(args, '--dir');
const pageId = await getPageId(engine, slug, sourceId);
+13 -3
View File
@@ -18,12 +18,22 @@
import { loadConfig } from '../config.ts';
export function hasAnthropicKey(): boolean {
if (process.env.ANTHROPIC_API_KEY) return true;
return resolveAnthropicKey() !== undefined;
}
/**
* Resolve the actual key value: env first, then the gbrain config file.
* Callers constructing an Anthropic client directly (e.g. the legacy
* subagent path) must pass this as `apiKey` — a bare `new Anthropic()`
* only sees env, so launchd/MCP workers with config-stored keys fail.
*/
export function resolveAnthropicKey(): string | undefined {
if (process.env.ANTHROPIC_API_KEY) return process.env.ANTHROPIC_API_KEY;
try {
const cfg = loadConfig();
if (cfg?.anthropic_api_key) return true;
if (cfg?.anthropic_api_key) return cfg.anthropic_api_key;
} catch {
// loadConfig may throw on first-run installs; treat as no key available.
}
return false;
return undefined;
}
+2 -3
View File
@@ -68,7 +68,6 @@ import {
type BrainstormCheckpoint,
type CheckpointCross,
} from './checkpoint.ts';
import { resolveOwnerHolder } from '../owner-holder.ts';
export { BudgetExhausted };
@@ -140,7 +139,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 `'self'`. */
/** When set, force the user holder for calibration profile lookup. Falls back to config (`emotional_weight.user_holder`) then `'garry'`. */
holderOverride?: string;
/** Source scope. */
sourceId?: string;
@@ -624,7 +623,7 @@ async function _runBrainstormInner(
}
// ---- Phase 3: calibration context (cold-start fallback) ----
const holder = resolveOwnerHolder({ override: opts.holderOverride, configValue: config.emotional_weight?.user_holder });
const holder = opts.holderOverride ?? config.emotional_weight?.user_holder ?? 'garry';
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. Resolves via resolveOwnerHolder (config emotional_weight.user_holder, else 'self'). */
/** Holder context for calibration. Default 'garry'. */
holder?: string;
/** Engine for DB write. */
engine: BrainEngine;
+2 -6
View File
@@ -26,7 +26,6 @@
*/
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';
@@ -97,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 resolves via resolveOwnerHolder (config emotional_weight.user_holder, else 'self'). */
/** Holder to generate the profile for. Default 'garry'. */
holder?: string;
/** Inject the patterns generator (tests). */
patternsGenerator?: PatternStatementsGenerator;
@@ -228,10 +227,7 @@ class CalibrationProfilePhase extends BaseCyclePhase {
_ctx: OperationContext,
opts: CalibrationProfileOpts,
): Promise<{ summary: string; details: Record<string, unknown>; status?: PhaseStatus }> {
const holder = resolveOwnerHolder({
override: opts.holder,
configValue: await engine.getConfig('emotional_weight.user_holder'),
});
const holder = opts.holder ?? 'garry';
const promptVersion = opts.promptVersion ?? CALIBRATION_PROFILE_PROMPT_VERSION;
const modelId = opts.model ?? TIER_DEFAULTS.reasoning;
const gradeCompletion = opts.gradeCompletion ?? 1.0;
+4 -7
View File
@@ -14,8 +14,6 @@
* 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
@@ -45,12 +43,11 @@ export const HIGH_EMOTION_TAGS: ReadonlySet<string> = new Set([
]);
/**
* 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.
* 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).
*/
export const DEFAULT_USER_HOLDER = DEFAULT_OWNER_HOLDER;
export const DEFAULT_USER_HOLDER = 'garry';
export interface EmotionalWeightTake {
holder: string;
+5 -1
View File
@@ -48,6 +48,7 @@ import {
logSubagentHeartbeat,
} from './subagent-audit.ts';
import { resolveModel, isAnthropicProvider, TIER_DEFAULTS } from '../../model-config.ts';
import { resolveAnthropicKey } from '../../ai/anthropic-key.ts';
import { buildSystemPrompt, DEFAULT_SUBAGENT_SYSTEM } from '../system-prompt.ts';
import { toolLoop as gatewayToolLoop } from '../../ai/gateway.ts';
import type { ChatToolDef, ChatMessage, ChatBlock, ChatResult, ToolHandler } from '../../ai/gateway.ts';
@@ -186,7 +187,10 @@ export function makeSubagentHandler(deps: SubagentDeps) {
// lives at sdk.messages.create. Assigning sdk.messages directly gets the
// right object; JS method-call semantics preserve `this` at the call
// site (subagent.ts invokes client.create(...) with client === sdk.messages).
const makeAnthropic = deps.makeAnthropic ?? (() => new Anthropic());
// Resolve the key env-first, then config (anthropic_api_key) — a bare
// new Anthropic() only reads env, so launchd/MCP workers whose key lives
// in the gbrain config file would fail auth (#2048).
const makeAnthropic = deps.makeAnthropic ?? (() => new Anthropic({ apiKey: resolveAnthropicKey() }));
const client: MessagesClient = deps.client ?? makeAnthropic().messages;
const config = deps.config ?? loadConfig() ?? ({ engine: 'postgres' } as GBrainConfig);
const rateLeaseKey = deps.rateLeaseKey ?? DEFAULT_RATE_KEY;
+3 -2
View File
@@ -3289,7 +3289,7 @@ const get_calibration_profile: Operation = {
holder: {
type: 'string',
description:
"Holder slug, e.g. 'self' or 'people/charlie-example'. Defaults to config emotional_weight.user_holder, else 'self', when omitted.",
"Holder slug, e.g. 'garry' or 'people/charlie-example'. Defaults to 'garry' when omitted.",
},
},
handler: async (ctx, p) => {
@@ -4562,7 +4562,8 @@ 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'];
const { BUNDLED_PACK_NAMES } = await import('./schema-pack/bundled.ts');
const bundled = [...BUNDLED_PACK_NAMES];
const installedDir = gbrainPath('schema-packs');
const installed: string[] = [];
if (existsSync(installedDir)) {
-24
View File
@@ -1,24 +0,0 @@
/**
* 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;
}
+24
View File
@@ -0,0 +1,24 @@
// Bundled schema-pack registry — single source of truth for the packs that
// ship in src/core/schema-pack/base/. Keep every bundled-pack consumer
// (CLI/MCP inspection, active-pack loading, mutation guards, upgrade
// discovery) on this one list so they cannot drift.
//
// v0.39 T8 — gbrain-base + gbrain-recommended.
// v0.41 T4 — lens packs: creator, investor, engineer, everything (meta-pack).
// v0.42 type-unification — gbrain-base-v2, the 15-type canonical successor.
export const BUNDLED_PACK_NAMES = [
'gbrain-base',
'gbrain-recommended',
'gbrain-creator',
'gbrain-investor',
'gbrain-engineer',
'gbrain-everything',
'gbrain-base-v2',
] as const;
export type BundledPackName = typeof BUNDLED_PACK_NAMES[number];
export function isBundledPackName(name: string): name is BundledPackName {
return (BUNDLED_PACK_NAMES as readonly string[]).includes(name);
}
+2 -22
View File
@@ -37,6 +37,7 @@ import {
type ResolutionInput,
type ResolutionResult,
} from './registry.ts';
import { isBundledPackName } from './bundled.ts';
/**
* Inputs the caller (operations.ts handler / engine query path) provides.
@@ -92,28 +93,7 @@ export function _resetPackLocatorForTests(): void {
* throwing UnknownPackError with a paste-ready install hint.
*/
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 (isBundledPackName(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));
+31
View File
@@ -159,6 +159,29 @@ export function parseYamlMini(content: string): unknown {
return parseMapping(baseIndent);
}
function parseBlockScalar(parentIndent: number, folded: boolean): string {
const contentIndent = parentIndent + 2;
const out: string[] = [];
while (i < lines.length) {
const raw = lines[i];
// Inside a block scalar everything is literal content — '#' is NOT a
// comment here, so use the raw line (no stripComment / isBlank).
if (raw.trim() === '') {
out.push('');
i++;
continue;
}
const indent = indentOf(raw);
if (indent <= parentIndent) break;
out.push(raw.slice(Math.min(contentIndent, indent)));
i++;
}
if (folded) {
return out.join(' ').replace(/\s+$/u, '');
}
return out.join('\n').replace(/\n+$/u, '');
}
function parseSequence(baseIndent: number): unknown[] {
const result: unknown[] = [];
while (i < lines.length) {
@@ -227,6 +250,10 @@ export function parseYamlMini(content: string): unknown {
i++;
if (rest2 === '') {
map[key2] = parseBlock(nextIndent + 2);
} else if (rest2 === '|' || rest2 === '|-' || rest2 === '|+') {
map[key2] = parseBlockScalar(nextIndent, false);
} else if (rest2 === '>' || rest2 === '>-' || rest2 === '>+') {
map[key2] = parseBlockScalar(nextIndent, true);
} else {
map[key2] = parseScalar(rest2);
}
@@ -257,6 +284,10 @@ export function parseYamlMini(content: string): unknown {
i++;
if (rest === '') {
result[key] = parseBlock(indent + 2);
} else if (rest === '|' || rest === '|-' || rest === '|+') {
result[key] = parseBlockScalar(indent, false);
} else if (rest === '>' || rest === '>-' || rest === '>+') {
result[key] = parseBlockScalar(indent, true);
} else {
result[key] = parseScalar(rest);
}
+2 -1
View File
@@ -65,6 +65,7 @@ import { invalidateQueryCache } from './query-cache-invalidator.ts';
import { logMutationFailure, logMutationSuccess, type MutationActor, type MutationOp } from './mutate-audit.ts';
import { runFilePlaneLintRules } from './lint-rules.ts';
import { withPackLock, type PackLockOpts } from './pack-lock.ts';
import { BUNDLED_PACK_NAMES as BUNDLED_PACK_NAME_LIST } from './bundled.ts';
import type { BrainEngine } from '../engine.ts';
export type PackFileFormat = 'json' | 'yaml';
@@ -93,7 +94,7 @@ export class SchemaPackMutationError extends Error {
}
}
export const BUNDLED_PACK_NAMES = new Set(['gbrain-base', 'gbrain-recommended', 'gbrain-base-v2']);
export const BUNDLED_PACK_NAMES = new Set<string>(BUNDLED_PACK_NAME_LIST);
export interface MutateResult {
/** Pack name that was mutated. */
+3 -7
View File
@@ -23,7 +23,6 @@ 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';
@@ -77,8 +76,8 @@ export interface RunThinkOpts {
*/
withCalibration?: boolean;
/**
* Holder to retrieve the calibration profile for. Resolves via resolveOwnerHolder
* (config emotional_weight.user_holder, else 'self'). Only consulted when withCalibration=true.
* Holder to retrieve the calibration profile for. Default 'garry'. Only
* consulted when withCalibration=true.
*/
calibrationHolder?: string;
/**
@@ -309,10 +308,7 @@ export async function runThink(
try {
const { getLatestProfile } = await import('../../commands/calibration.ts');
const profile = await getLatestProfile(engine, {
holder: resolveOwnerHolder({
override: opts.calibrationHolder,
configValue: await engine.getConfig('emotional_weight.user_holder'),
}),
holder: opts.calibrationHolder ?? 'garry',
});
if (profile) {
calibrationBlockOpts = {
+33 -1
View File
@@ -10,7 +10,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { withEnv } from '../helpers/with-env.ts';
import { hasAnthropicKey } from '../../src/core/ai/anthropic-key.ts';
import { hasAnthropicKey, resolveAnthropicKey } from '../../src/core/ai/anthropic-key.ts';
const tmpDirs: string[] = [];
function freshHome(withConfig?: Record<string, unknown>): string {
@@ -62,3 +62,35 @@ describe('hasAnthropicKey', () => {
);
});
});
describe('resolveAnthropicKey (#2048 — subagent config-key auth)', () => {
test('env wins over config', async () => {
const home = freshHome({ anthropic_api_key: 'sk-from-config' });
await withEnv(
{ ANTHROPIC_API_KEY: 'sk-from-env', GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined },
async () => {
expect(resolveAnthropicKey()).toBe('sk-from-env');
},
);
});
test('config key returned when env unset', async () => {
const home = freshHome({ anthropic_api_key: 'sk-from-config' });
await withEnv(
{ ANTHROPIC_API_KEY: undefined, GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined },
async () => {
expect(resolveAnthropicKey()).toBe('sk-from-config');
},
);
});
test('neither → undefined', async () => {
const home = freshHome();
await withEnv(
{ ANTHROPIC_API_KEY: undefined, GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined },
async () => {
expect(resolveAnthropicKey()).toBeUndefined();
},
);
});
});
+7 -13
View File
@@ -27,12 +27,6 @@ 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 ?? []);
@@ -217,17 +211,17 @@ describe('formatProfileText', () => {
// ─── getCalibrationProfileOp ────────────────────────────────────────
describe('getCalibrationProfileOp (MCP)', () => {
test('defaults holder to "self" when omitted (config emotional_weight.user_holder unset)', async () => {
const { engine } = buildMockEngine({ rows: [buildProfile({ holder: 'self' })] });
test('defaults holder to "garry" when omitted', async () => {
const { engine } = buildMockEngine({ rows: [buildProfile({ holder: 'garry' })] });
const ctx = buildCtx(engine);
const result = await getCalibrationProfileOp(ctx, {});
expect(result?.holder).toBe('self');
expect(result?.holder).toBe('garry');
});
test('routes through sourceScopeOpts: scalar source-bound client gets source-scoped result', async () => {
const rows = [
buildProfile({ holder: 'self', source_id: 'default' }),
buildProfile({ holder: 'self', source_id: 'tenant-b' }),
buildProfile({ holder: 'garry', source_id: 'default' }),
buildProfile({ holder: 'garry', source_id: 'tenant-b' }),
];
const { engine } = buildMockEngine({ rows });
const ctx = buildCtx(engine, { sourceId: 'tenant-b' });
@@ -237,8 +231,8 @@ describe('getCalibrationProfileOp (MCP)', () => {
test('federated read scope sees the union of allowed sources', async () => {
const rows = [
buildProfile({ holder: 'self', source_id: 'tenant-a' }),
buildProfile({ holder: 'self', source_id: 'tenant-z' }),
buildProfile({ holder: 'garry', source_id: 'tenant-a' }),
buildProfile({ holder: 'garry', source_id: 'tenant-z' }),
];
const { engine } = buildMockEngine({ rows });
const ctx = buildCtx(engine, { allowedSources: ['tenant-a', 'tenant-b'] });
+2 -26
View File
@@ -32,7 +32,7 @@ interface CapturedSql {
params: unknown[];
}
function buildMockEngine(opts: { scorecard: TakesScorecard; userHolder?: string | null }): {
function buildMockEngine(opts: { scorecard: TakesScorecard }): {
engine: BrainEngine;
captured: CapturedSql[];
} {
@@ -42,10 +42,6 @@ function buildMockEngine(opts: { scorecard: TakesScorecard; userHolder?: string
async getScorecard() {
return opts.scorecard;
},
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 ?? [] });
return [];
@@ -238,7 +234,7 @@ 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('self'); // holder (resolved via resolveOwnerHolder, no override)
expect(insert!.params[1]).toBe('garry'); // holder
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
@@ -334,24 +330,4 @@ 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,12 +32,6 @@ 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,7 +112,3 @@ 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');
});
+6 -6
View File
@@ -55,13 +55,13 @@ describe('v0.41 T4: all 4 bundled lens packs parse cleanly', () => {
});
describe('v0.41 T4: bundled registry includes lens packs', () => {
test('load-active.ts BUNDLED array source includes the 4 lens pack names', () => {
const loadActiveSrc = readFileSync(
join(here, '..', 'src', 'core', 'schema-pack', 'load-active.ts'),
'utf-8',
);
test('BUNDLED_PACK_NAMES includes the 4 lens pack names', async () => {
// The bundled list moved from load-active.ts to bundled.ts (the
// single source of truth); assert the array directly instead of
// grepping source text.
const { BUNDLED_PACK_NAMES } = await import('../src/core/schema-pack/bundled.ts');
for (const name of PACK_NAMES) {
expect(loadActiveSrc).toContain(`'${name}'`);
expect(BUNDLED_PACK_NAMES).toContain(name);
}
});
});
+3
View File
@@ -149,6 +149,9 @@ describe('list_schema_packs', () => {
seedPack('mine');
const result = await operationsByName.list_schema_packs!.handler(ctxOf(), {}) as { bundled: string[]; installed: string[] };
expect(result.bundled).toContain('gbrain-base');
expect(result.bundled).toContain('gbrain-recommended');
expect(result.bundled).toContain('gbrain-base-v2');
expect(result.bundled).toContain('gbrain-investor');
expect(result.installed).toContain('mine');
});
});
-27
View File
@@ -1,27 +0,0 @@
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');
});
});
+38 -1
View File
@@ -64,11 +64,14 @@ describe('gbrain schema CLI (Phase C)', () => {
expect(r.stdout + r.stderr).toMatch(/schema|active|list|show|validate|use/i);
});
test('schema list shows gbrain-base bundled', () => {
test('schema list shows all bundled packs', () => {
const r = gbrain(['schema', 'list']);
expect(r.code).toBe(0);
expect(r.stdout).toContain('Bundled packs:');
expect(r.stdout).toContain('gbrain-base');
expect(r.stdout).toContain('gbrain-recommended');
expect(r.stdout).toContain('gbrain-base-v2');
expect(r.stdout).toContain('gbrain-investor');
});
test('schema show gbrain-base prints manifest details', () => {
@@ -97,6 +100,40 @@ describe('gbrain schema CLI (Phase C)', () => {
expect(r.stdout).toContain('valid manifest');
});
test('schema show/validate exposes bundled gbrain-recommended', () => {
const show = gbrain(['schema', 'show', 'gbrain-recommended']);
expect(show.code).toBe(0);
expect(show.stdout).toContain('gbrain-recommended v1.0.0');
expect(show.stdout).toContain('Page types (');
expect(show.stdout).toContain('meeting :: temporal');
const validate = gbrain(['schema', 'validate', 'gbrain-recommended']);
expect(validate.code).toBe(0);
expect(validate.stdout).toContain('valid manifest');
});
test('schema show exposes bundled gbrain-base-v2 successor pack', () => {
const r = gbrain(['schema', 'show', 'gbrain-base-v2']);
expect(r.code).toBe(0);
expect(r.stdout).toContain('gbrain-base-v2 v1.0.0');
expect(r.stdout).toContain('Page types (');
expect(r.stdout).toContain('Link verbs (14)');
});
test('schema active loads configured gbrain-recommended with real types', () => {
const home = mkdtempSync(join(tmpdir(), 'gbrain-schema-active-recommended-'));
try {
mkdirSync(join(home, '.gbrain'), { recursive: true });
writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ schema_pack: 'gbrain-recommended' }), 'utf-8');
const r = gbrain(['schema', 'active'], { GBRAIN_HOME: home });
expect(r.code).toBe(0);
expect(r.stdout).toContain('Active pack: gbrain-recommended');
expect(r.stdout).not.toContain('Page types: 0');
} finally {
rmSync(home, { recursive: true, force: true });
}
});
test('schema active reports default resolution', () => {
const r = gbrain(['schema', 'active']);
expect(r.code).toBe(0);
+49
View File
@@ -345,6 +345,34 @@ describe('YAML mini-parser', () => {
expect(result.types[1].weight).toBe(2);
});
test('parses block scalar without swallowing following keys', () => {
const yaml = `name: blocky
description: |
First line.
Second line.
page_types:
- name: meeting
primitive: temporal
path_prefixes:
- meetings/
aliases: []
extractable: true
expert_routing: false`;
const result = parseYamlMini(yaml) as { description: string; page_types: Array<Record<string, unknown>> };
expect(result.description).toBe('First line.\nSecond line.');
expect(result.page_types).toHaveLength(1);
expect(result.page_types[0].name).toBe('meeting');
});
test('block scalar keeps # as literal content, not a comment', () => {
const yaml = `description: |
See issue #2029 for context.
name: hashy`;
const result = parseYamlMini(yaml) as Record<string, unknown>;
expect(result.description).toBe('See issue #2029 for context.');
expect(result.name).toBe('hashy');
});
test('strips comments', () => {
const result = parseYamlMini('# top comment\nname: value # inline comment') as Record<string, unknown>;
expect(result.name).toBe('value');
@@ -374,6 +402,27 @@ extends: null`;
const pack = loadPackFromString(json, 'fixture.json');
expect(pack.name).toBe('json-pack');
});
test('loads block-scalar pack descriptions without losing page types', () => {
const pack = loadPackFromString(`api_version: gbrain-schema-pack-v1
name: recommended-fixture
version: 1.0.0
extends: gbrain-base
description: |
Operational starter pack.
page_types:
- name: meeting
primitive: temporal
path_prefixes:
- meetings/
aliases: []
extractable: true
expert_routing: false
link_types: []`, 'fixture.yaml');
expect(pack.name).toBe('recommended-fixture');
expect(pack.extends).toBe('gbrain-base');
expect(pack.page_types.map((t) => t.name)).toContain('meeting');
});
});
describe('ReDoS guard', () => {
+4 -1
View File
@@ -103,7 +103,10 @@ describe('locateMutablePackFile — bundled guard', () => {
expect(BUNDLED_PACK_NAMES.has('gbrain-recommended')).toBe(true);
// v0.42 (T22): gbrain-base-v2 joins the bundled set.
expect(BUNDLED_PACK_NAMES.has('gbrain-base-v2')).toBe(true);
expect(BUNDLED_PACK_NAMES.size).toBe(3);
// Derived from the single bundled registry — the lens packs (creator,
// investor, engineer, everything) are read-only too.
expect(BUNDLED_PACK_NAMES.has('gbrain-investor')).toBe(true);
expect(BUNDLED_PACK_NAMES.size).toBe(7);
});
it('rejects gbrain-base-v2 with PACK_READONLY (bundled guard)', () => {