Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
bootstrap verify: remove the probe pages on every roundtrip exit (#6001)
garrytanc570162750bb
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex a0d95c74b3..3eac909d87 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -33,7 +33,7 @@- `src/core/backup/status-file.ts` — ENGINE-FREE core of the monthly backup-coverage check: the cached verdict (`~/.gbrain/backup-status.json`, schema `gbrain-backup-status-v2`, which includes the `connector` asset kind; a cache with any other schema reads as absent and is recomputed; fail-open load, atomic tmp+rename write, `invalidateBackupStatus()` fired by the fix paths — `bootstrap repo` receipt write, `sources harden`, `workspacePush` finish on ok when the cache carried a warn or failing/unpushed totals (a routine healthy push leaves an ok cache alone, preserving the monthly throttle)), the notice renderer (`backupNoticeText(s, 'human'|'aggregate')` — human ≤300 chars names assets, aggregate is counts-only for remote surfaces; the remote-privacy pin), and the bounded nag gate shared by every render channel (`backupNagGate(channel, s)` on `backup-nag-state.json`, OWN schema `gbrain-backup-nag-v1` — skillpack `loadNagState` would drop the extra fields on round-trip, so only the pure policy fns `decideNagAction`/`recordNagDisplay` are reused). Budget = AND of: 24h cross-channel dampener (`last_shown_at`), per-channel ceiling 3 per pseudo-version (`YYYY-MM(checked_at)` + no-remote fingerprint — month rollover or a changed verdict re-surfaces; a same-month recompute with an unchanged verdict stays quiet), and a global cap of 3 recorded impressions per month (`global_shown_count`/`global_month`). `backupNagReadOnlyConsult` is the OpenClaw context-engine's never-writes variant; `backupSpawnDue`/`recordBackupSpawn` debounce the session-end detached spawn (no sidecar file); `maybeEmitBackupNag` is the cli.ts startup rail body (skip set incl. serve/call/jobs; `BACKUP_LOCAL_ONLY <n>` machine marker + human line). Off switches: `GBRAIN_BACKUP_CHECK=0`, config `backup.check_enabled`; interval env `GBRAIN_BACKUP_CHECK_DAYS` > config `backup.check_interval_days` > 30; values <1 or non-numeric fall back to the 30-day default (`DAYS=0` never means "always stale"; `config set` rejects <1 outright). Tests: `test/backup-status-file.serial.test.ts`. Remote evidence is identity-bound and one-hour-limited; absent, stale, future-dated or inconsistent evidence cannot produce verified recovery counts, and failed refresh does not overwrite cache.- Workspace push and backup coverage (`src/core/workspace-push.ts`, `src/core/backup/{coverage,repository}.ts`): see [workspace-push-and-backup.md](workspace-push-and-backup.md).- `src/core/gbrain-home.ts` — the single GBRAIN_HOME resolution choke point (delegates to config's parent-dir semantics; 0700 on create) — durability, push, hooks, and bootstrap all route through it so home semantics cannot drift.-- `src/core/bootstrap/verify.ts` + `status.ts` — verify is the definition of done: fail-soft check suite over the REAL write path (put_page op → write-through file under `brain/` → in-process sweep → graph floor via link tables → recall), the keyless magic-moment check (`## Facts` fence → zero-LLM reconciliation → world-visibility read-back), source_id collision resolution (as the one bootstrap subcommand holding an engine: a manifest `source_id` already registered to a DIFFERENT checkout → derives a stable `workspace-<8char-path-hash>`, persists it to agent.json, names the re-register steps — every consumer reads `manifest.source_id`), the `embedding_plane` check (keyed installs live-embed ONE probe string and compare the RETURNED width to the actual `content_chunks.embedding` width — a plane split is a named FAIL with the recovery command, keyless passes, a dead probe warns; runs BEFORE the roundtrip so a keyless-passing roundtrip can never certify a brain whose keyed writes all fail), token sweep, byte floors, secret scan, deny globs, repo privacy, hooks smoke (in-process IPC), capability report, first-run tour; snapshots kept last-5 under `<home>/bootstrap/`. status owns the ordered PHASES list (the runbook defers to it), artifact-first detection, install.jsonl, the runbook version-stamp skew check, and the support blob doctor/agents relay verbatim.+- `src/core/bootstrap/verify.ts` + `status.ts` — verify is the definition of done: fail-soft check suite over the REAL write path (put_page op → write-through file under `brain/` → in-process sweep → graph floor via link tables → recall), the keyless magic-moment check (`## Facts` fence → zero-LLM reconciliation → world-visibility read-back), source_id collision resolution (as the one bootstrap subcommand holding an engine: a manifest `source_id` already registered to a DIFFERENT checkout → derives a stable `workspace-<8char-path-hash>`, persists it to agent.json, names the re-register steps — every consumer reads `manifest.source_id`), the `embedding_plane` check (keyed installs live-embed ONE probe string and compare the RETURNED width to the actual `content_chunks.embedding` width — a plane split is a named FAIL with the recovery command, keyless passes, a dead probe warns; runs BEFORE the roundtrip so a keyless-passing roundtrip can never certify a brain whose keyed writes all fail), token sweep, byte floors, secret scan, deny globs, repo privacy, hooks smoke (in-process IPC), capability report, first-run tour; snapshots kept last-5 under `<home>/bootstrap/`. The roundtrip's probe section runs under one try/finally, so both fixed-slug probes are removed on every exit, early failure returns included (#6001; pinned by the early-exit case in `test/bootstrap-verify.serial.test.ts`). status owns the ordered PHASES list (the runbook defers to it), artifact-first detection, install.jsonl, the runbook version-stamp skew check, and the support blob doctor/agents relay verbatim.- `src/core/bootstrap/template-repo.ts` + `scripts/generate-template-repo.ts` — deterministic public-template generation (render `--minimal` + placeholder manifest + stamped README); published only by the release workflow after diffing against the vendored tree.- `scripts/check-bootstrap-tag.sh` / `scripts/check-bootstrap-templates.sh` — CI guards: sanctioned distribution ref only (`latest-stable`; the release job advances it after assets publish) + runbook stamp == VERSION; template↔question-bank token bijection + placeholder-only assertion + offline generator↔vendored byte-diff + runbook-phase↔status.ts consistency. Both skip gracefully when their subjects are absent.- `src/core/cycle/synthesize-concepts.ts` concept-quality addendum — a `concepts/<x>` page whose frontmatter lacks `synthesized_by: synthesize_concepts-*` belongs to a human or another writer: the phase checks it before any LLM spend, never rewrites it, and reports it in `details.skipped_human_owned` (pinned by `test/cycle/synthesize-concepts-human-owned.test.ts`). Concept refs are normalized before grouping (`conceptStemFor`: last path segment through `slugifySegment`, validated by `validatePageSlug`; one atom counts once per concept), so spelling variants share one page and no slug carries a space. Each page records `member_hash` (member atom slugs, titles and bodies without their `## Facts` / `## Takes` sections, which the prompt also omits, plus the synthesis model; a page still carrying the full-body hash whose inputs are unchanged is rehashed without a model call, `details.rehashed`; a narrative a `chat_fallback_chain` model wrote is hashed under that model, so the next cycle re-synthesizes it); an unchanged hash on an `llm` or `deterministic_tier` page is skipped without spend (`details.skipped_unchanged`), and a budget or error fallback never replaces an existing `llm` narrative (`details.kept_existing_narrative`); fallback pages retry next cycle. Pinned by `test/cycle/synthesize-concepts-identity.test.ts`. Eligible groups are processed deterministically by tier, descending atom count, then concept slug so the fixed LLM budget reaches the strongest evidence first regardless of database row order. Every page and phase receipt distinguishes `llm`, intended `deterministic_tier`, `budget_fallback`, and `error_fallback` synthesis modes. The narrative call's output cap is sized from the resolved `models.dream.synthesize` model via `resolveSynthMaxOutputTokens`: 500 for non-thinking models, the gateway's `THINKING_MODEL_MAX_OUTPUT_TOKENS` (no phase-private number — DeepSeek v4 truncates at 8192-class caps) when the gateway's shared `isThinkingModel` matches (name-matched Claude 5 or recipe-declared `thinking_by_default`; unknown providers count as non-thinking), so a tier-`reasoning` thinking model no longer spends the whole budget on reasoning and persists a template stub or truncated chain-of-thought as the concept narrative. Pinned by `test/cycle/synthesize-concepts-token-cap.test.ts`. Right after each concept page write the phase banks concept<->member-atom provenance edges through `engine.addLinksBatch` (`link_source: 'concept-provenance'`; `synthesized_from` concept->atom, `synthesizes` atom->concept; audit site `cycle.synthesize_concepts.provenance`), both endpoints scoped to the cycle's source, so the concept pages are graph-reachable (backlinks, relational recall, doctor `graph_signals_coverage`/`orphans`) even though the prompt forbids enumerating atoms in the body. The dedicated `link_source` keeps reconcile passes from pruning them; `ON CONFLICT DO NOTHING` makes re-runs the backfill; a failed or zero-row edge write lands in `link_warnings[]` (phase `warn`) — NOT in `failures[]`, which means "LLM-failed → template fallback" downstream and drives the rollup's `halt_delta`/`round_completed_delta` — and never aborts the page write. Atom discovery (the `type = 'atom'` scan) is scoped to the cycle source (`opts.sourceId ?? 'default'`) so same-slug atoms from other sources are never grouped into this source's concepts. Pinned by the `#4589` describe in `test/cycle/extract-atoms-synthesize-concepts.test.ts` and `test/cycle/synthesize-concepts-source-scope.test.ts`. The phase budget is `cycle.synthesize_concepts.budget_usd` (finite USD above 0, default 1.5; `config set` refuses other values, a stored invalid value keeps the default with a named-key warning, specs in `src/core/cycle/phase-config-values.ts`); groups refused at the cap are counted in the summary and `details.warnings`. Pinned by `test/cycle-synthesize-concepts-budget-config.test.ts`. A narrative whose stop reason is `length`, `refusal` or `content_filter` is a failure (template fallback for a new concept; an existing `llm` page and its `member_hash` stay), and failed narratives are bounded per concept and member hash by `cycle/concept-retry-bound.ts` (`ConceptRetryBound`, DB-only config key `dream.concepts.failed_attempts`, `MAX_CONCEPT_ATTEMPTS` = 3): a bounded concept is skipped before any spend into `details.skipped_retry_bound` until its members change, a narrative succeeds, or the key is unset (`test/cycle/synthesize-concepts-stop-reason.test.ts`).diff --git a/docs/guides/bootstrap.md b/docs/guides/bootstrap.mdindex 85544eebb8..9e493ce72a 100644--- a/docs/guides/bootstrap.md+++ b/docs/guides/bootstrap.md@@ -405,6 +405,15 @@ collisions, schema state, and prints fixes. `gbrain bootstrap status --json` emia support blob (versions, harness, last verify/push, hook failure rate) your agentcan relay verbatim when you report a problem.+Doctor's `bootstrap_last_verify` check reads the verify snapshots under+`<home>/bootstrap/verify-*.json` and reports only when one exists: a brain that+never ran `gbrain bootstrap verify` (a sole-writer deployment with no agent+workspace, for example) has no snapshot and the check does not fire, so there is+no not-applicable switch to set. Deleting those snapshot files returns the check+to that silent state. `bootstrap verify` removes its two fixed-slug probe pages+(`wiki/bootstrap-verify-probe`, `wiki/bootstrap-verify-probe-entity`) on every+exit, including a roundtrip that fails at its first step.+## Real-agent e2eMost bootstrap tests drive the dispatcher with PATH-shimmed `claude`/`codex`diff --git a/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.tsindex 3f44bdace8..dbd80c251a 100644--- a/src/core/bootstrap/verify.ts+++ b/src/core/bootstrap/verify.ts@@ -767,129 +767,135 @@ async function runRoundtrip(await sweepProbeLeftovers(engine, ws, sourceId);- // 1. Write both probe pages through the REAL op handler [G1].- let writeThroughDetail = '';+ // #6001: the probe section runs under one try/finally so the fixed-slug+ // probes are removed on every exit, including the early returns below.+ // `checks` is the same array the early returns hand back, so a cleanup+ // warning pushed in `finally` still reaches the caller.try {- await putPage.handler(ctx, { slug: VERIFY_PROBE_ENTITY_SLUG, content: PROBE_ENTITY_CONTENT });- const res = (await putPage.handler(ctx, { slug: VERIFY_PROBE_SLUG, content: PROBE_CONTENT })) as {- write_through?: { written: boolean; path?: string; skipped?: string; error?: string };- };- const wt = res.write_through;- const expectedFile = join(ws, 'brain', `${VERIFY_PROBE_SLUG}.md`);- if (wt?.written && wt.path && existsSync(wt.path)) {- writeThroughDetail = `file materialized at ${wt.path}`;- checks.push({ id: 'roundtrip', ok: true, detail: `put_page landed in DB and ${writeThroughDetail}` });- } else if (existsSync(expectedFile)) {- checks.push({ id: 'roundtrip', ok: true, detail: `put_page landed in DB and file materialized at ${expectedFile}` });- } else if (wt?.skipped === 'disabled_by_config') {- // DB-only by operator choice (`sync.write_through=false`), not a broken- // install: the DB write landed, so WARN and keep the remaining- // roundtrip-family checks — sweep/graph/search/magic-moment all run off- // the DB row and still prove the memory loop.- checks.push({- id: 'roundtrip',- ok: true,- warn: true,- detail:- `put_page landed in DB; no file under brain/ because sync.write_through is disabled by config — ` +- `agent writes stay DB-only (run \`gbrain config set sync.write_through true\` to materialize repo files)`,- });- } else {- // [G1] A green verify with an empty repo is impossible: name the- // write-through problem explicitly.- const why = wt?.skipped ?? wt?.error ?? 'write-through reported nothing';- checks.push({- id: 'roundtrip',- ok: false,- detail:- `put_page wrote the DB but NO file appeared under brain/ (write-through: ${why}). ` +- `The workspace source must be registered with its brain/ dir as local_path ` +- `(gbrain sources add ${sourceId} --path ${join(ws, 'brain')}) or agent writes never reach the repo.`,- });+ // 1. Write both probe pages through the REAL op handler [G1].+ let writeThroughDetail = '';+ try {+ await putPage.handler(ctx, { slug: VERIFY_PROBE_ENTITY_SLUG, content: PROBE_ENTITY_CONTENT });+ const res = (await putPage.handler(ctx, { slug: VERIFY_PROBE_SLUG, content: PROBE_CONTENT })) as {+ write_through?: { written: boolean; path?: string; skipped?: string; error?: string };+ };+ const wt = res.write_through;+ const expectedFile = join(ws, 'brain', `${VERIFY_PROBE_SLUG}.md`);+ if (wt?.written && wt.path && existsSync(wt.path)) {+ writeThroughDetail = `file materialized at ${wt.path}`;+ checks.push({ id: 'roundtrip', ok: true, detail: `put_page landed in DB and ${writeThroughDetail}` });+ } else if (existsSync(expectedFile)) {+ checks.push({ id: 'roundtrip', ok: true, detail: `put_page landed in DB and file materialized at ${expectedFile}` });+ } else if (wt?.skipped === 'disabled_by_config') {+ // DB-only by operator choice (`sync.write_through=false`), not a broken+ // install: the DB write landed, so WARN and keep the remaining+ // roundtrip-family checks — sweep/graph/search/magic-moment all run off+ // the DB row and still prove the memory loop.+ checks.push({+ id: 'roundtrip',+ ok: true,+ warn: true,+ detail:+ `put_page landed in DB; no file under brain/ because sync.write_through is disabled by config — ` ++ `agent writes stay DB-only (run \`gbrain config set sync.write_through true\` to materialize repo files)`,+ });+ } else {+ // [G1] A green verify with an empty repo is impossible: name the+ // write-through problem explicitly.+ const why = wt?.skipped ?? wt?.error ?? 'write-through reported nothing';+ checks.push({+ id: 'roundtrip',+ ok: false,+ detail:+ `put_page wrote the DB but NO file appeared under brain/ (write-through: ${why}). ` ++ `The workspace source must be registered with its brain/ dir as local_path ` ++ `(gbrain sources add ${sourceId} --path ${join(ws, 'brain')}) or agent writes never reach the repo.`,+ });+ return { checks };+ }+ } catch (e) {+ checks.push({ id: 'roundtrip', ok: false, detail: `put_page failed: ${(e as Error).message}` });return { checks };}- } catch (e) {- checks.push({ id: 'roundtrip', ok: false, detail: `put_page failed: ${(e as Error).message}` });- return { checks };- }- // 2. Sweep — the `gbrain sweep --once` equivalent, run in-process because- // verify's caller holds the engine [CX2-5].- const caps = opts.capabilities ?? detectCapabilities();- try {- const report = await runMaintenanceSweep(engine, {- sourceId,- budgetMs: opts.sweepBudgetMs ?? 20_000,- capabilities: caps,- log: opts.log,- });- opts.log?.(`[verify] sweep: facts=${report.factsReconciled} links=${report.linksExtracted} timeline=${report.timelineExtracted}`);- } catch (e) {- checks.push({ id: 'graph_floor', ok: false, detail: `maintenance sweep failed: ${(e as Error).message}` });- return { checks };- }-- // 3. Graph floor: ≥1 extracted edge, answered through the link tables.- try {- const links = await engine.getLinks(VERIFY_PROBE_SLUG, { sourceId });- const edge = links.find((l) => l.to_slug === VERIFY_PROBE_ENTITY_SLUG);- const backlinks = await engine.getBacklinks(VERIFY_PROBE_ENTITY_SLUG, { sourceId });- const back = backlinks.find((l) => l.from_slug === VERIFY_PROBE_SLUG);- if (edge && back) {- checks.push({ id: 'graph_floor', ok: true, detail: `entity link extracted and the edge-only query answers (probe → entity, ${links.length} outbound / ${backlinks.length} inbound)` });- } else {- checks.push({ id: 'graph_floor', ok: false, detail: `expected probe→entity edge missing after sweep (outbound: ${links.length}, inbound: ${backlinks.length}) — link extraction is not compounding the graph` });+ // 2. Sweep — the `gbrain sweep --once` equivalent, run in-process because+ // verify's caller holds the engine [CX2-5].+ const caps = opts.capabilities ?? detectCapabilities();+ try {+ const report = await runMaintenanceSweep(engine, {+ sourceId,+ budgetMs: opts.sweepBudgetMs ?? 20_000,+ capabilities: caps,+ log: opts.log,+ });+ opts.log?.(`[verify] sweep: facts=${report.factsReconciled} links=${report.linksExtracted} timeline=${report.timelineExtracted}`);+ } catch (e) {+ checks.push({ id: 'graph_floor', ok: false, detail: `maintenance sweep failed: ${(e as Error).message}` });+ return { checks };}- } catch (e) {- checks.push({ id: 'graph_floor', ok: false, detail: `edge query failed: ${(e as Error).message}` });- }- // 4. get_page + search recall.- try {- await getPage.handler(ctx, { slug: VERIFY_PROBE_SLUG });- } catch (e) {- checks.push({ id: 'roundtrip', ok: false, detail: `get_page read-back failed: ${(e as Error).message}` });- }- try {- const result = await queryOp.handler(ctx, {- query: 'bootstrap verify probe lighthouse',- limit: 10,- expand: false,- });- const found = JSON.stringify(result).includes(VERIFY_PROBE_SLUG);- if (!found) {- checks.push({ id: 'roundtrip', ok: false, detail: `search did not return the probe page (${caps.search} search) — retrieval round-trip broken` });+ // 3. Graph floor: ≥1 extracted edge, answered through the link tables.+ try {+ const links = await engine.getLinks(VERIFY_PROBE_SLUG, { sourceId });+ const edge = links.find((l) => l.to_slug === VERIFY_PROBE_ENTITY_SLUG);+ const backlinks = await engine.getBacklinks(VERIFY_PROBE_ENTITY_SLUG, { sourceId });+ const back = backlinks.find((l) => l.from_slug === VERIFY_PROBE_SLUG);+ if (edge && back) {+ checks.push({ id: 'graph_floor', ok: true, detail: `entity link extracted and the edge-only query answers (probe → entity, ${links.length} outbound / ${backlinks.length} inbound)` });+ } else {+ checks.push({ id: 'graph_floor', ok: false, detail: `expected probe→entity edge missing after sweep (outbound: ${links.length}, inbound: ${backlinks.length}) — link extraction is not compounding the graph` });+ }+ } catch (e) {+ checks.push({ id: 'graph_floor', ok: false, detail: `edge query failed: ${(e as Error).message}` });}- } catch (e) {- checks.push({ id: 'roundtrip', ok: false, detail: `search failed: ${(e as Error).message}` });- }- // 5. Magic moment [CX-P0.5]: the fence fact reconciled by the ZERO-LLM- // sweep pass, read back at visibility='world' (what the harness can read).- try {- const rows = await engine.executeRaw<{ fact: string }>(- `SELECT fact FROM facts WHERE source_id = $1 AND visibility = 'world' AND fact LIKE $2 LIMIT 1`,- [sourceId, `%${VERIFY_MAGIC_TOKEN}%`],- );- if (rows.length > 0) {- checks.push({ id: 'magic_moment', ok: true, detail: `fence-written fact recalled at visibility=world (keyless path: ${caps.mode === 'keyless' ? 'yes' : 'keyed install, same zero-LLM pass'})` });- } else {- checks.push({ id: 'magic_moment', ok: false, detail: 'the ## Facts fence fact never reached the facts index — keyless memory (agent-authored fences) is broken; check the sweep fence pass' });+ // 4. get_page + search recall.+ try {+ await getPage.handler(ctx, { slug: VERIFY_PROBE_SLUG });+ } catch (e) {+ checks.push({ id: 'roundtrip', ok: false, detail: `get_page read-back failed: ${(e as Error).message}` });+ }+ try {+ const result = await queryOp.handler(ctx, {+ query: 'bootstrap verify probe lighthouse',+ limit: 10,+ expand: false,+ });+ const found = JSON.stringify(result).includes(VERIFY_PROBE_SLUG);+ if (!found) {+ checks.push({ id: 'roundtrip', ok: false, detail: `search did not return the probe page (${caps.search} search) — retrieval round-trip broken` });+ }+ } catch (e) {+ checks.push({ id: 'roundtrip', ok: false, detail: `search failed: ${(e as Error).message}` });}- } catch (e) {- checks.push({ id: 'magic_moment', ok: false, detail: `facts read-back failed: ${(e as Error).message}` });- }- // 6. Delete the probes [G13] — failure is a WARNING, never a verify fail.- // HARD delete via the engine primitive (same as sweepProbeLeftovers): the- // probe is not user content and verify is a trusted local caller. The- // delete_page OP is a v0.26.5 SOFT delete (sets deleted_at, row stays in- // pages until the 72h purge) — using it here left two probe tombstones in- // the user's brain after every verify run, visible to include_deleted- // readers and pinned as residue by the Postgres e2e cleanup assertion.- const deleteWarnings = await removeProbes(engine, ws, sourceId);- if (deleteWarnings.length > 0) {- checks.push({ id: 'probe_cleanup', ok: false, warn: true, detail: `probe deletion incomplete: ${deleteWarnings.join('; ')}` });+ // 5. Magic moment [CX-P0.5]: the fence fact reconciled by the ZERO-LLM+ // sweep pass, read back at visibility='world' (what the harness can read).+ try {+ const rows = await engine.executeRaw<{ fact: string }>(+ `SELECT fact FROM facts WHERE source_id = $1 AND visibility = 'world' AND fact LIKE $2 LIMIT 1`,+ [sourceId, `%${VERIFY_MAGIC_TOKEN}%`],+ );+ if (rows.length > 0) {+ checks.push({ id: 'magic_moment', ok: true, detail: `fence-written fact recalled at visibility=world (keyless path: ${caps.mode === 'keyless' ? 'yes' : 'keyed install, same zero-LLM pass'})` });+ } else {+ checks.push({ id: 'magic_moment', ok: false, detail: 'the ## Facts fence fact never reached the facts index — keyless memory (agent-authored fences) is broken; check the sweep fence pass' });+ }+ } catch (e) {+ checks.push({ id: 'magic_moment', ok: false, detail: `facts read-back failed: ${(e as Error).message}` });+ }+ } finally {+ // 6. Delete the probes [G13] — failure is a WARNING, never a verify fail.+ // HARD delete via the engine primitive (same as sweepProbeLeftovers): the+ // probe is not user content and verify is a trusted local caller. The+ // delete_page OP is a v0.26.5 SOFT delete (sets deleted_at, row stays in+ // pages until the 72h purge) — using it here left two probe tombstones in+ // the user's brain after every verify run, visible to include_deleted+ // readers and pinned as residue by the Postgres e2e cleanup assertion.+ const deleteWarnings = await removeProbes(engine, ws, sourceId);+ if (deleteWarnings.length > 0) {+ checks.push({ id: 'probe_cleanup', ok: false, warn: true, detail: `probe deletion incomplete: ${deleteWarnings.join('; ')}` });+ }}return { checks };diff --git a/test/bootstrap-verify.serial.test.ts b/test/bootstrap-verify.serial.test.tsindex fe6cd72da3..5a9d9d4ed2 100644--- a/test/bootstrap-verify.serial.test.ts+++ b/test/bootstrap-verify.serial.test.ts@@ -331,6 +331,31 @@ describe('verifyWorkspace — write-through disabled by config', () => {}, 240_000);});+describe('verifyWorkspace — probe cleanup on an early roundtrip exit (#6001)', () => {+ test('a roundtrip that fails before its cleanup step still removes both probe pages', async () => {+ // A DIRECTORY where the second probe's file must go: the entity probe lands (row + file), the+ // probe page's put_page throws, the roundtrip FAILS at step 1 and returns early, which used to+ // skip removeProbes and leave the entity probe behind.+ const inTheWay = join(ws, 'brain', `${VERIFY_PROBE_SLUG}.md`);+ mkdirSync(inTheWay, { recursive: true });+ try {+ const res = await verifyWorkspace(engine, ws, { sourceId: 'workspace', gbrainHomeDir: home, capabilities: KEYLESS, skipHooksSmoke: true });+ const rt = check(res.checks, 'roundtrip');+ expect(rt.some((c) => !c.ok && c.detail.includes('put_page failed'))).toBe(true);+ expect(res.checks.filter((c) => c.id === 'graph_floor')).toEqual([]);+ expect(res.checks.filter((c) => c.id === 'probe_cleanup')).toEqual([]);+ const probeRows = await engine.executeRaw<{ n: string }>(+ `SELECT count(*)::text AS n FROM pages WHERE source_id = 'workspace' AND slug = ANY($1::text[])`,+ [[VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG]],+ );+ expect(probeRows[0].n).toBe('0');+ expect(existsSync(join(ws, 'brain', `${VERIFY_PROBE_ENTITY_SLUG}.md`))).toBe(false);+ } finally {+ rmSync(inTheWay, { recursive: true, force: true });+ }+ }, 240_000);+});+describe('verifyWorkspace — engine-plane side effects', () => {test('[CX-P1.1] facts.default_visibility: unset → set to world; explicit private → untouched', async () => {const e2 = new PGLiteEngine();