Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(resolve): a bare name that collides under prefix expansion resolves to its exact-title page (N9-5)

garrytanaf006bcb40bf
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index be870db0ea..06f141ef25 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -81,7 +81,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax cases) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K). `checkResolvable(skillsDir, opts?)` takes an optional `skillsDirSource` (the detection tier from `autoDetectSkillsDir`, threaded by both callers: doctor.ts and the check-resolvable command; an explicit `--skills-dir` passes `null`). An `unreachable` issue downgrades from `error` to `warning` only when ALL hold: the directory was found via the ungated `cwd_walk_up` tier, no resolver file contributes rows (no `RESOLVER.md`; a generic `AGENTS.md` with zero table rows counts as absent), unreachable skills outnumber reachable ones, and no `manifest.json` exists on disk. This keeps a foreign tool's `skills/` dir walked up to from cwd from being scored as a broken gbrain skillpack, while a real skillpack (RESOLVER.md present, higher-confidence tier, dense trigger coverage, or any manifest.json, even a corrupted one) stays strict. A foreign dir with zero `triggers:` and no resolver file still hard-fails via the `missing_file` branch (separate follow-up).
-- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` (tagged `prefix_expansion`, not `fuzzy_match`: the sole candidate is chosen by cardinality, so `facts/backstop.ts` appends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), the candidate is an entity page (person/company/fund/org, host, project, concept or deal — never a meeting or note), and it is the only such candidate, so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper takes a fuzzy hit only at trigram ≥ 0.7 with a 0.1 margin over the runner-up. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC`. Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard).
+- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` (when several candidates share one directory, the single page titled exactly the bare name wins: "Acme" over "Acme Labs", gbrain-evals N9-5; cross-directory collisions and duplicate exact titles stay ambiguous) (tagged `prefix_expansion`, not `fuzzy_match`: the sole candidate is chosen by cardinality, so `facts/backstop.ts` appends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), the candidate is an entity page (person/company/fund/org, host, project, concept or deal — never a meeting or note), and it is the only such candidate, so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper takes a fuzzy hit only at trigram ≥ 0.7 with a 0.1 margin over the runner-up. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC`. Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard).
- `src/core/facts/subject-infer.ts` — zero-LLM fact subject inference shared by the write paths (remember, the facts backstop) and `gbrain facts relink`. `inferFactSubject(engine, sourceId, { fact, pageSlug?, mode, excludePrivate? })` returns `{ slug, via: 'page' | 'mention' }` or a miss reason (`ambiguous`, `unverified_match`, `no_mention`, `no_page`). Page tier: the trusted page the fact came from, when it is a live fact-entity page. Mention tier: strong `extractCandidates` names plus slugs written in the text, resolved through `resolveStrictEntityReference` (exact slug, unique basename, unique alias; `relink` mode adds the same-name trigram arm); exactly one entity links. Any other real name that does not resolve to the same entity (including names with no page and bare first names) vetoes the link; sentence-start capitals, weekdays/months and role terms (CEO, Q3) do not. `excludePrivate` removes private pages before uniqueness is counted. Also `appendContextNote`/`contextHead` (the `" — "` note convention), `recordedPageSlug` (page provenance of page-extraction rows only) and `isEntityInferenceEnabled` (`facts.entity_inference` kill switch for write-time inference; relink ignores it). `resolveStrictEntityReference` in `entities/resolve.ts` never guesses from a bare-name prefix and never slug-falls-back. Pinned by `test/facts-subject-infer.test.ts` (a 40+ fact labeled fixture: write precision >= 0.99, relink free tiers >= 0.95).
diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.ts
index c79d2144a6..a1db9cf0df 100644
--- a/src/core/entities/resolve.ts
+++ b/src/core/entities/resolve.ts
@@ -35,7 +35,8 @@ import { privatePagesFilterFragment } from '../search/private-visibility.ts';
* exact pages.slug row in this source), return it untouched. A mention
* that is exactly one live page's own name (slug basename) resolves to
* it next, before any other page's alias.
- * 2. Resolve a bare name only when prefix expansion finds one candidate.
+ * 2. Resolve a bare name only when prefix expansion finds one candidate,
+ * or one candidate whose title is exactly that name.
* 3. For multi-token input, take a fuzzy candidate within the source only
* when it carries the same name tokens (sameEntityName).
* 4. Fall back to a deterministic slugify: lowercase-no-spaces with
@@ -85,7 +86,7 @@ export async function resolveEntitySlug(
// `"Alice"` → `people/alice-example` before we phantom-stub a bare
// `people/alice.md`.
if (isBareName(trimmed)) {
- const expanded = await tryUnambiguousPrefixExpansion(engine, source_id, slugify(trimmed));
+ const expanded = await tryUnambiguousPrefixExpansion(engine, source_id, trimmed);
if (expanded) return expanded;
} else {
// 3. Fuzzy match against existing pages within the source. Bare names
@@ -279,7 +280,7 @@ export async function resolveEntitySlugWithSource(
if (basenames.length > 1) return { slug: fallbackSlugify(trimmed), source: 'fallback_slugify' };
if (isBareName(trimmed)) {
- const expanded = await tryUnambiguousPrefixExpansion(engine, source_id, slugify(trimmed));
+ const expanded = await tryUnambiguousPrefixExpansion(engine, source_id, trimmed);
if (expanded) return { slug: expanded, source: 'prefix_expansion' };
} else {
const fuzzy = await tryFuzzyMatch(engine, source_id, trimmed);
@@ -476,13 +477,43 @@ export async function findPrefixCandidates(
}
}
+/**
+ * The sole prefix candidate, or, when every candidate sits in one entity
+ * directory, the one page whose title is exactly the bare name: "Acme" is
+ * `companies/acme-0` titled "Acme", not `companies/acme-labs-50` titled
+ * "Acme Labs" (gbrain-evals N9-5). A collision across directories (a person
+ * and a host) or two exact titles stays ambiguous.
+ */
async function tryUnambiguousPrefixExpansion(
engine: BrainEngine,
source_id: string,
- token: string,
+ raw: string,
): Promise<string | null> {
+ const token = slugify(raw);
const candidates = await findPrefixCandidates(engine, source_id, token);
- return candidates.length === 1 ? candidates[0].slug : null;
+ if (candidates.length === 1) return candidates[0].slug;
+ if (candidates.length === 0) return null;
+ const patterns = PREFIX_EXPANSION_DIRS.flatMap(dir => [`${dir}/${token}`, `${dir}/${token}-%`]);
+ try {
+ const dirs = await engine.executeRaw<{ dir: string }>(
+ `SELECT DISTINCT split_part(slug, '/', 1) AS dir FROM pages
+ WHERE source_id = $1 AND deleted_at IS NULL AND slug LIKE ANY($2::text[])
+ LIMIT 2`,
+ [source_id, patterns],
+ );
+ if (dirs.length !== 1) return null;
+ const rows = await engine.executeRaw<{ slug: string; title: string | null }>(
+ `SELECT slug, title FROM pages
+ WHERE source_id = $1 AND deleted_at IS NULL
+ AND slug LIKE ANY($2::text[]) AND lower(title) = lower($3)
+ LIMIT 3`,
+ [source_id, patterns, raw.trim()],
+ );
+ const exact = rows.filter(r => sameEntityName(raw, r.title, r.slug));
+ return exact.length === 1 ? exact[0].slug : null;
+ } catch {
+ return null;
+ }
}
/**
diff --git a/test/entity-resolve-prefix-dirs.test.ts b/test/entity-resolve-prefix-dirs.test.ts
index 56c4d46b85..f7f54c223b 100644
--- a/test/entity-resolve-prefix-dirs.test.ts
+++ b/test/entity-resolve-prefix-dirs.test.ts
@@ -18,7 +18,7 @@
*/
import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
-import { resolveEntitySlug } from '../src/core/entities/resolve.ts';
+import { resolveEntitySlug, resolveEntitySlugWithSource } from '../src/core/entities/resolve.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
let engine: PGLiteEngine;
@@ -39,6 +39,13 @@ beforeAll(async () => {
// infra/ is a mixed namespace of analysis/runbook docs — must NOT be
// prefix-expanded.
{ slug: 'infra/vault-runbook', title: 'Vault Runbook', type: 'note' },
+ // N9-5: two companies share the prefix; one is titled exactly the name.
+ { slug: 'companies/acme-0', title: 'Acme', type: 'company' },
+ { slug: 'companies/acme-labs-50', title: 'Acme Labs', type: 'company' },
+ // Two exact titles in one directory stay ambiguous.
+ { slug: 'companies/delta-1', title: 'Delta', type: 'company' },
+ { slug: 'companies/delta-2', title: 'Delta', type: 'company' },
+ { slug: 'companies/delta-labs-3', title: 'Delta Labs', type: 'company' },
];
for (const p of pages) {
await engine.putPage(p.slug, {
@@ -69,6 +76,15 @@ describe('resolveEntitySlug — hosts/ and projects/ prefix expansion', () => {
expect(await resolveEntitySlug(engine, 'default', 'kiwi')).toBe('kiwi');
});
+ it('N9-5: a same-directory collision resolves to the page titled exactly the bare name', async () => {
+ expect(await resolveEntitySlug(engine, 'default', 'Acme')).toBe('companies/acme-0');
+ expect(await resolveEntitySlugWithSource(engine, 'default', 'Acme')).toEqual({ slug: 'companies/acme-0', source: 'prefix_expansion' });
+ });
+
+ it('N9-5: two exact titles in one directory stay ambiguous', async () => {
+ expect(await resolveEntitySlug(engine, 'default', 'Delta')).toBe('delta');
+ });
+
it('infra/ pages are not prefix-expanded', async () => {
expect(await resolveEntitySlug(engine, 'default', 'vault')).toBe('vault');
});
diff --git a/test/relational-recall.test.ts b/test/relational-recall.test.ts
index ad0bc71307..120b22fd8a 100644
--- a/test/relational-recall.test.ts
+++ b/test/relational-recall.test.ts
@@ -45,6 +45,14 @@ beforeAll(async () => {
await installFixtureChunks(eng, 'people/mallory-secret', [{ chunk_index: 0, chunk_source: 'compiled_truth',
chunk_text: 'Mallory runs a stealth family office in Zurich.' }]);
await eng.addLink('people/mallory-secret', 'companies/widget-co', '', 'invested_in', 'manual');
+
+ // N9-5 (gbrain-evals world-v1): "Acme" collides with "Acme Labs" under
+ // bare-name prefix expansion; the page titled exactly "Acme" is the seed.
+ await eng.putPage('companies/acme-0', { type: 'company', title: 'Acme', compiled_truth: 'A robotics company.', timeline: '' });
+ await eng.putPage('companies/acme-labs-50', { type: 'company', title: 'Acme Labs', compiled_truth: 'A research lab.', timeline: '' });
+ await eng.putPage('people/bea-example', { type: 'person', title: 'Bea Example', compiled_truth: 'Bea is an engineer.', timeline: '' });
+ await installFixtureChunks(eng, 'people/bea-example', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Bea is an engineer.' }]);
+ await eng.addLink('people/bea-example', 'companies/acme-0', '', 'works_at', 'manual');
}, 60_000);
afterAll(async () => { await eng.disconnect(); });
@@ -61,6 +69,13 @@ describe('buildRelationalArm', () => {
expect(alice!.chunk_id).toBeGreaterThan(0);
});
+ test('N9-5: a bare company name that collides under prefix expansion seeds from its exact-title page', async () => {
+ const list = await buildRelationalArm(eng, 'Who works at Acme?');
+ const bea = list.find(r => r.slug === 'people/bea-example');
+ expect(bea).toBeDefined();
+ expect(bea!.relational_seed).toBe('companies/acme-0');
+ });
+
test('non-relational query is a pure no-op', async () => {
const meta: { fired?: boolean } = {};
const list = await buildRelationalArm(eng, 'summary of the payments roadmap', { onMeta: m => { meta.fired = m.fired; } });