Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

A held-fact move accepted while the checkout is busy commits under the request it named

garrytan8479f3b6c68c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6d7aa4d28d..adc768943e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,6 +26,7 @@ identifiers and attribution are available in the pre-removal Git revision
- `src/commands/access-rules.ts`: the rule preview lists `held_facts_moving` and the apply moves them (`held_facts: {moved, unmovable}`), for the database and git stores; `gbrain access apply` and `gbrain access resume` move them too. Each listed fact's `to` comes from `heldRowDestination`, the resolution the move itself uses, so a row saved under a bare name shows the page that name resolves to. The preview now runs the move's own planner: it lists every row the apply moves (`from` and `to`, and `because: its page exists` for a row that moves only because its entity's page now exists), the struck rows that leave with them (`held_struck_rows_leaving`), and per page the rows and versions the receipts will record (`held_versions_editing.pages`: the versions carrying them now plus the one each move saves). The apply reports a pending move as incomplete with its request id.
- `src/core/facts/fence-fact-append.ts`, `src/core/persistence/prepared-maintenance.ts`: a held row that leaves a holding page (the shared page or a folder's) for a page not every reader of it can read also leaves that page's saved versions, with the entity's struck rows, in the same transaction; every other byte of each version is kept, Git history is not rewritten, and the move's write receipt records it (`held_versions_edited`: the rows' fact ids, the row and version counts, where they went). The rule preview counts the rows and versions (`held_versions_editing`). A saved version stored in segments is not edited: the preview names how many per page (`segmented_versions_not_edited`, and a line saying readers of that page's saved versions can still read the moved rows there), and the apply's `held_facts` says `complete: false` with the same words (`segmented_pages`). A saved version with no timeline keeps a NULL timeline.
- `src/core/facts/purge.ts`: purge's saved-version redaction moves, unchanged in SQL and transaction, into `rewriteVersionBodies` (its `keepNullTimeline` flag, which purge does not pass, writes a NULL timeline back as NULL for the held-row edit), which the held-row edit above also calls, so the page body reader ratchet still lists one saved-version reader.
+- `src/core/persistence/prepared-maintenance.ts`: the row hash a fact-fence adoption or held-fact move pins counts `valid_from` and `valid_until` to the second, the precision a fence cell keeps. A move accepted while the checkout is busy now commits under the request it named after the facts reconcile rewrites a new row's time to its cell's; before, that request ended `revision_conflict` and a second request made the move.
- `src/commands/sync/perform.ts`, `src/core/cycle/extract-facts.ts`: after a managed sync releases its lease, held facts that a rule it applied narrows below their holding page's readers move at once (one query decides, and nothing is due when nothing changed); the maintenance cycle stays the fallback. Running it after the lease only spares a follower sync the wait: the lease is re-entrant and the move's writes are not sync rows. Either path names the page when the move left a segmented saved version unedited (`HELD_VERSIONS_NOT_EDITED` in the cycle) or is still pending (`HELD_FACT_PENDING`).
- `src/core/repair/facts-home.ts`, `src/core/facts/facts-home.ts`: `gbrain repair facts-home` writes a ruled entity's fact to its folder's page; `folder_restricted` now means only `page_rule` or `access_unreadable`.
- Docs: `git-canonical.md`, `entity-scoped-facts.md`, `access-designations.md`, `repair.md`, `write-refusals.md`, `memory-boundaries.md`, `MEMORY_VERBS_v1.md`, `error-codes.md` (regenerated).
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index 22e677d3b4..52f01ce966 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -418,6 +418,16 @@ export async function submitMaintenanceConsolidation(engine: BrainEngine, author
/** One legacy fact the v0.32.2 backfill adopts at a fence position; `hash` pins its whole row at admission. */
export interface FactFenceAssignment { id: number; row_num: number; hash: string }
+/**
+ * The row hash an adoption or held-move plan pins. `valid_from` and `valid_until` count to the second, the precision a fence
+ * cell keeps: the facts reconcile rewrites a new row's sub-second time to its cell's, and a request still pending across
+ * that reconcile commits instead of ending revision_conflict beside a second request for the same move (GST-2492).
+ */
+const SUBSECOND = /\.\d+(?=Z$|[+-]\d\d(?::?\d\d)?$)/;
+const toSecond = (time: unknown) => (typeof time === 'string' ? time.replace(SUBSECOND, '') : time);
+const pinnedFactHash = (value: Record<string, unknown> | null | undefined) =>
+ digest(value ? { ...value, valid_from: toSecond(value.valid_from), valid_until: toSecond(value.valid_until) } : null);
+
/**
* v0.32.2 on a managed brain: publish the page with its rendered facts fence
* and adopt the legacy rows in place, so the canonical projection matches
@@ -461,7 +471,7 @@ export type FactFenceAdoptionPlan =
export async function planFactFenceAdoption(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,
options: { content: string; expectedRevision: string; assignments: Array<{ id: number; row_num: number }>; move?: { note: string; from_entity?: string; from_slug?: string; drop?: readonly HeldDrop[] } }): Promise<FactFenceAdoptionPlan> {
const current = await readFacts(engine, authority.writer.sourceId, options.assignments.map(a => a.id));
- const facts: FactFenceAssignment[] = options.assignments.map(a => ({ ...a, hash: digest(current.find(f => f.id === a.id)?.value ?? null) }));
+ const facts: FactFenceAssignment[] = options.assignments.map(a => ({ ...a, hash: pinnedFactHash(current.find(f => f.id === a.id)?.value) }));
const intent = { kind: options.move ? HELD_FACT_MOVE : 'managed_maintenance_adopt_fact_fence', expected_revision: options.expectedRevision,
source_incarnation: authority.writer.sourceIncarnation, content: options.content, facts, planner: FACT_FENCE_PLANNER,
...(options.move ? { note: options.move.note, ...(options.move.from_entity ? { from_entity: options.move.from_entity } : {}),
@@ -561,7 +571,7 @@ async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteReques
const current = await readFacts(db, row.source_id, facts.map(f => f.id), lock);
for (const assignment of facts) {
const fact = current.find(f => f.id === assignment.id);
- if (!fact || digest(fact.value) !== assignment.hash || !ownsRow(fact.value, assignment.row_num) || fact.value.expired_at !== null
+ if (!fact || pinnedFactHash(fact.value) !== assignment.hash || !ownsRow(fact.value, assignment.row_num) || fact.value.expired_at !== null
|| (held ? fact.value.source_markdown_slug !== fromSlug || fact.value.row_num === null : fact.value.row_num !== null)) {
throw opError('revision_conflict', 'A legacy fact changed, was already adopted or moved to another owner before adoption.',
`A legacy fact on ${row.slug} in ${row.source_id} changed before fact-fence adoption request ${row.request_id} published; nothing was written. The next fact backfill run re-reads the facts and plans a fresh request.`,
diff --git a/test/folder-holding-page-gst2492.test.ts b/test/folder-holding-page-gst2492.test.ts
index c697f83d42..7d3a88c323 100644
--- a/test/folder-holding-page-gst2492.test.ts
+++ b/test/folder-holding-page-gst2492.test.ts
@@ -761,6 +761,46 @@ for (const backend of testBackends()) describe(`[${backend}] the folder-rule hol
expect(upkeep.warnings.some(w => w.startsWith('HELD_FACT_PENDING: ') && w.includes(request))).toBe(true);
await settleManagedGitEffects(engine);
expect(await factRows(engine, garden)).toMatchObject([{ source_markdown_slug: 'notes/garden-plan' }]);
+ // The request the apply named is the one that commits: the facts reconcile that ran between its acceptance and its commit
+ // (it rewrites the new row's time to the second its fence cell keeps) does not strand it beside a second request.
+ expect(await engine.executeRaw("SELECT request_id::text AS request_id, state FROM persistence_requests WHERE slug = 'notes/garden-plan' AND intent->>'kind' = 'managed_maintenance_move_held_fact' ORDER BY sequence"))
+ .toEqual([{ request_id: request, state: 'committed' }]);
+ }), 300_000);
+
+ test('a sync that brings a rule, a maintenance pass and a save on the same holding page all finish, and every fact ends on one page', () => strict(async ({ engine, ctx, root }) => {
+ const moveModule = await import('../src/core/facts/held-fact-move.ts');
+ const acme = 'The acme-example brief is moved under contention.';
+ const beta = 'The beta-example plan is moved under contention.';
+ const late = 'The garden plan is saved under contention.';
+ await remember(ctx, acme, 'clients/acme-example/brief');
+ await remember(ctx, beta, 'clients/beta-example/plan');
+ await settleManagedGitEffects(engine);
+ const policy = (rules: FolderRule[]) => commitPolicyFile(root, POLICY_FILE, () => serializePolicyYaml(rules), 'access: rule');
+ const sync = () => performSync(engine, { sourceId: 'default', repoPath: root, noPull: true, noEmbed: true } as never);
+ // One rule is applied with its move lost, so maintenance has a move due; the second rule arrives with the contended sync.
+ const died = spyOn(moveModule, 'moveRuledSharedHeld').mockImplementation(async () => { throw new Error('process died'); });
+ try { policy([rule('beta', 'clients/beta-example/', ['alice-example'])]); await sync(); } finally { died.mockRestore(); }
+ expect(await factRows(engine, beta)).toMatchObject([{ source_markdown_slug: HOLD }]);
+ policy([rule('beta', 'clients/beta-example/', ['alice-example']), rule('acme', 'clients/acme-example/', ['alice-example'])]);
+ // The sync holds its lease and then moves, the maintenance pass moves, and a save appends to the page both take rows off.
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const watchdog = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error('a sync, a maintenance pass and a save on one holding page did not all finish within 120 s')), 120_000); });
+ try {
+ const [, , saved] = await Promise.race([Promise.all([sync(), runExtractFacts(engine, { sourceId: 'default' }), remember(ctx, late, 'notes/garden-plan')]), watchdog]);
+ expect(saved).toMatchObject({ status: 'inserted', page: HOLD });
+ } finally { clearTimeout(timer); }
+ // Whatever the three left undone, the next passes finish it: nothing stays due and no request stays open.
+ for (let pass = 0; (await moveModule.moveRuledSharedHeld(engine, 'default')) !== null; pass++) { expect(pass).toBeLessThan(4); await settleManagedGitEffects(engine); }
+ await settleManagedGitEffects(engine);
+ expect(await factRows(engine, acme)).toMatchObject([{ entity_slug: 'clients/acme-example/brief', source_markdown_slug: 'clients/acme-example/memory/unattributed' }]);
+ expect(await factRows(engine, beta)).toMatchObject([{ entity_slug: 'clients/beta-example/plan', source_markdown_slug: 'clients/beta-example/memory/unattributed' }]);
+ expect(await factRows(engine, late)).toMatchObject([{ source_markdown_slug: HOLD }]);
+ expect(await engine.executeRaw("SELECT request_id::text AS request_id, state FROM persistence_requests WHERE completed_at IS NULL")).toEqual([]);
+ const shared = head(root, `${HOLD}.md`);
+ expect(shared).toContain(late);
+ for (const moved of [acme, beta]) expect(shared).not.toContain(moved);
+ expect(head(root, 'clients/acme-example/memory/unattributed.md')).toContain(acme);
+ expect(head(root, 'clients/beta-example/memory/unattributed.md')).toContain(beta);
}), 300_000);
test('a source that is not strict, and a brain with no Git repository, keep a ruled entity\'s fact database-only as before', async () => {