Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(takes): a removed take's row number is never handed out again (W9F item 4)

time-attack95bc699efe9d
diff --git a/docs/architecture/key-files/hindsight.md b/docs/architecture/key-files/hindsight.md
index 4872d4ba89..be220576e3 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 fence and the takes table 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. `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. `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/src/core/persistence/takes-prepare.ts b/src/core/persistence/takes-prepare.ts
index cc6fefbfba..00b4fc91eb 100644
--- a/src/core/persistence/takes-prepare.ts
+++ b/src/core/persistence/takes-prepare.ts
@@ -12,7 +12,8 @@ import type { WriteRequest } from './model.ts';
import type { PreparedMutation } from './coordinator.ts';
import { assertPageRevision } from '../page-state/types.ts';
import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';
-import { normalizeTargetFences } from '../fence-repair/import-step.ts';
+import { normalizeTargetFences, storedFenceRows } from '../fence-repair/import-step.ts';
+import { nextFreeRowNum } from '../fence-repair/normalize.ts';
import { scanCanonicalFences, targetFenceRefusal } from '../fence-repair/refusal.ts';
import { pageFencesNormalized } from '../fence-repair/report.ts';
@@ -80,13 +81,17 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
let result: Record<string, unknown>;
let oldRow: number | undefined;
let removedRow: number | undefined;
+ // W9F item 4: a new row number never seen on this page, fence rows (reservations included) and stored rows alike.
+ let allocated: number | undefined;
+ const nextRow = async () => nextFreeRowNum({ compiled_truth: body, timeline: '' },
+ await storedFenceRows(engine, row.source_id, row.slug, snapshot.page.id));
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,
- source:p.source as string | undefined,sinceDate:p.since as string,active:true});
- next=added.body; changed=parseTakesFence(next).takes.filter(t=>t.rowNum===added.rowNum);
+ 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};
} else {
if (!Number.isSafeInteger(p.row_num) || Number(p.row_num)<1) throw takesRefusal('invalid_params','row_num must be a positive integer.',row,
@@ -103,7 +108,7 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
if (stored && stored.claim!==target.claim) throw takesRefusal('invalid_params',`Row #${number}'s database copy disagrees with the page's takes fence; run gbrain takes rebuild ${row.slug} --source-id ${row.source_id} first.`,row,
`Rebuild the page's takes index from its fence first with gbrain takes rebuild ${row.slug} --source-id ${row.source_id}, check the row, then remove it again.`);
removedRow=number;
- next=edit.replaceFence(body,parsed.takes.filter(t=>t.rowNum!==number));
+ next=edit.replaceFence(body,parsed.takes.filter(t=>t.rowNum!==number),[number]);
result={slug:row.slug,row_num:number,removed:true};
} else if (!target.active) throw new TakesWriteError('row_inactive','The take was superseded.');
else if (row.operation==='takes_supersede') {
@@ -112,8 +117,8 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
const holder=typeof p.holder==='string'?p.holder:target.holder;
edit.assertHolderAllowed(holder,holders); requiredHolders.add(holder);
const superseded=supersedeRow(body,number,{claim:p.claim,kind:p.kind as string ?? target.kind,holder,
- weight:p.weight as number ?? Math.max(0,target.weight-0.1),source:p.source as string | undefined,sinceDate:p.since as string});
- next=superseded.body; oldRow=number;
+ weight:p.weight as number ?? Math.max(0,target.weight-0.1),source:p.source as string | undefined,sinceDate:p.since as string},await nextRow());
+ next=superseded.body; oldRow=number; allocated=superseded.newRowNum;
changed=parseTakesFence(next).takes.filter(t=>t.rowNum===number || t.rowNum===superseded.newRowNum);
result={slug:row.slug,old_row:number,new_row:superseded.newRowNum};
} else {
@@ -144,6 +149,10 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
const prepared=await preparePageMutation(engine,row,config,{content:next,expectedRevision:snapshot.revision});
return {...prepared,validate:async tx=>{
await prepared.validate?.(tx);
+ if (allocated!==undefined && (await tx.executeRaw('SELECT 1 FROM takes WHERE page_id=$1 AND row_num=$2',[snapshot.page.id,allocated])).length) {
+ throw takesRefusal('revision_conflict',`Take row #${allocated} was recorded on ${row.slug} while this write was prepared.`,row,
+ `Another writer recorded take row #${allocated} on ${row.slug} after this request read the page.`);
+ }
for (const holder of requiredHolders) await authorizeTakeHolder(tx,row.authority,holder);
await tx.executeRaw(`UPDATE persistence_requests
SET authority=jsonb_set(authority,'{takeHoldersUsed}',$2::text::jsonb)
diff --git a/src/core/takes-fence.ts b/src/core/takes-fence.ts
index 8e0b24347c..2e173baa49 100644
--- a/src/core/takes-fence.ts
+++ b/src/core/takes-fence.ts
@@ -100,6 +100,24 @@ export interface ParsedTake {
export interface ParseResult {
takes: ParsedTake[];
warnings: string[];
+ /**
+ * Row numbers held by reservation rows (`takes remove`, W9F item 4): kept
+ * in the fence so the number is never handed out again, never a take.
+ */
+ reservedRowNums: number[];
+}
+
+/**
+ * A removed take leaves a reservation row in its place: a fully parsed row
+ * whose struck claim and source cell carry these markers and whose other
+ * cells are reset, so `nextFreeRowNum` keeps seeing its number. The parser
+ * returns it in `reservedRowNums`, never in `takes`.
+ */
+export const TAKE_RESERVATION_CLAIM = '(removed)';
+export const TAKE_RESERVATION_SOURCE = 'removed';
+
+function reservationRow(rowNum: number): ParsedTake {
+ return { rowNum, claim: TAKE_RESERVATION_CLAIM, kind: 'take', holder: 'world', weight: 0, source: TAKE_RESERVATION_SOURCE, active: false };
}
// HTML-comment fence markers — verbatim per spec.
@@ -255,20 +273,21 @@ export function parseTakesFence(body: string): ParseResult {
`marker "${TAKES_FENCE_BEGIN}" — use the three-dash comment form`,
);
}
- return { takes: [], warnings };
+ return { takes: [], warnings, reservedRowNums: [] };
}
if (beginIdx === -1 || endIdx === -1) {
warnings.push('TAKES_FENCE_UNBALANCED: missing begin or end marker');
- return { takes: [], warnings };
+ return { takes: [], warnings, reservedRowNums: [] };
}
if (endIdx < beginIdx) {
warnings.push('TAKES_FENCE_UNBALANCED: end marker before begin');
- return { takes: [], warnings };
+ return { takes: [], warnings, reservedRowNums: [] };
}
const inner = body.slice(beginIdx + TAKES_FENCE_BEGIN.length, endIdx);
const lines = inner.split('\n');
const takes: ParsedTake[] = [];
+ const reservedRowNums: number[] = [];
let sawHeader = false;
// Map from resolution column name → cell index in the row. Empty when the
// fence is a v0.28 7-column shape; populated when resolution columns appear.
@@ -348,6 +367,10 @@ export function parseTakesFence(body: string): ParseResult {
}
const { text: claimText, struck } = stripStrikethrough(claimRaw);
+ if (struck && claimText === TAKE_RESERVATION_CLAIM && sourceRaw.trim() === TAKE_RESERVATION_SOURCE) {
+ reservedRowNums.push(rowNum);
+ continue;
+ }
const { since, until } = parseSinceCell(sinceRaw);
// v0.30 resolution columns. Only populated when the header contained the
@@ -394,7 +417,7 @@ export function parseTakesFence(body: string): ParseResult {
warnings.push('TAKES_TABLE_MALFORMED: pipe-rows present but no recognizable header');
}
- return { takes, warnings };
+ return { takes, warnings, reservedRowNums };
}
/**
@@ -417,7 +440,7 @@ export function parseTakesFence(body: string): ParseResult {
* round-trip-preservation test in test/takes-fence.test.ts is the
* regression gate.
*/
-export function renderTakesFence(takes: ParsedTake[]): string {
+export function renderTakesFence(takes: ParsedTake[], reservedRowNums: readonly number[] = []): string {
const hasAnyResolution = takes.some(t => t.resolvedQuality !== undefined);
const header = hasAnyResolution
? `| # | claim | kind | who | weight | since | source | resolved | quality | evidence | value | unit | by |`
@@ -425,7 +448,16 @@ export function renderTakesFence(takes: ParsedTake[]): string {
const separator = hasAnyResolution
? `|---|-------|------|-----|--------|-------|--------|----------|---------|----------|-------|------|----|`
: `|---|-------|------|-----|--------|-------|--------|`;
- const rows = takes.map(t => {
+ // Reservation rows sit at their row number among the takes (W9F item 4).
+ const live = new Set(takes.map(t => t.rowNum));
+ const reserved = [...new Set(reservedRowNums)].filter(n => !live.has(n)).sort((a, b) => a - b);
+ const ordered: ParsedTake[] = [];
+ for (const t of takes) {
+ while (reserved.length && reserved[0]! < t.rowNum) ordered.push(reservationRow(reserved.shift()!));
+ ordered.push(t);
+ }
+ ordered.push(...reserved.map(reservationRow));
+ const rows = ordered.map(t => {
const claimCell = t.active ? t.claim : `~~${t.claim}~~`;
const sinceCell = t.untilDate ? `${t.sinceDate ?? ''} → ${t.untilDate}` : (t.sinceDate ?? '');
const w = formatWeight(t.weight);
@@ -465,13 +497,25 @@ function formatWeight(w: number): string {
return String(parseFloat(w.toFixed(2)));
}
+/**
+ * The page's next take row number from its own text: GBRA-54's
+ * `nextFreeRowNum`, the one allocator. Loaded lazily because the fence-repair
+ * modules import this one.
+ */
+function nextTakeRowNum(body: string): number {
+ const { nextFreeRowNum } = require('./fence-repair/normalize.ts') as typeof import('./fence-repair/normalize.ts');
+ return nextFreeRowNum({ compiled_truth: body, timeline: '' });
+}
+
/**
* Append a new take row to the body. If a fenced takes table exists, the
* row is added to the end of it. If not, a new `## Takes` section + fence
* is created at the end of the body.
*
- * Append-only per CEO-D6 + eng-D9: row_num is set to (max existing rowNum
- * in the fence) + 1. Stable forever.
+ * Append-only per CEO-D6 + eng-D9: row_num is `newRow.rowNum` when given
+ * (callers with stored rows pass `nextFreeRowNum` over them), else
+ * `nextFreeRowNum` over the body. Never a number used on the page before,
+ * reservation rows included (W9F item 4).
*
* `claim`, `kind`, `holder` of the input are required; `weight` defaults
* to 0.5 if omitted; `active` defaults to true.
@@ -480,12 +524,11 @@ export function upsertTakeRow(
body: string,
newRow: Omit<ParsedTake, 'rowNum'> & { rowNum?: number },
): { body: string; rowNum: number } {
- const { takes, warnings } = parseTakesFence(body);
+ const { takes, warnings, reservedRowNums } = parseTakesFence(body);
// Surface warnings to caller via an attached marker — caller decides what to do.
// (We don't throw here so writes proceed; doctor surfaces the underlying issue.)
void warnings;
- const nextRowNum = newRow.rowNum
- ?? (takes.length > 0 ? Math.max(...takes.map(t => t.rowNum)) + 1 : 1);
+ const nextRowNum = newRow.rowNum ?? nextTakeRowNum(body);
const allRows: ParsedTake[] = [
...takes,
@@ -502,7 +545,7 @@ export function upsertTakeRow(
},
];
- const newFence = renderTakesFence(allRows);
+ const newFence = renderTakesFence(allRows, reservedRowNums);
// If fence already exists, replace it. Otherwise append a Takes section.
const { beginIdx, endIdx } = locateOutsideCode(body, TAKES_FENCE_BEGIN, TAKES_FENCE_END);
@@ -529,6 +572,8 @@ export function upsertTakeRow(
* Supersede an existing row: strike through the target row's claim AND
* append a new row at the end with the new claim. Both rows preserved
* in markdown for git-blame archaeology. Returns oldRowNum + newRowNum.
+ * The new row takes `newRowNum` when given, else `nextFreeRowNum` over the
+ * body (W9F item 4).
*
* Throws when the target row is not found in the fence.
*/
@@ -536,14 +581,14 @@ export function supersedeRow(
body: string,
oldRowNum: number,
replacement: Omit<ParsedTake, 'rowNum' | 'active'>,
+ newRowNum: number = nextTakeRowNum(body),
): { body: string; oldRowNum: number; newRowNum: number } {
- const { takes } = parseTakesFence(body);
+ const { takes, reservedRowNums } = parseTakesFence(body);
const idx = takes.findIndex(t => t.rowNum === oldRowNum);
if (idx === -1) {
throw new Error(`supersedeRow: row #${oldRowNum} not found in takes fence`);
}
const oldClaim = takes[idx].claim;
- const newRowNum = takes.length > 0 ? Math.max(...takes.map(t => t.rowNum)) + 1 : 1;
// The pointer lives on the OLD row (the canonical projection reads it there),
// after the row's own provenance. A stale self-reference written by older
@@ -568,7 +613,7 @@ export function supersedeRow(
});
void oldClaim; // Reserved for future "show what changed" diff helper.
- const newFence = renderTakesFence(updatedTakes);
+ const newFence = renderTakesFence(updatedTakes, reservedRowNums);
const { beginIdx, endIdx } = locateOutsideCode(body, TAKES_FENCE_BEGIN, TAKES_FENCE_END);
if (beginIdx === -1 || endIdx === -1) {
throw new Error('supersedeRow: fence markers missing in body (unexpected — parseTakesFence found rows)');
diff --git a/src/core/takes-write.ts b/src/core/takes-write.ts
index cc79322bc7..470414a84e 100644
--- a/src/core/takes-write.ts
+++ b/src/core/takes-write.ts
@@ -393,8 +393,12 @@ function assertFenceRoundTrips(parsed: ParseResult): void {
}
}
-function replaceFence(body: string, rows: ParsedTake[]): string {
- const newFence = renderTakesFence(rows);
+/**
+ * Re-render the body's takes fence with `rows`. The fence's reservation rows
+ * stay, and `reserve` adds new ones (W9F item 4: `takes remove`).
+ */
+function replaceFence(body: string, rows: ParsedTake[], reserve: readonly number[] = []): string {
+ const newFence = renderTakesFence(rows, [...parseTakesFence(body).reservedRowNums, ...reserve]);
const { beginIdx, endIdx } = locateOutsideCode(body, TAKES_FENCE_BEGIN, TAKES_FENCE_END);
return body.slice(0, beginIdx) + newFence + body.slice(endIdx + TAKES_FENCE_END.length);
}
diff --git a/test/e2e/takes-row-reservation-postgres.test.ts b/test/e2e/takes-row-reservation-postgres.test.ts
new file mode 100644
index 0000000000..ad7dc54625
--- /dev/null
+++ b/test/e2e/takes-row-reservation-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../takes-row-reservation.test.ts'));
diff --git a/test/fence-marker-code-context.test.ts b/test/fence-marker-code-context.test.ts
index 607effa01d..f647b43cd8 100644
--- a/test/fence-marker-code-context.test.ts
+++ b/test/fence-marker-code-context.test.ts
@@ -130,7 +130,7 @@ describe('markdown code map', () => {
describe('takes fence markers quoted in code are documentation', () => {
test('parse ignores a fenced example and still reads the real fence after it', () => {
- expect(parseTakesFence(`doc\n\n${takesExample}\n`)).toEqual({ takes: [], warnings: [] });
+ expect(parseTakesFence(`doc\n\n${takesExample}\n`)).toEqual({ takes: [], warnings: [], reservedRowNums: [] });
const body = `doc\n\n${takesExample}\n\n${realTakes('REAL-CLAIM')}`;
expect(parseTakesFence(body).takes.map(t => t.claim)).toEqual(['REAL-CLAIM']);
});
@@ -161,7 +161,7 @@ describe('remote privacy boundary', () => {
// Readers no longer treat the mention as a fence, but the privacy boundary
// only ever changes toward hiding more, so the tail stays protected.
const body = `intro\n\nThe marker is \`${TAKES_FENCE_BEGIN}\` on its own line.\n\nPRIVATE TAIL`;
- expect(parseTakesFence(body)).toEqual({ takes: [], warnings: [] });
+ expect(parseTakesFence(body)).toEqual({ takes: [], warnings: [], reservedRowNums: [] });
expect(sanitizeRemoteBody(body)).not.toContain('PRIVATE TAIL');
expect(stripTakesFence(body)).not.toContain('PRIVATE TAIL');
});
diff --git a/test/helpers/takes-reservation-contract.ts b/test/helpers/takes-reservation-contract.ts
new file mode 100644
index 0000000000..36918ea1fa
--- /dev/null
+++ b/test/helpers/takes-reservation-contract.ts
@@ -0,0 +1,165 @@
+/**
+ * W9F item 4 (Decision 3): `takes remove` leaves a reservation row, so a
+ * removed take's number is never handed out again. Shared by the PGLite unit
+ * test and the Postgres E2E so both engines run the same cases through the
+ * coordinated takes path (`takes_add`, `takes_supersede`, `takes_remove`).
+ */
+import { expect } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { dispatchToolCall as dispatch } from '../../src/mcp/dispatch.ts';
+import { serializePageToMarkdown } from '../../src/core/markdown.ts';
+import { withVerifiedLocalRegistration, type LocalRegistration } from '../../src/core/persistence/identity.ts';
+import { parseTakesFence } from '../../src/core/takes-fence.ts';
+import { extractTakes } from '../../src/core/cycle/extract-takes.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { acceptProposal } from '../../src/core/take-proposals.ts';
+import { operations } from '../../src/core/operations.ts';
+import { parseMarkdown } from '../../src/core/markdown.ts';
+import { assertExportProjectionRoundtrip } from '../../src/core/shared-skills/migration-projection.ts';
+
+export interface ReservationHarness { engine: BrainEngine; cli: LocalRegistration; repo: string }
+
+export function reservationCases(h: () => ReservationHarness) {
+ const config = () => ({ engine: h().engine.kind, embedding_disabled: true });
+ const call = async (operation: string, params: Record<string, unknown>) => {
+ const { engine, cli } = h();
+ const result = await withVerifiedLocalRegistration(engine, cli,
+ () => dispatch(engine, operation, { request_id: randomUUID(), ...params }, { config: config(), remote: false, sourceId: 'default' }));
+ const body = JSON.parse(result.content[0].text);
+ if (result.isError) throw new Error(`${operation} failed: ${result.content[0].text}`);
+ return body as Record<string, unknown>;
+ };
+ const remove = async (slug: string, rowNum: number) => {
+ const { engine, cli } = h();
+ const op = operations.find(candidate => candidate.name === 'takes_remove')!;
+ return withVerifiedLocalRegistration(engine, cli, () => op.handler({ engine, config: config(), remote: false, sourceId: 'default', dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } }, { request_id: randomUUID(), slug, row_num: rowNum })) as Promise<Record<string, unknown>>;
+ };
+ const file = (slug: string) => readFileSync(join(h().repo, `${slug}.md`), 'utf8');
+ const fence = (slug: string) => parseTakesFence(file(slug));
+ const stored = async (slug: string) => (await h().engine.executeRaw<{ row_num: number; claim: string }>(
+ 'SELECT t.row_num, t.claim FROM takes t JOIN pages p ON p.id=t.page_id WHERE p.slug=$1 ORDER BY t.row_num', [slug])).map(r => [Number(r.row_num), r.claim]);
+ const seed = async (slug: string, compiledTruth = `about ${slug}`) => {
+ const { engine, repo } = h();
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: compiledTruth }, { sourceId: 'default' });
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ const path = join(repo, `${slug}.md`);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, serializePageToMarkdown(snapshot.page, snapshot.tags), 'utf8');
+ };
+ const add = async (slug: string, claim: string) => Number((await call('takes_add', { slug, claim, kind: 'take', holder: 'world' })).row_num);
+
+ return {
+ 'remove #3 then add takes #4, and the reservation keeps #3 out of takes and the index': async () => {
+ const slug = 'notes/reserve-basic';
+ await seed(slug);
+ for (const claim of ['One', 'Two', 'Three']) await add(slug, claim);
+ expect(await remove(slug, 3)).toMatchObject({ row_num: 3, removed: true });
+ expect(await add(slug, 'Four')).toBe(4);
+ const parsed = fence(slug);
+ expect(parsed.warnings).toEqual([]);
+ expect(parsed.reservedRowNums).toEqual([3]);
+ expect(parsed.takes.map(t => [t.rowNum, t.claim])).toEqual([[1, 'One'], [2, 'Two'], [4, 'Four']]);
+ expect(file(slug)).not.toContain('Three');
+ expect(file(slug)).toContain('| 3 | ~~(removed)~~ | take | world | 0.0 | | removed |');
+ expect(await stored(slug)).toEqual([[1, 'One'], [2, 'Two'], [4, 'Four']]);
+ const page = (await h().engine.readPageSnapshot(slug, { sourceId: 'default' }))!.page;
+ await assertExportProjectionRoundtrip(h().engine, parseMarkdown(file(slug), `${slug}.md`), page.id, 'default');
+ },
+
+ 'a stored take row number with no fence row is never handed out either': async () => {
+ const slug = 'notes/reserve-stored';
+ await seed(slug);
+ await add(slug, 'One');
+ const page = (await h().engine.readPageSnapshot(slug, { sourceId: 'default' }))!.page;
+ await h().engine.executeRaw(`INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, active)
+ VALUES ($1, 7, 'Stale index row', 'take', 'world', 0.5, true)`, [page.id]);
+ expect(await add(slug, 'Two')).toBe(8);
+ },
+
+ 'the reservation survives further adds and supersessions; no number is reused': async () => {
+ const slug = 'notes/reserve-chain';
+ await seed(slug);
+ for (const claim of ['One', 'Two']) await add(slug, claim);
+ await remove(slug, 2);
+ expect(await add(slug, 'Three')).toBe(3);
+ const superseded = await call('takes_supersede', { slug, row_num: 1, claim: 'One, revised' });
+ expect(superseded).toMatchObject({ old_row: 1, new_row: 4 });
+ await remove(slug, 3);
+ expect(await add(slug, 'Five')).toBe(5);
+ const parsed = fence(slug);
+ expect(parsed.warnings).toEqual([]);
+ expect(parsed.reservedRowNums).toEqual([2, 3]);
+ expect(parsed.takes.map(t => [t.rowNum, t.claim, t.active])).toEqual([[1, 'One', false], [4, 'One, revised', true], [5, 'Five', true]]);
+ },
+
+ 'takes rebuild and a canonical import keep the reservation and project no row for it': async () => {
+ const slug = 'notes/reserve-rebuild';
+ await seed(slug);
+ for (const claim of ['One', 'Two']) await add(slug, claim);
+ await remove(slug, 2);
+ const rebuilt = await extractTakes(h().engine, { source: 'db', slugs: [slug], sourceId: 'default', rebuild: true });
+ expect(rebuilt.warnings).toEqual([]);
+ expect(await stored(slug)).toEqual([[1, 'One']]);
+ await importFromContent(h().engine, slug, file(slug), { noEmbed: true });
+ expect(await stored(slug)).toEqual([[1, 'One']]);
+ expect(await add(slug, 'Three')).toBe(3);
+ },
+
+ 'on a page with a facts fence the next take skips every facts row number too': async () => {
+ const slug = 'notes/reserve-mixed';
+ await seed(slug, [
+ 'About a mixed page.', '', '## Facts', '', '<!--- gbrain:facts:begin -->', '',
+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',
+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',
+ '| 1 | First fact | fact | 1.0 | world | medium | 2026-01-01 | | test | |',
+ '| 2 | Second fact | fact | 1.0 | world | medium | 2026-01-01 | | test | |',
+ '<!--- gbrain:facts:end -->',
+ ].join('\n'));
+ expect(await add(slug, 'One')).toBe(3);
+ await remove(slug, 3);
+ expect(await add(slug, 'Two')).toBe(4);
+ expect(fence(slug).reservedRowNums).toEqual([3]);
+ },
+
+ 'accept, remove, accept again: the proposal stays settled on its removed row and adds nothing': async () => {
+ const slug = 'notes/reserve-accept';
+ await seed(slug);
+ const { engine, repo } = h();
+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO take_proposals
+ (source_id, page_slug, content_hash, prompt_version, proposal_run_id, claim_text, kind, holder, weight, domain, model_id, status)
+ VALUES ('default', $1, md5('reserve'), 'test-v1', 'run-test', 'Accepted claim', 'bet', 'world', 0.7, NULL, 'test-model', 'pending') RETURNING id`, [slug]);
+ const target = { engine, brainDir: repo, sourceId: 'default', actedBy: 'people/tester', config: config() };
+ const { rowNum } = await acceptProposal(target, row.id);
+ await remove(slug, rowNum);
+ await expect(acceptProposal(target, row.id)).rejects.toThrow(/already 'accepted'/);
+ const [proposal] = await engine.executeRaw<{ promoted_row_num: number }>('SELECT promoted_row_num FROM take_proposals WHERE id=$1', [row.id]);
+ expect(Number(proposal.promoted_row_num)).toBe(rowNum);
+ expect(fence(slug).reservedRowNums).toEqual([rowNum]);
+ expect(fence(slug).takes).toEqual([]);
+ expect(await add(slug, 'Later claim')).toBe(rowNum + 1);
+ },
+
+ 'a take removed while its accept settles keeps the proposal pointing at the removed number, never at a new take': async () => {
+ const slug = 'notes/reserve-settle';
+ await seed(slug);
+ const { engine, repo } = h();
+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO take_proposals
+ (source_id, page_slug, content_hash, prompt_version, proposal_run_id, claim_text, kind, holder, weight, domain, model_id, status)
+ VALUES ('default', $1, md5('settle'), 'test-v1', 'run-test', 'Settling claim', 'bet', 'world', 0.7, NULL, 'test-model', 'pending') RETURNING id`, [slug]);
+ const target = { engine, brainDir: repo, sourceId: 'default', actedBy: 'people/tester', config: config() };
+ const { rowNum } = await acceptProposal(target, row.id);
+ await engine.executeRaw('UPDATE take_proposals SET promoted_row_num = NULL WHERE id = $1', [row.id]);
+ await remove(slug, rowNum);
+ expect(await add(slug, 'Unrelated claim')).toBe(rowNum + 1);
+ expect((await acceptProposal(target, row.id)).rowNum).toBe(rowNum);
+ const [proposal] = await engine.executeRaw<{ promoted_row_num: number }>('SELECT promoted_row_num FROM take_proposals WHERE id=$1', [row.id]);
+ expect(Number(proposal.promoted_row_num)).toBe(rowNum);
+ expect(fence(slug).reservedRowNums).toEqual([rowNum]);
+ expect(fence(slug).takes.map(t => [t.rowNum, t.claim])).toEqual([[rowNum + 1, 'Unrelated claim']]);
+ },
+ };
+}
diff --git a/test/takes-reservation-callers.test.ts b/test/takes-reservation-callers.test.ts
new file mode 100644
index 0000000000..b8d9d2db0a
--- /dev/null
+++ b/test/takes-reservation-callers.test.ts
@@ -0,0 +1,42 @@
+/**
+ * W9F item 4: `parseTakesFence` returns reservation rows in `reservedRowNums`,
+ * never in `takes`, and every re-render goes through `renderTakesFence` with
+ * them. This census names every caller and why it is right about
+ * reservations; a new caller fails until someone reviews it here.
+ */
+import { expect, test } from 'bun:test';
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+
+const root = join(import.meta.dir, '..');
+const REVIEWED: Record<string, string> = {
+ 'src/core/cycle/concept-publication.ts': 'compares rows of fence blocks it copies verbatim, reservations included',
+ 'src/core/cycle/extract-takes.ts': 'projects takes only; a reserved number has no take, so rebuild prunes its stale index row',
+ 'src/core/cycle/grade-takes.ts': 'looks up live fence rows by number; a reserved number is not a gradeable take',
+ 'src/core/extract-takes-from-pages.ts': 'dedupes held claims against live takes only',
+ 'src/core/fence-repair/content.ts': 'reads warnings only (clean or not)',
+ 'src/core/fence-repair/import-step.ts': 'hidden rows feed allocation, which nextFreeRowNum already bases on every raw fence row',
+ 'src/core/fence-repair/page-checks.ts': 'a reserved number used twice in one fence is a parser collision warning',
+ 'src/core/fence-repair/refusal.ts': 'same warning and collision checks as page-checks',
+ 'src/core/persistence/canonical-projections.ts': 'projects takes only, so a reservation projects no row and its old row is deleted',
+ 'src/core/persistence/takes-prepare.ts': 'allocates with nextFreeRowNum, re-renders through upsertTakeRow/supersedeRow/replaceFence, and remove adds the reservation',
+ 'src/core/repair/connector-fences.ts': 'moves fence blocks verbatim, reservations included',
+ 'src/core/repair/take-supersession.ts': 're-renders through replaceFence, which keeps the reservations of the body it replaces',
+ 'src/core/shared-skills/migration-projection.ts': 'compares stored takes with fence takes; neither holds a reservation',
+ 'src/core/takes-write.ts': 'replaceFence, upsertTakeRow and supersedeRow keep reservations; round-trip checks count takes only',
+};
+
+function sources(dir: string): string[] {
+ return readdirSync(dir).flatMap(name => {
+ const path = join(dir, name);
+ return statSync(path).isDirectory() ? sources(path) : path.endsWith('.ts') ? [path] : [];
+ });
+}
+
+test('every parseTakesFence caller is reviewed for reservation rows', () => {
+ // test-reads-source-ok[structural]: a census of call sites, like canonical-writer-inventory.
+ const callers = sources(join(root, 'src')).map(path => relative(root, path))
+ .filter(path => path !== 'src/core/takes-fence.ts' && readFileSync(join(root, path), 'utf8').includes('parseTakesFence('))
+ .sort();
+ expect(callers).toEqual(Object.keys(REVIEWED).sort());
+});
diff --git a/test/takes-row-reservation.test.ts b/test/takes-row-reservation.test.ts
new file mode 100644
index 0000000000..3cd6a68b24
--- /dev/null
+++ b/test/takes-row-reservation.test.ts
@@ -0,0 +1,82 @@
+/**
+ * W9F item 4 (Decision 3): a removed take's row number is never handed out
+ * again. `takes remove` leaves a reservation row in the fence; every new row
+ * number comes from GBRA-54's `nextFreeRowNum` (fence rows, reservations
+ * included, plus stored rows), and the reservation survives adds,
+ * supersessions, rebuild and import while projecting no take.
+ *
+ * Protects: `slug#N` citations and `take_proposals.promoted_row_num` never
+ * start pointing at an unrelated take after a removal.
+ * Fails when: remove drops the row and the next add reuses its number (the
+ * pre-fix `max(fence)+1` allocation), or a re-render drops the reservation.
+ * Runs on PGLite, and on Postgres too when DATABASE_URL is set (the e2e lane
+ * registers it through test/e2e/takes-row-reservation-postgres.test.ts).
+ */
+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 type { BrainEngine } from '../src/core/engine.ts';
+import { registerLocalWriter, type LocalRegistration } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { parseTakesFence, renderTakesFence, supersedeRow, upsertTakeRow } from '../src/core/takes-fence.ts';
+import { reservationCases } from './helpers/takes-reservation-contract.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+for (const backend of testBackends()) {
+ describe(`takes row reservation through the coordinated takes path (${backend})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let cli: LocalRegistration;
+ let repo: string;
+ beforeAll(async () => {
+ ({ engine, close } = await isolatedSharedSkillsEngine(backend === 'postgres' ? requirePostgresTestDatabase() : undefined));
+ cli = await registerLocalWriter(engine, 'cli');
+ repo = mkdtempSync(join(tmpdir(), 'gbrain-takes-reserve-'));
+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [repo]);
+ await claimWorktree(engine, 'default', repo);
+ }, 120_000);
+ afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ await close();
+ rmSync(repo, { recursive: true, force: true });
+ });
+ for (const [name, run] of Object.entries(reservationCases(() => ({ engine, cli, repo })))) test(name, run, 60_000);
+ });
+}
+
+describe('takes row reservation in the fence helpers', () => {
+ const body = `x\n\n## Takes\n\n${renderTakesFence([
+ { rowNum: 1, claim: 'One', kind: 'take', holder: 'world', weight: 0.5, active: true },
+ { rowNum: 3, claim: 'Three', kind: 'bet', holder: 'brain', weight: 0.7, active: true, resolvedQuality: 'correct', resolvedAt: '2026-10-01' },
+ ], [2, 4])}\n`;
+
+ test('the fence round-trips with reservations in row order, also in the wide resolution shape', () => {
+ const parsed = parseTakesFence(body);
+ expect(parsed.warnings).toEqual([]);
+ expect(parsed.reservedRowNums).toEqual([2, 4]);
+ expect(parsed.takes.map(t => t.rowNum)).toEqual([1, 3]);
+ expect(renderTakesFence(parsed.takes, parsed.reservedRowNums)).toBe(body.slice(body.indexOf('<!---'), body.lastIndexOf('-->') + 3));
+ const rows = body.split('\n').filter(l => /^\| \d/.test(l)).map(l => Number(l.split('|')[1]));
+ expect(rows).toEqual([1, 2, 3, 4]);
+ });
+
+ test('upsertTakeRow and supersedeRow keep every reservation and never reuse a reserved number', () => {
+ const added = upsertTakeRow(body, { claim: 'Five', kind: 'take', holder: 'world', weight: 0.5, active: true });
+ expect(added.rowNum).toBe(5);
+ const superseded = supersedeRow(added.body, 1, { claim: 'One, revised', kind: 'take', holder: 'world', weight: 0.4 });
+ expect(superseded.newRowNum).toBe(6);
+ const parsed = parseTakesFence(superseded.body);
+ expect(parsed.warnings).toEqual([]);
+ expect(parsed.reservedRowNums).toEqual([2, 4]);
+ expect(parsed.takes.map(t => t.rowNum)).toEqual([1, 3, 5, 6]);
+ });
+
+ test('a user row that merely says "removed" is still a take', () => {
+ const parsed = parseTakesFence(`${renderTakesFence([{ rowNum: 1, claim: '(removed)', kind: 'take', holder: 'world', weight: 0.5, source: 'removed', active: true }])}`);
+ expect(parsed.reservedRowNums).toEqual([]);
+ expect(parsed.takes.map(t => t.claim)).toEqual(['(removed)']);
+ });
+});