Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Drop restated owner-held takes from proposals and scan quoted fences in the atom repair

garrytanb051e247fd04
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0c8d2a60fd..35102dd759 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,7 +17,7 @@ identifiers and attribution are available in the pre-removal Git revision
### Itemized changes
- `src/core/cycle/extract-atoms-input.ts`: a page's extraction input is its `publicBody` (facts rows other than world and the takes fence removed); the cap, the watermark and quote verification apply to that text, on the cycle phase and the managed path alike.
-- `src/core/cycle/propose-takes.ts`: the extractor receives the page's `publicBody`; the content hash, fence skip and dedup rows still read the stored body.
+- `src/core/cycle/propose-takes.ts`: the extractor receives the page's `publicBody`, and a proposal that restates a take held by someone other than `world` is dropped before it is filed; the content hash, fence skip and dedup rows still read the stored body.
- `src/core/cycle/patterns.ts`: reflection excerpts in the subagent prompt and the quote-grounding sources are the reflection's `publicBody`.
- `src/core/repair/atom-fence-rows.ts` (new, registered in `repair/core.ts`, `repair/registry.ts`, `persistence/preview-approval.ts`): explicit-only, preview-bound kind; the preview lists each world atom with its source page and the row kinds and numbers it carries (never the row text) and changes nothing; the apply sets `visibility: private` on exactly the previewed set through a revision-bound put_page.
- `src/commands/doctor/checks/atom-fence-rows.ts` (new, a host-only `WAVE_CHECKS` entry, BRAIN category): `atom_fence_rows` warns with the count per source and the preview command.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index df24feef58..c5f6d10ac7 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -1995,8 +1995,9 @@ gbrain repair atom-fence-rows --source <id> --apply --expect <hash>
An atom is listed when it is live, page-bound (`source_slug`), stamped
`visibility: world`, and its title, body or `source_quote` contains (case and
-whitespace folded) the claim of such a row of its live source page, unless the
-page's world text holds the same claim too. Claims shorter than 12 characters
+whitespace folded) the claim of such a row in any fence of its live source page
+a world reader does not see (a fence quoted in a code block included), unless
+the page's world text holds the same claim too. Claims shorter than 12 characters
are not matched. The preview names each atom with its source page and the
rows (`facts row 2`, `takes row 1`), never the row text, and changes nothing.
A source page stored in segments is not read: its world atoms are counted as
diff --git a/llms-full.txt b/llms-full.txt
index b8356e3356..1eae7e3049 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5053,7 +5053,7 @@ off until the user opts in, and paid enrichment is a separate choice.
| "harvest this skill into gbrain", "publish this skill to gbrain", "lift this skill upstream", "share this skill with other gbrain clients", "promote my skill to gbrain" | `skills/skillpack-harvest/SKILL.md` |
| Post-restart health + auto-fix, "did the container restart break anything", smoke test | `skills/smoke-test/SKILL.md` |
| `GBRAIN_DB_ACCESS`, "gbrain database error", "gbrain connection refused", "brain database is down", "cannot reach the brain database", "fix gbrain database access", "repair gbrain postgres" | `skills/db-repair/SKILL.md` |
-| Doctor `timeline_history` / `derived_visibility` / unsealed pages, "repair timeline history", "fix atom visibility", "re-seal withheld pages" | Preview with `gbrain repair`, apply one kind with `gbrain repair <kind> --apply` on the brain host after the user agrees. See `docs/guides/repair.md` |
+| Doctor `timeline_history` / `derived_visibility` / `atom_fence_rows` / unsealed pages, "repair timeline history", "fix atom visibility", "re-seal withheld pages" | Preview with `gbrain repair` (or `gbrain repair <kind>` for an explicit-only kind), apply one kind with the `--apply` command its preview prints, on the brain host after the user agrees. See `docs/guides/repair.md` |
| A page write refused `owner_unavailable` with `detail: unbound_source` (classic Postgres) | Write the file, commit, `gbrain sync --source <id>` (remote: relay to the user); never claim or activate to get one write through. See `skills/conventions/agent-operator-protocol.md` |
| A write or sync refused with `file_database_drift`, `ambiguous_source_path`, `physical_root_device_changed`, `cursor_processing_options_conflict`, `take_row_collision`, `invalid_source_uri`, `queue_capacity`, or doctor `parked_effects` | Relay the error's `suggestion` command; see `docs/guides/write-refusals.md` before running it |
| A gbrain command or MCP tool returned an error, exited 3 (`confirmation_required`), 10 or 11, or printed `[AGENT]` / a notice block; "what does this error code mean" | Follow the agent operator protocol, `docs/protocol/AGENT_OPERATOR_v1.md` (read `code`, follow `fix.next`); look a code up offline with `gbrain errors <code>` |
diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.ts
index fe0dc4aa90..df5c26a2c8 100644
--- a/src/core/cycle/propose-takes.ts
+++ b/src/core/cycle/propose-takes.ts
@@ -1068,6 +1068,9 @@ class ProposeTakesPhase extends BaseCyclePhase {
failures.succeed(sourceId, page.slug, ch);
llmHalt.reset();
if (attributionChecks) proposals = downgradeAssistantOnlyHolders(proposals, body);
+ const fold = (text: string) => text.replace(/\s+/g, ' ').trim().toLowerCase();
+ const heldTakes = existingTakes.filter(take => take.holder !== 'world').map(take => fold(take.claim)).filter(claim => claim.length >= 12);
+ proposals = proposals.filter(p => !heldTakes.some(claim => fold(p.claim_text).includes(claim)));
// Write proposals to take_proposals. #2138: the idempotency key is
// per-CLAIM — take_proposals_idempotency_idx folds md5(claim_text) into
diff --git a/src/core/repair/atom-fence-rows.ts b/src/core/repair/atom-fence-rows.ts
index 2fd74f04cf..860ed1e350 100644
--- a/src/core/repair/atom-fence-rows.ts
+++ b/src/core/repair/atom-fence-rows.ts
@@ -22,8 +22,9 @@
* The same scan backs doctor's `atom_fence_rows` check.
*/
import type { BrainEngine } from '../engine.ts';
-import { parseFactsFence } from '../facts-fence.ts';
-import { parseTakesFence } from '../takes-fence.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from '../facts-fence.ts';
+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence } from '../takes-fence.ts';
+import { protectedRegions } from '../fence-scan.ts';
import { publicBody } from '../mentions/aliases.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { OperationError } from '../ops/contract.ts';
@@ -51,12 +52,21 @@ interface ScanOptions { atomId?: number; timeoutMs?: number }
const fold = (text: string) => text.replace(/~~/g, '').replace(/\s+/g, ' ').trim().toLowerCase();
+/** Every fence publicBody removes (one quoted in a code block and an unterminated tail included), each closed for parsing. */
+function fenceRegions(body: string, begin: string, end: string): string[] {
+ const { regions, truncatedAt } = protectedRegions(body, [{ begin, end }]);
+ const texts = regions.map(region => body.slice(region.start, region.end));
+ return truncatedAt === -1 ? texts : [...texts, `${body.slice(truncatedAt)}\n${end}`];
+}
+
/** Claims of the page's facts rows other than world and takes rows held by someone other than world, absent from its world text. */
function hiddenRows(body: string): Array<HiddenRowMatch & { claim: string }> {
const world = fold(publicBody(body));
const rows = [
- ...parseFactsFence(body).facts.filter(f => f.visibility !== 'world').map(f => ({ kind: 'facts' as const, row: f.rowNum, claim: fold(f.claim) })),
- ...parseTakesFence(body).takes.filter(t => t.holder !== 'world').map(t => ({ kind: 'takes' as const, row: t.rowNum, claim: fold(t.claim) })),
+ ...fenceRegions(body, FACTS_FENCE_BEGIN, FACTS_FENCE_END).flatMap(text => parseFactsFence(text).facts)
+ .filter(f => f.visibility !== 'world').map(f => ({ kind: 'facts' as const, row: f.rowNum, claim: fold(f.claim) })),
+ ...fenceRegions(body, TAKES_FENCE_BEGIN, TAKES_FENCE_END).flatMap(text => parseTakesFence(text).takes)
+ .filter(t => t.holder !== 'world').map(t => ({ kind: 'takes' as const, row: t.rowNum, claim: fold(t.claim) })),
];
return rows.filter(r => r.claim.length >= MIN_CLAIM_CHARS && !world.includes(r.claim));
}
diff --git a/test/cycle-world-fence-rows.test.ts b/test/cycle-world-fence-rows.test.ts
index ebe28dcd6e..434aaf2174 100644
--- a/test/cycle-world-fence-rows.test.ts
+++ b/test/cycle-world-fence-rows.test.ts
@@ -39,9 +39,10 @@ for (const backend of testBackends()) {
test('propose_takes: the extractor input and the proposals hold only world rows', async () => {
const bodies: string[] = [];
- const extractor: ProposeTakesExtractor = async ({ pageBody }) => {
+ const extractor: ProposeTakesExtractor = async ({ pageBody, existingTakes }) => {
bodies.push(pageBody);
- return [WORLD_ROW, PRIVATE_ROW, HIDDEN_TAKE_ROW].filter(row => pageBody.includes(row))
+ const seen = `${pageBody}\n${JSON.stringify(existingTakes)}`;
+ return [WORLD_ROW, PRIVATE_ROW, HIDDEN_TAKE_ROW].filter(row => seen.includes(row))
.map(row => ({ claim_text: row, kind: 'take' as const, holder: 'world', weight: 0.6 }));
};
const ctx: OperationContext = { engine, config: {} as never, logger: { info() {}, warn() {}, error() {} } as never, dryRun: false, remote: false, sourceId: 'default' };
diff --git a/test/repair-atom-fence-rows.test.ts b/test/repair-atom-fence-rows.test.ts
index 03743427d3..d738adc12c 100644
--- a/test/repair-atom-fence-rows.test.ts
+++ b/test/repair-atom-fence-rows.test.ts
@@ -24,7 +24,7 @@ import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
import { withEnv } from './helpers/with-env.ts';
import { managedBrain } from './helpers/managed-brain.ts';
-import { HIDDEN_TAKE_ROW, PRIVATE_ROW, WORLD_PAGE_BODY, WORLD_ROW } from './helpers/world-fence-page.ts';
+import { FENCES, HIDDEN_TAKE_ROW, PRIVATE_ROW, WORLD_PAGE_BODY, WORLD_ROW } from './helpers/world-fence-page.ts';
interface RepairJson { results: Array<{ affected: number; residuals: Record<string, number>; apply_command: string; applied: number; skipped: number;
listing?: Array<{ item: string; class: string; detail?: string }>; outcomes?: Record<string, number> }> }
@@ -128,6 +128,22 @@ for (const kind of testBackends()) {
expect((await atomFenceRowsCheck(engine, [sourceId])).status).toBe('ok');
expect((await repair([])).results[0]!.listing ?? []).toEqual([]);
}, 120_000);
+
+ test('a fence quoted in a code block counts as hidden, as it does for a world reader', async () => {
+ const quotedOrigin = 'notes/launch-review-quoted';
+ const quotedAtom = 'atoms/2026-01-01/renewal-terms-quoted';
+ await engine.putPage(quotedOrigin, { type: 'note', title: 'Launch review quoted', compiled_truth: `# Launch review\n\n\`\`\`markdown\n${FENCES}\`\`\`\n`, timeline: '' }, { sourceId });
+ await putAtom(quotedAtom, `Recorded on the page: ${PRIVATE_ROW}.`, { source_slug: quotedOrigin });
+ expect(await remoteGet(quotedOrigin)).not.toContain(PRIVATE_ROW);
+
+ const finding = await atomFenceRowsCheck(engine, [sourceId]);
+ expect(finding.status).toBe('warn');
+ expect(finding.details).toMatchObject({ count: 1 });
+ const listing = (await repair([])).results[0]!.listing!;
+ expect(listing.map(row => ({ item: row.item, class: row.class, detail: row.detail }))).toEqual([
+ { item: `${sourceId}:${quotedAtom}`, class: 'facts', detail: `source page ${quotedOrigin}: facts row 2` },
+ ]);
+ }, 120_000);
test('managed brain: the apply narrows the previewed atom through the coordinator', async () => {
await managedBrain(async ({ engine: brain }) => {
const run = async (args: string[]): Promise<RepairJson> => {