Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(takes): receipted takes reextract/rebuild and take-supersession reprojection

time-attack95a68a5e4615
diff --git a/src/core/cycle/extract-takes.ts b/src/core/cycle/extract-takes.ts
index c304c7c010..96c92efe33 100644
--- a/src/core/cycle/extract-takes.ts
+++ b/src/core/cycle/extract-takes.ts
@@ -14,8 +14,9 @@
* claim is unchanged keeps its resolution and vector (#5167). Without
* rebuild, ON CONFLICT (page_id, row_num) DO UPDATE keeps the table in sync
* incrementally.
- * On a managed brain the db path publishes each page's rows through the
- * persistence coordinator (the `takes` guard refuses any other writer).
+ * On a managed brain the db path publishes each page that needs a change as a
+ * receipted database-only maintenance request (the `takes` guard refuses any
+ * other writer).
*
* Sync-failure surfacing: malformed table rows produce
* `TAKES_TABLE_MALFORMED` and `TAKES_ROW_NUM_COLLISION` warnings. v0.28
@@ -30,9 +31,16 @@ import type { BrainEngine, TakeBatchInput } from '../engine.ts';
import { parseTakesFence, TAKES_FENCE_BEGIN, type ParsedTake } from '../takes-fence.ts';
import { walkMarkdownFiles } from '../../commands/extract.ts';
import { takesPreparation } from '../takes-write.ts';
-import { withCoordinatedWrite } from '../persistence/context.ts';
-import { maintenanceAttribution, maintenanceTransaction } from '../persistence/attribution.ts';
+import { buildTakeRows } from '../batch-rows.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import { isTerminal, type WriteRequest } from '../persistence/model.ts';
+import { authorizeWrite } from '../persistence/authority.ts';
+import { digest } from '../persistence/digest.ts';
+import { getWriteRequest } from '../persistence/journal.ts';
+import { maintenancePreflight, submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
+import { opError, OperationError } from '../ops/contract.ts';
export interface ExtractTakesOpts {
/** Brain repo root. Required for source='fs'. */
@@ -237,6 +245,11 @@ export async function extractTakesFromDb(
const refs = (await engine.listAllPageRefs()).filter(ref => (!slugFilter || slugFilter.has(ref.slug)) && (!opts.sourceId || ref.source_id === opts.sourceId));
const buffer: TakeBatchInput[] = [];
const coordinated = !dryRun && await managedPersistenceEnabled(engine);
+ const authorities = new Map<string, Promise<MaintenanceAuthority>>();
+ const authorityFor = (sourceId: string) => {
+ if (!authorities.has(sourceId)) authorities.set(sourceId, maintenancePreflight(engine, sourceId).then(a => a!));
+ return authorities.get(sourceId)!;
+ };
for (const { slug, source_id } of refs) {
result.pagesScanned++;
@@ -246,7 +259,7 @@ export async function extractTakesFromDb(
// A page with no takes marker at all yields no prune, no upsert and no
// warning; near-miss and unbalanced markers still reach the parser.
if (`${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`.includes('gbrain:takes:')) {
- await reextractCoordinated(engine, slug, source_id, rebuild, result);
+ await reextractCoordinated(engine, authorityFor, slug, source_id, rebuild, result);
}
continue;
}
@@ -291,32 +304,108 @@ async function reconcilePageTakes(
return takes;
}
+export const TAKES_REEXTRACT_INTENT = 'managed_maintenance_takes_reextract';
+
+/** The page's takes reconcile as it stands: what a write would prune, rebuild and upsert. */
+async function plannedTakes(db: BrainEngine, page: { id: number; compiled_truth: string | null; timeline: string | null }, rebuild: boolean) {
+ const body = `${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`;
+ const { takes, warnings } = parseTakesFence(body);
+ const { rows } = buildTakeRows(takes.map(t => takesPreparation.toCanonicalBatchInput(page.id, t)));
+ const stored = await db.executeRaw<{ row_num: number; claim: string; kind: string; holder: string; weight: number | string; since_date: string | null;
+ until_date: string | null; source: string | null; superseded_by: number | null; active: boolean }>(
+ 'SELECT row_num, claim, kind, holder, weight, since_date, until_date, source, superseded_by, active FROM takes WHERE page_id = $1', [page.id]);
+ const byRow = new Map(stored.map(r => [Number(r.row_num), r]));
+ const prunes = warnings.length === 0 && body.includes(TAKES_FENCE_BEGIN) && stored.some(r => !takes.some(t => t.rowNum === Number(r.row_num)));
+ const diverged = rebuild && stored.some(r => !takes.some(t => t.rowNum === Number(r.row_num) && t.claim === r.claim));
+ const upserts = rows.some(row => {
+ const s = byRow.get(row.row_num);
+ return !s || s.claim !== row.claim || s.kind !== row.kind || s.holder !== row.holder
+ || Math.abs(Number(s.weight) - row.weight) > 1e-4 || (s.since_date ?? null) !== row.since_date || (s.until_date ?? null) !== row.until_date
+ || (s.source ?? null) !== row.source || (s.superseded_by == null ? null : Number(s.superseded_by)) !== row.superseded_by || s.active !== row.active;
+ });
+ return { changed: prunes || diverged || upserts, takes };
+}
+
/**
- * Managed brains guard `takes` (#5728): each page publishes as a coordinated
- * write under its page lock, against the text read inside that transaction.
- * Rows carry the `superseded_by` the canonical publication projects (the
- * shared `takesPreparation.toCanonicalBatchInput`), so a page it already
- * projected keeps the same values. Resolution columns stay untouched,
- * as on the unmanaged path: some resolutions live only in the database.
+ * Managed brains guard `takes` (#5728): each page that needs a change
+ * publishes a database-only `managed_maintenance_takes_reextract` request
+ * bound to its revision, and its preparer reconciles the page against the
+ * text read under the page lock. Rows carry the `superseded_by` the
+ * canonical publication projects (the shared
+ * `takesPreparation.toCanonicalBatchInput`), so a page it already projected
+ * keeps the same values and admits nothing. Resolution columns stay
+ * untouched, as on the unmanaged path: some resolutions live only in the
+ * database.
*/
async function reextractCoordinated(
engine: BrainEngine,
+ authorityFor: (sourceId: string) => Promise<MaintenanceAuthority>,
slug: string,
sourceId: string,
rebuild: boolean,
result: ExtractTakesResult,
): Promise<void> {
- const attribution = await maintenanceAttribution(engine);
- await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {
- await tx.lockPageKeys([{ sourceId, slug }]);
- const [page] = await tx.executeRaw<{ id: number; compiled_truth: string | null; timeline: string | null }>(
- 'SELECT id, compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL',
- [sourceId, slug]);
- if (!page) return;
- const takes = await reconcilePageTakes(tx, page, slug, rebuild, false, result);
- if (takes.length === 0) return;
- result.takesUpserted += await tx.addTakesBatch(takes.map(t => takesPreparation.toCanonicalBatchInput(page.id, t)));
- }, attribution));
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });
+ const [page] = await engine.executeRaw<{ id: number; compiled_truth: string | null; timeline: string | null }>(
+ 'SELECT id, compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [sourceId, slug]);
+ if (!snapshot || !page || Number(page.id) !== snapshot.page.id) return;
+ const plan = await plannedTakes(engine, page, rebuild);
+ if (!plan.changed) {
+ const { warnings } = parseTakesFence(`${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`);
+ recordTakesWarnings(slug, warnings, result);
+ if (plan.takes.length) result.pagesWithTakes++;
+ return;
+ }
+ const authority = await authorityFor(sourceId);
+ for (let attempt = 0; ; attempt++) {
+ const h = digest(['extract-takes-db-v1', authority.writer.sourceIncarnation, sourceId, slug, snapshot.revision, rebuild, attempt]);
+ const requestId = `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
+ const prior = await getWriteRequest(engine, authority.writer.principal, requestId);
+ if (prior && isTerminal(prior) && prior.state !== 'committed') continue;
+ try {
+ const receipt = await submitDatabaseMaintenanceIntent(engine, authority, slug,
+ { kind: TAKES_REEXTRACT_INTENT, expected_revision: snapshot.revision, rebuild }, requestId);
+ result.takesUpserted += Number(receipt.takes_upserted ?? 0);
+ if (receipt.with_takes === true) result.pagesWithTakes++;
+ recordTakesWarnings(slug, Array.isArray(receipt.warnings) ? receipt.warnings.map(String) : [], result);
+ return;
+ } catch (error) {
+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed', 'write_pending'].includes(error.code)) {
+ result.warnings.push(`${slug}: TAKES_REEXTRACT_DEFERRED: the page changed or its request is still pending (${error.code}); rerun to extract it`);
+ return;
+ }
+ throw error;
+ }
+ }
+}
+
+function recordTakesWarnings(slug: string, warnings: string[], result: ExtractTakesResult): void {
+ for (const w of warnings) {
+ result.warnings.push(`${slug}: ${w}`);
+ if (w.startsWith('TAKES_HOLDER_INVALID')) result.failedFiles.push({ path: slug, error: w });
+ }
+}
+
+/** Preparer for `managed_maintenance_takes_reextract`: reconciles one page's takes under its key. */
+export async function prepareTakesReextract(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ if (!snapshot || snapshot.page.id !== Number(row.page_id)) {
+ throw opError('page_identity_changed', 'The page was deleted or replaced before its takes were extracted.',
+ `Page ${row.slug} in source ${row.source_id} changed before request ${row.request_id} ran, so its takes index was left as it was. Run gbrain extract takes --source db again; it reads the current page.`);
+ }
+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);
+ const rebuild = (row.intent as { rebuild?: unknown } | null)?.rebuild === true;
+ return { observedRevision: snapshot.revision, noop: true,
+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },
+ apply: async tx => {
+ const [page] = await tx.executeRaw<{ id: number; compiled_truth: string | null; timeline: string | null }>(
+ 'SELECT id, compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [row.source_id, row.slug]);
+ const local: ExtractTakesResult = { pagesScanned: 0, pagesWithTakes: 0, takesUpserted: 0, warnings: [], failedFiles: [] };
+ const takes = page ? await reconcilePageTakes(tx, page, row.slug, rebuild, false, local) : [];
+ const upserted = takes.length ? await tx.addTakesBatch(takes.map(t => takesPreparation.toCanonicalBatchInput(page!.id, t))) : 0;
+ return { status: 'completed', takes_upserted: upserted, with_takes: local.pagesWithTakes > 0,
+ warnings: local.warnings.map(w => w.slice(row.slug.length + 2)) };
+ } };
}
/** Single-entry dispatch for `gbrain extract takes` and the v0_28_0 orchestrator. */
diff --git a/src/core/repair/take-supersession.ts b/src/core/repair/take-supersession.ts
index 46f2ee0db2..6c197c990c 100644
--- a/src/core/repair/take-supersession.ts
+++ b/src/core/repair/take-supersession.ts
@@ -30,17 +30,20 @@
* `superseded by #N` after its own provenance, and self-pointers are
* dropped, exactly as `supersedeRow` writes a new supersession. A page whose
* fence is already right but whose database pointers differ is reprojected
- * under the page key (coordinator capability on a managed brain, a
- * maintenance transaction otherwise). A second apply finds nothing to do.
+ * under the page key (a receipted database-only request on a managed brain,
+ * a maintenance transaction otherwise). A second apply finds nothing to do.
*/
import type { BrainEngine } from '../engine.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import type { OperationContext } from '../ops/contract.ts';
-import { opError } from '../ops/contract.ts';
+import { opError, OperationError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
-import { maintenanceAttribution, maintenanceTransaction } from '../persistence/attribution.ts';
-import { withCoordinatedWrite } from '../persistence/context.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { authorizeWrite } from '../persistence/authority.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import type { WriteRequest } from '../persistence/model.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
import { submitPageMutation } from '../persistence/page-mutations.ts';
import { TAKES_FENCE_BEGIN, parseTakesFence, type ParsedTake } from '../takes-fence.ts';
import { takesPreparation } from '../takes-write.ts';
@@ -206,27 +209,60 @@ async function candidatePages(engine: BrainEngine, sourceIds: string[], after: R
return pages.filter(page => afterCursor({ phase: 0, id: page.id }, after));
}
-/** Reproject a page whose fence is already right: under the page key, against the planned revision. */
-async function reprojectPage(engine: BrainEngine, plan: PagePlan): Promise<void> {
+export const TAKE_REPROJECT_INTENT = 'managed_maintenance_take_reproject';
+
+const revisionConflict = (page: TakePage) => opError('revision_conflict', 'The page changed after the supersession repair read it; nothing was written.',
+ `Page ${page.slug} in source ${page.source_id} changed during the repair, so its take pointers were left as they are. Preview again with the command in fix; it plans against the current page.`,
+ { fix: readFix('Previews the take supersession repair against the current pages without changing anything.', { argv: ['gbrain', 'repair', 'take-supersession', '--source', page.source_id] }) });
+
+async function writeReprojection(tx: BrainEngine, plan: PagePlan): Promise<void> {
+ for (const row of plan.reproject) {
+ await tx.executeRaw('UPDATE takes SET superseded_by = $3 WHERE page_id = $1 AND row_num = $2', [plan.page.id, row.row_num, row.to]);
+ }
+}
+
+/**
+ * Reproject a page whose fence is already right, against the planned
+ * revision: a receipted database-only request on a managed brain (its
+ * preparer replans under the page key), a maintenance transaction otherwise.
+ */
+async function reprojectPage(ctx: OperationContext, entry: RepairItem, plan: PagePlan): Promise<void> {
const { page } = plan;
- const write = async (tx: BrainEngine) => {
- await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);
- const current = await tx.readPageSnapshot(page.slug, { sourceId: page.source_id });
- if (!current || current.revision !== plan.revision) {
- throw opError('revision_conflict', 'The page changed after the supersession repair read it; nothing was written.',
- `Page ${page.slug} in source ${page.source_id} changed during the repair, so its take pointers were left as they are. Preview again with the command in fix; it plans against the current page.`,
- { fix: readFix('Previews the take supersession repair against the current pages without changing anything.', { argv: ['gbrain', 'repair', 'take-supersession', '--source', page.source_id] }) });
+ if (await managedPersistenceEnabled(ctx.engine)) {
+ const authority = (await maintenancePreflight(ctx.engine, page.source_id))!;
+ try {
+ await submitDatabaseMaintenanceIntent(ctx.engine, authority, page.slug, { kind: TAKE_REPROJECT_INTENT, expected_revision: plan.revision,
+ page_id: page.id, reproject: plan.reproject }, await repairRequestId(ctx, 'take-supersession', entry, plan.revision));
+ } catch (error) {
+ if (error instanceof OperationError && error.code === 'revision_conflict') throw revisionConflict(page);
+ throw error;
}
- for (const row of plan.reproject) {
- await tx.executeRaw('UPDATE takes SET superseded_by = $3 WHERE page_id = $1 AND row_num = $2', [page.id, row.row_num, row.to]);
- }
- };
- if (await managedPersistenceEnabled(engine)) {
- const attribution = await maintenanceAttribution(engine);
- await engine.transaction(tx => withCoordinatedWrite(tx, [page.source_id], () => write(tx), attribution));
- } else {
- await maintenanceTransaction(engine, write);
+ return;
}
+ await maintenanceTransaction(ctx.engine, async tx => {
+ await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);
+ const current = await tx.readPageSnapshot(page.slug, { sourceId: page.source_id });
+ if (!current || current.revision !== plan.revision) throw revisionConflict(page);
+ await writeReprojection(tx, plan);
+ });
+}
+
+/** Preparer for `managed_maintenance_take_reproject`: replans the page under its key and writes the pointers it still needs. */
+export async function prepareTakeReprojection(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
+ const page = { id: Number(row.page_id), source_id: row.source_id, slug: row.slug };
+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ if (!snapshot || snapshot.page.id !== page.id) throw revisionConflict(page);
+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);
+ return { observedRevision: snapshot.revision, noop: true,
+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },
+ apply: async tx => {
+ const state = await readPage(tx, page);
+ if (!state || 'skipped' in state || state.analysis.ambiguous.length || state.analysis.fence_changed) {
+ return { status: 'completed', reprojected: [] };
+ }
+ await writeReprojection(tx, state);
+ return { status: 'completed', reprojected: state.reproject };
+ } };
}
interface SupersessionItem extends RepairItem { page: TakePage }
@@ -275,7 +311,7 @@ export const takeSupersessionRepair: RepairHandler = {
return { applied: true, outcome: 'repaired', detail: { links: state.analysis.links, self_pointers: state.analysis.self_pointers } };
}
if (!state.reproject.length) return { applied: false, outcome: 'unchanged' };
- await reprojectPage(ctx.engine, state);
+ await reprojectPage(ctx, entry, state);
return { applied: true, outcome: 'reprojected', detail: { rows: state.reproject } };
},
render(details) {