Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs(facts): name the unmanaged path where pre-v0.60.218.0 adoption could publish a private fact as world; add its regression test

garrytan16b096970b23
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0b25740770..9a7100be5d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,15 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**The v0.60.218.0 notes now say where a private fact could become world.** Before v0.60.218.0, fencing a legacy fact into a leftover fence row with a different visibility was refused on a managed brain. An unmanaged brain had no such check, so a private fact could be published as world, in the page file and in the database. The `BEHAVIOR_CHANGES` row and `docs/guides/write-refusals.md#fence_unrenderable` claimed the refusal held everywhere; both now describe the two paths. Code is unchanged: v0.60.218.0 already closed the unmanaged path.
+
+### Itemized changes
+
+- **Docs**: the v0.60.218.0 fact-fence row in `src/core/behavior-change-notice.ts` (wording only) and the `fence_unrenderable` entry in `docs/guides/write-refusals.md` name the unmanaged path.
+- **Regression test**: `test/fact-fence-adoption-exits.test.ts` covers an unmanaged brain (PGLite and Postgres): a leftover world cell plus a private legacy fact with the same claim and source keeps the fact private in the file and the database after `extract_facts`. It fails on the build before v0.60.218.0 and passes now.
+
## [0.60.232.0] - 2026-10-14
**MCP `list_write_conflicts` refuses a source outside the caller's grant and bounds its window to that source's own requests (#6643 follow-up).** A remote caller that named a source outside its grant used to get an empty report back. The response's `window` sequences were also brain-wide, so polling one granted source showed write activity in sources the caller cannot see. Both were found by GBRA-60's D5 agent smoke.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index b92e854ea5..cddbb4f594 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -84,7 +84,7 @@ of making a duplicate.
| <a id="purge_lookup_timeout"></a>`purge_lookup_timeout` | `purge_lookup_timeout` | A page purge (`gbrain delete <slug> --purge`) ran one of the journal lookups that still execute inside its publication transaction (the lookup of stored intents for the slug, the re-check of requests admitted after its preparation scan or pending at that scan, the locking read of the requests to redact) and that statement hit the transaction's 5-second statement budget on a large `persistence_requests` table. The request failed terminally instead of being released as `database_contention` and claimed again: nothing of the page was removed or tombstoned, nothing in the journal was redacted, and later writes to the source move again. Do not assume the requested content was erased. The substring search for the page's claims no longer runs here: it runs at preparation in bounded keyset chunks under the preparation budget, and a sweep that outruns that budget twice ends [`preparation_stalled`](#preparation_stalled) instead. A committed purge's receipt reports `journal_sweep` (`scanned`, `ceiling`, `tail`, `pending_rechecked`, `complete`); `complete: false` means a cap was hit (the 10,000-match cap or the tail bound) and some requests were not tested. | If the receipt says the slug index `persistence_requests_slug_intent` is missing or INVALID, run `gbrain repair request-indexes --apply` (the `persistence_request_slug_intent_index` migration builds it online; the index serves the slug lookup, not the substring sweep), then submit the purge again with a new `request_id`. Otherwise submit it again with a new `request_id` (a retry with the same id returns this failure); if it times out again, report the request id with the `persistence_request_indexes` and `persistence_request_growth` entries of `gbrain doctor --json`. |
| <a id="preparation_stalled"></a>`preparation_stalled` | `preparation_stalled` | The write's owner could not finish *preparing* it. Every write has a preparation budget (`persistence.sync_preparation_ms` for a managed sync member, `persistence.maintenance_preparation_ms` for every other managed kind, 120 s each; `remember`, `put_page` and `edit_page` keep 30 s), the owner releases the claim at the budget and tries again, and a request cut off `persistence.max_preparation_attempts` times (default 2; a process killed mid-preparation counts too) is finished `failed` with this code instead of being claimed again and holding the rest of its root. The receipt names the last recorded step and what it was waiting on (`git`, `fs`, `db`, `pool` or `unknown`); while the write was still running, `gbrain sources writer status --json` showed the same on `claim.stall` (`preparation_overdue`). The rest of the root keeps publishing. A **managed sync member** (an import, delete or rename of a file) is also **held**: the sync turns the failed receipt into a `preparation_stalled` hold and carries on, so the file is not imported until it is retried. The file is fine; this is the write owner stalling (a database or pool wait, a hung step), never a frontmatter or fence problem, so no repair applies. The hold's `message` names the request and the step; a held deletion keeps its page. A stalled hold re-screens by itself only when the gbrain version changes; a run that stalls many files in a row stops with [`preparation_systemic`](#preparation_systemic) instead of holding them all. A **foreground write** (`put_page`, `edit_page`, `remember`) or a **maintenance write** (fact-fence adoption, maintenance page writes) gets the terminal receipt only. The deadlines sit behind `persistence.preparation_deadlines` (`false` restores the old behaviour, where only `remember`, `put_page` and `edit_page` had a 30 s budget). | Run `gbrain sources writer status --source <source> --json` (read-only: the step, its wait cause, the owner process and its gbrain version), fix what it names (restart or upgrade an owner that predates deadlines, free the pool, let the lock holder finish), then for a sync hold run `gbrain sources retry-held <source>` and the same `gbrain sync` with the same options (the hold's `fix.then.then` and `retry-held` print it, for example `gbrain sync --source <source> --no-pull --no-embed`). When that sync still has a backlog to finish, it finishes it first and re-screens the scheduled files in the same invocation (the drain yields at the checkpoint and discovers again), so one run of the printed command clears the hold. A foreground write needs a new `request_id`; the next maintenance run submits its write again. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). |
| <a id="write_outcome_unknown"></a>`write_outcome_unknown` | `write_outcome_unknown` | The database session dropped while the write was being admitted (a pooler reap, a failover, `pg_terminate_backend`), and it kept dropping through the re-reads, so whether the write was accepted is unknown (#6355). A single drop never reaches you: the admission attempt is re-run after 100, 300 and 900 ms, and every attempt begins by reading the retained `request_id`, so a re-run replays an admitted row instead of admitting again. Before this code existed the raw socket error (`write CONNECTION_CLOSED …`, `57P01`) reached the caller while the write went on to commit, and a receipt oracle took it for a refusal. | Read the request first: `gbrain write-request -- <request_id>` or `get_write_request { request_id }` (the error's `fix` names it). A committed or pending row means the write was accepted: replay the same `request_id` to wait for it. No row means it was not: submit it again with the same `request_id`. Never resubmit under a new `request_id` without that read. |
-| <a id="fence_unrenderable"></a>`fence_unrenderable` | `fence_unrenderable` | A legacy fact row (an active `facts` row with no fence row number) was not adopted into its page's `## Facts` fence because the fence codec reads the rendered row back as something other than the stored fact: a whitespace-only claim comes back empty, `~~x~~` comes back struck, a literal `<br>` comes back as a line break, or another column changes. Surrounding whitespace and CRLF line endings are the one accepted difference: such a row is adopted and `facts.fact` takes the fence's text. A second legacy row whose normalized claim, source and visibility the page already carries is left too (`duplicate_claim`; a private and a world row with one text are two facts and both adopt). The cycle and the v0.32.2 migration print `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)`; doctor `fence_integrity` lists the pages, fact ids and reason classes under `unrenderable_legacy_facts` (never the claim text). The same code refuses a planned adoption whose rendered fence does not read back as its facts; that is a gbrain planning defect, not caller input. The planner runs the publisher's own read-back check on the whole rendered fence first, so such a page is reported as unadoptable (class `whole_fence`) instead of being submitted. A managed adoption refused in the last day is not resubmitted: the cycle reports it as class `prior_refusal` with the refused request id (`gbrain write-request -- <id>` reads it), and a direct `submitFactFenceAdoption` call refuses with `The same fact-fence adoption was already refused.`. It is retried a day after the refusal, or at once by a build whose adoption planner revision changed. Unadopted rows hold only their own page: the phantom-redirect pass skips a phantom that owns one and redirects the others. To count what an older build left in the writer table, run the read-only `scripts/diagnose/fence-adoption-census.sql` on the brain host against the brain's Postgres database (its header shows the `psql` command). | Nothing to fix in the page: the rows stay active and searchable, nothing is lost, and their pages skip destructive fact reconciliation until the rows are adopted. Report the pages and reason classes with the gbrain version. Never `forget_fact` a row to clear the count. |
+| <a id="fence_unrenderable"></a>`fence_unrenderable` | `fence_unrenderable` | A legacy fact row (an active `facts` row with no fence row number) was not adopted into its page's `## Facts` fence because the fence codec reads the rendered row back as something other than the stored fact: a whitespace-only claim comes back empty, `~~x~~` comes back struck, a literal `<br>` comes back as a line break, or another column changes. Surrounding whitespace and CRLF line endings are the one accepted difference: such a row is adopted and `facts.fact` takes the fence's text. A second legacy row whose normalized claim, source and visibility the page already carries is left too (`duplicate_claim`; a private and a world row with one text are two facts and both adopt). The cycle and the v0.32.2 migration print `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)`; doctor `fence_integrity` lists the pages, fact ids and reason classes under `unrenderable_legacy_facts` (never the claim text). The same code refuses a planned adoption whose rendered fence does not read back as its facts; that is a gbrain planning defect, not caller input. The planner runs the publisher's own read-back check on the whole rendered fence first, so such a page is reported as unadoptable (class `whole_fence`) instead of being submitted. A managed adoption refused in the last day is not resubmitted: the cycle reports it as class `prior_refusal` with the refused request id (`gbrain write-request -- <id>` reads it), and a direct `submitFactFenceAdoption` call refuses with `The same fact-fence adoption was already refused.`. It is retried a day after the refusal, or at once by a build whose adoption planner revision changed. Unadopted rows hold only their own page: the phantom-redirect pass skips a phantom that owns one and redirects the others. Before v0.60.218.0 the planner could reuse a leftover fence row (one with no database owner) whose visibility differed from the legacy fact's. On a managed brain the publisher refused that page here every cycle, so no private fact was published as world. An unmanaged brain had no such check: it fenced the fact into the leftover row, and the same cycle's reconcile copied that row's visibility into the fact, so a private fact could become world. The current planner never reuses a leftover row for a fact with a different visibility unless the fact is private, and re-renders a reused row from the fact. To count what an older build left in the writer table, run the read-only `scripts/diagnose/fence-adoption-census.sql` on the brain host against the brain's Postgres database (its header shows the `psql` command). | Nothing to fix in the page: the rows stay active and searchable, nothing is lost, and their pages skip destructive fact reconciliation until the rows are adopted. Report the pages and reason classes with the gbrain version. Never `forget_fact` a row to clear the count. |
| <a id="reconcile-private-facts"></a>reconcile private facts | `permission_denied` | `gbrain sources reconcile --apply` (and its preview) found a `## Facts` row that would edit, renumber or change the visibility of a stored private fact, copy a stored private claim into a row under another visibility, or copy a stored private row's context (24 characters or longer) verbatim into a world row. A row is identified by its row number and claim, so a world row that only shares a private row's claim is not a private row and publishes. The refusal names the row number, never its text. It guards against verbatim copies only; reworded text is not detected, so it is not a confidentiality proof. Sources are not compared, because rows share provenance such as "Slack import". Nothing was written. | Read the stored page with the printed `gbrain get --source <id> -- <slug>`, keep the named row as stored in the file (or remove the copied text), then run a fresh `gbrain sources reconcile <id> <slug> --preview` and apply it. Change private facts with `remember` and `forget`. |
| <a id="maintenance_backpressure"></a>`maintenance_backpressure` (exit 12) | `maintenance_backpressure` | A managed maintenance run (`gbrain extract-conversation-facts`, its cycle phase or job) publishes each page as its own request, under the same local CLI writer your own CLI writes use. Before the run it counts the requests the whole run plans; before each page's model work it checks again. It stops admitting once the writer's outstanding requests, reserved receipt bytes (`persistence.limits.principal_terminal_bytes`; each request reserves 16 KiB until its receipt compacts after the retention window) or permanent request ids (`persistence.limits.principal_lifetime_ids`; never freed) would pass 80% of their limit, so the last 20% stays free for your other writes. The message names the resource. Pages already published keep their facts and nothing is half-written. | Outstanding requests: read them with `gbrain sources writer status --source <id> --json`; a resident `gbrain serve`, or the next CLI run, publishes them, then rerun the same command. Receipt bytes or request ids: run the smaller batch the message prints (`gbrain extract-conversation-facts --source-id <id> --limit <n>`), or wait for receipts to compact; raising the named `persistence.limits.*` key is the user's call. |
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index f0b507223e..eb9870825f 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -548,7 +548,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.232.0', text: 'MCP `list_write_conflicts` now refuses a `source_id` outside the caller\'s grant with `permission_denied` (whether or not the source exists), like other source-scoped reads, instead of returning an empty report; its `window` sequences end at the source\'s own newest request (current incarnation) instead of the brain-wide newest, so they no longer reflect writes in other sources.' },
{ since: '0.60.217.0', text: 'Doctor has a new `maintenance_write_drift` check: it warns when pages behind recent `file_database_drift` conflict receipts (or recorded concept skips) still have a canonical file that differs from the database, and names the read-only `--audit --conflicts` listing and the explicit-only `gbrain repair file-drift` preview. New: `gbrain sources reconcile <source> --audit --conflicts`, MCP `list_write_conflicts` (read scope; database-derived fields only for remote callers) and `gbrain repair file-drift --prefer file|database`.' },
// #6650 (fact-fence adoption exits). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
- { since: '0.60.218.0', text: 'Fencing a legacy fact into a fence row a partial earlier run left behind now rebuilds that row from the stored fact: the published row carries the fact\'s own visibility, kind, validity, confidence and speaker attribution instead of the leftover cell\'s, a leftover private row is never reused for a world fact (the world fact gets its own row), and a newly fenced fact keeps its `attributed_to`. Before, a leftover row with a different visibility made the adoption refuse every time, a leftover row with the same visibility overwrote the fact\'s kind, dates and confidence, and every adoption cleared the fact\'s speaker attribution.' },
+ { since: '0.60.218.0', text: 'Fencing a legacy fact into a fence row a partial earlier run left behind now rebuilds that row from the stored fact: the published row carries the fact\'s own visibility, kind, validity, confidence and speaker attribution instead of the leftover cell\'s, a leftover private row is never reused for a world fact (the world fact gets its own row), and a newly fenced fact keeps its `attributed_to`. Before, a leftover row with a different visibility made a managed adoption refuse every time, while an unmanaged brain fenced the fact into that row and the reconcile gave the fact the leftover row\'s visibility (a private fact could become world); a leftover row with the same visibility overwrote the fact\'s kind, dates and confidence, and every adoption cleared the fact\'s speaker attribution.' },
{ since: '0.60.218.0', text: 'A managed fact-fence adoption refused as a planning defect (`fence_unrenderable`) is no longer resubmitted every cycle: for a day after the refusal the page is reported as unadoptable (`prior_refusal`), then it gets one more try, or right away once the adoption planner changes. The writer stops collecting one identical failed request per page per cycle.' },
{ since: '0.60.218.0', text: 'The `extract_facts` phantom-redirect pass no longer waits for the whole source to have no unfenced legacy fact rows: it holds only the top-level pages that own such rows or are the provenance page of an ontology observation (`phantoms_held_legacy_rows` in the cycle report), and redirects the rest.' },
// Cat 41 run 4 (GBRA-60). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
diff --git a/test/fact-fence-adoption-exits.test.ts b/test/fact-fence-adoption-exits.test.ts
index 459b6731b1..f2b25060cb 100644
--- a/test/fact-fence-adoption-exits.test.ts
+++ b/test/fact-fence-adoption-exits.test.ts
@@ -5,7 +5,10 @@
* - A leftover fence cell the adoption reuses is re-rendered from the legacy
* row, so a stale world cell never publishes a private legacy fact as world
* and a stale cell never overwrites the fact's kind or validity; a private
- * cell is never widened to world (the world row appends instead).
+ * cell is never widened to world (the world row appends instead). On an
+ * unmanaged brain (no publisher read-back before #6650) the old planner
+ * fenced a private fact into a leftover world cell and the reconcile made
+ * the fact world in the database too.
* - Planner and publisher share one read-back predicate.
* - A deterministic refusal of the same intent is not resubmitted within a
* day, so cycles stop minting identical failed requests; a day later, or a
@@ -15,7 +18,8 @@
* - One unadoptable legacy row no longer stops the phantom-redirect pass for
* the whole source; only a phantom that owns legacy rows is held.
* Seams: planFence against an engine stub, the managed-brain helper for the
- * coordinator path, PGLite for the extract_facts cycle.
+ * coordinator path, PGLite for the extract_facts cycle, and an unmanaged
+ * brain with a source checkout (PGLite and Postgres) for the file path.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
@@ -36,6 +40,8 @@ import { requirePostgresTestDatabase, testBackends } from './helpers/test-backen
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { withEnv } from './helpers/with-env.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { managedPersistenceEnabled } from '../src/core/persistence/ownership.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
const SLUG = 'people/alice-example';
@@ -279,3 +285,42 @@ describe('extract_facts: an unadoptable row holds only its own phantom (#6650)',
});
});
});
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ test(`${backend}: unmanaged: a leftover world cell does not make a private legacy fact world (file or database)`, async () => {
+ const claim = 'Alice example has a private appointment';
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'fence-adoption-unmanaged-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ expect(await managedPersistenceEnabled(engine)).toBe(false);
+ const brainDir = path.join(home, 'brain');
+ fs.mkdirSync(brainDir, { recursive: true });
+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [brainDir]);
+ const page = await engine.putPage(SLUG, { type: 'person', title: 'Alice Example',
+ compiled_truth: pageWithLeftover({ rowNum: 1, claim, confidence: 1, validFrom: '2026-03-01' }) });
+ await engine.executeRaw('UPDATE pages SET source_path = $1 WHERE id = $2', [`${SLUG}.md`, page.id]);
+ // Cell 1 is a leftover: no database row owns it.
+ await engine.executeRaw('DELETE FROM facts WHERE source_id = $1 AND source_markdown_slug = $2', ['default', SLUG]);
+ const snapshot = (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!;
+ const file = path.join(brainDir, `${SLUG}.md`);
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, serializePageToMarkdown(snapshot.page, snapshot.tags));
+ const [legacy] = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence)
+ VALUES ('default', $1, $2, 'fact', 'private', 'medium', '2026-03-01', 'mcp:remember', 1.0) RETURNING id`, [SLUG, claim]);
+
+ const result = await runExtractFacts(engine, { sourceId: 'default', brainDir });
+ expect(result.unfencedRowsFenced).toBe(1);
+ expect(await engine.executeRaw('SELECT id, visibility, row_num FROM facts WHERE source_id = $1 AND fact = $2 AND expired_at IS NULL ORDER BY id',
+ ['default', claim])).toEqual([{ id: legacy.id, visibility: 'private', row_num: 1 }]);
+ expect(parseFactsFence(fs.readFileSync(file, 'utf8')).facts.filter(f => f.claim === claim).map(f => [f.rowNum, f.visibility]))
+ .toEqual([[1, 'private']]);
+ } finally { await close(); }
+ });
+ } finally { fs.rmSync(home, { recursive: true, force: true }); }
+ }, 120_000);
+}