Compare commits

..
Author SHA1 Message Date
Garry TanandClaude Fable 5 6548e5cffc fix(autopilot): add --target to value-flag set so install targets survive positional translation
Review finding on #3103: --target is installDaemon's value flag
(macos | linux-systemd | ephemeral-container | linux-cron). The
translator only knew --repo/--interval, so `gbrain autopilot
--install --target linux-cron` misread the target value as an
unknown positional subcommand and exited 2 before installDaemon ran.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 12:05:46 -07:00
0ac3d4da9c fix(autopilot): translate positional subcommands so autopilot status doesn't start the daemon
Takeover/rebase of #1529 onto current master. `gbrain autopilot status`
(and install/uninstall/start) previously fell through the flag-only
branches in runAutopilot and silently started the daemon (lockfile +
worker spawn + sync dispatch). A pure translatePositionalSubcommands()
now maps known positionals to their flag form before any side effect,
is value-flag aware (--repo/--interval), and fails loud (exit 2) on
unknown positionals. 22 tests including the exact #1525 repro.

Fixes #1525

Co-authored-by: Oszkar <Oszkar@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:28:16 -07:00
13 changed files with 339 additions and 279 deletions
+109
View File
@@ -151,6 +151,100 @@ export function shouldSpawnAutopilotWorker(args: string[]): boolean {
return !args.includes('--no-worker');
}
/**
* #1525 — positional subcommand translation.
*
* Pre-fix, `gbrain autopilot status` silently fell through to "start daemon"
* because `runAutopilot()` only branched on flag forms (`--status`, etc.).
* `status` was treated as a stray positional and ignored.
*
* This translator maps known positional subcommands to their flag form so
* `autopilot status` is equivalent to `autopilot --status`, then rejects
* any unrecognized positional with a fail-loud error before any side
* effect (lockfile, daemon spawn, sync dispatch) runs.
*
* Scope decisions:
* - Known aliases: `status` → `--status`, `install` → `--install`,
* `uninstall` → `--uninstall`, `start` → (drop; default daemon launch).
* - `stop` is intentionally NOT aliased here. Stopping a running daemon
* is a new behavior (read PID from lock, SIGTERM, drain) that deserves
* its own design and PR. Users typing `gbrain autopilot stop` today get
* the unknown-positional error with the canonical alternatives.
* - At most one positional allowed; multiple positionals fail loud.
*/
// Every flag that consumes the NEXT argv token. Missing one here makes the
// translator misread the flag's value as a positional subcommand and exit 2
// (e.g. `--install --target linux-cron`). Keep in sync with parseArg call sites.
const AUTOPILOT_VALUE_FLAGS = new Set(['--repo', '--interval', '--target']);
const AUTOPILOT_POSITIONAL_ALIASES: Record<string, string | null> = {
status: '--status',
install: '--install',
uninstall: '--uninstall',
start: null, // drop the positional; default behavior is daemon launch
};
export type PositionalTranslation =
| { ok: true; args: string[] }
| {
ok: false;
reason: 'unknown_subcommand' | 'multiple_subcommands';
message: string;
};
export function translatePositionalSubcommands(args: string[]): PositionalTranslation {
const out: string[] = [];
let positionalSeen = false;
let i = 0;
while (i < args.length) {
const a = args[i];
if (AUTOPILOT_VALUE_FLAGS.has(a)) {
// Pass through the flag and its value untouched. If the value is
// missing at end-of-argv, fall through so the existing parseArg
// path can report the broken usage.
out.push(a);
if (i + 1 < args.length) {
out.push(args[i + 1]);
i += 2;
} else {
i += 1;
}
continue;
}
if (a.startsWith('-')) {
out.push(a);
i += 1;
continue;
}
// Positional subcommand.
if (positionalSeen) {
const known = Object.keys(AUTOPILOT_POSITIONAL_ALIASES).join(', ');
return {
ok: false,
reason: 'multiple_subcommands',
message: `Multiple subcommands given. Use only one of: ${known}.`,
};
}
positionalSeen = true;
if (a in AUTOPILOT_POSITIONAL_ALIASES) {
const alias = AUTOPILOT_POSITIONAL_ALIASES[a];
if (alias) out.push(alias);
i += 1;
continue;
}
const known = Object.keys(AUTOPILOT_POSITIONAL_ALIASES).join(', ');
return {
ok: false,
reason: 'unknown_subcommand',
message:
`Unknown subcommand: \`${a}\`.\n` +
`Allowed subcommands: ${known}.\n` +
`Or use the flag form: --status, --install, --uninstall.\n` +
`Run \`gbrain autopilot --help\` for full usage.`,
};
}
return { ok: true, args: out };
}
export function isPidAlive(pid: number): boolean {
if (!Number.isFinite(pid) || pid <= 0) return false;
try {
@@ -363,6 +457,11 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
' gbrain autopilot --install [--repo <path>]\n' +
' gbrain autopilot --uninstall\n' +
' gbrain autopilot --status [--json]\n\n' +
'Subcommand aliases:\n' +
' gbrain autopilot status → --status\n' +
' gbrain autopilot install → --install\n' +
' gbrain autopilot uninstall → --uninstall\n' +
' gbrain autopilot start → (default daemon launch)\n\n' +
'Self-maintaining brain daemon. Runs the full maintenance cycle\n' +
'(lint + backlinks + sync + extract + embed + orphans) on an interval.\n\n' +
'For a one-shot cron-triggered cycle, see `gbrain dream`.',
@@ -370,6 +469,16 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
return;
}
// #1525: translate positional subcommands to their flag form BEFORE any
// side effect (lockfile, daemon spawn, sync dispatch). Unknown positionals
// fail loud here rather than silently starting the daemon.
const translated = translatePositionalSubcommands(args);
if (!translated.ok) {
console.error(translated.message);
process.exit(2);
}
args = translated.args;
if (args.includes('--install')) {
await installDaemon(engine, args);
return;
+5 -5
View File
@@ -19,7 +19,7 @@
*/
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';
@@ -167,7 +167,7 @@ export async function runCalibration(
config: GBrainConfig,
): Promise<void> {
const { opts } = parseArgs(args);
const holder = await resolveCalibrationHolder(engine, opts.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).
@@ -253,14 +253,14 @@ 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 = 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 calibration.user_holder config (then "garry")',
'pass holder="<slug>" or omit to default to "garry"',
);
}
const holder = await resolveCalibrationHolder(ctx.engine, params.holder);
const scope = sourceScopeOpts(ctx);
return getLatestProfile(ctx.engine, { holder, ...scope });
}
-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)
+2 -22
View File
@@ -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: `calibration.user_holder` config, then 'garry'. */
/** Holder to generate the profile for. Default 'garry'. */
holder?: string;
/** Inject the patterns generator (tests). */
patternsGenerator?: PatternStatementsGenerator;
@@ -194,26 +194,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 +227,7 @@ 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 = opts.holder ?? 'garry';
const promptVersion = opts.promptVersion ?? CALIBRATION_PROFILE_PROMPT_VERSION;
const modelId = opts.model ?? TIER_DEFAULTS.reasoning;
const gradeCompletion = opts.gradeCompletion ?? 1.0;
+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`,
);
+1 -4
View File
@@ -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)) {
@@ -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));
@@ -0,0 +1,197 @@
/**
* Tests for translatePositionalSubcommands() — the v0.41.x #1525 fix that
* prevents `gbrain autopilot status` from silently starting the daemon.
*
* IRON RULE regression guard: the exact ticket repro (`gbrain autopilot
* status`) MUST translate to `--status`, not fall through to the default
* daemon launch. Verified by the "ticket-exact repro" case below.
*/
import { describe, test, expect } from 'bun:test';
import { translatePositionalSubcommands } from '../src/commands/autopilot.ts';
describe('translatePositionalSubcommands — known aliases', () => {
test('IRON RULE — `autopilot status` translates to `--status` (ticket #1525 repro)', () => {
const r = translatePositionalSubcommands(['status']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(['--status']);
});
test('`install` translates to `--install`', () => {
const r = translatePositionalSubcommands(['install']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(['--install']);
});
test('`uninstall` translates to `--uninstall`', () => {
const r = translatePositionalSubcommands(['uninstall']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(['--uninstall']);
});
test('`start` drops the positional (default daemon launch)', () => {
const r = translatePositionalSubcommands(['start']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual([]);
});
test('`start --json` drops only the positional, keeps the flag', () => {
const r = translatePositionalSubcommands(['start', '--json']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(['--json']);
});
});
describe('translatePositionalSubcommands — flag/positional interleaving', () => {
test('`status --json` preserves the trailing flag', () => {
const r = translatePositionalSubcommands(['status', '--json']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(['--status', '--json']);
});
test('`--json status` preserves the leading flag', () => {
const r = translatePositionalSubcommands(['--json', 'status']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(['--json', '--status']);
});
test('`--repo /foo status` does not mis-classify the path as positional', () => {
const r = translatePositionalSubcommands(['--repo', '/foo', 'status']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(['--repo', '/foo', '--status']);
});
test('`--interval 300 install` does not mis-classify the number as positional', () => {
const r = translatePositionalSubcommands(['--interval', '300', 'install']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(['--interval', '300', '--install']);
});
test('`--install --target linux-cron` does not mis-classify the target as positional', () => {
// --target is installDaemon's value flag; its value must never be read
// as a positional subcommand (regression guard for the review fix).
const r = translatePositionalSubcommands(['--install', '--target', 'linux-cron']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(['--install', '--target', 'linux-cron']);
});
test('`install --target macos` keeps the alias translation and the target value', () => {
const r = translatePositionalSubcommands(['install', '--target', 'macos']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(['--install', '--target', 'macos']);
});
test('value-flag at end of argv with missing value passes through (so parseArg can report it)', () => {
const r = translatePositionalSubcommands(['--repo']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(['--repo']);
});
test('value-flag whose value looks like an alias is NOT translated', () => {
// `--repo status` means "use repo path 'status'", not "show status".
// Translator must not destructure the value of --repo.
const r = translatePositionalSubcommands(['--repo', 'status']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(['--repo', 'status']);
});
});
describe('translatePositionalSubcommands — pass-through cases', () => {
test('empty args returns empty args', () => {
const r = translatePositionalSubcommands([]);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual([]);
});
test('flag-only invocation passes through unchanged', () => {
const r = translatePositionalSubcommands(['--status', '--json']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(['--status', '--json']);
});
test('short flag `-h` passes through unchanged', () => {
const r = translatePositionalSubcommands(['-h']);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(['-h']);
});
test('all known bare flags pass through unchanged', () => {
const flags = ['--help', '--install', '--uninstall', '--status', '--json', '--inline', '--no-worker'];
const r = translatePositionalSubcommands(flags);
expect(r.ok).toBe(true);
if (r.ok) expect(r.args).toEqual(flags);
});
});
describe('translatePositionalSubcommands — rejection of unknown positionals', () => {
test('unknown positional `foo` fails with reason=unknown_subcommand + structured message', () => {
const r = translatePositionalSubcommands(['foo']);
expect(r.ok).toBe(false);
if (!r.ok) {
expect(r.reason).toBe('unknown_subcommand');
expect(r.message).toContain('Unknown subcommand: `foo`');
expect(r.message).toContain('status');
expect(r.message).toContain('install');
expect(r.message).toContain('uninstall');
expect(r.message).toContain('--help');
}
});
test('unknown positional `stop` fails with reason=unknown_subcommand (NOT silently aliased)', () => {
// Stop is mentioned in the ticket but deliberately NOT aliased in this
// PR — stopping a running daemon is a new behavior, not just an alias.
// Until that feature lands separately, `stop` must fail loud rather
// than starting the daemon (the bug we're fixing).
const r = translatePositionalSubcommands(['stop']);
expect(r.ok).toBe(false);
if (!r.ok) {
expect(r.reason).toBe('unknown_subcommand');
expect(r.message).toContain('Unknown subcommand: `stop`');
}
});
test('unknown positional `status-detail` (close-but-not-matching) fails', () => {
const r = translatePositionalSubcommands(['status-detail']);
expect(r.ok).toBe(false);
if (!r.ok) {
expect(r.reason).toBe('unknown_subcommand');
expect(r.message).toContain('Unknown subcommand: `status-detail`');
}
});
test('multiple positionals fail with reason=multiple_subcommands (`start install`)', () => {
const r = translatePositionalSubcommands(['start', 'install']);
expect(r.ok).toBe(false);
if (!r.ok) {
expect(r.reason).toBe('multiple_subcommands');
expect(r.message).toContain('Multiple subcommands');
}
});
test('multiple positionals fail even when both are known aliases (`status install`)', () => {
const r = translatePositionalSubcommands(['status', 'install']);
expect(r.ok).toBe(false);
if (!r.ok) {
expect(r.reason).toBe('multiple_subcommands');
expect(r.message).toContain('Multiple subcommands');
}
});
test('known-then-unknown rejects with multiple_subcommands (first-positional-wins)', () => {
// First positional is known, second is not. Rejection comes from the
// multiple-positional rule, which fires before the unknown check; the
// intent is "only one subcommand allowed."
const r = translatePositionalSubcommands(['status', 'garbage']);
expect(r.ok).toBe(false);
if (!r.ok) expect(r.reason).toBe('multiple_subcommands');
});
test('unknown-then-known rejects on the unknown (unknown fires before second-positional check)', () => {
const r = translatePositionalSubcommands(['garbage', 'status']);
expect(r.ok).toBe(false);
if (!r.ok) {
expect(r.reason).toBe('unknown_subcommand');
expect(r.message).toContain('garbage');
}
});
});
+1 -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 }): {
engine: BrainEngine;
captured: CapturedSql[];
} {
@@ -42,9 +42,6 @@ function buildMockEngine(opts: { scorecard: TakesScorecard; config?: Record<stri
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 [];
@@ -244,36 +241,6 @@ 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 () => [
-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 ───────────────────────────────────────────────────────
@@ -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([]);
});
});