akm-cli
Version:
akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur
768 lines (767 loc) • 37 kB
JavaScript
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
import { randomBytes } from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { resolveStashDir } from "../../core/common.js";
import { getSources, loadConfig, resolveConfiguredSources, resolveSecret } from "../../core/config/config.js";
import { NotFoundError, UsageError } from "../../core/errors.js";
import { sanitizeCommitMessage } from "../../core/git-message.js";
import { isGitBackedStash, tryListGitChangedPaths } from "../../core/git-path-safety.js";
import { runGit } from "../../core/git-run.js";
import { lockContentRootFor } from "../../integrations/lockfile.js";
import { gitCredentialEnvironment } from "../../registry/resolve.js";
import { storeSecretResolver } from "../snapshot-fetchers/secret-seam.js";
import { getCachePaths, parseGitRepoUrl } from "./git-provider.js";
export class GitStashPushError extends Error {
commit;
/** False when the push was of commits made earlier (nothing was committed by this call). */
committedNow;
constructor(message, commit, committedNow = true) {
super(message);
this.name = "GitStashPushError";
this.commit = commit;
this.committedNow = committedNow;
}
}
const GIT_PUSH_TIMEOUT_MS = 120_000;
const ZERO_OID = "0000000000000000000000000000000000000000";
let exactCommitHookForTests;
/**
* TEST-ONLY. Interleave work into the exact-path commit sequence; `undefined`
* restores. Exists because the CAS window is a few microseconds wide between
* two synchronous `git` invocations — a wall-clock race would be
* non-deterministic, and every earlier pre-check would swallow a commit that
* landed before the window opened. Inert in production.
*/
export function _setGitExactCommitHookForTests(hook) {
exactCommitHookForTests = hook;
}
/** Fire a named exact-path-commit race point (no-op outside tests). */
function gitExactCommitHook(point) {
exactCommitHookForTests?.(point);
}
/**
* Resolve the writable flag for an end-of-run / `akm sync` commit from the
* configured default bundle.
*/
export function resolveWritableOverride(config) {
const source = resolveConfiguredSources(config).find((entry) => entry.name === config.defaultBundle);
if (!source)
return undefined;
return (source.writable ?? source.type === "filesystem") ? true : undefined;
}
/**
* Commit (and optionally push) local changes in a git-backed stash.
*
* Behaviour:
* - Not a git repo → skipped (no-op)
* - Git repo, no remote → commit only
* - Git repo, has remote, but stash is not writable → commit only
* - Git repo, has remote, stash is writable → commit + push, unless the
* branch has no upstream or is behind or diverged from it: then commit
* only, and `reason` says why
*
* When `name` is omitted the primary stash directory is used.
* When `message` is omitted a timestamp is used.
*
* `options.repoDir` overrides the primary-stash directory the commit targets
* (only honoured when `name` is omitted). Callers that already resolved the
* primary stash dir (e.g. `akm improve`'s end-of-run sync, whose pre-commit
* gate validates that exact directory) pass it here so the gate and the commit
* operate on the SAME directory instead of independently calling
* `resolveStashDir()`. When absent, behaviour is unchanged.
*/
export function saveGitStash(name, message, writableOverride, options) {
// `push: false` (from `akm sync --no-push`) commits but never pushes, even
// when the stash is writable with a remote configured.
const allowPush = options?.push !== false;
const timestamp = new Date().toISOString().replace("T", " ").slice(0, 19);
// Sanitize the user-supplied message: strip CR/LF/NUL, collapse whitespace,
// clamp length. An attacker can otherwise pass `--message "subject\n\n\
// Co-Authored-By: someone-else"` and forge trailers in the commit log.
// Empty result falls back to the timestamped default.
const sanitized = message ? sanitizeCommitMessage(message) : "";
const bodyLines = (options?.body ?? []).map(sanitizeCommitMessage).filter(Boolean);
const commitMessage = [
sanitized || `akm save ${timestamp}`,
...(bodyLines.length > 0 ? ["", ...bodyLines] : []),
].join("\n");
const transactionId = options?.transactionId;
if (transactionId !== undefined && !/^[A-Za-z0-9._-]{1,128}$/.test(transactionId)) {
throw new Error("Invalid Git transaction identifier.");
}
let repoDir;
let writable = false;
let managedContentRoot;
let namedCredential;
if (name) {
const config = loadConfig();
const stash = findSyncStashByTarget(getSources(config), name);
// NotFoundError (exit 1), not UsageError (exit 2): the argument is
// well-formed, the bundle just isn't configured.
if (!stash)
throw new NotFoundError(`No git-backed bundle found with name "${name}"`, "SOURCE_NOT_FOUND");
namedCredential = stash.credential;
if (stash.enabled === false) {
throw new UsageError(`Bundle "${name}" is disabled and cannot be synced.`, "INVALID_FLAG_VALUE");
}
if (stash.type === "filesystem") {
if (!stash.path)
throw new UsageError(`Filesystem bundle "${name}" has no path configured.`);
const contentRoot = path.resolve(stash.path);
const topLevel = runGit(["-C", contentRoot, "rev-parse", "--show-toplevel"]);
if (topLevel.status !== 0 || !topLevel.stdout.trim()) {
throw new UsageError(`Filesystem bundle "${name}" is not a Git working tree at ${contentRoot}.`);
}
repoDir = path.resolve(topLevel.stdout.trim());
managedContentRoot = contentRoot;
writable = stash.writable !== false;
}
else {
const lockedRoot = lockContentRootFor(stash.name, stash.type);
if (lockedRoot) {
const topLevel = runGit(["-C", lockedRoot, "rev-parse", "--show-toplevel"]);
if (topLevel.status !== 0 || !topLevel.stdout.trim()) {
throw new UsageError(`Managed Git stash "${name}" is not a checkout at ${lockedRoot}`);
}
repoDir = path.resolve(topLevel.stdout.trim());
managedContentRoot = path.resolve(lockedRoot);
}
else {
if (!stash.url)
throw new UsageError(`Stash "${name}" has no URL configured`);
const repo = parseGitRepoUrl(stash.url);
repoDir = getCachePaths(repo.canonicalUrl).repoDir;
}
writable = stash.writable === true;
}
}
else {
// Honour an explicit primary-stash dir override (keeps the improve gate and
// the commit on the same directory); otherwise resolve the default.
repoDir = options?.repoDir ?? resolveStashDir();
// Allow the caller to pass the configured default bundle's writability.
if (writableOverride !== undefined) {
writable = writableOverride;
}
}
// No-op: not a git repo
if (!isGitBackedStash(repoDir)) {
return { committed: false, pushed: false, skipped: true, reason: "not a git repository", output: "" };
}
const statusResult = runGit(["-C", repoDir, "status", "--porcelain"]);
if (statusResult.error || statusResult.status !== 0) {
throw new Error(`git status failed: ${statusResult.error?.message || statusResult.stderr?.trim() || "unknown error"}`);
}
const hasRemote = readHasRemote(repoDir);
// `--no-push`, a read-only bundle and a bundle without a remote never touch the network.
let syncWithRemote = hasRemote && writable && allowPush;
// The bundle's configured credential reaches fetch and push through the child environment only. One
// that cannot be resolved only skips the network step: the local commit still happens.
let remoteEnv;
let credentialFailure;
if (syncWithRemote) {
const credentialRef = name ? namedCredential : credentialForRepo(repoDir);
if (credentialRef) {
try {
remoteEnv = gitCredentialEnvironment(resolveSecret(credentialRef, storeSecretResolver.resolveSecret));
}
catch (error) {
credentialFailure = `not pushed: ${error instanceof Error ? error.message : "credential could not be resolved"}`;
syncWithRemote = false;
}
}
}
const report = (result) => credentialFailure && !result.reason ? { ...result, reason: credentialFailure } : result;
if (!statusResult.stdout.trim() && options?.paths === undefined) {
return report(nothingToCommit(repoDir, "nothing to commit, working tree clean", syncWithRemote, remoteEnv));
}
// Selection (#476, #1502): an explicit sync commits every unignored change inside the bundle, so a
// file outside the asset directories is never left behind. What it never does is reach beyond the
// bundle or sweep in work staged elsewhere: the commit is built from exact paths only.
//
// Precedence:
// 1. Explicit modified-file list (`options.paths`) — stage exactly those.
// 2. A lock-backed or filesystem content root below the repo — its changed paths only.
// 3. Otherwise (the bundle is the repo root) — every changed path.
// Ignored paths and nested repositories are dropped from 2 and 3.
const managedRelativeRoot = managedContentRoot
? path.relative(repoDir, managedContentRoot).replaceAll(path.sep, "/")
: "";
const requestedPaths = normalizeExactPaths(repoDir, options?.paths ?? pathsSyncWouldCommit(repoDir, managedRelativeRoot).paths);
if (requestedPaths.length === 0) {
return report(nothingToCommit(repoDir, "nothing to commit", syncWithRemote, remoteEnv));
}
assertNoIgnoredExactPaths(repoDir, requestedPaths);
const baseHead = readOptionalHead(repoDir);
const exactCommit = createExactPathCommit(repoDir, {
baseHead,
commitMessage,
paths: requestedPaths,
transactionId,
expectedSnapshots: options?.expectedSnapshots,
});
if (!exactCommit) {
return report(nothingToCommit(repoDir, "nothing to commit", syncWithRemote, remoteEnv));
}
// Bring in whatever another host pushed, then push. A branch that cannot be pushed still keeps its
// commit: only the push is skipped, and the result says why.
const integration = syncWithRemote ? integrateUpstream(repoDir, remoteEnv) : undefined;
const upstream = integration && "blocked" in integration
? integration.blocked
: syncWithRemote
? readActualUpstream(repoDir, readOptionalHead(repoDir))
: undefined;
const pushTarget = typeof upstream === "object" ? upstream : undefined;
if (!pushTarget) {
return report({
committed: true,
pushed: false,
skipped: false,
...(typeof upstream === "string" ? { reason: `not pushed: ${upstream}` } : {}),
output: `commit ${exactCommit}`,
commit: exactCommit,
});
}
const pushOutput = pushToUpstream(repoDir, pushTarget, readOptionalHead(repoDir) ?? exactCommit, exactCommit, true, remoteEnv);
return {
committed: true,
pushed: true,
skipped: false,
output: pushOutput || "changes committed and pushed",
commit: exactCommit,
};
}
function readHasRemote(repoDir) {
const remoteResult = runGit(["-C", repoDir, "remote"]);
if (remoteResult.status !== 0) {
throw new Error(`git remote failed: ${remoteResult.stderr?.trim() || "unknown error"}`);
}
return remoteResult.stdout.trim().length > 0;
}
/**
* Push `head` to the upstream, leased on the upstream head just read. Throws {@link GitStashPushError}
* (carrying `commit`) when git refuses. Returns git's stdout.
*/
function pushToUpstream(repoDir, target, head, commit, committedNow = true, env) {
const pushResult = runGit([
"-C",
repoDir,
"push",
`--force-with-lease=${target.mergeRef}:${target.upstreamHead}`,
target.remote,
`${head}:${target.mergeRef}`,
], { timeout: GIT_PUSH_TIMEOUT_MS, ...(env ? { env } : {}) });
if (pushResult.status !== 0) {
throw new GitStashPushError(`git push failed: ${pushResult.stderr?.trim() || "unknown error"}`, commit, committedNow);
}
return pushResult.stdout.trim();
}
/**
* Nothing to commit still brings in the upstream, so a host with no changes of its own keeps up. Commits
* made earlier and never pushed (a proposal accept, a killed improve run) are pushed here, once the
* branch is up to date with its upstream and ahead of it.
*/
function nothingToCommit(repoDir, output, syncWithRemote, env) {
const integration = syncWithRemote ? integrateUpstream(repoDir, env) : undefined;
if (integration && "blocked" in integration) {
return { committed: false, pushed: false, skipped: false, reason: `not pushed: ${integration.blocked}`, output };
}
// readUpstreamConfig is undefined on a detached HEAD or a branch with no upstream: nothing to push.
const head = syncWithRemote && readUpstreamConfig(repoDir) ? readOptionalHead(repoDir) : undefined;
const upstream = head ? readActualUpstream(repoDir, head) : undefined;
if (head && typeof upstream === "object" && upstream.upstreamHead !== head) {
const pushOutput = pushToUpstream(repoDir, upstream, head, head, false, env);
return {
committed: false,
pushed: true,
skipped: false,
output: pushOutput || `pushed ${upstream.upstreamHead.slice(0, 7)}..${head.slice(0, 7)}`,
};
}
return { committed: false, pushed: false, skipped: false, output: integration?.integrated ?? output };
}
function readUpstreamConfig(repoDir) {
const branchRef = runGit(["-C", repoDir, "symbolic-ref", "--quiet", "HEAD"]);
if (branchRef.status !== 0 || !branchRef.stdout.trim())
return undefined;
const branch = branchRef.stdout.trim().replace(/^refs\/heads\//, "");
const remote = runGit(["-C", repoDir, "config", "--get", `branch.${branch}.remote`]);
const merge = runGit(["-C", repoDir, "config", "--get", `branch.${branch}.merge`]);
if (remote.status !== 0 || merge.status !== 0)
return undefined;
return { remote: remote.stdout.trim(), mergeRef: merge.stdout.trim() };
}
function isAncestor(repoDir, ancestor, descendant) {
return runGit(["-C", repoDir, "merge-base", "--is-ancestor", ancestor, descendant]).status === 0;
}
/**
* Fetch the branch's remote and bring its upstream into HEAD: nothing to do when HEAD already has it,
* a fast-forward when HEAD is behind, otherwise git's default merge. A merge that conflicts is aborted
* so the working tree and the local commits stay exactly as they were. `blocked` says why the branch
* could not be brought up to date (and therefore must not be pushed); `integrated` describes what moved.
*/
function integrateUpstream(repoDir, env) {
const config = readUpstreamConfig(repoDir);
if (!config)
return {};
const fetch = runGit(["-C", repoDir, "fetch", config.remote], {
timeout: GIT_PUSH_TIMEOUT_MS,
...(env ? { env } : {}),
});
if (fetch.status !== 0) {
return { blocked: `could not fetch ${config.remote}: ${fetch.stderr?.trim() || "unknown error"}` };
}
const upstream = runGit(["-C", repoDir, "rev-parse", "--verify", "@{u}"]);
const head = readOptionalHead(repoDir);
if (upstream.status !== 0 || !head)
return {};
const upstreamHead = upstream.stdout.trim();
if (isAncestor(repoDir, upstreamHead, head))
return {};
const fastForward = isAncestor(repoDir, head, upstreamHead);
const merge = runGit([
"-C",
repoDir,
"-c",
"user.name=akm",
"-c",
"user.email=akm@local",
"merge",
...(fastForward ? ["--ff-only"] : ["--no-edit", "-m", `akm sync: merge ${config.remote} upstream`]),
upstreamHead,
]);
if (merge.status === 0)
return { integrated: fastForward ? "fast-forwarded to upstream" : "merged upstream" };
const conflicted = runGit(["-C", repoDir, "diff", "--name-only", "--diff-filter=U"])
.stdout.split("\n")
.filter(Boolean);
// Not every refusal leaves a merge in progress (e.g. local changes in the way); abort only if one is.
if (runGit(["-C", repoDir, "rev-parse", "--verify", "--quiet", "MERGE_HEAD"]).status === 0) {
runGit(["-C", repoDir, "merge", "--abort"]);
}
return {
blocked: conflicted.length > 0
? `merging upstream conflicts in ${conflicted.join(", ")}; the merge was aborted and the local commit kept`
: `could not merge upstream (${merge.stderr?.trim() || merge.stdout?.trim() || "unknown error"}); the local commit was kept`,
};
}
/** Git lists a nested repository as a bare directory; it is not a file sync can publish, so it is left out. */
/**
* The paths an explicit sync of the bundle at `managedRelativeRoot` of the repository would commit: every changed path inside
* the bundle that is not a directory (a nested repository) or ignored. `ok` is false when git could not list the changes, and
* the paths are then not to be trusted.
*/
export function pathsSyncWouldCommit(repoDir, managedRelativeRoot = "") {
const changed = tryListGitChangedPaths(repoDir);
const inside = managedRelativeRoot && managedRelativeRoot !== ".." && !managedRelativeRoot.startsWith("../")
? changed.paths.filter((changedPath) => changedPath === managedRelativeRoot || changedPath.startsWith(`${managedRelativeRoot}/`))
: changed.paths;
return { paths: withoutIgnoredPaths(repoDir, withoutDirectories(repoDir, inside)), ok: changed.ok };
}
function withoutDirectories(repoDir, paths) {
return paths.filter((candidate) => {
try {
return !fs.lstatSync(path.join(repoDir, candidate)).isDirectory();
}
catch {
return true; // deleted
}
});
}
/** The credential reference of the configured Git bundle whose working tree is `repoDir`. */
function credentialForRepo(repoDir) {
for (const stash of getSources(loadConfig())) {
if (!stash.credential || stash.enabled === false || stash.type === "filesystem")
continue;
const root = lockContentRootFor(stash.name, stash.type) ??
(stash.url ? getCachePaths(parseGitRepoUrl(stash.url).canonicalUrl).repoDir : undefined);
if (!root)
continue;
const topLevel = runGit(["-C", path.resolve(root), "rev-parse", "--show-toplevel"]);
if (topLevel.status === 0 && path.resolve(topLevel.stdout.trim()) === path.resolve(repoDir))
return stash.credential;
}
return undefined;
}
/**
* Drop paths a `.gitignore` rule matches from the paths sync picks for itself. Ignoring means "do
* not publish", also for a file committed before the rule existed (`.akm/evals/runs/latest` in a
* stash whose eval runs are ignored): git refuses to stage such a file, which would fail the whole
* sync. Only an explicit `paths` request still reaches {@link assertNoIgnoredExactPaths}.
*/
function withoutIgnoredPaths(repoDir, paths) {
const ignored = new Set(listIgnoredExactPaths(repoDir, paths, { includeTracked: true }));
return ignored.size === 0 ? paths : paths.filter((candidate) => !ignored.has(candidate));
}
function normalizeExactPaths(repoDir, paths) {
const normalized = [...new Set(paths.map((value) => value.replaceAll(path.sep, "/")))];
for (const filePath of normalized) {
const absolute = path.resolve(repoDir, filePath);
const relative = path.relative(repoDir, absolute).replaceAll(path.sep, "/");
if (!filePath ||
filePath.includes("\0") ||
path.isAbsolute(filePath) ||
relative !== filePath ||
relative === ".." ||
relative.startsWith("../")) {
throw new Error(`Unsafe exact Git path: ${filePath || "<empty>"}`);
}
}
return normalized;
}
function runExactPathChunks(repoDir, command, paths, options = {}) {
const CHUNK = 500;
const results = [];
for (let i = 0; i < paths.length; i += CHUNK) {
results.push(runGit(["--literal-pathspecs", "-C", repoDir, ...command, "--", ...paths.slice(i, i + CHUNK)], {
env: options.env,
}));
}
return results;
}
/**
* The subset of `paths` a `.gitignore` rule matches. By default a tracked file never counts (git's
* own `check-ignore` skips it); `includeTracked` asks about the rule alone, as `git add` does.
*/
export function listIgnoredExactPaths(repoDir, paths, options = {}) {
if (paths.length === 0)
return [];
const input = `${paths.join("\0")}\0`;
const result = runGit(["-C", repoDir, "check-ignore", "-z", "--stdin", ...(options.includeTracked ? ["--no-index"] : [])], {
input,
});
if (result.status === 1)
return [];
if (result.status !== 0) {
throw new Error(`git check-ignore failed: ${result.stderr.trim() || "unknown error"}`);
}
return result.stdout.split("\0").filter(Boolean);
}
export function assertNoIgnoredExactPaths(repoDir, paths) {
const ignored = listIgnoredExactPaths(repoDir, normalizeExactPaths(repoDir, paths));
if (ignored.length > 0) {
throw new UsageError(`Exact Git publication path is ignored: ${ignored[0]}. Update .gitignore or choose a tracked destination before writing.`);
}
}
function readOptionalHead(repoDir) {
const result = runGit(["-C", repoDir, "rev-parse", "--verify", "HEAD"]);
return result.status === 0 && result.stdout.trim() ? result.stdout.trim() : undefined;
}
function readBranchRef(repoDir) {
const result = runGit(["-C", repoDir, "symbolic-ref", "--quiet", "HEAD"]);
if (result.status !== 0 || !result.stdout.trim()) {
throw new UsageError(`Writable Git target at ${repoDir} is detached from a branch.`);
}
return result.stdout.trim();
}
/**
* Where a commit on top of `baseHead` can be pushed: the branch's upstream, as
* long as it is an ancestor of `baseHead` (ahead is fine, the push fast-forwards
* it). Otherwise why not: no upstream, or behind or diverged from it.
*/
function readActualUpstream(repoDir, baseHead) {
const branchRef = readBranchRef(repoDir);
const branch = branchRef.replace(/^refs\/heads\//, "");
const remote = runGit(["-C", repoDir, "config", "--get", `branch.${branch}.remote`]);
const merge = runGit(["-C", repoDir, "config", "--get", `branch.${branch}.merge`]);
const upstream = runGit(["-C", repoDir, "rev-parse", "--verify", "@{u}"]);
if (remote.status !== 0 || merge.status !== 0 || upstream.status !== 0)
return "no upstream branch is configured";
const upstreamHead = upstream.stdout.trim();
if (!baseHead || runGit(["-C", repoDir, "merge-base", "--is-ancestor", upstreamHead, baseHead]).status !== 0) {
return "the branch is behind its upstream or has diverged from it";
}
return { remote: remote.stdout.trim(), mergeRef: merge.stdout.trim(), upstreamHead };
}
function readIndexEntries(repoDir, paths) {
const entries = new Map(paths.map((filePath) => [filePath, []]));
for (const result of runExactPathChunks(repoDir, ["ls-files", "--stage", "-z"], paths)) {
if (result.status !== 0)
throw new Error(`Cannot inspect Git index: ${result.stderr.trim() || "unknown error"}`);
for (const record of result.stdout.split("\0")) {
if (!record)
continue;
const tab = record.indexOf("\t");
const match = record.slice(0, tab).match(/^(\d+) ([0-9a-f]+) (\d+)$/);
if (tab < 0 || !match)
throw new Error(`Cannot parse Git index entry.`);
const filePath = record.slice(tab + 1);
entries.get(filePath)?.push({ mode: match[1], oid: match[2], stage: Number(match[3]) });
}
}
return entries;
}
function readTreeStates(repoDir, treeish, paths) {
const states = new Map(paths.map((filePath) => [filePath, null]));
if (!treeish)
return states;
for (const result of runExactPathChunks(repoDir, ["ls-tree", "-z", treeish], paths)) {
if (result.status !== 0)
throw new Error(`Cannot inspect Git tree: ${result.stderr.trim() || "unknown error"}`);
for (const record of result.stdout.split("\0")) {
if (!record)
continue;
const tab = record.indexOf("\t");
const match = record.slice(0, tab).match(/^(\d+) blob ([0-9a-f]+)$/);
if (tab < 0 || !match)
throw new Error(`Exact Git path is not a blob.`);
const mode = match[1];
if (mode !== "100644" && mode !== "100755" && mode !== "120000") {
throw new Error(`Unsupported Git mode ${mode}.`);
}
states.set(record.slice(tab + 1), { mode, oid: match[2] });
}
}
return states;
}
function assertIndexMatchesBase(paths, indexEntries, baseStates) {
if (indexMatchesTree(paths, indexEntries, baseStates))
return;
const dirtyPath = paths.find((filePath) => {
const entries = indexEntries.get(filePath) ?? [];
const base = baseStates.get(filePath) ?? null;
return !(base === null
? entries.length === 0
: entries.length === 1 &&
entries[0]?.stage === 0 &&
entries[0]?.mode === base.mode &&
entries[0]?.oid === base.oid);
});
throw new UsageError(`Exact Git operation path has staged work: ${dirtyPath ?? paths[0]}. Commit, stash, or discard that path before retrying.`);
}
function indexMatchesTree(paths, indexEntries, treeStates) {
for (const filePath of paths) {
const entries = indexEntries.get(filePath) ?? [];
const state = treeStates.get(filePath) ?? null;
if (!(state === null
? entries.length === 0
: entries.length === 1 &&
entries[0]?.stage === 0 &&
entries[0]?.mode === state.mode &&
entries[0]?.oid === state.oid)) {
return false;
}
}
return true;
}
/** Repair only the stale base index left by a crash after an exact commit CAS. */
export function reconcileGitExactPathIndex(repoDir, baseCommit, commit, paths) {
const normalized = normalizeExactPaths(repoDir, paths);
const current = readIndexEntries(repoDir, normalized);
const committedStates = readTreeStates(repoDir, commit, normalized);
if (indexMatchesTree(normalized, current, committedStates))
return;
const baseStates = readTreeStates(repoDir, baseCommit, normalized);
if (!indexMatchesTree(normalized, current, baseStates)) {
throw new UsageError(`Exact Git operation path has staged work after transaction recovery. Commit, stash, or discard it before retrying.`);
}
for (const result of runExactPathChunks(repoDir, ["reset", "--quiet", commit], normalized)) {
if (result.status !== 0)
throw new Error(`git index cleanup failed during exact transaction recovery`);
}
}
/** Git's effective `core.filemode`: on unless the repository (or Git's probe at init) turned it off. */
function fileModeTracked(repoDir) {
const result = runGit(["-C", repoDir, "config", "--type=bool", "--get", "core.filemode"]);
return result.status !== 0 || result.stdout.trim() !== "false";
}
/**
* With `core.filemode` off the filesystem's executable bit means nothing to Git, so a regular file keeps
* the mode its baseline entry already has and a new one gets Git's `100644`. `modeBaseline` is that
* baseline (null: no entry); leaving it undefined means the bit is read from the filesystem.
*/
function captureWorktreeState(repoDir, filePath, modeBaseline) {
const absolutePath = path.join(repoDir, filePath);
let stat;
try {
stat = fs.lstatSync(absolutePath);
}
catch (error) {
if (error.code === "ENOENT")
return null;
throw error;
}
let mode;
let result;
if (stat.isSymbolicLink()) {
mode = "120000";
result = runGit(["-C", repoDir, "hash-object", "--stdin"], { input: fs.readlinkSync(absolutePath) });
}
else if (stat.isFile()) {
const baseMode = modeBaseline?.base?.mode;
mode = modeBaseline ? (baseMode === "100755" ? "100755" : "100644") : stat.mode & 0o111 ? "100755" : "100644";
result = runGit(["-C", repoDir, "hash-object", `--path=${filePath}`, "--", absolutePath]);
}
else {
throw new Error(`Exact Git publication path is not a file: ${filePath}`);
}
if (result.status !== 0 || !result.stdout.trim()) {
throw new Error(`Cannot hash exact Git publication path: ${filePath}`);
}
return { oid: result.stdout.trim(), mode };
}
function samePathState(left, right) {
return left === null ? right === null : right !== null && left.oid === right.oid && left.mode === right.mode;
}
function assertWorktreeMatchesExpected(paths, expected, captureState) {
for (const filePath of paths) {
if (!samePathState(captureState(filePath), expected.get(filePath) ?? null)) {
throw new Error(`Exact Git publication path changed while committing: ${filePath}`);
}
}
}
function sameIndexEntries(left, right) {
return JSON.stringify([...left]) === JSON.stringify([...right]);
}
function resetRealIndexPaths(repoDir, commit, paths, initial) {
const current = readIndexEntries(repoDir, paths);
if (!sameIndexEntries(initial, current))
return;
for (const result of runExactPathChunks(repoDir, ["reset", "--quiet", commit], paths)) {
if (result.status !== 0)
throw new Error(`git index cleanup failed after exact commit`);
}
}
function createExactPathCommit(repoDir, options) {
const branchRef = readBranchRef(repoDir);
const baseStates = readTreeStates(repoDir, options.baseHead, options.paths);
const initialIndex = readIndexEntries(repoDir, options.paths);
assertIndexMatchesBase(options.paths, initialIndex, baseStates);
const ignoreFileMode = !fileModeTracked(repoDir);
const captureState = (filePath) => captureWorktreeState(repoDir, filePath, ignoreFileMode ? { base: baseStates.get(filePath) ?? null } : undefined);
const expected = new Map();
for (const filePath of options.paths) {
expected.set(filePath, options.expectedSnapshots && Object.hasOwn(options.expectedSnapshots, filePath)
? (options.expectedSnapshots[filePath] ?? null)
: captureState(filePath));
}
const gitIndex = runGit(["-C", repoDir, "rev-parse", "--git-path", "index"]);
if (gitIndex.status !== 0 || !gitIndex.stdout.trim())
throw new Error(`Cannot resolve Git index path.`);
const realIndexPath = path.resolve(repoDir, gitIndex.stdout.trim());
const temporaryIndex = `${realIndexPath}.akm-${process.pid}-${randomBytes(6).toString("hex")}`;
const env = { GIT_INDEX_FILE: temporaryIndex };
try {
const seeded = options.baseHead
? runGit(["-C", repoDir, "read-tree", options.baseHead], { env })
: runGit(["-C", repoDir, "read-tree", "--empty"], { env });
if (seeded.status !== 0)
throw new Error(`Cannot seed temporary Git index: ${seeded.stderr.trim()}`);
const stagePaths = options.paths.filter((filePath) => (expected.get(filePath) ?? null) !== null || (baseStates.get(filePath) ?? null) !== null);
for (const result of runExactPathChunks(repoDir, ["add", "-A"], stagePaths, { env })) {
if (result.status !== 0)
throw new Error(`Cannot stage exact Git paths: ${result.stderr.trim()}`);
}
const tree = runGit(["-C", repoDir, "write-tree"], { env });
if (tree.status !== 0 || !tree.stdout.trim())
throw new Error(`Cannot write exact Git tree.`);
const treeOid = tree.stdout.trim();
const committedStates = readTreeStates(repoDir, treeOid, options.paths);
for (const filePath of options.paths) {
if (!samePathState(committedStates.get(filePath) ?? null, expected.get(filePath) ?? null)) {
throw new Error(`Exact Git publication path changed while committing: ${filePath}`);
}
}
assertWorktreeMatchesExpected(options.paths, expected, captureState);
const baseTreeResult = options.baseHead
? runGit(["-C", repoDir, "rev-parse", `${options.baseHead}^{tree}`])
: undefined;
if (baseTreeResult && (baseTreeResult.status !== 0 || !baseTreeResult.stdout.trim())) {
throw new Error(`Cannot inspect base Git tree.`);
}
const baseTree = baseTreeResult?.stdout.trim() ?? "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
if (treeOid === baseTree)
return null;
const body = options.transactionId
? `${options.commitMessage}\n\nAKM-Transaction: ${options.transactionId}\n`
: `${options.commitMessage}\n`;
const commit = runGit([
"-C",
repoDir,
"-c",
"user.name=akm",
"-c",
"user.email=akm@local",
"commit-tree",
treeOid,
...(options.baseHead ? ["-p", options.baseHead] : []),
], { input: body });
if (commit.status !== 0 || !commit.stdout.trim()) {
throw new Error(`git commit-tree failed: ${commit.stderr.trim() || "unknown error"}`);
}
const commitOid = commit.stdout.trim();
const currentBranch = readBranchRef(repoDir);
const currentHead = readOptionalHead(repoDir);
if (currentBranch !== branchRef || currentHead !== options.baseHead) {
throw new Error(`Git target changed before its exact commit could be attached.`);
}
assertWorktreeMatchesExpected(options.paths, expected, captureState);
// Race window: everything below this line is defended only by the
// update-ref compare-and-swap. See
// tests/integration/sync-exact-commit-cas.test.ts.
gitExactCommitHook("before-update-ref");
const update = runGit(["-C", repoDir, "update-ref", branchRef, commitOid, options.baseHead ?? ZERO_OID]);
if (update.status !== 0) {
throw new Error(`Git target advanced before its exact commit could be attached.`);
}
resetRealIndexPaths(repoDir, commitOid, options.paths, initialIndex);
return commitOid;
}
finally {
fs.rmSync(temporaryIndex, { force: true });
fs.rmSync(`${temporaryIndex}.lock`, { force: true });
}
}
function findSyncStashByTarget(stashes, target) {
return stashes.find((stash) => {
if (stash.type === "git")
return matchesGitStashTarget(stash, target);
if (stash.type !== "filesystem")
return false;
if (stash.name === target || stash.path === target)
return true;
return stash.path !== undefined && path.resolve(stash.path) === path.resolve(target);
});
}
function matchesGitStashTarget(stash, target) {
if (stash.type !== "git")
return false;
if (stash.name === target || stash.url === target)
return true;
if (!stash.url)
return false;
try {
const repo = parseGitRepoUrl(stash.url);
if (repo.canonicalUrl === target)
return true;
return buildGithubTargetAliases(repo.canonicalUrl).has(target);
}
catch {
return false;
}
}
function buildGithubTargetAliases(canonicalUrl) {
try {
const parsed = new URL(canonicalUrl);
if (parsed.hostname !== "github.com")
return new Set();
const segments = parsed.pathname.split("/").filter(Boolean);
if (segments.length < 2)
return new Set();
const owner = segments[0];
const repo = segments[1];
const aliases = new Set([`${owner}/${repo}`, `github:${owner}/${repo}`]);
if (segments[2] === "tree" && segments.length >= 4) {
const ref = segments.slice(3).join("/");
aliases.add(`${owner}/${repo}#${ref}`);
aliases.add(`github:${owner}/${repo}#${ref}`);
}
return aliases;
}
catch {
return new Set();
}
}