Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence): G7b-1, remote writes to a strict source go through the owner's door; a landed door commit stays on the receipt

garrytanf804b0bae823
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.md
index 57bb33e4af..c48ee82f3a 100644
--- a/docs/architecture/key-files/core-persistence-request-indexes.md
+++ b/docs/architecture/key-files/core-persistence-request-indexes.md
@@ -13,3 +13,4 @@ The online-built request-table indexes (the managed sync checkpoint pair, the pa
- Segmented withdrawal mirror (`src/core/persistence/{effects,effect-recovery,effect-model,staging}.ts`, flip lane A) — a withdrawal's mirror and Git scans treat a page stored in segments as an inline page (older binaries skipped it with `page_body_segmented`). `mirrorPage` renders its file from the segments (`page-prepare.ts` `unreadPageFile`, a `StreamedFileContent`) and reserves a version 2 `EffectRecovery` (`after: null`; `staging.publication` names the streamed file by path and SHA-256; the reservation counts the file once). `recoverEffectPublication` writes that stage before its transaction (`stageStreamedMirror`: from the measured file, or after a crash from the segments at the recorded revision, first discarding a stream a crash cut short under its in-progress name; seams `effect_recovery:before_stage` / `effect_recovery:staged`), then renames the verified stage (`staging.ts` `publishStreamedStage`). A segmented page's withdrawal is not materialized again: its rows were struck in its segments when the withdrawal committed. v0.60.290.0 reads a version 2 record as version 1 (`Buffer.from(null)`, untyped `effect_unavailable` on every attempt, never parks) but never deletes it or its stage, so `mirrorPage` writes none while that binary could claim it (next entry). Test: `test/large-pages/segmented-withdrawal-mirror.test.ts` (purge and forget twins, Git commits, two interruption seams, both engines).
- `src/core/persistence/{recovery-version,segmented-mirror-gate,segmented-gate-hold}.ts` — forward compatibility of recovery records. `recovery-version.ts` lists the record versions this binary reads (`EFFECT_RECOVERY_VERSIONS`, `REQUEST_RECOVERY_VERSIONS`); `assertRecoveryVersion` refuses any other `recovery_version_unsupported` (fix `gbrain upgrade`, `host_admin`) before a reader touches the record: `recoverEffectPublication`, `reserveEffectRecovery`, `rebaseStaleEffectRecovery` (the `--keep withdrawn` rebase), `upgradeRecoveryStaging` (both tables) and `model.ts` `recoveryFiles` (request recovery, clearing, stuck-recovery); the stuck-recovery preview (`recovery-resolve.ts` `scanStuckRecoveries`) lists such a record refused with that code and fix; `head-blocker.ts` reports such a record as an intervention with the same fix. `segmented-mirror-gate.ts`: `mirrorPage` calls `assertSegmentedMirrorGate` before streaming a segmented page's file; while `mirrorGateBlockers` sees a live writer below SEGMENTED_WRITER_FLOOR (the switch's TTL-cached `segmentedWriterBlockers`, filtered by `segmented-gate-hold.ts` `liveSegmentedBlockers`, the classification doctor `segmented_storage` uses: this host's own pre-upgrade writes superseded by the same kind of write from this build are not live; cached per gate read and host) it refuses `segmented_mirror_writer_gate` without reserving a record, and the target retries and parks as usual. `resumeGatedMirrors` (each effect pass, at most once per gate TTL per engine) requeues, via `retryParkedEffects`, requests whose parked targets all carry that code, or `withdrawal_mirror_failed` for the Git/embedding siblings parked behind the mirror (re-armed once it commits), once the gate is clear. No version 1 fallback: it would hold the file whole, and v0.60.290.0's recovery of it refuses to materialize a segmented page forever. Tests: `test/pathological/lp-d-recovery-version.test.ts`, `test/pathological/lp-d-segmented-mirror-gate.test.ts` (both engines).
- `src/core/persistence/effect-links.ts` — the `links` effect of a remote page write (`mcp.remote_auto_links`, link_source `mcp-remote-mention`). `runLinksEffect` reconciles a put_page/capture/edit_page page's plain mention edges against its whole compiled truth at the published revision (a later revision skips it as `superseded`), keeping targets that exist in the source, are visible to the writer (`writableTargets`) and sit inside its slug grant, and records missing targets as wanted pages. #7122: an effect with `data.range` (a remote append_page to the compiled truth) is `runAppendLinksEffect`: it reads only those stored truth bytes with the writer's audience (`readBodyRange` with the remote audience on a segmented page, loading only the segments the range overlaps; on an inline page the raw stored truth (`inlineRegions`) with its protected regions cut out of the range, then `sanitizeRemoteBody`), applies the same target filter and adds edges only, never removing one or replacing wanted rows. At a later revision it still runs when the range's trusted bytes hash to `data.range.sha256` (two appends whose effects run after both link both) and is skipped as `superseded` otherwise (an inline range is hash-checked at its own revision too); a write that lands between its read and its page lock is decided the same way under the lock, by reading the range again at the live revision, so a busy page never makes it retry. Tests: `test/persistence-links-effect.test.ts`, `test/large-pages/append-mention-links.test.ts` (both engines; readSegmentTexts spy).
+- `src/core/persistence/pending-import.ts` `landedCommit` with `recoverPublication` (`coordinator.ts`) and `completeWrite` (`journal.ts`) — G7b: on a strict source, a request whose door commit landed before its row is requeued with `outcome.persistence = {git_state: committed, git_commit, landed_before_row: true}` (the newest commit in the record's `door.head..HEAD` that touched its path; none in that range stamps nothing). `completeWrite` keeps it on a receipt that ends without committing (a grant revoked before the replay, a charged interruption), so the caller sees the bytes are in Git and will be indexed; a committed replay writes the ordinary door receipt. Tests: `test/git-door-remote-g7b.test.ts` (both engines; remote OAuth and legacy-token callers, owner down, revoked grant, group commit).
diff --git a/docs/architecture/thin-client.md b/docs/architecture/thin-client.md
index ec01048ff2..87fcea799e 100644
--- a/docs/architecture/thin-client.md
+++ b/docs/architecture/thin-client.md
@@ -49,6 +49,15 @@ configurations can deliberately use starter/verbs to expose fewer tools. Stdio
serves the server-resolved surface directly, without a client row; per-client
surface ceilings (`effectiveSurfaceForClient`) apply only to OAuth HTTP.
+**Writes to a strict source:** a thin client's write is an ordinary remote
+journal request. On a source in git-canonical mode (`canonical: git`) the
+brain owner's door commits it to Git before the database row commits, and the
+receipt names the commit (`outcome.persistence.git_commit`). While the owner
+is down the call ends `write_pending` (exit 10) with its request id, and
+`gbrain write-request <id>` follows it; nothing is written to the
+database first. Design: `docs/designs/GIT_CANONICAL_MEMORY.md`, "Remote and
+hosted writes".
+
Key files (per-file detail lives in each file's `KEY_FILES.md` entry; this doc
carries the routing-seam picture):
diff --git a/docs/designs/GIT_CANONICAL_MEMORY.md b/docs/designs/GIT_CANONICAL_MEMORY.md
index 69136400b5..e5c944682c 100644
--- a/docs/designs/GIT_CANONICAL_MEMORY.md
+++ b/docs/designs/GIT_CANONICAL_MEMORY.md
@@ -68,6 +68,8 @@ What remains: a bad merge from another clone is indexed as committed (git wins),
A write from a remote MCP caller or a thin client becomes a journal request that the checkout owner's door commits. The caller receives the revision once it is committed and indexed, or `write_pending` with a request id while the owner is unavailable. It is never written database-first. A hosted brain runs the door against a server-side bare repository, with an optional push to a repository the user owns.
+The request carries the bytes, the expected revision, the idempotency key (`request_id`) and the caller's grant, and the owner re-authorizes it against the live grant inside the publication transaction, before the door commit. A grant revoked while the request waits is refused with no commit and no row. If a door commit landed and the transaction then failed, the request is replayed; should the replay end without committing (its grant revoked meanwhile), the receipt still names the landed commit (`outcome.persistence.landed_before_row`), because Git holds those bytes and the indexer will import them: they were authorized when they were committed, and a later revocation does not retract committed content.
+
## Conversion
A source changes mode only through a preview-bound verb. The preview is the [git-gap census](#the-git-gap-census): every page whose row differs from its committed blob, every page with no file that is not in a declared class, held items and parked effects, by category. The operator chooses per category to commit the database content through the door, declare it, or let git win. The preview lists any database content that git-wins would discard, and the apply binds to that preview. A source can return to its previous mode.
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 90c06c9b00..1d1b710e58 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -42,7 +42,7 @@ import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePer
import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
-import { PENDING_IMPORT, SYNC_HELD } from './pending-import.ts';
+import { landedCommit, PENDING_IMPORT, SYNC_HELD } from './pending-import.ts';
import { CANONICAL_FILE_MISSING, databaseRefusal, ownerExceptionFailure, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';
import { SYNC_CURSOR_REPLACED, SYNC_PASS_SUPERSEDED } from './sync-checkpoint-replaced.ts';
import { fenceFailureDetail } from '../fence-repair/refusal.ts';
@@ -703,6 +703,7 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostId
const [current] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [id]);
if (!current.recovery) return current;
const records = recoveryFiles(current.recovery);
+ let landed: string | null = null;
if (current.recovery.version === 2) {
const owner = await guardOwnership(tx, current, hostId);
if (!owner) throw opError('owner_unavailable', 'Skill recovery requires its canonical owner.',
@@ -731,6 +732,7 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostId
if (actual !== record.beforeHash && actual !== record.afterHash) throw unexpectedRecoveryBytes('Canonical recovery bytes changed during restoration.', current, 'changed while recovery was restoring it and');
// G2: a strict publication whose commit landed keeps the committed file; Git holds it.
if (current.recovery.version === 1 && await doorCommitLanded(record)) {
+ landed = await landedCommit(record.door!.root, record.door!.head, record.path);
if (record.staging?.before) await withFilesystemPublication([record.root], async () => cleanupRecoveryStaging(record, { priorIntact: true }));
} else if (record.staging?.before) {
await withFilesystemPublication([record.root], async () => {
@@ -769,11 +771,13 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostId
// Withdrawal is authoritative DB state and is never rolled back here.
const failure: PublicationFailure | undefined = terminalError ?? (current.error_code ? {code:current.error_code,message:current.error_message ?? 'Publication failed before database completion.',
...(current.error_detail ? { detail: current.error_detail as unknown as PublicationFailureDetail } : {})} : undefined);
- if (failure) return completeWrite(tx, current, failureState(failure.code), {}, failure);
+ // G7b: a door commit that landed before its row is named on the receipt, whatever the replay's outcome.
+ const kept = landed ? { persistence: { git_state: 'committed', git_commit: landed, landed_before_row: true } } : null;
+ if (failure) return completeWrite(tx, current, failureState(failure.code), kept ?? {}, failure);
for (const key of ['brain', `worktree:${current.worktree_id}`]) await tx.executeRaw('UPDATE persistence_counters SET recovery_bytes=recovery_bytes-$2 WHERE key=$1', [key, Number(current.recovery_bytes)]);
const [queued] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state='queued',execution_token=NULL,
- claim_expires_at=NULL,recovery=NULL,recovery_bytes=0,publication_started=false,blocked_reason=NULL,updated_at=now()
- WHERE id=$1::uuid RETURNING *`, [id]);
+ claim_expires_at=NULL,recovery=NULL,recovery_bytes=0,publication_started=false,blocked_reason=NULL,outcome=COALESCE($2::text::jsonb,outcome),updated_at=now()
+ WHERE id=$1::uuid RETURNING *`, [id, kept ? JSON.stringify(kept) : null]);
return queued;
});
if (isTerminal(row) && row.blocked_reason !== 'unexpected_staging_bytes') {
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index db2414b663..f8665f1d73 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -914,6 +914,9 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'co
`The journal row of request ${row.request_id} in source ${row.source_id} disappeared before its completion was recorded, so no outcome was saved. Inspect the source's requests with the command in fix before submitting anything again.`,
{ fix: ownerStatusFix(row.source_id) });
if (isTerminal(current)) return current;
+ // G7b: a strict write whose door commit landed before its row keeps naming that commit when it ends without committing.
+ const landed = (current.outcome as { persistence?: { landed_before_row?: boolean } } | null)?.persistence;
+ if (state !== 'committed' && landed?.landed_before_row === true && !('persistence' in outcome)) outcome = { ...outcome, persistence: landed };
if (row.execution_token !== current.execution_token) throw opError('write_claim_lost', 'Write claim changed before completion.',
`Another owner pass claimed request ${row.request_id} in source ${row.source_id} before this pass recorded its outcome, so this pass's completion was discarded; the current claim records the final outcome. Inspect the request with the command in fix instead of resubmitting it.`,
{ fix: requestInspectFix(row) });
diff --git a/src/core/persistence/pending-import.ts b/src/core/persistence/pending-import.ts
index 7eacb35b4d..e78d619eb9 100644
--- a/src/core/persistence/pending-import.ts
+++ b/src/core/persistence/pending-import.ts
@@ -107,6 +107,14 @@ export async function committedBlob(root: string, path: string, signal?: AbortSi
return await quiet(gitRead(root, ['hash-object', '--', `./${relative(root, path).split(sep).join('/')}`], signal), signal) === head ? head : null;
}
+/**
+ * The newest commit after `from` (to HEAD) that touched `path`: the door commit of a strict publication that landed
+ * before its row; null when no commit in that range touched it, or when Git cannot read it.
+ */
+export async function landedCommit(root: string, from: string | null, path: string): Promise<string | null> {
+ return quiet(gitRead(root, ['rev-list', '-1', from ? `${from}..HEAD` : 'HEAD', '--', `:(literal)${relative(root, path).split(sep).join('/')}`]));
+}
+
/** The commit HEAD names in `root`, or null on an unborn branch or when Git cannot read it. */
export async function headCommit(root: string, signal?: AbortSignal): Promise<string | null> {
return quiet(gitRead(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], signal), signal);
diff --git a/test/git-door-remote-g7b.test.ts b/test/git-door-remote-g7b.test.ts
new file mode 100644
index 0000000000..d010e9ece5
--- /dev/null
+++ b/test/git-door-remote-g7b.test.ts
@@ -0,0 +1,229 @@
+/**
+ * G7b, remote writes in git-canonical memory (docs/designs/GIT_CANONICAL_MEMORY.md, "Remote and hosted writes"). A
+ * remote MCP caller or thin client (OperationContext.remote = true, an OAuth client or a legacy token) writing a strict
+ * source (`sources.config.canonical = "git"`) submits a journal request; the owner's door commits it to Git before its
+ * row (src/core/persistence/git-door.ts). Protects:
+ * - every page-content operation a remote caller has commits through the door: each committed request's receipt names
+ * the commit that holds its path, reachable from HEAD, and the file is clean in the checkout;
+ * - the commit exists before the row commits (publication:before_commit), for a remote write;
+ * - with the owner down, the caller gets write_pending with its request id, and neither a row nor a commit exists;
+ * once the owner runs it, it commits exactly once and a replay of the same request id returns that revision;
+ * - a grant revoked while the request waits is refused when the owner runs it: no row and no commit.
+ * PGLite here; with DATABASE_URL also Postgres (test/postgres-unit-arms.txt).
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { createHash, randomUUID } from 'node:crypto';
+import { writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { disposePersistenceConsumer, startPersistenceConsumer } from '../src/core/persistence/service.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { durableGitRepo, git } from './helpers/git-publication.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { waitFor } from './helpers/wait-for.ts';
+
+const page = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\n---\n\n${body}\n`;
+const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };
+const strict = (engine: BrainEngine) => engine.executeRaw(`UPDATE sources SET config = config || '{"canonical":"git"}'::jsonb WHERE id='default'`);
+
+/** A remote OAuth client and a remote legacy token, both granted read and write on the default source. */
+async function remoteCallers(engine: BrainEngine, ctx: OperationContext): Promise<{ oauth: OperationContext; token: OperationContext; tokenId: string; clientId: string }> {
+ const clientId = `client-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_secret_hash,client_name,scope,source_id) VALUES($1,'fixture-hash','example-client','read write','default')`, [clientId]);
+ const minted = await mintLegacyToken(engine, { name: `token-${clientId}`, scopes: ['read', 'write'], sourceGrant: ['default'], takesHolders: ['world'] });
+ return {
+ clientId, tokenId: minted.id,
+ oauth: { ...ctx, remote: true, transport: 'http', auth: { token: 'fixture', clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['read', 'write'], sourceId: 'default' } } as OperationContext,
+ token: { ...ctx, remote: true, transport: 'http', takesHoldersAllowList: ['world'],
+ auth: { token: '', clientId: minted.id, principal: { kind: 'legacy_token', id: minted.id }, sourceId: 'default', allowedSources: ['default'], scopes: ['read', 'write'] } } as OperationContext,
+ };
+}
+
+const call = (ctx: OperationContext, name: string, params: Record<string, unknown>) =>
+ (operationsByName[name]!.handler(ctx, { request_id: randomUUID(), wait_ms: 30_000, ...params }) as Promise<Record<string, any>>)
+ .catch((error: Error & { code?: string }) => { throw Object.assign(error, { message: `${name}: ${error.message}` }); });
+const sha256 = (text: string) => createHash('sha256').update(text).digest('hex');
+const revision = async (engine: BrainEngine, slug: string) => (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision;
+const lastSequence = async (engine: BrainEngine) => Number((await engine.executeRaw<{ s: number }>('SELECT COALESCE(max(sequence),0) AS s FROM persistence_requests'))[0]!.s);
+const commitsTouching = (root: string, rel: string) => git(root, 'log', '--format=%H', '--', rel).split('\n').filter(Boolean);
+
+/**
+ * Every committed page request after `after`: its receipt names a commit reachable from HEAD that holds its file (or,
+ * for a removal, no longer holds it), and the checkout holds that file clean. Returns how many there were.
+ */
+async function assertCommittedThroughDoor(engine: BrainEngine, root: string, after: number): Promise<number> {
+ const rows = await engine.executeRaw<{ slug: string; operation: string; state: string; outcome: Record<string, any> | null }>(
+ `SELECT slug, operation, state, outcome FROM persistence_requests WHERE sequence > $1 AND slug IS NOT NULL AND source_id='default' ORDER BY sequence`, [after]);
+ const published = rows.filter(row => row.state === 'committed' && row.outcome?.persistence?.git_state !== undefined);
+ for (const row of published) {
+ const commit = row.outcome!.persistence.git_commit as string;
+ expect({ slug: row.slug, operation: row.operation, git_state: row.outcome!.persistence.git_state, commit: typeof commit }).toEqual({ slug: row.slug, operation: row.operation, git_state: 'committed', commit: 'string' });
+ git(root, 'merge-base', '--is-ancestor', commit, 'HEAD');
+ const rel = `${row.slug}.md`;
+ const listed = git(root, 'ls-tree', '--name-only', commit, '--', rel).trim();
+ expect({ slug: row.slug, operation: row.operation, inCommit: listed === rel }).toEqual({ slug: row.slug, operation: row.operation, inCommit: row.operation !== 'delete_page' });
+ expect(git(root, 'status', '--porcelain', '--', rel)).toBe('');
+ }
+ return published.length;
+}
+
+for (const backend of testBackends()) describe(`[${backend}] G7b: remote writes to a strict source go through the owner's door`, () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ afterEach(() => installFaultHook(undefined));
+
+ test('every page-content operation of a remote caller commits to Git before its row, for an OAuth client and a legacy token', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const { oauth, token } = await remoteCallers(engine, ctx);
+ for (const [name, remote] of [['oauth', oauth], ['token', token]] as const) {
+ const base = `notes/${name}`;
+ const start = await lastSequence(engine);
+ const requestId = randomUUID();
+ const seen: { blob?: string } = {};
+ installFaultHook(async (point, detail) => {
+ if (point === 'publication:before_commit' && detail.requestId === requestId) seen.blob = git(root, 'show', `HEAD:${base}-a.md`);
+ });
+ expect(await call(remote, 'put_page', { request_id: requestId, slug: `${base}-a`, content: page('A', 'First body.') })).toMatchObject({ state: 'committed' });
+ installFaultHook(undefined);
+ expect(seen.blob).toContain('First body.');
+ await call(remote, 'edit_page', { slug: `${base}-a`, expected_revision: await revision(engine, `${base}-a`), edits: [{ old_text: 'First body.', new_text: 'Edited body.' }] });
+ await call(remote, 'append_page', { slug: `${base}-a`, text: 'An appended line.' });
+ await call(remote, 'add_tag', { slug: `${base}-a`, tag: 'example' });
+ await call(remote, 'remove_tag', { slug: `${base}-a`, tag: 'example' });
+ await call(remote, 'add_timeline_entry', { slug: `${base}-a`, date: '2026-01-01', summary: 'Met alice-example.' });
+ if (name === 'token') await call(remote, 'takes_add', { slug: `${base}-a`, claim: 'Example claims are testable.', kind: 'take', holder: 'world', weight: 0.5 });
+ await call(remote, 'capture', { content: `A captured note from the ${name} caller.` });
+ expect(await call(remote, 'put_pages', { pages: [{ slug: `${base}-b`, content: page('B', 'Bee.') }, { slug: `${base}-c`, content: page('C', 'Cee.') }] }))
+ .toMatchObject({ state: 'committed', counts: { committed: 2, failed: 0 } });
+ await call(remote, 'delete_page', { slug: `${base}-c`, expected_revision: await revision(engine, `${base}-c`) });
+ const deleted = await engine.readPageSnapshot(`${base}-c`, { sourceId: 'default', includeDeleted: true });
+ await call(remote, 'restore_page', { slug: `${base}-c`, expected_revision: deleted!.revision });
+ const [first] = await engine.executeRaw<{ id: number }>(`SELECT v.id FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id='default' AND p.slug=$1 ORDER BY v.id LIMIT 1`, [`${base}-a`]);
+ await call(remote, 'revert_version', { slug: `${base}-a`, version_id: Number(first!.id), expected_revision: await revision(engine, `${base}-a`) });
+ const uploaded = page('D', 'Uploaded.');
+ const upload = await call(remote, 'begin_page_upload', { slug: `${base}-d`, mode: 'create', total_bytes: Buffer.byteLength(uploaded), sha256: sha256(uploaded) });
+ await call(remote, 'upload_page_part', { upload_id: upload.upload_id, part: 0, text: uploaded, part_sha256: sha256(uploaded) });
+ expect(await call(remote, 'commit_page_upload', { upload_id: upload.upload_id })).toMatchObject({ state: 'committed' });
+ const operations = (await engine.executeRaw<{ operation: string }>("SELECT DISTINCT operation FROM persistence_requests WHERE sequence > $1 AND state='committed' AND outcome->'persistence'->>'git_state'='committed'", [start])).map(row => row.operation).sort();
+ expect(operations).toEqual(expect.arrayContaining(['append_page', 'capture', 'delete_page', 'edit_page', 'put_page', 'restore_page', 'revert_version']));
+ expect(await assertCommittedThroughDoor(engine, root, start)).toBeGreaterThanOrEqual(12);
+ }
+ expect(git(root, 'status', '--porcelain', '--', 'notes')).toBe('');
+ }, { databaseUrl, setup }), 240_000);
+
+ test('the owner down: write_pending with its request id, no row and no commit; once the owner runs it, one commit, and a replay returns it', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const { oauth } = await remoteCallers(engine, ctx);
+ const [binding] = await engine.executeRaw<{ owner: string }>('SELECT owner_host_id::text AS owner FROM persistence_worktrees');
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_worktrees SET owner_host_id=$1::uuid', [randomUUID()]);
+ const head = git(root, 'rev-parse', 'HEAD').trim();
+ const requestId = randomUUID();
+ const pending = await call(oauth, 'put_page', { request_id: requestId, wait_ms: 1_000, slug: 'notes/pending', content: page('Pending', 'Waits for its owner.') })
+ .then(() => ({ code: 'returned' }), (error: { code?: string; writeRequest?: { request_id?: string; state?: string } }) => ({ code: error.code, request: error.writeRequest }));
+ expect(pending).toMatchObject({ code: 'write_pending', request: { request_id: requestId, state: 'queued' } });
+ expect(git(root, 'rev-parse', 'HEAD').trim()).toBe(head);
+ expect(await engine.executeRaw("SELECT 1 FROM pages WHERE source_id='default' AND slug='notes/pending'")).toHaveLength(0);
+
+ await engine.executeRaw('UPDATE persistence_worktrees SET owner_host_id=$1::uuid', [binding!.owner]);
+ startPersistenceConsumer(engine, ctx.config as never).wake(true);
+ await waitFor(async () => (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]?.state === 'committed',
+ { timeoutMs: 60_000, label: 'the pending remote write commits' });
+ const [done] = await engine.executeRaw<{ outcome: Record<string, any> }>('SELECT outcome FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);
+ expect(commitsTouching(root, 'notes/pending.md')).toEqual([done!.outcome.persistence.git_commit]);
+ const replay = await call(oauth, 'put_page', { request_id: requestId, slug: 'notes/pending', content: page('Pending', 'Waits for its owner.') });
+ expect(replay).toMatchObject({ state: 'committed', revision: await revision(engine, 'notes/pending') });
+ expect(commitsTouching(root, 'notes/pending.md')).toHaveLength(1);
+ }, { databaseUrl, setup }), 120_000);
+
+ test('a grant revoked while its write waits is refused when the owner runs it: no row and no commit', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const { token, tokenId } = await remoteCallers(engine, ctx);
+ const [binding] = await engine.executeRaw<{ owner: string }>('SELECT owner_host_id::text AS owner FROM persistence_worktrees');
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_worktrees SET owner_host_id=$1::uuid', [randomUUID()]);
+ const head = git(root, 'rev-parse', 'HEAD').trim();
+ const requestId = randomUUID();
+ await expect(call(token, 'put_page', { request_id: requestId, wait_ms: 1_000, slug: 'notes/revoked', content: page('Revoked', 'Never published.') }))
+ .rejects.toMatchObject({ code: 'write_pending' });
+ await engine.executeRaw('UPDATE access_tokens SET revoked_at=now() WHERE id=$1', [tokenId]);
+ await engine.executeRaw('UPDATE persistence_worktrees SET owner_host_id=$1::uuid', [binding!.owner]);
+ startPersistenceConsumer(engine, ctx.config as never).wake(true);
+ await waitFor(async () => !['queued', 'running', 'recovering'].includes((await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]?.state ?? ''),
+ { timeoutMs: 60_000, label: 'the revoked remote write ends' });
+ const [done] = await engine.executeRaw<{ state: string; error_code: string | null }>('SELECT state, error_code FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);
+ expect(done).toEqual({ state: 'failed', error_code: 'permission_denied' });
+ expect(git(root, 'rev-parse', 'HEAD').trim()).toBe(head);
+ expect(git(root, 'status', '--porcelain', '--', 'notes')).toBe('');
+ expect(await engine.executeRaw("SELECT 1 FROM pages WHERE source_id='default' AND slug='notes/revoked'")).toHaveLength(0);
+ }, { databaseUrl, setup }), 120_000);
+
+ test('a door commit that landed before its grant was revoked: the replay refuses, and its receipt names the landed commit', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const { token, tokenId } = await remoteCallers(engine, ctx);
+ const requestId = randomUUID();
+ let landed = '';
+ installFaultHook(async (point, detail) => {
+ if (detail.requestId !== requestId) return;
+ if (point === 'publication:before_commit' && !landed) { landed = git(root, 'rev-parse', 'HEAD').trim(); throw Object.assign(new Error('database interruption'), { code: 'CONNECTION_CLOSED' }); }
+ if (point === 'publication:prepared' && landed) await engine.executeRaw('UPDATE access_tokens SET revoked_at=now() WHERE id=$1 AND revoked_at IS NULL', [tokenId]);
+ });
+ await expect(call(token, 'put_page', { request_id: requestId, slug: 'notes/landed', content: page('Landed', 'Committed, then revoked.') }))
+ .rejects.toMatchObject({ code: 'permission_denied' });
+ expect(landed).not.toBe('');
+ const [done] = await engine.executeRaw<{ state: string; error_code: string; outcome: Record<string, any> }>('SELECT state, error_code, outcome FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);
+ const holder = commitsTouching(root, 'notes/landed.md');
+ expect(holder).toHaveLength(1);
+ expect(git(root, 'show', `${holder[0]}:notes/landed.md`)).toContain('Committed, then revoked.');
+ expect(done).toEqual({ state: 'failed', error_code: 'permission_denied',
+ outcome: { persistence: { git_state: 'committed', git_commit: holder[0], landed_before_row: true } } });
+ expect(await engine.executeRaw("SELECT 1 FROM pages WHERE source_id='default' AND slug='notes/landed'")).toHaveLength(0);
+ }, { databaseUrl, setup }), 120_000);
+
+ test('a replay after a landed door commit that commits carries the normal door receipt, without landed_before_row', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const { oauth } = await remoteCallers(engine, ctx);
+ const requestId = randomUUID();
+ let thrown = false;
+ installFaultHook(async (point, detail) => {
+ if (point === 'publication:before_commit' && detail.requestId === requestId && !thrown) { thrown = true; throw Object.assign(new Error('database interruption'), { code: 'CONNECTION_CLOSED' }); }
+ });
+ expect(await call(oauth, 'put_page', { request_id: requestId, slug: 'notes/replayed', content: page('Replayed', 'Landed, then indexed.') })).toMatchObject({ state: 'committed' });
+ expect(thrown).toBe(true);
+ const [done] = await engine.executeRaw<{ outcome: Record<string, any> }>('SELECT outcome FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);
+ expect(commitsTouching(root, 'notes/replayed.md')).toEqual([done!.outcome.persistence.git_commit]);
+ expect(done!.outcome.persistence.git_state).toBe('committed');
+ expect(done!.outcome.persistence).not.toHaveProperty('landed_before_row');
+ }, { databaseUrl, setup }), 120_000);
+
+ test('put_pages whose group commit landed before its grant was revoked: every landed member names that one commit', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const { token, tokenId } = await remoteCallers(engine, ctx);
+ const slugs = ['notes/m1', 'notes/m2', 'notes/m3'];
+ let thrown = false;
+ installFaultHook(async (point) => {
+ if (point === 'publication:before_commit' && !thrown) { thrown = true; throw Object.assign(new Error('database interruption'), { code: 'CONNECTION_CLOSED' }); }
+ if (point === 'publication:prepared' && thrown) await engine.executeRaw('UPDATE access_tokens SET revoked_at=now() WHERE id=$1 AND revoked_at IS NULL', [tokenId]);
+ });
+ await call(token, 'put_pages', { pages: slugs.map(slug => ({ slug, content: page(slug, `Body of ${slug}.`) })) }).catch(() => undefined);
+ installFaultHook(undefined);
+ expect(thrown).toBe(true);
+ const rows = await engine.executeRaw<{ slug: string; state: string; error_code: string | null; outcome: Record<string, any> | null }>(
+ "SELECT slug, state, error_code, outcome FROM persistence_requests WHERE source_id='default' AND slug = ANY($1::text[]) ORDER BY slug", [slugs]);
+ expect(rows.map(row => ({ slug: row.slug, state: row.state, error_code: row.error_code }))).toEqual(slugs.map(slug => ({ slug, state: 'failed', error_code: 'permission_denied' })));
+ const landed = rows.filter(row => commitsTouching(root, `${row.slug}.md`).length > 0);
+ expect(landed.length).toBeGreaterThan(0);
+ for (const row of rows) {
+ const holder = commitsTouching(root, `${row.slug}.md`);
+ expect({ slug: row.slug, persistence: row.outcome?.persistence ?? null })
+ .toEqual({ slug: row.slug, persistence: holder.length ? { git_state: 'committed', git_commit: holder[0], landed_before_row: true } : null });
+ }
+ // Postgres publishes the batch as one group (group-publish.ts), so every member landed in one door commit; PGLite publishes one at a time.
+ if (backend === 'postgres') expect({ landed: landed.length, commits: new Set(landed.map(row => row.outcome!.persistence.git_commit)).size }).toEqual({ landed: slugs.length, commits: 1 });
+ expect(await engine.executeRaw("SELECT 1 FROM pages WHERE source_id='default' AND slug = ANY($1::text[])", [slugs])).toHaveLength(0);
+ }, { databaseUrl, setup }), 120_000);
+});
+
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 6ae31ddb4e..38c14c0adb 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -78,6 +78,7 @@ test/file-drift-soft-delete-hold-release-gbra133.test.ts
test/forecast-journal.test.ts
test/frontmatter-reserved-keys-6454.test.ts
test/get-chunks-paging.test.ts
+test/git-door-remote-g7b.test.ts
test/git-door-strict-gbra133.test.ts
test/git-gap-census.test.ts
test/google-connector-facts-fence-7292.test.ts