Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(pages): a page an older version stored under a now-invalid slug can be deleted and restored, database-only (#6212)
time-attackf70ee662bc1b
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 88a701fcf7..bdc300427b 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -31,14 +31,14 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/health-memo.ts` — in-process memo for the `get_health` op only (O-ENG-13). An entry is reused when engine object, scope key (`all`, `scalar:<id>`, `set:<sorted unique ids>`, `empty` for an empty or no-sources grant; derived from the exact scope handed to `engine.getHealth`, so no scope reads another's entry), config generation (hash of the orphan exclusions, embedding column registry keys and schema pack setting), page clock (`page_generation_clock_seq.last_value` plus the `persistence_brain` id) and TTL all match. TTL: `GBRAIN_HEALTH_CACHE_TTL_MS`, else config `health.cache_ttl_ms`, else 30000 ms; 0 disables. The TTL bounds staleness from writes that do not touch `pages` (links, timeline rows, chunks). A failed clock/config read computes uncached. `engine.getHealth` stays uncached, so doctor, remediation, maintain, embedding migration and repair verification always read fresh numbers; `gbrain repair --apply` and `gbrain doctor --remediate` call `clearHealthMemo`. Pinned by `test/health-memo.test.ts`.-- `src/core/ops/context.ts` (source-id confinement helpers) — `assertSourceInCallerScope(ctx, id)` is the READ-scope confinement for an explicitly named source id (`sources_status`): untrusted callers may only name an id inside the `sourceScopeOpts` ladder. `assertSourceInCallerWriteScope(ctx, id)` is its WRITE-authority twin for destructive source ops (`sources_remove`): federation (`ctx.auth.allowedSources`) is read authority and confers no removal right, so a bound untrusted caller (write source `ctx.auth.sourceId ?? ctx.sourceId`, and/or any federated grant) may name only its own write source; a bound caller with no write source (or the `__all__` sentinel) may name nothing; an unbound untrusted caller keeps full authority; trusted local passes. Both answer `OperationError('not_found', 'Unknown source: <id>')`. `resolveRequestedScope(ctx, sourceId, allSources, explicitReads?)` takes an optional explicit-read admission set (#5081) that only `federatedSearchScope` passes: a granted token admits nothing extra, a stdio connection bound by `GBRAIN_SOURCE`/`.gbrain-source` admits `ctx.explicitReadBinding.sourceIds`, and an unbound connection admits its own `localFederatedSourceIds`; its denial hint names why (token grant, binding, opted-out source) with `docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection`. Image, loops and code-intel pass nothing and keep the original denial (`test/explicit-read-admission-5081.test.ts`, `test/serve-stdio-bound-explicit-read.test.ts`). `enforceSubagentSlugFence` stays fail-closed on a missing `subagentId`; its one exception (#5994) is a failed-writes replay whose `replayAuthority` is restricted and whose allow-list equals the stored non-empty `delegatedPrefixes` exactly, and the slug must still match it.+- `src/core/ops/context.ts` (source-id confinement helpers) — `assertSourceInCallerScope(ctx, id)` is the READ-scope confinement for an explicitly named source id (`sources_status`): untrusted callers may only name an id inside the `sourceScopeOpts` ladder. `assertSourceInCallerWriteScope(ctx, id)` is its WRITE-authority twin for destructive source ops (`sources_remove`): federation (`ctx.auth.allowedSources`) is read authority and confers no removal right, so a bound untrusted caller (write source `ctx.auth.sourceId ?? ctx.sourceId`, and/or any federated grant) may name only its own write source; a bound caller with no write source (or the `__all__` sentinel) may name nothing; an unbound untrusted caller keeps full authority; trusted local passes. Both answer `OperationError('not_found', 'Unknown source: <id>')`. `resolveRequestedScope(ctx, sourceId, allSources, explicitReads?)` takes an optional explicit-read admission set (#5081) that only `federatedSearchScope` passes: a granted token admits nothing extra, a stdio connection bound by `GBRAIN_SOURCE`/`.gbrain-source` admits `ctx.explicitReadBinding.sourceIds`, and an unbound connection admits its own `localFederatedSourceIds`; its denial hint names why (token grant, binding, opted-out source) with `docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection`. Image, loops and code-intel pass nothing and keep the original denial (`test/explicit-read-admission-5081.test.ts`, `test/serve-stdio-bound-explicit-read.test.ts`). `enforceSubagentSlugFence` stays fail-closed on a missing `subagentId`; its one exception (#5994) is a failed-writes replay whose `replayAuthority` is restricted and whose allow-list equals the stored non-empty `delegatedPrefixes` exactly, and the slug must still match it. `isOpPageSlug` is the `validatePageSlug` grammar as a predicate; page-prepare's `prepareFileTarget` returns no file for a slug outside it, so an admitted legacy row publishes database-only and never removes a file its stale `source_uri`/`source_path` names (#6212).- `src/core/ops/insights.ts` — stored contradiction reports load only for explicitly trusted, unscoped local callers. Other callers receive the fixed availability note and an empty contradictions list before any report storage access. Expert search threads page and holder policy and performs final authorized-page admission after enrichment.- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`); `get_backlinks`' `type`/`group`/`limit`/`cursor` live in `backlinks-paged.ts`. Three load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`. (3) Link-read source scope: the three read ops take `source_id` (`parseSourceIdParam`, `__all__` admitted) and `all_sources` (equivalent to `__all__`; both together is `invalid_params`). `resolveLinkReadScope` composes `federatedSearchScope` (grant check, #5081 admission, unqualified no-grant widening to `localFederatedSourceIds`; a grant never widens), then `assertExplicitSourceLive` (so an archived source outside the caller's admission answers `permission_denied`, not `unknown_source`), then `linkReadScopeOpts` (remote scalar promoted to `sourceIds[]` for the engine's all-endpoints branch), then `readPolicyOpts`. A trusted local unqualified read that comes back as the federated `sourceIds[]` runs the scalar read once per federated source (set order, resolved source first) and merges de-duplicated on link identity, keeping the scalar branch's cross-source far endpoints; `traverse_graph` walks the federated set in one query because its scalar walk already scopes every node. A trusted local unqualified link read that returns nothing prints a stderr rerun hint naming sources outside the read that hold links for the slug (quiet under `json`, never for remote callers). CLI names: `links` (alias `get_links`), `backlinks`, `graph`. Pinned by `test/federated-link-reads-5827.test.ts`, `test/link-reads-thin-client-5827.serial.test.ts` and `test/e2e/federated-link-reads-postgres.test.ts`. `traverse_graph` `hops` (1-3 `{link_type, toward}`) runs a typed chain through `runRelationalChain` under the op's read scope, returns `{anchor, answers, paths, diagnostics}` with evidence edges (remote context sanitized), refuses `hops` combined with `depth`/`link_type`/`direction` and bad hops as `invalid_params` naming the parameter path, and emits a `relational_chain` notice with the next call when the chain finds nothing. Pinned by `test/traverse-graph-hops.test.ts`.-- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` `content_only` (`ops/get-page-projection.ts`) returns slug, source_id, type, title, revision, tags and content (keys pinned by `test/get-page-content-roundtrip-2225.test.ts`). A put_page `revision_conflict` (`ops/put-page-revision-source.ts`) whose expected_revision is the current revision of the same slug in another source the caller may read (grant via `federatedSearchScope`, private pages excluded for untrusted readers) names that source and gets a re-read fix; otherwise the refusal is unchanged. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`. An `updated_after` the database cannot cast (SQLSTATE 22007/22008, the shared `isDatetimeInputError` in `core/utils.ts` that the hybrid lexical arms also use) is `invalid_params` with a read-only list_pages fix, never echoing the value; other SQLSTATEs pass through (`test/list-pages-timestamp-input.test.ts`). put_page (dry runs included) refuses a new `.md`/`.mdx`-suffixed slug (`persistence/suffixed-slug.ts`).+- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` `content_only` (`ops/get-page-projection.ts`) returns slug, source_id, type, title, revision, tags and content (keys pinned by `test/get-page-content-roundtrip-2225.test.ts`). A put_page `revision_conflict` (`ops/put-page-revision-source.ts`) whose expected_revision is the current revision of the same slug in another source the caller may read (grant via `federatedSearchScope`, private pages excluded for untrusted readers) names that source and gets a re-read fix; otherwise the refusal is unchanged. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`. An `updated_after` the database cannot cast (SQLSTATE 22007/22008, the shared `isDatetimeInputError` in `core/utils.ts` that the hybrid lexical arms also use) is `invalid_params` with a read-only list_pages fix, never echoing the value; other SQLSTATEs pass through (`test/list-pages-timestamp-input.test.ts`). put_page (dry runs included) refuses a new `.md`/`.mdx`-suffixed slug (`persistence/suffixed-slug.ts`). #6212: `delete_page` and `restore_page` (dry runs included) go through `persistence/page-mutations.ts:validateMutationSlug`, which admits a legacy stored slug (`ops/context.ts:isLegacyStoredPageSlug`: refused by today's grammar, still accepted by `validateSlug`) only when an existing row in the target source holds it; every other operation keeps `validatePageSlug`, and remote purge stays denied by `assertPurgeParams`.- `src/core/ops/page-edit.ts` — the `edit_page` operation (write scope, starter surface, client slug-fence allowlist): validates edits, then submits through `submitPageMutation` like put_page; matching and the diff live in `persistence/page-edit.ts`.- `src/core/ops/persistence.ts` — get/list/cancel own-write receipt controls, all requiring write scope and an explicit current operation grant. SQL principal/source/incarnation plus current operation and prefix predicates precede list pagination; original accepted authority and current source/slug grants remain the final guard. Public output selects receipt fields and target metadata only; a failed receipt adds `write_error_message`, the same allowlisted `writeFailureDiagnostic` message managed sync prints, never raw journal error text (`test/sync-frontmatter-slug-conflict.test.ts`). Cancellation rechecks receipt permission under the same transaction grant locks as the original write. Starter/full expose the helpers; frozen verbs stay unchanged, and existing operation snapshots require explicit regrant. Tests: `test/persistence-receipt-operations.test.ts`, `test/client-grants.test.ts`, `test/mcp-surface.test.ts`.diff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex f95019d0bb..0212d006cb 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -17,6 +17,7 @@ import type { AuthInfo, Operation, OperationContext } from './contract.ts';import type { Action } from '../agent-output.ts';import { hostFix, invalidParam, paramUse, readFix } from './op-fix.ts';import { CJK_SLUG_CHARS, SLUG_WORD_CHARS } from '../cjk.ts';+import { validateSlug } from '../utils.ts';import { ALL_SOURCES, NO_SOURCES, isValidSourceId } from '../source-id.ts';import { encodeDeepResearchId } from '../deep-research-id.ts';import { isSearchMode } from '../search/mode.ts';@@ -206,6 +207,7 @@ export function validateUploadPath(filePath: string, root: string, strict = true// Dot stays continuation-only — `..` traversal remains impossible.const OP_PAGE_SLUG_PART = `[${SLUG_WORD_CHARS}_][${SLUG_WORD_CHARS}._\\-]*`;const OP_PAGE_SLUG_SEG = `${OP_PAGE_SLUG_PART}(?::${OP_PAGE_SLUG_PART})*`;+const OP_PAGE_SLUG_RE = new RegExp(`^${OP_PAGE_SLUG_SEG}(\\/${OP_PAGE_SLUG_SEG})*$`, 'iu');/*** Allowlist validator for page slugs. Rejects URL-encoded traversal, backslashes,@@ -223,12 +225,30 @@ export function validatePageSlug(slug: string): void {// #3417: letters/numbers from any script allowed in segments (u flag required// for the \p{...} classes in OP_PAGE_SLUG_SEG). Shape rules (word-char lead,// dot/underscore/hyphen continuation) preserved.- if (!new RegExp(`^${OP_PAGE_SLUG_SEG}(\\/${OP_PAGE_SLUG_SEG})*$`, 'iu').test(slug)) {+ if (!OP_PAGE_SLUG_RE.test(slug)) {throw opError('invalid_params', `Invalid page_slug: ${slug} (allowed: letters/numbers in any script, with '.', '_', '-' after the first character of a part, optional colon-separated namespace parts, and forward-slash separated segments)`,'Use a slug shaped like people/alice-example or notes/v1.0.0: no spaces, backslashes, percent-encoding or dot-led segments.');}}+/** True when `slug` passes validatePageSlug's op-boundary grammar. */+export function isOpPageSlug(slug: string): boolean {+ return typeof slug === 'string' && slug.length > 0 && slug.length <= 255 && OP_PAGE_SLUG_RE.test(slug);+}++/**+ * #6212: a slug an older gbrain stored that today's grammar refuses (a space,+ * as in `people/jane doe`). Admitted only to delete or restore that exact+ * existing row, and only if it still passes the storage guard (validateSlug:+ * no traversal, leading `/`, backslash, control or bidi characters, or encoded+ * separators). Such a row is published database-only (page-prepare.ts): its+ * recorded file path may belong to another page.+ */+export function isLegacyStoredPageSlug(slug: string): boolean {+ if (isOpPageSlug(slug) || typeof slug !== 'string' || slug.length > 255) return false;+ try { validateSlug(slug); return true; } catch { return false; } // refused by the storage guard too: not a legacy slug+}+/*** Match a slug against a list of allow-list prefix globs.*diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex d3d0d59985..039d465cfa 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -1,4 +1,4 @@-import { pageMutationSource, submitPageMutation } from '../persistence/page-mutations.ts';+import { pageMutationSource, submitPageMutation, validateMutationSlug } from '../persistence/page-mutations.ts';import { suffixedSlugDryRun } from '../persistence/suffixed-slug.ts';import { PAGE_MUTATION_PARAMS, CAPTURE_EVENT_PARAMS, WRITE_WAIT_PARAM } from '../persistence/params.ts';import { assertPurgeParams } from '../persistence/purge-params.ts';@@ -383,11 +383,11 @@ const delete_page: Operation = {mutating: true,scope: 'write',handler: async (ctx, p) => {- pageMutationSource(ctx, p, 'delete_page');+ const sourceId = pageMutationSource(ctx, p, 'delete_page');assertPurgeParams(p, ctx.remote);if (ctx.dryRun) {if (typeof p.slug === 'string') {- validatePageSlug(p.slug);+ await validateMutationSlug(ctx, 'delete_page', p.slug, sourceId);enforceClientSlugFence(ctx, p.slug, 'delete_page');enforceSubagentSlugFence(ctx, p.slug, 'delete_page');}@@ -411,10 +411,10 @@ const restore_page: Operation = {mutating: true,scope: 'write',handler: async (ctx, p) => {- pageMutationSource(ctx, p, 'restore_page');+ const sourceId = pageMutationSource(ctx, p, 'restore_page');if (ctx.dryRun) {if (typeof p.slug === 'string') {- validatePageSlug(p.slug);+ await validateMutationSlug(ctx, 'restore_page', p.slug, sourceId);enforceClientSlugFence(ctx, p.slug, 'restore_page');enforceSubagentSlugFence(ctx, p.slug, 'restore_page');}diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 814d7ee15c..140dd8c697 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -7,7 +7,7 @@ import type { OperationContext } from '../ops/contract.ts';import { OperationError } from '../ops/contract.ts';import { VERSION } from '../../version.ts';import { ownerBuildMismatch } from './publication-failure.ts';-import { enforceClientSlugFence, enforceSubagentSlugFence, normalizeSlugPrefix, parseSourceIdParam, requireWritablePage, validatePageSlug } from '../ops/context.ts';+import { enforceClientSlugFence, enforceSubagentSlugFence, isLegacyStoredPageSlug, normalizeSlugPrefix, parseSourceIdParam, requireWritablePage, validatePageSlug } from '../ops/context.ts';import { suffixedSlugAdmission } from './suffixed-slug.ts';import { defaultSlug, detectBinaryNullByte, explicitCaptureType, mergeCaptureFrontmatter, normalizeForHash } from '../capture-content.ts';import { computeContentHash } from '../ingestion/types.ts';@@ -92,6 +92,18 @@ export async function withBatchAdmission<T>(ctx: OperationContext, run: (own: Opreturn withVerifiedLocalRegistration(ctx.engine, registration, () => run(ctx, shared));}/** Validate explicit routing before any admission, including dry-run adapters. */+/**+ * validatePageSlug, except that delete and restore may name a slug an older+ * gbrain stored and today's grammar refuses, when an existing row in+ * `sourceId` holds exactly that slug (#6212). Such a row publishes+ * database-only (page-prepare.ts prepareFileTarget).+ */+export async function validateMutationSlug(ctx: OperationContext, operation: string, slug: string, sourceId: string): Promise<void> {+ if ((operation === 'delete_page' || operation === 'restore_page') && isLegacyStoredPageSlug(slug)+ && await ctx.engine.readPageSnapshot(slug, { sourceId, includeDeleted: true })) return;+ validatePageSlug(slug);+}+export function pageMutationSource(ctx: OperationContext, params: Record<string, unknown>, operation: string): string {const sourceId = parseSourceIdParam(params.source_id, operation) ?? ctx.sourceId ?? 'default';if (sourceId === '__all__') {@@ -256,7 +268,7 @@ export async function preparePageAdmission(ctx: OperationContext,}if (typeof intent.capture_path === 'string') intent.capture_file_hash = sha256(p.content);}- validatePageSlug(slug);+ await validateMutationSlug(ctx, input.operation, slug, sourceId);enforceClientSlugFence(ctx, slug, input.operation);enforceSubagentSlugFence(ctx, slug, input.operation);// Preserve same-source diagnostics for new timeline writes without makingdiff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 69c97bac1b..3434030537 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -9,6 +9,7 @@ import { importFromContent, type ParsedPage } from '../import-file.ts';import { frontmatterHoldMessageWithoutKeys, parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParseOpts } from '../markdown.ts';import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';+import { isOpPageSlug } from '../ops/context.ts';import { shellQuote, type Action } from '../agent-output.ts';import type { RegistryCode } from '../error-registry.ts';import { pageIdentityError } from './page-identity.ts';@@ -138,6 +139,9 @@ export async function fileMatchesSnapshot(engine: BrainEngine, slug: string, bytexport async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>, snapshot: PageSnapshot | null,content: string | null, hostId?: string, options: { allowMissing?: boolean; deleting?: boolean; capture?: { path: string; hash: string }; activePack?: ParseOpts['activePack']; remote?: boolean } = {}): Promise<PreparedMutation['file']> {if (!row.worktree_id) return undefined;+ // #6212: a legacy slug (admitted only to delete or restore its existing row) never owns a file: its recorded+ // source_uri or source_path may name the file of another page, such as the one sync now slugs it to.+ if (!isOpPageSlug(row.slug)) return undefined;// #5409: a read-only mirror's checkout belongs to its Git remote; nothing is written or removed there.if (await sourceMirrorReadOnly(engine, row.source_id)) return undefined;if (snapshot && !snapshot.page.source_path && await isMirrorOnlyPage(engine, row.source_id, row.slug)) return undefined;diff --git a/test/e2e/legacy-slug-delete-postgres.test.ts b/test/e2e/legacy-slug-delete-postgres.test.tsnew file mode 100644index 0000000000..7e94a7bf9a--- /dev/null+++ b/test/e2e/legacy-slug-delete-postgres.test.ts@@ -0,0 +1,10 @@+/** Postgres arm of test/legacy-slug-delete.test.ts (#6212). */+import { describe, test } from 'bun:test';+import { legacySlugLifecycle, legacySlugRefusals } from '../helpers/legacy-slug-scenarios.ts';++const url = process.env.DATABASE_URL;+describe.skipIf(!url)('Postgres legacy stored slugs (#6212)', () => {+ test('a legacy row soft-deletes, restores and purges database-only', () => legacySlugLifecycle(url), 180_000);+ test('a legacy row with a recorded source_path is also database-only', () => legacySlugLifecycle(url, { sourcePath: true }), 180_000);+ test('nothing else accepts the legacy grammar, and remote purge stays denied', () => legacySlugRefusals(url), 180_000);+});diff --git a/test/helpers/legacy-slug-scenarios.ts b/test/helpers/legacy-slug-scenarios.tsnew file mode 100644index 0000000000..894d221921--- /dev/null+++ b/test/helpers/legacy-slug-scenarios.ts@@ -0,0 +1,74 @@+/**+ * #6212: pages an older gbrain stored under a slug today's grammar refuses+ * (`people/jane doe`) can be deleted, restored and purged, database-only, and+ * nothing else. PGLite runs these from test/legacy-slug-delete.test.ts; the+ * Postgres arm is test/e2e/legacy-slug-delete-postgres.test.ts.+ */+import { expect } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { managedBrain } from './managed-brain.ts';++export const LEGACY = 'people/jane doe';+const VAULT_BYTES = '---\ntype: person\ntitle: Jane Doe\n---\n\nJane Doe, captured from the vault.\n';++/** A capture-era row: no file of its own, but source_uri (and optionally source_path) naming a vault file another page owns. */+async function plantLegacyRow({ engine, root }: { engine: BrainEngine; root: string }, opts: { sourcePath?: boolean } = {}) {+ mkdirSync(join(root, 'people'), { recursive: true });+ writeFileSync(join(root, 'people', 'Jane Doe.md'), VAULT_BYTES);+ await engine.putPage(LEGACY, { type: 'person', title: 'Jane Doe', compiled_truth: 'Jane Doe, captured from the vault.', timeline: '' });+ await engine.executeRaw('UPDATE pages SET source_uri = $1, source_path = $2 WHERE slug = $3',+ [`file://${join(root, 'people', 'Jane Doe.md')}`, opts.sourcePath ? 'people/Jane Doe.md' : null, LEGACY]);+}++const revisionOf = async (engine: BrainEngine, slug: string) =>+ (await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true }))?.revision;+const mutate = (ctx: OperationContext, operation: string, params: Record<string, unknown>) =>+ submitPageMutation(ctx, { operation, params: { request_id: randomUUID(), ...params } }) as Promise<Record<string, any>>;+const refusal = (run: Promise<unknown>) => run.then(() => 'ok', (error: { code?: string }) => error.code ?? 'error');++/** Soft-delete, restore and purge a legacy row; every step is database-only and the vault file and the real page survive. */+export async function legacySlugLifecycle(databaseUrl?: string, opts: { sourcePath?: boolean } = {}) {+ await managedBrain(async ({ engine, ctx, root }) => {+ const real = await mutate(ctx, 'put_page', { slug: 'people/jane-doe', content: VAULT_BYTES });+ const realFile = readFileSync(join(root, 'people', 'jane-doe.md'), 'utf8');+ const deleted = (await mutate(ctx, 'delete_page', { slug: LEGACY, expected_revision: await revisionOf(engine, LEGACY) })).outcome;+ expect(deleted).toMatchObject({ status: 'soft_deleted', write_through: { written: false } });+ const restored = (await mutate(ctx, 'restore_page', { slug: LEGACY, expected_revision: await revisionOf(engine, LEGACY) })).outcome;+ expect(restored.write_through).toMatchObject({ written: false });+ expect((await engine.readPageSnapshot(LEGACY, { sourceId: 'default' }))?.page.deleted_at ?? null).toBeNull();+ expect(existsSync(join(root, 'people', 'jane doe.md'))).toBe(false);+ const purged = (await mutate(ctx, 'delete_page', { slug: LEGACY, purge: true, expected_revision: await revisionOf(engine, LEGACY) })).outcome;+ expect(purged).toMatchObject({ status: 'purged' });+ expect(await engine.readPageSnapshot(LEGACY, { sourceId: 'default', includeDeleted: true })).toBeNull();+ expect(readFileSync(join(root, 'people', 'Jane Doe.md'), 'utf8')).toBe(VAULT_BYTES);+ expect(readFileSync(join(root, 'people', 'jane-doe.md'), 'utf8')).toBe(realFile);+ expect((await engine.readPageSnapshot('people/jane-doe', { sourceId: 'default' }))?.revision).toBe((real.outcome ?? real).revision);+ }, { databaseUrl, setup: brain => plantLegacyRow(brain, opts) });+}++/** The legacy grammar opens nothing else: other operations, absent rows, other sources, stale revisions and remote purge stay refused. */+export async function legacySlugRefusals(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ const revision = await revisionOf(engine, LEGACY);+ expect(await refusal(mutate(ctx, 'put_page', { slug: LEGACY, content: VAULT_BYTES, expected_revision: revision }))).toBe('invalid_params');+ expect(await refusal(mutate(ctx, 'edit_page', { slug: LEGACY, edits: [{ old: 'Jane', new: 'J' }], expected_revision: revision }))).toBe('invalid_params');+ expect(await refusal(mutate(ctx, 'delete_page', { slug: 'people/john doe', expected_revision: revision }))).toBe('invalid_params');+ expect(await refusal(mutate(ctx, 'delete_page', { slug: LEGACY, source_id: 'archive', expected_revision: revision }))).toBe('invalid_params');+ expect(await refusal(mutate(ctx, 'delete_page', { slug: LEGACY, expected_revision: randomUUID() }))).toBe('revision_conflict');+ const remote = { ...ctx, remote: true as const };+ expect(await refusal(mutate(remote, 'delete_page', { slug: LEGACY, purge: true, expected_revision: revision }))).toBe('permission_denied');+ expect(await refusal(mutate({ ...remote, auth: { sourceId: 'archive' } } as OperationContext, 'delete_page', { slug: LEGACY, source_id: 'default', expected_revision: revision })))+ .toBe('permission_denied');+ expect(await refusal(mutate({ ...remote, auth: { sourceId: 'default', clientId: 'notes-only', boundSlugPrefixes: ['notes/'] } } as OperationContext,+ 'delete_page', { slug: LEGACY, expected_revision: revision }))).toBe('permission_denied');+ expect((await mutate(remote, 'delete_page', { slug: LEGACY, expected_revision: revision })).outcome).toMatchObject({ status: 'soft_deleted' });+ }, { databaseUrl, setup: async brain => {+ await brain.engine.executeRaw("INSERT INTO sources (id, name) VALUES ('archive', 'archive')");+ await plantLegacyRow(brain);+ } });+}diff --git a/test/legacy-slug-delete.test.ts b/test/legacy-slug-delete.test.tsnew file mode 100644index 0000000000..324b64dfd5--- /dev/null+++ b/test/legacy-slug-delete.test.ts@@ -0,0 +1,19 @@+/** #6212 on PGLite; the Postgres arm is test/e2e/legacy-slug-delete-postgres.test.ts. */+import { describe, expect, test } from 'bun:test';+import { isLegacyStoredPageSlug, isOpPageSlug } from '../src/core/ops/context.ts';+import { legacySlugLifecycle, legacySlugRefusals } from './helpers/legacy-slug-scenarios.ts';++describe('#6212 legacy stored slugs', () => {+ test('only a slug the storage guard still accepts counts as legacy', () => {+ expect(isOpPageSlug('people/jane-doe')).toBe(true);+ expect(isLegacyStoredPageSlug('people/jane-doe')).toBe(false);+ expect(isLegacyStoredPageSlug('people/jane doe')).toBe(true);+ for (const unsafe of ['people/../x', '/people/x', 'people\\x', 'people/%2e%2e', 'people/a\u202eb', 'people/a\u0000b', '']) {+ expect(isLegacyStoredPageSlug(unsafe)).toBe(false);+ }+ });++ test('a legacy row soft-deletes, restores and purges database-only; the vault file and the real page survive', () => legacySlugLifecycle(), 120_000);+ test('a legacy row with a recorded source_path is also database-only', () => legacySlugLifecycle(undefined, { sourcePath: true }), 120_000);+ test('nothing else accepts the legacy grammar, and remote purge stays denied', () => legacySlugRefusals(), 120_000);+});