Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
remember: a folder-less entity names exactly one page or is refused with candidates; pending replies name their target (#7248)
garrytanea1858ae6c5d
diff --git a/docs/architecture/key-files/core-memory.md b/docs/architecture/key-files/core-memory.mdindex 3fb72b4c9f..e1f41f70f2 100644--- a/docs/architecture/key-files/core-memory.md+++ b/docs/architecture/key-files/core-memory.md@@ -52,7 +52,8 @@ notice). User guide: [core memory](../../guides/core-memory.md).scan, window detection, once-per-segment state); wired in the user-prompthook and OpenClaw `assemble()`.- `src/core/remember-batch.ts`: `remember` with `items[]` (all-or-none- validation, deterministic child request ids, per-item status).+ validation, deterministic child request ids, per-item status; #7248: an+ item still publishing is `pending` with its `target`, not `failed`).- `src/commands/core.ts` (`gbrain core`), `src/commands/doctor/checks/core-memory.ts`(`core_memory`), schema `src/core/core-memory-schema.ts` + migration v213.- Tests: `test/core-memory.test.ts`, `test/core-guard.test.ts`,diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex 231da5febb..0d18537d10 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -6,7 +6,7 @@- `src/core/serve-service.ts` — the persistent-service half of `mcp expose`, everything under `gbrainPath('serve')` (`serveDir`, `adminTokenPath`, `wrapperPath`, `receiptPath`, `serveLogPath`, `serveErrPath`) so `GBRAIN_HOME` is honored. `SERVE_LAUNCHD_LABEL = 'com.gbrain.serve'`, `SERVE_SYSTEMD_UNIT = 'gbrain-serve.service'`, `detectServiceTarget(signals)` → `'macos' | 'linux-systemd' | 'none'` (a working user bus is required for systemd; cloud sandboxes and ephemeral containers fall to `none`). `renderServeWrapper` produces the 0755 launcher that sources the shell profiles and `~/.gbrain/env`, prepends the Bun dir to `PATH`, reads the admin token from its file at run time into `GBRAIN_ADMIN_BOOTSTRAP_TOKEN` (the token is never written into the wrapper, plist or unit), resolves `gbrain` the way autopilot's wrapper does (baked installer path, `type -P gbrain` fallback) and `exec`s `serve --http --port N --public-url URL [--surface] [--enable-dcr]`. `resolveServeGbrainCommand({ which, execPath, argv1, metaUrl, fileExists })` picks the baked program: a `gbrain` on PATH wins; a COMPILED binary — `import.meta.url` (or the injected `metaUrl`) under `/$bunfs/`, or an `execPath` that is not the bun runtime while `argv[1]` is absent/virtual — is `[execPath]` whatever its basename (release assets are renamed); otherwise the `[bun, <cli.ts>]` dev form only when that `cli.ts` exists on disk, else `[execPath]` rather than a path that cannot run; `renderServeLaunchdPlist` (RunAtLoad, KeepAlive, ThrottleInterval 30, logs to `serve.log` / `serve.err`, local `escapeXml`) and `renderServeSystemdUnit` (After=network-online.target, Restart=always, RestartSec=10, start-limit window; systemd specifiers escaped — `%` → `%%` in `ExecStart` and both `append:` log paths, `$` → `$$` in `ExecStart`). `ensureAdminToken` (0700 dir, 0600 file created with `wx` semantics, 64 hex chars; reuse a file matching the exported `ADMIN_TOKEN_SHAPE` = `^[A-Za-z0-9_-]{32,}$` — the same regex `serve-http.ts`'s `resolveBootstrapToken` accepts, so the file and the env var can never disagree on what a valid token is — unlink and regenerate otherwise), `installServeService` (launchd: domain-explicit `launchctl bootout gui/<uid> <plist>` — failure ignored — then `launchctl bootstrap gui/<uid> <plist>`, both through the one `launchctl(run, uid, plist, { modern, legacy })` helper whose legacy `launchctl unload` / `load` fallback is used ONLY when the modern verb exits non-zero with stderr matching `/Unknown command|unrecognized|not found/i`, never on a genuine failure or a killed call, and which reports the `verb` whose result it returns; a bootstrap that fails with stderr matching `LAUNCHCTL_SETTLE_RE` (`Input/output error`, `already in progress`, `\b5\b`, `\b37\b` — launchd still unloading the previous job) is retried up to `LAUNCHCTL_SETTLE_RETRIES` (5) times, `LAUNCHCTL_SETTLE_MS` (1s) apart through the injectable `sleep` param (default `setTimeout`; `mcp-expose.ts` passes `d.sleep`), a success after retries is a note and an exhausted retry appends "(after N settle retries)" to `error`; systemd: `daemon-reload` → `enable` → `restart` so a regenerated wrapper takes effect; `loginctl enable-linger` best effort) / `uninstallServeService` (launchd: the same `bootout gui/<uid>` with the same fallback; a bootout that exits non-zero — or is killed — with stderr NOT matching `LAUNCHCTL_NOT_LOADED_RE` (`No such process|not loaded|Could not find|not find service`) pushes `launchctl <verb> failed: <describeFailure>` into `notes`, and the exported `launchdBootoutFailed(result)` recognizes that note so `mcp-expose.ts` can say the job may still be loaded) / `serveServiceState` (`launchctl print gui/<uid>/<label>` / `systemctl --user is-active`); all three take `uid?: number` defaulting to `process.getuid?.() ?? 501`, threaded from `mcp-expose.ts`. Every supervisor subprocess carries a timeout — 60s for `launchctl bootstrap/bootout` (and the legacy `load/unload`) and `systemctl --user enable/restart/disable`, 15s for `launchctl print`, `daemon-reload`, `is-active` and `loginctl enable-linger` — and a `status: null` (killed) result counts as a failure (`error` / note) or `unknown` state; a failed call is described by `describeFailure` (its stderr, else stdout, else `exit <status>`). `readExposeReceipt` / `writeExposeReceipt` (`expose.json`, 0600, version 1, no secrets): the reader is a structural shape guard, not just `version`/`port`/`public_url` — it also requires `mode` in `tailnet|funnel`, a `service` object with a string `wrapper_path`, a `target` in `macos|linux-systemd|none`, a string `state` and string-or-null `plist_path` / `unit_path`, a `tailscale` object whose `binary` / `dns_name` are string-or-null, and string `mcp_url` / `admin_url` / `admin_token_file`; anything less is null (absent), so `--status` / `--remove` never dereference a half-written receipt. The token, receipt, wrapper, plist and unit writers refuse (clear error) when the target path is a symlink (`lstatSync`) before any supervisor call runs. Uses `shellQuote` from `src/core/mcp-registration.ts`; every filesystem/exec effect is behind injectable deps.- `src/core/harness/verify.ts` — Randomized server-side memory verification with revision-conditional cleanup and retained mutation UUIDs, with separate transport, identity, authority, read, write/readback, delegation and cleanup verdicts. Lost mutation responses are reconciled before retry; server success never certifies native-harness activation or cross-conversation behavior.-- `src/core/persistence/memory-mutations.ts` + `memory-prepare.ts` — managed `remember`, `forget`, and `forget_fact`: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Embedding preparation records the stored model/dimension generation and publication compares it under transaction row locks, preserving unchanged runtime overrides while refusing intervening migrations; fact vectors retain their actual provider model. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work; the call then rebuilds the withdrawn pages' text projections before acknowledging, because a CLI process has no resident projection worker (a failed rebuild stays queued). `src/core/facts/single-prepare.ts` isolates provider preparation from the SQL-only semantic decision and propagates cooperative provider abort without degrading it into success. Preparation checkpoints prevent a late aborted result from reaching publication. Tests: `test/persistence-memory-mutations.test.ts` runs identical races on PGLite and PostgreSQL; `test/withdrawal-followup-writes.test.ts` covers writes after a forget whose effects stay queued. #5836: an omitted `entity` is inferred before admission (`inferRememberTarget`), and the inferred slug is used only when `planRememberTarget`'s checks pass as predicates (plus withdrawal, fence parse, no owner claim); otherwise the save is unattributed with `warnings` (`NO_ENTITY`/`ENTITY_LINK_FAILED`) + `hint`. The `entity_inferred` intent marker makes preparation dedup exact text only (never supersede) and notes the context; `test/remember-entity-inference.test.ts`. `remember.replaces` (caller-directed replacement): `decideReplacement` (`facts/single-prepare.ts`) replaces the cosine decision when the intent names a target; it is checked at submission (fail fast) and again in `validate` with the target row locked `FOR UPDATE`, so two replacements of one fact serialize and the second sees `target_superseded`. Refusals are `invalid_params` with code prefixes (`target_withdrawn`, `target_superseded` naming the chain head, `target_expired`, `replaces_entity_mismatch`, `replaces_cross_page`, `replaces_duplicate`); remote callers get `not_found` for private targets; equal text is a `duplicate` no-op. Every `superseded` outcome carries `superseded_fact_id` (plus `replaced_by_caller` for `replaces`). `forget` responses gain `similar_active` (`facts/similar-active.ts`) after commit and on replay, and `semantic_review: false` keeps the claim out of overnight review. Pinned by `test/remember-replaces.test.ts`. remember's write intent carries the transport-resolved `ctx.sessionId` (MCP `_meta.session_id`, clamped to 256 characters), and preparation stores it as the fact's `source_session`, so `recall({session_id})` finds remembered facts; identity only, never an authorization input (`test/remember-session.test.ts`).+- `src/core/persistence/memory-mutations.ts` + `memory-prepare.ts` — managed `remember`, `forget`, and `forget_fact`: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Embedding preparation records the stored model/dimension generation and publication compares it under transaction row locks, preserving unchanged runtime overrides while refusing intervening migrations; fact vectors retain their actual provider model. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work; the call then rebuilds the withdrawn pages' text projections before acknowledging, because a CLI process has no resident projection worker (a failed rebuild stays queued). `src/core/facts/single-prepare.ts` isolates provider preparation from the SQL-only semantic decision and propagates cooperative provider abort without degrading it into success. Preparation checkpoints prevent a late aborted result from reaching publication. Tests: `test/persistence-memory-mutations.test.ts` runs identical races on PGLite and PostgreSQL; `test/withdrawal-followup-writes.test.ts` covers writes after a forget whose effects stay queued. #5836: an omitted `entity` is inferred before admission (`inferRememberTarget`), and the inferred slug is used only when `planRememberTarget`'s checks pass as predicates (plus withdrawal, fence parse, no owner claim); otherwise the save is unattributed with `warnings` (`NO_ENTITY`/`ENTITY_LINK_FAILED`) + `hint`. The `entity_inferred` intent marker makes preparation dedup exact text only (never supersede) and notes the context; `test/remember-entity-inference.test.ts`. `remember.replaces` (caller-directed replacement): `decideReplacement` (`facts/single-prepare.ts`) replaces the cosine decision when the intent names a target; it is checked at submission (fail fast) and again in `validate` with the target row locked `FOR UPDATE`, so two replacements of one fact serialize and the second sees `target_superseded`. Refusals are `invalid_params` with code prefixes (`target_withdrawn`, `target_superseded` naming the chain head, `target_expired`, `replaces_entity_mismatch`, `replaces_cross_page`, `replaces_duplicate`); remote callers get `not_found` for private targets; equal text is a `duplicate` no-op. Every `superseded` outcome carries `superseded_fact_id` (plus `replaced_by_caller` for `replaces`). `forget` responses gain `similar_active` (`facts/similar-active.ts`) after commit and on replay, and `semantic_review: false` keeps the claim out of overnight review. Pinned by `test/remember-replaces.test.ts`. remember's write intent carries the transport-resolved `ctx.sessionId` (MCP `_meta.session_id`, clamped to 256 characters), and preparation stores it as the fact's `source_session`, so `recall({session_id})` finds remembered facts; identity only, never an authorization input (`test/remember-session.test.ts`). #7248: an explicit `entity` without a folder resolves through `resolveStrictEntityReference` (one readable entity page by exact slug, unique basename, alias or same name); a miss with near pages (`entityReferenceCandidates` in `entities/resolve.ts`) is refused `invalid_params` with `reason: entity_ambiguous | entity_unverified | entity_not_entity | entity_no_page` and the candidates, and a name nothing resembles keeps its slugified key. A pending or refused reply's `write_request.target` (`slug`, `entity_slug`) names where the fact goes, and `pendingWriteHint` repeats it (`test/remember-entity-target-7248.test.ts`).- `src/core/page-state/import-guard.ts` — imported canonical bytes publish only after source/page identity and knowledge-revision CAS, including unchanged-file and legacy hash-repair paths. Prepared same-hash imports compare full canonical metadata and additive tags, since captured timestamps are excluded from content hashes. Tests: `import-revision-concurrency.test.ts`.- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. An unchanged per-tick refresh writes nothing: the registry directory and records are chmodded only when their mode differs and the directory is fsynced only when a record changed (`root-registry-idle-chmod-5297.test.ts`). The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints; an update that changes only embedding, telemetry or write-attribution columns of facts/takes is a physical projection and passes without the coordinator. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 7e4053034e..80727d6ceb 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1046,6 +1046,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.330.0', text: '`gbrain entity <name>` now resolves one unambiguous name variant when no exact name matches (a nickname, an initial, a title in front, reversed order, a one-letter surname typo, a surname only one page has), across every source you can read, and says so in `card.match`; a variant two pages share is a miss with `ambiguous: true`. Cards list `possible_duplicates` (title-prefixed person pages, never merged), and a miss or a card with no backlinks or facts while mention coverage is incomplete lists the pages whose text names it (`text_mentions`). The human miss line is now just "No entity found."; timing and mention coverage print on their own lines. `gbrain config set entity.name_variants false` (or `variants: false`) keeps exact names only. Doctor adds `person_title_duplicates`, which lists such pairs with the merge to review and changes nothing.' },{ since: '0.60.330.0', text: '`gbrain recall <entity>` on a local brain now reads every slug the entity\'s facts may be saved under, as the recall operation already did (identity siblings, the title subject, and the bare basename when no other page claims it), so facts saved before the page existed show up. `gbrain recall "<name> <topic words>"` that matched nothing as one entity or text now recalls the leading or trailing name\'s facts with the topic matches first, with a note naming the entity. `recall --entity <x>` is accepted (never split or widened to a text match). With `GBRAIN_FAIL_ON_EMPTY=1`, a recall or entity lookup that matches nothing exits 12 (`no_results`); by default it still exits 0, and recall\'s list `--json` adds `status: "no_results"`.' },{ since: '0.60.330.0', text: 'A search for an identifier (an email, a URL, a phone number in any common format, a long number, a hex id or a code such as an invoice number) now puts the pages that contain it verbatim first (`exact_lookup: identifier`) before the ranked results; dates and ordinary words are unchanged.' },+ { since: '0.60.330.0', text: '`remember` with a folder-less `entity` (`alex-example`, `Alice`) now saves only when it names exactly one readable entity page (by slug, a unique basename, an alias or the same name). When it could mean several pages, only begins a page name, or only resembles pages, the call is refused `invalid_params` with `reason` `entity_ambiguous`, `entity_unverified`, `entity_not_entity` or `entity_no_page` and up to five candidate slugs, and nothing is saved; before, the fact was keyed under a bare slug no page carries. A name nothing resembles still saves under its slug, and a slug with a folder saves as before. A pending reply\'s `write_request.target` names the page and entity the fact goes to, and a `remember` batch reports an item still publishing as `pending`, not `failed` (#7248).' },// GBRA-150 (synced-but-not-searchable landing checks). `since` is restamped at the merge slot.{ since: '0.60.337.0', id: 'sync_status_blocked_means_source_stopped', text: '`gbrain sync status` now reads `blocked` only when the source cannot advance without a person or an operator, the meaning a sync run\'s drain outcome and a sync job\'s `blocked` progress already had. A file hold that waits on a person while the rest of the source keeps syncing now reads `synced` with the new reason `held_needs_human` (it read `blocked` before); `needs_human`, `next` and the hold rows are unchanged, so a client acting on `needs_human` sees no difference.' },{ since: '0.60.337.0', id: 'sources_resolve_path', text: 'New read-only `gbrain sources resolve-path <id> <path...> [--stdin] [--json]` (MCP `sources_resolve_path`, read scope, at most 200 paths) says what gbrain did with each file path of a source by its own rules: the slug sync gives it, whether it is skipped, held, not synced yet, deleted, or a live page, and whether search can find it (`searchable` true, `keyword` or false), with a `why` and a `fix`. Landing checks should call it instead of copying gbrain\'s path-to-slug rules. `gbrain sync status --detail` adds a `landing` block, and the new cheap doctor check `sync_landing_gaps` warns when pages a managed sync committed more than the freshness target ago still cannot be fully searched.' },diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.tsindex e9f729c6d7..a6bb9e484f 100644--- a/src/core/entities/resolve.ts+++ b/src/core/entities/resolve.ts@@ -556,6 +556,45 @@ export async function resolveStrictEntityReference(return { slug: null, miss: 'no_page' };}+/**+ * #7248: up to five readable live pages a reference could mean, sorted by+ * slug, for a refusal to name: the entity-directory basenames, organization+ * variants, alias hits and bare-name prefix expansions, else the nearest+ * entity pages by title or slug similarity that share the reference's first+ * name token. Never a slugified guess.+ */+export async function entityReferenceCandidates(+ engine: BrainEngine,+ source_id: string,+ raw: string,+ opts: { excludePrivate?: boolean } = {},+): Promise<string[]> {+ const trimmed = raw.trim();+ const token = slugify(trimmed);+ if (!token) return [];+ const privacy = opts.excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : '';+ const aliases = await aliasHitSlugs(engine, source_id, trimmed).catch(() => [] as string[]);+ const prefixed = (await findPrefixCandidates(engine, source_id, token)).map(c => c.slug);+ const named = await engine.executeRaw<{ slug: string }>(+ `SELECT p.slug FROM pages p+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND NOT ${retiredPageSql('p')} AND p.slug = ANY($2::text[]) ${privacy}+ ORDER BY p.slug LIMIT 5`,+ [source_id, [...new Set([...BASENAME_DIRS.map(dir => `${dir}/${token}`), ...orgDirVariants(trimmed), ...aliases, ...prefixed])]],+ );+ if (named.length) return named.map(r => r.slug);+ const near = await engine.executeRaw<{ slug: string; title: string; type: string | null }>(+ `SELECT p.slug, p.title, p.type FROM pages p+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND NOT ${retiredPageSql('p')} ${privacy}+ AND (lower(p.title) % $2 OR p.slug ILIKE '%' || $3 || '%')+ ORDER BY GREATEST(similarity(lower(p.title), $2), similarity(p.slug, $3)) DESC, p.slug ASC+ LIMIT 20`,+ [source_id, trimmed.toLowerCase(), token],+ ).catch(err => { if (isMissingTrigramError(err)) return []; throw err; });+ const lead = token.split('-')[0]!;+ const sharesLead = (r: { slug: string; title: string }) => slugify(r.title).split('-')[0] === lead || (r.slug.split('/').pop() ?? '').split('-')[0] === lead;+ return near.filter(r => isFactEntityPage(r.slug, r.type) && sharesLead(r)).slice(0, 5).map(r => r.slug).sort();+}+/*** v0.35.5 — phantom-canonical resolver. Variant of `resolveEntitySlug` that* SKIPS the exact-slug step at the top: a phantom slug like `'alice'` woulddiff --git a/src/core/persistence/health.ts b/src/core/persistence/health.tsindex 3a8d212352..6e9baf3cb4 100644--- a/src/core/persistence/health.ts+++ b/src/core/persistence/health.ts@@ -32,5 +32,6 @@ export function writeHealth(row: { state: WriteRequestState; created_at: Date |export function pendingWriteHint(receipt: WriteReceipt, operation?: string): string {const identity = `Use the same operation with the same arguments and request_id ${receipt.request_id}. Do not submit a new request_id for this write.`;if (receipt.diagnostic?.next_action === 'inspect_owner') return `${identity} Ask the operator to inspect gbrain sources writer status --probe --json on the selected brain's existing owner. Do not claim, transfer, activate, or remove locks. Poll no faster than ${receipt.retry_after_ms ?? 30_000} ms; if receipt helpers are unavailable, replay the same verb only after inspection.`;- return `${identity} Poll get_write_request after ${receipt.retry_after_ms ?? 1000} ms, or retry the same verb with identical arguments if receipt helpers are unavailable.${operation === 'put_page' ? ' Next time pass wait_ms (up to 30000) so the reply waits for the commit, and write more than 3 pages with put_pages.' : ''}`;+ const target = receipt.target?.slug ? ` Its fact goes to page ${receipt.target.slug}${receipt.target.entity_slug && receipt.target.entity_slug !== receipt.target.slug ? ` (entity ${receipt.target.entity_slug})` : ''}; get_write_request reports when it is saved there.` : '';+ return `${identity}${target} Poll get_write_request after ${receipt.retry_after_ms ?? 1000} ms, or retry the same verb with identical arguments if receipt helpers are unavailable.${operation === 'put_page' ? ' Next time pass wait_ms (up to 30000) so the reply waits for the commit, and write more than 3 pages with put_pages.' : ''}`;}diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex e19517ccf6..b5eda3e501 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -159,7 +159,7 @@ async function inferRememberTarget(ctx: OperationContext, sourceId: string, sourexport async function submitRememberMutation(ctx: OperationContext, params: Record<string, unknown>, waitMs?: number): Promise<Record<string, unknown>> {registerMutationPreparer('remember', prepareMemoryMutation);const sub = await submission(ctx, 'remember', params);- if (sub.prior) return throwIfHeld(writeResponse(await waitForWrite(ctx.engine, sub.prior, ctx.config, waitMs ?? ctx.writeWaitMs)));+ if (sub.prior) { const prior = sub.prior; const settled = await waitForWrite(ctx.engine, prior, ctx.config, waitMs ?? ctx.writeWaitMs); return throwIfHeld(withRememberTarget(prior, () => writeResponse(settled))); }const { p, sourceId, principal, callerIntent, requestId, clientRequestId } = sub;const [source] = await ctx.engine.executeRaw<RememberSource>("SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);@@ -167,8 +167,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Recoconst { parseTtlParam } = await import('../ops/facts.ts');const validUntil = parseTtlParam(p.ttl);const entity = typeof p.entity === 'string' && !isNullLikeEntity(p.entity) ? p.entity.trim() : null;- const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');- const resolved = entity ? await resolveEntitySlugWithSource(ctx.engine, sourceId, entity) : null;+ const resolved = entity ? await resolveRememberEntity(ctx, sourceId, entity) : null;const inference = entity === null ? await inferRememberTarget(ctx, sourceId, source, p) : null;const linked = inference && 'target' in inference ? inference : null;const entitySlug = linked?.target.slug ?? resolved?.slug ?? null;@@ -192,11 +191,62 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco...(linked ? { entity_inferred: linked.via } : {}), ...(inference && 'warning' in inference ? { entity_warning: inference.warning } : {}),session_id: ctx.sessionId ?? null },authority, worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });- const response = throwIfHeld(writeResponse(await waitForWrite(ctx.engine, row, ctx.config, waitMs ?? ctx.writeWaitMs)));+ const written = await waitForWrite(ctx.engine, row, ctx.config, waitMs ?? ctx.writeWaitMs);+ const response = throwIfHeld(withRememberTarget(row, () => writeResponse(written)));emitFenceNotice(ctx, response, row.slug);return response;}+/**+ * #7248: a pending (or refused) remember names the page its fact goes to and+ * the entity it is keyed under, so a caller can tell a misfile at once and+ * poll the right receipt.+ */+function withRememberTarget<T>(row: WriteRequest, reply: () => T): T {+ try { return reply(); } catch (error) {+ if (error instanceof OperationError && error.writeRequest) {+ const entity = (row.intent as { entity_slug?: unknown } | null)?.entity_slug;+ error.writeRequest.target = { slug: row.slug || null, entity_slug: typeof entity === 'string' ? entity : null };+ }+ throw error;+ }+}++/**+ * #7248: an explicit entity names its page. A reference with a folder keeps+ * the lenient resolution (an existing page, else that exact slug for a page+ * not written yet); a folder-less one must resolve to exactly one readable+ * entity page by identity evidence, else the call is refused with the pages+ * it could mean instead of keying the fact under a bare slug no page carries.+ * A name no page resembles keeps its slugified key, as a fact about an entity+ * with no page yet always has.+ */+async function resolveRememberEntity(ctx: OperationContext, sourceId: string, entity: string): Promise<{ slug: string }> {+ const { entityReferenceCandidates, resolveEntitySlugWithSource, resolveStrictEntityReference } = await import('../entities/resolve.ts');+ if (entity.includes('/')) return (await resolveEntitySlugWithSource(ctx.engine, sourceId, entity))!;+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);+ const strict = await resolveStrictEntityReference(ctx.engine, sourceId, entity, { sameName: true, excludePrivate });+ if (strict.slug !== null) return { slug: strict.slug };+ const candidates = await entityReferenceCandidates(ctx.engine, sourceId, entity, { excludePrivate });+ if (strict.miss === 'no_page' && !candidates.length) {+ const unnamed = await resolveEntitySlugWithSource(ctx.engine, sourceId, entity);+ if (unnamed?.source === 'fallback_slugify') return { slug: unnamed.slug };+ }+ const named = candidates.length ? ` It could mean: ${candidates.join(', ')}.` : '';+ const what = {+ ambiguous: `entity "${entity}" matches more than one page.`,+ unverified: `entity "${entity}" is not a page name; it only begins one.`,+ not_entity: `entity "${entity}" names a page that is not a person, company or other entity.`,+ no_page: `No page is named "${entity}".`,+ }[strict.miss];+ const example = candidates[0] ?? `people/${entity.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')}`;+ const error = verbError('invalid_params', `${what}${named} Nothing was saved.`,+ `Pass entity as the page slug with its folder, e.g. entity: "${example}". A slug with a folder saves under that page, even one not written yet; a name without one must match exactly one page.`);+ error.reason = `entity_${strict.miss}`;+ if (candidates.length) error.detail = `candidates: ${candidates.join(', ')}`;+ throw error;+}+interface WithdrawalTarget { id: number; entity_slug: string | null; source_markdown_slug: string | null; expired_at: Date | null; trust_tier?: string | null; }/**diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.tsindex cbfbea5f24..9d2c4d33b5 100644--- a/src/core/persistence/types.ts+++ b/src/core/persistence/types.ts@@ -56,6 +56,8 @@ export interface WriteReceipt {created_at?: string;updated_at?: string;diagnostic?: WriteDiagnostic;+ /** #7248: a remember's target page and the entity slug its fact is keyed under (set on its own replies, never read back from the journal). */+ target?: { slug: string | null; entity_slug: string | null };}/** Wire names stay separate from the engine's camelCase precondition. */@@ -149,6 +151,7 @@ export function publicWriteReceipt(receipt: WriteReceipt): WriteReceipt {} } : {}),...(receipt.created_at !== undefined ? { created_at: receipt.created_at } : {}),...(receipt.updated_at !== undefined ? { updated_at: receipt.updated_at } : {}),+ ...(receipt.target !== undefined ? { target: receipt.target } : {}),...(!isTerminalWriteState(receipt.state) && isWriteDiagnostic(receipt.diagnostic) ? { diagnostic: {age_ms: receipt.diagnostic.age_ms, assessment: receipt.diagnostic.assessment,reason: receipt.diagnostic.reason, next_action: receipt.diagnostic.next_action,diff --git a/src/core/remember-batch.ts b/src/core/remember-batch.tsindex e5ee465bf8..1448ebbc6e 100644--- a/src/core/remember-batch.ts+++ b/src/core/remember-batch.ts@@ -103,19 +103,28 @@ export async function runRememberBatch(ctx: OperationContext, p: Record<string,});} catch (e) {if (!(e instanceof OperationError)) throw e;+ // #7248: an accepted item still publishing is pending, not failed; resending it would save it twice.+ if (e.writeError === 'write_pending' && e.writeRequest) {+ results.push({ index, request_id: child, status: 'pending', state: e.writeRequest.state, retry_after_ms: e.writeRequest.retry_after_ms ?? null,+ ...(e.writeRequest.target ? { target: e.writeRequest.target } : {}) });+ continue;+ }results.push({ index, request_id: child, status: 'failed', error: { code: e.code, message: e.message, ...(e.detail ? { detail: e.detail } : {}), ...(e.suggestion ? { suggestion: e.suggestion } : {}), ...(e.withdrawn ? { withdrawn: e.withdrawn } : {}) } });}}const failed = results.filter(r => r.status === 'failed').length;+ const pending = results.filter(r => r.status === 'pending').length;return {protocol_version: 1,request_id: requestId,...(clientRequestId ? { client_request_id: clientRequestId } : {}),items: results,- saved: results.length - failed,+ saved: results.length - failed - pending,failed,+ ...(pending ? { pending } : {}),partial: failed > 0 && failed < results.length,...(hints.size ? { hints: [...hints] } : {}),- ...(failed > 0 ? { next: 'Fix each failed item as its error says, then send only the failed items in a new remember call with a new request_id; the saved items are already stored.' } : {}),+ ...(failed > 0 ? { next: 'Fix each failed item as its error says, then send only the failed items in a new remember call with a new request_id; the saved items are already stored.' }+ : pending > 0 ? { next: 'Pending items are accepted and still publishing: poll get_write_request with each pending item\'s request_id; do not send them again.' } : {}),};}diff --git a/test/remember-entity-target-7248.test.ts b/test/remember-entity-target-7248.test.tsnew file mode 100644index 0000000000..297865eac4--- /dev/null+++ b/test/remember-entity-target-7248.test.ts@@ -0,0 +1,121 @@+/**+ * #7248: remember with a folder-less entity resolves to exactly one readable+ * entity page or refuses with the pages it could mean (never a bare slug no+ * page carries), and a pending remember names its target page in the reply+ * and in a batch item. PGLite, synthetic names only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { operationsByName } from '../src/core/operations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';++let engine: PGLiteEngine;+const sourceId = 'remember-target-7248';+const context = (overrides: Partial<OperationContext> = {}): OperationContext => ({ engine, remote: false, sourceId,+ config: { engine: 'pglite' }, dryRun: false, logger: { info() {}, warn() {}, error() {} }, ...overrides } as OperationContext);+const remember = (params: Record<string, unknown>, ctx = context()) =>+ operationsByName.remember!.handler(ctx, { provenance: 'chat 2026-10-21', infer_entity: false, ...params }) as Promise<Record<string, any>>;+async function refusal(params: Record<string, unknown>, ctx = context()): Promise<OperationError> {+ try { await remember(params, ctx); } catch (e) { if (e instanceof OperationError) return e; throw e; }+ throw new Error('remember was not refused');+}+async function putEntity(slug: string, title: string, type: string, frontmatter: Record<string, unknown> = {}) {+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () =>+ tx.putPage(slug, { type, title, compiled_truth: '# ' + title, frontmatter }, { sourceId }), TEST_WRITE_ATTRIBUTION));+}+const factRows = (fact: string) => engine.executeRaw<{ entity_slug: string | null }>('SELECT entity_slug FROM facts WHERE source_id=$1 AND fact=$2', [sourceId, fact]);++beforeAll(async () => {+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ await registerLocalWriter(engine, 'cli'); await registerLocalWriter(engine, 'stdio');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await putEntity('people/alice-example', 'Alice Example', 'person');+ await putEntity('people/alex-example', 'Alex Example', 'person');+ await putEntity('companies/alex-example', 'Alex Example Inc', 'company');+ await putEntity('companies/acme-example-labs', 'Acme Example Labs', 'company');+ await putEntity('companies/acme-example-capital', 'Acme Example Capital', 'company');+}, 60_000);+afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ resetGateway();+});++describe('remember: a folder-less entity names exactly one page (#7248)', () => {+ test('a unique basename and an exact display name resolve to the page and land in its fence', async () => {+ const a = await remember({ fact: 'Alice Example prefers tea', entity: 'alice-example' });+ expect(a).toMatchObject({ status: 'inserted', entity_slug: 'people/alice-example' });+ const b = await remember({ fact: 'Alice Example runs on Sundays', entity: 'Alice Example' });+ expect(b.entity_slug).toBe('people/alice-example');+ const page = (await engine.readPageSnapshot('people/alice-example', { sourceId }))!.page.compiled_truth;+ expect(page).toContain('Alice Example prefers tea');+ expect(page).toContain('Alice Example runs on Sundays');+ });++ test('a basename two pages share is refused with both, and nothing is saved', async () => {+ const e = await refusal({ fact: 'Alex Example closed the round', entity: 'alex-example' });+ expect(e.code).toBe('invalid_params');+ expect(e.reason).toBe('entity_ambiguous');+ expect(e.message).toContain('companies/alex-example, people/alex-example');+ expect(e.detail).toBe('candidates: companies/alex-example, people/alex-example');+ expect(e.suggestion).toContain('entity: "companies/alex-example"');+ expect(await factRows('Alex Example closed the round')).toEqual([]);+ });++ test('a first name that only begins a page is refused with that page, not guessed', async () => {+ const e = await refusal({ fact: 'Alice prefers window seats', entity: 'alice' });+ expect(e.reason).toBe('entity_unverified');+ expect(e.detail).toBe('candidates: people/alice-example');+ expect(await factRows('Alice prefers window seats')).toEqual([]);+ });++ test('a name with near pages but none its own is refused with them; a name nothing resembles saves under its slug as before', async () => {+ const e = await refusal({ fact: 'Acme Example hired a CFO', entity: 'acme-example' });+ expect(e.reason).toBe('entity_no_page');+ expect(e.message).toContain('companies/acme-example-capital, companies/acme-example-labs');+ expect(await factRows('Acme Example hired a CFO')).toEqual([]);+ const bare = await remember({ fact: 'Bob Example moved to Lisbon', entity: 'bob-example' });+ expect(bare).toMatchObject({ status: 'inserted', entity_slug: 'bob-example' });+ const saved = await remember({ fact: 'Bob Example moved to Porto', entity: 'people/bob-example' });+ expect(saved).toMatchObject({ status: 'inserted', entity_slug: 'people/bob-example' });+ });++ test('a remote caller is never told about a private page it cannot read', async () => {+ await putEntity('people/carol-example', 'Carol Example', 'person', { visibility: 'private' });+ const e = await refusal({ fact: 'Carol Example likes jazz', entity: 'carol-example' }, context({ remote: true }));+ expect(e.reason).toBe('entity_no_page');+ expect(e.detail).toBeUndefined();+ expect(e.message).not.toContain('people/carol-example');+ expect(await factRows('Carol Example likes jazz')).toEqual([]);+ });+});++describe('remember: a pending reply names its target page (#7248)', () => {+ test('the write_request carries target and the hint names the page', async () => {+ let pending: OperationError | null = null;+ try { await remember({ fact: 'Alice Example joined the board', entity: 'alice-example' }, context({ writeWaitMs: 0 })); } catch (e) { if (e instanceof OperationError) pending = e; else throw e; }+ expect(pending?.writeError).toBe('write_pending');+ const wire = pending!.toJSON() as Record<string, any>;+ expect(wire.write_request.target).toEqual({ slug: 'people/alice-example', entity_slug: 'people/alice-example' });+ expect(wire.suggestion).toContain('Its fact goes to page people/alice-example');+ });++ test('a batch reports a pending item as pending with its target, not failed', async () => {+ const out = await remember({ items: [{ fact: 'Alice Example speaks Portuguese', entity: 'people/alice-example' }, { fact: 'Alex Example ships weekly', entity: 'alex-example' }] },+ context({ writeWaitMs: 0 }));+ const [first, second] = out.items as Array<Record<string, any>>;+ expect(first).toMatchObject({ status: 'pending', target: { slug: 'people/alice-example', entity_slug: 'people/alice-example' } });+ expect(second).toMatchObject({ status: 'failed', error: { code: 'invalid_params' } });+ expect(out).toMatchObject({ saved: 0, failed: 1, pending: 1, partial: true });+ });+});