Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/Aquaticat/Monochromatic. TypeScript and Rust monorepo: Claude Code and Pi coding-agent plugins, a m
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249/** The per-worktree landing lock and the recovery every acquisition runs first.
@module */import { join, } from 'node:path';import { tagged, } from '@monochromatic-dev/module-logger/ts';import { hasValidLandingLease, LANDING_LEASE_ENV,} from '../index-lock/landing-lease.ts';import { acquireOwnerLock, type OwnerLock,} from '../owner-lock/owner-lock.ts';import { type InspectedEntry, inspectRegistryEntry,} from './commit-transaction-recovery-inspect.ts';import { enteredLanding, } from './commit-transaction-recovery-evidence.ts';import { recoverDeadTransaction, } from './commit-transaction-recovery-landing.ts';import type { CommitTransactionRecoveryOutcome, } from './commit-transaction-recovery-types.ts';import { listTransactionEntries, } from './commit-transaction-registry.ts';
/** Module logger. */const l = tagged({ tag: 'cli-git', },);
/** Landing lock directory name inside the transaction registry. */export const LANDING_LOCK_NAME = 'landing.lock';
/** Builds an entry's recovery-order key: creation time when attributed, otherwise a key after every ISO time.
@param inspected - inspected entry
@returns sortable key */function creationKey(inspected: InspectedEntry,): string { /** Entry owner evidence. */ const { owner, entry, } = inspected; return (typeof owner) === 'string' ? `~${entry.path}` : `${owner.record .createdAt} ${entry.path}`;}
/** Orders inspected entries by owner creation time, oldest first.
@param entries - inspected entries
@returns ordered entries
@example ```ts oldestFirst(await Promise.all(entries.map(inspectRegistryEntry))); ``` */export function oldestFirst(entries: readonly InspectedEntry[],): readonly InspectedEntry[] { return entries.toSorted(function byCreation( left, right, ): number { /** Left key. */ const leftKey = creationKey(left,); /** Right key. */ const rightKey = creationKey(right,); if (leftKey === rightKey) return 0; return leftKey < rightKey ? -1 : 1; },);}
/** Recovers every dead-owner transaction that entered the landing critical section, holding a landing record or the record of a real `index.lock` it created; the caller holds the landing lock. An owner killed while holding the landing lock and `index.lock` has no landing record yet, and its `index.lock` would otherwise block this landing as an unproven foreign lock.
@param root - transaction registry
@param gitPath - real Git executable
@param effectiveCwd - owning worktree directory
@returns one outcome per recovered transaction
@example ```ts await recoverDeadLandings({ root, gitPath: '/usr/bin/git', effectiveCwd: '/repo' }); ``` */export async function recoverDeadLandings({ root, gitPath, effectiveCwd,}: Readonly<{ root: string; gitPath: string; effectiveCwd: string;}>,): Promise<readonly CommitTransactionRecoveryOutcome[]> { /** Tagged landing recovery logger. */ const rl = tagged({ tag: recoverDeadLandings.name, l, },); /** Published transactions with owner evidence. */ const inspected = await Promise.all((await listTransactionEntries(root,)) .filter(function isPublished(entry,): boolean { return entry.kind === 'transaction'; },) .map(function inspectEntry(entry,): Promise<InspectedEntry> { return inspectRegistryEntry(entry,); },),); /** Outcomes in recovery order. */ const outcomes: CommitTransactionRecoveryOutcome[] = []; for (const item of oldestFirst(inspected,)) { /** Entry owner evidence. */ const { owner, entry, } = item; if (((typeof owner) === 'string') || (owner.liveness === 'alive')) continue; // oxlint-disable-next-line no-await-in-loop -- Each recovery mutates the ref or index the next one validates. if (!(await enteredLanding(entry.path,))) continue; rl.debug(`recovering dead landing ${entry.path}`,); outcomes.push({ directory: entry.path, // oxlint-disable-next-line no-await-in-loop -- Each recovery mutates the ref or index the next one validates. action: await recoverDeadTransaction({ directory: entry.path, transactionId: entry.transactionId, ownerPid: owner.record .ownerPid, gitPath, effectiveCwd, },), },); } return outcomes;}
/** Lock view for an invocation nested under a landing-lock holder, which releases nothing.
@param lockDirectory - landing lock directory the ancestor holds
@returns held-by-ancestor lock */function inheritedLandingLock(lockDirectory: string,): OwnerLock { return { lockDirectory, token: process.env[LANDING_LEASE_ENV] ?? '', [Symbol.asyncDispose]: function keepAncestorLock(): Promise<void> { l.debug(`leaving ${lockDirectory} to the ancestor that holds it`,); return Promise.resolve(); }, };}
/** Acquires the landing lock and first recovers dead transactions that entered the landing critical section, so a crashed landing is resolved before another landing moves the ref or index. An invocation nested under the holder, proven by an inherited landing lease, proceeds under its ancestor's lock instead of waiting for it.
@param gitPath - real Git executable
@param cwd - owning worktree directory
@param registryRoot - transaction registry
@returns held landing lock
@example ```ts await using lock = await acquireLandingLock({ gitPath: '/usr/bin/git', cwd: '/repo', registryRoot }); ``` */export async function acquireLandingLock({ gitPath, cwd, registryRoot,}: Readonly<{ gitPath: string; cwd: string; registryRoot: string;}>,): Promise<OwnerLock> { /** Landing lock directory. */ const lockDirectory = join( registryRoot, LANDING_LOCK_NAME, ); /** Held landing lock, or the ancestor's. */ const lock = await hasValidLandingLease({ environment: process.env, lockDirectory, },) ? inheritedLandingLock(lockDirectory,) : await acquireOwnerLock({ lockDirectory, },); /** Whether ownership passed to the caller. */ const handedOver = new Set<'handed-over'>(); /** Releases the lock when recovery fails before the caller receives it. */ await using _releaseOnFailure = { [Symbol.asyncDispose]: async function releaseUnreturnedLock(): Promise<void> { if (handedOver.size === 0) await lock[Symbol.asyncDispose](); }, }; await recoverDeadLandings({ root: registryRoot, gitPath, effectiveCwd: cwd, },); handedOver.add('handed-over',); return lock;}