Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(takes): refuse a malformed holder at the write boundary and round-trip every published fence (#6450)

garrytan394bbb9973ef
diff --git a/docs/architecture/key-files/hindsight.md b/docs/architecture/key-files/hindsight.md
index 9b6d1a6838..62e42b6862 100644
--- a/docs/architecture/key-files/hindsight.md
+++ b/docs/architecture/key-files/hindsight.md
@@ -33,7 +33,7 @@ unresolvable+true|false, pre-v80 NULL/NULL rows survive).
- `src/core/think/prompt.ts` — anti-bias prompt shaping. `withCalibration` option on `buildThinkSystemPrompt` adds anti-bias rules. `buildCalibrationBlock()` emits the `<calibration>` XML. `buildThinkUserMessage` has TWO shapes: default (question first), and with-calibration (retrieval → calibration → question) when opt-in. Wired into `runThink` via `opts.withCalibration` + `opts.calibrationHolder`.
- `src/commands/calibration.ts` — CLI: `gbrain calibration` (read + print), `--regenerate`, `--undo-wave <ver>`, `ab-report`. MCP op `get_calibration_profile` (scope: read) backs the same data path. Source-scoped via `sourceScopeOpts(ctx)`.
- `src/core/owner-holder.ts` — single source of truth for "the brain owner" holder string. `DEFAULT_OWNER_HOLDER = 'self'` (matches the consolidate facts→takes writer + `docs/takes-vs-facts.md`); `resolveOwnerHolder({override, configValue})` returns override > `emotional_weight.user_holder` config > `'self'`. Consumed by the calibration_profile cycle phase, `gbrain calibration` CLI, the `get_calibration_profile` op, `think`'s calibration block, `emotional-weight`'s `DEFAULT_USER_HOLDER`, and doctor's `calibration_freshness`. Pure; unit-tested in `test/owner-holder.test.ts`. Does NOT unify owner-identity fragmentation (`self`/`brain`/`people-<owner>`) — tracked separately.
-- `src/commands/takes.ts` — the full `gbrain takes` subcommand dispatcher (list/search/embed/add/update/supersede/resolve/propose/scorecard/calibration/extract/revisit). `takes list --limit N --offset N` validates integers at the CLI; the engine clamps limit (default 100, cap 500) and floors offset at 0. `takes revisit <slug>` opens $EDITOR on the source page with a `<!-- gbrain:revisit -->` cursor marker. #5167: `takes remove <slug> --row N` goes through `takes-mutation.ts` to the local-only `takes_remove` op (persistence `takes-prepare.ts`): the row leaves the takes table and its fence row becomes a reservation row (`| N | ~~(removed)~~ | take | world | 0.0 | | removed |`, W9F item 4) in one coordinated publication, other row numbers stay, and a resolved row, a row another row cites as "superseded by" it, or a row whose DB claim disagrees with the fence is refused (the last names `takes rebuild`); thin clients are refused. Reservations: `parseTakesFence` returns them in `reservedRowNums`, never in `takes`, so no reader or projection sees a take there; `renderTakesFence(takes, reservedRowNums)` puts them back in row order, and `upsertTakeRow`, `supersedeRow` and `takesPreparation.replaceFence` keep the reservations of the body they rewrite. Every new take row number comes from GBRA-54's `nextFreeRowNum` (`fence-repair/normalize.ts`): one more than every fence row on the page (facts and takes, live, struck and reserved) and, in `takes-prepare.ts`, every stored facts/takes row (`storedFenceRows`), revalidated under the publication lock; the promise holds while the reservation row exists. `test/takes-row-reservation.test.ts` (both engines), `test/takes-reservation-callers.test.ts` (census of `parseTakesFence` callers). `takes rebuild <slug> [--source-id]` runs the local-only `takes_rebuild` op (W9F item 8; `runTakesRebuild` in `takes-mutation.ts`, delegated to a resident `gbrain serve` owner over persistence IPC, else the local engine, with the same JSON, warnings and exit 1 on a missing page or a warning), which calls `extractTakes({source:"db", slugs:[slug], sourceId, rebuild:true})`, whose rebuild now deletes only indexed rows whose (row_num, claim) left the fence, so matching rows keep resolutions and vectors. The v0_28_0 hint names `gbrain reindex --markdown` instead of the nonexistent `extract takes --rebuild`.
+- `src/commands/takes.ts` — the full `gbrain takes` subcommand dispatcher (list/search/embed/add/update/supersede/resolve/propose/scorecard/calibration/extract/revisit). `takes list --limit N --offset N` validates integers at the CLI; the engine clamps limit (default 100, cap 500) and floors offset at 0. `takes revisit <slug>` opens $EDITOR on the source page with a `<!-- gbrain:revisit -->` cursor marker. #5167: `takes remove <slug> --row N` goes through `takes-mutation.ts` to the local-only `takes_remove` op (persistence `takes-prepare.ts`): the row leaves the takes table and its fence row becomes a reservation row (`| N | ~~(removed)~~ | take | world | 0.0 | | removed |`, W9F item 4) in one coordinated publication, other row numbers stay, and a resolved row, a row another row cites as "superseded by" it, or a row whose DB claim disagrees with the fence is refused (the last names `takes rebuild`); thin clients are refused. Reservations: `parseTakesFence` returns them in `reservedRowNums`, never in `takes`, so no reader or projection sees a take there; `renderTakesFence(takes, reservedRowNums)` puts them back in row order, and `upsertTakeRow`, `supersedeRow` and `takesPreparation.replaceFence` keep the reservations of the body they rewrite. Every new take row number comes from GBRA-54's `nextFreeRowNum` (`fence-repair/normalize.ts`): one more than every fence row on the page (facts and takes, live, struck and reserved) and, in `takes-prepare.ts`, every stored facts/takes row (`storedFenceRows`), revalidated under the publication lock; the promise holds while the reservation row exists. #6450: `takes_add` and an explicit `takes_supersede` holder override are trimmed and checked with `isValidHolder` at the write boundary (syntax before authority: `invalid_params` naming the grammar, before `assertHolderAllowed`); the inherited supersede holder is not re-validated (the existing fence already round-tripped). Every prepared takes fence is parsed again before publication and refused `invalid_params` on any warning, so no write can leave a fence the next write would refuse. Test: `test/takes-holder-validation-6450.test.ts`. `test/takes-row-reservation.test.ts` (both engines), `test/takes-reservation-callers.test.ts` (census of `parseTakesFence` callers). `takes rebuild <slug> [--source-id]` runs the local-only `takes_rebuild` op (W9F item 8; `runTakesRebuild` in `takes-mutation.ts`, delegated to a resident `gbrain serve` owner over persistence IPC, else the local engine, with the same JSON, warnings and exit 1 on a missing page or a warning), which calls `extractTakes({source:"db", slugs:[slug], sourceId, rebuild:true})`, whose rebuild now deletes only indexed rows whose (row_num, claim) left the fence, so matching rows keep resolutions and vectors. The v0_28_0 hint names `gbrain reindex --markdown` instead of the nonexistent `extract takes --rebuild`.
- `src/core/extract-takes-from-pages.ts` — bootstrap extraction selects uncovered pages newest first. Managed pages capture their revision before classification and publish the complete appended takes fence through coordinated `put_page`, whose canonical projection commits the takes rows with the page; conflicts skip that page. Unmanaged pages retain the md-first writer. Pinned by `test/persistence-managed-takes-extract.test.ts` and `test/extract-takes-md-first.test.ts`. `takes extract --before <updated_at>,<id>` (CLI-only) continues strictly below a prior run's `next_before`, an `(updated_at, id)` keyset with exact timestamptz text, so zero-claim pages no longer starve older ones; a budget stop resumes at the first unclassified page, a failed page stays uncovered for the next run without `--before`, and a malformed cursor is an exit-2 `invalid_params` refusal before any page is read. Pinned by `test/extract-takes-from-pages-progression.test.ts`, `test/takes-extract-json.test.ts` and `test/e2e/takes-extract-cursor-postgres.test.ts`.
- `src/core/take-proposals.ts` — owns the `take_proposals` queue's row contract. `normalizeTakeProposalRow` coerces Postgres driver BigInt/string values (`id`, `weight`, `promoted_row_num`) to numbers at the query boundary so both engines return the same numeric row shape. `acceptProposal` promotes through a coordinated `takes_add` mutation (`submitPageMutation`, the same path `gbrain takes add` uses), so accept works on a managed brain where a direct fence write is refused with `writer_coordinator_required` (`test/takes-propose-accept-managed.test.ts`). #5214: an accepted proposal's take records `take_proposals#<id>` as its source; `acceptProposal(target, id, edits)` (`takes propose --accept <id> --claim/--weight/--who/--kind`) applies the edits as a plain takes_add with source `take_proposals#<id> (edited)` while the queue row keeps the original claim text.
- `admin/src/pages/Calibration.tsx` — Calibration tab. Single-column layout. `<TrustedSVG>` wrapper handles `dangerouslySetInnerHTML` for the server-rendered SVG.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 6c7b014160..9b5c269f17 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -164,6 +164,7 @@ with each file and fix the ones that need no guessing."*
| <a id="preparation_stalled-hold"></a>`preparation_stalled` | The write for this file could not finish *preparing* within its attempt limit, so the sync held the file and kept going. The file is fine: no repair applies, and it is not imported until it is retried. Full reference: [`preparation_stalled`](#preparation_stalled). | `gbrain sources writer status --source <source> --json` (read-only), fix what it names, then `gbrain sources retry-held <source>` and the same sync with its options. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). |
| <a id="worktree_dirty"></a>`worktree_dirty` | The working tree holds uncommitted bytes for this file that match neither the pinned commit nor the current page (an agent mid-edit on a live checkout), and importing the pinned version would discard them (#6340). Before this release the refusal (`source_changed` / `pinned_git_worktree_conflict`) stopped the whole run; now the file is held, the local edit is untouched and the rest of the source syncs. The hold keeps the pinned blob (`meta.blob_oid`) and a hash of the working bytes, counts `meta.attempts` each time the same file is held again, and a page held three times is reported `needs_human` by `gbrain sync status`. Bytes that are **committed at HEAD** past the pinned target are not a conflict at all: sync imports them as HEAD has them and the later pin..HEAD diff re-imports the same bytes as a no-op. | Commit the edit (or restore the file), then `gbrain sync unblock --source <source> --apply` re-screens every held file that is now committed and prints the sync to run (`gbrain sources retry-held <source>` does the same for all holds). A later commit that changes the file re-screens it on its own. Never discard or normalize the local bytes. Runbook: [sync unblock](sync-unblock-runbook.md). |
| <a id="sync_parser_regression"></a>`sync_parser_regression` | Sync stopped without advancing because it would hold a file whose exact bytes imported before (default `sync.parser_regression=stop`). This is a gbrain bug, not a content problem. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then `gbrain sync --source <source> --no-pull --retry-failed`. To keep syncing meanwhile, `gbrain config set sync.parser_regression hold` (ask the user). |
+| <a id="takes_holder_invalid"></a>takes holder (`invalid_params`) | `takes_add`, or `takes_supersede` with an explicit `holder`, was given a holder the takes fence cannot carry: empty, whitespace, or not `world`, `brain`, `people/<slug>` or `companies/<slug>` (a legacy bare slug is accepted). The value is trimmed first, so `" world "` is stored as `world`. Nothing was written: before this release such a holder was published into the fence and every later takes write on that page was refused `target_fence_malformed`. A supersede without an override keeps the row's stored holder. A page whose stored holder is already malformed still refuses every takes write (`invalid_fence`); `gbrain repair fences` is the way out. | Resend with a holder in that grammar (`holder: me` on the brain host resolves the owner's holder). For a page already carrying a malformed holder, preview `gbrain repair fences --slug <slug>` and apply it, or edit the `who` cell by hand. Format: [holders](fence-format.md#holders). |
| <a id="changed_since_preview"></a>`changed_since_preview` | A hash-bound repair apply (`gbrain repair frontmatter --apply --expect <hash>`, `gbrain repair fences --apply --expect <hash>`, `gbrain repair content --apply --expect <h1>[,<h2>]`) found a file, its proposed change or its page different from what the preview showed, so that item was not written; the rest of the approved set still applied. | Preview again with the same selection and apply the new hash (for the content lane, one hash per kind in lane order). For frontmatter, show the user the new diff first; a fence repair needs no extra consent ([fence reason](#fence-changed_since_preview)). |
<a id="invalid_fence"></a>
diff --git a/src/core/persistence/takes-prepare.ts b/src/core/persistence/takes-prepare.ts
index 725a2c3f12..934ca3efac 100644
--- a/src/core/persistence/takes-prepare.ts
+++ b/src/core/persistence/takes-prepare.ts
@@ -3,7 +3,7 @@ import type { GBrainConfig } from '../config.ts';
import { OperationError, opError, type OperationContext } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import type { RegistryCode } from '../error-registry.ts';
-import { parseTakesFence, upsertTakeRow, supersedeRow, type ParsedTake, type TakeQuality } from '../takes-fence.ts';
+import { isValidHolder, parseTakesFence, upsertTakeRow, supersedeRow, type ParsedTake, type TakeQuality } from '../takes-fence.ts';
import { takesPreparation as edit, TakesWriteError } from '../takes-write.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { preparePageMutation } from './page-prepare.ts';
@@ -50,6 +50,17 @@ function takesRefusal(code: RegistryCode, message: string, row: WriteRequest, ca
{ argv: ['gbrain', 'get', '--source', row.source_id, '--', row.slug], mcp: { tool: 'get_page', arguments: { slug: row.slug, source_id: row.source_id } } }) });
}
+/**
+ * #6450: the holder is trimmed and checked against the fence grammar at the write boundary (syntax before authority), so a
+ * malformed holder is refused `invalid_params` instead of being published into a fence the next write would refuse.
+ */
+function validHolder(raw: string, row: WriteRequest): string {
+ const holder = raw.trim();
+ if (isValidHolder(holder)) return holder;
+ throw takesRefusal('invalid_params', 'holder must be world | brain | people/<slug> | companies/<slug> (a legacy bare slug is accepted).', row,
+ `Its holder is not a value the takes fence can carry; pass holder as world, brain, people/<slug> or companies/<slug>.`);
+}
+
function fail(error: unknown): never {
if (!(error instanceof TakesWriteError)) throw error;
const code = error.code === 'holder_denied' ? 'permission_denied' : error.code === 'row_not_found' ? 'not_found'
@@ -98,11 +109,12 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
if (row.operation === 'takes_add') {
if (typeof p.claim !== 'string' || !p.claim.trim() || typeof p.kind !== 'string' || typeof p.holder !== 'string') throw takesRefusal('invalid_params','claim, kind and holder are required.',row,
'takes_add needs claim, kind and holder as non-empty text.');
- edit.assertHolderAllowed(p.holder,holders); requiredHolders.add(p.holder);
- const added = upsertTakeRow(body,{claim:p.claim,kind:p.kind,holder:p.holder,weight:p.weight as number ?? 0.5,
+ const holder=validHolder(p.holder,row);
+ edit.assertHolderAllowed(holder,holders); requiredHolders.add(holder);
+ const added = upsertTakeRow(body,{claim:p.claim,kind:p.kind,holder,weight:p.weight as number ?? 0.5,
source:p.source as string | undefined,sinceDate:p.since as string,active:true,rowNum:await nextRow()});
next=added.body; allocated=added.rowNum; changed=parseTakesFence(next).takes.filter(t=>t.rowNum===added.rowNum);
- result={slug:row.slug,row_num:added.rowNum,holder:p.holder};
+ result={slug:row.slug,row_num:added.rowNum,holder};
} else {
if (!Number.isSafeInteger(p.row_num) || Number(p.row_num)<1) throw takesRefusal('invalid_params','row_num must be a positive integer.',row,
`Pass row_num as the take's row number on the page (takes_list with page_slug ${row.slug} lists them).`);
@@ -124,7 +136,8 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
else if (row.operation==='takes_supersede') {
if (typeof p.claim!=='string' || !p.claim.trim()) throw takesRefusal('invalid_params','claim is required.',row,
'takes_supersede needs the replacement claim as non-empty text.');
- const holder=typeof p.holder==='string'?p.holder:target.holder;
+ // Only an explicit override is validated; the inherited holder already round-tripped with the existing fence.
+ const holder=typeof p.holder==='string'?validHolder(p.holder,row):target.holder;
edit.assertHolderAllowed(holder,holders); requiredHolders.add(holder);
const [stored]=await engine.executeRaw<{id:number;trust_tier:string}>('SELECT id,trust_tier FROM takes WHERE page_id=$1 AND row_num=$2',[snapshot.page.id,number]);
const accepted=p.trust_accept!==undefined && stored ? await ownerAcceptedTake(engine,row,Number(stored.id),snapshot.page.id) : null;
@@ -169,6 +182,10 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
result={slug:row.slug,row_num:number,...(row.operation==='takes_resolve'?{quality:p.quality,resolved_by:p.resolved_by}:{})};
}
}
+ // #6450 post-condition: never publish a fence the next write would refuse.
+ const republished = parseTakesFence(next);
+ if (republished.warnings.length) throw takesRefusal('invalid_params',`The write would publish a takes fence the next write would refuse: ${republished.warnings[0]}`,row,
+ 'One of the values would not round-trip through the takes fence; correct it (holder, kind, claim and source are single-line fence cells).');
const gate = allocated !== undefined ? decideTakeWrite({ claim: String(p.claim), source: (p.source as string | undefined) ?? null }, { sourceId: row.source_id, slug: row.slug,
payload: { page_id: snapshot.page.id, claim: p.claim, kind: p.kind ?? null, holder: p.holder ?? null, weight: p.weight ?? null, source: p.source ?? null, since: p.since ?? null },
input: gateInput(trust, row.id), cfg: await loadWriteGateConfig(engine) }) : null;
diff --git a/src/core/takes-write.ts b/src/core/takes-write.ts
index c0639fb39c..763c151548 100644
--- a/src/core/takes-write.ts
+++ b/src/core/takes-write.ts
@@ -391,7 +391,7 @@ function assertFenceRoundTrips(parsed: ParseResult): void {
// #3697: this used to name `gbrain extract takes --slugs`, which is not the
// command grammar (extract has links/timeline/all; takes extraction lives
// under `gbrain takes extract`). Point at surfaces that exist.
- "Reconcile the page's takes fence before mutating — it contains rows this version can't safely round-trip. Fix the malformed fence rows by hand, or re-extract via `gbrain takes extract --from-pages --include-covered`.",
+ "Reconcile the page's takes fence before mutating — it contains rows this version can't safely round-trip. Preview its repair with `gbrain repair fences` (read-only; it names the exact edit when gbrain will not repair it), fix the malformed fence rows by hand, or re-extract via `gbrain takes extract --from-pages --include-covered`.",
);
}
}
diff --git a/test/takes-holder-validation-6450.test.ts b/test/takes-holder-validation-6450.test.ts
new file mode 100644
index 0000000000..2d9ce0136d
--- /dev/null
+++ b/test/takes-holder-validation-6450.test.ts
@@ -0,0 +1,152 @@
+/**
+ * #6450: `takes_add` accepted any string as `holder` (and `takes_supersede`
+ * any explicit override), so `''`, `' '`, `'Not A Slug!'` or
+ * `'people/Bad Slug'` were published into the page's takes fence, where the
+ * next write refused the whole fence (`target_fence_malformed`) and the page
+ * was wedged until `gbrain repair fences`.
+ *
+ * The write boundary now trims the holder, validates it against the fence
+ * grammar (`isValidHolder`: `world`, `brain`, `people/<slug>`,
+ * `companies/<slug>`, or a legacy bare slug) and refuses `invalid_params`
+ * before any page, file or table change; the supersede validates only an
+ * explicit override, never the inherited holder. Every prepared fence is
+ * round-tripped before publication, so no write can leave behind a fence the
+ * next write would refuse. A page whose stored holder is already malformed is
+ * refused as before, and the refusal names `gbrain repair fences`.
+ *
+ * Fresh page per case; every refusal asserts the stored body, revision and
+ * takes rows unchanged. PGLite, trusted local caller. Synthetic content only.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { TAKES_FENCE_BEGIN as TB, TAKES_FENCE_END as TE, isValidHolder, parseTakesFence } from '../src/core/takes-fence.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+
+const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';
+const takeRow = (n: number, claim: string, who: string) => `| ${n} | ${claim} | take | ${who} | 0.7 | 2026-01 | chat |`;
+const takesFence = (...rows: string[]) => `${TB}\n${TH}\n${rows.join('\n')}\n${TE}`;
+const page = (title: string, body = 'Synthetic prose.') => `---\ntitle: ${title}\n---\n# ${title}\n\n${body}\n`;
+
+let engine: PGLiteEngine;
+const home = mkdtempSync(join(tmpdir(), 'gbrain-takes-holder-6450-'));
+const env = { GBRAIN_HOME: home };
+const op = (name: string) => operations.find(o => o.name === name)!;
+let n = 0;
+
+function ctx(): OperationContext {
+ return { engine, config: { engine: 'pglite' as const }, logger: { info: () => {}, warn: () => {}, error: () => {} }, dryRun: false,
+ remote: false, sourceId: 'default', deferEmbeds: true } as OperationContext;
+}
+async function freshPage(): Promise<string> {
+ const slug = `people/holder-case-${++n}`;
+ await op('put_page').handler(ctx(), { slug, content: page(`Case ${n}`) });
+ return slug;
+}
+interface State { body: string; revision: unknown; rows: unknown[]; committed: number }
+async function state(slug: string): Promise<State> {
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ const rows = await engine.executeRaw('SELECT row_num, claim, holder, active FROM takes WHERE page_id=$1 ORDER BY row_num', [snapshot.page.id]);
+ const [{ committed }] = await engine.executeRaw<{ committed: number }>("SELECT count(*)::int AS committed FROM persistence_requests WHERE slug=$1 AND state='committed'", [slug]);
+ return { body: snapshot.page.compiled_truth, revision: snapshot.revision, rows, committed };
+}
+async function refusal(run: () => Promise<unknown>): Promise<OperationError> {
+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('expected a refusal');
+}
+const add = (slug: string, holder: string, claim = 'A synthetic take') => op('takes_add').handler(ctx(), { slug, claim, kind: 'take', holder, weight: 0.6, since: '2026-02' }) as Promise<Record<string, any>>;
+const supersede = (slug: string, row_num: number, holder?: string) => op('takes_supersede').handler(ctx(), { slug, row_num, claim: 'A replacement take', ...(holder !== undefined ? { holder } : {}) }) as Promise<Record<string, any>>;
+const holders = async (slug: string) => parseTakesFence((await engine.getPage(slug, { sourceId: 'default' }))!.compiled_truth).takes.map(t => [t.rowNum, t.holder, t.active]);
+
+/** A refusal leaves the page exactly as it was (body, revision, takes rows) and commits no request. */
+async function expectUnchanged(slug: string, before: State): Promise<void> {
+ const after = await state(slug);
+ expect(after.body).toBe(before.body);
+ expect(after.revision).toEqual(before.revision);
+ expect(after.rows).toEqual(before.rows);
+ expect(after.committed).toBe(before.committed);
+}
+
+beforeAll(async () => withEnv(env, async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }), 120_000);
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });
+
+describe('isValidHolder (pure probe)', () => {
+ test('rejects the malformed forms and accepts the grammar; whitespace is valid only after a trim', () => {
+ for (const bad of ['', ' ', 'Not A Slug!', 'people/Bad Slug', ' world ']) expect(isValidHolder(bad)).toBe(false);
+ for (const ok of ['world', 'brain', 'people/alice-example', 'companies/acme-example', 'xxxxx']) expect(isValidHolder(ok)).toBe(true);
+ expect(isValidHolder(' world '.trim())).toBe(true);
+ });
+});
+
+describe('takes_add refuses a malformed holder before any state change (#6450)', () => {
+ for (const holder of ['', ' ', 'Not A Slug!', 'people/Bad Slug']) {
+ test(`holder ${JSON.stringify(holder)} → invalid_params, page untouched, and the next takes_add on that page still succeeds`, () => withEnv(env, async () => {
+ const slug = await freshPage();
+ const before = await state(slug);
+ const error = await refusal(() => add(slug, holder));
+ expect(error.canonicalCode).toBe('invalid_params');
+ expect(error.message).toMatch(/holder/i);
+ expect(error.message).toContain('people/<slug>');
+ await expectUnchanged(slug, before);
+ const next = await add(slug, 'world', 'A follow-up take');
+ expect(next.holder).toBe('world');
+ expect(await holders(slug)).toEqual([[1, 'world', true]]);
+ }));
+ }
+
+ test('a padded valid holder is trimmed, validated and stored as the bare value', () => withEnv(env, async () => {
+ const slug = await freshPage();
+ const result = await add(slug, ' world ');
+ expect(result.holder).toBe('world');
+ expect(await holders(slug)).toEqual([[1, 'world', true]]);
+ expect(await engine.executeRaw('SELECT holder FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.slug=$1', [slug])).toEqual([{ holder: 'world' }]);
+ }));
+
+ test('a valid legacy bare-slug holder is accepted and its row can be superseded without an override', () => withEnv(env, async () => {
+ const slug = await freshPage();
+ expect((await add(slug, 'xxxxx')).holder).toBe('xxxxx');
+ const superseded = await supersede(slug, 1);
+ expect(superseded).toMatchObject({ old_row: 1, new_row: 2 });
+ expect(await holders(slug)).toEqual([[1, 'xxxxx', false], [2, 'xxxxx', true]]);
+ }));
+});
+
+describe('takes_supersede validates only an explicit holder override (#6450)', () => {
+ test('a malformed override → invalid_params with the fence untouched; a padded valid override is trimmed', () => withEnv(env, async () => {
+ const slug = await freshPage();
+ await add(slug, 'world');
+ const before = await state(slug);
+ const error = await refusal(() => supersede(slug, 1, 'Not A Slug!'));
+ expect(error.canonicalCode).toBe('invalid_params');
+ expect(error.message).toMatch(/holder/i);
+ await expectUnchanged(slug, before);
+ const ok = await supersede(slug, 1, ' brain ');
+ expect(ok).toMatchObject({ old_row: 1, new_row: 2 });
+ expect(await holders(slug)).toEqual([[1, 'world', false], [2, 'brain', true]]);
+ }));
+
+ test('a stored holder that is already malformed keeps refusing every takes write, and the refusal names gbrain repair fences', () => withEnv(env, async () => {
+ const slug = await freshPage();
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(
+ 'UPDATE pages SET compiled_truth=$3 WHERE source_id=$1 AND slug=$2', ['default', slug, `# Legacy\n\nSynthetic prose.\n\n${takesFence(takeRow(1, 'An old take', 'Not A Slug!'))}\n`]), TEST_WRITE_ATTRIBUTION));
+ const before = await state(slug);
+ // The existing malformed-fence refusal stays: typed invalid_fence / target_fence_malformed for the supersede.
+ const superseded = await refusal(() => supersede(slug, 1));
+ expect({ code: superseded.canonicalCode, reason: superseded.reason }).toEqual({ code: 'invalid_fence', reason: 'target_fence_malformed' });
+ expect(JSON.stringify(superseded.toJSON())).toContain('gbrain repair fences');
+ await expectUnchanged(slug, before);
+ // takes_add normalizes what it can; a holder it cannot resolve leaves the fence unparseable and the write refused.
+ const added = await refusal(() => add(slug, 'world'));
+ expect(['invalid_fence', 'invalid_params']).toContain(added.canonicalCode);
+ expect(JSON.stringify(added.toJSON())).toContain('gbrain repair fences');
+ await expectUnchanged(slug, before);
+ }));
+});