Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

P4.5 #4845 #6158: g_contacts_dir, connector stubs yield to the canonical twin under cross_source, junk_entity_hubs remedies

garrytane0ba0cf560fa
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.md
index 47d83bd5b2..1744a2d0e2 100644
--- a/docs/architecture/key-files/entity-recall.md
+++ b/docs/architecture/key-files/entity-recall.md
@@ -5,7 +5,7 @@ subject, frontmatter alias or declared code) to that entity page, keeps the
links current from `gbrain extract --stale`, and serves them on the `entity`
card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).
-- `src/core/by-mention.ts` — the pure mention matcher plus its gazetteer. `buildGazetteer(engine, opts)` loads linkable entity titles and aliases per source (drops below-minimum, generic, ambiguous-first-word and colliding names, reported as `DroppedName`), keyed by lowercase first token and sorted longest-first. `findMentionedEntities(text, gazetteer, opts)` masks code with `stripCodeBlocks`, then picks the longest matching entry at each token (maximal munch), first mention per target only, skipping self-links and other sources unless `allowCrossSource` (an own-source twin wins). Word-run scripts match whole tokens; Han and Kana match character substrings. A Hangul name must start a word, keep its written spacing, and end at a non-Hangul character or an attached title/particle/copula suffix (`HANGUL_NAME_SUFFIX_RE`), so 지원에게 matches and 지원하는 does not ([measurement](../../designs/hangul-mention-boundaries.md)). A matcher change bumps `MENTION_EXTRACTOR_VERSION` (`mentions/pass.ts`, every page rescans once) and the semantics tag inside `hashGazetteer` (the `extract links --by-mention` resume checkpoint). `scanStaleMentions` is the read-only doctor scan for mention rows the current gazetteer no longer produces.
+- `src/core/by-mention.ts` — the pure mention matcher plus its gazetteer. `buildGazetteer(engine, opts)` loads linkable entity titles and aliases per source (drops below-minimum, generic, ambiguous-first-word and colliding names, reported as `DroppedName`), keyed by lowercase first token and sorted longest-first. `findMentionedEntities(text, gazetteer, opts)` masks code with `stripCodeBlocks`, then picks the longest matching entry at each token (maximal munch), first mention per target only, skipping self-links and other sources unless `allowCrossSource` (an own-source twin wins, except that a connector contact stub, `connector_stub` from `google_contact_id` frontmatter, yields under `allowCrossSource` to the one canonical same-name page in another source or the one sharing its slug; #6158). Word-run scripts match whole tokens; Han and Kana match character substrings. A Hangul name must start a word, keep its written spacing, and end at a non-Hangul character or an attached title/particle/copula suffix (`HANGUL_NAME_SUFFIX_RE`), so 지원에게 matches and 지원하는 does not ([measurement](../../designs/hangul-mention-boundaries.md)). A matcher change bumps `MENTION_EXTRACTOR_VERSION` (`mentions/pass.ts`, every page rescans once) and the semantics tag inside `hashGazetteer` (the `extract links --by-mention` resume checkpoint). `scanStaleMentions` is the read-only doctor scan for mention rows the current gazetteer no longer produces.
- `src/core/mentions/policy.ts` — the one linkable-type resolver. `linkableTypesFor(pack, policy)`: `person`, `company`, `organization`, `entity` (`ALWAYS_LINKABLE_TYPES`, never removable) plus every pack type with `primitive: entity` and its type aliases (`product` excluded), adjusted by `mentions.entity_types` (`+type`/`type` adds, `-type` removes). `readMentionPolicy` reads `auto_link`, `mentions.auto_link`, `mentions.entity_types`, `mentions.ignore` and `mentions.exclude_slugs` (#5829: listed pages get no gazetteer entry by title or alias, dropped as `excluded_slug`; JSON array or comma list, `parseNameList`). `canonicalTypeOf` / `typeAliasPairs` map a stored type through the pack's type aliases (`untyped` for none); pairs are bound as two `text[]`. `loadSourcePack(engine, sourceId, {strict})` returns null on a resolution failure unless strict. Tests: `test/mentions-policy-aliases.test.ts`.
- `src/core/mentions/aliases.ts` — derived names of an entity page. `titleSubject` (text after the last `: `), `declaredNames` (the `account code` / `also known as` / `a.k.a.` / `aka` / `short name` / `ticker` / `code name` parser shared with search's `aliasDeclarations`), `deriveEntityAliases` (subject `origin='subject'`, declarations `origin='declared'`, read from `publicBody`: private takes and facts fences stripped; a single-token declaration is `case_sensitive`). `aliasRejection`: under 4 characters, a generic word, or the first word of the page's own multi-word name. Rejections are returned for explain. Tests: `test/mentions-policy-aliases.test.ts`.
- `src/core/mentions/pass.ts` — `runMentionPass(engine, {sourceId?, deadline?, signal?, beforePublish?})`, run by `extractStaleFromDB` (unmanaged) and `extractManagedStaleLinks` (managed, unless `mentions: false`). Per source: policy off → `disableSource` deletes plain mention links (`link_kind` null or `plain`; `typed_ner` stays), derived alias rows, saved entries and page state once and records `disabled`; a changed policy fingerprint (types, cross-source flag, ignore list) marks every page due; `refreshAliases` rewrites derived rows of entity pages whose `page_mention_state.alias_revision`/`alias_version` differ (revision-checked, coordinated write when managed) and removes them from pages that stopped being entities; `buildGazetteer({strict: true})` failing writes nothing and records `failed`; `saveEntries` diffs `mention_gazetteer_entries` under `pg_advisory_xact_lock`, bumps the source generation and marks due only pages linking to a removed target plus pages a mini-gazetteer of added names matches (ASCII names prefiltered with `LIKE` on lower-cased text, others scanned in JS; a first save marks the source due); `reconcileSource` scans due pages (no state row, or `mention_revision`/`mention_version` differ) in batches of 200 and publishes only when the source generations (`FOR SHARE`) and each page's `knowledge_revision` (`FOR SHARE`) are unchanged, writing link diffs (`addLinksBatch`, audit site `extract.mentions`) and page state in one transaction; then the status row gets state, pending count and `last_pass_at`. `writeDerivedAliases` / `writePageAliases` are import's and `reindex --aliases`' alias projection. `MENTION_EXTRACTOR_VERSION` and `ALIAS_DERIVATION_VERSION` are independent of `LINK_EXTRACTOR_VERSION_TS`. The scanned text is title, compiled truth and timeline; frontmatter `mention_ignore` names are skipped per page. Tests: `test/mentions-pass.test.ts`, `test/mentions-managed.test.ts`, `test/e2e/mentions-parity.test.ts`.
diff --git a/docs/guides/google-connect.md b/docs/guides/google-connect.md
index b6eb47dc7e..8dbecebe4a 100644
--- a/docs/guides/google-connect.md
+++ b/docs/guides/google-connect.md
@@ -99,6 +99,30 @@ Repeat `gbrain google connect --account [email protected]` per account; each
account becomes its own source (`gbrain sources add gmail-work --kind google
--account [email protected]`) with independent sync cursors and locks.
+## Contacts next to your own person pages
+
+A Google source renders each contact as a near-empty person page under
+`people/<slug>` by default, the same directory a brain repo uses for its own
+hand-written profiles. On a multi-source brain that collision has two
+costs: mentions in the Gmail source bind to the contact stub instead of the
+real profile, and `gbrain doctor` lists the stubs under `junk_entity_hubs`.
+Two remedies, independent of each other:
+
+- **Keep contacts out of `people/`.** Add the source with
+ `--contacts-dir contacts` (stored as the source's `g_contacts_dir`; any
+ relative directory of lower-case segments). Contact pages are found by
+ their `google_contact_id`, not by directory, so a source whose directory
+ changes moves every contact on its next sweep: the new page lands first,
+ then the page under the old directory is retired. The default stays
+ `people` for every existing source.
+- **Let the stub yield.** With `gbrain config set link_resolution.cross_source
+ true`, a mention in the Gmail source of a name that has a real page in
+ another source binds to that page instead of the connector's stub (one
+ canonical page, or the one sharing the stub's slug; a tie keeps the stub).
+ The next mention pass (`gbrain extract --stale`, or autopilot) re-binds
+ pages it reaches; `gbrain doctor --only junk_entity_hubs` names the
+ canonical twin of each stub and the next step.
+
## Secondary calendars
The calendar sweep reads ONE calendar per source (so each keeps its own
diff --git a/src/commands/doctor/checks/graph-embedding.ts b/src/commands/doctor/checks/graph-embedding.ts
index 1437a71f67..1789d8ac1e 100644
--- a/src/commands/doctor/checks/graph-embedding.ts
+++ b/src/commands/doctor/checks/graph-embedding.ts
@@ -11,6 +11,7 @@ import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { checkError } from '../check-fix.ts';
import { isConnectorSourceKind } from '../../../core/persistence/connector-identity.ts';
+import { isCrossSourceLinksEnabled } from '../../../core/link-extraction.ts';
/**
* v0.40.4 graph_signals_coverage doctor check.
@@ -462,7 +463,7 @@ export async function checkJunkEntityHubs(
chunks: number;
connector_page: boolean;
source_kind: string | null;
- default_twin: boolean;
+ canonical_twin_source: string | null;
}>(
`WITH edge_counts AS (
SELECT page_id, COUNT(*)::int AS edges FROM (
@@ -481,8 +482,11 @@ export async function checkJunkEntityHubs(
SELECT p.slug, p.source_id, ec.edges, COALESCE(cc.chunks, 0)::int AS chunks,
(p.frontmatter ->> 'google_contact_id') IS NOT NULL AS connector_page,
s.config ->> 'kind' AS source_kind,
- EXISTS (SELECT 1 FROM pages t WHERE t.source_id = 'default' AND t.slug = p.slug
- AND t.deleted_at IS NULL AND p.source_id <> 'default') AS default_twin
+ (SELECT t.source_id FROM pages t LEFT JOIN sources ts ON ts.id = t.source_id
+ WHERE t.slug = p.slug AND t.source_id <> p.source_id AND t.deleted_at IS NULL
+ AND (t.frontmatter ->> 'google_contact_id') IS NULL
+ AND COALESCE(ts.config ->> 'kind', '') NOT IN ('google', 'github')
+ ORDER BY (t.source_id = 'default') DESC, t.source_id LIMIT 1) AS canonical_twin_source
FROM edge_counts ec
JOIN pages p ON p.id = ec.page_id AND p.deleted_at IS NULL
LEFT JOIN sources s ON s.id = p.source_id
@@ -518,19 +522,39 @@ export async function checkJunkEntityHubs(
`buildGazetteer drops single-generic-token person titles. If a page is an intentional thin ` +
`hub/index page, opt it out with junk_hub_exempt: true in frontmatter.`);
}
+ // #6158 / #4845 (W14 P4.5): the remedies are real now. With
+ // link_resolution.cross_source on, the mention pass binds a name in the
+ // connector's source to the canonical twin instead of the stub (the stub
+ // yields; by-mention.ts), and a Google source added with --contacts-dir
+ // keeps its contact pages out of people/ altogether.
+ const crossSource = twins.length > 0 ? await isCrossSourceLinksEnabled(engine) : false;
+ const withTwin = twins.filter(r => r.canonical_twin_source !== null).length;
if (twins.length > 0) {
parts.push(
`${twins.length} connector contact page(s) with >${edgeThreshold} edges:\n${twins.map(line).join('\n')}\n` +
`These are not junk: a connector renders each contact as its own page, and mentions in that source link to it ` +
- `before the main-brain page of the same name (by design). Frontmatter edits do not stick (the connector re-renders ` +
- `the page) and gbrain has no merge command. Whether a contact page should defer to its main-brain twin is an open ` +
- `policy question (issue #6158); nothing needs doing now, so ask the user before changing anything.`);
+ `before a page of the same name elsewhere unless link_resolution.cross_source is on. ` +
+ `${withTwin} of them ${withTwin === 1 ? 'has' : 'have'} a canonical twin in another source. ` +
+ (crossSource
+ ? `cross_source is on, so the next mention pass (gbrain extract --stale, or autopilot) re-binds those mentions to the twin; ` +
+ `edges already on the stub move as the pass reaches each page.`
+ : `Run gbrain config set link_resolution.cross_source true, then gbrain extract --stale: mentions in the connector source ` +
+ `bind to the twin from then on. `) +
+ `To keep a Google source's contacts out of people/ entirely, add it with --contacts-dir contacts (g_contacts_dir). ` +
+ `Frontmatter edits do not stick (the connector re-renders the page) and gbrain has no merge command.`);
}
+ const verify = { argv: ['gbrain', 'doctor', '--only', 'junk_entity_hubs', '--json'] };
+ const twinFix = twins.length === 0 ? {} : crossSource
+ ? { fix: { argv: ['gbrain', 'extract', '--stale'], consent: [], actor: 'agent' as const, requires_exclusive: false,
+ why: 'Runs the mention pass, which binds names in the connector source to their canonical twin now that cross_source is on.', verify } }
+ : { fix: { argv: ['gbrain', 'config', 'set', 'link_resolution.cross_source', 'true'], consent: [], actor: 'agent' as const, requires_exclusive: false,
+ why: 'Lets a mention resolve to a same-name page in another source; a connector contact stub then yields to its canonical twin on the next mention pass (gbrain extract --stale).',
+ user_message: 'Mentions in your Gmail source bind to the connector\'s own contact stubs instead of your real person pages. Turn on cross-source link resolution so they bind to the real pages?', verify } };
return {
name: 'junk_entity_hubs',
status: 'warn',
message: parts.join('\n'),
- ...(twins.length > 0 ? { fix_unavailable_reason: 'operator_judgement' as const } : {}),
+ ...twinFix,
details: {
hubs: hubs.map(r => ({
slug: r.slug,
@@ -543,7 +567,8 @@ export async function checkJunkEntityHubs(
source_id: r.source_id ?? 'default',
edges: r.edges,
chunks: r.chunks,
- canonical_twin: r.default_twin ? r.slug : null,
+ canonical_twin: r.canonical_twin_source ? r.slug : null,
+ canonical_twin_source: r.canonical_twin_source,
})),
},
};
diff --git a/src/commands/sources-google-flags.ts b/src/commands/sources-google-flags.ts
index 4a45066529..c91b768252 100644
--- a/src/commands/sources-google-flags.ts
+++ b/src/commands/sources-google-flags.ts
@@ -1,18 +1,20 @@
/**
* The Google-kind tuning flags of the legacy `gbrain sources add` parser
* (`--history-days`, `--future-days`, `--loops-exclude-labels`,
- * `--calendar-id`): one value each, validated the moment they are read.
+ * `--contacts-dir`, `--calendar-id`): one value each, validated the moment they are read.
* The connected-source parser (sources-lifecycle-args.ts) validates the same
* flags through the operation contract; this module keeps the legacy path's
* exit-2 behaviour without growing runAdd.
*/
import { CALENDAR_FUTURE_DAYS_MAX } from '../core/google/calendar-window.ts';
import { parseExcludeLabelTokens } from '../core/google/loops-exclusion.ts';
+import { parseContactsDir } from '../core/google/source-config.ts';
import { DEFAULT_CALENDAR_ID } from '../core/google/types.ts';
export interface GoogleAddTuning {
historyDays: number;
calendarId: string;
+ contactsDir?: string;
futureDays?: number;
loopsExcludeLabels?: string[];
}
@@ -45,6 +47,12 @@ export function parseGoogleAddFlag(flag: string, value: string | undefined, tuni
tuning.loopsExcludeLabels = labels;
return true;
}
+ case '--contacts-dir': {
+ const dir = parseContactsDir(value);
+ if (!dir) refuse('--contacts-dir must be a relative directory of lower-case segments (a-z, 0-9, -, _), e.g. --contacts-dir contacts.');
+ tuning.contactsDir = dir!;
+ return true;
+ }
case '--calendar-id': {
const v = (value ?? '').trim();
if (!v) refuse('--calendar-id needs a value (see: gbrain google calendars).');
diff --git a/src/commands/sources-lifecycle-args.ts b/src/commands/sources-lifecycle-args.ts
index 9ee53b3275..3715355d90 100644
--- a/src/commands/sources-lifecycle-args.ts
+++ b/src/commands/sources-lifecycle-args.ts
@@ -11,6 +11,7 @@ import { isValidRepoName } from '../core/github-source.ts';
import { ALL_GOOGLE_SERVICES, DEFAULT_CALENDAR_ID } from '../core/google/types.ts';
import { CALENDAR_FUTURE_DAYS_MAX, CALENDAR_HORIZON_DAYS } from '../core/google/calendar-window.ts';
import { parseExcludeLabelTokens } from '../core/google/loops-exclusion.ts';
+import { parseContactsDir } from '../core/google/source-config.ts';
export const SOURCE_LIFECYCLE_COMMANDS = ['add', 'remove', 'archive', 'restore', 'purge', 'set-path', 'reclone'] as const;
export function isSourceLifecycleCommand(value: string): boolean {
@@ -40,7 +41,7 @@ export function parseSourceLifecycleArgs(args: string[], generatedId = randomUUI
'federated', 'no-federated', 'no-federate', 'refederate', 'no-harden']);
const valued = new Set(['request-id', 'expected-incarnation', 'brain', 'path', 'url', 'name', 'clone-dir',
'pat-file', 'kind', 'account', 'access', 'token-command', 'token-env', 'services', 'history-days',
- 'future-days', 'loops-exclude-labels', 'calendar-id', 'scope', 'repos', 'dir', 'app-id', 'app-pem', 'app-install']);
+ 'future-days', 'loops-exclude-labels', 'contacts-dir', 'calendar-id', 'scope', 'repos', 'dir', 'app-id', 'app-pem', 'app-install']);
for (let i = 0; i < rest.length; i++) {
const token = rest[i];
if (!token.startsWith('-')) { positionals.push(token); continue; }
@@ -105,7 +106,7 @@ export function parseSourceLifecycleArgs(args: string[], generatedId = randomUUI
'Pass --kind github or --kind google; a directory or Git remote source uses --path or --url instead of --kind.');
if ([values.has('path'), values.has('url'), kind !== undefined].filter(Boolean).length > 1) throw invalid('--path, --url and --kind are mutually exclusive.',
'Give exactly one of --path (a local directory), --url (an https Git remote) or --kind (github or google).');
- const googleOnly = ['account', 'access', 'token-command', 'services', 'history-days', 'future-days', 'loops-exclude-labels', 'calendar-id'];
+ const googleOnly = ['account', 'access', 'token-command', 'services', 'history-days', 'future-days', 'loops-exclude-labels', 'contacts-dir', 'calendar-id'];
const githubOnly = ['scope', 'repos', 'app-id', 'app-pem', 'app-install'];
const kindOptions = [...googleOnly, ...githubOnly, 'dir', 'token-env'];
for (const key of kindOptions) if (values.has(key) && !kind) throw invalid(`--${key} requires --kind github or google.`,
@@ -158,7 +159,11 @@ export function parseSourceLifecycleArgs(args: string[], generatedId = randomUUI
const loopsExcludeLabels = parseExcludeLabelTokens(values.get('loops-exclude-labels'));
if (values.has('loops-exclude-labels') && loopsExcludeLabels.length === 0) throw invalid('--loops-exclude-labels needs at least one label.',
'Pass --loops-exclude-labels as a comma-separated list of Gmail label names or ids, e.g. --loops-exclude-labels "Newsletters,Label_7".');
+ const contactsDir = values.has('contacts-dir') ? parseContactsDir(values.get('contacts-dir')) : undefined;
+ if (contactsDir === null) throw invalid('--contacts-dir must be a relative directory of lower-case segments.',
+ 'Pass --contacts-dir as one or more segments of a-z, 0-9, - and _ (e.g. --contacts-dir contacts); it is relative to the source directory.');
opts.google = { account, services, historyDays: number('history-days', 90)!, calendarId: values.get('calendar-id') ?? DEFAULT_CALENDAR_ID,
+ ...(contactsDir ? { contactsDir } : {}),
...(futureDays !== undefined ? { futureDays } : {}), ...(loopsExcludeLabels.length > 0 ? { loopsExcludeLabels } : {}),
dir: absolute(values.get('dir') ?? defaultCloneDir(`${id}-google`)), access: access as 'vault' | 'command' | 'env',
tokenCommand: values.get('token-command'), tokenEnv: values.get('token-env') };
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 382f5dc988..0b38fe557d 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -144,7 +144,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
'[--repos owner/name,...] [--dir <path>] ' +
'[--app-id <n> --app-pem <path>] [--app-install <n>]\n' +
' google kind: --account <email> [--services gmail,calendar,contacts] ' +
- '[--history-days <n>] [--future-days <n>] [--loops-exclude-labels <a,b>] [--calendar-id <id>] [--dir <path>] (connect first: gbrain google connect)\n' +
+ '[--history-days <n>] [--future-days <n>] [--loops-exclude-labels <a,b>] [--contacts-dir <dir>] [--calendar-id <id>] [--dir <path>] (connect first: gbrain google connect)\n' +
' [--access vault|command|env] [--token-command "<cmd>"] [--token-env <VAR>] (non-vault Google access: gog/gcloud/gateway)',
);
process.exit(2);
diff --git a/src/core/by-mention.ts b/src/core/by-mention.ts
index c181546a43..7b6379f658 100644
--- a/src/core/by-mention.ts
+++ b/src/core/by-mention.ts
@@ -88,6 +88,13 @@ export interface GazetteerEntry {
caseTokens?: string[];
/** Spelling being matched (the alias, not the display title, for aliases). */
matchText?: string;
+ /**
+ * #6158: the page is a connector's own contact rendering (`google_contact_id`
+ * frontmatter), a near-empty stub of a person who may have a canonical page
+ * elsewhere. Under the cross-source opt-in a mention in the stub's source
+ * binds to that canonical twin instead (see findMentionedEntities).
+ */
+ connector_stub?: true;
}
/**
@@ -479,13 +486,15 @@ export async function buildGazetteer(
}
const allTypes = [...new Set([...typesBySource.values()].flatMap(set => [...set]))];
const linkable = (sourceId: string | null, type: string | null) => !!type && (typesBySource.get(sourceId ?? 'default')?.has(type) ?? false);
- const rows = (await engine.executeRaw<{ slug: string; source_id: string | null; title: string | null; type: string | null }>(
- `SELECT slug, source_id, title, type
+ const rows = (await engine.executeRaw<{ slug: string; source_id: string | null; title: string | null; type: string | null; connector_stub: boolean }>(
+ `SELECT slug, source_id, title, type, (frontmatter ->> 'google_contact_id') IS NOT NULL AS connector_stub
FROM pages
WHERE type = ANY($1::text[])
AND deleted_at IS NULL`,
[allTypes],
)).filter(r => linkable(r.source_id, r.type));
+ const stubPages = new Set(rows.filter(r => r.connector_stub).map(r => `${r.source_id ?? 'default'}\0${r.slug}`));
+ const stubFlag = (src: string, slug: string) => stubPages.has(`${src}\0${slug}`) ? { connector_stub: true as const } : {};
const ignoreSet = new Set<string>(DEFAULT_IGNORE_LIST);
const userIgnore = new Set(policy.ignore.map(n => tokenizeTitle(n).join(' ')).filter(Boolean));
@@ -535,7 +544,7 @@ export async function buildGazetteer(
// below.
if (tokens.length === 1 && row.type === 'person' && isGenericEntityToken(tokens[0]!)) { drop({ ...base, reason: 'generic_token' }); continue; }
noteFirstWord(src, tokens);
- add({ slug: row.slug, source_id: src, title: row.title, tokens, origin: 'title', matchText: row.title });
+ add({ slug: row.slug, source_id: src, title: row.title, tokens, origin: 'title', matchText: row.title, ...stubFlag(src, row.slug) });
}
// ── Alias entries ────────────────────────────────────────────────────────
@@ -625,7 +634,7 @@ export async function buildGazetteer(
if (tokens.length === 1 && isGenericEntityToken(tokens[0]!)) { drop({ ...base, reason: 'generic_token' }); continue; }
const caseTokens = a.case_sensitive && a.alias_text ? caseTokensOf(a.alias_text) : undefined;
const entry: GazetteerEntry = { slug: a.slug, source_id: src, title: a.title, tokens, origin, matchText: alias,
- ...(caseTokens && caseTokens.length === tokens.length ? { caseTokens } : {}) };
+ ...(caseTokens && caseTokens.length === tokens.length ? { caseTokens } : {}), ...stubFlag(src, a.slug) };
noteFirstWord(src, tokens);
aliasEntries.push({ entry, base });
}
@@ -781,17 +790,26 @@ export function findMentionedEntities(
// Same-name twin in the scanning page's own source wins over a foreign
// one: bucket order is length-only, so `matched` may be the cross-source
// twin even when an own-source entry with identical tokens exists.
+ const sameName = (e: GazetteerEntry, want: GazetteerEntry) =>
+ e.tokens.length === want.tokens.length
+ && e.tokens.every((t, k) => t === want.tokens[k])
+ && caseMatches(e, i)
+ && hasHangulMatchBoundary(stripped, tokens, i, e);
if (matched.source_id !== opts.fromSourceId) {
- const want = matched.tokens;
- const own = bucket.find(
- e => e.source_id === opts.fromSourceId
- && e.tokens.length === want.length
- && e.tokens.every((t, k) => t === want[k])
- && caseMatches(e, i)
- && hasHangulMatchBoundary(stripped, tokens, i, e),
- );
+ const want = matched;
+ const own = bucket.find(e => e.source_id === opts.fromSourceId && sameName(e, want));
if (own) matched = own;
}
+ // #6158: under the cross-source opt-in, a connector's contact stub (own
+ // source or not) yields to the canonical same-name page in another
+ // source: the one such page, or the one that shares its slug. Several
+ // candidates and no slug match keep the stub (an honest tie).
+ if (opts.allowCrossSource && matched.connector_stub) {
+ const stub = matched;
+ const canonical = bucket.filter(e => !e.connector_stub && e.source_id !== stub.source_id && sameName(e, stub));
+ const pick = canonical.length === 1 ? canonical[0] : canonical.find(e => e.slug === stub.slug);
+ if (pick && canonical.filter(e => e.slug === pick.slug).length === 1) matched = pick;
+ }
if (ignored.size > 0 && ignored.has(matched.tokens.join(' '))) {
i += matchedTokens;
continue;
diff --git a/src/core/google/google-render.ts b/src/core/google/google-render.ts
index 396c4ef30c..649cb55aeb 100644
--- a/src/core/google/google-render.ts
+++ b/src/core/google/google-render.ts
@@ -14,7 +14,7 @@ import { createHash } from 'node:crypto';
import { renderAttachmentInspection, threadAttachmentReceipts } from './attachment-receipts.ts';
import { emailCitation } from '../output/scaffold.ts';
-import type { CalendarEventData, ContactData, GmailThreadData } from './types.ts';
+import { DEFAULT_CONTACTS_DIR, type CalendarEventData, type ContactData, type GmailThreadData } from './types.ts';
// ── Noise + signature rules (recipes/email-to-brain.md, now code) ───────────
@@ -343,7 +343,7 @@ export function renderCalendarEventPage(ev: CalendarEventData): RenderedPage | n
// ── Person page (contacts) ───────────────────────────────────────────────────
-export function personSlugFromContact(c: ContactData, disambiguate = false): string | null {
+export function personSlugFromContact(c: ContactData, disambiguate = false, dir: string = DEFAULT_CONTACTS_DIR): string | null {
const base = c.displayName ?? c.emails[0]?.split('@')[0] ?? null;
if (!base) return null;
const slug = base
@@ -355,7 +355,7 @@ export function personSlugFromContact(c: ContactData, disambiguate = false): str
// Two different contacts named "John Smith" must not fight over one page —
// the caller requests disambiguation when the base slug is already owned
// by a DIFFERENT google_contact_id.
- return disambiguate ? `people/${slug}-${sha8(c.resourceName)}` : `people/${slug}`;
+ return disambiguate ? `${dir}/${slug}-${sha8(c.resourceName)}` : `${dir}/${slug}`;
}
/**
@@ -364,8 +364,8 @@ export function personSlugFromContact(c: ContactData, disambiguate = false): str
* marker are connector-owned and fully re-rendered; hand-authored pages at
* the same path are skipped entirely — body AND frontmatter untouched.
*/
-export function renderPersonPage(c: ContactData, disambiguate = false): RenderedPage | null {
- const slug = personSlugFromContact(c, disambiguate);
+export function renderPersonPage(c: ContactData, disambiguate = false, dir: string = DEFAULT_CONTACTS_DIR): RenderedPage | null {
+ const slug = personSlugFromContact(c, disambiguate, dir);
if (!slug || c.emails.length === 0) return null;
const name = c.displayName ?? c.emails[0];
const aliases = [...new Set([...c.emails, ...(c.displayName ? [c.displayName] : [])])];
diff --git a/src/core/google/people-calendar-sweep.ts b/src/core/google/people-calendar-sweep.ts
index e8d83d3ab3..f976afa656 100644
--- a/src/core/google/people-calendar-sweep.ts
+++ b/src/core/google/people-calendar-sweep.ts
@@ -52,13 +52,15 @@ export async function sweepContacts(
const m = readFileSync(filePath, 'utf-8').match(/^google_contact_id:\s*"([^"]+)"/m);
return m ? m[1] : 'hand-authored';
};
+ const contactsDir = deps.cfg.contactsDir;
for (const c of result.contacts) {
if (deps.opts.signal?.aborted) return;
- // DB lookup by contact id FIRST: deletion tombstones typically carry only
- // resourceName + deleted (no names/emails — slug derivation yields null),
- // and a renamed contact's current name derives a DIFFERENT slug than the
- // page it owns. Both cases need the id-keyed path (mirror of the calendar
- // sweep's event_id keying).
+ // DB lookup by contact id FIRST, in any directory: deletion tombstones
+ // typically carry only resourceName + deleted (no names/emails — slug
+ // derivation yields null), a renamed contact's current name derives a
+ // DIFFERENT slug than the page it owns, and a changed `g_contacts_dir`
+ // (#4845) moves every page. All three need the id-keyed path (mirror of
+ // the calendar sweep's event_id keying).
const existingPath = await contactPageRelPathByContactId(deps, c.resourceName);
if (c.deleted) {
if (existingPath && await ownerOf(existingPath) === c.resourceName) {
@@ -66,7 +68,7 @@ export async function sweepContacts(
} else {
// Page not (yet) in the DB — fall back to slug candidates, guarded
// by file ownership. Delete only the page THIS contact owns.
- for (const slug of [personSlugFromContact(c, false), personSlugFromContact(c, true)]) {
+ for (const slug of [personSlugFromContact(c, false, contactsDir), personSlugFromContact(c, true, contactsDir)]) {
if (slug && await ownerOf(`${slug}.md`) === c.resourceName) {
await deletePageByRelPath(deps, `${slug}.md`, summary);
}
@@ -74,23 +76,25 @@ export async function sweepContacts(
}
continue;
}
- const baseSlug = personSlugFromContact(c);
+ const baseSlug = personSlugFromContact(c, false, contactsDir);
if (!baseSlug) continue;
const baseOwner = await ownerOf(`${baseSlug}.md`);
const collides = baseOwner !== null && baseOwner !== 'hand-authored' && baseOwner !== c.resourceName;
- const rendered = renderPersonPage(c, collides);
+ const rendered = renderPersonPage(c, collides, contactsDir);
if (!rendered) continue;
const owner = await ownerOf(rendered.relPath);
if (owner === 'hand-authored') {
deps.log(`[google] skipping hand-authored ${rendered.relPath}`);
continue;
}
- // Rename: this contact previously rendered elsewhere — remove the page it
- // owned there, or the old slug lives on as a stale orphan.
+ // Staged rename: this contact previously rendered elsewhere (a rename, or
+ // a changed contacts directory). The new page lands first, then the page
+ // it owned at the old path is retired, so a sweep that dies in between
+ // leaves the contact with a page rather than none.
+ await importRendered(deps, rendered.relPath, rendered.markdown, activePack, summary, countedSlugs);
if (existingPath && existingPath !== rendered.relPath && await ownerOf(existingPath) === c.resourceName) {
await deletePageByRelPath(deps, existingPath, summary);
}
- await importRendered(deps, rendered.relPath, rendered.markdown, activePack, summary, countedSlugs);
deps.tick(`contact ${c.resourceName}`);
}
// Cursor commits only after the whole sweep succeeded.
@@ -106,7 +110,7 @@ async function contactPageRelPathByContactId(
try {
const rows = await deps.engine.executeRaw<{ source_path: string | null }>(
`SELECT source_path FROM pages
- WHERE source_id = $1 AND deleted_at IS NULL AND slug LIKE 'people/%'
+ WHERE source_id = $1 AND deleted_at IS NULL
AND frontmatter->>'google_contact_id' = $2
LIMIT 1`,
[deps.sourceId, resourceName],
diff --git a/src/core/google/source-config.ts b/src/core/google/source-config.ts
index 9e14ebf2eb..6298f4ade8 100644
--- a/src/core/google/source-config.ts
+++ b/src/core/google/source-config.ts
@@ -1,5 +1,5 @@
/** Parse a Google connector source's `sources.config`. Dependency-light so migrations and the connector identity can import it. */
-import { ALL_GOOGLE_SERVICES, DEFAULT_CALENDAR_ID, type GoogleService, type GoogleSourceConfig } from './types.ts';
+import { ALL_GOOGLE_SERVICES, DEFAULT_CALENDAR_ID, DEFAULT_CONTACTS_DIR, type GoogleService, type GoogleSourceConfig } from './types.ts';
import { CALENDAR_FUTURE_DAYS_MAX } from './calendar-window.ts';
import { parseExcludeLabelTokens } from './loops-exclusion.ts';
@@ -34,6 +34,7 @@ export function parseGoogleSourceConfig(
typeof config.g_calendar_id === 'string' && config.g_calendar_id.trim().length > 0
? config.g_calendar_id.trim()
: DEFAULT_CALENDAR_ID;
+ const contactsDir = parseContactsDir(config.g_contacts_dir) ?? DEFAULT_CONTACTS_DIR;
const dir =
typeof config.g_dir === 'string' && config.g_dir.length > 0 ? config.g_dir : fallbackDir;
const access =
@@ -45,6 +46,7 @@ export function parseGoogleSourceConfig(
...(futureDays !== undefined ? { futureDays } : {}),
...(loopsExcludeLabels.length > 0 ? { loopsExcludeLabels } : {}),
calendarId,
+ contactsDir,
dir,
access,
...(typeof config.g_token_command === 'string' && config.g_token_command.trim()
@@ -56,15 +58,27 @@ export function parseGoogleSourceConfig(
};
}
+/**
+ * A contacts directory as the user wrote it, normalized (`/contacts/` →
+ * `contacts`), or null when it is not a safe relative path: one or more
+ * lower-case segments of `[a-z0-9_-]`, no dot segments, nothing hidden.
+ */
+export function parseContactsDir(raw: unknown): string | null {
+ if (typeof raw !== 'string') return null;
+ const dir = raw.trim().replace(/^\/+|\/+$/g, '');
+ return /^[a-z0-9][a-z0-9_-]*(\/[a-z0-9][a-z0-9_-]*)*$/.test(dir) ? dir : null;
+}
+
/**
* The per-source tuning keys `sources add` writes, each only when set so an
* existing source's config keeps its exact shape (`DEFAULT_CALENDAR_ID` and
* `CALENDAR_HORIZON_DAYS` stay parse-time fallbacks): `g_calendar_id`
- * (#5296), `g_future_days` (#5442), `g_loops_exclude_labels` (#5445).
+ * (#5296), `g_contacts_dir` (#4845), `g_future_days` (#5442), `g_loops_exclude_labels` (#5445).
*/
-export function googleTuningConfig(google: { calendarId?: string; futureDays?: number; loopsExcludeLabels?: string[] }): Record<string, unknown> {
+export function googleTuningConfig(google: { calendarId?: string; contactsDir?: string; futureDays?: number; loopsExcludeLabels?: string[] }): Record<string, unknown> {
return {
...(google.calendarId && google.calendarId !== DEFAULT_CALENDAR_ID ? { g_calendar_id: google.calendarId } : {}),
+ ...(google.contactsDir && google.contactsDir !== DEFAULT_CONTACTS_DIR ? { g_contacts_dir: google.contactsDir } : {}),
...(google.futureDays !== undefined ? { g_future_days: google.futureDays } : {}),
...(google.loopsExcludeLabels && google.loopsExcludeLabels.length > 0 ? { g_loops_exclude_labels: google.loopsExcludeLabels.join(',') } : {}),
};
diff --git a/src/core/google/types.ts b/src/core/google/types.ts
index 49f519c2a7..359a0f6e03 100644
--- a/src/core/google/types.ts
+++ b/src/core/google/types.ts
@@ -11,6 +11,8 @@ export type GoogleService = 'gmail' | 'calendar' | 'contacts';
export const ALL_GOOGLE_SERVICES: readonly GoogleService[] = ['gmail', 'calendar', 'contacts'];
/** The account's primary calendar — the Calendar API's own alias, and the default a google source sweeps. */
+/** Where a Google source renders its contact pages unless `g_contacts_dir` says otherwise. */
+export const DEFAULT_CONTACTS_DIR = 'people';
export const DEFAULT_CALENDAR_ID = 'primary';
export interface GoogleSourceConfig {
@@ -39,6 +41,14 @@ export interface GoogleSourceConfig {
* source so each keeps its own sync token — point a second source at a
* secondary calendar id to ingest it too. */
calendarId: string;
+ /**
+ * Directory (relative to `dir`) the contact pages render under
+ * (`g_contacts_dir`, default DEFAULT_CONTACTS_DIR = `people`; #4845). A brain
+ * that maintains its own `people/` pages points its Google source at
+ * `contacts` so the two namespaces never collide. Contact pages are found
+ * by `google_contact_id`, not by directory, so changing it moves them.
+ */
+ contactsDir: string;
/** Managed dir where pages are materialized. */
dir: string;
/**
diff --git a/src/core/persistence/connector-identity.ts b/src/core/persistence/connector-identity.ts
index 5b04cdbefa..f4bc01e15c 100644
--- a/src/core/persistence/connector-identity.ts
+++ b/src/core/persistence/connector-identity.ts
@@ -36,7 +36,7 @@ const underAuto = (config: GitHubSourceConfig): LeafClass => config.scope === 'a
*/
export const CONNECTOR_LEAF_RULES: { google: Record<string, LeafClass>; github: Record<string, Rule> } = {
google: {
- account: 'identity', services: 'identity', historyDays: 'identity', futureDays: 'identity', calendarId: 'identity', dir: 'identity',
+ account: 'identity', services: 'identity', historyDays: 'identity', futureDays: 'identity', calendarId: 'identity', contactsDir: 'identity', dir: 'identity',
access: 'excluded', tokenCommand: 'excluded', tokenEnv: 'excluded', loopsExcludeLabels: 'excluded',
},
github: {
diff --git a/src/core/sources-ops.ts b/src/core/sources-ops.ts
index 49807cae8f..802faf502d 100644
--- a/src/core/sources-ops.ts
+++ b/src/core/sources-ops.ts
@@ -196,6 +196,8 @@ export interface AddSourceOpts {
historyDays: number;
/** Calendar swept by this source (default DEFAULT_CALENDAR_ID). */
calendarId?: string;
+ /** #4845: directory under `dir` for contact pages (`g_contacts_dir`; default `people`). */
+ contactsDir?: string;
/** #5442: days ahead the calendar sweep covers (`g_future_days`; default CALENDAR_HORIZON_DAYS when absent). */
futureDays?: number;
/** #5445: Gmail label names/ids whose threads never enter loop extraction (`g_loops_exclude_labels`). */
diff --git a/test/by-mention.test.ts b/test/by-mention.test.ts
index 2f14023f03..d1826073d1 100644
--- a/test/by-mention.test.ts
+++ b/test/by-mention.test.ts
@@ -293,6 +293,36 @@ describe('findMentionedEntities — pure cases', () => {
]);
});
+ // #6158 / #4845: a connector renders its contacts as near-empty person pages in its own source. With
+ // cross_source on, a mention in that source binds to the canonical twin elsewhere, not the stub; with it
+ // off the own-source posture is unchanged; two foreign twins (no same-slug one) keep the stub (honest tie).
+ test('17f. a connector contact stub yields to the one canonical twin under allowCrossSource only', () => {
+ const g = gazetteerFromEntries([
+ { slug: 'people/dana-example', source_id: 'gmail-a', title: 'Dana Example', connector_stub: true },
+ { slug: 'people/dana-example', source_id: 'workspace', title: 'Dana Example' },
+ ]);
+ const opts = { fromSlug: 'emails/2026/08/thread-1', fromSourceId: 'gmail-a' };
+ expect(findMentionedEntities('Call with Dana Example.', g, opts)).toEqual([expect.objectContaining({ slug: 'people/dana-example', source_id: 'gmail-a' })]);
+ expect(findMentionedEntities('Call with Dana Example.', g, { ...opts, allowCrossSource: true }))
+ .toEqual([expect.objectContaining({ slug: 'people/dana-example', source_id: 'workspace' })]);
+ const tie = gazetteerFromEntries([
+ { slug: 'people/dana-example', source_id: 'gmail-a', title: 'Dana Example', connector_stub: true },
+ { slug: 'people/dana-e', source_id: 'workspace', title: 'Dana Example' },
+ { slug: 'people/dana-example-2', source_id: 'notes', title: 'Dana Example' },
+ ]);
+ expect(findMentionedEntities('Call with Dana Example.', tie, { ...opts, allowCrossSource: true }))
+ .toEqual([expect.objectContaining({ slug: 'people/dana-example', source_id: 'gmail-a' })]);
+ // A third source's page mentioning the name binds to the canonical twin, not the stub the bucket sorts first.
+ expect(findMentionedEntities('Call with Dana Example.', g, { fromSlug: 'notes/x', fromSourceId: 'notes', allowCrossSource: true }))
+ .toEqual([expect.objectContaining({ slug: 'people/dana-example', source_id: 'workspace' })]);
+ const stubOnly = gazetteerFromEntries([
+ { slug: 'people/dana-example', source_id: 'gmail-a', title: 'Dana Example', connector_stub: true },
+ { slug: 'people/dana-example', source_id: 'gmail-b', title: 'Dana Example', connector_stub: true },
+ ]);
+ expect(findMentionedEntities('Call with Dana Example.', stubOnly, { ...opts, allowCrossSource: true }))
+ .toEqual([expect.objectContaining({ slug: 'people/dana-example', source_id: 'gmail-a' })]);
+ });
+
test('17e. allowCrossSource — first-mention dedup keys on (source_id, slug), not bare slug', () => {
const g = gazetteerFromEntries([
{ slug: 'entities/shared', source_id: 'team-b', title: 'Beta Entity' },
@@ -711,6 +741,17 @@ describe('buildGazetteer — engine integration', () => {
expect(g.get('apple')![0]!.slug).toBe('companies/apple');
});
+ test('#6158: a page carrying google_contact_id builds a connector_stub entry; a hand-written page does not', async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('gmail-a', 'gmail-a', '{"kind":"google"}'::jsonb) ON CONFLICT (id) DO NOTHING`);
+ await engine.putPage('people/dana-example', { type: 'person', title: 'Dana Example', compiled_truth: 'Profile.', timeline: '', frontmatter: {} });
+ await engine.putPage('people/dana-example', { type: 'person', title: 'Dana Example', compiled_truth: 'Contact: [email protected].', timeline: '',
+ frontmatter: { google_contact_id: 'people/c1' } }, { sourceId: 'gmail-a' });
+ const g = await buildGazetteer(engine);
+ const bucket = g.get('dana')!.filter((e) => e.origin === 'title');
+ expect(bucket.find((e) => e.source_id === 'gmail-a')?.connector_stub).toBe(true);
+ expect(bucket.find((e) => e.source_id === 'default')?.connector_stub).toBeUndefined();
+ });
+
test('alias entries (v0.46.15, #3801): page_aliases become gazetteer entries', async () => {
await engine.putPage('people/saoirse-x', {
type: 'person', title: 'Saoirse Example', compiled_truth: 'b', timeline: '', frontmatter: {},
diff --git a/test/google-render.test.ts b/test/google-render.test.ts
index a377b37696..9936132256 100644
--- a/test/google-render.test.ts
+++ b/test/google-render.test.ts
@@ -462,6 +462,13 @@ describe('personSlugFromContact', () => {
test('null when neither name nor email', () => {
expect(personSlugFromContact(contact({ displayName: null, emails: [] }))).toBeNull();
});
+
+ test('#4845: the contacts directory is a parameter, default people/', () => {
+ expect(personSlugFromContact(contact(), false, 'contacts')).toBe('contacts/alice-example');
+ expect(personSlugFromContact(contact(), true, 'google/contacts')).toMatch(/^google\/contacts\/alice-example-[0-9a-f]{8}$/);
+ expect(renderPersonPage(contact(), false, 'contacts')?.relPath).toBe('contacts/alice-example.md');
+ expect(renderPersonPage(contact())?.relPath).toBe('people/alice-example.md');
+ });
});
describe('renderPersonPage', () => {
diff --git a/test/google-source-reconcile.test.ts b/test/google-source-reconcile.test.ts
index 22c5395410..3839740391 100644
--- a/test/google-source-reconcile.test.ts
+++ b/test/google-source-reconcile.test.ts
@@ -865,6 +865,40 @@ describe('syncToken 410 recovery', () => {
}
});
+ test('contacts (#4845): g_contacts_dir moves contact pages; a page the contact owned under the old dir is retired by contact id', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-ppldir-'));
+ const fx = emptyFx();
+ const vault = makeVault();
+ fx.contacts = [{
+ resourceName: 'people/c000000001',
+ names: [{ displayName: 'Alice Example', metadata: { primary: true } }],
+ emailAddresses: [{ value: '[email protected]' }],
+ }];
+ const slugs = async () => (await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE source_id = 'gsrc' AND deleted_at IS NULL AND type = 'person' ORDER BY slug`)).map((r) => r.slug);
+ try {
+ await insertGoogleSource(dir);
+ await withHome(async () => {
+ await sweep(dir, fx, vault, {}, 'contacts');
+ expect(await slugs()).toEqual(['people/alice-example']);
+ // The same source now renders contacts under contacts/: the old page goes, the new one lands, one page per contact.
+ const moved = await sweep(dir, fx, vault, { full: true }, 'contacts', { cfg: { g_contacts_dir: 'contacts' } });
+ expect(moved.added).toBe(1);
+ expect(moved.deleted).toBe(1);
+ expect(await slugs()).toEqual(['contacts/alice-example']);
+ expect(existsSync(join(dir, 'people/alice-example.md'))).toBe(false);
+ expect(existsSync(join(dir, 'contacts/alice-example.md'))).toBe(true);
+ // A deletion tombstone (resourceName only) still finds the page under the new dir by contact id.
+ fx.contactsDelta = [{ resourceName: 'people/c000000001', metadata: { deleted: true } }];
+ const gone = await sweep(dir, fx, vault, {}, 'contacts', { cfg: { g_contacts_dir: 'contacts' } });
+ expect(gone.deleted).toBe(1);
+ expect(await slugs()).toEqual([]);
+ });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
test('contacts: HTTP 400 expiry recovers without restarting Gmail or losing the contact', async () => {
const dir = mkdtempSync(join(tmpdir(), 'gsrc-ppl400-'));
const fx = emptyFx();
diff --git a/test/junk-entity-guards.test.ts b/test/junk-entity-guards.test.ts
index 12325056f3..1a3ff0a4f1 100644
--- a/test/junk-entity-guards.test.ts
+++ b/test/junk-entity-guards.test.ts
@@ -336,9 +336,24 @@ describe('junk_entity_hubs connector contact pages (#6158)', () => {
expect(check.message).not.toContain('generic-token');
expect(check.message).not.toContain('junk_hub_exempt');
expect(check.message).toContain('people/alice-example [google-example]');
- expect((check as { fix_unavailable_reason?: string }).fix_unavailable_reason).toBe('operator_judgement');
+ // W14 P4.5: real remedies instead of "open policy question": cross_source makes the stub yield to its twin.
+ expect(check.message).not.toContain('open policy question');
+ expect(check.message).toContain('link_resolution.cross_source true');
+ expect(check.message).toContain('--contacts-dir');
+ expect((check as { fix_unavailable_reason?: string }).fix_unavailable_reason).toBeUndefined();
+ expect((check as { fix?: { argv: string[] } }).fix?.argv).toEqual(['gbrain', 'config', 'set', 'link_resolution.cross_source', 'true']);
const details = check.details as { hubs: unknown[]; connector_twins: Array<Record<string, unknown>> };
expect(details.hubs).toEqual([]);
- expect(details.connector_twins).toEqual([expect.objectContaining({ slug: 'people/alice-example', source_id: 'google-example', canonical_twin: 'people/alice-example' })]);
+ expect(details.connector_twins).toEqual([expect.objectContaining({ slug: 'people/alice-example', source_id: 'google-example',
+ canonical_twin: 'people/alice-example', canonical_twin_source: 'default' })]);
+ // With cross_source already on, the next step is the mention pass itself.
+ await engine.setConfig('link_resolution.cross_source', 'true');
+ try {
+ const on = await checkJunkEntityHubs(engine, { edgeThreshold: 3, maxChunks: 2 });
+ expect((on as { fix?: { argv: string[] } }).fix?.argv).toEqual(['gbrain', 'extract', '--stale']);
+ expect(on.message).toContain('extract --stale');
+ } finally {
+ await engine.setConfig('link_resolution.cross_source', 'false');
+ }
});
});
diff --git a/test/loops-exclusion.test.ts b/test/loops-exclusion.test.ts
index 2c6bdcca5a..c4f76bcb77 100644
--- a/test/loops-exclusion.test.ts
+++ b/test/loops-exclusion.test.ts
@@ -100,6 +100,16 @@ describe('#5445 resolution', () => {
expect(pageLabelIds({})).toEqual([]);
});
+ test('#4845: g_contacts_dir parses onto the source config, defaults to people, and refuses an escaping path', () => {
+ const base = { kind: 'google', g_account: '[email protected]', g_services: 'contacts', g_history_days: 90, g_dir: '/tmp/x' };
+ expect(parseGoogleSourceConfig(base, '/tmp/x').contactsDir).toBe('people');
+ expect(parseGoogleSourceConfig({ ...base, g_contacts_dir: ' /contacts/ ' }, '/tmp/x').contactsDir).toBe('contacts');
+ expect(parseGoogleSourceConfig({ ...base, g_contacts_dir: 'google/contacts' }, '/tmp/x').contactsDir).toBe('google/contacts');
+ for (const bad of ['../people', 'a/../b', '', ' ', 'People Dir', '.hidden']) {
+ expect(parseGoogleSourceConfig({ ...base, g_contacts_dir: bad }, '/tmp/x').contactsDir).toBe('people');
+ }
+ });
+
test('g_loops_exclude_labels parses onto the source config and is absent when unset', () => {
const base = { kind: 'google', g_account: '[email protected]', g_services: 'gmail', g_history_days: 90, g_dir: '/tmp/x' };
expect(parseGoogleSourceConfig(base, '/tmp/x').loopsExcludeLabels).toBeUndefined();
diff --git a/test/persistence-source-cli.test.ts b/test/persistence-source-cli.test.ts
index 1915e55dbb..578099aa5d 100644
--- a/test/persistence-source-cli.test.ts
+++ b/test/persistence-source-cli.test.ts
@@ -40,8 +40,10 @@ describe('source lifecycle CLI', () => {
google: { tokenEnv: 'EXAMPLE_TOKEN', access: 'env', services: ['calendar'], dir: process.cwd() } } });
// #5442 / #5445: the per-source calendar horizon and loop exclusion labels ride the same add.
const tuned = parseSourceLifecycleArgs(['add', 'example', '--kind', 'google', '--account', '[email protected]',
- '--future-days', '365', '--loops-exclude-labels', 'Newsletters, Label_7', '--dir', '.'], id);
- expect(tuned.params).toMatchObject({ options: { google: { futureDays: 365, loopsExcludeLabels: ['Newsletters', 'Label_7'] } } });
+ '--future-days', '365', '--loops-exclude-labels', 'Newsletters, Label_7', '--contacts-dir', '/contacts/', '--dir', '.'], id);
+ expect(tuned.params).toMatchObject({ options: { google: { futureDays: 365, loopsExcludeLabels: ['Newsletters', 'Label_7'], contactsDir: 'contacts' } } });
+ expect(google.params).not.toHaveProperty('options.google.contactsDir');
+ expect(() => parseSourceLifecycleArgs(['add', 'example', '--kind', 'google', '--account', '[email protected]', '--contacts-dir', '../people'])).toThrow('contacts-dir');
expect(google.params).not.toHaveProperty('options.google.futureDays');
expect(() => parseSourceLifecycleArgs(['add', 'example', '--kind', 'google', '--account', '[email protected]', '--future-days', '0'])).toThrow('positive integer');
expect(() => parseSourceLifecycleArgs(['add', 'example', '--kind', 'google', '--account', '[email protected]', '--future-days', '4000'])).toThrow('3650');