Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Make the purge's derived-page check read only the pages that name the purged page
garrytan0c9189614f5c
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.mdindex f6b566b071..e8e3a17657 100644--- a/docs/architecture/key-files/memory-purge.md+++ b/docs/architecture/key-files/memory-purge.md@@ -34,6 +34,6 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu- `src/commands/doctor/checks/atom-fence-rows.ts` — doctor `atom_fence_rows` (BRAIN, a host-only `WAVE_CHECKS` repair entry cleared by the explicit-only `atom-fence-rows`, so remediation classifies it `explicit_kind_required`): runs `findAtomFenceRows` per source, each statement bounded by `PLAN_STATEMENT_MS`; `warn` names the count per source and the read-only preview `gbrain repair atom-fence-rows --source <id> --json` as an agent `fix`, never a slug or row text; an overrun reports the count as unknown.- `src/core/persistence/purge-parks.ts` — #6741 C: per-tombstone purge parks in op_checkpoints (op `purge-deleted-park`, key source+slug+deleted_at, so a re-deleted page starts fresh); park at `PURGE_PARK_LIMIT` (5) non-deferral failures, a success clears it, and parks of a source seen inactive rearm the first run its writer is active again (`notePurgeSourceWriter`). `purgeStaleCheckpoints` exempts the op; `prunePurgeParks` drops parks whose tombstone is gone. A park records the gbrain `version` of its last failure; `isParked` (the managed and unmanaged selection, doctor `purge_parked_pages`) counts only the running version's, so a park another version wrote (or one with no version) gets one automatic attempt and a failure re-parks it under the running version. Tests: `test/purge-deleted-parks.test.ts`, `test/purge-parks-version.test.ts` (Postgres: `test/e2e/purge-parks-version-postgres.test.ts`).-- `src/core/persistence/derived-origin-hold.ts` + `src/core/repair/origin-carry.ts` — GST-2689: a page that reads as world by its own label but is hidden from remote callers only through a private origin (`derived_from`, an atom's `source_slug`, followed through `slug_aliases` and `slug_rename_history`, or a concept's provenance atom) keeps that privacy once the origin row is gone. `origin-carry.ts` finds the dependents with `private-labels.ts` `dependentsSql('remove')` (the postimage drops the origin rows; a page that names readers is returned when its listed readers would gain it, and gets the label with its `readable_by` kept; a life-chronicle event is returned when the removal opens it, never when its `event.depth` page is removed, since it then fails closed) and gives each `visibility: private` through the label door (`publishMaintenancePages` with `keepTrust` and the label edit on a managed brain, batch `derived-origin-carry:<request_id>`; `writeLabelFile` or `importAtRevision` otherwise). `deletePageCarryingPrivate` is the `delete_page` handler body: a soft delete (local or remote) labels after it committed and returns the unchanged receipt; a purge labels first and, when that fails, soft-deletes instead (an existing tombstone stays), parks the origin and returns `purge_held`. `carryPrivateBeforePurge` runs before every expiry over all the origins (`type = 'atom'` or hidden by `privacyPartSql`) expired or expiring within `CARRY_LEAD_HOURS` (24) at once, so a page private through two of them is found and none crosses the cutoff mid-run uncarried; it publishes the labels 200 per maintenance batch, parks the blocked ones and returns the ones whose park no longer applies, which `purgeDeletedPagesCoordinated` clears only after its purge, so an origin parked when the purge was previewed stays that run; a consented manual purge (`gbrain pages purge-deleted`, `purge_deleted_pages`) first runs `retryParkedOrigins` so its preview lists the origins it frees. A soft-deleted dependent is returned too but never labelled: it blocks its origin (`dependent_soft_deleted`) until it is purged or restored, since a restore would bring it back with the origin row gone; a removed origin tied to another removed origin counts as such a dependent (judged on its own row), since another hold may keep it. Inside each delete transaction `parkUncarriedInPurge` rechecks the origins about to go (the page purge for an explicit or managed retention purge, the unmanaged bulk delete, and each recorded tombstone): an origin a page written after the carry still depends on is parked in that transaction and its row is kept (a live page is soft-deleted instead, and the receipt carries `purge_held` naming no page), so the next purge labels the page and the one after removes the origin. The origin is looked up by the lowercased slug, as `submitPageMutation` deletes it. `derived-origin-hold.ts` is the park (op_checkpoints op `derived-origin-park`, fingerprint the page id, with `blocking_slug`, `code` and `reason`), `derivedOriginPurgeHold` (no engine-sql imports), prune of restored or purged pages, and `readDerivedOriginParks` for doctor `derived_origin_parked`; `purgeStaleCheckpoints` exempts the op. Tests: `test/derived-origin-carry-private.test.ts` (repo-less, minted tokens), `test/derived-origin-carry-managed.test.ts` (managed Git brain).+- `src/core/persistence/derived-origin-hold.ts` + `src/core/repair/origin-carry.ts` — GST-2689: a page that reads as world by its own label but is hidden from remote callers only through a private origin (`derived_from`, an atom's `source_slug`, followed through `slug_aliases` and `slug_rename_history`, or a concept's provenance atom) keeps that privacy once the origin row is gone. `origin-carry.ts` finds the dependents with `private-labels.ts` `dependentsSql('remove')` (it reads only the pages whose frontmatter names a removed slug, or a slug a rename moved to it, through `idx_pages_frontmatter`, one jsonpath scan per 100 slugs of a source, so its cost does not grow with the source; the postimage drops the origin rows; a page that names readers is returned when its listed readers would gain it, and gets the label with its `readable_by` kept; a life-chronicle event is returned when the removal opens it, never when its `event.depth` page is removed, since it then fails closed) and gives each `visibility: private` through the label door (`publishMaintenancePages` with `keepTrust` and the label edit on a managed brain, batch `derived-origin-carry:<request_id>`; `writeLabelFile` or `importAtRevision` otherwise). `deletePageCarryingPrivate` is the `delete_page` handler body: a soft delete (local or remote) labels after it committed and returns the unchanged receipt; a purge labels first and, when that fails, soft-deletes instead (an existing tombstone stays), parks the origin and returns `purge_held`. `carryPrivateBeforePurge` runs before every expiry over all the origins (`type = 'atom'` or hidden by `privacyPartSql`) expired or expiring within `CARRY_LEAD_HOURS` (24) at once, so a page private through two of them is found and none crosses the cutoff mid-run uncarried; it publishes the labels 200 per maintenance batch, parks the blocked ones and returns the ones whose park no longer applies, which `purgeDeletedPagesCoordinated` clears only after its purge, so an origin parked when the purge was previewed stays that run; a consented manual purge (`gbrain pages purge-deleted`, `purge_deleted_pages`) first runs `retryParkedOrigins` so its preview lists the origins it frees. A soft-deleted dependent is returned too but never labelled: it blocks its origin (`dependent_soft_deleted`) until it is purged or restored, since a restore would bring it back with the origin row gone; a removed origin tied to another removed origin counts as such a dependent (judged on its own row), since another hold may keep it. Inside each delete transaction `parkUncarriedInPurge` rechecks the origins about to go (the page purge for an explicit or managed retention purge, the unmanaged bulk delete, and each recorded tombstone): an origin a page written after the carry still depends on is parked in that transaction and its row is kept (a live page is soft-deleted instead, and the receipt carries `purge_held` naming no page), so the next purge labels the page and the one after removes the origin. The origin is looked up by the lowercased slug, as `submitPageMutation` deletes it. `derived-origin-hold.ts` is the park (op_checkpoints op `derived-origin-park`, fingerprint the page id, with `blocking_slug`, `code` and `reason`), `derivedOriginPurgeHold` (no engine-sql imports), prune of restored or purged pages, and `readDerivedOriginParks` for doctor `derived_origin_parked`; `purgeStaleCheckpoints` exempts the op. Tests: `test/derived-origin-carry-private.test.ts` (repo-less, minted tokens), `test/derived-origin-carry-managed.test.ts` (managed Git brain), `test/derived-origin-recheck-plan.test.ts` (pages rows the recheck visits).- `src/core/repair/segmented-mirror.ts` — `gbrain repair segmented-mirror` (LPH a), explicit-only, preview-bound, destructive consent, `checks: []` (no doctor scan: detection reads every segmented file). `scanSegmentedMirrors` (read-only, owner host; a non-owner source is held `not_owner_host`) walks live `body_storage='segmented'` pages of sources with a worktree binding whose snapshot ledger applies (`ledgerApplies`), runs `prepareFileTarget(..., null, { allowMissing })` (the mirror's own drift check; `file_database_drift` or any other `OperationError` is held, never rewritten), then lists the page only when overlaying the ledger on the file's facts fences changes its region digests (`fileBodyDigests` vs `overlaidFileBodyDigests` over `FileBytes`, bounded memory) and the streamed render (`unreadPageFile`) hashes differently. The hash (`segmented-mirror-v1`) binds source selection, slug, page id, revision, path and both SHA-256s; the approved set lives in `op_checkpoints`. Apply re-checks revision and file hash of every page not yet admitted (`preview_changed`), then per page admits and commits, in one transaction like a withdrawal, a `repair_segmented_mirror` request (request id derived from the hash; its receipt) that inserts a version-2 targeted `withdrawal-mirror` + `git` effect (no embedding) whose `data.approved_file` carries the preview's file and render SHA-256 (`mirrorPage` skips the target `preview_changed` when the file's before-hash or the streamed render differs, before the gate or any recovery record; `publishGitPage` skips it when the file is not the approved render; the outcome is `refused` `preview_changed` with a read-only fix re-running the preview); it wakes this process's consumer and waits up to the write wait for them (`mirrored` / `mirror_queued` / `held` / `failed`; a replay is `replayed`). Test: `test/pathological/lp-a-segmented-mirror.test.ts`.diff --git a/src/core/repair/origin-carry.ts b/src/core/repair/origin-carry.tsindex 1feec7f669..a6baac09f0 100644--- a/src/core/repair/origin-carry.ts+++ b/src/core/repair/origin-carry.ts@@ -43,7 +43,8 @@ const failureOf = (error: unknown): Failure => ({ code: typeof (error as { code?async function dependentsOf(engine: BrainEngine, origins: Origin[]): Promise<Dependent[]> {const rows = await engine.executeRaw<{ id: number; cleared_id: number; source_id: string; slug: string; deleted: boolean }>(- `SELECT d.id, d.cleared_id, p.source_id, p.slug, p.deleted_at IS NOT NULL AS deleted FROM (${dependentsSql('remove')}) d JOIN pages p ON p.id = d.id ORDER BY d.id`,+ `SELECT d.id, d.cleared_id, p.source_id, p.slug, p.deleted_at IS NOT NULL AS deleted FROM (${dependentsSql('remove')}) d+ JOIN LATERAL (SELECT pages.source_id, pages.slug, pages.deleted_at FROM pages WHERE pages.id = d.id OFFSET 0) p ON true ORDER BY d.id`,[origins.map(o => o.id), origins.map(o => o.source_id), origins.map(o => o.slug), origins.map(() => '')], bounded);return rows.map(row => ({ id: Number(row.id), origin_id: Number(row.cleared_id), source_id: row.source_id, slug: row.slug, deleted: row.deleted === true }));}diff --git a/src/core/repair/private-labels.ts b/src/core/repair/private-labels.tsindex 649611fd0b..220d2b902f 100644--- a/src/core/repair/private-labels.ts+++ b/src/core/repair/private-labels.ts@@ -226,6 +226,25 @@ async function planRestore(engine: BrainEngine, scope: RepairScope, selection: Sreturn { counts: counts as Record<string, number>, entries, unreadable };}+/**+ * The pages of a source in `from` (source_id, slug) whose frontmatter can name one of its slugs: `event.depth` alone with+ * `depthOnly`, else also `source_slug` and a `derived_from` string or array entry, with or without `.md`. Each source's+ * slugs, 100 at a time, make one jsonpath filter that idx_pages_frontmatter answers in a single scan (every GIN scan reads+ * the index's whole pending list, so a scan per slug and shape cost more than the full read it replaced on a brain with+ * recent writes). A slug that reads as a JSON number or boolean is also matched as that scalar, since `->>` and+ * jsonb_array_elements_text read one as its text.+ */+function namingSql(from: string, depthOnly = false): string {+ const test = depthOnly ? `'@.event.depth == ' || f.v`+ : `'@.source_slug == ' || f.v || ' || @.event.depth == ' || f.v || ' || @.derived_from == ' || f.v || ' || @.derived_from == ' || to_jsonb(n.slug || '.md')::text`;+ return `SELECT p.id, p.source_id, p.slug, p.frontmatter ? 'derived_from' AS declares FROM (+ SELECT n.source_id, ('$ ? (' || string_agg(${test}, ' || ') || ')')::jsonpath AS path+ FROM (SELECT DISTINCT source_id, slug, (dense_rank() OVER (PARTITION BY source_id ORDER BY slug) - 1) / 100 AS part FROM ${from} r) n+ CROSS JOIN LATERAL (SELECT to_jsonb(n.slug)::text AS v UNION ALL SELECT n.slug WHERE n.slug ~ '^(-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE][+-]?[0-9]+)?|true|false)$') f+ GROUP BY n.source_id, n.part) q+ JOIN LATERAL (SELECT p.id, p.source_id, p.slug, p.frontmatter FROM pages p WHERE p.frontmatter @? q.path AND p.source_id = q.source_id OFFSET 0) p ON true`;+}+/*** The windowDependents statement: (id, cleared_id, category) for each exposed page and the cleared page it is tied to, from* the cleared pages ($1 ids, $2 source ids, $3 slugs, $4 comma-joined label keys). It never pairs every page with every@@ -236,17 +255,27 @@ async function planRestore(engine: BrainEngine, scope: RepairScope, selection: S** GST-2689 `remove`: the postimage is the pages table with the cleared pages removed instead (their rows, so the links to* them go too), `keys` is unused, an atom also ties to the page a rename moved its `source_slug` to (slug_aliases and- * slug_rename_history, read before a purge scrubs them). A page that names readers is judged by the same privacy rules,- * since readable_by never relaxes them: it is returned when the removal would open it to its listed readers. A soft-deleted- * page is a candidate too, since a restore brings it back with the origin row gone, and so is a removed page tied to- * another removed page (judged on its own row, against the postimage), since another hold may keep it from the purge.+ * slug_rename_history, read before a purge scrubs them). Its references are read only from the pages that can name a+ * cleared page, found through idx_pages_frontmatter (a containment probe per reference shape, for each cleared slug and+ * each slug a rename moved to it), and from the events whose `event.depth` names one of those pages, so the statement+ * costs the same on a large source as on a small one; the probes find a superset and `refs` keeps only exact matches.+ * A page that names readers is judged by the same privacy rules, since readable_by never relaxes them: it is returned+ * when the removal would open it to its listed readers. A soft-deleted page is a candidate too, since a restore brings it+ * back with the origin row gone, and so is a removed page tied to another removed page (judged on its own row, against+ * the postimage), since another hold may keep it from the purge.*/export function dependentsSql(mode: 'clear' | 'remove' = 'clear'): string {const remove = mode === 'remove';const live = (sql: string) => remove ? '' : sql;return `WITH cleared AS MATERIALIZED (- SELECT * FROM unnest($1::integer[], $2::text[], $3::text[], $4::text[]) AS c(id, source_id, slug, keys)),- refs AS MATERIALIZED (SELECT p.id, p.source_id, p.slug, p.deleted_at, r.kind, r.ref FROM pages p+ SELECT * FROM unnest($1::integer[], $2::text[], $3::text[], $4::text[]) AS c(id, source_id, slug, keys)),${remove ? `+ named AS MATERIALIZED (SELECT c.source_id, c.slug FROM cleared c+ UNION SELECT a.source_id, a.alias_slug FROM cleared c JOIN slug_aliases a ON a.source_id = c.source_id AND a.canonical_slug = c.slug AND a.notes = 'rename'+ UNION SELECT m.source_id, m.old_slug FROM cleared c JOIN slug_rename_history m ON m.source_id = c.source_id AND m.new_slug = c.slug),+ naming AS MATERIALIZED (${namingSql('named')}),+ depth_naming AS MATERIALIZED (${namingSql('(SELECT DISTINCT source_id, slug FROM naming WHERE declares)', true)}),` : ''}+ refs AS MATERIALIZED (SELECT p.id, p.source_id, p.slug, p.deleted_at, r.kind, r.ref FROM ${remove ? `(SELECT id FROM naming UNION SELECT id FROM depth_naming) k+ JOIN LATERAL (SELECT pages.id, pages.source_id, pages.slug, pages.deleted_at, pages.frontmatter FROM pages WHERE pages.id = k.id OFFSET 0) p ON true` : 'pages p'}CROSS JOIN LATERAL (SELECT 'source_slug' AS kind, p.frontmatter->>'source_slug' AS refUNION ALL SELECT 'depth', p.frontmatter->'event'->>'depth'UNION ALL SELECT 'declared', regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text(@@ -267,15 +296,17 @@ export function dependentsSql(mode: 'clear' | 'remove' = 'clear'): string {WHERE h.kind = 'declared'${live(' AND r.deleted_at IS NULL')}UNION ALL SELECT p.id, t.cleared_id FROM provenance t JOIN pages p ON p.id = t.from_page_id AND p.source_id = t.source_id${live(' AND p.deleted_at IS NULL')}),candidates AS MATERIALIZED (SELECT DISTINCT t.id, t.cleared_id FROM ties t WHERE ${remove ? 't.id <> t.cleared_id' : 'NOT EXISTS (SELECT 1 FROM cleared x WHERE x.id = t.id)'}),${remove ? `- candidate_rows AS MATERIALIZED (SELECT a.id, a.source_id, a.slug, a.type, a.frontmatter FROM pages a WHERE a.id IN (SELECT id FROM candidates)),` : ''}- public_after AS MATERIALIZED (WITH pages AS NOT MATERIALIZED (SELECT pg.id, pg.source_id, pg.slug, pg.type, pg.deleted_at,+ candidate_rows AS MATERIALIZED (SELECT a.id, a.source_id, a.slug, a.type, a.frontmatter FROM (SELECT DISTINCT id FROM candidates) k+ JOIN LATERAL (SELECT pages.id, pages.source_id, pages.slug, pages.type, pages.frontmatter FROM pages WHERE pages.id = k.id OFFSET 0) a ON true),` : ''}+ public_after AS MATERIALIZED (WITH pages AS NOT MATERIALIZED (${remove ? `SELECT pg.id, pg.source_id, pg.slug, pg.type, pg.deleted_at, pg.frontmatter+ FROM pages pg WHERE pg.id <> ALL($1::integer[])` : `SELECT pg.id, pg.source_id, pg.slug, pg.type, pg.deleted_at,CASE WHEN c.id IS NULL THEN pg.frontmatter ELSE pg.frontmatter - string_to_array(c.keys, ',') END AS frontmatter- FROM pages pg LEFT JOIN cleared c ON c.id = pg.id${remove ? ' WHERE c.id IS NULL' : ''})+ FROM pages pg LEFT JOIN cleared c ON c.id = pg.id`})SELECT after_clear.id FROM (${remove ? 'SELECT * FROM candidate_rows' : `SELECT a.id, a.source_id, a.slug, a.type, a.frontmatter FROM (SELECT DISTINCT id FROM candidates) kJOIN pages a ON a.id = k.id`} OFFSET 0) after_clear WHERE ${privacyPartSql('after_clear', true)})SELECT cand.id, cand.cleared_id, CASE WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN 'life_chronicle'WHEN p.type = 'atom' THEN 'atom' WHEN p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL THEN 'concept' ELSE 'derived_from' END AS category- FROM candidates cand JOIN pages p ON p.id = cand.id+ FROM candidates cand JOIN ${remove ? 'candidate_rows' : 'pages'} p ON p.id = cand.idWHERE cand.id IN (SELECT id FROM public_after) AND NOT ${privacyPartSql('p')}ORDER BY cand.id, cand.cleared_id`;}diff --git a/test/derived-origin-recheck-plan.test.ts b/test/derived-origin-recheck-plan.test.tsnew file mode 100644index 0000000000..16ec1fd067--- /dev/null+++ b/test/derived-origin-recheck-plan.test.ts@@ -0,0 +1,128 @@+/**+ * GST-2689 follow-up: the derived-origin recheck inside a purge's delete transaction reads only the pages that can+ * name the purged pages, not every page of the source.+ *+ * Protects: `parkUncarriedInPurge` (the single-page purge and the bulk delete call it in their transaction) sends one+ * dependents statement (private-labels.ts `dependentsSql('remove')`) that visits a handful of `pages` rows on a source of+ * thousands, measured from EXPLAIN (ANALYZE, FORMAT JSON) on PGLite and Postgres; and the statement still returns every+ * tie the full scan found: a derived_from string with `.md`, a derived_from array with and without `.md`, an atom's+ * source_slug, an atom whose source_slug a rename (slug_aliases, slug_rename_history) moved to the origin, a concept+ * through its provenance atom, a life-chronicle event's own derived_from and an event whose event.depth page derives+ * from the origin (including a slug that reads as a number, and a dated slug such as `2026-11`, which is never cast+ * as one), and never an event that fails closed on a removed event.depth page or a page already private.+ * Regression it catches: a dependents statement that lists the references of every page of the source, so the purge's+ * transaction grows with the brain. No wall-clock thresholds.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { parkUncarriedInPurge } from '../src/core/repair/origin-carry.ts';+import { dependentsSql } from '../src/core/repair/private-labels.ts';+import { readHonorAliases, withoutCallerAccess } from '../src/core/search/private-visibility.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const SRC = 'source-a';+const FILLER = 12_000;++type PlanNode = { 'Relation Name'?: string; 'Subplan Name'?: string; 'Actual Rows'?: number; 'Actual Loops'?: number; 'Rows Removed by Filter'?: number; 'Rows Removed by Index Recheck'?: number; Plans?: PlanNode[] };+/**+ * The pages rows the statement's own joins and CTEs visit. The correlated subqueries of the privacy rules+ * (private-visibility.ts, `SubPlan`/`InitPlan` nodes) are left out: they judge each candidate the same way every read does.+ */+function pagesVisited(node: PlanNode): number {+ if (/^(SubPlan|InitPlan)/.test(node['Subplan Name'] ?? '')) return 0;+ const own = node['Relation Name'] === 'pages'+ ? ((node['Actual Rows'] ?? 0) + (node['Rows Removed by Filter'] ?? 0) + (node['Rows Removed by Index Recheck'] ?? 0)) * (node['Actual Loops'] ?? 1) : 0;+ return own + (node.Plans ?? []).reduce((sum, child) => sum + pagesVisited(child), 0);+}++/** Every page a removal of `o/origin` (and `o/second`, removed with it) opens, then the pages it must never return. */+const OPENED = ['o/digest-md', 'o/digest-array', 'o/digest-array-md', 'o/atom', 'o/atom-aliased', 'o/atom-moved', 'o/concept', 'o/event', 'o/depth', 'o/event-via-depth', 'o/twelve', 'o/dated'];+const KEPT = ['o/own', 'o/closed', 'o/plain'];+const PAGES: Record<string, string[]> = {+ 'o/origin': ['type: note', 'visibility: private'],+ '12': ['type: note', 'visibility: private'],+ '2026-11': ['type: note', 'visibility: private'],+ 'o/digest-md': ['type: note', 'derived_from: o/origin.md'],+ 'o/digest-array': ['type: note', 'derived_from: [o/origin]'],+ 'o/digest-array-md': ['type: note', 'derived_from: [o/plain, o/origin.md]'],+ 'o/atom': ['type: atom', 'visibility: world', 'source_slug: o/origin'],+ 'o/atom-aliased': ['type: atom', 'visibility: world', 'source_slug: o/old-name'],+ 'o/atom-moved': ['type: atom', 'visibility: world', 'source_slug: o/older-name'],+ 'o/concept': ['type: concept', 'synthesized_by: test', 'visibility: world'],+ 'o/event': ['type: event', 'captured_via: life-chronicle:auto', 'visibility: world', 'derived_from: [o/origin.md]', 'event:', ' depth: o/plain'],+ 'o/depth': ['type: meeting', 'derived_from: [o/origin]'],+ 'o/event-via-depth': ['type: event', 'captured_via: life-chronicle:auto', 'visibility: world', 'event:', ' depth: o/depth'],+ 'o/twelve': ['type: note', 'derived_from: [12]'],+ 'o/dated': ['type: note', "derived_from: ['2026-11']"],+ 'o/own': ['type: note', 'visibility: private', 'derived_from: [o/origin]'],+ 'o/closed': ['type: event', 'captured_via: life-chronicle:auto', 'visibility: world', 'event:', ' depth: o/origin'],+ 'o/plain': ['type: note'],+};++for (const kind of testBackends()) {+ describe(`the in-purge derived-origin recheck reads by index (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const ids: Record<string, number> = {};+ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; close = () => lite.disconnect(); }+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);+ await engine.executeRaw(`INSERT INTO pages (source_id, slug, type, title, compiled_truth, frontmatter)+ SELECT $1, 'filler/p-' || g, 'note', 'Filler ' || g, 'filler body',+ CASE g % 4 WHEN 0 THEN jsonb_build_object('derived_from', jsonb_build_array('filler/p-' || (g + 1)))+ WHEN 1 THEN jsonb_build_object('source_slug', 'filler/p-' || (g + 1)) ELSE '{}'::jsonb END+ FROM generate_series(1, $2::int) g`, [SRC, FILLER]);+ for (const [slug, fm] of Object.entries(PAGES)) {+ const text = ['---', `title: ${slug}`, ...fm, '---', `# ${slug}`, '', 'Body.'].join('\n');+ expect((await importFromContent(engine, slug, text, { sourceId: SRC, noEmbed: true })).status).toBe('imported');+ }+ for (const row of await engine.executeRaw<{ id: number; slug: string }>("SELECT id, slug FROM pages WHERE source_id=$1 AND slug NOT LIKE 'filler/%'", [SRC])) ids[row.slug] = Number(row.id);+ await engine.executeRaw("INSERT INTO slug_aliases (source_id, alias_slug, canonical_slug, notes) VALUES ($1, 'o/old-name', 'o/origin', 'rename')", [SRC]);+ await engine.executeRaw("INSERT INTO slug_rename_history (source_id, old_slug, new_slug) VALUES ($1, 'o/older-name', 'o/origin')", [SRC]);+ await engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, link_source) VALUES ($1, $2, 'synthesized_from', 'concept-provenance')`, [ids['o/concept'], ids['o/atom']]);+ await engine.executeRaw('ANALYZE pages');+ }, 240_000);+ afterAll(async () => { await close?.(); });++ test('the removal of the origins returns every page it opens and none it keeps', async () => {+ const origins = ['o/origin', '12', '2026-11'];+ const rows = await withoutCallerAccess(async () => {+ await readHonorAliases(engine);+ return engine.executeRaw<{ id: number; cleared_id: number }>(dependentsSql('remove'),+ [origins.map(slug => ids[slug]), origins.map(() => SRC), origins, origins.map(() => '')], { jitOff: true });+ });+ const bySlug = Object.fromEntries(Object.entries(ids).map(([slug, id]) => [id, slug]));+ expect([...new Set(rows.map(row => bySlug[Number(row.id)]))].sort()).toEqual([...OPENED].sort());+ for (const slug of KEPT) expect(rows.some(row => bySlug[Number(row.id)] === slug)).toBe(false);+ });++ test('the recheck inside the delete transaction visits a handful of pages rows', async () => {+ const visits: number[] = [];+ await engine.transaction(async tx => {+ const measured = new Proxy(tx, { get(target, key) {+ if (key === 'executeRaw') return async (sql: string, params?: unknown[], opts?: unknown) => {+ if (sql.includes('cleared AS MATERIALIZED')) {+ const [plan] = await target.executeRaw<{ 'QUERY PLAN': unknown }>(`EXPLAIN (ANALYZE, FORMAT JSON) ${sql}`, params, opts as never);+ const parsed = (typeof plan!['QUERY PLAN'] === 'string' ? JSON.parse(plan!['QUERY PLAN'] as string) : plan!['QUERY PLAN']) as Array<{ Plan: PlanNode }>;+ visits.push(pagesVisited(parsed[0]!.Plan));+ }+ return target.executeRaw(sql, params, opts as never);+ };+ const value = Reflect.get(target, key, target);+ return typeof value === 'function' ? value.bind(target) : value;+ } });+ const parks = await parkUncarriedInPurge(measured, [ids['o/origin']!], { recheckParked: true });+ expect(parks.map(park => park.slug)).toEqual(['o/origin']);+ throw new RollbackForTest();+ }).catch(error => { if (!(error instanceof RollbackForTest)) throw error; });+ expect(visits).toHaveLength(1);+ expect(visits[0]).toBeLessThan(200);+ });+ });+}++class RollbackForTest extends Error {}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 2345f6c6b6..a4716d57ef 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -91,6 +91,7 @@ test/degraded-engine-recovered-surface-9224.test.tstest/derived-link-reconciliation.test.tstest/derived-origin-carry-managed.test.tstest/derived-origin-carry-private.test.ts+test/derived-origin-recheck-plan.test.tstest/direct-pool-profile.test.tstest/doctor-attest-read-shared-scope.test.tstest/doctor-database-encoding.test.ts