Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(graph): schema-pack relations keep declared direction; canonical attendance under shipped packs; meeting seeds for 'who attended' (N9-2, N9-3, N9-4, N12-7)

garrytan81755f5b6cdd
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index 35861a5ee7..9fe84de827 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -51,7 +51,7 @@ export { reconcileSourceLinks, type SourceLinkReconciliationResult } from '../co
export { extractMarkdownLinks } from '../core/link-extraction.ts';
import {
extractPageLinks, parseTimelineEntries, deriveTimelineAnchor, inferLinkType, makeResolver,
- attendanceEvidenceRanges, hasAttendanceEvidence, resolvedLinkCandidate, orientCanonicalAttendance, extractMarkdownLinks,
+ attendanceEvidenceRanges, hasAttendanceEvidence, resolvedLinkCandidate, orientCanonicalAttendance, extractMarkdownLinks, ownsAttendanceInference,
extractFrontmatterLinks, isGlobalBasenameEnabled, isCrossSourceLinksEnabled, LINK_EXTRACTOR_VERSION_TS,
WIKILINK_BASENAME_LINK_TYPE,
buildBasenameIndex, queryBasenameIndex, stripCodeBlocks, normalizeBasename,
@@ -505,6 +505,7 @@ export async function extractLinksFromFile(
const globalBasename = opts?.globalBasename ?? false;
const pack = opts?.pack ?? null;
const packBudget = pack ? new PageRegexBudget() : undefined;
+ const packOwnsAttendance = ownsAttendanceInference(pack);
const activePack = pack?.page_types ? { page_types: pack.page_types } : undefined;
const parsed = parseMarkdown(content, relPath, { activePack });
const fm = parsed.frontmatter;
@@ -539,6 +540,7 @@ export async function extractLinksFromFile(
const position = index ?? scanContent.indexOf(name);
const evidence = scanContent.slice(Math.max(0, position - 120), position + 240);
let inferred = pack ? inferLinkTypeFromPack(pack, guessedPageType, evidence, packBudget, targetType) : null;
+ if (inferred === 'attended' && guessedPageType === 'meeting' && !packOwnsAttendance) inferred = null;
const bareTarget = relTarget.endsWith('.md') ? relTarget.slice(0, -3) : relTarget;
const ambiguousAttendance = !inferred && guessedPageType === 'meeting' && targetType === 'person'
&& !bareTarget.includes('/') && new Set([slugifyPath(bareTarget), normalizeBasename(bareTarget)]
@@ -546,13 +548,13 @@ export async function extractLinksFromFile(
&& (opts?.pageTypes?.get(candidate) ?? parseMarkdown('', `${candidate}.md`, { activePack }).type) === 'person')).size > 1;
const canonicalAttendance = !inferred && guessedPageType === 'meeting' && targetType === 'person'
&& resolvedSlugs.length === 1 && !ambiguousAttendance
- && !pack?.link_types.some(lt => lt.name === 'attended' && (lt.inference?.page_type || lt.inference?.target_type))
+ && !(packOwnsAttendance && pack?.link_types.some(lt => lt.name === 'attended' && (lt.inference?.page_type || lt.inference?.target_type)))
&& hasAttendanceEvidence(attendanceRanges, position);
if (!inferred) {
inferred = guessedPageType === 'meeting' ? (canonicalAttendance ? 'attended' : 'mentions')
: inferLinkType(guessedPageType, evidence, scanContent, target, targetType);
if (inferred === 'mentions' && !pack && !parsed.typeExplicit) inferred = inferTypeByDir(fileDir, dirname(target), fm);
- if (pack?.link_types.some(lt => lt.name === inferred && (lt.inference?.page_type || lt.inference?.target_type))) inferred = 'mentions';
+ if (!canonicalAttendance && pack?.link_types.some(lt => lt.name === inferred && (lt.inference?.page_type || lt.inference?.target_type))) inferred = 'mentions';
}
if (inferred === 'attended' && guessedPageType === 'meeting' && targetType !== 'person') inferred = 'mentions';
const link: ExtractedLink = {
diff --git a/src/core/attendance-repair.ts b/src/core/attendance-repair.ts
index d56eb8b798..90815dd86d 100644
--- a/src/core/attendance-repair.ts
+++ b/src/core/attendance-repair.ts
@@ -1,7 +1,7 @@
import { createHash, randomUUID } from 'node:crypto';
import type { BrainEngine, LinkBatchInput } from './engine.ts';
import { extractPageLinks, extractEntityRefs, attendanceEvidenceRanges, hasAttendanceEvidence,
- resolvedLinkCandidate, normalizeBasename, LINK_EXTRACTOR_VERSION_TS,
+ resolvedLinkCandidate, normalizeBasename, ownsAttendanceInference, LINK_EXTRACTOR_VERSION_TS,
type LinkExtractionPack, type SlugResolver } from './link-extraction.ts';
import { slugifyPath } from './sync.ts';
import { isValidSourceId } from './source-id.ts';
@@ -112,9 +112,7 @@ async function ontology(engine: BrainEngine, sourceId: string) {
invalidatePackCache(resolved.manifest.name);
resolved = await loadActivePackForEngine(engine, { remote: false, sourceId });
const pack = resolved.manifest;
- const overridden = pack.link_types.some(link => link.name === 'attended' && link.inference)
- || pack.frontmatter_links.some(mapping => mapping.page_type === 'meeting'
- && (mapping.link_type === 'attended' || mapping.fields.includes('attendees')));
+ const overridden = ownsAttendanceInference(pack);
return { hash: attendanceRepairHash([bindings, approvedSchemaIdentity(resolved)]), name: pack.name,
direction: overridden ? 'pack_semantics_preserved' as const : 'person_to_meeting' as const, pack };
} catch {
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index 9110ed344f..5e9549dc17 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -52,6 +52,12 @@ export { parseInlineCitationTimelineEntries, type InlineCitationTimelineCandidat
* OR updated_at > links_extracted_at`. It is an ISO-8601 string (NOT a number) —
* the column is TIMESTAMPTZ and the predicate binds it as `::timestamptz`.
*/
+// 2026-10-01: eval wave N9-2/N9-3/N12-7 — schema-pack frontmatter mappings
+// keep FRONTMATTER_LINK_MAP's declared direction (company `investors:` is
+// investor -> company, meeting `attendees:` is person -> meeting), and a
+// pack's `attended` verb on a meeting page follows canonical evidence-gated
+// attendance, so edges the legacy gbrain-base pack stored backwards (or typed
+// attended from a notes mention) re-derive on `extract --stale`.
// 2026-09-30: #5749 — with link_resolution.global_basename on, a unique
// basename match resolves a frontmatter wikilink before the fuzzy and live
// keyword steps, so edges the managed stale sweep re-pointed at a transcript
@@ -82,7 +88,7 @@ export { parseInlineCitationTimelineEntries, type InlineCitationTimelineCandidat
// PRE-wave code after this date reads as fresh and won't re-extract until
// the page is next edited; no fixed watermark can cover code that keeps
// running past it.
-export const LINK_EXTRACTOR_VERSION_TS = '2026-09-30T00:00:00Z';
+export const LINK_EXTRACTOR_VERSION_TS = '2026-10-01T00:00:00Z';
// ─── Entity references ──────────────────────────────────────────
@@ -613,6 +619,17 @@ export interface PageLinksResult {
attendanceComplete: boolean;
}
+/**
+ * True when a pack decides meeting attendance itself: one of its `attended`
+ * rules matches a phrase regex. A rule bound only to the meeting page type
+ * (and optionally a person target), as gbrain-base and company-brain ship,
+ * mirrors the in-code meeting prior, so meeting links follow canonical
+ * evidence-gated attendance (person -> meeting) instead.
+ */
+export function ownsAttendanceInference(pack: Pick<LinkExtractionPack, 'link_types'> | null | undefined): boolean {
+ return !!pack?.link_types.some(lt => lt.name === 'attended' && lt.inference?.regex);
+}
+
/**
* Extract all link candidates from a page.
*
@@ -651,6 +668,7 @@ export async function extractPageLinks(
// here and every such edge landed as 'mentions'.
const pack = opts.pack ?? null;
const packBudget = pack ? new PageRegexBudget() : undefined;
+ const packOwnsAttendance = ownsAttendanceInference(pack);
// Timeline / See-also links never receive the page-role prior — see
// rolePriorSuppressedRanges (matched on the code-stripped content, so a
// fenced `## Timeline` never opens a range). idx is the link's position in
@@ -665,7 +683,7 @@ export async function extractPageLinks(
const targetType = opts.targetType?.(targetSlug, sourceId);
if (pack) {
const packVerb = inferLinkTypeFromPack(pack, pageType as string, ctx, packBudget, targetType);
- if (packVerb) {
+ if (packVerb && (packOwnsAttendance || packVerb !== 'attended' || pageType !== 'meeting')) {
if (packVerb === 'attended' && pageType === 'meeting'
&& (opts.targetType ? targetType !== 'person' : !targetSlug.startsWith('people/'))) return { linkType: 'mentions' };
return { linkType: packVerb };
@@ -673,7 +691,7 @@ export async function extractPageLinks(
}
if (pageType === 'meeting') {
if (!bodyReference) return { linkType: 'mentions' };
- if (pack?.link_types.some(lt => lt.name === 'attended' && (lt.inference?.page_type || lt.inference?.target_type))) return { linkType: 'mentions' };
+ if (packOwnsAttendance && pack?.link_types.some(lt => lt.name === 'attended' && (lt.inference?.page_type || lt.inference?.target_type))) return { linkType: 'mentions' };
if (idx !== undefined && hasAttendanceEvidence(attendanceRanges, idx)) {
attendancePending.add(idx);
if (!opts.targetType || targetType !== undefined) attendanceResolved.add(idx);
@@ -1721,7 +1739,10 @@ export async function extractFrontmatterLinks(
const prefixes = pack.page_types?.find(pt => pt.name === expectedType)?.path_prefixes.map(p => p.replace(/^\/+|\/+$/g, ''));
const legacy = FRONTMATTER_LINK_MAP.find(mapping => mapping.fields.includes(field)
&& (!mapping.pageType || mapping.pageType === pageType));
- packMappings.push({ fields: [field], type, direction: 'outgoing', dirHint: prefixes?.length ? prefixes : legacy?.dirHint ?? '' });
+ const declared = FRONTMATTER_LINK_MAP.find(mapping => mapping.type === type
+ && (!mapping.pageType || mapping.pageType === pageType));
+ packMappings.push({ fields: [field], type, direction: declared?.direction ?? 'outgoing',
+ dirHint: prefixes?.length ? prefixes : legacy?.dirHint ?? '' });
}
}
}
@@ -1789,10 +1810,10 @@ export async function extractFrontmatterLinks(
continue;
}
onResolvedTarget?.(resolved);
- const expectedType = packMappings.includes(mapping)
- ? pack?.link_types.find(lt => lt.name === mapping.type)?.inference?.target_type
- : mapping.type === 'attended' && mapping.direction === 'incoming' ? 'person' : undefined;
- if (expectedType && (targetType || packMappings.includes(mapping)) && targetType?.(resolved) !== expectedType) {
+ const packTargetType = packMappings.includes(mapping)
+ ? pack?.link_types.find(lt => lt.name === mapping.type)?.inference?.target_type : undefined;
+ const expectedType = canonicalAttendance ? 'person' : packTargetType;
+ if (expectedType && (targetType || packTargetType) && targetType?.(resolved) !== expectedType) {
if (targetType?.(resolved) === undefined && mapping.type === 'attended') attendanceComplete = false;
unresolved.push({ field, name, reason: 'target_type_mismatch' });
continue;
diff --git a/src/core/search/relational-recall.ts b/src/core/search/relational-recall.ts
index 1a1ecee926..1ee8863de3 100644
--- a/src/core/search/relational-recall.ts
+++ b/src/core/search/relational-recall.ts
@@ -89,18 +89,35 @@ function scopeSources(opts: RelationalArmOpts): string[] {
return ['default'];
}
+/** Page types a relation's seed may be besides an entity. The entity resolver
+ * never returns a meeting, so "Who attended <meeting title>?" needs its own
+ * exact-title tier. */
+function titleSeedTypes(parsed: RelationalQuery): string[] {
+ return parsed.direction === 'in' && parsed.linkTypes?.includes('attended') ? ['meeting', 'event'] : [];
+}
+
/** Resolve a seed phrase to all in-scope (source_id, slug) pairs that
- * resolve to a REAL page (confidence gate D3 tier-1: drop fallback_slugify). */
+ * resolve to a REAL page (confidence gate D3 tier-1: drop fallback_slugify).
+ * When the entity resolver only slugifies, a live page of one of
+ * `titleTypes` whose title is exactly the phrase (case-insensitive, unique in
+ * the source) is the seed. */
async function resolveSeedScoped(
engine: BrainEngine,
sources: string[],
phrase: string,
policy: PageReadPolicy,
+ titleTypes: string[] = [],
): Promise<Array<{ source_id: string; slug: string }>> {
const out: Array<{ source_id: string; slug: string }> = [];
const seen = new Set<string>();
for (const sid of sources) {
- const r = await resolveEntitySlugWithSource(engine, sid, phrase);
+ let r = await resolveEntitySlugWithSource(engine, sid, phrase);
+ if (r?.source === 'fallback_slugify' && titleTypes.length) {
+ const titled = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND type = ANY($2::text[])
+ AND lower(title) = lower($3) LIMIT 2`, [sid, titleTypes, phrase.trim()]);
+ if (titled.length === 1) r = { slug: titled[0].slug, source: 'exact_page' };
+ }
if (!r || r.source === 'fallback_slugify') continue;
const key = `${sid}:${r.slug}`;
if (seen.has(key)) continue;
@@ -325,7 +342,7 @@ export async function buildRelationalArm(
}
// who_rel / who_at / intro: single logical seed (may resolve in N sources).
- const resolved = await resolveSeedScoped(engine, sources, parsed.seeds[0], opts);
+ const resolved = await resolveSeedScoped(engine, sources, parsed.seeds[0], opts, titleSeedTypes(parsed));
if (resolved.length === 0) return finish([]);
meta.seeds_resolved = resolved.length;
const slugs = Array.from(new Set(resolved.map(r => r.slug)));
diff --git a/test/attendance-repair.test.ts b/test/attendance-repair.test.ts
index 5afbfae110..89af090a9c 100644
--- a/test/attendance-repair.test.ts
+++ b/test/attendance-repair.test.ts
@@ -20,6 +20,8 @@ const meeting = 'meetings/planning';
const positive = 'Attendees: [Alice Example](../people/alice-example.md)';
const pack = { api_version: 'gbrain-schema-pack-v1', name: 'repair-fixture', version: '1.0.0', extends: null,
page_types: [], link_types: [], frontmatter_links: [] };
+const phraseOwnedPack = { ...pack, link_types: [{ name: 'attended', inference: { page_type: 'meeting', regex: '\\bpresent\\b' } }],
+ frontmatter_links: [{ page_type: 'meeting', fields: ['attendees'], link_type: 'attended' }] };
for (const kind of testBackends()) {
describe(`preview-bound attendance repair (${kind}; repair-fixture non-overridden person_to_meeting)`, () => {
@@ -166,7 +168,7 @@ for (const kind of testBackends()) {
test(`${proof} expired proof refuses ${state} replay and fresh approval recovers without renewing old proof`, async () => {
if (state === 'changed') await legacy();
else if (state === 'no-op') await apply(await preview());
- else { await engine.setConfig('schema_pack', 'company-brain'); await legacy(); }
+ else { writeFileSync(join(root, 'pack.json'), JSON.stringify(phraseOwnedPack)); await legacy(); }
const receipt = await preview();
await apply(receipt);
const before = await rows();
@@ -387,9 +389,8 @@ for (const kind of testBackends()) {
await apply(receipt); expect(await rows()).toEqual(before);
});
- test('pack-owned outgoing semantics are excluded and pinned', async () => {
- writeFileSync(join(root, 'pack.json'), JSON.stringify({ ...pack, link_types: [{ name: 'attended' }],
- frontmatter_links: [{ page_type: 'meeting', fields: ['attendees'], link_type: 'attended' }] }));
+ test('phrase-owned pack attendance semantics are excluded and pinned', async () => {
+ writeFileSync(join(root, 'pack.json'), JSON.stringify(phraseOwnedPack));
await legacy(); const before = await rows(); const receipt = await preview();
expect(receipt.counts.pack_semantics_preserved).toBe(1);
expect(receipt.direction).toBe('pack_semantics_preserved');
@@ -403,12 +404,14 @@ for (const kind of testBackends()) {
await apply(receipt); expect(await rows()).toEqual(before);
});
- for (const name of ['gbrain-base', 'company-brain']) test(`${name} shipped outgoing attendance is report-only`, async () => {
+ for (const name of ['gbrain-base', 'company-brain']) test(`${name} historical outgoing attendance repairs to person -> meeting`, async () => {
await engine.setConfig('schema_pack', name); await legacy();
- const before = await rows(); const receipt = await preview();
- expect(receipt.pack).toBe(name); expect(receipt.direction).toBe('pack_semantics_preserved');
- expect(receipt.counts).toMatchObject({ add: 0, remove: 0, pack_semantics_preserved: 1 });
- await apply(receipt); expect(await rows()).toEqual(before);
+ const receipt = await preview();
+ expect(receipt.pack).toBe(name); expect(receipt.direction).toBe('person_to_meeting');
+ expect(receipt.counts).toMatchObject({ add: 1, remove: 1, pack_semantics_preserved: 0 });
+ expect(await apply(receipt)).toMatchObject({ created: 1, removed: 1 });
+ expect((await engine.getBacklinks(meeting, { sourceId })).filter(row => row.link_type === 'attended').map(row => row.from_slug)).toEqual([person]);
+ expect((await engine.getLinks(meeting, { sourceId })).filter(row => row.link_type === 'attended')).toEqual([]);
});
for (const mutation of ['origin-edit', 'endpoint-edit', 'origin-delete', 'endpoint-delete', 'origin-recreate', 'endpoint-recreate',
@@ -543,7 +546,7 @@ for (const kind of testBackends()) {
for (const reason of ['pack_semantics_preserved', 'pack_unavailable', 'origin_size_limit', 'edge_limit', 'edge_size_limit', 'reference_limit']) {
test(`report-only ${reason} with existing edges replays a commit before private checkpoint progress`, async () => {
await legacy();
- if (reason === 'pack_semantics_preserved') await engine.setConfig('schema_pack', 'company-brain');
+ if (reason === 'pack_semantics_preserved') writeFileSync(join(root, 'pack.json'), JSON.stringify(phraseOwnedPack));
if (reason === 'pack_unavailable') await engine.setConfig('schema_pack', 'unavailable-fixture');
if (reason === 'origin_size_limit') await seed(meeting, 'meeting', 'x'.repeat(256 * 1024 + 1));
if (reason === 'edge_limit') await engine.executeRaw(`INSERT INTO links(from_page_id,to_page_id,link_type,link_source)
diff --git a/test/attendance-retrieval.test.ts b/test/attendance-retrieval.test.ts
index c8d07f095d..520bd823f3 100644
--- a/test/attendance-retrieval.test.ts
+++ b/test/attendance-retrieval.test.ts
@@ -44,7 +44,11 @@ for (const kind of testBackends()) {
await engine.setConfig('schema_pack', 'gbrain-base');
const base = (await loadActivePackForLocalEngine(engine))!.manifest;
writeFileSync(join(packRoot, 'pack.json'), JSON.stringify({ ...base, name: 'attendance-fixture', link_types: [], frontmatter_links: [] }));
- __setPackLocatorForTests(name => name === 'attendance-fixture' ? join(packRoot, 'pack.json') : bundledPackPath(name));
+ // A pack that decides attendance itself (a phrase regex) keeps its own outgoing semantics.
+ writeFileSync(join(packRoot, 'phrase-owned.json'), JSON.stringify({ ...base, name: 'phrase-owned-fixture', frontmatter_links: [],
+ link_types: [{ name: 'attended', inference: { page_type: 'meeting', target_type: 'person', regex: '\\bAttendees\\b' } }] }));
+ __setPackLocatorForTests(name => name === 'attendance-fixture' ? join(packRoot, 'pack.json')
+ : name === 'phrase-owned-fixture' ? join(packRoot, 'phrase-owned.json') : bundledPackPath(name));
await engine.setConfig('schema_pack', 'attendance-fixture');
await engine.setConfig('dream.synthesize.session_corpus_dir', root);
}, 120_000);
@@ -119,8 +123,8 @@ for (const kind of testBackends()) {
}
for (const lane of ['fs-sync', 'fs-incremental', 'fs-batch', 'prepare', 'sweep', 'db', 'stale']) {
for (const [globalPack, sourcePack, incoming] of [
- ['attendance-fixture', 'gbrain-base', false],
- ['gbrain-base', 'attendance-fixture', true],
+ ['attendance-fixture', 'phrase-owned-fixture', false],
+ ['phrase-owned-fixture', 'attendance-fixture', true],
['missing-example-pack', 'attendance-fixture', true],
] as const) test(`${lane}: source-selected ${sourcePack} overrides global ${globalPack}`, async () => {
await engine.setConfig('schema_pack', globalPack);
@@ -159,7 +163,7 @@ for (const kind of testBackends()) {
expect(await attendees()).toEqual([person]);
});
test(`${lane}: unavailable ontology cannot reverse existing pack-owned attendance`, async () => {
- await engine.setConfig('schema_pack', 'gbrain-base');
+ await engine.setConfig('schema_pack', 'phrase-owned-fixture');
await seed(meeting, 'meeting', positive);
await extract('db');
const rows = () => engine.executeRaw('SELECT l.* FROM links l JOIN pages p ON p.id=l.from_page_id WHERE p.source_id=$1 ORDER BY l.id', [sourceId]);
@@ -180,7 +184,7 @@ for (const kind of testBackends()) {
} else await extract(lane, true);
expect(await rows()).toEqual(before);
expect((await engine.executeRaw<{ value: string | null }>('SELECT links_extracted_at AS value FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, meeting]))[0].value).toBeNull();
- await engine.setConfig('schema_pack', 'gbrain-base');
+ await engine.setConfig('schema_pack', 'phrase-owned-fixture');
await extract(lane, true);
expect((await engine.getLinks(meeting, { sourceId })).filter(row => row.link_type === 'attended')).toHaveLength(1);
expect((await engine.getBacklinks(meeting, { sourceId })).filter(row => row.link_type === 'attended')).toEqual([]);
@@ -345,7 +349,7 @@ for (const kind of testBackends()) {
const other = 'attendance-other-example';
await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [other]);
try {
- await engine.setConfig(`schema_pack.source.${sourceId}`, 'gbrain-base');
+ await engine.setConfig(`schema_pack.source.${sourceId}`, 'phrase-owned-fixture');
await engine.setConfig(`schema_pack.source.${other}`, 'attendance-fixture');
await seed(meeting, 'meeting', positive);
await engine.putPage(person, { type: 'person', title: 'Alice Example', compiled_truth: 'Other source.' }, { sourceId: other });
@@ -436,8 +440,8 @@ for (const kind of testBackends()) {
});
for (const origin of [sourceId, 'default']) {
for (const [globalPack, sourcePack, incoming] of [
- ['attendance-fixture', 'gbrain-base', false],
- ['gbrain-base', 'attendance-fixture', true],
+ ['attendance-fixture', 'phrase-owned-fixture', false],
+ ['phrase-owned-fixture', 'attendance-fixture', true],
['missing-example-pack', 'attendance-fixture', true],
] as const) test(`local publication: source-selected ${origin}/${sourcePack} overrides global ${globalPack}`, async () => {
await engine.setConfig('schema_pack', globalPack);
@@ -449,15 +453,16 @@ for (const kind of testBackends()) {
dryRun: false, logger: { info() {}, warn() {}, error() {} } }, { slug: meeting,
content: `---\ntype: meeting\ntitle: Planning\nattendees: ["${person}"]\n---\n${positive}` }) as { auto_links: { errors: number } };
expect(result.auto_links.errors).toBe(0);
- expect((await engine.getBacklinks(meeting, { sourceId: origin })).filter(row => row.link_type === 'attended')).toHaveLength(incoming ? 2 : 0);
- expect((await engine.getLinks(meeting, { sourceId: origin })).filter(row => row.link_type === 'attended')).toHaveLength(incoming ? 0 : 2);
+ // Frontmatter attendees are always person -> meeting; only the phrase-owned body link stays outgoing.
+ expect((await engine.getBacklinks(meeting, { sourceId: origin })).filter(row => row.link_type === 'attended')).toHaveLength(incoming ? 2 : 1);
+ expect((await engine.getLinks(meeting, { sourceId: origin })).filter(row => row.link_type === 'attended')).toHaveLength(incoming ? 0 : 1);
} finally {
await engine.setConfig(`schema_pack.source.${origin}`, '');
if (origin === 'default') await engine.executeRaw('DELETE FROM pages WHERE source_id=$1', [origin]);
}
});
test(`local publication: unavailable source-selected ${origin} pack saves the note but preserves the graph`, async () => {
- await engine.setConfig(`schema_pack.source.${origin}`, 'gbrain-base');
+ await engine.setConfig(`schema_pack.source.${origin}`, 'phrase-owned-fixture');
try {
await engine.putPage(person, { type: 'person', title: 'Alice Example', compiled_truth: 'An example.' }, { sourceId: origin });
const op = operations.find(op => op.name === 'put_page')!;
@@ -465,14 +470,15 @@ for (const kind of testBackends()) {
dryRun: false, logger: { info() {}, warn() {}, error() {} } };
const content = `---\ntype: meeting\ntitle: Planning\nattendees: ["${person}"]\n---\n${positive}`;
await op.handler(ctx, { slug: meeting, content });
- const before = await engine.getLinks(meeting, { sourceId: origin });
+ const graph = async () => [...await engine.getLinks(meeting, { sourceId: origin }), ...await engine.getBacklinks(meeting, { sourceId: origin })];
+ const before = await graph();
expect(before.filter(row => row.link_type === 'attended')).toHaveLength(2);
const snapshot = (await engine.readPageSnapshot(meeting, { sourceId: origin }))!;
await engine.setConfig(`schema_pack.source.${origin}`, 'missing-example-pack');
const result = await op.handler(ctx, { slug: meeting, expected_revision: snapshot.revision,
content: `${content}\nThe note must survive.` }) as { auto_links: { errors: number; created: number; removed: number } };
expect(result.auto_links).toMatchObject({ errors: 1, created: 0, removed: 0 });
- expect(await engine.getLinks(meeting, { sourceId: origin })).toEqual(before);
+ expect(await graph()).toEqual(before);
expect((await engine.getPage(meeting, { sourceId: origin }))!.compiled_truth).toContain('The note must survive.');
} finally {
await engine.setConfig(`schema_pack.source.${origin}`, '');
@@ -490,10 +496,10 @@ for (const kind of testBackends()) {
expect(created.auto_links.errors).toBe(0);
const rows = () => engine.executeRaw<{ id: string; from_slug: string; to_slug: string; producer: string }>(`SELECT l.id::text,f.slug AS from_slug,t.slug AS to_slug,l.link_source AS producer
FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
- WHERE f.source_id=$1 AND f.slug=$2 AND l.link_type='attended'`, [sourceId, meeting]);
+ WHERE t.source_id=$1 AND t.slug=$2 AND l.link_type='attended'`, [sourceId, meeting]);
const before = await rows();
expect(before).toHaveLength(1);
- expect(before[0]).toMatchObject({ from_slug: meeting, to_slug: person, producer: 'frontmatter' });
+ expect(before[0]).toMatchObject({ from_slug: person, to_slug: meeting, producer: 'frontmatter' });
const snapshot = (await engine.readPageSnapshot(meeting, { sourceId }))!;
const updated = await op.handler(ctx, { slug: meeting, expected_revision: snapshot.revision,
content: `${content}\nAn unrelated edit.` }) as { auto_links: { created: number; removed: number; errors: number } };
@@ -555,7 +561,7 @@ for (const kind of testBackends()) {
expect(await attendees()).toEqual([person]);
});
test('local publication preserves pack-owned attendance and reports unavailable ontology without losing the note', async () => {
- await engine.setConfig('schema_pack', 'gbrain-base');
+ await engine.setConfig('schema_pack', 'phrase-owned-fixture');
await seed(meeting, 'meeting', positive);
await extract('db');
const before = await engine.getLinks(meeting, { sourceId });
@@ -753,15 +759,25 @@ for (const kind of testBackends()) {
expect(await attendees()).toEqual([]);
expect(await stamp()).not.toEqual(before);
});
- for (const packName of ['gbrain-base', 'company-brain']) test(`${packName}: pack_semantics_preserved`, async () => {
+ for (const packName of ['gbrain-base', 'company-brain']) test(`${packName}: shipped attendance mappings are canonical person -> meeting`, async () => {
await engine.setConfig('schema_pack', packName);
await seed(meeting, 'meeting', positive, { attendees: [person] });
await runExtract(engine, ['links', '--source', 'db', '--source-id', sourceId, '--include-frontmatter']);
- const rows = (await engine.getLinks(meeting, { sourceId })).filter(row => row.link_type === 'attended');
+ const rows = (await engine.getBacklinks(meeting, { sourceId })).filter(row => row.link_type === 'attended');
expect(rows.map(row => row.link_source).sort()).toEqual(['frontmatter', 'markdown']);
- expect(rows.every(row => row.to_slug === person)).toBe(true);
- expect(await attendees()).toEqual([]);
+ expect(rows.every(row => row.from_slug === person)).toBe(true);
+ expect((await engine.getLinks(meeting, { sourceId })).filter(row => row.link_type === 'attended')).toEqual([]);
+ expect(await attendees()).toEqual([person]);
+ });
+ test('phrase-owned-fixture: pack_semantics_preserved for body attendance', async () => {
+ await engine.setConfig('schema_pack', 'phrase-owned-fixture');
+ await seed(meeting, 'meeting', positive, { attendees: [person] });
+ await runExtract(engine, ['links', '--source', 'db', '--source-id', sourceId, '--include-frontmatter']);
+ const outgoing = (await engine.getLinks(meeting, { sourceId })).filter(row => row.link_type === 'attended');
+ expect(outgoing.map(row => [row.to_slug, row.link_source])).toEqual([[person, 'markdown']]);
expect((await engine.relationalFanout([meeting], { sourceId, direction: 'out', linkTypes: ['attended'] })).map(row => row.slug)).toContain(person);
+ const incoming = (await engine.getBacklinks(meeting, { sourceId })).filter(row => row.link_type === 'attended');
+ expect(incoming.map(row => [row.from_slug, row.link_source])).toEqual([[person, 'frontmatter']]);
});
test('manual and other-origin rows survive exact meeting removal', async () => {
await seed(meeting, 'meeting', positive);
diff --git a/test/derived-link-reconciliation.test.ts b/test/derived-link-reconciliation.test.ts
index bc99a97a34..7f745a737b 100644
--- a/test/derived-link-reconciliation.test.ts
+++ b/test/derived-link-reconciliation.test.ts
@@ -196,7 +196,7 @@ for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]
await seed('sessions/weekly', 'meeting', 'See [[choices/choice]].', { attendees: ['members/alice-example'] });
expect((await reconcileSourceLinks(engine, sourceId, { pack })).ok).toBe(true);
expect((await graph()).map(row => [row.from_slug, row.to_slug, row.link_type])).toEqual([
- ['sessions/weekly', 'choices/choice', 'mentions'], ['sessions/weekly', 'members/alice-example', 'attended'],
+ ['members/alice-example', 'sessions/weekly', 'attended'], ['sessions/weekly', 'choices/choice', 'mentions'],
]);
});
diff --git a/test/extract-db.test.ts b/test/extract-db.test.ts
index 617b770bfe..b5b1ce7527 100644
--- a/test/extract-db.test.ts
+++ b/test/extract-db.test.ts
@@ -56,9 +56,9 @@ describe('gbrain extract links --source db', () => {
await runExtract(engine, ['links', '--source', 'db']);
- const links = await engine.getLinks('meetings/standup');
+ const links = await engine.getBacklinks('meetings/standup');
expect(links.length).toBe(2);
- expect(new Set(links.map(l => l.to_slug))).toEqual(new Set(['people/alice', 'people/bob']));
+ expect(new Set(links.map(l => l.from_slug))).toEqual(new Set(['people/alice', 'people/bob']));
expect(links.every(l => l.link_type === 'attended')).toBe(true);
});
@@ -295,7 +295,7 @@ describe('--since ref-level prefilter (#4304)', () => {
await runExtract(engine, ['links', '--source', 'db', '--since', '2000-01-01']);
- expect((await engine.getLinks('meetings/standup')).length).toBeGreaterThanOrEqual(1);
+ expect((await engine.getBacklinks('meetings/standup')).length).toBeGreaterThanOrEqual(1);
});
test('timeline walk applies --since at the ref level too', async () => {
diff --git a/test/extract-endpoint-revision.serial.test.ts b/test/extract-endpoint-revision.serial.test.ts
index 87245af754..d346f69d54 100644
--- a/test/extract-endpoint-revision.serial.test.ts
+++ b/test/extract-endpoint-revision.serial.test.ts
@@ -36,10 +36,10 @@ for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]
afterAll(async () => { await close?.(); });
async function graph() {
- return engine.executeRaw<{ id: number; link_type: string; link_source: string; to_source: string }>(
- `SELECT l.id,l.link_type,l.link_source,t.source_id AS to_source FROM links l
- JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
- WHERE f.source_id=$1 AND f.slug=$2 ORDER BY l.id`, [sourceId, originSlug]);
+ return engine.executeRaw<{ id: number; link_type: string; link_source: string; peer_source: string }>(
+ `SELECT l.id,l.link_type,l.link_source,CASE WHEN f.source_id=$1 AND f.slug=$2 THEN t.source_id ELSE f.source_id END AS peer_source
+ FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
+ WHERE (f.source_id=$1 AND f.slug=$2) OR (t.source_id=$1 AND t.slug=$2) ORDER BY l.id`, [sourceId, originSlug]);
}
async function stamp() {
const rows = await engine.executeRaw<{ links_extracted_at: string | null }>(
@@ -64,7 +64,7 @@ for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]
: runExtract(engine, [mode, '--source', 'db', '--source-id', sourceId, '--json']);
await run();
const before = await graph();
- expect(before.filter(row => row.link_source === 'markdown').map(row => [row.link_type, row.to_source]))
+ expect(before.filter(row => row.link_source === 'markdown').map(row => [row.link_type, row.peer_source]))
.toEqual([['attended', targetSourceId]]);
await engine.executeRaw('UPDATE pages SET links_extracted_at=NULL WHERE source_id=$1 AND slug=$2', [sourceId, originSlug]);
const targetSnapshot = (await engine.readPageSnapshot(targetSlug, { sourceId: targetSourceId }))!;
@@ -96,7 +96,7 @@ for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]
exitSpy.mockRestore();
}
expect(retyped).toBe(true);
- expect(captured.some(link => link.link_type === 'attended' && link.to_source_id === targetSourceId)).toBe(true);
+ expect(captured.some(link => link.link_type === 'attended' && link.from_slug === targetSlug && link.from_source_id === targetSourceId)).toBe(true);
expect(fences).toContainEqual({ slug: targetSlug, sourceId: targetSourceId, revision: targetSnapshot.revision });
expect(await graph()).toEqual(before);
expect(await stamp()).toBeNull();
diff --git a/test/extract-timeline-attendance.test.ts b/test/extract-timeline-attendance.test.ts
index 8161eee84b..cd72eabae2 100644
--- a/test/extract-timeline-attendance.test.ts
+++ b/test/extract-timeline-attendance.test.ts
@@ -62,7 +62,7 @@ for (const kind of testBackends()) {
test.each([
['gbrain-base-v2', person, meeting],
- ['gbrain-base', meeting, person],
+ ['gbrain-base', person, meeting],
])('%s qualified evidence reaches the attendee timeline', async (pack, from, to) => {
await engine.setConfig('schema_pack', pack);
await seed(person, 'person');
diff --git a/test/link-inference-constraints.test.ts b/test/link-inference-constraints.test.ts
index 707be75803..133ea66836 100644
--- a/test/link-inference-constraints.test.ts
+++ b/test/link-inference-constraints.test.ts
@@ -53,7 +53,7 @@ describe('conjunctive link inference', () => {
const withoutEvidence = await extractPageLinks('sessions/weekly', 'See [[choices/choice]] and [[members/alice-example]].', {}, 'meeting',
{ resolve: async () => null }, { pack: active, targetType: slug => slug.startsWith('members/') ? 'person' : 'decision' });
expect(withoutEvidence.candidates.find(c => c.targetSlug === 'choices/choice')?.linkType).toBe('mentions');
- expect(withoutEvidence.candidates.find(c => c.targetSlug === 'members/alice-example')?.linkType).toBe(active ? 'attended' : 'mentions');
+ expect(withoutEvidence.candidates.find(c => c.targetSlug === 'members/alice-example')?.linkType).toBe('mentions');
}
});
@@ -73,11 +73,11 @@ describe('conjunctive link inference', () => {
expect(resolved).toEqual({ ok: true, fromSlug: 'rivals/rival-example', fromSourceId: 'alpha', toSourceId: 'beta' });
});
- test('pack attendees override the legacy incoming mapping without inverse duplicates', async () => {
+ test('pack attendees keep the declared incoming direction without inverse duplicates', async () => {
const result = await extractPageLinks('sessions/weekly', '', { attendees: ['members/alice-example'] }, 'meeting',
{ resolve: async name => name }, { pack, targetType: () => 'person' });
expect(result.candidates.map(c => [c.fromSlug, c.targetSlug, c.linkType])).toEqual([
- ['sessions/weekly', 'members/alice-example', 'attended'],
+ ['members/alice-example', 'sessions/weekly', 'attended'],
]);
});
diff --git a/test/links-attendance-blocked.test.ts b/test/links-attendance-blocked.test.ts
index 9c83c41fb4..4520f85c06 100644
--- a/test/links-attendance-blocked.test.ts
+++ b/test/links-attendance-blocked.test.ts
@@ -75,7 +75,7 @@ async function marker(engine: BrainEngine, sourceId: string) {
}
async function attended(engine: BrainEngine, sourceId: string) {
- return (await engine.getLinks(MEETING, { sourceId })).filter(l => l.to_slug === PERSON && l.link_type === 'attended').length;
+ return (await engine.getBacklinks(MEETING, { sourceId })).filter(l => l.from_slug === PERSON && l.link_type === 'attended').length;
}
/** A managed filesystem source with the meeting and its link target; auto_link off so extraction owns the links. */
diff --git a/test/pack-relation-direction-engine.test.ts b/test/pack-relation-direction-engine.test.ts
new file mode 100644
index 0000000000..3acfce5e7c
--- /dev/null
+++ b/test/pack-relation-direction-engine.test.ts
@@ -0,0 +1,162 @@
+/**
+ * Schema-pack relation direction through real extraction, retrieval and the
+ * re-derivation path, on both engines (eval wave N9-2, N9-3, N9-4, N12-7).
+ *
+ * The brain has no schema_pack configured, so it resolves the bundled legacy
+ * gbrain-base pack, exactly like brains created before `gbrain init` wrote one.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runExtract, extractStaleFromDB } from '../src/commands/extract.ts';
+import { operations } from '../src/core/operations.ts';
+import { buildRelationalArm, type RelationalArmMeta } from '../src/core/search/relational-recall.ts';
+import { parseRelationalQuery } from '../src/core/search/relational-intent.ts';
+import { LINK_EXTRACTOR_VERSION_TS } from '../src/core/link-extraction.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const alice = 'people/alice-example';
+const bob = 'people/bob-example';
+const company = 'companies/gamma-example';
+const bodyMeeting = 'meetings/board-acme-example';
+const fmMeeting = 'meetings/board-beta-example';
+
+for (const kind of testBackends()) {
+ describe(`schema-pack relation direction (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ if (kind === 'postgres') {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ } else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+ beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM links');
+ await engine.executeRaw('DELETE FROM pages');
+ expect(await engine.getConfig('schema_pack')).toBeNull();
+ });
+
+ async function seed(slug: string, type: string, title: string, body: string, frontmatter: Record<string, unknown> = {}) {
+ await engine.putPage(slug, { type, title, compiled_truth: body, frontmatter });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `${title}. ${body}` }]);
+ }
+ async function seedRepro() {
+ await seed(alice, 'person', 'Alice Example', 'Alice Example is a founder.');
+ await seed(bob, 'person', 'Bob Example', 'Bob Example is an investor.');
+ await seed(bodyMeeting, 'meeting', 'Acme Example Board Meeting',
+ 'Attendees: [Alice Example](people/alice-example), [Bob Example](people/bob-example).\n\nThe board reviewed the quarter.');
+ await seed(fmMeeting, 'meeting', 'Beta Example Board Meeting', 'The board reviewed the quarter.', { attendees: [alice, bob] });
+ await seed(company, 'company', 'Gamma Example', 'Gamma Example builds tools.', { investors: [bob] });
+ }
+ async function extract(args: string[]) {
+ const log = spyOn(console, 'log').mockImplementation(() => {});
+ try { await runExtract(engine, args); } finally { log.mockRestore(); }
+ }
+ async function typedEdges() {
+ const rows = await engine.executeRaw<{ edge: string }>(`SELECT f.slug || ' -> ' || t.slug || ' (' || l.link_type || ', ' || l.link_source || ')' AS edge
+ FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
+ WHERE l.link_type IN ('attended','invested_in') ORDER BY 1`);
+ return rows.map(row => row.edge);
+ }
+ const expected = [
+ `${alice} -> ${bodyMeeting} (attended, markdown)`,
+ `${alice} -> ${fmMeeting} (attended, frontmatter)`,
+ `${bob} -> ${company} (invested_in, frontmatter)`,
+ `${bob} -> ${bodyMeeting} (attended, markdown)`,
+ `${bob} -> ${fmMeeting} (attended, frontmatter)`,
+ ];
+ async function fanout(seedSlug: string, question: string) {
+ const parsed = parseRelationalQuery(question)!;
+ return (await engine.relationalFanout([seedSlug], { linkTypes: parsed.linkTypes, direction: parsed.direction, depth: 1, sourceId: 'default' }))
+ .map(row => row.slug).sort();
+ }
+
+ test('db extraction stores declared incoming relations toward the company and meeting (N9-2, N9-3)', async () => {
+ await seedRepro();
+ await extract(['links', '--source', 'db', '--include-frontmatter']);
+ expect(await typedEdges()).toEqual(expected);
+ expect(await fanout(company, 'Who invested in Gamma Example?')).toEqual([bob]);
+ expect(await fanout(bodyMeeting, 'Who attended Acme Example Board Meeting?')).toEqual([alice, bob]);
+ expect(await fanout(fmMeeting, 'Who attended Beta Example Board Meeting?')).toEqual([alice, bob]);
+ });
+
+ test('local publication types only listed attendees as attended (N12-7)', async () => {
+ await seed(alice, 'person', 'Alice Example', 'Alice Example.');
+ await seed(bob, 'person', 'Bob Example', 'Bob Example.');
+ const put = operations.find(op => op.name === 'put_page')!;
+ const result = await put.handler({ engine, config: { engine: kind }, remote: false, sourceId: 'default', dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } }, { slug: 'meetings/sync',
+ content: `---\ntype: meeting\ntitle: Sync\ndate: 2026-04-01\n---\n# Sync\n\n## Attendees\n\n- [[${alice}|Alice Example]]\n\n## Notes\n\n[[${bob}|Bob Example]] will send the deck.\n` }) as { auto_links: { errors: number } };
+ expect(result.auto_links.errors).toBe(0);
+ expect((await engine.getBacklinks('meetings/sync')).filter(l => l.link_type === 'attended').map(l => l.from_slug)).toEqual([alice]);
+ expect((await engine.getLinks('meetings/sync')).filter(l => l.link_type === 'attended')).toEqual([]);
+ expect((await engine.getLinks('meetings/sync')).find(l => l.to_slug === bob)?.link_type).toBe('mentions');
+ });
+
+ test('"Who attended <meeting title>?" resolves the meeting seed and fires (N9-4)', async () => {
+ await seedRepro();
+ await extract(['links', '--source', 'db', '--include-frontmatter']);
+ let meta: RelationalArmMeta | undefined;
+ const rows = await buildRelationalArm(engine, 'Who attended Acme Example Board Meeting?', { onMeta: m => { meta = m; } });
+ expect(meta).toMatchObject({ fired: true, seeds_resolved: 1 });
+ expect(rows.map(row => row.slug).sort()).toEqual([alice, bob]);
+ expect(rows.every(row => row.relational_seed === bodyMeeting)).toBe(true);
+ });
+
+ test('meeting titles seed only relations that need them, and only when unique', async () => {
+ await seedRepro();
+ await extract(['links', '--source', 'db', '--include-frontmatter']);
+ let meta: RelationalArmMeta | undefined;
+ await buildRelationalArm(engine, 'Who invested in Acme Example Board Meeting?', { onMeta: m => { meta = m; } });
+ expect(meta).toMatchObject({ fired: false, seeds_resolved: 0 });
+ await seed('meetings/board-acme-example-2', 'meeting', 'Acme Example Board Meeting', 'A second meeting with the same title.');
+ await buildRelationalArm(engine, 'Who attended Acme Example Board Meeting?', { onMeta: m => { meta = m; } });
+ expect(meta).toMatchObject({ fired: false, seeds_resolved: 0 });
+ });
+
+ async function insertPreFixEdges() {
+ // What extraction under the legacy pack wrote before the fix: incoming
+ // frontmatter mappings stored page -> target, body attendance stored
+ // meeting -> person with no origin, and a notes-only mention typed attended.
+ await engine.addLinksBatch([
+ { from_slug: company, to_slug: bob, link_type: 'invested_in', link_source: 'frontmatter', origin_slug: company, origin_field: 'investors', context: `frontmatter.investors: ${bob}` },
+ { from_slug: fmMeeting, to_slug: alice, link_type: 'attended', link_source: 'frontmatter', origin_slug: fmMeeting, origin_field: 'attendees', context: `frontmatter.attendees: ${alice}` },
+ { from_slug: fmMeeting, to_slug: bob, link_type: 'attended', link_source: 'frontmatter', origin_slug: fmMeeting, origin_field: 'attendees', context: `frontmatter.attendees: ${bob}` },
+ { from_slug: bodyMeeting, to_slug: alice, link_type: 'attended', link_source: 'markdown', context: 'Attendees: [Alice Example]' },
+ { from_slug: bodyMeeting, to_slug: bob, link_type: 'attended', link_source: 'markdown', context: 'Attendees: [Bob Example]' },
+ { from_slug: 'meetings/sync', to_slug: bob, link_type: 'attended', link_source: 'markdown', context: 'Bob Example will send the deck.' },
+ ]);
+ }
+
+ test('re-derivation: extract links --source db --include-frontmatter rewrites stored pre-fix edges', async () => {
+ await seedRepro();
+ await seed('meetings/sync', 'meeting', 'Sync', `## Attendees\n\n- [[${alice}|Alice Example]]\n\n## Notes\n\n[[${bob}|Bob Example]] will send the deck.\n`);
+ await insertPreFixEdges();
+ await extract(['links', '--source', 'db', '--include-frontmatter']);
+ expect(await typedEdges()).toEqual([...expected, `${alice} -> meetings/sync (attended, markdown)`].sort());
+ expect((await engine.getLinks('meetings/sync')).find(l => l.to_slug === bob)?.link_type).toBe('mentions');
+ });
+
+ test('re-derivation: the extractor version bump makes extract --stale rewrite pages stamped before it', async () => {
+ await seedRepro();
+ await insertPreFixEdges();
+ // Stamped by the pre-fix extractor after its own watermark (2026-09-30T00:00:00Z).
+ const before = '2026-09-30T12:00:00Z';
+ expect(Date.parse(LINK_EXTRACTOR_VERSION_TS)).toBeGreaterThan(Date.parse(before));
+ await engine.executeRaw(`UPDATE pages SET updated_at=$1::timestamptz - interval '1 day', links_extracted_at=$1::timestamptz`, [before]);
+ const result = await extractStaleFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, includeFrontmatter: true, catchUp: true });
+ expect(result.pagesProcessed).toBe(5);
+ expect(await typedEdges()).toEqual(expected);
+ const stale = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE links_extracted_at < $1::timestamptz', [LINK_EXTRACTOR_VERSION_TS]);
+ expect(stale[0].n).toBe(0);
+ });
+ });
+}
diff --git a/test/pack-relation-direction.test.ts b/test/pack-relation-direction.test.ts
new file mode 100644
index 0000000000..7f420cfd63
--- /dev/null
+++ b/test/pack-relation-direction.test.ts
@@ -0,0 +1,103 @@
+/**
+ * Schema-pack relation direction (eval wave N9-2, N9-3, N12-7).
+ *
+ * The bundled packs mirror FRONTMATTER_LINK_MAP and the in-code meeting
+ * attendance rule. Pack-declared frontmatter mappings must keep the declared
+ * direction (company `investors:` is investor -> company, meeting `attendees:`
+ * is person -> meeting), and a pack's `attended` verb on a meeting page must
+ * follow canonical, evidence-gated attendance (person -> meeting, only from an
+ * explicit attendee list). Pure extraction checks run here; the engine-level
+ * checks live in test/pack-relation-direction-engine.test.ts.
+ */
+import { describe, expect, test } from 'bun:test';
+import { extractPageLinks, type LinkCandidate, type SlugResolver } from '../src/core/link-extraction.ts';
+import { loadPackFromFile } from '../src/core/schema-pack/loader.ts';
+import { bundledPackPath } from '../src/core/schema-pack/bundled-assets.ts';
+
+const types: Record<string, string> = {
+ 'people/alice-example': 'person', 'people/bob-example': 'person', 'companies/gamma-example': 'company',
+ 'funds/fund-a': 'fund', 'deals/gamma-seed': 'deal', 'meetings/board-example': 'meeting', 'customers/acme-example': 'customer',
+};
+const resolver: SlugResolver = {
+ async resolve(name) { return types[name] ? name : null; },
+ async resolveAttendance(name) { return types[name] === 'person' ? name : null; },
+};
+const pack = (name: string) => loadPackFromFile(bundledPackPath(name)!);
+const edges = (candidates: LinkCandidate[], self: string) => candidates
+ .filter(c => c.linkType !== 'mentions')
+ .map(c => {
+ const from = c.fromSlug ?? self;
+ return c.canonicalAttendance ? `${c.targetSlug} -> ${from} (${c.linkType})` : `${from} -> ${c.targetSlug} (${c.linkType})`;
+ }).sort();
+async function extract(packName: string | null, slug: string, type: string, body: string, frontmatter: Record<string, unknown> = {}) {
+ const result = await extractPageLinks(slug, body, frontmatter, type as never, resolver,
+ { pack: packName ? pack(packName) : null, targetType: target => types[target] });
+ return { ...result, edges: edges(result.candidates, slug) };
+}
+
+for (const packName of [null, 'gbrain-base', 'company-brain', 'gbrain-base-v2']) {
+ const label = packName ?? 'no pack';
+ describe(`frontmatter relation direction (${label})`, () => {
+ test('meeting attendees are stored person -> meeting', async () => {
+ const r = await extract(packName, 'meetings/board-example', 'meeting', 'The board reviewed the quarter.',
+ { attendees: ['people/alice-example', 'people/bob-example'] });
+ expect(r.edges).toEqual([
+ 'people/alice-example -> meetings/board-example (attended)',
+ 'people/bob-example -> meetings/board-example (attended)',
+ ]);
+ });
+ });
+}
+
+for (const packName of [null, 'gbrain-base']) {
+ describe(`incoming frontmatter mappings keep their direction (${packName ?? 'no pack'})`, () => {
+ test('company investors, key_people and partner point at the company', async () => {
+ const r = await extract(packName, 'companies/gamma-example', 'company', 'Gamma Example builds tools.', {
+ investors: ['funds/fund-a'], key_people: ['people/alice-example'], partner: 'people/bob-example',
+ });
+ expect(r.edges).toEqual([
+ 'funds/fund-a -> companies/gamma-example (invested_in)',
+ 'people/alice-example -> companies/gamma-example (works_at)',
+ 'people/bob-example -> companies/gamma-example (yc_partner)',
+ ]);
+ });
+ test('deal investors and lead point at the deal', async () => {
+ const r = await extract(packName, 'deals/gamma-seed', 'deal', 'Seed round.', { investors: ['people/bob-example'], lead: 'funds/fund-a' });
+ expect(r.edges).toEqual(['funds/fund-a -> deals/gamma-seed (led_round)', 'people/bob-example -> deals/gamma-seed (invested_in)']);
+ });
+ test('outgoing person mappings stay outgoing', async () => {
+ const r = await extract(packName, 'people/alice-example', 'person', 'Alice Example.', { company: 'companies/gamma-example' });
+ expect(r.edges).toEqual(['people/alice-example -> companies/gamma-example (works_at)']);
+ });
+ });
+}
+
+test('a pack mapping with no declared incoming counterpart stays outgoing (company-brain owner)', async () => {
+ const r = await extract('company-brain', 'customers/acme-example', 'customer', 'A customer.', { owner: 'people/alice-example' });
+ expect(r.edges).toEqual(['customers/acme-example -> people/alice-example (owned_by)']);
+});
+
+for (const packName of [null, 'gbrain-base', 'company-brain', 'gbrain-base-v2']) {
+ describe(`meeting body attendance (${packName ?? 'no pack'})`, () => {
+ test('an explicit attendee list is canonical person -> meeting attendance', async () => {
+ const r = await extract(packName, 'meetings/board-example', 'meeting',
+ 'Attendees: [Alice Example](people/alice-example), [Bob Example](people/bob-example).\n\nThe board reviewed the quarter.');
+ expect(r.candidates.filter(c => c.linkType === 'attended').every(c => c.canonicalAttendance)).toBe(true);
+ expect(r.edges).toEqual([
+ 'people/alice-example -> meetings/board-example (attended)',
+ 'people/bob-example -> meetings/board-example (attended)',
+ ]);
+ expect(r.attendanceComplete).toBe(true);
+ });
+ test('a person only mentioned in the notes is not an attendee (N12-7)', async () => {
+ const r = await extract(packName, 'meetings/board-example', 'meeting',
+ '## Attendees\n\n- [[people/alice-example|Alice Example]]\n\n## Notes\n\n[[people/bob-example|Bob Example]] will send the deck.\n');
+ expect(r.edges).toEqual(['people/alice-example -> meetings/board-example (attended)']);
+ expect(r.candidates.find(c => c.targetSlug === 'people/bob-example')?.linkType).toBe('mentions');
+ });
+ test('a non-person in the attendee list is a mention', async () => {
+ const r = await extract(packName, 'meetings/board-example', 'meeting', 'Attendees: [Gamma](companies/gamma-example)');
+ expect(r.edges).toEqual([]);
+ });
+ });
+}