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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468import { SubprocessError, } from 'nano-spawn';import { caughtValueText, } from '@monochromatic-dev/module-caught-value/ts';import { tagged, } from '@monochromatic-dev/module-logger/ts';
import { autoPush, } from './auto-push.ts';import { forwardToRealGit, } from './forward-real-git.ts';import { installGitChildEnvironment, } from './git-child-environment.ts';import { IndexLockUnprovenOwnerError, } from './index-lock/index-lock-wait.ts';import { resolveGitWorktreeIdentity, } from './git-worktree-identity.ts';import { parseGlobalOptions, } from './parse-global-options.ts';import { parseManagementArgs, } from './management-parser.ts';import { runManagementCommand, } from './management.ts';import { parseCommitRegion, } from './parser/commit.ts';import { printPostCommandOutput, } from './post-command-output.ts';import { COMMIT_TRANSACTION_NOT_APPLICABLE, } from './policy-engine/commit-transaction.ts';import { runCommitTransactionBoundary, } from './policy-engine/commit-transaction-boundary.ts';import { NativeCommitFailedError, } from './policy-engine/commit-preparation-native.ts';import { hasValidInheritedLease, } from './hook-dispatch/preparation-lease.ts';import { CommitTransactionRecoveryError, recoverCommitTransaction,} from './policy-engine/commit-transaction-recovery.ts';import { runPreForwardPolicyEngine, } from './policy-engine/pre-forward-engine.ts';import { runPostCommitLifecycle, } from './policy-engine/post-commit-lifecycle.ts';import { MANUAL_PUSH_NOT_APPLICABLE, runManualPushGate,} from './policy-engine/manual-push-gate.ts';import { createEngineFailureEvent, renderPolicyEvents,} from './policy-engine/events.ts';import { resolveRealGit as resolveGit, } from '@monochromatic-dev/git-executable/ts';import { TrustedConfigError, } from './trust/config-loader.ts';import { classifyConfigLoading, } from './trust/command-classification.ts';import { resolveRuntimeConfig, RUNTIME_CONFIG_ABSENT,} from './trust/runtime-config.ts';import { ForwardedGitWorktreeCopyError, WorktreeCopyError,} from './worktree-copy/errors.ts';import { DEFAULT_CONCURRENCY_CONFIG, } from './trust/config-validation-concurrency.ts';
/** Logger root for cli-git after removing the package log shim. @example ```ts const rl = tagged({ tag: someFunction.name, l, },); ``` */const l = tagged({ tag: 'cli-git', },);
//region Rule pipeline: validate and transform args before forwarding to real git
/** Tagged logger for the main entry point. */const rl = tagged({ tag: 'main', l,},);
//endregion Rule pipeline
//region Execution: resolve real git, apply rules, spawn
/** Wrapper runtime-config resolution result. */type WrapperRuntimeResolution = | Readonly<{ loaded: Awaited<ReturnType<typeof resolveRuntimeConfig>>; }> | Readonly<{ error: unknown; }>;
/** Expected non-zero policy decision after buffered events were emitted. */class PolicyDecisionError extends Error { /** Settled cli-git exit code. */ public readonly exitCode: 1 | 2;
/** Creates control-flow error that cannot be confused with engine exceptions. @param exitCode - settled policy decision */ public constructor(exitCode: 1 | 2,) { super('policy decision blocked real Git',); this.name = 'PolicyDecisionError'; this.exitCode = exitCode; }}
/** Runs one direct cli-git invocation. Package root calls this function only when its single MJS artifact is Node's direct program entry. @example ```ts await runCliGit(); ``` */export async function runCliGit(): Promise<void> { installGitChildEnvironment(process.env,); /** Raw arguments passed after the script name. */ const rawArgs: readonly string[] = process.argv .slice(2,);
/** Resolves trusted config from process-owned wrapper arguments while retaining failures. @returns loaded config or captured failure. @example ```ts await resolveCurrentWrapperRuntime(); ``` */ async function resolveCurrentWrapperRuntime(): Promise<WrapperRuntimeResolution> { try { return { loaded: await resolveRuntimeConfig({ args: rawArgs, },), }; } catch (error: unknown) { return { error, }; } }
/** Layout used to intercept namespaced management command before Git forwarding. */ const managementLayout = parseGlobalOptions(rawArgs,); /** Whether parsed real-Git option token bypasses named subcommand execution. */ const { willShortCircuit, } = managementLayout; /** Whether wrapper owns this invocation as a management command. */ const isManagementCommand = (!willShortCircuit) && (rawArgs[managementLayout.subcommandIndex] === 'cli-git');
try { if (isManagementCommand) { /** Arguments owned by cli-git management after namespace dispatch. */ const managementArgs = rawArgs.slice(managementLayout.subcommandIndex + 1,); /** Early parse used only to keep successful help free of repository access. */ const managementAction = parseManagementArgs(managementArgs,); /** Whether invocation is successful help and must skip recovery mutation. */ const isManagementHelp = ((typeof managementAction) !== 'symbol') && (managementAction.command === 'help'); if (!isManagementHelp) { /** Real Git required for startup transaction recovery. */ const gitPath = await resolveGit(); await recoverCommitTransaction({ args: rawArgs, gitPath, },); } process.exitCode = await runManagementCommand({ args: managementArgs, gitGlobalArgs: rawArgs.slice( 0, managementLayout.subcommandIndex, ), },); } else { /** Absolute real Git path needed before repository config executes. */ const gitPath = await resolveGit(); /** Repository identity reused only when classification proves config cannot mutate process selection. */ const configFreeIdentity = (!willShortCircuit) && (classifyConfigLoading(rawArgs,) === 'skip-config') ? await resolveGitWorktreeIdentity({ args: rawArgs, gitPath, },) : undefined; // A hook of a live outer transaction inherits its lease; recovery would only find that live owner. if ((!willShortCircuit) && (!(await hasValidInheritedLease(process.env,)))) await recoverCommitTransaction({ args: rawArgs, gitPath, ...(configFreeIdentity === undefined ? {} : { identity: configFreeIdentity, }), },); /** Trusted runtime config resolution after transaction recovery. */ const runtimeResolution: WrapperRuntimeResolution = willShortCircuit ? { loaded: RUNTIME_CONFIG_ABSENT, } : await resolveCurrentWrapperRuntime(); if ('error' in runtimeResolution) { /** Stable trust failure code. */ const code = runtimeResolution.error instanceof TrustedConfigError ? runtimeResolution.error .code : 'trust-failed'; process.stderr .write(renderPolicyEvents([createEngineFailureEvent({ sequence: 0, code, message: caughtValueText(runtimeResolution.error,), },),],),); throw new PolicyDecisionError(2,); }
rl.debug(`using real git at ${gitPath}`,); /** Trusted policy options retained identically across convergence passes. */ const policyOptions = runtimeResolution.loaded === RUNTIME_CONFIG_ABSENT ? {} : { config: { policies: runtimeResolution.loaded .validated .policySeverities, }, registeredPolicies: runtimeResolution.loaded .validated .registeredPolicies, policyOptions: runtimeResolution.loaded .validated .policyOptions, }; /** Supported commit transaction, including final stable policy pass. */ const commitTransaction = willShortCircuit ? COMMIT_TRANSACTION_NOT_APPLICABLE : await runCommitTransactionBoundary({ args: rawArgs, gitPath, policyOptions, ...(runtimeResolution.loaded === RUNTIME_CONFIG_ABSENT ? {} : { concurrency: runtimeResolution.loaded .validated .concurrency, }), },); /** Stable policy result before real Git forwarding. */ const policyResult = willShortCircuit ? undefined : ((typeof commitTransaction) !== 'symbol' ? commitTransaction.policyResult : await runPreForwardPolicyEngine({ options: { args: rawArgs, trigger: 'pre-forward', ...policyOptions, }, gitPath, },)); if (policyResult !== undefined) { /** Stable wrapper JSONL emitted only after pass settles. */ const renderedEvents = renderPolicyEvents(policyResult.events,); if (renderedEvents !== '') process.stderr .write(renderedEvents,); if (!policyResult.shouldForward) { if (policyResult.exitCode === 0) throw new TypeError('Non-forwarding policy result cannot use exit code 0.',); throw new PolicyDecisionError(policyResult.exitCode,); } }
/** Final arguments after staged policy execution and fixed transforms. */ const processedArgs = policyResult?.args ?? rawArgs;
if (willShortCircuit) rl.debug('pre-subcommand short-circuit flag present, skipping policy pipeline',);
rl.debug(`final args: [${processedArgs.join(', ',)}]`,);
/** Layout of `processedArgs`: where the subcommand sits, what precedes it, and the directory git will operate in after `-C` chaining. */ const { subcommandIndex, effectiveCwd, } = parseGlobalOptions(processedArgs,); /** Subcommand at the located index; `undefined` when args carry no subcommand (e.g. `git --version`). */ const subcommand = processedArgs[subcommandIndex]; /** Post-subcommand region used by commit lifecycle classification. */ const postSubcommand = processedArgs.slice(subcommandIndex + 1,); if (runtimeResolution.loaded !== RUNTIME_CONFIG_ABSENT) { /** Settled manual-push gate or not-applicable sentinel. */ const manualPushResult = await runManualPushGate({ rawArgs, transformedArgs: processedArgs, gitPath, policySeverities: runtimeResolution.loaded .validated .policySeverities, registeredPolicies: runtimeResolution.loaded .validated .registeredPolicies, policyOptions: runtimeResolution.loaded .validated .policyOptions, },); if (manualPushResult !== MANUAL_PUSH_NOT_APPLICABLE) { /** Manual-push events use wrapper stderr routing. */ const renderedManualPushEvents = renderPolicyEvents(manualPushResult.events,); if (renderedManualPushEvents !== '') process.stderr .write(renderedManualPushEvents,); if (!manualPushResult.shouldForward) { if (manualPushResult.exitCode === 0) throw new TypeError('Non-forwarding manual-push result cannot use exit code 0.',); throw new PolicyDecisionError(manualPushResult.exitCode,); } } } /** Commit the transaction landed, read later instead of live `HEAD`. */ const landedOid = (typeof commitTransaction) === 'symbol' ? undefined : commitTransaction.landedOid; /** Whether private-index transaction already executed real Git. */ const transactionCommitted = landedOid !== undefined; if (((typeof commitTransaction) !== 'symbol') && (!transactionCommitted)) throw new TypeError('A commit transaction that landed nothing must block forwarding.',); if (!transactionCommitted) { await forwardToRealGit({ args: processedArgs, gitPath, unprovenOwnerTimeoutMs: (runtimeResolution.loaded === RUNTIME_CONFIG_ABSENT ? DEFAULT_CONCURRENCY_CONFIG : runtimeResolution.loaded .validated .concurrency).indexLock .unprovenOwnerTimeoutMs, ...(configFreeIdentity === undefined ? {} : { identity: configFreeIdentity, }), },); }
/** True when a real commit just landed (the spawn above succeeded and this was not a dry-run preview), so the new commit should be backed up. Dry-run detection uses the parsed commit region, which covers `--dry-run` plus the output-format flags git documents as implying it (`--short`, `--porcelain`, `--long`, `-z`/`--null`) in any accepted abbreviation. A failed commit throws out of the spawn above and never reaches here. */ const committed = transactionCommitted || ((subcommand === 'commit') && (!parseCommitRegion(postSubcommand,) .isDryRun));
if (committed) { /** Post-commit policy gate against landed commit ground truth. */ const postCommitResult = await runPostCommitLifecycle({ rawArgs, transformedArgs: processedArgs, gitPath, cwd: effectiveCwd, ...(landedOid === undefined ? {} : { landedOid, }), ...(runtimeResolution.loaded === RUNTIME_CONFIG_ABSENT ? {} : { policySeverities: runtimeResolution.loaded .validated .policySeverities, registeredPolicies: runtimeResolution.loaded .validated .registeredPolicies, policyOptions: runtimeResolution.loaded .validated .policyOptions, }), },); /** Settled post-commit JSONL including explicit landed state when blocked. */ const renderedPostCommitEvents = renderPolicyEvents(postCommitResult.events,); if (renderedPostCommitEvents !== '') process.stderr .write(renderedPostCommitEvents,); if (postCommitResult.blocked) throw new PolicyDecisionError(2,); await autoPush({ gitPath, cwd: effectiveCwd, landedOid: postCommitResult.oid, },); }
printPostCommandOutput({ rawArgs, processedArgs, },); }}catch (error) { if ((error instanceof CommitTransactionRecoveryError) || (error instanceof IndexLockUnprovenOwnerError)) { process.stderr .write(renderPolicyEvents([createEngineFailureEvent({ sequence: 0, code: error instanceof IndexLockUnprovenOwnerError ? 'index-lock-unproven-owner' : 'content-unavailable', message: error.message, },),],),); process.exitCode = 2; } else if ((error instanceof PolicyDecisionError) || (error instanceof NativeCommitFailedError)) process.exitCode = error.exitCode; else if (error instanceof ForwardedGitWorktreeCopyError) { console.error(error.copyFailureMessage,); process.exitCode = error.gitFailed ? error.gitFailureExitCode ?? 1 : 2; } else if (error instanceof WorktreeCopyError) { console.error(error.message,); process.exitCode = 2; } else if (error instanceof SubprocessError) process.exitCode = error.exitCode ?? 1; else if (Error.isError(error,)) { console.error(error.message,); process.exitCode = 1; } else { throw error; }}}
//endregion Execution