Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(bootstrap): verify clears its own probe purge tombstones so the next run is not refused (#6634)

time-attack73d85aeba2e5
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index ad288f2021..c26f12505a 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -32,7 +32,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, waiting as long as a CLI write: `resolveCliWriteWaitMs`, so `GBRAIN_WRITE_WAIT_MS`/`persistence.write_wait_ms`, default 30 s; a write still pending after that names its request and `gbrain write-request` poll command → 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/verify.ts` + `status.ts` — verify is the definition of done: fail-soft check suite over the REAL write path (put_page op, waiting as long as a CLI write: `resolveCliWriteWaitMs`, so `GBRAIN_WRITE_WAIT_MS`/`persistence.write_wait_ms`, default 30 s; a write still pending after that names its request and `gbrain write-request` poll command → 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`). On a managed brain each probe is purged through the coordinator and its purge tombstones (page, plus the fact/take purges of that request) are then cleared with the host-only `unpurgePage`, also on every sweep, so the constant probe bodies are never refused `purged_content` on the next run and `page_purges` does not grow (#6634). 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 case and spacing variants share one page and no slug carries a space; punctuation variants (`network-effects` / `networkeffects`) fold per run through `cycle/concept-redirects.ts` `addSpellingRedirects` (#5965; documented with `concept-publication.ts` in `core-cycle-continued.md`). 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/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.ts
index 21ad95e51e..f02dead312 100644
--- a/src/core/bootstrap/verify.ts
+++ b/src/core/bootstrap/verify.ts
@@ -30,6 +30,7 @@
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { managedFilesystemRootFor } from '../persistence/filesystem-guard.ts';
import { submitPageMutation } from '../persistence/page-mutations.ts';
+import { unpurgePage } from '../persistence/page-purge.ts';
import { withCoordinatedWrite } from '../persistence/context.ts';
import { pendingReceiptOf, pollCommand, resolveCliWriteWaitMs, WRITE_WAIT_ENV } from '../persistence/write-wait.ts';
import { maintenanceAttribution } from '../persistence/attribution.ts';
@@ -207,6 +208,11 @@ async function sweepProbeLeftovers(engine: BrainEngine, ws: string, sourceId: st
* engine primitives. A managed brain (#5280) purges each probe through the
* coordinator (`delete_page --purge`, bound to its revision, which also removes
* its canonical file) and removes the probe facts in a coordinated transaction.
+ * #6634: the probe bodies are constant, so a purge tombstone would refuse the
+ * next run's put_page as `purged_content`; each probe's tombstones (page, and
+ * the fact/take purges of the same request) are cleared through the host-only
+ * unpurge path after its purge, and on every sweep, which also clears leftovers
+ * of earlier runs. Probe pages are not user content.
*/
async function removeProbes(engine: BrainEngine, ws: string, sourceId: string): Promise<string[]> {
const warnings: string[] = [];
@@ -223,6 +229,11 @@ async function removeProbes(engine: BrainEngine, ws: string, sourceId: string):
} catch (e) {
warnings.push(`${slug}: ${(e as Error).message}`);
}
+ try {
+ await unpurgePage(localCtx(engine, sourceId), { slug, source_id: sourceId });
+ } catch {
+ /* page_purges may not exist on a pre-migration brain — doctor_green names that */
+ }
if (managed) continue;
try {
rmSync(join(ws, 'brain', `${slug}.md`), { force: true });
diff --git a/test/bootstrap-verify.serial.test.ts b/test/bootstrap-verify.serial.test.ts
index 0d8e5d8eb0..481653f1f0 100644
--- a/test/bootstrap-verify.serial.test.ts
+++ b/test/bootstrap-verify.serial.test.ts
@@ -674,6 +674,67 @@ describe('verifyWorkspace — managed brain (#5280)', () => {
}, 240_000);
});
+describe('verifyWorkspace — managed brain, repeated runs (#6634)', () => {
+ // Adapted from PR #6634 (@Masashi-Ono0611). The probe bodies stay constant; verify clears its own purge tombstones
+ // instead of carrying a per-run nonce, so page_purges does not grow by a row per probe per run.
+ test('verify can roundtrip twice after purging both probe pages, leaving no probe tombstones', async () => {
+ await claimWorktree(engine, 'workspace', join(ws, 'brain'));
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const probeTombstones = async () => ({
+ pages: (await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_purges WHERE source_id = 'workspace' AND slug = ANY($1::text[])`,
+ [[VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG]]))[0]!.n,
+ facts: (await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM fact_purges WHERE source_id = 'workspace' AND request_id IN (
+ SELECT request_id FROM persistence_requests WHERE source_id = 'workspace' AND operation = 'delete_page' AND slug = ANY($1::text[]))`,
+ [[VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG]]))[0]!.n,
+ });
+ try {
+ const opts = { sourceId: 'workspace', gbrainHomeDir: home, capabilities: KEYLESS, skipHooksSmoke: true };
+ const first = await verifyWorkspace(engine, ws, opts);
+ expect(check(first.checks, 'roundtrip').filter((c) => !c.ok)).toEqual([]);
+ expect(await probeTombstones()).toEqual({ pages: 0, facts: 0 });
+
+ const second = await verifyWorkspace(engine, ws, opts);
+ const secondRoundtrip = check(second.checks, 'roundtrip');
+ expect(secondRoundtrip.length).toBeGreaterThan(0);
+ expect(secondRoundtrip.filter((c) => !c.ok)).toEqual([]);
+ expect(await probeTombstones()).toEqual({ pages: 0, facts: 0 });
+ const refused = await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE source_id = 'workspace' AND error_code = 'purged_content'
+ AND slug = ANY($1::text[])`, [[VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG]]);
+ expect(refused).toEqual([]);
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ }, 240_000);
+
+ test('probe tombstones an earlier verify left behind are swept before the probes are written', async () => {
+ await claimWorktree(engine, 'workspace', join(ws, 'brain'));
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ // Keep a copy of every tombstone verify clears, so the test can put back exactly what an older verify left.
+ await engine.executeRaw(`CREATE TABLE w6634_kept (LIKE page_purges)`);
+ await engine.executeRaw(`CREATE FUNCTION w6634_keep() RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN INSERT INTO w6634_kept SELECT OLD.*; RETURN OLD; END $$`);
+ await engine.executeRaw(`CREATE TRIGGER w6634_keep BEFORE DELETE ON page_purges FOR EACH ROW EXECUTE FUNCTION w6634_keep()`);
+ try {
+ const opts = { sourceId: 'workspace', gbrainHomeDir: home, capabilities: KEYLESS, skipHooksSmoke: true };
+ expect(check((await verifyWorkspace(engine, ws, opts)).checks, 'roundtrip').filter((c) => !c.ok)).toEqual([]);
+ await engine.executeRaw(`DROP TRIGGER w6634_keep ON page_purges`);
+ await engine.executeRaw(`INSERT INTO page_purges SELECT * FROM w6634_kept`);
+ const left = await engine.executeRaw<{ slug: string }>(`SELECT slug FROM page_purges WHERE source_id = 'workspace' AND slug = ANY($1::text[])`,
+ [[VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG]]);
+ expect(new Set(left.map((r) => r.slug))).toEqual(new Set([VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG]));
+ const second = await verifyWorkspace(engine, ws, opts);
+ expect(check(second.checks, 'roundtrip').filter((c) => !c.ok)).toEqual([]);
+ } finally {
+ await engine.executeRaw(`DROP TRIGGER IF EXISTS w6634_keep ON page_purges`);
+ await engine.executeRaw(`DROP FUNCTION IF EXISTS w6634_keep()`);
+ await engine.executeRaw(`DROP TABLE IF EXISTS w6634_kept`);
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ }, 240_000);
+});
+
describe('bootstrap verify write wait (#6356)', () => {
test('the probe ctx waits as long as a CLI write: 30 s by default, GBRAIN_WRITE_WAIT_MS when set', async () => {
const verify = await import('../src/core/bootstrap/verify.ts') as Record<string, unknown>;