mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-17 10:22:34 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d2b814e4d |
+5
-15
@@ -43,7 +43,7 @@ import {
|
||||
} from '../core/link-extraction.ts';
|
||||
import { createProgress } from '../core/progress.ts';
|
||||
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
|
||||
import { pathToSlug, slugifyPath, pruneDir, isSyncable } from '../core/sync.ts';
|
||||
import { pathToSlug, pruneDir, isSyncable } from '../core/sync.ts';
|
||||
// v0.41.18.0: withRetry + isRetryableConnError + WithRetryOpts moved to
|
||||
// src/core/retry.ts as the canonical primitive. Engine methods
|
||||
// (addLinksBatch/addTimelineEntriesBatch/upsertChunks) now self-retry via
|
||||
@@ -269,24 +269,14 @@ export function extractMarkdownLinks(content: string): { name: string; relTarget
|
||||
export function resolveSlug(fileDir: string, relTarget: string, allSlugs: Set<string>): string | null {
|
||||
const targetNoExt = relTarget.endsWith('.md') ? relTarget.slice(0, -3) : relTarget;
|
||||
|
||||
// Issue #1964: wikilinks carry raw Obsidian paths (`[[llm-wiki/entities/AI 3.0]]`)
|
||||
// but allSlugs holds sync-slugified slugs (`llm-wiki/entities/ai-3.0`). Try the
|
||||
// raw candidate first (back-compat), then the sync-consistent slugified form.
|
||||
const hit = (candidate: string): string | null => {
|
||||
if (allSlugs.has(candidate)) return candidate;
|
||||
const slugified = slugifyPath(candidate);
|
||||
if (slugified !== candidate && allSlugs.has(slugified)) return slugified;
|
||||
return null;
|
||||
};
|
||||
|
||||
const s1 = hit(join(fileDir, targetNoExt));
|
||||
if (s1) return s1;
|
||||
const s1 = join(fileDir, targetNoExt);
|
||||
if (allSlugs.has(s1)) return s1;
|
||||
|
||||
const parts = fileDir.split('/').filter(Boolean);
|
||||
for (let strip = 1; strip <= parts.length; strip++) {
|
||||
const ancestor = parts.slice(0, parts.length - strip).join('/');
|
||||
const candidate = hit(ancestor ? join(ancestor, targetNoExt) : targetNoExt);
|
||||
if (candidate) return candidate;
|
||||
const candidate = ancestor ? join(ancestor, targetNoExt) : targetNoExt;
|
||||
if (allSlugs.has(candidate)) return candidate;
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
import type { BrainEngine } from './engine.ts';
|
||||
import type { PageType } from './types.ts';
|
||||
import { ensureWellFormed } from './text-safe.ts';
|
||||
import { slugifyPath } from './sync.ts';
|
||||
|
||||
/**
|
||||
* v0.42.7 — link-extraction version stamp. Bump this ISO timestamp whenever the
|
||||
@@ -483,29 +482,14 @@ export async function extractPageLinks(
|
||||
// pre-v0.40.8.2 behavior of dropping bare wikilinks outside
|
||||
// DIR_PATTERN.
|
||||
if (ref.needsResolution) {
|
||||
if (typeof resolver.resolveBasenameMatches !== 'function') continue;
|
||||
if (!opts.globalBasename || typeof resolver.resolveBasenameMatches !== 'function') {
|
||||
continue;
|
||||
}
|
||||
// Issue #972 (codex): resolve by the wikilink TARGET (ref.slug — the
|
||||
// text inside `[[...]]` before any `|`), NOT the display alias
|
||||
// (ref.name = match[2]). `[[struktura|the project]]` must resolve
|
||||
// `struktura`, not "the project". The display text is for context only.
|
||||
//
|
||||
// Issue #1964: a dir-qualified wikilink (`[[llm-wiki/entities/AI 3.0]]`)
|
||||
// carries a raw Obsidian path while page slugs are sync-slugified
|
||||
// (`llm-wiki/entities/ai-3.0`). Slugify the path the same way sync does,
|
||||
// then match by exact slug or path-suffix (wiki-root-relative authoring).
|
||||
// This runs regardless of global_basename — it's dir-qualified, so the
|
||||
// cross-dir false-positive risk the flag guards against doesn't apply.
|
||||
// Mirrors the FS path's resolveSlug ancestor walk. Bare `[[name]]`
|
||||
// wikilinks still require the global_basename flag.
|
||||
let matches: string[] = [];
|
||||
const slugified = ref.slug.includes('/') ? slugifyPath(ref.slug) : '';
|
||||
if (slugified.includes('/')) {
|
||||
const tail = slugified.slice(slugified.lastIndexOf('/') + 1);
|
||||
matches = (await resolver.resolveBasenameMatches(tail))
|
||||
.filter(m => m === slugified || m.endsWith(`/${slugified}`));
|
||||
} else if (opts.globalBasename) {
|
||||
matches = await resolver.resolveBasenameMatches(ref.slug);
|
||||
}
|
||||
const matches = await resolver.resolveBasenameMatches(ref.slug);
|
||||
if (matches.length === 0) continue;
|
||||
const idx = content.indexOf(ref.slug);
|
||||
const context = idx >= 0 ? excerpt(content, idx, 240) : ref.name;
|
||||
|
||||
+35
-1
@@ -135,7 +135,16 @@ export function parseMarkdown(
|
||||
const type = coerceFrontmatterString(frontmatter.type) || (
|
||||
opts?.activePack ? inferTypeFromPack(filePath, opts.activePack) : inferType(filePath)
|
||||
);
|
||||
const title = coerceFrontmatterString(frontmatter.title).trim() || inferTitle(filePath);
|
||||
// #2446: title precedence is frontmatter `title:` > the body's first H1 >
|
||||
// the slug/filename-humanized fallback. Slug-based imports (contacts,
|
||||
// calendar) write a correct `# Heading` but no frontmatter title; without
|
||||
// the H1 fallback they get junk titles humanized from the slug
|
||||
// (`Contact 20170928 5 John Defalco`), which also breaks anything keyed on
|
||||
// the title (e.g. the by-mention gazetteer's first-token bucketing).
|
||||
const title =
|
||||
coerceFrontmatterString(frontmatter.title).trim() ||
|
||||
inferTitleFromBody(body) ||
|
||||
inferTitle(filePath);
|
||||
const tags = extractTags(frontmatter);
|
||||
const slug = coerceFrontmatterString(frontmatter.slug) || inferSlug(filePath);
|
||||
|
||||
@@ -602,6 +611,31 @@ function inferTypeWithPrefixes(
|
||||
return 'concept';
|
||||
}
|
||||
|
||||
/**
|
||||
* #2446: derive a title from the body's first ATX H1 (`# Heading`).
|
||||
*
|
||||
* Returns the trimmed heading text with the leading `# ` and any decorative
|
||||
* trailing `#` run stripped, or '' if the body has no H1. Only a SINGLE leading
|
||||
* `#` matches — `##`+ (h2 and deeper) are skipped — and lines inside a fenced
|
||||
* code block (```/~~~) are ignored so a `# comment` in a shell snippet can't be
|
||||
* mistaken for the page title.
|
||||
*/
|
||||
function inferTitleFromBody(body: string): string {
|
||||
let inFence = false;
|
||||
for (const raw of body.split('\n')) {
|
||||
const fence = /^\s*(`{3,}|~{3,})/.exec(raw);
|
||||
if (fence) {
|
||||
inFence = !inFence;
|
||||
continue;
|
||||
}
|
||||
if (inFence) continue;
|
||||
// Exactly one leading `#`, then whitespace, then the heading text.
|
||||
const m = /^#(?!#)\s+(.+?)\s*$/.exec(raw);
|
||||
if (m) return m[1].replace(/\s+#+\s*$/, '').trim();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function inferTitle(filePath?: string): string {
|
||||
if (!filePath) return 'Untitled';
|
||||
|
||||
|
||||
@@ -389,33 +389,6 @@ describe('resolveSlugAll', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ─── issue #1964: cross-directory wikilinks — slug/path mismatch ──────────
|
||||
|
||||
describe('issue #1964: raw Obsidian wikilink paths resolve to sync-slugified slugs', () => {
|
||||
test('resolveSlug slugifies the candidate (sync-consistent), no flag needed', () => {
|
||||
const all = new Set(['llm-wiki/entities/ai-3.0']);
|
||||
// Wikilink literal `[[llm-wiki/entities/AI 3.0]]` — spaces + uppercase.
|
||||
expect(resolveSlug('llm-wiki/notes', 'llm-wiki/entities/AI 3.0.md', all))
|
||||
.toBe('llm-wiki/entities/ai-3.0');
|
||||
});
|
||||
|
||||
test('resolveSlug slugifies raw (unslugified) fileDir too', () => {
|
||||
const all = new Set(['llm-wiki/entities/ai-3.0']);
|
||||
// fileDir comes from dirname(relPath) — the raw on-disk directory.
|
||||
expect(resolveSlug('LLM Wiki/Notes', 'entities/AI 3.0.md', all))
|
||||
.toBe('llm-wiki/entities/ai-3.0');
|
||||
});
|
||||
|
||||
test('extractLinksFromFile resolves cross-directory wikilink with flag OFF as a typed edge', async () => {
|
||||
const allSlugs = new Set(['llm-wiki/entities/ai-3.0', 'llm-wiki/notes/roadmap']);
|
||||
const content = '---\ntitle: Roadmap\ntype: concept\n---\n\nSee [[llm-wiki/entities/AI 3.0]].\n';
|
||||
const links = await extractLinksFromFile(content, 'llm-wiki/notes/roadmap.md', allSlugs);
|
||||
expect(links.map(l => l.to_slug)).toEqual(['llm-wiki/entities/ai-3.0']);
|
||||
// Dir-qualified path resolution is exact, NOT the basename fallback.
|
||||
expect(links[0].link_type).not.toBe('wikilink_basename');
|
||||
});
|
||||
});
|
||||
|
||||
describe('issue #972 repro: bare wikilinks resolve when flag is on', () => {
|
||||
// End-to-end: reproduces the issue's exact repro inside a tempdir +
|
||||
// PGLite, then asserts edge count under both flag states.
|
||||
|
||||
@@ -9,8 +9,6 @@ import {
|
||||
parseTimelineEntries,
|
||||
isAutoLinkEnabled,
|
||||
FRONTMATTER_LINK_MAP,
|
||||
buildBasenameIndex,
|
||||
queryBasenameIndex,
|
||||
type SlugResolver,
|
||||
} from '../src/core/link-extraction.ts';
|
||||
import type { BrainEngine } from '../src/core/engine.ts';
|
||||
@@ -426,46 +424,6 @@ describe('extractPageLinks', () => {
|
||||
expect(strk!.linkType).toBe('wikilink_basename');
|
||||
});
|
||||
|
||||
// ─── issue #1964: dir-qualified wikilinks with raw Obsidian paths ────────
|
||||
|
||||
test('#1964: dir-qualified wikilink resolves via sync-consistent slugification (flag OFF)', async () => {
|
||||
// `[[llm-wiki/entities/AI 3.0]]` is a raw Obsidian path; the page slug
|
||||
// is the sync-slugified `llm-wiki/entities/ai-3.0`. Must resolve WITHOUT
|
||||
// global_basename (it's dir-qualified) and must NOT leak to a same-tail
|
||||
// page in a different directory.
|
||||
const resolver: SlugResolver = {
|
||||
resolve: async () => null,
|
||||
resolveBasenameMatches: async (name) =>
|
||||
name === 'ai-3.0' ? ['other/ai-3.0', 'llm-wiki/entities/ai-3.0'] : [],
|
||||
};
|
||||
const { candidates } = await extractPageLinks(
|
||||
'llm-wiki/notes/roadmap',
|
||||
'See [[llm-wiki/entities/AI 3.0]] for the model.',
|
||||
{}, 'concept', resolver,
|
||||
// opts.globalBasename omitted (= false) — path is dir-qualified
|
||||
);
|
||||
expect(candidates.map(c => c.targetSlug)).toEqual(['llm-wiki/entities/ai-3.0']);
|
||||
expect(candidates[0].linkType).toBe('wikilink_basename');
|
||||
expect(candidates[0].linkSource).toBe('wikilink-resolved');
|
||||
});
|
||||
|
||||
test('#1964: path-suffix match resolves wiki-root-relative paths against a real index', async () => {
|
||||
// Author writes `[[llm-wiki/entities/AI 3.0]]` but the brain nests the
|
||||
// wiki under a vault dir. Suffix match rescues it; queried through the
|
||||
// REAL basename index so the tail-key lookup is exercised end to end.
|
||||
const idx = buildBasenameIndex(['vault/llm-wiki/entities/ai-3.0', 'people/ai-3.0']);
|
||||
const resolver: SlugResolver = {
|
||||
resolve: async () => null,
|
||||
resolveBasenameMatches: async (name) => queryBasenameIndex(idx, name),
|
||||
};
|
||||
const { candidates } = await extractPageLinks(
|
||||
'vault/llm-wiki/notes/roadmap',
|
||||
'See [[llm-wiki/entities/AI 3.0]].',
|
||||
{}, 'concept', resolver,
|
||||
);
|
||||
expect(candidates.map(c => c.targetSlug)).toEqual(['vault/llm-wiki/entities/ai-3.0']);
|
||||
});
|
||||
|
||||
test('opts.skipFrontmatter suppresses the frontmatter pass', async () => {
|
||||
// Real resolver shape that WOULD resolve frontmatter source: too,
|
||||
// but skipFrontmatter blocks the path entirely.
|
||||
|
||||
@@ -343,3 +343,47 @@ describe('issue #1939 — non-string frontmatter coercion', () => {
|
||||
expect(parsed.title).toBe('A Normal Title');
|
||||
});
|
||||
});
|
||||
|
||||
// issue #2446 — when frontmatter has no `title:`, prefer the body's first H1
|
||||
// over the slug/filename-humanized fallback. Slug-based imports (contacts,
|
||||
// calendar) carry a correct `# Heading` but no frontmatter title; humanizing
|
||||
// the slug leaks date/id tokens and loses casing (`Defalco` vs `DeFalco`).
|
||||
describe('issue #2446 — body H1 fallback for missing frontmatter title', () => {
|
||||
test('no frontmatter title uses the body H1, not the slug-humanized junk', () => {
|
||||
const md = '---\ntype: person\n---\n\n# John DeFalco\n\nNotes about John.\n';
|
||||
const parsed = parseMarkdown(md, 'people/contact-20170928-5-john-defalco.md');
|
||||
expect(parsed.title).toBe('John DeFalco');
|
||||
// The slug-derived junk title must NOT win.
|
||||
expect(parsed.title).not.toBe('Contact 20170928 5 John Defalco');
|
||||
});
|
||||
|
||||
test('no frontmatter title and no H1 falls back to the inferred slug title', () => {
|
||||
const md = '---\ntype: note\n---\n\njust body prose, no heading\n';
|
||||
const parsed = parseMarkdown(md, 'people/alice-example.md');
|
||||
expect(parsed.title).toBe('Alice Example');
|
||||
});
|
||||
|
||||
test('frontmatter title wins over a body H1 (no regression)', () => {
|
||||
const md = '---\ntitle: Frontmatter Wins\n---\n\n# Body Heading\n\nbody\n';
|
||||
const parsed = parseMarkdown(md, 'people/some-slug.md');
|
||||
expect(parsed.title).toBe('Frontmatter Wins');
|
||||
});
|
||||
|
||||
test('h2 is not treated as the title; first real H1 is used', () => {
|
||||
const md = '---\ntype: note\n---\n\n## Subsection First\n\n# The Real Title\n\nbody\n';
|
||||
const parsed = parseMarkdown(md, 'notes/x.md');
|
||||
expect(parsed.title).toBe('The Real Title');
|
||||
});
|
||||
|
||||
test('a # inside a fenced code block is not mistaken for the title', () => {
|
||||
const md = '---\ntype: note\n---\n\n```sh\n# this is a shell comment, not a heading\n```\n\n# Actual Heading\n';
|
||||
const parsed = parseMarkdown(md, 'notes/x.md');
|
||||
expect(parsed.title).toBe('Actual Heading');
|
||||
});
|
||||
|
||||
test('trailing closing hashes are stripped from the H1', () => {
|
||||
const md = '---\ntype: note\n---\n\n# Closed ATX Heading #\n\nbody\n';
|
||||
const parsed = parseMarkdown(md, 'notes/x.md');
|
||||
expect(parsed.title).toBe('Closed ATX Heading');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user