mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-16 18:02:30 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62bd7fb3b7 | ||
|
|
733fcd633a | ||
|
|
97e716b01f | ||
|
|
ff737e4345 |
+3
-22
@@ -433,10 +433,7 @@ export async function extractLinksFromFile(
|
||||
async resolve(name: string, dirHint?: string | string[]): Promise<string | null> {
|
||||
if (!name) return null;
|
||||
const trimmed = name.trim();
|
||||
// Same broadened slug-shape as makeResolver step 1: accepts
|
||||
// digit-leading folders (`90-people/nicolai`) and nested paths.
|
||||
// Exact Set membership guards it — no false positives.
|
||||
if (/\//.test(trimmed) && /^[a-z0-9][a-z0-9/_-]*$/.test(trimmed) && allSlugs.has(trimmed)) {
|
||||
if (/^[a-z][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/.test(trimmed) && allSlugs.has(trimmed)) {
|
||||
return trimmed;
|
||||
}
|
||||
const hints = Array.isArray(dirHint) ? dirHint : (dirHint ? [dirHint] : []);
|
||||
@@ -585,17 +582,6 @@ export interface ExtractOpts {
|
||||
* before (single-'default'-source brains unaffected).
|
||||
*/
|
||||
sourceId?: string;
|
||||
/**
|
||||
* v0.42 — also extract frontmatter links on the incremental (slugs) path.
|
||||
* `extractForSlugs` extracts BODY links only by default; set this true to also
|
||||
* parse each changed page's frontmatter so `sources:`/`related:` edges stay fresh
|
||||
* when YAML is edited externally and synced in. Applied PER changed page, so the
|
||||
* incremental walk stays bounded (no switch to a full DB scan). Only honored on
|
||||
* the incremental path (`slugs` defined); the full-walk path already covers
|
||||
* frontmatter via its own dispatch. Gated upstream by the config key
|
||||
* `autopilot.incremental_extract_include_frontmatter` (default off).
|
||||
*/
|
||||
includeFrontmatter?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -634,7 +620,7 @@ export async function runExtractCore(engine: BrainEngine, opts: ExtractOpts): Pr
|
||||
// Nothing changed — skip entirely.
|
||||
return result;
|
||||
}
|
||||
const r = await extractForSlugs(engine, opts.dir, opts.slugs, opts.mode, dryRun, jsonMode, workers, opts.signal, opts.sourceId, opts.includeFrontmatter);
|
||||
const r = await extractForSlugs(engine, opts.dir, opts.slugs, opts.mode, dryRun, jsonMode, workers, opts.signal, opts.sourceId);
|
||||
result.links_created = r.links_created;
|
||||
result.timeline_entries_created = r.timeline_created;
|
||||
result.pages_processed = r.pages;
|
||||
@@ -1025,11 +1011,6 @@ async function extractForSlugs(
|
||||
signal?: AbortSignal,
|
||||
// #1747/#1503: stamp resolved brain source id on batch rows (see ExtractOpts.sourceId).
|
||||
sourceId?: string,
|
||||
// v0.42: when true, also extract frontmatter links per changed page so
|
||||
// externally-edited YAML (`sources:`/`related:`) stays fresh on the cycle.
|
||||
// Default false preserves the body-only incremental behavior. Gated upstream
|
||||
// by `autopilot.incremental_extract_include_frontmatter`.
|
||||
includeFrontmatter: boolean = false,
|
||||
): Promise<{ links_created: number; timeline_created: number; pages: number }> {
|
||||
// Build the full slug set for link resolution (fast: just readdir, no file reads)
|
||||
const allFiles = walkMarkdownFiles(brainDir);
|
||||
@@ -1104,7 +1085,7 @@ async function extractForSlugs(
|
||||
const content = readFileSync(fullPath, 'utf-8');
|
||||
|
||||
if (doLinks) {
|
||||
const links = await extractLinksFromFile(content, relPath, allSlugs, { globalBasename, includeFrontmatter });
|
||||
const links = await extractLinksFromFile(content, relPath, allSlugs, { globalBasename });
|
||||
for (const link of links) {
|
||||
if (dryRun) {
|
||||
if (!jsonMode) console.log(` ${link.from_slug} → ${link.to_slug} (${link.link_type})`);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -121,18 +121,6 @@ export interface GBrainConfig {
|
||||
/** Daily spend cap (USD); bounds drains/day = floor(cap / ~$0.30). Default 2.0. */
|
||||
max_usd_per_day?: number;
|
||||
};
|
||||
/**
|
||||
* v0.42 — keep frontmatter links fresh on the incremental cycle. The cycle's
|
||||
* extract phase re-extracts only the slugs a sync changed, but `extractForSlugs`
|
||||
* extracts BODY links only — frontmatter (`sources:`/`related:` etc.) link edges
|
||||
* silently drift stale when a page's YAML is edited externally and synced in.
|
||||
* Set true to also extract frontmatter links per changed page each cycle, keeping
|
||||
* externally-edited YAML edges fresh without a full rescan. Default false
|
||||
* (preserves current behavior). Read via the file/env/DB plane in the cycle's
|
||||
* extract dispatch. Disable/enable with
|
||||
* `gbrain config set autopilot.incremental_extract_include_frontmatter <bool>`.
|
||||
*/
|
||||
incremental_extract_include_frontmatter?: boolean;
|
||||
};
|
||||
eval?: {
|
||||
/** false disables capture entirely. Defaults to true. */
|
||||
|
||||
@@ -996,21 +996,6 @@ async function runPhaseExtract(
|
||||
): Promise<PhaseResult> {
|
||||
try {
|
||||
const { runExtractCore } = await import('../commands/extract.ts');
|
||||
const { loadConfig } = await import('./config.ts');
|
||||
// Default off: the incremental cycle extracts body links only unless the
|
||||
// operator opts in to keeping externally-edited frontmatter links fresh too.
|
||||
// Both planes, file wins (env > file > DB precedence, per loadConfigWithEngine):
|
||||
// `gbrain config set autopilot.incremental_extract_include_frontmatter true`
|
||||
// writes the DB plane (engine.setConfig), so a file-plane-only read here
|
||||
// would make the documented enable command a silent no-op (#2120 class).
|
||||
const fileVal = loadConfig()?.autopilot?.incremental_extract_include_frontmatter;
|
||||
let includeFrontmatter = fileVal === true;
|
||||
if (fileVal === undefined) {
|
||||
try {
|
||||
includeFrontmatter =
|
||||
(await engine.getConfig('autopilot.incremental_extract_include_frontmatter')) === 'true';
|
||||
} catch { /* config table unreadable → default off */ }
|
||||
}
|
||||
// Extract is read-mostly against the filesystem + write to links table.
|
||||
// Honor dryRun by skipping with a 'skipped' entry: extract doesn't have
|
||||
// a clean dry-run mode today and runCycle should be honest about it.
|
||||
@@ -1031,7 +1016,6 @@ async function runPhaseExtract(
|
||||
slugs: changedSlugs, // undefined = full walk (first run / manual)
|
||||
signal,
|
||||
sourceId,
|
||||
includeFrontmatter, // honored on the incremental (slugs) path only
|
||||
});
|
||||
const linksCreated = result?.links_created ?? 0;
|
||||
const timelineCreated = result?.timeline_entries_created ?? 0;
|
||||
|
||||
@@ -942,17 +942,8 @@ export function makeResolver(
|
||||
|
||||
const hints = Array.isArray(dirHint) ? dirHint : (dirHint ? [dirHint] : []);
|
||||
|
||||
// Step 1: already a slug? Try an exact page lookup for any slug-shaped
|
||||
// value (contains '/', slug charset). Broadened beyond the original
|
||||
// single-segment lowercase-leading form (`^[a-z][a-z0-9-]*\/[a-z0-9]...`)
|
||||
// to also accept digit-leading folders (`90-people/nicolai`,
|
||||
// `01-trading/...`) and nested paths (`a/b/c`) — common in PARA-numbered
|
||||
// vaults. This is an EXACT getPage match only — no fuzzy — so it never
|
||||
// produces a false positive; a non-existent slug just falls through to
|
||||
// the steps below. Fixes frontmatter `related: [[dir/slug]]` values
|
||||
// (unwrapped by unwrapWikilink) that name a real page the strict regex
|
||||
// could not reach and whose full-path fuzzy score is below threshold.
|
||||
if (/\//.test(trimmed) && /^[a-z0-9][a-z0-9/_-]*$/.test(trimmed)) {
|
||||
// Step 1: already a slug? (dir/name shape, lowercase, hyphenated)
|
||||
if (/^[a-z][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/.test(trimmed)) {
|
||||
const page = await engine.getPage(trimmed);
|
||||
if (page) {
|
||||
cache.set(cacheKey, trimmed);
|
||||
@@ -1012,25 +1003,6 @@ export function makeResolver(
|
||||
|
||||
// ─── Frontmatter extractor ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Unwrap an Obsidian `[[wikilink]]` frontmatter value to its bare link
|
||||
* target so the resolver (which expects bare titles / dir slugs) can match
|
||||
* it. Mainstream Obsidian authors frontmatter links as `related: ["[[Page]]"]`;
|
||||
* without this, the resolver treats the brackets as part of the value and a
|
||||
* `[[90-people/nicolai]]` is normalized into `90peoplenicolai`, so it never
|
||||
* resolves. Strips a trailing `|alias`, `#heading`, or `^block` suffix — the
|
||||
* link target only. The regex is anchored to a wholly-wrapped value
|
||||
* (`^\s*\[\[…\]\]\s*$`), so bare titles and any value not fully wrapped pass
|
||||
* through unchanged and existing behavior is preserved exactly.
|
||||
*/
|
||||
export function unwrapWikilink(value: string): string {
|
||||
const match = /^\s*\[\[(.+?)\]\]\s*$/.exec(value);
|
||||
if (!match) return value;
|
||||
// Take the link target: drop |alias, then #heading / ^block suffixes.
|
||||
const target = match[1].split('|')[0].split('#')[0].split('^')[0];
|
||||
return target.trim();
|
||||
}
|
||||
|
||||
export interface UnresolvedFrontmatterRef {
|
||||
/** The frontmatter field name. */
|
||||
field: string;
|
||||
@@ -1088,12 +1060,7 @@ export async function extractFrontmatterLinks(
|
||||
}
|
||||
if (!name) continue; // skip numbers, nulls, malformed objects
|
||||
|
||||
// Accept Obsidian `[[wikilink]]` values in frontmatter link fields by
|
||||
// unwrapping to the bare target before resolution. Bare titles pass
|
||||
// through unchanged; the original `name` is preserved for the
|
||||
// unresolved report and edge context.
|
||||
const linkTarget = unwrapWikilink(name);
|
||||
const resolved = await resolver.resolve(linkTarget, mapping.dirHint);
|
||||
const resolved = await resolver.resolve(name, mapping.dirHint);
|
||||
if (!resolved) {
|
||||
unresolved.push({ field, name });
|
||||
continue;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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();
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -191,37 +191,3 @@ describe('runExtractCore — incremental cycle path (#417)', () => {
|
||||
expect(result.links_created).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
describe('runExtractCore — incremental frontmatter gate (includeFrontmatter)', () => {
|
||||
// alice has a `source:` frontmatter edge but NO body links. The incremental
|
||||
// path extracts body links only by default, so the frontmatter edge is the
|
||||
// sole signal that distinguishes the gate off vs on.
|
||||
const aliceFm = '---\nsource: companies/acme-example\n---\n# alice';
|
||||
|
||||
test('9. default (flag omitted) does NOT extract frontmatter links on the incremental path', async () => {
|
||||
await seedPage('companies/acme-example', '# acme');
|
||||
await seedPage('people/alice-example', aliceFm);
|
||||
const result = await runExtractCore(engine as unknown as BrainEngine, {
|
||||
mode: 'all',
|
||||
dir: tempDir,
|
||||
slugs: ['people/alice-example'],
|
||||
});
|
||||
// alice's only potential edge is her frontmatter `source:`; with the gate off
|
||||
// it must not be extracted (preserves the body-only incremental behavior).
|
||||
expect(result.pages_processed).toBe(1);
|
||||
expect(result.links_created).toBe(0);
|
||||
});
|
||||
|
||||
test('10. includeFrontmatter: true extracts the frontmatter link on the incremental path', async () => {
|
||||
await seedPage('companies/acme-example', '# acme');
|
||||
await seedPage('people/alice-example', aliceFm);
|
||||
const result = await runExtractCore(engine as unknown as BrainEngine, {
|
||||
mode: 'all',
|
||||
dir: tempDir,
|
||||
slugs: ['people/alice-example'],
|
||||
includeFrontmatter: true,
|
||||
});
|
||||
// Same page, gate on → the `source:` frontmatter edge is now extracted.
|
||||
expect(result.pages_processed).toBe(1);
|
||||
expect(result.links_created).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -76,18 +76,6 @@ describe('extractLinksFromFile', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('resolves wrapped [[wikilink]] digit-leading slug-path in frontmatter (fs resolver, broadened step 1)', async () => {
|
||||
// Same bug class as makeResolver step 1 (#1983): the fs resolver's strict
|
||||
// `^[a-z]…` slug regex rejected digit-leading / nested paths, so a PARA-vault
|
||||
// `related: "[[90-people/nicolai]]"` never resolved even though the page exists.
|
||||
const content = '---\nrelated: "[[90-people/nicolai]]"\ntype: concept\n---\nContent.';
|
||||
const allSlugs = new Set(['wiki/note', '90-people/nicolai']);
|
||||
const links = await extractLinksFromFile(content, 'wiki/note.md', allSlugs, { includeFrontmatter: true });
|
||||
const related = links.filter(l => l.link_type === 'related_to');
|
||||
expect(related).toHaveLength(1);
|
||||
expect(related[0].to_slug).toBe('90-people/nicolai');
|
||||
});
|
||||
|
||||
it('frontmatter extraction is default OFF (back-compat)', async () => {
|
||||
// Without includeFrontmatter, fs-source no longer auto-extracts frontmatter.
|
||||
// Matches db-source behavior. User opts in with --include-frontmatter flag.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
parseTimelineEntries,
|
||||
isAutoLinkEnabled,
|
||||
FRONTMATTER_LINK_MAP,
|
||||
unwrapWikilink,
|
||||
type SlugResolver,
|
||||
} from '../src/core/link-extraction.ts';
|
||||
import type { BrainEngine } from '../src/core/engine.ts';
|
||||
@@ -1292,175 +1291,3 @@ describe('parseTimelineEntries — Format 3: inline [Source: ..., YYYY-MM-DD] ci
|
||||
expect(parseTimelineEntries('[Source: import batch, 2025-07-01]')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
// ─── Frontmatter [[wikilink]] + slug-path resolution ──────────────────────
|
||||
// Mainstream Obsidian authors frontmatter links as `related: ["[[Page]]"]`,
|
||||
// and PARA-numbered vaults use digit-leading / nested slug paths like
|
||||
// `[[90-people/nicolai]]`. Both were silently dropped: brackets were treated
|
||||
// as part of the value and the step-1 slug regex (`^[a-z]…`) rejected
|
||||
// digit-leading / nested paths, while full-path fuzzy scored below threshold.
|
||||
// Fix: unwrapWikilink() before resolution + an exact getPage() for any
|
||||
// slug-shaped value (exact-match only → no false positives).
|
||||
|
||||
describe('unwrapWikilink', () => {
|
||||
test('wrapped title → bare title', () => {
|
||||
expect(unwrapWikilink('[[Monday Range]]')).toBe('Monday Range');
|
||||
});
|
||||
test('wrapped slug-path (digit-leading folder) → bare slug', () => {
|
||||
expect(unwrapWikilink('[[90-people/nicolai]]')).toBe('90-people/nicolai');
|
||||
});
|
||||
test('wrapped nested slug-path → bare slug', () => {
|
||||
expect(unwrapWikilink('[[01-trading/wiki/strategies/opening-range-breakout]]'))
|
||||
.toBe('01-trading/wiki/strategies/opening-range-breakout');
|
||||
});
|
||||
test('strips |alias', () => {
|
||||
expect(unwrapWikilink('[[90-people/nicolai|Nicolai]]')).toBe('90-people/nicolai');
|
||||
});
|
||||
test('strips #heading', () => {
|
||||
expect(unwrapWikilink('[[Page#Section]]')).toBe('Page');
|
||||
});
|
||||
test('strips ^block', () => {
|
||||
expect(unwrapWikilink('[[Page^abc123]]')).toBe('Page');
|
||||
});
|
||||
test('surrounding whitespace tolerated', () => {
|
||||
expect(unwrapWikilink(' [[Page]] ')).toBe('Page');
|
||||
});
|
||||
test('bare title passes through unchanged', () => {
|
||||
expect(unwrapWikilink('Monday Range')).toBe('Monday Range');
|
||||
});
|
||||
test('bare slug passes through unchanged', () => {
|
||||
expect(unwrapWikilink('90-people/nicolai')).toBe('90-people/nicolai');
|
||||
});
|
||||
test('partially-wrapped value is NOT unwrapped (anchored)', () => {
|
||||
// Not a wholly-wrapped value → left intact so existing behavior is exact.
|
||||
expect(unwrapWikilink('see [[Page]] for detail')).toBe('see [[Page]] for detail');
|
||||
});
|
||||
});
|
||||
|
||||
describe('makeResolver — slug-path exact getPage (step 1 broadened)', () => {
|
||||
function fakeEngine(
|
||||
slugs: string[],
|
||||
fuzzyMap: Map<string, { slug: string; similarity: number }> = new Map(),
|
||||
): BrainEngine {
|
||||
const lookup = new Set(slugs);
|
||||
return {
|
||||
async getPage(slug: string) { return lookup.has(slug) ? { slug } as any : null; },
|
||||
async findByTitleFuzzy(name: string) { return fuzzyMap.get(name) ?? null; },
|
||||
async searchKeyword() { return []; },
|
||||
} as unknown as BrainEngine;
|
||||
}
|
||||
|
||||
test('digit-leading folder slug resolves via exact getPage', async () => {
|
||||
const r = makeResolver(fakeEngine(['90-people/nicolai']));
|
||||
expect(await r.resolve('90-people/nicolai')).toBe('90-people/nicolai');
|
||||
});
|
||||
|
||||
test('nested (>2 segment) slug resolves via exact getPage', async () => {
|
||||
const r = makeResolver(fakeEngine(['01-trading/wiki/strategies/opening-range-breakout']));
|
||||
expect(await r.resolve('01-trading/wiki/strategies/opening-range-breakout'))
|
||||
.toBe('01-trading/wiki/strategies/opening-range-breakout');
|
||||
});
|
||||
|
||||
test('regression: single-segment lowercase slug still resolves', async () => {
|
||||
const r = makeResolver(fakeEngine(['people/pedro']));
|
||||
expect(await r.resolve('people/pedro')).toBe('people/pedro');
|
||||
});
|
||||
|
||||
test('exact-only: slug-shaped value with no matching page falls through (no false positive)', async () => {
|
||||
// `90-people/ghost` is slug-shaped but absent → step-1 getPage misses,
|
||||
// no fuzzy hit → null. Never invents an edge.
|
||||
const r = makeResolver(fakeEngine(['90-people/nicolai']));
|
||||
expect(await r.resolve('90-people/ghost')).toBeNull();
|
||||
});
|
||||
|
||||
test('non-slug value still routes to fuzzy', async () => {
|
||||
const r = makeResolver(fakeEngine(
|
||||
['01-trading/monday-range'],
|
||||
new Map([['Monday Range', { slug: '01-trading/monday-range', similarity: 1 }]]),
|
||||
));
|
||||
expect(await r.resolve('Monday Range')).toBe('01-trading/monday-range');
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractFrontmatterLinks — [[wikilink]] related: values (end-to-end)', () => {
|
||||
function fakeEngine(
|
||||
slugs: string[],
|
||||
fuzzyMap: Map<string, { slug: string; similarity: number }> = new Map(),
|
||||
): BrainEngine {
|
||||
const lookup = new Set(slugs);
|
||||
return {
|
||||
async getPage(slug: string) { return lookup.has(slug) ? { slug } as any : null; },
|
||||
async findByTitleFuzzy(name: string) { return fuzzyMap.get(name) ?? null; },
|
||||
async searchKeyword() { return []; },
|
||||
} as unknown as BrainEngine;
|
||||
}
|
||||
|
||||
test('wrapped slug-path related: resolves (the core win)', async () => {
|
||||
const resolver = makeResolver(fakeEngine(['90-people/nicolai']));
|
||||
const { candidates, unresolved } = await extractFrontmatterLinks(
|
||||
'wiki/originals/ideas/note', 'note' as never,
|
||||
{ related: '[[90-people/nicolai]]' }, resolver,
|
||||
);
|
||||
expect(unresolved).toHaveLength(0);
|
||||
expect(candidates).toHaveLength(1);
|
||||
expect(candidates[0]).toMatchObject({
|
||||
fromSlug: 'wiki/originals/ideas/note',
|
||||
targetSlug: '90-people/nicolai',
|
||||
linkType: 'related_to',
|
||||
linkSource: 'frontmatter',
|
||||
});
|
||||
});
|
||||
|
||||
test('wrapped nested slug-path related: resolves', async () => {
|
||||
const resolver = makeResolver(fakeEngine(['01-trading/wiki/strategies/opening-range-breakout']));
|
||||
const { candidates } = await extractFrontmatterLinks(
|
||||
'wiki/note', 'note' as never,
|
||||
{ related: ['[[01-trading/wiki/strategies/opening-range-breakout]]'] }, resolver,
|
||||
);
|
||||
expect(candidates).toHaveLength(1);
|
||||
expect(candidates[0].targetSlug).toBe('01-trading/wiki/strategies/opening-range-breakout');
|
||||
});
|
||||
|
||||
test('wrapped value with |alias resolves to the target', async () => {
|
||||
const resolver = makeResolver(fakeEngine(['90-people/nicolai']));
|
||||
const { candidates } = await extractFrontmatterLinks(
|
||||
'wiki/note', 'note' as never,
|
||||
{ related: '[[90-people/nicolai|Nicolai]]' }, resolver,
|
||||
);
|
||||
expect(candidates).toHaveLength(1);
|
||||
expect(candidates[0].targetSlug).toBe('90-people/nicolai');
|
||||
});
|
||||
|
||||
test('regression: bare slug related: still resolves', async () => {
|
||||
const resolver = makeResolver(fakeEngine(['90-people/nicolai']));
|
||||
const { candidates } = await extractFrontmatterLinks(
|
||||
'wiki/note', 'note' as never,
|
||||
{ related: '90-people/nicolai' }, resolver,
|
||||
);
|
||||
expect(candidates).toHaveLength(1);
|
||||
expect(candidates[0].targetSlug).toBe('90-people/nicolai');
|
||||
});
|
||||
|
||||
test('regression: wrapped title resolves via fuzzy (brackets harmless)', async () => {
|
||||
const resolver = makeResolver(fakeEngine(
|
||||
['01-trading/monday-range'],
|
||||
new Map([['Monday Range', { slug: '01-trading/monday-range', similarity: 1 }]]),
|
||||
));
|
||||
const { candidates } = await extractFrontmatterLinks(
|
||||
'wiki/note', 'note' as never,
|
||||
{ related: '[[Monday Range]]' }, resolver,
|
||||
);
|
||||
expect(candidates).toHaveLength(1);
|
||||
expect(candidates[0].targetSlug).toBe('01-trading/monday-range');
|
||||
});
|
||||
|
||||
test('unknown wrapped slug → unresolved (no crash), original value preserved', async () => {
|
||||
const resolver = makeResolver(fakeEngine(['90-people/nicolai']));
|
||||
const { candidates, unresolved } = await extractFrontmatterLinks(
|
||||
'wiki/note', 'note' as never,
|
||||
{ related: '[[99-archive/does-not-exist]]' }, resolver,
|
||||
);
|
||||
expect(candidates).toHaveLength(0);
|
||||
expect(unresolved).toHaveLength(1);
|
||||
expect(unresolved[0]).toEqual({ field: 'related', name: '[[99-archive/does-not-exist]]' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
|
||||
+38
-1
@@ -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);
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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)', () => {
|
||||
|
||||
Reference in New Issue
Block a user