mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-16 18:02:30 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b45023dba |
Vendored
-56
File diff suppressed because one or more lines are too long
Vendored
+57
File diff suppressed because one or more lines are too long
Vendored
+1
-1
@@ -7,7 +7,7 @@
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
|
||||
<script type="module" crossorigin src="/admin/assets/index-CoGEje3-.js"></script>
|
||||
<script type="module" crossorigin src="/admin/assets/index-CzLjRij_.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/admin/assets/index-GxkWX7v3.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -39,6 +39,7 @@ export const api = {
|
||||
stats: () => apiFetch('/admin/api/stats'),
|
||||
health: () => apiFetch('/admin/api/health-indicators'),
|
||||
agents: () => apiFetch('/admin/api/agents'),
|
||||
sources: () => apiFetch('/admin/api/sources'),
|
||||
requests: (page = 1, qs = '') => apiFetch(`/admin/api/requests?page=${page}${qs}`),
|
||||
apiKeys: () => apiFetch('/admin/api/api-keys'),
|
||||
createApiKey: (name: string) => apiFetch('/admin/api/api-keys', { method: 'POST', body: JSON.stringify({ name }) }),
|
||||
|
||||
@@ -23,9 +23,16 @@ interface Agent {
|
||||
total_requests: number;
|
||||
requests_today: number;
|
||||
token_ttl: number | null;
|
||||
source_id: string | null;
|
||||
federated_read: string[] | null;
|
||||
status: 'active' | 'revoked';
|
||||
}
|
||||
|
||||
interface SourceOption {
|
||||
id: string;
|
||||
name: string | null;
|
||||
}
|
||||
|
||||
interface ApiKey {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -88,6 +95,7 @@ export function AgentsPage() {
|
||||
<th>Name</th>
|
||||
<th>Type</th>
|
||||
<th>Scopes</th>
|
||||
<th>Source</th>
|
||||
<th>Status</th>
|
||||
<th>Requests</th>
|
||||
<th>Last Used</th>
|
||||
@@ -108,6 +116,9 @@ export function AgentsPage() {
|
||||
<span key={s} className={`badge badge-${s}`} style={{ marginRight: 4 }}>{s}</span>
|
||||
))}
|
||||
</td>
|
||||
<td className="mono" style={{ fontSize: 12, color: 'var(--text-secondary)' }}>
|
||||
{a.auth_type === 'oauth' ? (a.source_id || 'default') : 'all'}
|
||||
</td>
|
||||
<td>
|
||||
<span className={`badge ${a.status === 'active' ? 'badge-success' : 'badge-danger'}`}>{a.status}</span>
|
||||
</td>
|
||||
@@ -257,9 +268,29 @@ function RegisterModal({ onClose, onRegistered }: {
|
||||
Object.fromEntries(ALLOWED_SCOPES_LIST.map(s => [s, s === 'read'])) as Record<Scope, boolean>,
|
||||
);
|
||||
const [ttl, setTtl] = useState('86400'); // 24h default
|
||||
const [redirectUris, setRedirectUris] = useState('');
|
||||
const [sources, setSources] = useState<SourceOption[]>([{ id: 'default', name: 'default' }]);
|
||||
const [sourceId, setSourceId] = useState('default');
|
||||
const [readSources, setReadSources] = useState<Record<string, boolean>>({ default: true });
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
api.sources()
|
||||
.then((rows: SourceOption[]) => {
|
||||
const nextSources = rows.length > 0 ? rows : [{ id: 'default', name: 'default' }];
|
||||
const nextSourceId = nextSources.some(s => s.id === sourceId) ? sourceId : nextSources[0].id;
|
||||
setSources(nextSources);
|
||||
setSourceId(nextSourceId);
|
||||
setReadSources(prev => {
|
||||
const next = Object.fromEntries(nextSources.map(s => [s.id, Boolean(prev[s.id])])) as Record<string, boolean>;
|
||||
next[nextSourceId] = true;
|
||||
return next;
|
||||
});
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const ttlOptions = [
|
||||
{ label: '1 hour', value: '3600' },
|
||||
{ label: '24 hours', value: '86400' },
|
||||
@@ -277,11 +308,24 @@ function RegisterModal({ onClose, onRegistered }: {
|
||||
try {
|
||||
// Use the CLI registration endpoint (POST to admin API)
|
||||
const selectedScopes = Object.entries(scopes).filter(([, v]) => v).map(([k]) => k).join(' ');
|
||||
const federatedRead = sources.map(s => s.id).filter(id => readSources[id]);
|
||||
if (federatedRead.length === 0) { setError('Select at least one read source'); setLoading(false); return; }
|
||||
// #1036: redirect URIs, one per line. Mirrors the CLI convention
|
||||
// (src/commands/auth.ts): presence of redirect URIs implies
|
||||
// authorization_code + refresh_token grants unless the user had none.
|
||||
const uris = redirectUris.split('\n').map(u => u.trim()).filter(Boolean);
|
||||
const res = await fetch('/admin/api/register-client', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: name.trim(), scopes: selectedScopes, tokenTtl: ttl === '0' ? 315360000 : Number(ttl) }),
|
||||
body: JSON.stringify({
|
||||
name: name.trim(),
|
||||
scopes: selectedScopes,
|
||||
tokenTtl: ttl === '0' ? 315360000 : Number(ttl),
|
||||
source_id: sourceId,
|
||||
federated_read: federatedRead,
|
||||
...(uris.length > 0 ? { redirectUris: uris, grantTypes: ['authorization_code', 'refresh_token'] } : {}),
|
||||
}),
|
||||
});
|
||||
if (!res.ok) throw new Error('Registration failed');
|
||||
const data = await res.json();
|
||||
@@ -312,6 +356,42 @@ function RegisterModal({ onClose, onRegistered }: {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<label>Write Source</label>
|
||||
<select value={sourceId} onChange={e => {
|
||||
const id = e.target.value;
|
||||
setSourceId(id);
|
||||
setReadSources(p => ({ ...p, [id]: true }));
|
||||
}}
|
||||
style={{ width: '100%', background: 'var(--bg-secondary)', color: 'var(--text-primary)', border: '1px solid var(--border)', borderRadius: 6, padding: '6px 10px', fontSize: 14 }}>
|
||||
{sources.map(s => <option key={s.id} value={s.id}>{s.name && s.name !== s.id ? `${s.id} (${s.name})` : s.id}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<label>Read Sources</label>
|
||||
<div className="checkbox-group">
|
||||
{sources.map(s => (
|
||||
<label key={s.id} className="checkbox-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(readSources[s.id])}
|
||||
onChange={e => setReadSources(p => ({ ...p, [s.id]: e.target.checked }))}
|
||||
/>
|
||||
{s.name && s.name !== s.id ? `${s.id} (${s.name})` : s.id}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<label>Redirect URIs <span style={{ color: 'var(--text-secondary)', fontWeight: 400 }}>(optional, one per line — enables authorization_code flow)</span></label>
|
||||
<textarea
|
||||
placeholder={'https://example.com/callback'}
|
||||
value={redirectUris}
|
||||
onChange={e => setRedirectUris(e.target.value)}
|
||||
rows={2}
|
||||
style={{ width: '100%', background: 'var(--bg-secondary)', color: 'var(--text-primary)', border: '1px solid var(--border)', borderRadius: 6, padding: '6px 10px', fontSize: 13, fontFamily: 'inherit', resize: 'vertical' }}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<label>Token Lifetime</label>
|
||||
<select value={ttl} onChange={e => setTtl(e.target.value)}
|
||||
@@ -528,6 +608,8 @@ function AgentDrawer({ agent, onClose, onRevoked }: { agent: Agent; onClose: ()
|
||||
client_name: agentName,
|
||||
auth_type: agent.auth_type,
|
||||
scope: agent.scope,
|
||||
source_id: agent.source_id,
|
||||
federated_read: agent.federated_read,
|
||||
}, null, 2),
|
||||
};
|
||||
|
||||
@@ -547,6 +629,10 @@ function AgentDrawer({ agent, onClose, onRevoked }: { agent: Agent; onClose: ()
|
||||
<span>{(agent.scope || '').split(' ').filter(Boolean).map(s => (
|
||||
<span key={s} className={`badge badge-${s}`} style={{ marginRight: 4 }}>{s}</span>
|
||||
))}</span>
|
||||
<span style={{ color: 'var(--text-secondary)' }}>Write Source</span>
|
||||
<span className="mono">{agent.source_id || (isOAuth ? 'default' : 'all')}</span>
|
||||
<span style={{ color: 'var(--text-secondary)' }}>Read Sources</span>
|
||||
<span className="mono">{isOAuth ? (agent.federated_read && agent.federated_read.length > 0 ? agent.federated_read.join(', ') : (agent.source_id || 'default')) : 'all'}</span>
|
||||
<span style={{ color: 'var(--text-secondary)' }}>Registered</span>
|
||||
<span>{new Date(agent.created_at).toLocaleDateString()}</span>
|
||||
<span style={{ color: 'var(--text-secondary)' }}>Token TTL</span>
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
// AUTO-GENERATED — do not edit by hand.
|
||||
// Run `bun run scripts/build-admin-embedded.ts` to regenerate.
|
||||
// Source: admin/dist/ at 2026-05-27.
|
||||
// Source: admin/dist/ at 2026-07-21.
|
||||
//
|
||||
// Bun resolves the file: imports to a path that works at runtime even
|
||||
// inside a compiled binary (`bun build --compile`). The manifest maps
|
||||
// the request path the express handler sees to (resolved-path, mime).
|
||||
|
||||
// @ts-ignore — type: 'file' is Bun ESM, not in lib.d.ts
|
||||
import A_0_assets_index_CoGEje3__js from '../admin/dist/assets/index-CoGEje3-.js' with { type: 'file' };
|
||||
import A_0_assets_index_CzLjRij__js from '../admin/dist/assets/index-CzLjRij_.js' with { type: 'file' };
|
||||
// @ts-ignore — type: 'file' is Bun ESM, not in lib.d.ts
|
||||
import A_1_assets_index_GxkWX7v3_css from '../admin/dist/assets/index-GxkWX7v3.css' with { type: 'file' };
|
||||
// @ts-ignore — type: 'file' is Bun ESM, not in lib.d.ts
|
||||
@@ -19,7 +19,7 @@ export interface AdminAsset {
|
||||
}
|
||||
|
||||
export const ADMIN_ASSETS: Record<string, AdminAsset> = {
|
||||
"/admin/assets/index-CoGEje3-.js": { path: A_0_assets_index_CoGEje3__js as unknown as string, mime: "application/javascript; charset=utf-8" },
|
||||
"/admin/assets/index-CzLjRij_.js": { path: A_0_assets_index_CzLjRij__js as unknown as string, mime: "application/javascript; charset=utf-8" },
|
||||
"/admin/assets/index-GxkWX7v3.css": { path: A_1_assets_index_GxkWX7v3_css as unknown as string, mime: "text/css; charset=utf-8" },
|
||||
"/admin/index.html": { path: A_2_index_html as unknown as string, mime: "text/html; charset=utf-8" },
|
||||
};
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ import * as db from '../core/db.ts';
|
||||
import { sqlQueryForEngine, executeRawJsonb } from '../core/sql-query.ts';
|
||||
import { MinionQueue } from '../core/minions/queue.ts';
|
||||
import { isRetryableError } from '../core/retry-matcher.ts';
|
||||
import { normalizeAdminClientSourceScope } from '../core/admin-source-scope.ts';
|
||||
import {
|
||||
computeContentHash,
|
||||
validateIngestionEvent,
|
||||
@@ -1086,6 +1087,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
const oauthClients = await sql`
|
||||
SELECT c.client_id as id, c.client_name as name, 'oauth' as auth_type,
|
||||
c.grant_types, c.scope, c.created_at, c.token_ttl,
|
||||
c.source_id, c.federated_read,
|
||||
CASE WHEN c.deleted_at IS NOT NULL THEN 'revoked' ELSE 'active' END as status,
|
||||
(SELECT max(created_at) FROM mcp_request_log WHERE token_name = c.client_id) as last_used_at,
|
||||
(SELECT count(*)::int FROM mcp_request_log WHERE token_name = c.client_id) as total_requests,
|
||||
@@ -1095,6 +1097,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
const legacyKeys = await sql`
|
||||
SELECT a.id, a.name, 'api_key' as auth_type,
|
||||
'{"bearer"}' as grant_types, 'read write admin' as scope, a.created_at, null as token_ttl,
|
||||
null as source_id, null as federated_read,
|
||||
CASE WHEN a.revoked_at IS NOT NULL THEN 'revoked' ELSE 'active' END as status,
|
||||
a.last_used_at,
|
||||
(SELECT count(*)::int FROM mcp_request_log WHERE token_name = a.name) as total_requests,
|
||||
@@ -1107,6 +1110,17 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/admin/api/sources', requireAdmin, async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const sources = await engine.listAllSources({ includeArchived: false });
|
||||
const options = sources.map(s => ({ id: s.id, name: s.name }));
|
||||
if (!options.some(s => s.id === 'default')) options.unshift({ id: 'default', name: 'default' });
|
||||
res.json(options);
|
||||
} catch (e) {
|
||||
res.status(503).json({ error: 'service_unavailable' });
|
||||
}
|
||||
});
|
||||
|
||||
// v0.38 Slice 4 — per-OAuth-client agent spend viewer. Pre-computes today's
|
||||
// spend (committed + pending reservations) per client so the Agents tab
|
||||
// can render a "$X / $Y today" cell. Read-side endpoint only — no mutation.
|
||||
@@ -1440,6 +1454,8 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
// missing, empty) and rejects the rest with a structured 400.
|
||||
const { name, tokenTtl, grantTypes, redirectUris, tokenEndpointAuthMethod } = req.body;
|
||||
const rawScopes = (req.body as Record<string, unknown>).scopes ?? (req.body as Record<string, unknown>).scope;
|
||||
const rawSourceId = (req.body as Record<string, unknown>).source_id ?? (req.body as Record<string, unknown>).sourceId;
|
||||
const rawFederatedRead = (req.body as Record<string, unknown>).federated_read ?? (req.body as Record<string, unknown>).federatedRead;
|
||||
if (!name) { res.status(400).json({ error: 'Name required' }); return; }
|
||||
let scopeString: string;
|
||||
try {
|
||||
@@ -1470,8 +1486,23 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
});
|
||||
return;
|
||||
}
|
||||
let sourceScope: ReturnType<typeof normalizeAdminClientSourceScope>;
|
||||
try {
|
||||
const sources = await engine.listAllSources({ includeArchived: false });
|
||||
sourceScope = normalizeAdminClientSourceScope(
|
||||
rawSourceId,
|
||||
rawFederatedRead,
|
||||
sources.map(s => s.id),
|
||||
);
|
||||
} catch (e) {
|
||||
res.status(400).json({
|
||||
error: 'invalid_source_scope',
|
||||
message: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const result = await oauthProvider.registerClientManual(
|
||||
name, grants, scopeString, uris, 'default', undefined, validatedAuthMethod,
|
||||
name, grants, scopeString, uris, sourceScope.sourceId, sourceScope.federatedRead, validatedAuthMethod,
|
||||
);
|
||||
// Set per-client TTL if specified
|
||||
if (tokenTtl && Number(tokenTtl) > 0) {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { isValidSourceId } from './source-id.ts';
|
||||
|
||||
export interface AdminClientSourceScope {
|
||||
sourceId: string;
|
||||
federatedRead: string[];
|
||||
}
|
||||
|
||||
function parseFederatedReadInput(raw: unknown, sourceId: string): string[] {
|
||||
if (raw === undefined || raw === null) return [sourceId];
|
||||
if (typeof raw === 'string') {
|
||||
const values = raw.split(',').map(s => s.trim()).filter(Boolean);
|
||||
return values.length > 0 ? values : [sourceId];
|
||||
}
|
||||
if (Array.isArray(raw)) {
|
||||
if (!raw.every(v => typeof v === 'string')) {
|
||||
throw new Error('federated_read must be an array of source ids');
|
||||
}
|
||||
const values = raw.map(v => v.trim()).filter(Boolean);
|
||||
return values.length > 0 ? values : [sourceId];
|
||||
}
|
||||
throw new Error('federated_read must be a string or array');
|
||||
}
|
||||
|
||||
export function normalizeAdminClientSourceScope(
|
||||
rawSourceId: unknown,
|
||||
rawFederatedRead: unknown,
|
||||
availableSourceIds: string[],
|
||||
): AdminClientSourceScope {
|
||||
const knownSources = new Set(availableSourceIds);
|
||||
const fallbackSourceId = knownSources.has('default') ? 'default' : (availableSourceIds[0] ?? 'default');
|
||||
const sourceId = rawSourceId === undefined || rawSourceId === null || rawSourceId === ''
|
||||
? fallbackSourceId
|
||||
: rawSourceId;
|
||||
if (!isValidSourceId(sourceId)) {
|
||||
throw new Error(`Invalid source_id: ${JSON.stringify(sourceId)}`);
|
||||
}
|
||||
if (knownSources.size > 0 && !knownSources.has(sourceId)) {
|
||||
throw new Error(`Unknown source_id: ${sourceId}`);
|
||||
}
|
||||
|
||||
const federatedRead = Array.from(new Set(parseFederatedReadInput(rawFederatedRead, sourceId)));
|
||||
for (const id of federatedRead) {
|
||||
if (!isValidSourceId(id)) {
|
||||
throw new Error(`Invalid federated_read source_id: ${JSON.stringify(id)}`);
|
||||
}
|
||||
if (knownSources.size > 0 && !knownSources.has(id)) {
|
||||
throw new Error(`Unknown federated_read source_id: ${id}`);
|
||||
}
|
||||
}
|
||||
return { sourceId, federatedRead };
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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`,
|
||||
);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,44 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { normalizeAdminClientSourceScope } from '../src/core/admin-source-scope.ts';
|
||||
|
||||
describe('admin register-client source scope normalization', () => {
|
||||
const sources = ['default', 'team-a', 'team-b'];
|
||||
|
||||
test('defaults write and read scope to default source', () => {
|
||||
expect(normalizeAdminClientSourceScope(undefined, undefined, sources)).toEqual({
|
||||
sourceId: 'default',
|
||||
federatedRead: ['default'],
|
||||
});
|
||||
});
|
||||
|
||||
test('accepts snake-case body fields with multiple read sources', () => {
|
||||
expect(normalizeAdminClientSourceScope('team-a', ['team-a', 'team-b'], sources)).toEqual({
|
||||
sourceId: 'team-a',
|
||||
federatedRead: ['team-a', 'team-b'],
|
||||
});
|
||||
});
|
||||
|
||||
test('accepts comma-separated federated_read for API callers', () => {
|
||||
expect(normalizeAdminClientSourceScope('team-a', 'team-b, default,team-b', sources)).toEqual({
|
||||
sourceId: 'team-a',
|
||||
federatedRead: ['team-b', 'default'],
|
||||
});
|
||||
});
|
||||
|
||||
test('falls back to selected write source when federated_read is empty', () => {
|
||||
expect(normalizeAdminClientSourceScope('team-b', [], sources)).toEqual({
|
||||
sourceId: 'team-b',
|
||||
federatedRead: ['team-b'],
|
||||
});
|
||||
});
|
||||
|
||||
test('rejects malformed source ids before registration', () => {
|
||||
expect(() => normalizeAdminClientSourceScope('../secret', undefined, sources)).toThrow(/Invalid source_id/);
|
||||
expect(() => normalizeAdminClientSourceScope('team-a', ['snake_case'], sources)).toThrow(/Invalid federated_read/);
|
||||
});
|
||||
|
||||
test('rejects valid-looking but unregistered source ids', () => {
|
||||
expect(() => normalizeAdminClientSourceScope('ghost', undefined, sources)).toThrow(/Unknown source_id/);
|
||||
expect(() => normalizeAdminClientSourceScope('team-a', ['ghost'], sources)).toThrow(/Unknown federated_read/);
|
||||
});
|
||||
});
|
||||
@@ -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 () => [
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -78,6 +78,8 @@ describe('v0.36.1.x #1077 — admin register-client supports PKCE public clients
|
||||
// (under either name) from req.body. Pin the fallback pattern so the
|
||||
// PKCE-fix regression contract stays load-bearing.
|
||||
expect(src).toMatch(/req\.body[^;]*scopes\s*\?\?\s*[^;]*scope\b/);
|
||||
expect(src).toMatch(/req\.body[^;]*source_id\s*\?\?\s*[^;]*sourceId\b/);
|
||||
expect(src).toMatch(/req\.body[^;]*federated_read\s*\?\?\s*[^;]*federatedRead\b/);
|
||||
// v0.41.3 (T4 atomicity fix, codex F4): admin endpoint now validates
|
||||
// tokenEndpointAuthMethod via the shared validator and passes it to
|
||||
// registerClientManual as a positional arg. Pre-v0.41.3 the route did
|
||||
@@ -87,6 +89,7 @@ describe('v0.36.1.x #1077 — admin register-client supports PKCE public clients
|
||||
// UPDATE block (the regex deliberately asserts the post-insert UPDATE
|
||||
// is GONE).
|
||||
expect(src).toMatch(/validateTokenEndpointAuthMethod\(tokenEndpointAuthMethod\)/);
|
||||
expect(src).toMatch(/normalizeAdminClientSourceScope\(/);
|
||||
expect(src).toMatch(/registerClientManual\([^)]*validatedAuthMethod[^)]*\)/);
|
||||
// Regression guard: post-insert UPDATE flipping client_secret_hash to
|
||||
// NULL based on a runtime check is exactly the non-atomic pattern T4
|
||||
@@ -267,3 +270,26 @@ describe('v0.42.43.0 #2095 — volunteer-events sink + cycle purge wiring (struc
|
||||
expect(src).toMatch(/purged_volunteer_events_count/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#1490 + #1036 — admin Register Agent form exposes source scope + redirect URIs', () => {
|
||||
test('Agents.tsx RegisterModal sends source_id + federated_read in the POST body (#1490)', () => {
|
||||
const src = readFileSync('admin/src/pages/Agents.tsx', 'utf8');
|
||||
expect(src).toMatch(/source_id:\s*sourceId/);
|
||||
expect(src).toMatch(/federated_read:\s*federatedRead/);
|
||||
// The source list comes from the requireAdmin-gated endpoint, not a hardcoded 'default'.
|
||||
expect(src).toMatch(/api\.sources\(\)/);
|
||||
});
|
||||
|
||||
test('serve-http.ts serves /admin/api/sources behind requireAdmin (#1490)', () => {
|
||||
const src = readFileSync('src/commands/serve-http.ts', 'utf8');
|
||||
expect(src).toMatch(/app\.get\('\/admin\/api\/sources',\s*requireAdmin/);
|
||||
});
|
||||
|
||||
test('Agents.tsx RegisterModal sends redirectUris + authorization_code grants when URIs are entered (#1036)', () => {
|
||||
const src = readFileSync('admin/src/pages/Agents.tsx', 'utf8');
|
||||
// One-per-line textarea split into an array...
|
||||
expect(src).toMatch(/redirectUris\.split\('\\n'\)/);
|
||||
// ...included in the body with the CLI's grant-type inference convention.
|
||||
expect(src).toMatch(/redirectUris:\s*uris,\s*grantTypes:\s*\['authorization_code',\s*'refresh_token'\]/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -125,6 +125,30 @@ describe('client registration', () => {
|
||||
expect(client!.client_name).toBe('test-agent');
|
||||
});
|
||||
|
||||
test('registerClientManual persists source_id and federated_read into AuthInfo', async () => {
|
||||
await sql`
|
||||
INSERT INTO sources (id, name) VALUES (${'team-a'}, ${'Team A'}), (${'team-b'}, ${'Team B'})
|
||||
ON CONFLICT DO NOTHING
|
||||
`;
|
||||
const { clientId, clientSecret } = await provider.registerClientManual(
|
||||
'source-scoped-test',
|
||||
['client_credentials'],
|
||||
'read write',
|
||||
[],
|
||||
'team-a',
|
||||
['team-a', 'team-b'],
|
||||
);
|
||||
|
||||
const tokens = await provider.exchangeClientCredentials(clientId, clientSecret!, 'read');
|
||||
const authInfo = await provider.verifyAccessToken(tokens.access_token) as {
|
||||
sourceId?: string;
|
||||
allowedSources?: string[];
|
||||
};
|
||||
|
||||
expect(authInfo.sourceId).toBe('team-a');
|
||||
expect(authInfo.allowedSources).toEqual(['team-a', 'team-b']);
|
||||
});
|
||||
|
||||
test('getClient returns undefined for unknown client', async () => {
|
||||
const client = await provider.clientsStore.getClient('nonexistent');
|
||||
expect(client).toBeUndefined();
|
||||
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user