Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(persistence): the strict door commits by plumbing, without the checkout's index (GBRA-133)
garrytan6388b3d28063
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.tsindex d03f3e51a1..d0cef9eeef 100644--- a/src/core/persistence/effect-git.ts+++ b/src/core/persistence/effect-git.ts@@ -26,7 +26,7 @@ const canonical = (path: string) => { try { return join(realpathSync(dirname(patconst effectStatusFix = readFix('Shows each source\'s canonical owner with its retrying and parked Git effects, read-only.',{ argv: ['gbrain', 'sources', 'writer', 'status', '--json'] });-const gitFailure = (message: string, cause: string) => opError('git_unavailable', message,+export const gitFailure = (message: string, cause: string) => opError('git_unavailable', message,`${cause} The page write itself is committed; the effect worker tries this Git effect again and parks it after repeated failures. If it keeps failing, check the checkout with git status on the brain host.`,{ fix: effectStatusFix });const rootGone = (relativePath: string) => opError('git_target_unsafe', 'The canonical Git root disappeared.',@@ -60,12 +60,22 @@ export interface GitEffectOwner {onReclaim?: (receipt: IndexLockReclaim) => void;}-interface GitSession { root: string; hooks: string; signal?: AbortSignal; timeoutMs: number; owner?: GitEffectOwner }+export interface GitSession { root: string; hooks: string; signal?: AbortSignal; timeoutMs: number; owner?: GitEffectOwner }++const gitArgs = (session: GitSession, args: string[], literal: boolean) =>+ [...(literal ? ['--literal-pathspecs'] : []), '-C', session.root, '-c', `core.hooksPath=${session.hooks}`, '-c', 'commit.gpgsign=false', ...args];+const gitOptions = (session: GitSession) => ({ timeout: session.timeoutMs, termGraceMs: GIT_TERM_GRACE_MS, maxBuffer: 1024 * 1024, signal: session.signal, env: gitChildEnv(GIT_ENV) });function run(session: GitSession, args: string[], literal = true) {- return execFileBounded('git', [...(literal ? ['--literal-pathspecs'] : []), '-C', session.root, '-c', `core.hooksPath=${session.hooks}`, '-c', 'commit.gpgsign=false', ...args], {- timeout: session.timeoutMs, termGraceMs: GIT_TERM_GRACE_MS, maxBuffer: 1024 * 1024, signal: session.signal, env: gitChildEnv(GIT_ENV),- });+ return execFileBounded('git', gitArgs(session, args, literal), gitOptions(session));+}++/** A read-only git step whose stdout is raw bytes (a tree object); null when git exits non-zero. */+export async function gitBytes(session: GitSession, args: string[]): Promise<Buffer | null> {+ const { error, stdout } = await execFileBounded('git', gitArgs(session, args, true), { ...gitOptions(session), maxBuffer: 256 * 1024 * 1024, encoding: 'buffer' });+ if (error && (error.killed || typeof error.code !== 'number')) throw gitFailure('Git execution did not finish within its bounded attempt.',+ `A git command in the canonical checkout did not finish within ${Math.round(session.timeoutMs / 1000)} seconds or could not start.`);+ return error ? null : stdout;}/** The deadline of one staging or commit step in a checkout whose index holds `indexBytes`. */@@ -120,9 +130,9 @@ async function indexLockError(session: GitSession, stderr: string, mayReclaim: b{ detail: lock, fix: staleLockFix(session.root, lock, why) });}-async function git(session: GitSession, args: string[]): Promise<{ stdout: string; stderr: string; code: number }> {+export async function git(session: GitSession, args: string[], literal = true): Promise<{ stdout: string; stderr: string; code: number }> {for (let reclaimed = false; ; reclaimed = true) {- const { error, stdout, stderr } = await run(session, args);+ const { error, stdout, stderr } = await run(session, args, literal);if (error && (error.killed || typeof error.code !== 'number')) throw gitFailure('Git execution did not finish within its bounded attempt.',`A git command in the canonical checkout did not finish within ${Math.round(session.timeoutMs / 1000)} seconds or could not start.`);const code = error?.code as number ?? 0;@@ -195,15 +205,19 @@ async function refuseIgnoredTarget(session: GitSession, relativePath: string): Pif (status.code !== 0 || !status.stdout.startsWith('!! ')) return;// check-ignore takes no literal pathspecs; it only names the rule for the message.const matched = await run(session, ['check-ignore', '-v', '--', relativePath], false);- const rule = matched.error ? '.gitignore' : matched.stdout.split('\t')[0]!.replace(/^(.*?):(\d+):/, '$1:$2: ');+ throw ignoredTargetError(relativePath, matched.error ? '.gitignore' : matched.stdout.split('\t')[0]!.replace(/^(.*?):(\d+):/, '$1:$2: '));+}++/** The refusal of a target a .gitignore `rule` (`source:line: pattern`) excludes; `detail` names the rule. */+export function ignoredTargetError(relativePath: string, rule: string): OperationError {const error = new OperationError('git_target_ignored', `Git ignores ${relativePath} (${rule}), so its Git effect cannot commit it.`,`Either remove or narrow the rule (${rule}) and commit that change, then retry the parked effects with gbrain sources writer retry-effects and --parked-code git_target_ignored for the source this checkout backs (gbrain sources writer status names it); or keep the file out of Git and leave the effect parked. The page itself is committed in the database.`);error.detail = rule;- throw error;+ return error;}/** A git session with an empty hooks directory; `scaled` sizes its step deadline by the checkout's index. */-async function withSession<T>(root: string, signal: AbortSignal | undefined, owner: GitEffectOwner | undefined, scaled: boolean,+export async function withSession<T>(root: string, signal: AbortSignal | undefined, owner: GitEffectOwner | undefined, scaled: boolean,work: (session: GitSession) => Promise<T>): Promise<T> {const base = join(persistenceHome(), 'empty-hooks');mkdirSync(base, { recursive: true, mode: 0o700 });@@ -217,6 +231,18 @@ async function withSession<T>(root: string, signal: AbortSignal | undefined, ownconst commitText = (text: string) => text.replace(/[\u0000-\u001f\u007f]/g, '');+/**+ * The message paragraphs (`-m` arguments) of a commit of `commitPaths` (see commitGitTargets): the subject, the noted+ * paths' lines when several paths commit together, and their trailers last.+ */+export function commitMessage(commitPaths: string[], noted: ReadonlyMap<string, GitCommitNote>): string[] {+ const subject = commitPaths.length > 1 ? `gbrain: persist ${commitPaths.length} canonical memory updates`+ : commitText(noted.get(commitPaths[0]!)?.subject ?? '') || 'gbrain: persist canonical memory update';+ const body = commitPaths.length > 1 ? [...new Set([...noted.keys()].sort().map(path => commitText(noted.get(path)!.line)).filter(Boolean))] : [];+ const trailers = [...new Set([...noted.keys()].sort().map(path => commitText(noted.get(path)!.trailer ?? '')).filter(Boolean))];+ return [subject, ...(body.length ? [body.join('\n')] : []), ...(trailers.length ? [trailers.join('\n')] : [])];+}+/*** #5530: commit a group of single-file targets with one `commit --only`. The* caller owns the native worktree lock and has probed durability. Each@@ -308,11 +334,8 @@ export async function commitGitTargets(root: string, relativePaths: string[], siconst commitPaths = [...new Set(changed.map(c => c.path))];const noted = new Map<string, GitCommitNote>();for (const c of changed) { const note = notes?.get(c.requested); if (note && !noted.has(c.path)) noted.set(c.path, note); }- const subject = commitPaths.length > 1 ? `gbrain: persist ${commitPaths.length} canonical memory updates`- : commitText(noted.get(commitPaths[0]!)?.subject ?? '') || 'gbrain: persist canonical memory update';- const body = commitPaths.length > 1 ? [...new Set([...noted.keys()].sort().map(path => commitText(noted.get(path)!.line)).filter(Boolean))] : [];- const trailers = [...new Set([...noted.keys()].sort().map(path => commitText(noted.get(path)!.trailer ?? '')).filter(Boolean))];- const result = await git(session, [...(commitPaths.some(path => removed.has(path)) ? NO_FSCACHE : []), 'commit', '--only', '-m', subject, ...(body.length ? ['-m', body.join('\n')] : []), ...(trailers.length ? ['-m', trailers.join('\n')] : []), '--', ...commitPaths]);+ const message = commitMessage(commitPaths, noted).flatMap(paragraph => ['-m', paragraph]);+ const result = await git(session, [...(commitPaths.some(path => removed.has(path)) ? NO_FSCACHE : []), 'commit', '--only', ...message, '--', ...commitPaths]);const outcome = result.code === 0 ? { git: 'committed' } : gitFailure('Cannot commit the canonical Git target.',`git commit failed for ${commitPaths.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);for (const c of changed) results.set(c.requested, outcome);diff --git a/src/core/persistence/git-door.ts b/src/core/persistence/git-door.tsindex 3242f56995..aa91d3f0ba 100644--- a/src/core/persistence/git-door.ts+++ b/src/core/persistence/git-door.ts@@ -1,28 +1,49 @@/*** G2, the door of git-canonical memory (Git is the source of truth; the database derives from it): a source whose row says `config.canonical = "git"` (strict, default off)* commits each published file to Git before its database row commits. publishMutation and publishGroup commit the- * published paths with one path-only `commit --only` under the worktree's writer lock, after the files are renamed into- * place and before the database transaction commits, and stamp the commit on the receipt- * (`outcome.persistence.git_commit`). The Git effect of such a write only pushes.+ * published paths with one commit under the worktree's writer lock, after the files are renamed into place and before+ * the database transaction commits, and stamp the commit on the receipt (`outcome.persistence.git_commit`). The Git+ * effect of such a write only pushes.+ *+ * The commit is made by plumbing, without the checkout's index (GBRA-174: a porcelain `commit --only` rewrites and+ * refreshes the whole index, about 1.7 s at 312k files): `hash-object -w` hashes each published file (its clean+ * filters apply, as `git add` would), the trees along the changed paths are rebuilt from HEAD's (`cat-file tree`, then+ * `hash-object -w -t tree`, which refuses a malformed tree), `commit-tree` writes the commit with the porcelain path's+ * message (`commitMessage`), and `update-ref <branch> <new> <old>` moves the branch only if it still names the HEAD the+ * commit was built on. A branch that moved meanwhile (a commit made in the checkout) is read again and the commit+ * rebuilt once; a second move refuses, so the publication rolls back. The checkout's index then gets exactly the+ * published entries (`update-index --cacheinfo` / `--force-remove`): `git status` shows them clean, a later commit from+ * that index keeps them, and every other entry, staged or not, is left as it was.** Recovery inverts for those writes: the recovery record names the HEAD it was prepared against (`door`), and a* publication that stopped after its commit landed keeps the committed file instead of restoring the prior bytes.* The request is queued again; its replay finds the file already holding the bytes it publishes, committed, and* completes the database row against it (page-prepare.ts).+ *+ * Door commits of one checkout run one at a time in this process (lane groups and a foreground write beside them share+ * the writer lock). They are not coalesced across publications: a single write holds its worktree lock exclusively+ * from its file rename to its database commit, the consumer runs one single write per root at a time, and a+ * publication refuses while another request of its worktree holds a recovery record, so no second write is ever+ * waiting at the door to join. Batching independent writes needs those three to change; until then a batch commits+ * once through publishGroup.*/-import { relative, sep } from 'node:path';+import { createHash } from 'node:crypto';+import { existsSync, lstatSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { join, relative, resolve, sep } from 'node:path';import { OperationError, opError } from '../ops/contract.ts';-import { commitGitTargets } from './effect-git.ts';+import { commitMessage, git, gitBytes, gitFailure, ignoredTargetError, withSession, type GitSession } from './effect-git.ts';import type { GitCommitNote } from './effect-model.ts';+import { persistenceHome } from './identity.ts';import { hashFile } from './large-file.ts';import type { FileRecoveryRecord, SqlEngine } from './model.ts';+import { nativeFileTarget } from './native-file-target.ts';import type { NativeLockHandle } from './native-lock.ts';import { committedBlob, headBlob, headCommit } from './pending-import.ts';/** Whether `sourceId` is a strict (git-canonical) source; `lock` reads its row FOR SHARE inside a publication. */export async function sourceCanonicalGit(engine: SqlEngine, sourceId: string, lock = false): Promise<boolean> {const [row] = await engine.executeRaw<{ strict: boolean }>(- `SELECT COALESCE(config->>'canonical','')='git' AS strict FROM sources WHERE id=$1${lock ? ' FOR SHARE' : ''}`, [sourceId]);+ `SELECT COALESCE(config->>'canonical','')='git' AS strict FROM sources WHERE id=$1${ lock ? ' FOR SHARE' : ''}`, [sourceId]);return row?.strict === true;}@@ -37,20 +58,277 @@ export function strictChanged(sourceId: string): OperationError {'Retry the write with a new request_id.');}+/** Test seam: runs after a door commit is written and before the compare-and-swap that moves the branch to it. */+export const doorSeams: { beforeUpdateRef?: (root: string, attempt: number) => Promise<void> | void } = {};++const doorTurns = new Map<string, Promise<void>>();+/** Refusals that keep their own code: the checkout's state, not the commit, stopped the write. */+const TYPED = new Set(['git_detached_head', 'git_branch_unborn', 'git_index_locked', 'git_index_stale']);+const landedFailures = new WeakSet<object>();+/**- * Commits the published files of one publication with one path-only commit under the caller's writer lock and returns- * the commit HEAD then names (the commit that holds these bytes, also when every path was already committed). A- * target Git refuses throws, so the publication rolls back and recovery restores the prior bytes.+ * Commits the published files of one publication under the caller's writer lock and returns the commit HEAD then+ * names (the commit that holds these bytes, also when every path was already committed). A target Git refuses throws,+ * so the publication rolls back and recovery restores the prior bytes.*/export async function commitThroughDoor(root: string, files: { path: string; note?: GitCommitNote }[], writerLock?: NativeLockHandle): Promise<string | null> {- const rel = (path: string) => relative(root, path).split(sep).join('/');- const notes = new Map(files.flatMap(file => file.note ? [[rel(file.path), file.note] as const] : []));- const outcomes = await commitGitTargets(root, files.map(file => rel(file.path)), undefined, notes, writerLock ? { writerLock } : undefined);- for (const [path, outcome] of outcomes) if (outcome instanceof OperationError) {- throw opError(outcome.code === 'git_target_ignored' ? 'git_target_ignored' : 'git_unavailable', `The strict source's commit of ${path} failed, so this write was not published.`,- `${outcome.message} A strict (canonical: git) source publishes a file only once Git holds it; recovery restores the prior bytes. Fix the checkout (git status on the brain host), then retry the write with a new request_id.`);+ let key = resolve(root);+ try { key = realpathSync(root); } catch { /* the session reports a missing checkout */ }+ const prior = doorTurns.get(key) ?? Promise.resolve();+ let release: (() => void) | undefined;+ const turn = prior.then(() => new Promise<void>(done => { release = done; }));+ doorTurns.set(key, turn);+ await prior;+ try {+ return await withSession(root, undefined, writerLock ? { writerLock } : undefined, true, session => doorCommit(session, root, files));+ } catch (error) {+ if (!(error instanceof OperationError) || TYPED.has(error.code) || landedFailures.has(error)) throw error;+ const paths = files.map(file => relative(root, file.path).split(sep).join('/'));+ throw opError(error.code === 'git_target_ignored' ? 'git_target_ignored' : 'git_unavailable', `The strict source's commit of ${paths.join(', ')} failed, so this write was not published.`,+ `${error.message} A strict (canonical: git) source publishes a file only once Git holds it; recovery restores the prior bytes. Fix the checkout (git status on the brain host), then retry the write with a new request_id.`);+ } finally {+ release?.();+ if (doorTurns.get(key) === turn) doorTurns.delete(key);+ }+}++interface TreeEntry { mode: string; oid: Buffer }+interface Target { rel: string; name: string; dir: string; note?: GitCommitNote; mode?: string; oid?: string }++const TREE_MODE = '40000';+const latin1 = (text: string) => Buffer.from(text, 'utf8').toString('latin1');++interface Found { start: number; end: number; mode: string; oid: Buffer }+interface Dir { raw: Buffer; found: Map<string, Found>; edits: Map<string, TreeEntry | null> }++/** Each entry of a raw tree object, by byte range: [start, space) is its mode, (space, nul) its name, (nul, end) its id. */+function eachEntry(raw: Buffer, oidBytes: number, visit: (start: number, space: number, nul: number, end: number) => boolean | void): void {+ for (let at = 0; at < raw.length;) {+ const space = raw.indexOf(0x20, at), nul = space < 0 ? -1 : raw.indexOf(0, space + 1);+ if (space < 0 || nul < 0 || nul + 1 + oidBytes > raw.length) throw gitFailure('Cannot read the canonical Git tree.', 'git cat-file returned a tree object that does not parse.');+ if (visit(at, space, nul, nul + 1 + oidBytes) === false) return;+ at = nul + 1 + oidBytes;}- return headCommit(root);+}++/** The entries of a raw tree named in `names` (latin1), found in one pass without decoding the others. */+function lookupTree(raw: Buffer, oidBytes: number, names: string[]): Map<string, Found> {+ const found = new Map<string, Found>();+ const byLength = new Map<number, Buffer[]>();+ for (const name of new Set(names)) { const bytes = Buffer.from(name, 'latin1'); byLength.set(bytes.length, [...byLength.get(bytes.length) ?? [], bytes]); }+ if (!byLength.size) return found;+ eachEntry(raw, oidBytes, (start, space, nul, end) => {+ for (const name of byLength.get(nul - space - 1) ?? []) if (raw.compare(name, 0, name.length, space + 1, nul) === 0) {+ found.set(name.toString('latin1'), { start, end, mode: raw.toString('latin1', start, space), oid: raw.subarray(nul + 1, end) });+ }+ return found.size < names.length;+ });+ return found;+}++/**+ * A raw tree with `edits` applied (an entry set, or removed by null) and every other entry's bytes kept, in Git's+ * entry order: a new name is inserted where it sorts (a directory sorts as if its name ended in '/').+ */+function rewriteTree(dir: Dir, oidBytes: number): Buffer {+ const ops: { start: number; end: number; bytes: Buffer }[] = [];+ const inserts: { key: Buffer; bytes: Buffer }[] = [];+ for (const [name, entry] of dir.edits) {+ const before = dir.found.get(name);+ const bytes = entry ? Buffer.concat([Buffer.from(`${entry.mode} ${name}\0`, 'latin1'), entry.oid]) : Buffer.alloc(0);+ if (before && entry && (before.mode === TREE_MODE) === (entry.mode === TREE_MODE)) { ops.push({ start: before.start, end: before.end, bytes }); continue; }+ if (before) ops.push({ start: before.start, end: before.end, bytes: Buffer.alloc(0) });+ if (entry) inserts.push({ key: Buffer.from(entry.mode === TREE_MODE ? `${name}/` : name, 'latin1'), bytes });+ }+ inserts.sort((a, b) => Buffer.compare(a.key, b.key));+ let next = 0;+ if (inserts.length) eachEntry(dir.raw, oidBytes, (start, space, nul) => {+ const name = dir.raw.subarray(space + 1, nul);+ const key = space - start === TREE_MODE.length && dir.raw[start] === 0x34 ? Buffer.concat([name, Buffer.from('/')]) : name;+ while (next < inserts.length && Buffer.compare(inserts[next]!.key, key) < 0) ops.push({ start, end: start, bytes: inserts[next++]!.bytes });+ return next < inserts.length;+ });+ while (next < inserts.length) ops.push({ start: dir.raw.length, end: dir.raw.length, bytes: inserts[next++]!.bytes });+ ops.sort((a, b) => a.start - b.start || a.end - b.end);+ const chunks: Buffer[] = [];+ let at = 0;+ for (const op of ops) { chunks.push(dir.raw.subarray(at, op.start), op.bytes); at = op.end; }+ chunks.push(dir.raw.subarray(at));+ return Buffer.concat(chunks);+}++/** Git's whitespace cleanup of a `-m` paragraph, as `git commit -m` applies it: trailing blanks, repeated and edge blank lines go. */+function stripspace(paragraph: string): string {+ const lines: string[] = [];+ for (const line of paragraph.split('\n').map(text => text.replace(/[ \t\r]+$/, ''))) if (line || lines.length && lines[lines.length - 1]) lines.push(line);+ while (lines.length && !lines[lines.length - 1]) lines.pop();+ return lines.join('\n');+}++async function doorCommit(session: GitSession, root: string, files: { path: string; note?: GitCommitNote }[]): Promise<string> {+ const symbolic = await git(session, ['symbolic-ref', '-q', 'HEAD']);+ if (symbolic.code !== 0) throw opError('git_detached_head', `${root} is on a detached HEAD, so the strict source's write has no branch to commit to; nothing was published.`,+ 'Check out the branch the source tracks (git switch <branch>) on the brain host, then retry the write with a new request_id.');+ const branch = symbolic.stdout.trim();+ const layout = await git(session, ['rev-parse', '--show-object-format', '--show-prefix']);+ if (layout.code !== 0) throw gitFailure('Cannot inspect the canonical Git checkout.', 'git rev-parse failed.');+ const [format, prefix = ''] = layout.stdout.split('\n');+ const algorithm = format === 'sha256' ? 'sha256' : 'sha1';+ const oidBytes = algorithm === 'sha256' ? 32 : 20;++ const targets = new Map<string, Target>();+ for (const file of files) {+ const rel = relative(root, nativeFileTarget(root, file.path, 'git_target_unsafe')).split(sep).join('/');+ const full = `${prefix}${rel}`;+ const slash = full.lastIndexOf('/');+ const target = targets.get(rel) ?? { rel, dir: slash < 0 ? '' : full.slice(0, slash), name: latin1(full.slice(slash + 1)) };+ target.note ??= file.note;+ targets.set(rel, target);+ }+ const present = [...targets.values()].filter(target => existsSync(join(root, target.rel)));+ if (present.length) {+ const hashed = await git(session, ['hash-object', '-w', '--', ...present.map(target => target.rel)]);+ const oids = hashed.stdout.split('\n').filter(Boolean);+ if (hashed.code !== 0 || oids.length !== present.length) throw gitFailure('Cannot hash the canonical Git target.', `git hash-object failed for ${present.length} file(s).`);+ present.forEach((target, i) => { target.oid = oids[i]; target.mode = lstatSync(join(root, target.rel)).mode & 0o111 ? '100755' : '100644'; });+ }+ let fileModeTrusted: boolean | undefined;++ const temp = join(persistenceHome(), 'door');+ mkdirSync(temp, { recursive: true, mode: 0o700 });+ const scratch = mkdtempSync(join(temp, 'commit-'));+ try {+ for (let attempt = 0; ; attempt++) {+ const resolved = await git(session, ['rev-parse', '-q', '--verify', `${branch}^{commit}`]);+ if (resolved.code !== 0) throw opError('git_branch_unborn', `Branch ${branch} in ${root} has no commit yet, so the strict source's write has nothing to commit on; nothing was published.`,+ 'Make the first commit on the branch with git on the brain host, then retry the write with a new request_id.');+ const head = resolved.stdout.trim();++ // The directories along every target path, read from HEAD level by level; only the named entries are decoded.+ const want = new Map<string, string[]>([['', []]]);+ for (const target of targets.values()) {+ for (let i = target.dir.indexOf('/'); target.dir; i = target.dir.indexOf('/', i + 1)) {+ const dir = i < 0 ? target.dir : target.dir.slice(0, i);+ const slash = dir.lastIndexOf('/');+ if (!want.has(dir)) want.set(dir, []);+ const parent = slash < 0 ? '' : dir.slice(0, slash);+ want.get(parent)!.push(latin1(dir.slice(slash + 1)));+ if (i < 0) break;+ }+ want.get(target.dir)!.push(target.name);+ }+ const depth = (dir: string) => dir ? dir.split('/').length : 0;+ const byDepth = [...want.keys()].sort((a, b) => depth(a) - depth(b));+ const dirs = new Map<string, Dir>();+ const read = async (dir: string, spec: string | null) => {+ const raw = spec === null ? Buffer.alloc(0) : await gitBytes(session, ['cat-file', 'tree', spec]);+ if (!raw) throw gitFailure('Cannot read the canonical Git tree.', `git cat-file could not read ${spec}.`);+ dirs.set(dir, { raw, found: lookupTree(raw, oidBytes, want.get(dir)!), edits: new Map() });+ };+ const parentOf = (dir: string) => { const slash = dir.lastIndexOf('/'); return { parent: dirs.get(slash < 0 ? '' : dir.slice(0, slash))!, name: latin1(dir.slice(slash + 1)) }; };+ await read('', head);+ for (let level = 1; level <= depth(byDepth[byDepth.length - 1]!); level++) {+ await Promise.all(byDepth.filter(dir => depth(dir) === level).map(dir => {+ const { parent, name } = parentOf(dir);+ const entry = parent.found.get(name);+ return read(dir, entry?.mode === TREE_MODE ? entry.oid.toString('hex') : null);+ }));+ }++ const changed: Target[] = [];+ const fresh: Target[] = [];+ for (const target of targets.values()) {+ const dir = dirs.get(target.dir)!;+ const before = dir.found.get(target.name);+ if (target.oid) {+ if (!before || before.mode === TREE_MODE) fresh.push(target);+ if (before && /^100[0-7]{3}$/.test(before.mode) && target.mode !== before.mode) {+ fileModeTrusted ??= (await git(session, ['config', '--type=bool', '--default=true', 'core.fileMode'])).stdout.trim() !== 'false';+ if (!fileModeTrusted) target.mode = before.mode;+ }+ if (before && before.mode === target.mode && before.oid.toString('hex') === target.oid) continue;+ dir.edits.set(target.name, { mode: target.mode!, oid: Buffer.from(target.oid, 'hex') });+ } else {+ if (!before || before.mode === TREE_MODE) continue;+ dir.edits.set(target.name, null);+ }+ changed.push(target);+ }+ if (fresh.length) await refuseIgnored(session, fresh);+ if (!changed.length) {+ const stale = await git(session, ['diff-index', '--cached', '--quiet', head, '--', ...targets.keys()]);+ if (stale.code !== 0) await syncIndex(session, root, prefix, [...targets.values()], head);+ return head;+ }++ // The trees are rebuilt bottom-up: an emptied directory leaves its parent, the rest are written and linked.+ const written: { path: string; oid: string }[] = [];+ let tree = '';+ for (const path of [...byDepth].reverse()) {+ const dir = dirs.get(path)!;+ if (!dir.edits.size && path) continue;+ const content = rewriteTree(dir, oidBytes);+ const link = path ? parentOf(path) : null;+ if (link && !content.length) { link.parent.edits.set(link.name, null); continue; }+ const oid = createHash(algorithm).update(`tree ${content.length}\0`).update(content).digest();+ const file = join(scratch, `tree-${attempt}-${written.length}`);+ writeFileSync(file, content);+ written.push({ path: file, oid: oid.toString('hex') });+ if (link) link.parent.edits.set(link.name, { mode: TREE_MODE, oid });+ else tree = oid.toString('hex');+ }+ const stored = await git(session, ['hash-object', '-w', '-t', 'tree', '--no-filters', '--', ...written.map(entry => entry.path)]);+ if (stored.code !== 0 || stored.stdout.split('\n').filter(Boolean).join() !== written.map(entry => entry.oid).join()) {+ throw gitFailure('Cannot write the canonical Git tree.', `git hash-object refused a rebuilt tree: ${stored.stderr.trim().slice(0, 300) || 'object ids differ'}.`);+ }++ const noted = new Map(changed.flatMap(target => target.note ? [[target.rel, target.note] as const] : []));+ const message = commitMessage(changed.map(target => target.rel), noted).map(stripspace).filter(Boolean);+ const commit = await git(session, ['commit-tree', tree, '-p', head, ...message.flatMap(paragraph => ['-m', paragraph])]);+ if (commit.code !== 0) throw gitFailure('Cannot commit the canonical Git target.',+ `git commit-tree failed for ${changed.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);+ const created = commit.stdout.trim();+ await doorSeams.beforeUpdateRef?.(root, attempt);+ const moved = await git(session, ['update-ref', '-m', `commit: ${message[0]!.split('\n')[0]}`, branch, created, head]);+ if (moved.code === 0) {+ await syncIndex(session, root, prefix, [...targets.values()], created);+ return created;+ }+ if (attempt) throw new OperationError('git_unavailable', `${branch} in ${root} moved twice while this write was being committed, so it was not committed.`,+ 'Another commit landed in the checkout during the write; nothing of this write is in Git.');+ }+ } finally { rmSync(scratch, { recursive: true, force: true }); }+}++/** The new targets a .gitignore rule excludes (a negated rule matching last un-ignores) refuse as `git_target_ignored`. */+async function refuseIgnored(session: GitSession, fresh: Target[]): Promise<void> {+ // check-ignore takes no literal pathspecs; -n prints one line per path, in order, so no path is parsed back.+ const matched = await git(session, ['check-ignore', '-v', '-n', '--', ...fresh.map(target => target.rel)], false);+ if (matched.code !== 0 && matched.code !== 1) throw gitFailure('Cannot inspect the canonical Git target.', `git check-ignore failed for ${fresh.length} file(s).`);+ const lines = matched.stdout.split('\n');+ fresh.forEach((target, i) => {+ const rule = /^(.*):(\d+):(.*)$/.exec((lines[i] ?? '').split('\t')[0]!);+ if (rule && rule[3] && !rule[3].startsWith('!')) throw ignoredTargetError(target.rel, `${rule[1]}:${rule[2]}: ${rule[3]}`);+ });+}++/**+ * Points the checkout's index entries of the targets at `commit`'s (a removed target leaves the index) and touches no+ * other entry. A failure here comes after the commit landed, so it says so instead of claiming nothing was published.+ */+async function syncIndex(session: GitSession, root: string, prefix: string, targets: Target[], commit: string): Promise<void> {+ const kept = targets.filter(target => target.oid), removed = targets.filter(target => !target.oid);+ let failure = '';+ try {+ const updated = await git(session, ['update-index', '--add', ...kept.flatMap(target => ['--cacheinfo', `${target.mode},${target.oid},${prefix}${target.rel}`]),+ ...(removed.length ? ['--force-remove', '--', ...removed.map(target => target.rel)] : [])]);+ if (updated.code === 0) return;+ failure = updated.stderr.trim().slice(0, 300) || `exit ${updated.code}`;+ } catch (error) { failure = error instanceof Error ? error.message : String(error); }+ const error = opError('git_unavailable', `The strict source's commit ${commit.slice(0, 12)} landed, but the index of ${root} was not updated for ${targets.map(target => target.rel).join(', ')}.`,+ `git update-index failed (${failure}). Git holds the write; until the index is refreshed, git status lists those paths as staged reversions and a commit made from that index would undo them. Run git reset -q -- <those paths> in that checkout on the brain host.`);+ landedFailures.add(error);+ throw error;}/** Whether the working tree and HEAD both hold the record's published state at its path (its bytes, or no entry for a removal). */diff --git a/test/git-door-plumbing-gbra133.test.ts b/test/git-door-plumbing-gbra133.test.tsnew file mode 100644index 0000000000..b77b77254a--- /dev/null+++ b/test/git-door-plumbing-gbra133.test.ts@@ -0,0 +1,283 @@+/**+ * GBRA-133 G2 follow-up: the door commits by plumbing (src/core/persistence/git-door.ts), never through the checkout's+ * index. Protects:+ * - the checkout's index keeps every entry but the published ones byte for byte, stat data included (red before: the+ * porcelain `commit --only` refreshed the whole index, so a stale entry elsewhere was rewritten);+ * - an unrelated staged path stays staged and out of the commit, a dirty or untracked file is untouched;+ * - modes survive (an executable page, a sibling symlink and script), a removal drops its entry and an emptied tree;+ * - a branch moved between build and update-ref is rebuilt once, a second move refuses and the write rolls back;+ * - the message and trailers are the porcelain path's; detached HEAD and unborn branches refuse typed;+ * - a root below the repository toplevel, a non-UTF-8 sibling name and two door commits at once.+ * Seams: `doorSeams.beforeUpdateRef` for the race; real repositories otherwise, and real engines for the rollback.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { commitGitTargets } from '../src/core/persistence/effect-git.ts';+import type { GitCommitNote } from '../src/core/persistence/effect-model.ts';+import { commitThroughDoor, doorSeams } from '../src/core/persistence/git-door.ts';+import { gitChildEnv } from '../src/core/git-env.ts';+import { durableGitRepo } from './helpers/git-publication.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const env = gitChildEnv();+const raw = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env });+const git = (root: string, ...args: string[]) => raw(root, ...args).trim();+const lines = (text: string) => text.split('\n').filter(Boolean);+const OLD = new Date('2001-01-01T00:00:00Z');+const roots: string[] = [];++/** A repository on branch main whose files carry an old mtime, so no index entry is racily clean. */+function repo(files: Record<string, string>, sub = ''): string {+ const top = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-door-plumbing-')));+ roots.push(top);+ git(top, 'init', '-q', '-b', 'main');+ git(top, 'config', 'user.name', 'Example Writer'); git(top, 'config', 'user.email', '[email protected]');+ for (const [path, body] of Object.entries(files)) put(top, path, body);+ git(top, 'add', '-A'); git(top, 'commit', '-qm', 'seed');+ return sub ? join(top, sub) : top;+}+function put(root: string, path: string, body: string): string {+ const file = join(root, path);+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, body);+ utimesSync(file, OLD, OLD);+ return file;+}+/** Every index entry with its stat data (`ls-files --debug`), keyed by path. */+function indexEntries(root: string): Map<string, string> {+ const entries = new Map<string, string>();+ let path = '';+ for (const line of lines(raw(root, 'ls-files', '--debug'))) {+ if (!/^\s/.test(line)) { path = line; entries.set(path, ''); } else entries.set(path, entries.get(path) + line + '\n');+ }+ return entries;+}+const door = (root: string, ...paths: string[]) => commitThroughDoor(root, paths.map(path => ({ path: join(root, path) })));+/** A sandbox's git wrapper may append a co-author trailer to every `git commit` (never to commit-tree): both sides are read without it. */+const unshimmed = (message: string) => message.replace(/^Co-authored-by: .*\n/gm, '').replace(/\n+$/, '\n');+const refusal = (work: Promise<unknown>) => work.then(() => null, (error: { code?: string; message?: string }) => error);++afterEach(() => {+ doorSeams.beforeUpdateRef = undefined;+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+});++describe('G2 plumbing door commit', () => {+ test('the checkout\'s index keeps every other entry byte for byte, stat data included', async () => {+ const root = repo({ 'notes/a.md': 'a\n', 'notes/b.md': 'b\n', 'other/c.md': 'c\n' });+ // Same bytes, newer mtime: other/c.md's index entry is stale until something refreshes the whole index.+ utimesSync(join(root, 'other/c.md'), new Date('2002-01-01T00:00:00Z'), new Date('2002-01-01T00:00:00Z'));+ const before = indexEntries(root);+ put(root, 'notes/a.md', 'a, second revision\n');+ const commit = await door(root, 'notes/a.md');+ const after = indexEntries(root);+ expect(git(root, 'rev-parse', 'HEAD')).toBe(commit!);+ before.delete('notes/a.md'); after.delete('notes/a.md');+ expect(after).toEqual(before);+ expect(git(root, 'ls-files', '-s', '--', 'notes/a.md')).toContain(git(root, 'rev-parse', 'HEAD:notes/a.md'));+ expect(git(root, 'status', '--porcelain')).toBe('');+ });++ test('an unrelated staged path stays staged and out of the commit; dirty and untracked files are untouched', async () => {+ const root = repo({ 'notes/a.md': 'a\n', 'notes/staged.md': 'staged\n', 'other/c.md': 'c\n' });+ put(root, 'notes/staged.md', 'staged, second revision\n');+ git(root, 'add', '--', 'notes/staged.md');+ put(root, 'other/c.md', 'c, edited by hand\n');+ put(root, 'scratch.txt', 'untracked\n');+ put(root, 'notes/a.md', 'a, second revision\n');+ put(root, 'notes/new.md', 'new page\n');+ const commit = await door(root, 'notes/a.md', 'notes/new.md');+ expect(lines(git(root, 'show', '--name-only', '--format=', commit!)).sort()).toEqual(['notes/a.md', 'notes/new.md']);+ expect(lines(git(root, 'diff', '--cached', '--name-only'))).toEqual(['notes/staged.md']);+ expect(git(root, 'show', ':notes/staged.md')).toBe('staged, second revision');+ expect(lines(git(root, 'diff', '--name-only'))).toEqual(['other/c.md']);+ expect(readFileSync(join(root, 'other/c.md'), 'utf8')).toBe('c, edited by hand\n');+ expect(git(root, 'status', '--porcelain', '--', 'scratch.txt')).toBe('?? scratch.txt');+ expect(git(root, 'status', '--porcelain', '--', 'notes/a.md', 'notes/new.md')).toBe('');+ });++ test('an executable page keeps its bit; a sibling symlink and script keep theirs', async () => {+ const root = repo({ 'notes/a.md': 'a\n' });+ put(root, 'notes/run.md', 'run\n'); chmodSync(join(root, 'notes/run.md'), 0o755);+ symlinkSync('run.md', join(root, 'notes/link.md'));+ put(root, 'tools/script.sh', '#!/bin/sh\n'); chmodSync(join(root, 'tools/script.sh'), 0o755);+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'modes');+ const seeded = git(root, 'ls-tree', '-r', 'HEAD');+ put(root, 'notes/run.md', 'run, second revision\n');+ put(root, 'notes/door.md', 'door\n');+ await door(root, 'notes/run.md', 'notes/door.md');+ const tree = new Map(lines(git(root, 'ls-tree', '-r', 'HEAD')).map(line => [line.split('\t')[1]!, line.split('\t')[0]!.split(' ')]));+ expect(tree.get('notes/run.md')![0]).toBe('100755');+ expect(tree.get('notes/door.md')![0]).toBe('100644');+ const old = new Map(lines(seeded).map(line => [line.split('\t')[1]!, line.split('\t')[0]!]));+ expect(tree.get('notes/link.md')!.join(' ')).toBe(old.get('notes/link.md')!);+ expect(tree.get('notes/link.md')![0]).toBe('120000');+ expect(tree.get('tools/script.sh')!.join(' ')).toBe(old.get('tools/script.sh')!);+ expect(git(root, 'status', '--porcelain')).toBe('');+ });++ test('a removal drops its entry, and a directory it empties leaves the tree', async () => {+ const root = repo({ 'notes/a.md': 'a\n', 'notes/gone.md': 'gone\n', 'deep/only/x.md': 'x\n' });+ unlinkSync(join(root, 'notes/gone.md'));+ rmSync(join(root, 'deep'), { recursive: true });+ const commit = await door(root, 'notes/gone.md', 'deep/only/x.md');+ expect(lines(git(root, 'ls-tree', '-r', '--name-only', commit!))).toEqual(['notes/a.md']);+ expect(git(root, 'ls-files')).toBe('notes/a.md');+ expect(git(root, 'status', '--porcelain')).toBe('');+ // Removing what HEAD no longer holds commits nothing and returns HEAD.+ expect(await door(root, 'notes/gone.md')).toBe(commit);+ });++ test('a branch moved before update-ref is rebuilt once on the new HEAD', async () => {+ const root = repo({ 'notes/a.md': 'a\n', 'other/c.md': 'c\n' });+ let human = '';+ doorSeams.beforeUpdateRef = (_root, attempt) => {+ if (attempt) return;+ put(root, 'other/c.md', 'c, committed by hand\n');+ git(root, 'add', '--', 'other/c.md'); git(root, 'commit', '-qm', 'a commit made in the checkout');+ human = git(root, 'rev-parse', 'HEAD');+ };+ put(root, 'notes/a.md', 'a, second revision\n');+ const commit = await door(root, 'notes/a.md');+ expect(git(root, 'rev-parse', 'HEAD')).toBe(commit!);+ expect(git(root, 'rev-parse', 'HEAD^')).toBe(human);+ expect(git(root, 'show', 'HEAD:other/c.md')).toBe('c, committed by hand');+ expect(git(root, 'show', 'HEAD:notes/a.md')).toBe('a, second revision');+ expect(git(root, 'status', '--porcelain')).toBe('');+ });++ test('a branch that moves again refuses; Git and the index keep the other commits', async () => {+ const root = repo({ 'notes/a.md': 'a\n' });+ const seed = git(root, 'rev-parse', 'HEAD:notes/a.md');+ let moves = 0;+ doorSeams.beforeUpdateRef = () => { moves++; git(root, 'commit', '-q', '--allow-empty', '-m', 'moved'); };+ put(root, 'notes/a.md', 'a, second revision\n');+ const error = await refusal(door(root, 'notes/a.md'));+ expect(error).toMatchObject({ code: 'git_unavailable' });+ expect(moves).toBe(2);+ expect(git(root, 'log', '-1', '--format=%s')).toBe('moved');+ expect(git(root, 'rev-parse', 'HEAD:notes/a.md')).toBe(seed);+ expect(git(root, 'ls-files', '-s', '--', 'notes/a.md')).toContain(seed);+ });++ test('the message and trailers are the porcelain path\'s, alone and in a group', async () => {+ const seed = { 'notes/a.md': 'a\n', 'notes/b.md': 'b\n', 'notes/c.md': 'c\n' };+ const notes: Record<string, GitCommitNote> = {+ 'notes/a.md': { subject: 'gbrain: repair notes/a.md ', line: 'notes/a.md (invalid_fence)', trailer: 'gbrain-repair: invalid_fence deterministic high' },+ 'notes/b.md': { subject: 'gbrain: repair notes/b.md', line: 'notes/b.md (frontmatter_slug_conflict)', trailer: 'gbrain-repair: frontmatter_slug_conflict deterministic high' },+ };+ for (const paths of [['notes/a.md'], ['notes/c.md'], ['notes/a.md', 'notes/b.md', 'notes/c.md']]) {+ const porcelain = repo(seed), plumbing = repo(seed);+ for (const root of [porcelain, plumbing]) for (const path of paths) put(root, path, path + ', second revision\n');+ const outcomes = await commitGitTargets(porcelain, paths, undefined, new Map(paths.flatMap(path => notes[path] ? [[path, notes[path]!] as const] : [])));+ expect([...outcomes.values()].every(outcome => !(outcome instanceof Error) && outcome.git === 'committed')).toBe(true);+ await commitThroughDoor(plumbing, paths.map(path => ({ path: join(plumbing, path), note: notes[path] })));+ for (const format of ['%B', '%(trailers:only)', '%an <%ae>']) expect(unshimmed(raw(plumbing, 'log', '-1', '--format=' + format))).toBe(unshimmed(raw(porcelain, 'log', '-1', '--format=' + format)));+ expect(git(plumbing, 'rev-parse', 'HEAD^{tree}')).toBe(git(porcelain, 'rev-parse', 'HEAD^{tree}'));+ expect(git(plumbing, 'reflog', '-1', '--format=%gs')).toBe(git(porcelain, 'reflog', '-1', '--format=%gs'));+ }+ });++ test('new names land where Git sorts them: the tree equals the porcelain commit\'s', async () => {+ const seed = { 'notes/x.md': 'x\n', 'notes/x/inner.md': 'inner\n', 'notes/x-y/inner.md': 'inner\n', 'notes/z.md': 'z\n', 'top.md': 'top\n' };+ const added = ['notes/x.a.md', 'notes/x0.md', 'notes/x/new.md', 'notes/w.md', 'notes/zz.md', 'notes/x-.md', 'fresh/dir/page.md', 'a.md'];+ const porcelain = repo(seed), plumbing = repo(seed);+ for (const root of [porcelain, plumbing]) { for (const path of added) put(root, path, path + '\n'); unlinkSync(join(root, 'notes/z.md')); }+ const paths = [...added, 'notes/z.md'];+ await commitGitTargets(porcelain, paths);+ await door(plumbing, ...paths);+ expect(git(plumbing, 'rev-parse', 'HEAD^{tree}')).toBe(git(porcelain, 'rev-parse', 'HEAD^{tree}'));+ expect(git(plumbing, 'fsck', '--no-dangling', '--strict')).toBe('');+ });++ test('a detached HEAD and an unborn branch refuse typed and commit nothing', async () => {+ const detached = repo({ 'notes/a.md': 'a\n' });+ git(detached, 'checkout', '-q', '--detach');+ const head = git(detached, 'rev-parse', 'HEAD');+ put(detached, 'notes/a.md', 'a, second revision\n');+ expect(await refusal(door(detached, 'notes/a.md'))).toMatchObject({ code: 'git_detached_head' });+ expect(git(detached, 'rev-parse', 'HEAD')).toBe(head);+ const unborn = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-door-plumbing-')));+ roots.push(unborn);+ git(unborn, 'init', '-q', '-b', 'main');+ put(unborn, 'notes/a.md', 'a\n');+ expect(await refusal(door(unborn, 'notes/a.md'))).toMatchObject({ code: 'git_branch_unborn' });+ });++ test('a root below the toplevel commits at its prefix; an ignored new file refuses unless a later rule un-ignores it', async () => {+ const root = repo({ 'brain/notes/a.md': 'a\n', '.gitignore': 'brain/notes/ig*.md\n!brain/notes/ig-kept.md\n', 'README.md': 'top\n' }, 'brain');+ const top = dirname(root);+ put(root, 'notes/a.md', 'a, second revision\n');+ put(root, 'notes/ig-kept.md', 'kept\n');+ const commit = await door(root, 'notes/a.md', 'notes/ig-kept.md');+ expect(lines(git(top, 'show', '--name-only', '--format=', commit!)).sort()).toEqual(['brain/notes/a.md', 'brain/notes/ig-kept.md']);+ expect(git(top, 'status', '--porcelain')).toBe('');+ put(root, 'notes/ignored.md', 'ignored\n');+ const error = await refusal(door(root, 'notes/ignored.md'));+ expect(error).toMatchObject({ code: 'git_target_ignored' });+ expect(error?.message).toContain('notes/ignored.md');+ expect(git(top, 'rev-parse', 'HEAD')).toBe(commit!);+ expect(git(top, 'ls-files', '--', 'brain/notes/ignored.md')).toBe('');+ });++ test('a sibling whose name is not UTF-8 is carried over unchanged', async () => {+ const root = repo({ 'notes/a.md': 'a\n' });+ writeFileSync(Buffer.concat([Buffer.from(join(root, 'notes') + '/'), Buffer.from([0x6e, 0xe9, 0x2e, 0x6d, 0x64])]), 'latin-1 name\n');+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'latin-1 sibling');+ put(root, 'notes/a.md', 'a, second revision\n');+ await door(root, 'notes/a.md');+ expect(lines(git(root, 'diff', '--name-only', 'HEAD^', 'HEAD'))).toEqual(['notes/a.md']);+ expect(git(root, 'rev-parse', 'HEAD^:notes') === git(root, 'rev-parse', 'HEAD:notes')).toBe(false);+ expect(git(root, 'status', '--porcelain')).toBe('');+ });++ test('two door commits of one checkout at once both land, each holding its own file', async () => {+ const root = repo({ 'notes/a.md': 'a\n' });+ put(root, 'notes/one.md', 'one\n'); put(root, 'notes/two.md', 'two\n');+ const [one, two] = await Promise.all([door(root, 'notes/one.md'), door(root, 'notes/two.md')]);+ expect(new Set([one, two]).size).toBe(2);+ expect(git(root, 'show', one + ':notes/one.md')).toBe('one');+ expect(git(root, 'show', two + ':notes/two.md')).toBe('two');+ expect(git(root, 'rev-list', '--count', 'HEAD')).toBe('3');+ expect(git(root, 'status', '--porcelain')).toBe('');+ });+});++const putPage = operations.find(op => op.name === 'put_page')!;+const page = (title: string, body: string) => '---\ntype: note\ntitle: ' + title + '\n---\n\n' + body + '\n';+const strict = (engine: BrainEngine) => engine.executeRaw(`UPDATE sources SET config = config || '{"canonical":"git"}'::jsonb WHERE id='default'`);+const write = (ctx: OperationContext, slug: string, content: string, requestId = randomUUID(), expectedRevision?: string) =>+ putPage.handler(ctx, { slug, content, request_id: requestId, wait_ms: 30_000, ...(expectedRevision ? { expected_revision: expectedRevision } : {}) }) as Promise<Record<string, any>>;+const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };++for (const backend of testBackends()) describe(`[${backend}] G2 plumbing: a raced branch rolls the write back`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ test('a branch that keeps moving refuses the commit; the file and the row keep the prior revision', () => managedBrain(async ({ engine, ctx, root }) => {+ await strict(engine);+ const first = await write(ctx, 'notes/raced', page('Raced', 'First revision.'));+ expect(first).toMatchObject({ state: 'committed' });+ const prior = readFileSync(join(root, 'notes/raced.md'), 'utf8');+ let moves = 0;+ doorSeams.beforeUpdateRef = () => { moves++; git(root, 'commit', '-q', '--allow-empty', '-m', 'moved by hand'); };+ const requestId = randomUUID();+ const result = await write(ctx, 'notes/raced', page('Raced', 'Second revision.'), requestId, first.revision).then(value => value, (error: { code?: string }) => ({ thrown: error.code }));+ doorSeams.beforeUpdateRef = undefined;+ expect(result).not.toMatchObject({ state: 'committed' });+ expect(moves).toBeGreaterThanOrEqual(2);+ expect(readFileSync(join(root, 'notes/raced.md'), 'utf8')).toBe(prior);+ expect(git(root, 'show', 'HEAD:notes/raced.md')).toContain('First revision.');+ expect(git(root, 'status', '--porcelain', '--', 'notes/raced.md')).toBe('');+ const [receipt] = await engine.executeRaw<{ state: string; error_code: string | null }>('SELECT state, error_code FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);+ expect(receipt).toMatchObject({ state: 'failed', error_code: 'git_unavailable' });+ const [row] = await engine.executeRaw<{ compiled_truth: string }>("SELECT compiled_truth FROM pages WHERE source_id='default' AND slug='notes/raced'");+ expect(row!.compiled_truth).toContain('First revision.');+ }, { databaseUrl, setup }), 120_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex bb65741f26..c90150b1ae 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.tstest/forecast-journal.test.tstest/frontmatter-reserved-keys-6454.test.tstest/get-chunks-paging.test.ts+test/git-door-plumbing-gbra133.test.tstest/git-door-strict-gbra133.test.tstest/google-connector-facts-fence-7292.test.tstest/grade-takes-window.test.ts