Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
41.4 KB
Raw Blame
import { randomUUID } from 'node:crypto';
import { execFileSync } from '../spawn.ts';
import { appendFileSync, closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
import { OperationError } from '../ops/contract.ts';
import type { Action } from '../agent-output.ts';
import { gitChildEnv } from '../git-env.ts';
import { flushDirectory } from '../fs-durable.ts';
import { digest, sha256 } from './digest.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
import { OWNERSHIP_MARKER_GLOBS, PHYSICAL_ROOT_MARKER } from './root-metadata.ts';
import { ownerMarkerMissingError } from './owner-marker.ts';

export { OWNERSHIP_MARKER_GLOBS, PHYSICAL_ROOT_MARKER, isPhysicalRootMetadata } from './root-metadata.ts';
const RESERVATION_PREFIX = '.gbrain-owner-';
/**
 * Appends the marker globs to the exclude file of every Git checkout holding
 * `directories` (resolved with `git rev-parse --git-path`, so a linked
 * worktree writes its shared file). Idempotent; a repository-local file, never
 * committed; a missing trailing newline is repaired first. Best effort: an
 * unreadable checkout or a read-only git dir leaves the stamp in place and the
 * push deny list as the backstop.
 */
export function excludeOwnershipMarkers(directories: readonly string[]): void {
  const written = new Set<string>();
  for (const directory of directories) {
    let exclude: string;
    try {
      if (!statSync(directory).isDirectory()) continue;
      const path = execFileSync('git', ['-C', directory, 'rev-parse', '--git-path', 'info/exclude'],
        { stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv() }).toString().trim();
      if (!path) continue;
      exclude = resolve(directory, path);
    } catch { continue; }
    if (written.has(exclude)) continue;
    written.add(exclude);
    try {
      mkdirSync(dirname(exclude), { recursive: true });
      const body = existsSync(exclude) ? readFileSync(exclude, 'utf8') : '';
      const present = new Set(body.split('\n').map(line => line.trim()));
      const missing = OWNERSHIP_MARKER_GLOBS.filter(glob => !present.has(glob));
      if (!missing.length) continue;
      appendFileSync(exclude, `${body.length && !body.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`);
    } catch { /* best effort; the push deny list refuses a tracked marker */ }
  }
}
export interface PhysicalRootReservation {
  version: 1; token: string; brainId: string; worktreeId: string; hostId: string;
  root: string; coordinationPath: string; initialDevice: string | null; initialInode: string | null; initialBirth: string | null;
}
export interface PhysicalRootStamp { version: 1; token: string; brainId: string; worktreeId: string; root: string; device: string; inode: string; birth: string; }
const uuid = (value: unknown): value is string => typeof value === 'string' && /^[a-f0-9-]{36}$/i.test(value);
export function physicalRootError(message = 'The physical checkout identity changed or belongs to another owner.'): OperationError {
  return new OperationError('recovery_required', message, 'Use verified writer transfer or source recovery; do not remove ownership markers to claim this path.');
}
/** GST-465: an ownership record whose mode lets other users read it (a recursive chmod of a copied brain) proves nothing about its owner. */
export function ownershipRecordNotPrivateError(): OperationError {
  const error = physicalRootError('A private ownership record of this checkout is readable by other users, so the checkout identity cannot be verified.');
  error.detail = 'ownership_record_not_private';
  error.suggestion = 'On the brain host, gbrain doctor --only foreign_ownership_marker names the record and the chmod 600 that makes it private again. Never remove an ownership record to get past this.';
  return error;
}
/**
 * Doctor only: an ownership record other users can read, with the mode and the brain and worktree it records, or null when
 * it is private, absent, not a regular file or not well formed (Windows: always null). Never authority for a write.
 */
export function openOwnershipRecord(path: string): { mode: number; brainId: string; worktreeId: string } | null {
  if (process.platform === 'win32') return null;
  try {
    const info = lstatSync(path);
    if (!info.isFile() || (info.mode & 0o077) === 0 || info.size > 16_384) return null;
    const value = JSON.parse(readFileSync(path, 'utf8')) as { version?: unknown; brainId?: unknown; worktreeId?: unknown } | null;
    if (!value || value.version !== 1 || !uuid(value.brainId) || !uuid(value.worktreeId)) return null;
    return { mode: info.mode & 0o777, brainId: value.brainId, worktreeId: value.worktreeId };
  } catch { return null; }
}
export function physicalRootReservationPath(root: string): string {
  return join(dirname(root), `${RESERVATION_PREFIX}${sha256(root)}.json`);
}
function readPrivate(path: string): unknown | null {
  let fd: number | undefined;
  try {
    if (lstatSync(path).isSymbolicLink()) throw physicalRootError();
    fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
    const info = fstatSync(fd);
    if (!info.isFile() || info.size > 16_384) throw physicalRootError();
    if (process.platform !== 'win32' && (info.mode & 0o077) !== 0) throw ownershipRecordNotPrivateError();
    const value = JSON.parse(readFileSync(fd, 'utf8'));
    if (!value || typeof value !== 'object') throw physicalRootError();
    return value;
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
    if (error instanceof OperationError && error.detail === 'ownership_record_not_private') throw error;
    throw physicalRootError('The private physical-checkout identity cannot be verified.');
  } finally { if (fd !== undefined) closeSync(fd); }
}
/** Never rename over another claimant. A torn reservation remains a refusal. */
function createPrivate(path: string, value: unknown): boolean {
  let fd: number;
  try { fd = openSync(path, 'wx', 0o600); }
  catch (error) { if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false; throw physicalRootError('Cannot reserve the physical checkout privately.'); }
  try { writeFileSync(fd, JSON.stringify(value)); fsyncSync(fd); }
  finally { closeSync(fd); }
  flushDirectory(dirname(path));
  return true;
}
export function readPhysicalRootReservation(path: string): PhysicalRootReservation | null {
  return readReservationRecord(canonicalFilesystemPath(path));
}
/** #5914: the reservation written for `recorded` as it was recorded, even when that path now resolves elsewhere through a symlink. */
export function readRecordedPhysicalRootReservation(recorded: string): PhysicalRootReservation | null {
  return readReservationRecord(recorded);
}
/** Whether `path` is `root` or lies under it (both canonical). */
export function coordinationPathInsideRoot(root: string, path: string): boolean {
  const rel = relative(root, path);
  return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
}
/** `directory`: where to look for the reservation named for `root`; beside `root` unless a renamed parent carried it (#8625). */
function readReservationRecord(root: string, allowInsideLock = false, directory = dirname(root)): PhysicalRootReservation | null {
  const value = readPrivate(join(directory, `${RESERVATION_PREFIX}${sha256(root)}.json`)) as PhysicalRootReservation | null;
  if (value === null) return null;
  if (value.version !== 1 || ![value.token,value.brainId,value.worktreeId,value.hostId].every(uuid)
    || value.root !== root || typeof value.coordinationPath !== 'string' || !isAbsolute(value.coordinationPath) || value.coordinationPath.includes('\0')
    || ![value.initialDevice,value.initialInode,value.initialBirth].every(part => part === null || typeof part === 'string' && /^\d+$/.test(part))) throw physicalRootError();
  if (canonicalFilesystemPath(value.coordinationPath) !== value.coordinationPath) throw physicalRootError();
  if (!allowInsideLock && coordinationPathInsideRoot(root, value.coordinationPath)) throw physicalRootError('The stable coordination lock must live outside the canonical checkout. '
    + 'A reservation an older release wrote with its lock inside the checkout (GBRAIN_HOME inside the source root) is repaired by the next claim of this checkout on the host that reserved it; do not delete it.');
  return value;
}
/** #6766: the reservation an older release wedged with its lock inside the checkout (every other field valid), or null. */
export function readWedgedPhysicalRootReservation(path: string): PhysicalRootReservation | null {
  const root = canonicalFilesystemPath(path);
  const value = readReservationRecord(root, true);
  return value && coordinationPathInsideRoot(root, value.coordinationPath) ? value : null;
}
/** The guard every wedged-reservation repairer of `root` takes: beside the reservation, so it never depends on the coordination env. */
export function reservationRepairGuardPath(root: string): string {
  return `${physicalRootReservationPath(canonicalFilesystemPath(root))}.repair.lock`;
}
/**
 * #6766: rewrite only the coordinationPath of a wedged reservation. The caller holds the repair guard and verified the
 * brain, host and absence of a worktree row; the record is re-read and compared by digest before the atomic rename.
 */
export function repairReservationCoordinationPath(path: string, expected: PhysicalRootReservation, coordinationPath: string): void {
  const root = canonicalFilesystemPath(path);
  if (expected.root !== root || canonicalFilesystemPath(coordinationPath) !== coordinationPath || coordinationPathInsideRoot(root, coordinationPath)) {
    throw physicalRootError('The repaired coordination lock must be a canonical path outside the canonical checkout.');
  }
  replacePrivate(physicalRootReservationPath(root), { ...expected, coordinationPath }, () => {
    const current = readReservationRecord(root, true);
    if (!current || digest(current) !== digest(expected)) {
      const error = physicalRootError('The ownership reservation changed while its coordination lock was being repaired; run the claim again.');
      error.detail = 'stale_record';
      throw error;
    }
  });
  if (readPhysicalRootReservation(root)?.coordinationPath !== coordinationPath) throw physicalRootError('The repaired ownership reservation contains unexpected bytes.');
}
export function readPhysicalRootStamp(root: string): PhysicalRootStamp | null {
  const value = readPrivate(join(root, PHYSICAL_ROOT_MARKER)) as PhysicalRootStamp | null;
  if (value && (value.version !== 1 || ![value.token,value.brainId,value.worktreeId].every(uuid)
    || typeof value.root !== 'string' || !isAbsolute(value.root)
    || ![value.device,value.inode,value.birth].every(part => typeof part === 'string' && /^\d+$/.test(part)))) throw physicalRootError();
  return value;
}
export function restorePhysicalRootReservation(value: PhysicalRootReservation): void {
  createPrivate(physicalRootReservationPath(value.root), value);
}
export function reservePhysicalRootRecord(root: string, identity: Omit<PhysicalRootReservation, 'version' | 'token' | 'root' | 'initialDevice' | 'initialInode' | 'initialBirth'>): PhysicalRootReservation {
  const info = existsSync(root) ? statSync(root, { bigint: true }) : null;
  if (info && !info.isDirectory()) throw physicalRootError('The canonical checkout path is not a directory.');
  const value: PhysicalRootReservation = { version: 1, token: randomUUID(), root, ...identity,
    initialDevice: info?.dev.toString() ?? null, initialInode: info?.ino.toString() ?? null, initialBirth: info?.birthtimeNs.toString() ?? null };
  createPrivate(physicalRootReservationPath(root), value);
  return readPhysicalRootReservation(root)!;
}
/**
 * Every contender reserves before this scan, so racing ancestor/child claims cannot both succeed.
 * A subdirectory removed while the scan runs (git gc pruning loose objects) holds no reservation.
 */
export function assertNoPhysicalRootOverlap(root: string): void {
  for (let parent = dirname(root); parent !== root; parent = dirname(parent)) {
    if (readPhysicalRootReservation(parent) || existsSync(join(parent, PHYSICAL_ROOT_MARKER))) throw physicalRootError('This path lies inside another reserved canonical root.');
    if (parent === dirname(parent)) break;
  }
  if (!existsSync(root)) return;
  const visit = (directory: string) => {
    let entries;
    try { entries = readdirSync(directory, { withFileTypes: true }); } catch (error) {
      const code = (error as NodeJS.ErrnoException).code;
      if (directory !== root && (code === 'ENOENT' || code === 'ENOTDIR')) return;
      throw error;
    }
    for (const entry of entries) {
      if (entry.name.startsWith(RESERVATION_PREFIX) && entry.name.endsWith('.json') || directory !== root && entry.name === PHYSICAL_ROOT_MARKER) {
        throw physicalRootError('This root contains another reserved canonical root.');
      }
      if (entry.isDirectory()) visit(join(directory, entry.name));
    }
  };
  visit(root);
}
export function writePhysicalRootStamp(directory: string, reservation: PhysicalRootReservation): void {
  const info = statSync(directory, { bigint: true });
  if (!info.isDirectory()) throw physicalRootError();
  const stampFor = (live: { dev: bigint; ino: bigint; birthtimeNs: bigint }): PhysicalRootStamp => ({ version: 1, token: reservation.token, brainId: reservation.brainId,
    worktreeId: reservation.worktreeId, root: reservation.root, device: live.dev.toString(), inode: live.ino.toString(), birth: live.birthtimeNs.toString() });
  const marker = join(directory, PHYSICAL_ROOT_MARKER);
  createPrivate(marker, stampFor(info));
  // #6501 belt-and-braces: the stamp records what the directory reports after the marker landed in it.
  const after = statSync(directory, { bigint: true });
  if (after.dev !== info.dev || after.ino !== info.ino || after.birthtimeNs !== info.birthtimeNs) replacePrivate(marker, stampFor(after));
  assertPhysicalRootStamp(directory, reservation);
  excludeOwnershipMarkers([directory, reservation.root, dirname(reservation.root)]);
}
/**
 * #6501: how far a persisted directory birth stamp may sit from the live
 * `birthtimeNs` and still name the same directory. APFS reports a freshly
 * created directory's birth time tens of nanoseconds apart between the
 * process that created it and later processes (one Apple-Silicon timebase
 * tick), which left every write to such a root refused forever. 1 µs is 20x
 * the reported drift and far below anything a removed-and-recreated directory
 * can land in; everything else about the stamp (owner token, brain, worktree,
 * root, inode, device) still has to agree exactly.
 */
export const PHYSICAL_BIRTH_TOLERANCE_NS = 1_000n;
/**
 * Whether a persisted birth stamp names the live directory. Equal strings
 * always match (so `'0'` against a filesystem that reports no birth time
 * keeps working); a malformed stamp, or a zero on either side against a
 * non-zero on the other, fails closed; otherwise the two may differ by at
 * most PHYSICAL_BIRTH_TOLERANCE_NS. Persisted-stamp comparisons only: the
 * in-process path-race check, the staging identity and the prepared-record
 * digest compare exactly, because they guard a running operation.
 */
export function samePhysicalBirth(stored: string | null | undefined, live: bigint): boolean {
  if (typeof stored !== 'string' || !/^\d{1,30}$/.test(stored)) return false;
  const value = BigInt(stored);
  if (value === live) return true;
  if (value === 0n || live === 0n) return false;
  return (value > live ? value - live : live - value) <= PHYSICAL_BIRTH_TOLERANCE_NS;
}
/** #8625: a checkout found at `root` whose stamp records a root that no longer exists, and the move that explains it. Refusal evidence, never ownership authority. */
export interface MovedPhysicalRoot {
  recorded: string; root: string; brainId: string; worktreeId: string;
  /** The folder that moved: the checkout itself, or the renamed parent that carried it (`ancestor`). */
  from: string; to: string; ancestor: boolean;
  /** The live directory is the stamped one (device, inode and birth time), so moving it back reattaches the worktree. */
  sameDirectory: boolean;
}
/**
 * #8625: reads only the stamp in `root` and the reservation of the root it records: beside that old root when the checkout
 * itself moved, or beside `root` (still named for the old root) when a parent folder was renamed and carried both along.
 * The moved parent is the deepest one the paths share a tail below that no longer exists, so a folder moved under another
 * folder of the same name names itself, never the folders that held it.
 * A recorded root that still exists (a copy), a stamp and reservation that disagree on token, brain or worktree, or a
 * parent rename that also renamed the checkout is no move (null). An ownership record other users can read keeps its own refusal.
 */
export function describeMovedPhysicalRoot(root: string): MovedPhysicalRoot | null {
  try {
    const stamp = readPhysicalRootStamp(root);
    if (!stamp || stamp.root === root || existsSync(stamp.root)) return null;
    let reservation = readReservationRecord(stamp.root), from = stamp.root, to = root;
    if (!reservation) {
      const recorded = stamp.root.split(sep), current = root.split(sep);
      let shared = 0;
      while (shared < Math.min(recorded.length, current.length) - 2 && recorded[recorded.length - 1 - shared] === current[current.length - 1 - shared]) shared++;
      while (shared && existsSync(recorded.slice(0, -shared).join(sep))) shared--;
      if (!shared) return null;
      reservation = readReservationRecord(stamp.root, false, dirname(root));
      from = recorded.slice(0, -shared).join(sep); to = current.slice(0, -shared).join(sep);
    }
    if (!reservation || reservation.token !== stamp.token || reservation.brainId !== stamp.brainId || reservation.worktreeId !== stamp.worktreeId) return null;
    const info = statSync(root, { bigint: true });
    return { recorded: stamp.root, root, brainId: stamp.brainId, worktreeId: stamp.worktreeId, from, to, ancestor: from !== stamp.root,
      sameDirectory: stamp.device === info.dev.toString() && stamp.inode === info.ino.toString() && samePhysicalBirth(stamp.birth, info.birthtimeNs) };
  } catch (error) {
    if (error instanceof OperationError && error.detail === 'ownership_record_not_private') throw error;
    return null;
  }
}
export const PHYSICAL_ROOT_MOVED_MESSAGE = 'This folder holds the ownership stamp of a canonical checkout that was moved here from the path it is recorded at.';
/** #8625: the path-free refusal of `reservePhysicalRoot`, which remote page writes reach through the automatic claim. */
export function physicalRootMovedError(): OperationError {
  const error = physicalRootError(PHYSICAL_ROOT_MOVED_MESSAGE);
  error.detail = 'physical_root_moved';
  error.suggestion = 'Nothing changed. On the brain host, run the same gbrain sources add, set-path or writer claim with --dry-run in a terminal: it names the recorded path and the commands that bring the checkout back. Moving folders is the user\'s decision. Never remove the ownership markers.';
  error.docs = 'docs/guides/write-refusals.md#moved-root';
  return error;
}
const shellQuote = (path: string) => `'${path.replaceAll("'", "'\\''")}'`;
/**
 * #8625: the local CLI refusal for a moved checkout, with the exit built from existing verbs. A worktree that still has
 * sources: a symlink at the old path, `set-path` for each source (the #5914 relocation), then the symlink removed. One
 * whose source was removed: move it back and re-add (or claim) at the recorded path, which reattaches the worktree. A
 * folder that is not the stamped directory any more cannot be reattached by moving it, so the exit is restore or deactivate.
 */
export function physicalRootMovedRefusal(moved: MovedPhysicalRoot, exit: { sourceId: string; operation: 'add' | 'claim' | 'rebind'; members: Array<{ sourceId: string; relativePath: string }> }): OperationError {
  const { recorded, root, from, to, worktreeId } = moved, q = shellQuote;
  const where = `The checkout at ${q(root)} is worktree ${worktreeId}, recorded at ${q(recorded)}${moved.ancestor ? `; its folder ${q(from)} was moved to ${q(to)}` : ''}.`;
  const user = (why: string, argv: string[], user_message: string, extra: Partial<Action> = {}): Action =>
    ({ ask_user: true, argv, consent: [], actor: 'user', requires_exclusive: false, why, user_message, docs: 'docs/guides/write-refusals.md#moved-root', ...extra });
  const error = physicalRootError(where);
  error.detail = 'physical_root_moved';
  error.docs = 'docs/guides/write-refusals.md#moved-root';
  if (exit.members.length) {
    const steps = exit.members.map(member => ['gbrain', 'sources', 'set-path', member.sourceId, member.relativePath ? join(root, member.relativePath) : root]);
    error.message = `${where} It holds source${steps.length > 1 ? 's' : ''} ${exit.members.map(member => member.sourceId).join(', ')}.`;
    // The first set-path moves the worktree; each further source of it is pointed at the new path once the symlink is gone.
    const [first, ...rest] = steps, setPathText = (step: string[]) => `gbrain sources set-path ${step[3]} ${q(step[4])}`;
    error.suggestion = `Nothing changed. Ask the user before touching their folders. Then leave a symlink at the old path with ln -s ${q(to)} ${q(from)}, run ${setPathText(first)} `
      + `(it keeps worktree ${worktreeId} and its history and moves the ownership records to the new path), then remove the symlink with rm ${q(from)}`
      + `${rest.length ? `, then run ${rest.map(setPathText).join(', then ')}` : ''}. Never remove the ownership markers.`;
    const pointAt = (step: string[], then?: Action) => user(`Moves source ${step[3]}'s canonical path to the checkout's new place, keeping its worktree and history.`, step,
      `May I update source ${step[3]} to point at ${step[4]}?`, then ? { then } : {});
    let after: Action | undefined;
    for (const step of [...rest].reverse()) after = pointAt(step, after);
    const then = pointAt(first, user('Removes the symlink left at the old path; the checkout stays where it is now.', ['rm', from], 'The symlink at the old path is no longer needed. May I remove it?',
      after ? { then: after } : {}));
    error.fix = user(`Leaves a symlink at the old path so gbrain can verify the moved checkout is the same worktree before it moves its records.`, ['ln', '-s', to, from],
      `Your brain folder moved from ${from} to ${to}. I can leave a symlink at the old path, update gbrain's record of it, then remove the symlink; your files and Git history stay as they are. Shall I go ahead?`,
      { then, verify: { argv: [...steps[0], '--dry-run'] } });
    return error;
  }
  const label = exit.operation === 'claim' ? 'gbrain sources writer claim' : 'gbrain sources add';
  if (!moved.sameDirectory) {
    error.message = `${where} It has no source since its source was removed, and this folder is a copy, not the stamped directory (its device, inode or birth time differs).`;
    error.suggestion = `Nothing changed. Moving this copy back to ${q(recorded)} would not reattach worktree ${worktreeId}. Restore the original folder at ${q(recorded)} from a backup, then rerun ${label} ${exit.sourceId} --path ${q(recorded)}; `
      + 'or, if it is gone for good, switch the brain to classic mode with gbrain sources writer deactivate --dry-run (then the printed apply_command) and add the folder there. Never remove the ownership markers.';
    error.fix = user('Read-only preview of switching the brain to classic mode, where the copied folder can be added without the old ownership records.',
      ['gbrain', 'sources', 'writer', 'deactivate', '--dry-run'],
      `Your brain folder was copied to ${root} and the original at ${recorded} is gone. gbrain cannot reattach a copy. Do you want to restore the original from a backup, or switch the brain to classic mode?`);
    return error;
  }
  const command = exit.operation === 'claim' ? ['gbrain', 'sources', 'writer', 'claim', exit.sourceId, '--path', recorded]
    : ['gbrain', 'sources', 'add', exit.sourceId, '--path', recorded, ...(existsSync(join(root, '.git')) ? [] : ['--force'])];
  const readd = exit.operation === 'claim' ? [...command, '--admin-intent', 'writer_claim', '--expected-state', '<admin_state>'] : command;
  error.message = `${where} It has no source since its source was removed; the worktree and its history are kept.`;
  error.suggestion = `Nothing changed. Ask the user before touching their folders. Then move it back with mv ${q(to)} ${q(from)} and run ${label} ${exit.sourceId} --path ${q(recorded)}${exit.operation === 'claim' ? ' (with the admin intent writer status prints)' : ''}, `
    + `which reattaches worktree ${worktreeId} and its history. To keep the folder at its new place afterwards, move it again and run gbrain sources set-path ${exit.sourceId} --dry-run: it names the symlink steps. Never remove the ownership markers.`;
  error.fix = user('Moves the folder back to where gbrain recorded it, so the worktree and its history can be reattached.', ['mv', to, from],
    `Your brain folder moved from ${from} to ${to}, and gbrain only recognizes it at the old path. May I move it back and re-add it there? You can move it again afterwards with gbrain's help.`,
    { verify: { argv: [...command, '--dry-run'] },
      then: user(`Re-registers source ${exit.sourceId} at the recorded path, which reattaches worktree ${worktreeId}.`, readd, `May I register source ${exit.sourceId} at ${recorded}?`,
        exit.operation === 'claim' ? { inputs: [{ name: 'admin_state', how: 'admin_state from gbrain sources writer status --json on the brain host' }] } : {}) });
  return error;
}
const DIRECTORY_CHANGED_MESSAGE = 'The checkout directory at the recorded root is not the one this owner stamped (its inode or birth time changed) while the owner token, brain, worktree, root and device still match. '
  + 'Inspect writer status and use the deliberate self-transfer that confirms a relocated root to re-stamp this same path.';
/** A stored refusal message (a write receipt keeps code and message only) that is the #5914 directory-changed refusal. */
export const isPhysicalRootDirectoryChangedMessage = (message: string | null | undefined): boolean => message === DIRECTORY_CHANGED_MESSAGE;
/**
 * #7671: the relocated-root self-transfer as the refusal's fix, a host-admin step: prepare, then accept. `root` and
 * `epoch` are filled when the caller holds the binding; otherwise they are inputs read from writer status.
 */
export function relocatedRootTransferFix(sourceId: string, binding?: { root: string; epoch: string }): Action {
  const intent = (phase: string) => ['--admin-intent', `writer_transfer_${phase}`, '--expected-state', '<admin_state>'];
  const adminState = { name: 'admin_state', how: `admin_state from gbrain sources writer status ${sourceId} --json on the owner host (read it again before the accept)` };
  const prepare = ['gbrain', 'sources', 'writer', 'transfer', 'prepare', sourceId, '--self-transfer', '--confirm-relocated-root'];
  return { argv: [...prepare, ...intent('prepare')], preview_argv: [...prepare, '--dry-run'], inputs: [adminState], consent: [], actor: 'host_admin', requires_exclusive: false,
    docs: 'docs/guides/write-refusals.md#physical_root_directory_changed',
    why: `Source ${sourceId}'s checkout is a new directory at its recorded path (a restored or copied brain). The self-transfer re-stamps this same path on this host when everything but the directory identity still matches; never remove the ownership markers instead.`,
    then: { argv: ['gbrain', 'sources', 'writer', 'transfer', 'accept', sourceId, '--path', binding?.root ?? '<root>', '--expected-epoch', binding?.epoch ?? '<owner_epoch>',
      '--manifest', '<manifest digest printed by prepare>', '--self-transfer', '--confirm-relocated-root', ...intent('accept')],
    inputs: [adminState, ...(binding ? [] : [{ name: 'root', how: 'the binding root writer status prints' }, { name: 'owner_epoch', how: 'the owner_epoch prepare printed' }])],
    consent: [], actor: 'host_admin', requires_exclusive: false, why: 'Accepts the self-transfer: ownership stays on this host and writes to the source resume; retry the refused write with the same request_id.' } };
}
/** The #5914 exit for a directory recreated at its recorded path; filled with the source and root by lockWorktree (ownership.ts). */
export function physicalRootDirectoryChangedError(): OperationError {
  const error = physicalRootError(DIRECTORY_CHANGED_MESSAGE);
  error.detail = 'physical_root_directory_changed';
  error.suggestion = 'On the brain host, run gbrain sources writer status <source> and note admin_state, then gbrain sources writer transfer prepare <source> --self-transfer --confirm-relocated-root '
    + '--admin-intent writer_transfer_prepare --expected-state <admin_state>, then gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <manifest digest printed by prepare> '
    + '--self-transfer --confirm-relocated-root --admin-intent writer_transfer_accept --expected-state <admin_state from a fresh status>. Never remove the ownership markers to claim this path.';
  return error;
}
/** directory may be a verified staging directory; its stamp always names the final root. */
export function assertPhysicalRootStamp(directory: string, reservation: PhysicalRootReservation): void {
  const value = readPrivate(join(directory, PHYSICAL_ROOT_MARKER)) as PhysicalRootStamp | null;
  const info = statSync(directory, { bigint: true });
  // #8368: no stamp in a directory the reservation still identifies exactly (device, inode, birth) lost only its marker, and
  // the plain self-transfer re-creates it. A recreated or staged directory, one whose birth only drifted within tolerance
  // (the self-transfer compares it exactly), or one the reservation cannot identify keeps the generic refusal.
  if (value === null && reservation.initialDevice === info.dev.toString() && reservation.initialInode === info.ino.toString()
    && reservation.initialBirth === info.birthtimeNs.toString()) throw ownerMarkerMissingError();
  if (!value || value.version !== 1 || value.token !== reservation.token || value.brainId !== reservation.brainId || value.worktreeId !== reservation.worktreeId
    || value.root !== reservation.root) throw physicalRootError();
  if (value.inode !== info.ino.toString() || !samePhysicalBirth(value.birth, info.birthtimeNs)) {
    // #6501 door parity with the device change below: a well-formed stamp whose directory identity alone moved names the #5914 exit;
    // a malformed birth stamp is a damaged record, not a recreated directory, and keeps the generic refusal.
    if (value.device === info.dev.toString() && typeof value.birth === 'string' && /^\d+$/.test(value.birth)) throw physicalRootDirectoryChangedError();
    throw physicalRootError();
  }
  if (value.device !== info.dev.toString()) {
    if (typeof value.device === 'string' && /^\d+$/.test(value.device)) {
      const error = physicalRootError('The filesystem device identifier changed while the other checkout identity fields still match. Inspect writer status and use deliberate self-transfer to re-stamp this same root.');
      error.detail = 'physical_root_device_changed';
      throw error;
    }
    throw physicalRootError();
  }
}
/**
 * #5604: macOS may give the same checkout a new st_dev after a reboot. The
 * owner token binds the stamp, so a change is device-only when the stamp still
 * names this reservation, root, inode and a non-zero birth time. Filesystems
 * that report no birth time (some Linux mounts) keep the refusal.
 */
export function physicalRootDeviceChange(stamp: PhysicalRootStamp, reservation: Pick<PhysicalRootReservation, 'token' | 'brainId' | 'worktreeId' | 'root'>,
  info: { dev: bigint; ino: bigint; birthtimeNs: bigint }): { from: string; to: string } | null {
  if (stamp.token !== reservation.token || stamp.brainId !== reservation.brainId || stamp.worktreeId !== reservation.worktreeId
    || stamp.root !== reservation.root || stamp.inode !== info.ino.toString() || !samePhysicalBirth(stamp.birth, info.birthtimeNs)
    || info.birthtimeNs === 0n || stamp.device === info.dev.toString()) return null;
  return { from: stamp.device, to: info.dev.toString() };
}
function replacePrivate(path: string, value: unknown, beforeRename?: () => void): void {
  const temporary = `${path}.${randomUUID()}.tmp`;
  let created = false;
  try {
    created = createPrivate(temporary, value);
    if (!created || digest(readPrivate(temporary)) !== digest(value)) throw physicalRootError('The re-stamped ownership record contains unexpected bytes.');
    beforeRename?.();
    renameSync(temporary, path); created = false; flushDirectory(dirname(path));
  } finally { if (created) try { unlinkSync(temporary); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } }
}
/**
 * #5914: compare-and-swap of the outside-root reservation for a deliberate
 * relocation (recreated directory, moved checkout). The caller holds the
 * outside-root native lock and verified database ownership. A reservation
 * already equal to `next` is a no-op; one that matches neither `expected` nor
 * `next` was changed by someone else and refuses with detail `stale_record`.
 */
export function replacePhysicalRootReservation(root: string, expected: PhysicalRootReservation, next: PhysicalRootReservation): void {
  if (next.root !== root || expected.root !== root || next.token !== expected.token || next.worktreeId !== expected.worktreeId || next.brainId !== expected.brainId) throw physicalRootError();
  const current = readPhysicalRootReservation(root);
  if (current && digest(current) === digest(next)) return;
  if (!current || digest(current) !== digest(expected)) {
    const error = physicalRootError('The ownership reservation changed since this relocation was prepared; prepare it again from a fresh writer status.');
    error.detail = 'stale_record';
    throw error;
  }
  replacePrivate(physicalRootReservationPath(root), next);
  if (digest(readPhysicalRootReservation(root)) !== digest(next)) throw physicalRootError('The re-stamped ownership reservation contains unexpected bytes.');
}
/** Caller holds the outside-root native lock and verified database ownership; only the device fields change. */
export function restampPhysicalRootDevice(root: string, reservation: PhysicalRootReservation, stamp: PhysicalRootStamp, change: { from: string; to: string }): void {
  if (reservation.initialDevice === change.from) replacePrivate(physicalRootReservationPath(root), { ...reservation, initialDevice: change.to });
  replacePrivate(join(root, PHYSICAL_ROOT_MARKER), { ...stamp, device: change.to });
  assertPhysicalRootStamp(root, readPhysicalRootReservation(root)!);
}
/** Explicit verified transfer may adopt a copied stamp of this same logical worktree. */
export function adoptTransferredRootStamp(directory: string, reservation: PhysicalRootReservation, temporaryToken: string = randomUUID()): void {
  const path = join(directory, PHYSICAL_ROOT_MARKER);
  const previous = readPrivate(path) as PhysicalRootStamp | null;
  if (previous && (previous.brainId !== reservation.brainId || previous.worktreeId !== reservation.worktreeId)) throw physicalRootError();
  if (previous) {
    try { assertPhysicalRootStamp(directory, reservation); return; } catch {}
  }
  const info = statSync(directory, { bigint: true });
  const stamp: PhysicalRootStamp = { version: 1, token: reservation.token, brainId: reservation.brainId, worktreeId: reservation.worktreeId,
    root: reservation.root, device: info.dev.toString(), inode: info.ino.toString(), birth: info.birthtimeNs.toString() };
  const temporary = `${path}.${temporaryToken}.tmp`;
  let created = false;
  try {
    created = createPrivate(temporary, stamp);
    if (digest(readPrivate(temporary)) !== digest(stamp)) throw physicalRootError('The prepared ownership stamp contains unexpected bytes.');
    renameSync(temporary, path); flushDirectory(directory);
  } finally { if (created) try { unlinkSync(temporary); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } }
  assertPhysicalRootStamp(directory, reservation);
  excludeOwnershipMarkers([directory, reservation.root, dirname(reservation.root)]);
}
/**
 * #5914: the identity check a release that publishes nothing needs. The
 * outside-root reservation must name this worktree (and coordination path),
 * and a stamp, when one is readable, must carry the reservation's token; the
 * inode and birth time of a recreated directory are not compared. Callers
 * hold the native lock.
 */
export function assertPhysicalRootReservation(path: string, identity: { worktreeId: string; coordinationPath?: string | null }): void {
  try {
    const reservation = readPhysicalRootReservation(path);
    if (!reservation || reservation.worktreeId !== identity.worktreeId || identity.coordinationPath && reservation.coordinationPath !== identity.coordinationPath) throw physicalRootError();
    const stamp = existsSync(path) ? readPhysicalRootStamp(path) : null;
    if (stamp && (stamp.token !== reservation.token || stamp.worktreeId !== reservation.worktreeId || stamp.brainId !== reservation.brainId)) throw physicalRootError();
  } catch (error) { if (error instanceof OperationError) throw error; throw physicalRootError(); }
}
/**
 * #5914 (P1.3c): the recorded root now resolves through a symlink to `target`.
 * Verifies the moved checkout is this same worktree (reservation under the old
 * name and stamp inside the real directory agree on token, brainId and
 * worktreeId; the stamp names the old root) and returns both records.
 */
export function inspectRelocatedPhysicalRoot(recorded: string, target: string, identity: { worktreeId: string; coordinationPath?: string | null }):
  { reservation: PhysicalRootReservation; stamp: PhysicalRootStamp } {
  try {
    if (recorded === target || realpathSync(recorded) !== target || realpathSync(target) !== target) throw physicalRootError();
    const reservation = readRecordedPhysicalRootReservation(recorded), stamp = readPhysicalRootStamp(target);
    if (!reservation || !stamp || reservation.worktreeId !== identity.worktreeId || identity.coordinationPath && reservation.coordinationPath !== identity.coordinationPath
      || stamp.token !== reservation.token || stamp.worktreeId !== reservation.worktreeId || stamp.brainId !== reservation.brainId || stamp.root !== recorded) throw physicalRootError();
    return { reservation, stamp };
  } catch (error) { if (error instanceof OperationError) throw error; throw physicalRootError(); }
}
/**
 * #5914 (P1.3c): moves the ownership records of a verified relocation to the
 * real directory: the reservation is written under the new `sha256(root)`
 * name, the stamp is rewritten to name the new root from the live directory,
 * then the old reservation is removed. Caller holds the native lock and the
 * topology transaction; `inspectRelocatedPhysicalRoot` ran first.
 */
export function relocatePhysicalRoot(recorded: string, target: string, records: { reservation: PhysicalRootReservation; stamp: PhysicalRootStamp }): PhysicalRootReservation {
  const info = statSync(target, { bigint: true });
  const reservation: PhysicalRootReservation = { ...records.reservation, root: target,
    initialDevice: info.dev.toString(), initialInode: info.ino.toString(), initialBirth: info.birthtimeNs.toString() };
  const existing = readPhysicalRootReservation(target);
  if (existing && digest(existing) !== digest(reservation)) throw physicalRootError('Another reservation already names the relocated directory.');
  if (!existing && !createPrivate(physicalRootReservationPath(target), reservation)) throw physicalRootError();
  replacePrivate(join(target, PHYSICAL_ROOT_MARKER), { ...records.stamp, root: target, device: info.dev.toString(), inode: info.ino.toString(), birth: info.birthtimeNs.toString() });
  assertPhysicalRootStamp(target, reservation);
  try { unlinkSync(physicalRootReservationPath(recorded)); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
  flushDirectory(dirname(physicalRootReservationPath(recorded)));
  excludeOwnershipMarkers([target, dirname(target)]);
  return reservation;
}
export function assertPhysicalRoot(path: string, identity: { worktreeId: string; coordinationPath?: string | null }): void {
  try {
    const root = realpathSync(path);
    if (root !== path || lstatSync(path).isSymbolicLink()) throw physicalRootError();
    const reservation = readPhysicalRootReservation(root);
    if (!reservation || reservation.worktreeId !== identity.worktreeId || identity.coordinationPath && reservation.coordinationPath !== identity.coordinationPath) throw physicalRootError();
    assertPhysicalRootStamp(root, reservation);
    excludeMarkersInLaterCheckout(root);
  } catch (error) { if (error instanceof OperationError) throw error; throw physicalRootError(); }
}
/**
 * #8713: a root stamped before it was a Git checkout (`git init` on a repo-less brain) got no exclude, so an add-all
 * writer commits its stamp. A verified root inside a checkout whose exclude file lacks a marker glob gets them written.
 * A root in no checkout costs a few stats and an existing exclude one read; git runs only when one is missing (or the
 * checkout is a linked worktree, whose exclude git resolves).
 */
function excludeMarkersInLaterCheckout(root: string): void {
  let top = root;
  while (!existsSync(join(top, '.git'))) { if (dirname(top) === top) return; top = dirname(top); }
  try {
    const present = new Set(readFileSync(join(top, '.git', 'info', 'exclude'), 'utf8').split('\n').map(line => line.trim()));
    if (OWNERSHIP_MARKER_GLOBS.every(glob => present.has(glob))) return;
  } catch { /* no exclude file yet, or .git is a linked worktree's pointer file */ }
  excludeOwnershipMarkers([root, dirname(root)]);
}