Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(links): skip invalid mention targets before locking instead of failing the links effect (#7008)
garrytan570527d29a8b
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex f50390ecd1..a2c9feda4e 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -56,7 +56,7 @@ prompt or response text).|---|---|| Trusted local `put_page` / capture | Extracts supported page references without an LLM when auto-linking is enabled. || MCP `put_page` / capture / `edit_page`, including stdio | Saves body references as text; no inline graph extraction. The receipt reports `auto_links.skipped: remote`. |-| Post-commit `links` effect of an MCP page write | Adds untyped `mentions` edges (`link_source: mcp-remote-mention`) for the body's markdown links, `[[wikilinks]]` and page-path mentions whose target already exists in the same source, is not deleted, is visible to the writer and is inside its slug grant. No typed, frontmatter, timeline or cross-source edges and no new pages. The receipt reports `auto_links.mention_links: queued`; `get_write_request` lists the effect with `added`/`removed` counts. `gbrain config set mcp.remote_auto_links off` (or `auto_link off`) disables it. |+| Post-commit `links` effect of an MCP page write | Adds untyped `mentions` edges (`link_source: mcp-remote-mention`) for the body's markdown links, `[[wikilinks]]` and page-path mentions whose target already exists in the same source, is not deleted, is visible to the writer and is inside its slug grant. No typed, frontmatter, timeline or cross-source edges and no new pages. The receipt reports `auto_links.mention_links: queued`; `get_write_request` lists the effect with `added`/`removed` counts, plus `invalid_targets` (reason `invalid_slug`) for any target that is not a valid slug (`[[../x]]`, a backslash, an encoded separator): those are skipped and the page's other edges still land (#7008). `gbrain config set mcp.remote_auto_links off` (or `auto_link off`) disables it. || Stdio `gbrain serve` | Has bounded, best-effort startup and idle maintenance sweeps, unless disabled. This is eventual maintenance, not a guarantee that a remote write immediately has edges. || `gbrain serve --http` | Does not self-sweep. The host must run maintenance explicitly. |diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex 287aa66278..f52b7576be 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -355,17 +355,21 @@ export async function failEffect(engine: SqlEngine, effect: PersistenceEffect, r}/** Only public kind/state/reason, aggregated so withdrawal page counts cannot leak. */-export async function publicEffectsForRequest(engine: SqlEngine, requestId: string): Promise<Array<{ kind: EffectKind; state: string; reason?: string; push?: string; added?: number; removed?: number }>> {+export async function publicEffectsForRequest(engine: SqlEngine, requestId: string): Promise<Array<{ kind: EffectKind; state: string; reason?: string; push?: string; added?: number; removed?: number;+ invalid_targets?: Array<{ slug: string; reason: 'invalid_slug' }> }>> {const rows = await engine.executeRaw<{ kind: EffectKind; state: string; error_code: string | null; recovering: boolean; outcome: Record<string, unknown> | null }>('SELECT kind,state,error_code,outcome,recovery IS NOT NULL AS recovering FROM persistence_effects WHERE request_id=$1::uuid ORDER BY kind', [requestId]);return rows.filter(row => ['git', 'embedding', 'withdrawal-mirror', 'facts-backstop', 'links'].includes(row.kind)).map(row => {const reason = row.error_code ?? row.outcome?.reason;const push = row.outcome?.push;+ const invalid = Array.isArray(row.outcome?.skipped_targets) ? (row.outcome.skipped_targets as Array<{ slug: string; reason: string }>)+ .filter(target => target.reason === 'invalid_slug').map(target => ({ slug: target.slug, reason: 'invalid_slug' as const })) : [];return { kind: row.kind, state: row.recovering ? 'recovering' : row.outcome?.git === 'skipped' || row.outcome?.facts === 'skipped' || row.outcome?.embedding === 'skipped' || row.outcome?.links === 'skipped' ? 'skipped': row.outcome?.facts === 'queued' ? 'dispatched' : row.state,...(typeof reason === 'string' && /^[a-z_]{1,80}$/.test(reason) ? { reason } : {}),...(row.kind === 'git' && (push === 'committed' || push === 'skipped') ? { push } : {}),...(row.kind === 'links' && row.outcome?.links === 'committed' ? { added: Number(row.outcome.added), removed: Number(row.outcome.removed) } : {}),+ ...(invalid.length ? { invalid_targets: invalid } : {}),};});}diff --git a/src/core/persistence/effect-links.ts b/src/core/persistence/effect-links.tsindex b402f14559..ab0baf199a 100644--- a/src/core/persistence/effect-links.ts+++ b/src/core/persistence/effect-links.ts@@ -13,6 +13,7 @@ import type { SqlEngine, WriteAuthority, WriteRequest } from './model.ts';import { excludesPrivateWrites } from './page-visibility.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';import { extractSegmentedPageLinks } from '../page-body/segment-links.ts';+import { validateSlug } from '../utils.ts';import { isRemoteWantedPagesEnabled, replaceWantedLinks } from '../wanted-links.ts';/** `mcp.remote_auto_links`: unset is on; false/0/no/off (any case) turns the remote `links` effect off. */@@ -21,7 +22,7 @@ export async function isRemoteAutoLinksEnabled(engine: Pick<BrainEngine, 'getConreturn value == null || !['false', '0', 'no', 'off'].includes(value.trim().toLowerCase());}-export type SkippedLinkTarget = { slug: string; reason: 'cross_source' | 'missing' | 'not_visible' | 'outside_grant' };+export type SkippedLinkTarget = { slug: string; reason: 'cross_source' | 'invalid_slug' | 'missing' | 'not_visible' | 'outside_grant' };/** At most this many skipped targets are recorded on one effect outcome. */const SKIPPED_TARGET_LIMIT = 50;@@ -30,6 +31,10 @@ const SKIPPED_TARGET_LIMIT = 50;* page-path mentions in compiled_truth only. No frontmatter, no timeline* section, no schema-pack verbs; every edge is stored as an untyped `mentions`.* A segmented page's compiled truth is read block by block (page-body/segment-links.ts).+ * #7008: a target validateSlug refuses (`../x`, a backslash, an encoded separator)+ * is skipped as invalid_slug here, before any page key is locked, so it never+ * fails the effect or costs the page its valid edges; control characters in the+ * recorded slug are escaped so the outcome stays storable.*/async function mentionTargets(engine: BrainEngine, snapshot: PageSnapshot, sourceId: string) {const { page } = snapshot;@@ -43,12 +48,19 @@ async function mentionTargets(engine: BrainEngine, snapshot: PageSnapshot, sourcconst skipped: SkippedLinkTarget[] = [];for (const candidate of candidates) {if (candidate.fromSlug || candidate.targetSlug === page.slug) continue;- if (candidate.targetSourceId && candidate.targetSourceId !== sourceId) skipped.push({ slug: candidate.targetSlug, reason: 'cross_source' });+ if (!validSlug(candidate.targetSlug)) {+ const slug = candidate.targetSlug.replace(/[\x00-\x1f\x7f-\x9f]/g, c => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);+ if (!skipped.some(target => target.slug === slug)) skipped.push({ slug, reason: 'invalid_slug' });+ } else if (candidate.targetSourceId && candidate.targetSourceId !== sourceId) skipped.push({ slug: candidate.targetSlug, reason: 'cross_source' });else if (!targets.has(candidate.targetSlug)) targets.set(candidate.targetSlug, candidate.context);}return { targets, skipped };}+function validSlug(slug: string): boolean {+ try { validateSlug(slug); return true; } catch { return false; }+}+/** The writer's slug confinement, stored and current, applied to link targets. */async function targetGrant(tx: SqlEngine, a: WriteAuthority): Promise<(slug: string) => boolean> {const checks: Array<(slug: string) => boolean> = [];diff --git a/test/e2e/s-7008-links-invalid-target-postgres.test.ts b/test/e2e/s-7008-links-invalid-target-postgres.test.tsnew file mode 100644index 0000000000..2ca39601c3--- /dev/null+++ b/test/e2e/s-7008-links-invalid-target-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../pathological/s-7008-links-invalid-target.test.ts'));diff --git a/test/pathological/s-7008-links-invalid-target.test.ts b/test/pathological/s-7008-links-invalid-target.test.tsnew file mode 100644index 0000000000..5eac2f552b--- /dev/null+++ b/test/pathological/s-7008-links-invalid-target.test.ts@@ -0,0 +1,97 @@+/**+ * #7008 (GBRA-133): a remote put_page whose body mentions a target that is not+ * a valid slug (`[[../outside-example]]`, an encoded separator) queued a+ * `links` effect that threw in validateSlug inside lockPageKeys on every+ * attempt. On its own the page lost every mention edge (the effect was counted+ * to PARK_AFTER_FAILURES and skipped as effect_unavailable, valid targets+ * included); when most effects of a pass carried one, the pass looked systemic+ * and every effect retried as item_failures_systemic forever.+ *+ * Protects: an invalid mention target is set aside before any lock, recorded+ * on the effect as skipped with reason invalid_slug and shown on the write+ * receipt's links effect; the page's valid targets are linked on the first+ * pass. A run-scoped failure on the same page still retries (never counted,+ * never skipped). PGLite always, Postgres when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { publicEffectsForRequest } from '../../src/core/persistence/effect-journal.ts';+import { listBlockingEffects } from '../../src/core/persistence/blocking-effects.ts';+import { PARK_AFTER_FAILURES } from '../../src/core/persistence/effect-model.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { failLocks, passes } from './effects-fixture.ts';+import { expectUnitNotAborted, managedBrain, pathologicalArms, runScopedErrors } from './harness.ts';++const TARGET = 'notes/target-example';+const PAGES = Array.from({ length: 6 }, (_, i) => `notes/m-${i + 1}`);+const BAD = 'notes/m-3';+const INVALID = ['../outside-example', 'notes/a%2fb-example'];+const note = (slug: string, body: string) => `---\ntype: note\ntitle: ${slug}\n---\n\n${body}\n`;+const withInvalid = `See [[${TARGET}]], [[${INVALID[0]}]] and [[${INVALID[1]}]].`;++type Row = { slug: string; request_id: string; state: string; error_code: string | null; outcome: Record<string, any> | null };+const linksEffects = (engine: BrainEngine) => engine.executeRaw<Row>(`SELECT r.slug,r.id::text AS request_id,e.state,e.error_code,e.outcome+ FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='links' AND r.slug LIKE 'notes/m-%' ORDER BY r.slug`);+const edges = (engine: BrainEngine, from: string) => engine.executeRaw<{ to_slug: string }>(`SELECT t.slug AS to_slug 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='default' AND f.slug=$1 AND l.link_source='mcp-remote-mention' ORDER BY t.slug`, [from]);++async function remoteWrites(engine: BrainEngine, ctx: OperationContext, bodies: Map<string, string>): Promise<void> {+ const remote = { remote: true as const, transport: 'http' as const, config: ctx.config, sourceId: 'default', logger: ctx.logger,+ auth: { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default' } };+ for (const [slug, body] of [[TARGET, 'The target.'] as const, ...bodies]) {+ const response = await dispatchToolCall(engine, 'put_page', { request_id: randomUUID(), slug, content: note(slug, body) }, remote);+ const payload = JSON.parse((response.content[0] as { text: string }).text) as Record<string, unknown>;+ expect({ slug, isError: response.isError === true, state: payload.state }).toEqual({ slug, isError: false, state: 'committed' });+ }+ // The test's passes are the only effect drainer from here on, so no effect is left running by the resident consumer.+ await disposePersistenceConsumer(engine);+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`#7008 links effect with an invalid mention target (${backend})`, () => {+ test('#7008 item: one page with invalid targets keeps its valid edge and records each invalid target as skipped', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await remoteWrites(engine, ctx, new Map(PAGES.map(slug => [slug, slug === BAD ? withInvalid : `See [[${TARGET}]].`])));+ await expectUnitNotAborted(() => passes(engine, ctx.config, PARK_AFTER_FAILURES + 1));+ const rows = await linksEffects(engine);+ expect(rows.map(row => ({ slug: row.slug, state: row.state, links: row.outcome?.links, added: row.outcome?.added })))+ .toEqual(PAGES.map(slug => ({ slug, state: 'committed', links: 'committed', added: 1 })));+ const bad = rows.find(row => row.slug === BAD)!;+ expect(bad.outcome!.skipped_targets).toEqual(INVALID.map(slug => ({ slug, reason: 'invalid_slug' })));+ expect(await edges(engine, BAD)).toEqual([{ to_slug: TARGET }]);+ expect((await publicEffectsForRequest(engine, bad.request_id)).find(effect => effect.kind === 'links')).toEqual({ kind: 'links', state: 'committed',+ added: 1, removed: 0, invalid_targets: INVALID.map(slug => ({ slug, reason: 'invalid_slug' })) });+ expect(await listBlockingEffects(engine)).toEqual([]);+ }, { databaseUrl });+ }, 180_000);++ test('#7008 systemic: every page of the pass carrying an invalid target links on the first pass instead of retrying as item_failures_systemic', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await remoteWrites(engine, ctx, new Map(PAGES.map(slug => [slug, withInvalid])));+ await expectUnitNotAborted(() => passes(engine, ctx.config, 1));+ for (const row of await linksEffects(engine)) {+ expect({ slug: row.slug, state: row.state, error_code: row.error_code, links: row.outcome?.links, added: row.outcome?.added })+ .toEqual({ slug: row.slug, state: 'committed', error_code: null, links: 'committed', added: 1 });+ }+ expect(await listBlockingEffects(engine)).toEqual([]);+ }, { databaseUrl });+ }, 180_000);++ for (const injected of runScopedErrors()) {+ test(`#7008 run: a run-scoped failure (${injected.name}) on a page with invalid targets is never counted and stays queued`, async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await remoteWrites(engine, ctx, new Map([[BAD, withInvalid]]));+ const restore = failLocks(engine, new Set([BAD]), injected.error);+ try { await expectUnitNotAborted(() => passes(engine, ctx.config, PARK_AFTER_FAILURES + 1)); } finally { restore(); }+ const [row] = await linksEffects(engine);+ expect({ state: row!.state, outcome: row!.outcome }).toEqual({ state: 'queued', outcome: null });+ await passes(engine, ctx.config, 1);+ expect((await linksEffects(engine))[0]!.outcome).toMatchObject({ links: 'committed', added: 1 });+ }, { databaseUrl });+ }, 180_000);+ }+ });+}