Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(runtime): vendored static git via managed manifest runtime (#871)

Call White266988177f98
diff --git a/.github/workflows/build-git.yml b/.github/workflows/build-git.yml
new file mode 100644
index 000000000..138353fa9
--- /dev/null
+++ b/.github/workflows/build-git.yml
@@ -0,0 +1,793 @@
+name: Build local-only Git runtime
+
+on:
+ workflow_dispatch:
+ inputs:
+ release_tag:
+ description: "Optional git-runtime-v<version>-<revision> tag to publish"
+ required: false
+ default: ""
+
+permissions:
+ contents: read
+
+env:
+ GIT_VERSION: "2.55.0"
+ GIT_SOURCE_URL: "https://www.kernel.org/pub/software/scm/git/git-2.55.0.tar.xz"
+ GIT_SOURCE_SHA256: "457fdb04dc8728e007d4688695e6912e6f680727920f2a40bf11eacc17505357"
+ GIT_RELEASE_REVISION: "1"
+
+jobs:
+ source:
+ name: Verify and constrain source
+ runs-on: ubuntu-latest
+ steps:
+ - name: Fetch and verify upstream source
+ shell: bash
+ run: |
+ set -euo pipefail
+ mkdir -p source
+ curl --fail --location --silent --show-error \
+ --output "source/git-$GIT_VERSION.tar.xz" "$GIT_SOURCE_URL"
+ echo "$GIT_SOURCE_SHA256 source/git-$GIT_VERSION.tar.xz" | sha256sum --check -
+ tar -xJf "source/git-$GIT_VERSION.tar.xz" -C source
+
+ - name: Remove remote and external command surfaces
+ shell: bash
+ working-directory: source/git-${{ env.GIT_VERSION }}
+ run: |
+ set -euo pipefail
+ patch --ignore-whitespace -p1 <<'PATCH'
+ --- a/git.c
+ +++ b/git.c
+ @@ -382,30 +382,7 @@
+ fprintf_ln(stderr, _("'%s' is aliased to '%s'"),
+ alias_command, alias_string);
+ if (alias_string[0] == '!') {
+ - struct child_process child = CHILD_PROCESS_INIT;
+ - int nongit_ok;
+ -
+ - /* Aliases expect GIT_PREFIX, GIT_DIR etc to be set */
+ - setup_git_directory_gently(the_repository, &nongit_ok);
+ -
+ - commit_pager_choice();
+ -
+ - child.use_shell = 1;
+ - child.clean_on_exit = 1;
+ - child.wait_after_clean = 1;
+ - child.trace2_child_class = "shell_alias";
+ - strvec_push(&child.args, alias_string + 1);
+ - strvec_pushv(&child.args, args->v + 1);
+ -
+ - trace2_cmd_alias(alias_command, child.args.v);
+ - trace2_cmd_name("_run_shell_alias_");
+ -
+ - ret = run_command(&child);
+ - if (ret >= 0) /* normal exit */
+ - exit(ret);
+ -
+ - die_errno(_("while expanding alias '%s': '%s'"),
+ - alias_command, alias_string + 1);
+ + die(_("shell aliases are disabled in the Avibe local-only Git runtime"));
+ }
+ count = split_cmdline(alias_string, &new_argv);
+ if (count < 0)
+ @@ -463,6 +440,34 @@
+ return ret;
+ }
+
+ +static int avibe_remote_command(const char *command, int argc, const char **argv)
+ +{
+ + static const char *const disabled[] = {
+ + "archive", "backfill", "clone", "daemon", "fetch", "fetch-pack",
+ + "http-backend",
+ + "imap-send", "ls-remote", "pull", "push",
+ + "receive-pack", "remote", "remote-ext", "remote-fd",
+ + "request-pull", "send-email", "send-pack", "submodule", "upload-archive",
+ + "upload-pack",
+ + };
+ + int maintenance_auto = 0;
+ +
+ + if (!strcmp(command, "maintenance")) {
+ + for (int i = 1; i < argc; i++) {
+ + if (strstr(argv[i], "prefetch"))
+ + return 1;
+ + if (!strcmp(argv[i], "--auto"))
+ + maintenance_auto = 1;
+ + }
+ + return !maintenance_auto;
+ + }
+ +
+ + for (size_t i = 0; i < ARRAY_SIZE(disabled); i++)
+ + if (!strcmp(command, disabled[i]))
+ + return 1;
+ + return 0;
+ +}
+ +
+ static int run_builtin(struct cmd_struct *p, int argc, const char **argv, struct repository *repo)
+ {
+ int status, help;
+ @@ -470,6 +475,14 @@
+ struct stat st;
+ const char *prefix;
+ int run_setup = (p->option & (RUN_SETUP | RUN_SETUP_GENTLY));
+ +
+ + if (!strcmp(p->cmd, "maintenance") &&
+ + !avibe_remote_command(p->cmd, argc, argv))
+ + return 0;
+ +
+ + if (avibe_remote_command(p->cmd, argc, argv))
+ + die(_("remote-capable command '%s' is disabled in the Avibe local-only Git runtime"),
+ + p->cmd);
+
+ help = argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help-all"));
+ if (help && (run_setup & RUN_SETUP))
+ @@ -788,45 +801,8 @@
+
+ static void execv_dashed_external(const char **argv)
+ {
+ - struct child_process cmd = CHILD_PROCESS_INIT;
+ - int status;
+ -
+ - if (use_pager == -1 && !is_builtin(argv[0]))
+ - use_pager = check_pager_config(the_repository, argv[0]);
+ - commit_pager_choice();
+ -
+ - strvec_pushf(&cmd.args, "git-%s", argv[0]);
+ - strvec_pushv(&cmd.args, argv + 1);
+ - cmd.clean_on_exit = 1;
+ - cmd.wait_after_clean = 1;
+ - cmd.silent_exec_failure = 1;
+ - cmd.trace2_child_class = "dashed";
+ -
+ - trace2_cmd_name("_run_dashed_");
+ -
+ - /*
+ - * The code in run_command() logs trace2 child_start/child_exit
+ - * events, so we do not need to report exec/exec_result events here.
+ - */
+ - trace_argv_printf(cmd.args.v, "trace: exec:");
+ -
+ - /*
+ - * If we fail because the command is not found, it is
+ - * OK to return. Otherwise, we just pass along the status code,
+ - * or our usual generic code if we were not even able to exec
+ - * the program.
+ - */
+ - status = run_command(&cmd);
+ -
+ - /*
+ - * If the child process ran and we are now going to exit, emit a
+ - * generic string as our trace2 command verb to indicate that we
+ - * launched a dashed command.
+ - */
+ - if (status >= 0)
+ - exit(status);
+ - else if (errno != ENOENT)
+ - exit(128);
+ + die(_("external command 'git-%s' is disabled in the Avibe local-only Git runtime"),
+ + argv[0]);
+ }
+
+ static int is_deprecated_command(const char *cmd)
+ --- a/hook.c
+ +++ b/hook.c
+ @@ -536,19 +536,15 @@
+ struct run_hooks_opt *options)
+ {
+ struct string_list *hook_head;
+ + (void)r;
+ + (void)options;
+
+ if (!hookname)
+ BUG("null hookname was provided to hook_list()!");
+
+ CALLOC_ARRAY(hook_head, 1);
+ string_list_init_dup(hook_head);
+ -
+ - /* Add hooks from the config, e.g. hook.myhook.event = pre-commit */
+ - list_hooks_add_configured(r, hookname, hook_head, options);
+
+ - /* Add the default "traditional" hooks from hookdir. */
+ - list_hooks_add_default(r, hookname, hook_head, options);
+ -
+ return hook_head;
+ }
+
+ --- a/convert.c
+ +++ b/convert.c
+ @@ -1021,59 +1021,10 @@
+ return 0;
+ }
+
+ -static int read_convert_config(const char *var, const char *value,
+ +static int read_convert_config(const char *var UNUSED, const char *value UNUSED,
+ const struct config_context *ctx UNUSED,
+ void *cb UNUSED)
+ {
+ - const char *key, *name;
+ - size_t namelen;
+ - struct convert_driver *drv;
+ -
+ - /*
+ - * External conversion drivers are configured using
+ - * "filter.<name>.variable".
+ - */
+ - if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
+ - return 0;
+ - for (drv = user_convert; drv; drv = drv->next)
+ - if (!xstrncmpz(drv->name, name, namelen))
+ - break;
+ - if (!drv) {
+ - CALLOC_ARRAY(drv, 1);
+ - drv->name = xmemdupz(name, namelen);
+ - *user_convert_tail = drv;
+ - user_convert_tail = &(drv->next);
+ - }
+ -
+ - /*
+ - * filter.<name>.smudge and filter.<name>.clean specifies
+ - * the command line:
+ - *
+ - * command-line
+ - *
+ - * The command-line will not be interpolated in any way.
+ - */
+ -
+ - if (!strcmp("smudge", key)) {
+ - FREE_AND_NULL(drv->smudge);
+ - return git_config_string(&drv->smudge, var, value);
+ - }
+ -
+ - if (!strcmp("clean", key)) {
+ - FREE_AND_NULL(drv->clean);
+ - return git_config_string(&drv->clean, var, value);
+ - }
+ -
+ - if (!strcmp("process", key)) {
+ - FREE_AND_NULL(drv->process);
+ - return git_config_string(&drv->process, var, value);
+ - }
+ -
+ - if (!strcmp("required", key)) {
+ - drv->required = git_config_bool(var, value);
+ - return 0;
+ - }
+ -
+ return 0;
+ }
+
+ --- a/run-command.c
+ +++ b/run-command.c
+ @@ -680,6 +680,18 @@
+ int fdin[2], fdout[2], fderr[2];
+ int failed_errno;
+ const char *str;
+ +
+ + if (!cmd->git_cmd) {
+ + if (cmd->in > 0)
+ + close(cmd->in);
+ + if (cmd->out > 0)
+ + close(cmd->out);
+ + if (cmd->err > 0)
+ + close(cmd->err);
+ + child_process_clear(cmd);
+ + errno = EPERM;
+ + return -1;
+ + }
+
+ /*
+ * In case of errors we must keep the promise to close FDs
+ --- a/commit.c
+ +++ b/commit.c
+ @@ -1749,6 +1749,7 @@
+ struct object_id *parent_buf = NULL, *compat_oid = NULL;
+ struct object_id compat_oid_buf;
+ size_t i, nparents;
+ + sign_commit = NULL;
+
+ /* Not having i18n.commitencoding is the same as having utf-8 */
+ encoding_is_utf8 = is_encoding_utf8(git_commit_encoding);
+ --- a/diff.c
+ +++ b/diff.c
+ @@ -557,20 +557,7 @@
+
+ static const struct external_diff *external_diff(void)
+ {
+ - static struct external_diff external_diff_env, *external_diff_ptr;
+ - static int done_preparing = 0;
+ -
+ - if (done_preparing)
+ - return external_diff_ptr;
+ - external_diff_env.cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
+ - if (git_env_bool("GIT_EXTERNAL_DIFF_TRUST_EXIT_CODE", 0))
+ - external_diff_env.trust_exit_code = 1;
+ - if (external_diff_env.cmd)
+ - external_diff_ptr = &external_diff_env;
+ - else if (external_diff_cfg.cmd)
+ - external_diff_ptr = &external_diff_cfg;
+ - done_preparing = 1;
+ - return external_diff_ptr;
+ + return NULL;
+ }
+
+ /*
+ @@ -3762,11 +3749,9 @@
+ struct userdiff_driver *get_textconv(struct repository *r,
+ struct diff_filespec *one)
+ {
+ - if (!DIFF_FILE_VALID(one))
+ - return NULL;
+ -
+ - diff_filespec_load_driver(one, r->index);
+ - return userdiff_get_textconv(r, one->driver);
+ + (void)r;
+ + (void)one;
+ + return NULL;
+ }
+
+ static struct string_list *additional_headers(struct diff_options *o,
+ --- a/fsmonitor-settings.c
+ +++ b/fsmonitor-settings.c
+ @@ -102,48 +102,9 @@
+
+ static void lookup_fsmonitor_settings(struct repository *r)
+ {
+ - const char *const_str;
+ - char *to_free = NULL;
+ - int bool_value;
+ -
+ if (r->settings.fsmonitor)
+ return;
+ -
+ - /*
+ - * Overload the existing "core.fsmonitor" config setting (which
+ - * has historically been either unset or a hook pathname) to
+ - * now allow a boolean value to enable the builtin FSMonitor
+ - * or to turn everything off. (This does imply that you can't
+ - * use a hook script named "true" or "false", but that's OK.)
+ - */
+ - switch (repo_config_get_maybe_bool(r, "core.fsmonitor", &bool_value)) {
+ -
+ - case 0: /* config value was set to <bool> */
+ - if (bool_value)
+ - fsm_settings__set_ipc(r);
+ - else
+ - fsm_settings__set_disabled(r);
+ - return;
+ -
+ - case 1: /* config value was unset */
+ - const_str = getenv("GIT_TEST_FSMONITOR");
+ - break;
+ -
+ - case -1: /* config value set to an arbitrary string */
+ - if (repo_config_get_pathname(r, "core.fsmonitor", &to_free))
+ - return; /* should not happen */
+ - const_str = to_free;
+ - break;
+ -
+ - default: /* should not happen */
+ - return;
+ - }
+ -
+ - if (const_str && *const_str)
+ - fsm_settings__set_hook(r, const_str);
+ - else
+ - fsm_settings__set_disabled(r);
+ - free(to_free);
+ + fsm_settings__set_disabled(r);
+ }
+
+ enum fsmonitor_mode fsm_settings__get_mode(struct repository *r)
+ --- a/pager.c
+ +++ b/pager.c
+ @@ -84,26 +84,9 @@
+
+ const char *git_pager(struct repository *r, int stdout_is_tty)
+ {
+ - const char *pager;
+ -
+ - if (!stdout_is_tty)
+ - return NULL;
+ -
+ - pager = getenv("GIT_PAGER");
+ - if (!pager) {
+ - if (!pager_program)
+ - read_early_config(r,
+ - core_pager_config, NULL);
+ - pager = pager_program;
+ - }
+ - if (!pager)
+ - pager = getenv("PAGER");
+ - if (!pager)
+ - pager = DEFAULT_PAGER;
+ - if (!*pager || !strcmp(pager, "cat"))
+ - pager = NULL;
+ -
+ - return pager;
+ + (void)r;
+ + (void)stdout_is_tty;
+ + return NULL;
+ }
+
+ static void setup_pager_env(struct strvec *env)
+ --- a/setup.c
+ +++ b/setup.c
+ @@ -2262,7 +2262,7 @@
+ }
+ template_dir = data.path;
+ }
+ - if (!template_dir) {
+ + if (!template_dir && *DEFAULT_GIT_TEMPLATE_DIR) {
+ static char *dir;
+
+ if (!dir)
+ PATCH
+
+ - name: Package verified source
+ shell: bash
+ run: |
+ set -euo pipefail
+ tar -czf git-source-patched.tar.gz -C source "git-$GIT_VERSION"
+
+ - uses: actions/upload-artifact@v6
+ with:
+ name: git-source-patched
+ path: git-source-patched.tar.gz
+
+ build-linux:
+ name: linux-${{ matrix.arch }}
+ needs: source
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - arch: x64
+ platform: linux/amd64
+ - arch: arm64
+ platform: linux/arm64
+ steps:
+ - uses: actions/download-artifact@v6
+ with:
+ name: git-source-patched
+
+ - uses: docker/setup-qemu-action@v3
+
+ - name: Build and verify static local-only Git
+ shell: bash
+ env:
+ TARGET_ARCH: ${{ matrix.arch }}
+ TARGET_PLATFORM: ${{ matrix.platform }}
+ run: |
+ set -euo pipefail
+ tar -xzf git-source-patched.tar.gz
+ docker run --rm --platform "$TARGET_PLATFORM" \
+ -e GIT_VERSION -e TARGET_ARCH \
+ -v "$PWD:/work" -w "/work/git-$GIT_VERSION" alpine:3.22 sh -euxc '
+ apk add --no-cache build-base file zlib-dev zlib-static
+ make -j"$(getconf _NPROCESSORS_ONLN)" git \
+ NO_CURL=YesPlease NO_EXPAT=YesPlease NO_GETTEXT=YesPlease \
+ NO_PERL=YesPlease NO_PYTHON=YesPlease NO_TCLTK=YesPlease \
+ NO_OPENSSL=YesPlease NO_ICONV=YesPlease NO_RUST=YesPlease \
+ SKIP_DASHED_BUILT_INS=YesPlease RUNTIME_PREFIX=YesPlease \
+ template_dir= gitexecdir=bin \
+ CFLAGS=-Os LDFLAGS=-static
+ mkdir -p /work/package/bin /work/dist
+ cp git /work/package/bin/git
+ strip /work/package/bin/git
+ file /work/package/bin/git | grep -q "statically linked"
+
+ git_bin=/work/package/bin/git
+ scratch="$(mktemp -d)"
+ export HOME="$scratch/home"
+ export GIT_CONFIG_NOSYSTEM=1
+ export GIT_CONFIG_GLOBAL=/dev/null
+ export PATH="/work/package/bin:/usr/bin:/bin"
+ mkdir -p "$HOME"
+ "$git_bin" init "$scratch/repo"
+ printf "first\n" > "$scratch/repo/example.txt"
+ "$git_bin" -C "$scratch/repo" add example.txt
+ "$git_bin" -C "$scratch/repo" \
+ -c user.name=Avibe -c [email protected] \
+ commit -m initial
+ hook_marker="$scratch/hook-ran"
+ mkdir -p "$scratch/repo/.git/hooks"
+ printf "#!/bin/sh\ntouch \"%s\"\n" "$hook_marker" > "$scratch/repo/.git/hooks/pre-commit"
+ chmod +x "$scratch/repo/.git/hooks/pre-commit"
+ filter_marker="$scratch/filter-ran"
+ filter_script="$scratch/filter.sh"
+ printf "#!/bin/sh\ntouch \"%s\"\ncat\n" "$filter_marker" > "$filter_script"
+ chmod +x "$filter_script"
+ sign_marker="$scratch/sign-ran"
+ sign_script="$scratch/sign.sh"
+ printf "#!/bin/sh\ntouch \"%s\"\nexit 1\n" "$sign_marker" > "$sign_script"
+ chmod +x "$sign_script"
+ "$git_bin" -C "$scratch/repo" config filter.avibe.clean "$filter_script"
+ "$git_bin" -C "$scratch/repo" config filter.avibe.required true
+ "$git_bin" -C "$scratch/repo" config commit.gpgsign true
+ "$git_bin" -C "$scratch/repo" config gpg.program "$sign_script"
+ printf "*.filtered filter=avibe diff=avibe\n" > "$scratch/repo/.gitattributes"
+ printf "filter input\n" > "$scratch/repo/payload.filtered"
+ "$git_bin" -C "$scratch/repo" add .gitattributes payload.filtered
+ "$git_bin" -C "$scratch/repo" \
+ -c user.name=Avibe -c [email protected] \
+ commit -m hardening-smoke
+ test ! -e "$hook_marker"
+ test ! -e "$filter_marker"
+ test ! -e "$sign_marker"
+ fsmonitor_marker="$scratch/fsmonitor-ran"
+ fsmonitor_script="$scratch/fsmonitor.sh"
+ printf "#!/bin/sh\ntouch \"%s\"\nexit 1\n" "$fsmonitor_marker" > "$fsmonitor_script"
+ chmod +x "$fsmonitor_script"
+ "$git_bin" -C "$scratch/repo" config core.fsmonitor "$fsmonitor_script"
+ "$git_bin" -C "$scratch/repo" status --short
+ test ! -e "$fsmonitor_marker"
+ "$git_bin" -C "$scratch/repo" log --oneline -1
+ pager_marker="$scratch/pager-ran"
+ pager_script="$scratch/pager.sh"
+ printf "#!/bin/sh\ntouch \"%s\"\ncat\n" "$pager_marker" > "$pager_script"
+ chmod +x "$pager_script"
+ GIT_PAGER="$pager_script" "$git_bin" -C "$scratch/repo" --paginate log --oneline -1
+ test ! -e "$pager_marker"
+ printf "second\n" >> "$scratch/repo/example.txt"
+ diff_marker="$scratch/diff-ran"
+ diff_script="$scratch/diff.sh"
+ printf "#!/bin/sh\ntouch \"%s\"\nexit 1\n" "$diff_marker" > "$diff_script"
+ chmod +x "$diff_script"
+ "$git_bin" -C "$scratch/repo" config diff.external "$diff_script"
+ GIT_EXTERNAL_DIFF="$diff_script" "$git_bin" -C "$scratch/repo" diff -- example.txt
+ test ! -e "$diff_marker"
+ "$git_bin" -C "$scratch/repo" config --unset diff.external
+ textconv_marker="$scratch/textconv-ran"
+ textconv_script="$scratch/textconv.sh"
+ printf "#!/bin/sh\ntouch \"%s\"\ncat \"\$1\"\n" "$textconv_marker" > "$textconv_script"
+ chmod +x "$textconv_script"
+ "$git_bin" -C "$scratch/repo" config diff.avibe.textconv "$textconv_script"
+ printf "filter second\n" >> "$scratch/repo/payload.filtered"
+ "$git_bin" -C "$scratch/repo" diff --textconv -- payload.filtered
+ test ! -e "$textconv_marker"
+ "$git_bin" -C "$scratch/repo" restore -- example.txt payload.filtered
+ PATH=/nonexistent "$git_bin" -C "$scratch/repo" gc
+ test -z "$("$git_bin" -C "$scratch/repo" status --porcelain)"
+ "$git_bin" init --bare "$scratch/remote"
+ if remote_error="$("$git_bin" -C "$scratch/repo" push "$scratch/remote" HEAD 2>&1)"; then
+ echo "remote push unexpectedly succeeded" >&2
+ exit 1
+ fi
+ printf "%s\n" "$remote_error" | grep -Fq "remote-capable command"
+
+ archive="/work/dist/git-$GIT_VERSION-linux-$TARGET_ARCH.tar.gz"
+ tar -czf "$archive" -C /work/package bin/git
+ (cd /work/dist && sha256sum "$(basename "$archive")" > "$(basename "$archive").sha256")
+ '
+
+ - uses: actions/upload-artifact@v6
+ with:
+ name: git-runtime-linux-${{ matrix.arch }}
+ path: dist/git-*.tar.gz*
+
+ build-macos:
+ name: darwin-${{ matrix.arch }}
+ needs: source
+ runs-on: ${{ matrix.runner }}
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - arch: x64
+ runner: macos-15-intel
+ - arch: arm64
+ runner: macos-15
+ steps:
+ - uses: actions/download-artifact@v6
+ with:
+ name: git-source-patched
+
+ - name: Build and verify relocatable local-only Git
+ shell: bash
+ env:
+ TARGET_ARCH: ${{ matrix.arch }}
+ run: |
+ set -euo pipefail
+ tar -xzf git-source-patched.tar.gz
+ cd "git-$GIT_VERSION"
+ make -j"$(sysctl -n hw.ncpu)" git \
+ NO_CURL=YesPlease NO_EXPAT=YesPlease NO_GETTEXT=YesPlease \
+ NO_PERL=YesPlease NO_PYTHON=YesPlease NO_TCLTK=YesPlease \
+ NO_OPENSSL=YesPlease NO_RUST=YesPlease \
+ SKIP_DASHED_BUILT_INS=YesPlease RUNTIME_PREFIX=YesPlease \
+ template_dir= gitexecdir=bin \
+ CFLAGS=-Os LDFLAGS=-Wl,-dead_strip
+ mkdir -p ../package/bin ../dist
+ cp git ../package/bin/git
+ strip -x ../package/bin/git
+ codesign --force --sign - ../package/bin/git
+ file ../package/bin/git | grep -q "Mach-O 64-bit executable"
+ otool -L ../package/bin/git | tail -n +2 | awk '{print $1}' | while read -r dependency; do
+ case "$dependency" in
+ /usr/lib/*|/System/Library/*) ;;
+ *)
+ echo "non-system dependency: $dependency" >&2
+ exit 1
+ ;;
+ esac
+ done
+
+ git_bin="$PWD/../package/bin/git"
+ scratch="$(mktemp -d)"
+ export HOME="$scratch/home"
+ export GIT_CONFIG_NOSYSTEM=1
+ export GIT_CONFIG_GLOBAL=/dev/null
+ export PATH="$PWD/../package/bin:/usr/bin:/bin"
+ mkdir -p "$HOME"
+ "$git_bin" init "$scratch/repo"
+ printf "first\n" > "$scratch/repo/example.txt"
+ "$git_bin" -C "$scratch/repo" add example.txt
+ "$git_bin" -C "$scratch/repo" \
+ -c user.name=Avibe -c [email protected] \
+ commit -m initial
+ hook_marker="$scratch/hook-ran"
+ mkdir -p "$scratch/repo/.git/hooks"
+ printf "#!/bin/sh\ntouch \"%s\"\n" "$hook_marker" > "$scratch/repo/.git/hooks/pre-commit"
+ chmod +x "$scratch/repo/.git/hooks/pre-commit"
+ filter_marker="$scratch/filter-ran"
+ filter_script="$scratch/filter.sh"
+ printf "#!/bin/sh\ntouch \"%s\"\ncat\n" "$filter_marker" > "$filter_script"
+ chmod +x "$filter_script"
+ sign_marker="$scratch/sign-ran"
+ sign_script="$scratch/sign.sh"
+ printf "#!/bin/sh\ntouch \"%s\"\nexit 1\n" "$sign_marker" > "$sign_script"
+ chmod +x "$sign_script"
+ "$git_bin" -C "$scratch/repo" config filter.avibe.clean "$filter_script"
+ "$git_bin" -C "$scratch/repo" config filter.avibe.required true
+ "$git_bin" -C "$scratch/repo" config commit.gpgsign true
+ "$git_bin" -C "$scratch/repo" config gpg.program "$sign_script"
+ printf "*.filtered filter=avibe diff=avibe\n" > "$scratch/repo/.gitattributes"
+ printf "filter input\n" > "$scratch/repo/payload.filtered"
+ "$git_bin" -C "$scratch/repo" add .gitattributes payload.filtered
+ "$git_bin" -C "$scratch/repo" \
+ -c user.name=Avibe -c [email protected] \
+ commit -m hardening-smoke
+ test ! -e "$hook_marker"
+ test ! -e "$filter_marker"
+ test ! -e "$sign_marker"
+ fsmonitor_marker="$scratch/fsmonitor-ran"
+ fsmonitor_script="$scratch/fsmonitor.sh"
+ printf "#!/bin/sh\ntouch \"%s\"\nexit 1\n" "$fsmonitor_marker" > "$fsmonitor_script"
+ chmod +x "$fsmonitor_script"
+ "$git_bin" -C "$scratch/repo" config core.fsmonitor "$fsmonitor_script"
+ "$git_bin" -C "$scratch/repo" status --short
+ test ! -e "$fsmonitor_marker"
+ "$git_bin" -C "$scratch/repo" log --oneline -1
+ pager_marker="$scratch/pager-ran"
+ pager_script="$scratch/pager.sh"
+ printf "#!/bin/sh\ntouch \"%s\"\ncat\n" "$pager_marker" > "$pager_script"
+ chmod +x "$pager_script"
+ GIT_PAGER="$pager_script" "$git_bin" -C "$scratch/repo" --paginate log --oneline -1
+ test ! -e "$pager_marker"
+ printf "second\n" >> "$scratch/repo/example.txt"
+ diff_marker="$scratch/diff-ran"
+ diff_script="$scratch/diff.sh"
+ printf "#!/bin/sh\ntouch \"%s\"\nexit 1\n" "$diff_marker" > "$diff_script"
+ chmod +x "$diff_script"
+ "$git_bin" -C "$scratch/repo" config diff.external "$diff_script"
+ GIT_EXTERNAL_DIFF="$diff_script" "$git_bin" -C "$scratch/repo" diff -- example.txt
+ test ! -e "$diff_marker"
+ "$git_bin" -C "$scratch/repo" config --unset diff.external
+ textconv_marker="$scratch/textconv-ran"
+ textconv_script="$scratch/textconv.sh"
+ printf "#!/bin/sh\ntouch \"%s\"\ncat \"\$1\"\n" "$textconv_marker" > "$textconv_script"
+ chmod +x "$textconv_script"
+ "$git_bin" -C "$scratch/repo" config diff.avibe.textconv "$textconv_script"
+ printf "filter second\n" >> "$scratch/repo/payload.filtered"
+ "$git_bin" -C "$scratch/repo" diff --textconv -- payload.filtered
+ test ! -e "$textconv_marker"
+ "$git_bin" -C "$scratch/repo" restore -- example.txt payload.filtered
+ PATH=/nonexistent "$git_bin" -C "$scratch/repo" gc
+ test -z "$("$git_bin" -C "$scratch/repo" status --porcelain)"
+ "$git_bin" init --bare "$scratch/remote"
+ if remote_error="$("$git_bin" -C "$scratch/repo" push "$scratch/remote" HEAD 2>&1)"; then
+ echo "remote push unexpectedly succeeded" >&2
+ exit 1
+ fi
+ printf "%s\n" "$remote_error" | grep -Fq "remote-capable command 'push' is disabled"
+
+ archive="$PWD/../dist/git-$GIT_VERSION-darwin-$TARGET_ARCH.tar.gz"
+ COPYFILE_DISABLE=1 tar -czf "$archive" -C ../package bin/git
+ (cd ../dist && shasum -a 256 "$(basename "$archive")" > "$(basename "$archive").sha256")
+
+ - uses: actions/upload-artifact@v6
+ with:
+ name: git-runtime-darwin-${{ matrix.arch }}
+ path: dist/git-*.tar.gz*
+
+ manifest:
+ name: Manifest and optional release
+ needs: [build-linux, build-macos]
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ steps:
+ - uses: actions/download-artifact@v6
+ with:
+ pattern: git-runtime-*
+ path: dist
+ merge-multiple: true
+
+ - name: Generate pinned runtime manifest
+ shell: bash
+ env:
+ RELEASE_TAG: ${{ inputs.release_tag }}
+ run: |
+ set -euo pipefail
+ python3 - <<'PY'
+ import hashlib
+ import json
+ import os
+ import re
+ import tarfile
+ from pathlib import Path
+
+ version = os.environ["GIT_VERSION"]
+ source_url = os.environ["GIT_SOURCE_URL"]
+ source_sha256 = os.environ["GIT_SOURCE_SHA256"]
+ release_tag = os.environ.get("RELEASE_TAG") or f"git-runtime-v{version}-{os.environ['GIT_RELEASE_REVISION']}"
+ requested_tag = os.environ.get("RELEASE_TAG") or ""
+ if requested_tag and not re.fullmatch(rf"git-runtime-v{re.escape(version)}-[1-9][0-9]*", requested_tag):
+ raise SystemExit(f"invalid release tag: {requested_tag}")
+
+ archives = {}
+ for platform in ("darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"):
+ path = next(Path("dist").glob(f"git-{version}-{platform}.tar.gz"), None)
+ if path is None:
+ raise SystemExit(f"missing archive for {platform}")
+ with tarfile.open(path, "r:gz") as archive:
+ binary = archive.extractfile("bin/git")
+ if binary is None:
+ raise SystemExit(f"missing bin/git in {path}")
+ binary_sha256 = hashlib.sha256(binary.read()).hexdigest()
+ archives[platform] = {
+ "name": path.name,
+ "url": f"https://github.com/avibe-bot/avibe/releases/download/{release_tag}/{path.name}",
+ "sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
+ "binary_sha256": binary_sha256,
+ "size": path.stat().st_size,
+ "bin_path": "bin/git",
+ }
+
+ manifest = {
+ "schema_version": 1,
+ "git_version": version,
+ "source": "kernel.org/git",
+ "source_url": source_url,
+ "source_sha256": source_sha256,
+ "release_tag": release_tag,
+ "release_state": "published" if requested_tag else "pending",
+ "local_ops_only": True,
+ "archives": archives,
+ }
+ Path("dist/git-runtime-manifest.json").write_text(
+ json.dumps(manifest, indent=2, sort_keys=True) + "\n",
+ encoding="utf-8",
+ )
+ PY
+
+ - uses: actions/upload-artifact@v6
+ with:
+ name: git-runtime-manifest
+ path: dist/git-runtime-manifest.json
+
+ - name: Publish runtime release assets
+ if: inputs.release_tag != ''
+ uses: softprops/action-gh-release@v3
+ with:
+ tag_name: ${{ inputs.release_tag }}
+ name: "Avibe local-only Git runtime ${{ env.GIT_VERSION }} (build ${{ env.GIT_RELEASE_REVISION }})"
+ body: |
+ Avibe-managed local-only Git runtime built from the pinned upstream source tarball.
+ Remote-capable commands, external Git commands, and shell aliases are disabled.
+ files: |
+ dist/git-*.tar.gz
+ dist/git-*.tar.gz.sha256
+ dist/git-runtime-manifest.json
diff --git a/core/git_runtime.py b/core/git_runtime.py
new file mode 100644
index 000000000..2e23114af
--- /dev/null
+++ b/core/git_runtime.py
@@ -0,0 +1,279 @@
+from __future__ import annotations
+
+import logging
+import os
+import platform
+import shutil
+import subprocess
+import sys
+from collections.abc import Mapping
+from pathlib import Path
+from typing import Any
+
+from config import paths
+from core.managed_runtime import (
+ ManagedRuntimeManager,
+ ManagedRuntimeManifest,
+ ManagedRuntimeSpec,
+ env_flag_enabled,
+)
+from core.process_isolation import isolated_subprocess_kwargs
+
+
+logger = logging.getLogger(__name__)
+
+_GIT_MANIFEST_RESOURCE = "git_runtime_manifest.json"
+_MACOS_CODESIGN = Path("/usr/bin/codesign")
+_MACOS_XATTR = Path("/usr/bin/xattr")
+_MACOS_XCODE_SELECT = Path("/usr/bin/xcode-select")
+_GIT_SPEC = ManagedRuntimeSpec(
+ runtime_id="git",
+ manifest_resource=_GIT_MANIFEST_RESOURCE,
+ version_field="git_version",
+ default_bin_path="bin/git",
+)
+_MACHO_MAGICS = {
+ b"\xca\xfe\xba\xbe",
+ b"\xbe\xba\xfe\xca",
+ b"\xcf\xfa\xed\xfe",
+ b"\xce\xfa\xed\xfe",
+ b"\xfe\xed\xfa\xcf",
+ b"\xfe\xed\xfa\xce",
+}
+
+
+class GitRuntimeManager(ManagedRuntimeManager):
+ """Install and resolve Avibe's vendored local-only Git binary."""
+
+ def __init__(
+ self,
+ *,
+ runtime_dir: Path | None = None,
+ manifest_path: Path | str | None = None,
+ manifest_url: str | None = None,
+ offline: bool | None = None,
+ ) -> None:
+ manifest_path_value = manifest_path or os.environ.get("VIBE_GIT_MANIFEST_PATH")
+ super().__init__(
+ spec=_GIT_SPEC,
+ runtime_dir=runtime_dir or paths.get_runtime_dir() / "git",
+ manifest_path=manifest_path_value,
+ manifest_url=manifest_url if manifest_url is not None else os.environ.get("VIBE_GIT_MANIFEST_URL"),
+ offline=env_flag_enabled("VIBE_GIT_OFFLINE") if offline is None else offline,
+ )
+
+ def resolve_git_path(self) -> Path | None:
+ """Return a verified installed vendored Git, or ``None`` without installing."""
+
+ return self.resolve_binary()
+
+ def _manifest_installable(self, manifest: ManagedRuntimeManifest) -> bool:
+ if str(manifest.payload.get("release_state") or "published") != "published":
+ self._install_reason = "git_runtime_unpublished"
+ return False
+ return True
+
+ def _binary_version(self, binary: Path | None) -> str | None:
+ return _probe_git_version(binary)
+
+ def _prepare_binary(self, binary: Path) -> dict[str, Any]:
+ if sys.platform != "darwin" or not _is_macho(binary):
+ return {"ok": True, "skipped": True, "reason": "not_macos_macho"}
+ quarantine = _strip_quarantine(binary)
+ if _codesign_valid(binary):
+ return {"ok": True, "changed": False, "quarantine": quarantine}
+ if not _MACOS_CODESIGN.is_file():
+ return {"ok": False, "reason": "git_codesign_missing", "quarantine": quarantine}
+ try:
+ proc = subprocess.run(
+ [str(_MACOS_CODESIGN), "-f", "-s", "-", str(binary)],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ check=False,
+ **isolated_subprocess_kwargs(),
+ )
+ except Exception: # noqa: BLE001
+ return {"ok": False, "reason": "git_codesign_failed", "quarantine": quarantine}
+ verified = proc.returncode == 0 and _codesign_valid(binary)
+ return {
+ "ok": verified,
+ "changed": proc.returncode == 0,
+ "reason": None if verified else "git_codesign_failed",
+ "quarantine": quarantine,
+ }
+
+
+_manager: GitRuntimeManager | None = None
+
+
+def get_git_runtime_manager() -> GitRuntimeManager:
+ global _manager
+ if _manager is None:
+ _manager = GitRuntimeManager()
+ return _manager
+
+
+def set_git_runtime_manager_for_tests(manager: GitRuntimeManager | None) -> None:
+ global _manager
+ _manager = manager
+
+
+def git_runtime_status() -> dict[str, Any]:
+ manager = get_git_runtime_manager()
+ vendored = manager.resolve_git_path()
+ managed_status = manager.status()
+ system = resolve_system_git_path()
+ vendored_version = str(managed_status.get("version") or "") or None
+ system_version = None
+ if vendored is not None:
+ resolution = "vendored"
+ resolved_path = vendored
+ resolved_version = vendored_version
+ elif system is not None:
+ resolution = "system"
+ resolved_path = system
+ resolved_version = system_version
+ else:
+ resolution = "none"
+ resolved_path = None
+ resolved_version = None
+
+ if system is not None:
+ agent_resolution = "system"
+ agent_path = system
+ agent_version = system_version
+ elif vendored is not None:
+ agent_resolution = "vendored"
+ agent_path = vendored
+ agent_version = vendored_version
+ else:
+ agent_resolution = "none"
+ agent_path = None
+ agent_version = None
+
+ return {
+ "id": "git",
+ # Platform-owned features follow #669's vendored -> system order.
+ "resolution": resolution,
+ "path": str(resolved_path) if resolved_path else None,
+ "version": resolved_version,
+ # Planned Agent order for post-merge wiring; this PR does not mutate child PATH.
+ "agent": {
+ "resolution": agent_resolution,
+ "path": str(agent_path) if agent_path else None,
+ "version": agent_version,
+ },
+ "managed": managed_status,
+ }
+
+
+def resolve_system_git_path(*, env: Mapping[str, str] | None = None) -> Path | None:
+ """Resolve the Git selected by PATH without triggering the macOS CLT shim.
+
+ The Git candidate intentionally follows the supplied PATH for runtime status
+ reporting. When ``env`` is provided, an absent or empty PATH never falls
+ back to the parent process. Supporting system probes never follow that PATH.
+ """
+
+ source = env if env is not None else os.environ
+ search_path = source.get("PATH", "")
+ if not search_path:
+ return None
+ candidate = shutil.which("git", path=search_path)
+ if not candidate:
+ return None
+ candidate_path = Path(candidate)
+ if platform.system() == "Darwin" and _is_macos_system_git(candidate_path):
+ try:
+ proc = subprocess.run(
+ [str(_MACOS_XCODE_SELECT), "-p"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ check=False,
+ **isolated_subprocess_kwargs(),
+ )
+ except Exception: # noqa: BLE001
+ return None
+ if proc.returncode != 0 or not (proc.stdout or "").strip():
+ return None
+ return candidate_path
+
+
+def _probe_git_version(binary: Path | None) -> str | None:
+ if binary is None:
+ return None
+ try:
+ proc = subprocess.run(
+ [str(binary), "--version"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ check=False,
+ **isolated_subprocess_kwargs(),
+ )
+ except Exception: # noqa: BLE001
+ return None
+ if proc.returncode != 0:
+ return None
+ output = (proc.stdout or proc.stderr or "").strip()
+ prefix = "git version "
+ if not output.startswith(prefix):
+ return None
+ version = output[len(prefix) :].split()[0] if output[len(prefix) :].strip() else ""
+ return version or None
+
+
+def _is_macos_system_git(path: Path) -> bool:
+ try:
+ return path == Path("/usr/bin/git") or path.resolve() == Path("/usr/bin/git")
+ except OSError:
+ return path == Path("/usr/bin/git")
+
+
+def _is_macho(path: Path) -> bool:
+ try:
+ with path.open("rb") as handle:
+ return handle.read(4) in _MACHO_MAGICS
+ except OSError:
+ return False
+
+
+def _codesign_valid(binary: Path) -> bool:
+ if not _MACOS_CODESIGN.is_file():
+ return False
+ try:
+ proc = subprocess.run(
+ [str(_MACOS_CODESIGN), "-v", str(binary)],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ **isolated_subprocess_kwargs(),
+ )
+ except Exception: # noqa: BLE001
+ return False
+ return proc.returncode == 0
+
+
+def _strip_quarantine(binary: Path) -> dict[str, Any]:
+ if not _MACOS_XATTR.is_file():
+ return {"ok": True, "skipped": True, "reason": "xattr_missing"}
+ try:
+ proc = subprocess.run(
+ [str(_MACOS_XATTR), "-d", "com.apple.quarantine", str(binary)],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ **isolated_subprocess_kwargs(),
+ )
+ except Exception: # noqa: BLE001
+ return {"ok": False, "changed": False, "reason": "xattr_failed"}
+ if proc.returncode == 0:
+ return {"ok": True, "changed": True}
+ output = (proc.stderr or proc.stdout or "").lower()
+ if "no such xattr" in output or "no such file" in output:
+ return {"ok": True, "changed": False}
+ return {"ok": False, "changed": False, "reason": "xattr_failed"}
diff --git a/core/managed_runtime.py b/core/managed_runtime.py
new file mode 100644
index 000000000..e41fc3639
--- /dev/null
+++ b/core/managed_runtime.py
@@ -0,0 +1,787 @@
+from __future__ import annotations
+
+import hashlib
+import importlib.resources as package_resources
+import json
+import logging
+import os
+import platform
+import re
+import shutil
+import stat
+import sys
+import tarfile
+import tempfile
+import threading
+import urllib.parse
+import urllib.request
+from dataclasses import dataclass
+from pathlib import Path, PurePosixPath, PureWindowsPath
+from sysconfig import get_platform
+from typing import Any
+
+from storage.lock import MigrationFileLock, MigrationLockTimeout
+
+
+logger = logging.getLogger(__name__)
+
+_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
+_INSTALL_LOCKS: dict[str, threading.Lock] = {}
+_INSTALL_LOCKS_GUARD = threading.Lock()
+
+
+@dataclass(frozen=True)
+class ManagedRuntimeArchive:
+ platform: str
+ name: str
+ url: str
+ sha256: str
+ binary_sha256: str
+ size: int | None
+ bin_path: str
+
+
+@dataclass(frozen=True)
+class ManagedRuntimeManifest:
+ schema_version: int
+ runtime_version: str
+ source: str
+ source_url: str | None
+ archives: dict[str, ManagedRuntimeArchive]
+ digest: str
+ loaded_from: str
+ payload: dict[str, Any]
+
+
+@dataclass(frozen=True)
+class ManagedRuntimeSpec:
+ runtime_id: str
+ manifest_resource: str
+ version_field: str
+ default_bin_path: str
+ package: str = "vibe"
+
+ @property
+ def metadata_filename(self) -> str:
+ return f".avibe-{self.runtime_id}-runtime.json"
+
+
+class ManagedRuntimeManager:
+ """Shared manifest/download/verify/install core for managed runtimes."""
+
+ def __init__(
+ self,
+ *,
+ spec: ManagedRuntimeSpec,
+ runtime_dir: Path,
+ manifest_path: Path | str | None = None,
+ manifest_url: str | None = None,
+ offline: bool = False,
+ ) -> None:
+ self.spec = spec
+ self.runtime_dir = runtime_dir
+ self.manifest_path = Path(manifest_path).expanduser() if manifest_path else None
+ self.manifest_url = manifest_url
+ self.offline = offline
+ self._install_reason: str | None = None
+ self._install_lock = install_lock_for(spec.runtime_id)
+ self._install_file_lock_path = self.runtime_dir / ".install.lock"
+
+ def ensure(self, *, force: bool = False) -> dict[str, Any]:
+ try:
+ file_lock = self._acquire_mutation_lock()
+ except Exception as exc: # noqa: BLE001
+ logger.exception("Failed to acquire managed %s runtime lock", self.spec.runtime_id)
+ return self._failure(self._reason("install_lock_failed"), message=str(exc))
+ if file_lock is None:
+ return self._failure(
+ self._reason("install_already_running"),
+ message=f"{self.spec.runtime_id} install or repair is already running; try again shortly.",
+ skipped=True,
+ )
+ try:
+ manifest = self._load_manifest(allow_network=not self.offline)
+ if manifest is None:
+ return self._failure(self._install_reason or self._reason("manifest_missing"))
+ if not self._manifest_installable(manifest):
+ return self._failure(self._install_reason or self._reason("manifest_unavailable"), manifest=manifest)
+ archive = self._manifest_archive_for_platform(manifest)
+ if archive is None:
+ return self._failure(
+ self._install_reason or self._reason("platform_unsupported"),
+ manifest=manifest,
+ )
+
+ install_dir = self._manifest_install_dir(manifest, archive)
+ existing = self._verified_manifest_binary(install_dir, manifest, archive)
+ if existing is not None and not force:
+ return self._reuse_existing_install(existing, install_dir, manifest, archive)
+
+ archive_path = self._resolve_manifest_archive(archive)
+ if archive_path is None:
+ if existing is not None:
+ return self._reuse_existing_install(
+ existing,
+ install_dir,
+ manifest,
+ archive,
+ reason=self._install_reason,
+ )
+ return self._failure(
+ self._install_reason or self._reason("archive_unavailable"),
+ manifest=manifest,
+ archive=archive,
+ )
+
+ self.runtime_dir.mkdir(parents=True, exist_ok=True)
+ staging_dir = Path(tempfile.mkdtemp(prefix="install-", dir=self.runtime_dir))
+ try:
+ with tarfile.open(archive_path, "r:gz") as archive_file:
+ safe_extract_tar(archive_file, staging_dir)
+ staged_binary = staging_dir / archive.bin_path
+ if not staged_binary.is_file():
+ return self._failure(
+ self._reason("install_missing_binary"),
+ manifest=manifest,
+ archive=archive,
+ )
+ make_executable(staged_binary)
+ preparation = self._prepare_binary(staged_binary)
+ if not preparation.get("ok"):
+ return self._failure(
+ str(preparation.get("reason") or self._reason("binary_prepare_failed")),
+ manifest=manifest,
+ archive=archive,
+ )
+ binary_sha256 = file_sha256(staged_binary)
+ if binary_sha256 != archive.binary_sha256:
+ return self._failure(
+ self._reason("binary_checksum_mismatch"),
+ manifest=manifest,
+ archive=archive,
+ )
+ if not self._binary_matches_manifest(staged_binary, manifest):
+ return self._failure(
+ self._reason("binary_not_runnable"),
+ manifest=manifest,
+ archive=archive,
+ )
+
+ if install_dir.exists():
+ shutil.rmtree(install_dir)
+ install_dir.parent.mkdir(parents=True, exist_ok=True)
+ shutil.move(str(staging_dir), str(install_dir))
+ installed_binary = install_dir / archive.bin_path
+ self._write_manifest_install_metadata(
+ install_dir,
+ manifest,
+ archive,
+ binary_sha256=binary_sha256,
+ )
+ self._write_current_pointer(install_dir, manifest, archive)
+ self._install_reason = None
+ return {
+ **self._success_payload(
+ installed_binary,
+ install_dir,
+ manifest,
+ archive,
+ changed=True,
+ ),
+ "preparation": preparation,
+ }
+ except Exception as exc: # noqa: BLE001
+ logger.exception("Failed to install managed %s runtime", self.spec.runtime_id)
+ return self._failure(
+ self._reason("install_failed"),
+ manifest=manifest,
+ archive=archive,
+ message=str(exc),
+ )
+ finally:
+ if staging_dir.exists():
+ shutil.rmtree(staging_dir, ignore_errors=True)
+ finally:
+ self._release_mutation_lock(file_lock)
+
+ def resolve_binary(self) -> Path | None:
+ """Resolve an already installed runtime without performing network I/O."""
+
+ try:
+ manifest = self._load_manifest(allow_network=False)
+ if manifest is None or not self._manifest_installable(manifest):
+ return None
+ archive = self._manifest_archive_for_platform(manifest)
+ if archive is None:
+ return None
+ return self._verified_manifest_binary(
+ self._manifest_install_dir(manifest, archive),
+ manifest,
+ archive,
+ )
+ except Exception: # noqa: BLE001
+ logger.debug("Failed to resolve managed %s runtime", self.spec.runtime_id, exc_info=True)
+ return None
+
+ def status(self) -> dict[str, Any]:
+ manifest = self._load_manifest(allow_network=False)
+ platform_tag = runtime_platform_tag()
+ archive = manifest.archives.get(platform_tag) if manifest else None
+ install_dir = self._manifest_install_dir(manifest, archive) if manifest and archive else None
+ binary = self.resolve_binary() if manifest and archive else None
+ return {
+ "id": self.spec.runtime_id,
+ "provider": "manifest",
+ "platform": platform_tag,
+ "installed": binary is not None,
+ "version": manifest.runtime_version if manifest else None,
+ "status": "ready" if binary else "missing",
+ "path": str(binary) if binary else None,
+ "install_dir": str(install_dir) if install_dir else None,
+ "manifest": self._manifest_status_payload(manifest),
+ "archive": self._archive_status_payload(archive),
+ "reason": self._install_reason,
+ }
+
+ def clean(self, *, keep_previous: int = 1) -> dict[str, Any]:
+ try:
+ file_lock = self._acquire_mutation_lock()
+ except Exception as exc: # noqa: BLE001
+ logger.exception("Failed to acquire managed %s runtime lock", self.spec.runtime_id)
+ return {
+ "ok": False,
+ "removed": [],
+ "reason": self._reason("clean_lock_failed"),
+ "message": str(exc),
+ }
+ if file_lock is None:
+ return {
+ "ok": False,
+ "removed": [],
+ "reason": self._reason("install_already_running"),
+ }
+ try:
+ return self._clean_locked(keep_previous=keep_previous)
+ finally:
+ self._release_mutation_lock(file_lock)
+
+ def _clean_locked(self, *, keep_previous: int) -> dict[str, Any]:
+ removed: list[str] = []
+ for staging_dir in self.runtime_dir.glob("install-*"):
+ if staging_dir.is_dir():
+ shutil.rmtree(staging_dir, ignore_errors=True)
+ removed.append(str(staging_dir))
+
+ versions_dir = self.runtime_dir / "versions"
+ if not versions_dir.is_dir():
+ return {"ok": True, "removed": removed}
+
+ install_dirs = {
+ metadata_path.parent
+ for metadata_path in versions_dir.rglob(self.spec.metadata_filename)
+ if metadata_path.parent.is_dir()
+ }
+ current = self._current_install_dir(versions_dir)
+ protected = {current} if current is not None else set()
+ candidates = sorted(
+ (path for path in install_dirs if path.resolve() not in protected),
+ key=lambda path: path.stat().st_mtime,
+ reverse=True,
+ )
+ for path in candidates[max(0, keep_previous) :]:
+ shutil.rmtree(path, ignore_errors=True)
+ removed.append(str(path))
+ self._prune_empty_version_dirs(versions_dir)
+ return {"ok": True, "removed": removed}
+
+ def _manifest_installable(self, manifest: ManagedRuntimeManifest) -> bool:
+ return True
+
+ def _prepare_binary(self, binary: Path) -> dict[str, Any]:
+ return {"ok": True, "skipped": True}
+
+ def _binary_version(self, binary: Path | None) -> str | None:
+ raise NotImplementedError
+
+ def _binary_matches_manifest(self, binary: Path, manifest: ManagedRuntimeManifest) -> bool:
+ return self._binary_version(binary) == manifest.runtime_version
+
+ def _load_manifest(self, *, allow_network: bool) -> ManagedRuntimeManifest | None:
+ payload: bytes
+ loaded_from: str
+ cache_remote = False
+ if self.manifest_path is not None:
+ if not self.manifest_path.is_file():
+ self._install_reason = self._reason("manifest_missing")
+ return None
+ try:
+ payload = self.manifest_path.read_bytes()
+ except OSError:
+ self._install_reason = self._reason("manifest_missing")
+ return None
+ loaded_from = str(self.manifest_path)
+ elif self.manifest_url:
+ cached_manifest = self._remote_manifest_cache_path()
+ if self.offline or not allow_network:
+ if not cached_manifest.is_file():
+ self._install_reason = self._reason("manifest_unavailable_offline")
+ return None
+ try:
+ payload = cached_manifest.read_bytes()
+ except OSError:
+ self._install_reason = self._reason("manifest_unavailable_offline")
+ return None
+ loaded_from = f"cache:{self.manifest_url}"
+ else:
+ parsed_url = urllib.parse.urlparse(self.manifest_url)
+ if parsed_url.scheme not in {"https", "file"}:
+ self._install_reason = self._reason("manifest_url_unsupported")
+ return None
+ try:
+ with urllib.request.urlopen(self.manifest_url, timeout=30) as response:
+ payload = response.read()
+ except Exception: # noqa: BLE001
+ logger.exception("Failed to download %s manifest", self.spec.runtime_id)
+ self._install_reason = self._reason("manifest_download_failed")
+ return None
+ loaded_from = self.manifest_url
+ cache_remote = True
+ else:
+ try:
+ resource = package_resources.files(self.spec.package).joinpath(self.spec.manifest_resource)
+ except Exception: # noqa: BLE001
+ resource = None
+ if resource is None or not resource.is_file():
+ self._install_reason = self._reason("manifest_missing")
+ return None
+ try:
+ payload = resource.read_bytes()
+ except OSError:
+ self._install_reason = self._reason("manifest_missing")
+ return None
+ loaded_from = f"package:{self.spec.manifest_resource}"
+
+ manifest = self._parse_manifest(payload, loaded_from=loaded_from)
+ if manifest is None:
+ return None
+ if cache_remote:
+ cached_manifest = self._remote_manifest_cache_path()
+ try:
+ write_bytes_atomic(cached_manifest, payload)
+ except OSError:
+ logger.warning("Failed to cache %s manifest", self.spec.runtime_id, exc_info=True)
+ return manifest
+
+ def _remote_manifest_cache_path(self) -> Path:
+ url_digest = hashlib.sha256(str(self.manifest_url).encode("utf-8")).hexdigest()[:16]
+ return self.runtime_dir / "downloads" / f"manifest-{url_digest}.json"
+
+ def _parse_manifest(self, payload: bytes, *, loaded_from: str) -> ManagedRuntimeManifest | None:
+ try:
+ data = json.loads(payload.decode("utf-8"))
+ if not isinstance(data, dict):
+ raise ValueError("manifest root must be an object")
+ archives: dict[str, ManagedRuntimeArchive] = {}
+ for platform_tag, item in (data.get("archives") or {}).items():
+ if not isinstance(platform_tag, str) or not isinstance(item, dict):
+ raise ValueError("invalid archive entry")
+ name = str(item["name"])
+ url = str(item["url"])
+ sha256 = str(item["sha256"]).lower()
+ binary_sha256 = str(item["binary_sha256"]).lower()
+ bin_path = str(item.get("bin_path") or self.spec.default_bin_path)
+ size = int(item["size"]) if item.get("size") is not None else None
+ if Path(name).name != name or not name:
+ raise ValueError("unsafe archive name")
+ if not _SHA256_RE.fullmatch(sha256):
+ raise ValueError("invalid archive sha256")
+ if not _SHA256_RE.fullmatch(binary_sha256):
+ raise ValueError("invalid binary sha256")
+ if size is not None and size < 0:
+ raise ValueError("invalid archive size")
+ if archive_path_is_unsafe(bin_path):
+ raise ValueError("unsafe binary path")
+ archives[platform_tag] = ManagedRuntimeArchive(
+ platform=platform_tag,
+ name=name,
+ url=url,
+ sha256=sha256,
+ binary_sha256=binary_sha256,
+ size=size,
+ bin_path=bin_path,
+ )
+ manifest = ManagedRuntimeManifest(
+ schema_version=int(data.get("schema_version")),
+ runtime_version=str(data.get(self.spec.version_field) or ""),
+ source=str(data.get("source") or ""),
+ source_url=str(data.get("source_url") or "") or None,
+ archives=archives,
+ digest=hashlib.sha256(payload).hexdigest(),
+ loaded_from=loaded_from,
+ payload=data,
+ )
+ except Exception: # noqa: BLE001
+ self._install_reason = self._reason("manifest_invalid")
+ return None
+ if manifest.schema_version != 1 or not manifest.runtime_version or not manifest.archives:
+ self._install_reason = self._reason("manifest_invalid")
+ return None
+ self._install_reason = None
+ return manifest
+
+ def _manifest_archive_for_platform(
+ self,
+ manifest: ManagedRuntimeManifest,
+ ) -> ManagedRuntimeArchive | None:
+ archive = manifest.archives.get(runtime_platform_tag())
+ if archive is None:
+ self._install_reason = self._reason("platform_unsupported")
+ return archive
+
+ def _resolve_manifest_archive(self, archive: ManagedRuntimeArchive) -> Path | None:
+ cached = self.runtime_dir / "downloads" / archive.name
+ if cached.is_file() and self._downloaded_archive_matches(cached, archive):
+ return cached
+ if self.offline:
+ self._install_reason = self._reason("archive_unavailable_offline")
+ return None
+
+ parsed = urllib.parse.urlparse(archive.url)
+ if parsed.scheme not in {"https", "file"}:
+ self._install_reason = self._reason("archive_url_unsupported")
+ return None
+ cached.parent.mkdir(parents=True, exist_ok=True)
+ temporary = cached.with_suffix(cached.suffix + ".tmp")
+ try:
+ with urllib.request.urlopen(archive.url, timeout=60) as response, temporary.open("wb") as destination:
+ shutil.copyfileobj(response, destination)
+ if not self._downloaded_archive_matches(temporary, archive):
+ temporary.unlink(missing_ok=True)
+ return None
+ temporary.replace(cached)
+ self._install_reason = None
+ return cached
+ except Exception: # noqa: BLE001
+ logger.exception("Failed to download %s archive", self.spec.runtime_id)
+ temporary.unlink(missing_ok=True)
+ self._install_reason = self._reason("archive_download_failed")
+ return None
+
+ def _downloaded_archive_matches(self, path: Path, archive: ManagedRuntimeArchive) -> bool:
+ if archive.size is not None and path.stat().st_size != archive.size:
+ self._install_reason = self._reason("archive_size_mismatch")
+ return False
+ if file_sha256(path) != archive.sha256:
+ self._install_reason = self._reason("archive_checksum_mismatch")
+ return False
+ return True
+
+ def _manifest_install_dir(
+ self,
+ manifest: ManagedRuntimeManifest,
+ archive: ManagedRuntimeArchive,
+ ) -> Path:
+ fingerprint = hashlib.sha256(f"{manifest.digest}:{archive.sha256}".encode()).hexdigest()[:16]
+ return (
+ self.runtime_dir
+ / "versions"
+ / safe_path_part(manifest.runtime_version)
+ / safe_path_part(archive.platform)
+ / fingerprint
+ )
+
+ def _verified_manifest_binary(
+ self,
+ install_dir: Path,
+ manifest: ManagedRuntimeManifest,
+ archive: ManagedRuntimeArchive,
+ ) -> Path | None:
+ binary = install_dir / archive.bin_path
+ if not binary.is_file() or not os.access(binary, os.X_OK):
+ return None
+ try:
+ metadata = json.loads((install_dir / self.spec.metadata_filename).read_text(encoding="utf-8"))
+ except Exception: # noqa: BLE001
+ return None
+ if not (
+ metadata.get("provider") == "manifest"
+ and metadata.get("runtime_id") == self.spec.runtime_id
+ and metadata.get("manifest_sha256") == manifest.digest
+ and metadata.get("runtime_version") == manifest.runtime_version
+ and metadata.get("platform") == archive.platform
+ and metadata.get("archive_sha256") == archive.sha256
+ and metadata.get("bin_path") == archive.bin_path
+ and metadata.get("binary_sha256") == archive.binary_sha256
+ and file_sha256(binary) == archive.binary_sha256
+ ):
+ return None
+ return binary
+
+ def _write_manifest_install_metadata(
+ self,
+ install_dir: Path,
+ manifest: ManagedRuntimeManifest,
+ archive: ManagedRuntimeArchive,
+ *,
+ binary_sha256: str,
+ ) -> None:
+ write_json_atomic(
+ install_dir / self.spec.metadata_filename,
+ {
+ "provider": "manifest",
+ "runtime_id": self.spec.runtime_id,
+ "manifest_sha256": manifest.digest,
+ "runtime_version": manifest.runtime_version,
+ "platform": archive.platform,
+ "archive_name": archive.name,
+ "archive_sha256": archive.sha256,
+ "binary_sha256": binary_sha256,
+ "bin_path": archive.bin_path,
+ "manifest_source": manifest.loaded_from,
+ "source": manifest.source,
+ },
+ )
+
+ def _write_current_pointer(
+ self,
+ install_dir: Path,
+ manifest: ManagedRuntimeManifest,
+ archive: ManagedRuntimeArchive,
+ ) -> None:
+ write_json_atomic(
+ self.runtime_dir / "current.json",
+ {
+ "provider": "manifest",
+ "runtime_id": self.spec.runtime_id,
+ "runtime_version": manifest.runtime_version,
+ "platform": archive.platform,
+ "install_dir": str(install_dir),
+ "manifest_sha256": manifest.digest,
+ "archive_sha256": archive.sha256,
+ "bin_path": archive.bin_path,
+ },
+ )
+
+ def _current_install_dir(self, versions_dir: Path) -> Path | None:
+ try:
+ pointer = json.loads((self.runtime_dir / "current.json").read_text(encoding="utf-8"))
+ candidate = Path(str(pointer.get("install_dir") or "")).resolve()
+ if versions_dir.resolve() in candidate.parents:
+ return candidate
+ except Exception: # noqa: BLE001
+ return None
+ return None
+
+ def _prune_empty_version_dirs(self, versions_dir: Path) -> None:
+ for depth in (3, 2, 1):
+ for path in sorted(versions_dir.glob("/".join("*" for _ in range(depth))), reverse=True):
+ if path.is_dir() and not any(path.iterdir()):
+ path.rmdir()
+
+ def _manifest_status_payload(self, manifest: ManagedRuntimeManifest | None) -> dict[str, Any] | None:
+ if manifest is None:
+ return None
+ return {
+ "schema_version": manifest.schema_version,
+ self.spec.version_field: manifest.runtime_version,
+ "source": manifest.source,
+ "source_url": manifest.source_url,
+ "sha256": manifest.digest,
+ "loaded_from": manifest.loaded_from,
+ "release_state": manifest.payload.get("release_state"),
+ }
+
+ @staticmethod
+ def _archive_status_payload(archive: ManagedRuntimeArchive | None) -> dict[str, Any] | None:
+ if archive is None:
+ return None
+ return {
+ "platform": archive.platform,
+ "name": archive.name,
+ "url": archive.url,
+ "sha256": archive.sha256,
+ "binary_sha256": archive.binary_sha256,
+ "size": archive.size,
+ "bin_path": archive.bin_path,
+ }
+
+ def _reuse_existing_install(
+ self,
+ binary: Path,
+ install_dir: Path,
+ manifest: ManagedRuntimeManifest,
+ archive: ManagedRuntimeArchive,
+ *,
+ reason: str | None = None,
+ ) -> dict[str, Any]:
+ try:
+ self._write_current_pointer(install_dir, manifest, archive)
+ except Exception as exc: # noqa: BLE001
+ logger.exception("Failed to refresh managed %s runtime pointer", self.spec.runtime_id)
+ return self._failure(
+ self._reason("pointer_write_failed"),
+ manifest=manifest,
+ archive=archive,
+ message=str(exc),
+ )
+ payload = self._success_payload(binary, install_dir, manifest, archive, changed=False)
+ if reason:
+ payload["reason"] = reason
+ return payload
+
+ def _success_payload(
+ self,
+ binary: Path,
+ install_dir: Path,
+ manifest: ManagedRuntimeManifest,
+ archive: ManagedRuntimeArchive,
+ *,
+ changed: bool,
+ ) -> dict[str, Any]:
+ return {
+ "ok": True,
+ "installed": True,
+ "changed": changed,
+ "path": str(binary),
+ "version": manifest.runtime_version,
+ "platform": archive.platform,
+ "install_dir": str(install_dir),
+ }
+
+ def _failure(
+ self,
+ reason: str,
+ *,
+ manifest: ManagedRuntimeManifest | None = None,
+ archive: ManagedRuntimeArchive | None = None,
+ message: str | None = None,
+ skipped: bool = False,
+ ) -> dict[str, Any]:
+ self._install_reason = reason
+ return {
+ "ok": False,
+ "installed": False,
+ "changed": False,
+ "skipped": skipped,
+ "reason": reason,
+ "message": message or reason,
+ "version": manifest.runtime_version if manifest else None,
+ "platform": archive.platform if archive else runtime_platform_tag(),
+ "path": None,
+ }
+
+ def _reason(self, suffix: str) -> str:
+ return f"{self.spec.runtime_id}_{suffix}"
+
+ def _acquire_mutation_lock(self) -> MigrationFileLock | None:
+ if not self._install_lock.acquire(blocking=False):
+ return None
+ try:
+ file_lock = MigrationFileLock(self._install_file_lock_path, timeout_seconds=0)
+ file_lock.acquire()
+ except MigrationLockTimeout:
+ self._install_lock.release()
+ return None
+ except Exception:
+ self._install_lock.release()
+ raise
+ return file_lock
+
+ def _release_mutation_lock(self, file_lock: MigrationFileLock) -> None:
+ try:
+ file_lock.release()
+ finally:
+ self._install_lock.release()
+
+
+def runtime_platform_tag() -> str:
+ raw = get_platform().lower()
+ machine = raw.rsplit("-", 1)[-1]
+ if machine == "universal2":
+ machine = platform.machine().lower()
+ if machine in {"amd64", "x86_64"}:
+ arch = "x64"
+ elif machine in {"arm64", "aarch64"}:
+ arch = "arm64"
+ else:
+ arch = machine
+ if raw.startswith("macosx"):
+ os_name = "darwin"
+ elif raw.startswith("linux"):
+ os_name = "linux"
+ elif raw.startswith("win"):
+ os_name = "win32"
+ else:
+ os_name = os.name
+ return f"{os_name}-{arch}"
+
+
+def install_lock_for(runtime_id: str) -> threading.Lock:
+ with _INSTALL_LOCKS_GUARD:
+ return _INSTALL_LOCKS.setdefault(runtime_id, threading.Lock())
+
+
+def safe_extract_tar(archive: tarfile.TarFile, destination: Path) -> None:
+ destination_resolved = destination.resolve()
+ for member in archive.getmembers():
+ if not (member.isfile() or member.isdir()):
+ raise ValueError(f"Unsupported managed runtime archive member: {member.name}")
+ if archive_path_is_unsafe(member.name):
+ raise ValueError(f"Unsafe managed runtime archive path: {member.name}")
+ target = (destination / member.name).resolve()
+ if target != destination_resolved and destination_resolved not in target.parents:
+ raise ValueError(f"Unsafe managed runtime archive path: {member.name}")
+ if sys.version_info >= (3, 12):
+ archive.extractall(destination, filter="data")
+ else:
+ archive.extractall(destination)
+
+
+def archive_path_is_unsafe(value: str) -> bool:
+ if not value:
+ return True
+ posix_path = PurePosixPath(value)
+ windows_path = PureWindowsPath(value)
+ if posix_path.is_absolute() or windows_path.is_absolute():
+ return True
+ if windows_path.drive or windows_path.root:
+ return True
+ return ".." in posix_path.parts or ".." in windows_path.parts
+
+
+def file_sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def make_executable(path: Path) -> None:
+ path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
+
+
+def safe_path_part(value: str) -> str:
+ cleaned = "".join(ch if ch.isalnum() or ch in {"-", "_", "."} else "-" for ch in value.strip())
+ return cleaned.strip(".-") or "unknown"
+
+
+def env_flag_enabled(name: str, *, default: bool = False) -> bool:
+ value = os.environ.get(name)
+ if value is None:
+ return default
+ return value.strip().lower() in {"1", "true", "yes", "on"}
+
+
+def write_bytes_atomic(path: Path, payload: bytes) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = path.with_suffix(path.suffix + ".tmp")
+ temporary.write_bytes(payload)
+ temporary.replace(path)
+
+
+def write_json_atomic(path: Path, payload: dict[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = path.with_suffix(path.suffix + ".tmp")
+ temporary.write_text(json.dumps(payload, sort_keys=True) + "\n", encoding="utf-8")
+ temporary.replace(path)
diff --git a/docs/plans/git-runtime.md b/docs/plans/git-runtime.md
new file mode 100644
index 000000000..ca6fde7eb
--- /dev/null
+++ b/docs/plans/git-runtime.md
@@ -0,0 +1,65 @@
+# Vendored Git Runtime
+
+## Background
+
+Show Page checkpointing needs native Git on machines that may not have a safe
+system installation. macOS `/usr/bin/git` is also a Command Line Tools shim and
+must not be executed before `xcode-select -p` confirms the tools are installed.
+
+## Design
+
+- Add a reusable managed-runtime core for manifest loading, archive download,
+ archive and binary SHA-256 verification, safe extraction, versioned
+ installation, cross-process mutation locking, and cleanup.
+- Keep tmux and Show Runtime unchanged in this PR; Git is the first consumer of
+ the extracted core, which limits migration risk while establishing the common
+ boundary for a follow-up.
+- Install Git under
+ `~/.avibe/runtime/git/versions/<version>/<platform>/<fingerprint>/bin/git`.
+- Resolve an installed binary against the immutable binary hash in the active
+ manifest without network access or execution. Status classifies system Git
+ paths without executing PATH-selected binaries and reports both the platform
+ resolution (vendored first) and planned Agent resolution (system first).
+- Support `VIBE_GIT_MANIFEST_PATH`, `VIBE_GIT_MANIFEST_URL`, and
+ `VIBE_GIT_OFFLINE` for development, out-of-band updates, and offline use.
+- Keep Agent PATH injection out of this PR. The current caller-context object
+ is provenance, not the backend's final environment, and probing an untrusted
+ target PATH would execute workspace-controlled tools. The orchestrator-owned
+ post-#864 integration will define and wire the backend environment contract.
+
+## Build Boundary
+
+The workflow verifies the SHA-256-pinned upstream Git 2.55.0 tarball, then
+builds one stripped multicall binary per supported platform. Linux uses musl
+static linking; macOS links only Apple system libraries. Build flags remove
+curl, expat, gettext, Perl, Python, Tcl/Tk, OpenSSL, and Rust surfaces.
+
+The pinned source is additionally constrained so remote-capable commands and
+all non-Git child processes fail closed. Signing, pagers, fsmonitor helpers,
+external diff/textconv, external Git subcommands, shell aliases, hooks, and
+configured content filters are disabled or ignored so the retained operations
+stay deterministic. The workflow exercises `init`, `add`, `commit`, `status`,
+`log`, `diff`, `restore`, and `gc`; proves hostile helper markers do not run;
+and proves that `push` is rejected.
+
+## Publication Gate
+
+The packaged manifest remains `release_state: pending` with zero placeholders
+until the orchestrator runs the workflow with tag `git-runtime-v2.55.0-1`.
+Pending manifests never download or install. The published workflow artifact
+must replace `vibe/git_runtime_manifest.json` so real archive sizes plus archive
+and binary SHA-256 digests ship in the final integration commit.
+
+Offline resolution deliberately fails closed across manifest version changes:
+an install is reusable only when it matches the active trusted manifest. Avibe
+does not trust mutable local metadata as a cross-version fallback root; a
+multi-version manifest schema can be added later if real usage justifies it.
+
+## Deferred Work
+
+- Migrate tmux and Show Runtime to the common managed-runtime core in a separate
+ change after this interface has production evidence.
+- Wire `core/git_binary.py` to `GitRuntimeManager` in the orchestrator-owned
+ post-merge integration for #669.
+- Define and wire safe Agent PATH fallback after #864 at the concrete backend
+ child-environment seam.
diff --git a/pyproject.toml b/pyproject.toml
index 9b23cda81..30a67bc34 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -92,7 +92,12 @@ version-file = "vibe/_version.py"
[tool.hatch.build]
# Include generated assets even though they are in .gitignore (build artifacts)
-artifacts = ["ui/dist/**", "vibe/show_runtime_manifest.json", "vibe/tmux_runtime_manifest.json"]
+artifacts = [
+ "ui/dist/**",
+ "vibe/show_runtime_manifest.json",
+ "vibe/tmux_runtime_manifest.json",
+ "vibe/git_runtime_manifest.json",
+]
[tool.hatch.build.targets.wheel]
packages = ["vibe", "config", "core", "modules", "storage"]
@@ -113,6 +118,7 @@ include = [
"ui/dist/**",
"vibe/show_runtime_manifest.json",
"vibe/tmux_runtime_manifest.json",
+ "vibe/git_runtime_manifest.json",
"README.md",
"LICENSE",
]
diff --git a/tests/test_caller_context.py b/tests/test_caller_context.py
index 52f452403..71689a405 100644
--- a/tests/test_caller_context.py
+++ b/tests/test_caller_context.py
@@ -34,7 +34,9 @@ def test_caller_context_from_env_round_trips_metadata_and_env() -> None:
"backend": "codex",
"native_session_id": "thread789",
}
- assert context.to_env()[AVIBE_SESSION_ID_ENV] == "ses123"
+ caller_env = context.to_env()
+ assert caller_env[AVIBE_SESSION_ID_ENV] == "ses123"
+ assert "PATH" not in caller_env
def test_caller_context_from_platform_payload_prefers_agent_session_target() -> None:
diff --git a/tests/test_git_runtime.py b/tests/test_git_runtime.py
new file mode 100644
index 000000000..525d32900
--- /dev/null
+++ b/tests/test_git_runtime.py
@@ -0,0 +1,524 @@
+from __future__ import annotations
+
+import hashlib
+import io
+import json
+import os
+import stat
+import tarfile
+from pathlib import Path
+
+import pytest
+
+from core import git_runtime, managed_runtime
+from core.git_runtime import GitRuntimeManager
+from storage.lock import MigrationFileLock
+
+
+def _write_git_archive(tmp_path: Path, *, version: str = "2.55.0") -> Path:
+ root = tmp_path / "archive-root" / "bin"
+ root.mkdir(parents=True)
+ binary = root / "git"
+ binary.write_text(
+ f"#!/bin/sh\n[ \"$1\" = \"--version\" ] || exit 2\necho git version {version}\n",
+ encoding="utf-8",
+ )
+ binary.chmod(binary.stat().st_mode | stat.S_IXUSR)
+ archive = tmp_path / "git-test.tar.gz"
+ with tarfile.open(archive, "w:gz") as tar:
+ tar.add(binary, arcname="bin/git")
+ return archive
+
+
+def _write_manifest(
+ tmp_path: Path,
+ archive: Path,
+ *,
+ sha256: str | None = None,
+ binary_sha256: str | None = None,
+ release_state: str = "published",
+ version: str = "2.55.0",
+) -> Path:
+ if binary_sha256 is None:
+ with tarfile.open(archive, "r:gz") as tar:
+ binary = tar.extractfile("bin/git")
+ if binary is None:
+ raise ValueError("test archive is missing bin/git")
+ binary_sha256 = hashlib.sha256(binary.read()).hexdigest()
+ manifest = {
+ "schema_version": 1,
+ "git_version": version,
+ "source": "test",
+ "source_url": "file://test",
+ "release_state": release_state,
+ "archives": {
+ managed_runtime.runtime_platform_tag(): {
+ "name": archive.name,
+ "url": archive.as_uri(),
+ "sha256": sha256 or hashlib.sha256(archive.read_bytes()).hexdigest(),
+ "binary_sha256": binary_sha256,
+ "size": archive.stat().st_size,
+ "bin_path": "bin/git",
+ }
+ },
+ }
+ path = tmp_path / "git_runtime_manifest.json"
+ path.write_text(json.dumps(manifest), encoding="utf-8")
+ return path
+
+
+def test_manifest_parses_and_exposes_archive(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ archive = _write_git_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive)
+
+ status = GitRuntimeManager(manifest_path=manifest).status()
+
+ assert status["version"] == "2.55.0"
+ assert status["manifest"]["git_version"] == "2.55.0"
+ assert status["archive"]["sha256"] == hashlib.sha256(archive.read_bytes()).hexdigest()
+ assert status["archive"]["binary_sha256"] == json.loads(manifest.read_text(encoding="utf-8"))[
+ "archives"
+ ][managed_runtime.runtime_platform_tag()]["binary_sha256"]
+
+
+def test_manifest_requires_pinned_binary_sha256(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ archive = _write_git_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive)
+ payload = json.loads(manifest.read_text(encoding="utf-8"))
+ del payload["archives"][managed_runtime.runtime_platform_tag()]["binary_sha256"]
+ manifest.write_text(json.dumps(payload), encoding="utf-8")
+
+ status = GitRuntimeManager(manifest_path=manifest).status()
+
+ assert status["installed"] is False
+ assert status["manifest"] is None
+ assert status["reason"] == "git_manifest_invalid"
+
+
+def test_install_verifies_archive_and_uses_versioned_layout(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ home = tmp_path / "home"
+ monkeypatch.setenv("AVIBE_HOME", str(home))
+ archive = _write_git_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive)
+ manager = GitRuntimeManager(manifest_path=manifest)
+
+ result = manager.ensure()
+
+ assert result["ok"] is True
+ installed = Path(result["path"])
+ relative = installed.relative_to(home / "runtime" / "git")
+ assert relative.parts[:3] == (
+ "versions",
+ "2.55.0",
+ managed_runtime.runtime_platform_tag(),
+ )
+ assert len(relative.parts[3]) == 16
+ assert relative.parts[4:] == ("bin", "git")
+ assert manager.resolve_git_path() == installed
+
+
[email protected]("pointer_payload", [None, "not-json"])
+def test_reusing_install_repairs_current_pointer_before_clean(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ pointer_payload: str | None,
+) -> None:
+ home = tmp_path / "home"
+ monkeypatch.setenv("AVIBE_HOME", str(home))
+ archive = _write_git_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive)
+ manager = GitRuntimeManager(manifest_path=manifest)
+ first = manager.ensure()
+ assert first["ok"] is True
+ pointer = home / "runtime" / "git" / "current.json"
+ if pointer_payload is None:
+ pointer.unlink()
+ else:
+ pointer.write_text(pointer_payload, encoding="utf-8")
+
+ reused = manager.ensure()
+ cleaned = manager.clean(keep_previous=0)
+
+ assert reused["ok"] is True
+ assert reused["changed"] is False
+ assert json.loads(pointer.read_text(encoding="utf-8"))["install_dir"] == first["install_dir"]
+ assert first["install_dir"] not in cleaned["removed"]
+ assert Path(first["path"]).is_file()
+
+
+def test_managers_for_same_runtime_share_install_lock(tmp_path: Path) -> None:
+ first = GitRuntimeManager(runtime_dir=tmp_path / "first")
+ second = GitRuntimeManager(runtime_dir=tmp_path / "second")
+
+ assert first._install_lock is second._install_lock
+
+
+def test_install_and_clean_refuse_runtime_file_lock_held_elsewhere(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ archive = _write_git_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive)
+ manager = GitRuntimeManager(manifest_path=manifest)
+ external_lock = MigrationFileLock(manager._install_file_lock_path)
+ external_lock.acquire()
+ try:
+ install_result = manager.ensure()
+ clean_result = manager.clean()
+ finally:
+ external_lock.release()
+
+ assert install_result["ok"] is False
+ assert install_result["reason"] == "git_install_already_running"
+ assert install_result["skipped"] is True
+ assert clean_result == {
+ "ok": False,
+ "removed": [],
+ "reason": "git_install_already_running",
+ }
+
+
+def test_checksum_mismatch_installs_nothing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ archive = _write_git_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive, sha256="1" * 64)
+ manager = GitRuntimeManager(manifest_path=manifest)
+
+ result = manager.ensure()
+
+ assert result["ok"] is False
+ assert result["reason"] == "git_archive_checksum_mismatch"
+ assert manager.resolve_git_path() is None
+
+
+def test_binary_checksum_mismatch_installs_nothing(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ archive = _write_git_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive, binary_sha256="1" * 64)
+ manager = GitRuntimeManager(manifest_path=manifest)
+
+ result = manager.ensure()
+
+ assert result["ok"] is False
+ assert result["reason"] == "git_binary_checksum_mismatch"
+ assert manager.resolve_git_path() is None
+
+
+def test_install_rejects_archive_path_traversal(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ home = tmp_path / "home"
+ monkeypatch.setenv("AVIBE_HOME", str(home))
+ archive = tmp_path / "git-test.tar.gz"
+ payload = b"escape"
+ with tarfile.open(archive, "w:gz") as tar:
+ member = tarfile.TarInfo("../escaped")
+ member.size = len(payload)
+ tar.addfile(member, io.BytesIO(payload))
+ manifest = _write_manifest(tmp_path, archive, binary_sha256="0" * 64)
+
+ result = GitRuntimeManager(manifest_path=manifest).ensure()
+
+ assert result["ok"] is False
+ assert result["reason"] == "git_install_failed"
+ assert not (home / "runtime" / "git" / "escaped").exists()
+
+
+def test_resolve_rejects_tampered_installed_binary(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ archive = _write_git_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive)
+ manager = GitRuntimeManager(manifest_path=manifest)
+ result = manager.ensure()
+ assert result["ok"] is True
+ installed = Path(result["path"])
+
+ installed.write_text(installed.read_text(encoding="utf-8") + "# tampered\n", encoding="utf-8")
+ metadata_path = Path(result["install_dir"]) / manager.spec.metadata_filename
+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
+ metadata["binary_sha256"] = hashlib.sha256(installed.read_bytes()).hexdigest()
+ metadata_path.write_text(json.dumps(metadata), encoding="utf-8")
+
+ assert manager.resolve_git_path() is None
+
+
+def test_clean_preserves_current_install_and_removes_stale_version(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ archive = _write_git_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive)
+ manager = GitRuntimeManager(manifest_path=manifest)
+ first = manager.ensure()
+ assert first["ok"] is True
+
+ payload = json.loads(manifest.read_text(encoding="utf-8"))
+ payload["build_revision"] = 2
+ manifest.write_text(json.dumps(payload), encoding="utf-8")
+ second = manager.ensure()
+ assert second["ok"] is True
+ assert second["install_dir"] != first["install_dir"]
+
+ cleaned = manager.clean(keep_previous=0)
+
+ assert first["install_dir"] in cleaned["removed"]
+ assert Path(second["path"]).is_file()
+
+
+def test_offline_install_does_not_open_archive_url(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ archive = _write_git_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive)
+ monkeypatch.setattr(
+ managed_runtime.urllib.request,
+ "urlopen",
+ lambda *args, **kwargs: pytest.fail("offline install attempted I/O"),
+ )
+
+ result = GitRuntimeManager(manifest_path=manifest, offline=True).ensure()
+
+ assert result["ok"] is False
+ assert result["reason"] == "git_archive_unavailable_offline"
+
+
+def test_offline_environment_flag_is_honored(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("VIBE_GIT_OFFLINE", "1")
+
+ assert GitRuntimeManager().offline is True
+
+
+def test_offline_manifest_upgrade_fails_closed_instead_of_trusting_previous_install(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ home = tmp_path / "home"
+ monkeypatch.setenv("AVIBE_HOME", str(home))
+ first_archive = _write_git_archive(tmp_path / "first", version="2.55.0")
+ first_manifest = _write_manifest(tmp_path / "first", first_archive, version="2.55.0")
+ first = GitRuntimeManager(manifest_path=first_manifest).ensure()
+ assert first["ok"] is True
+
+ next_archive = _write_git_archive(tmp_path / "next", version="2.56.0")
+ next_manifest = _write_manifest(tmp_path / "next", next_archive, version="2.56.0")
+ upgraded = GitRuntimeManager(manifest_path=next_manifest, offline=True)
+
+ assert upgraded.resolve_git_path() is None
+ result = upgraded.ensure()
+ assert result["ok"] is False
+ assert result["reason"] == "git_archive_unavailable_offline"
+ assert Path(first["path"]).is_file()
+
+
+def test_resolve_missing_runtime_never_fetches_remote_manifest(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ monkeypatch.setattr(
+ managed_runtime.urllib.request,
+ "urlopen",
+ lambda *args, **kwargs: pytest.fail("resolve attempted network access"),
+ )
+ manager = GitRuntimeManager(manifest_url="https://example.invalid/git-manifest.json")
+
+ assert manager.resolve_git_path() is None
+
+
+def test_pending_manifest_fails_closed_before_download(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ archive = _write_git_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive, release_state="pending")
+ monkeypatch.setattr(
+ managed_runtime.urllib.request,
+ "urlopen",
+ lambda *args, **kwargs: pytest.fail("pending manifest attempted archive download"),
+ )
+
+ result = GitRuntimeManager(manifest_path=manifest).ensure()
+
+ assert result["ok"] is False
+ assert result["reason"] == "git_runtime_unpublished"
+
+
+def test_status_reports_platform_and_agent_resolution_orders(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ vendored = tmp_path / "runtime" / "bin" / "git"
+ system = tmp_path / "system" / "bin" / "git"
+
+ class FakeManager:
+ def resolve_git_path(self) -> Path:
+ return vendored
+
+ def status(self) -> dict[str, object]:
+ return {"installed": True, "path": str(vendored), "version": "vendored-version"}
+
+ monkeypatch.setattr(git_runtime, "get_git_runtime_manager", lambda: FakeManager())
+ monkeypatch.setattr(git_runtime, "resolve_system_git_path", lambda: system)
+ monkeypatch.setattr(git_runtime, "_probe_git_version", lambda path: pytest.fail("status executed Git"))
+
+ status = git_runtime.git_runtime_status()
+
+ assert status["resolution"] == "vendored"
+ assert status["path"] == str(vendored)
+ assert status["version"] == "vendored-version"
+ assert status["agent"] == {
+ "resolution": "system",
+ "path": str(system),
+ "version": None,
+ }
+
+
+def test_macos_system_git_checks_clt_before_executing_git(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[list[str]] = []
+ monkeypatch.setattr(git_runtime.platform, "system", lambda: "Darwin")
+ monkeypatch.setattr(
+ git_runtime.shutil,
+ "which",
+ lambda name, path=None: "/usr/bin/git"
+ if name == "git"
+ else pytest.fail("unexpected PATH lookup for a support tool"),
+ )
+
+ class MissingCLT:
+ returncode = 2
+ stdout = ""
+ stderr = "missing"
+
+ def fake_run(argv, **kwargs):
+ calls.append(argv)
+ return MissingCLT()
+
+ monkeypatch.setattr(git_runtime.subprocess, "run", fake_run)
+
+ assert git_runtime.resolve_system_git_path(env={"PATH": "/usr/bin"}) is None
+ assert calls == [["/usr/bin/xcode-select", "-p"]]
+
+
+def test_system_git_explicit_env_never_falls_back_to_parent_path(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("PATH", "/parent/process/bin")
+ monkeypatch.setattr(
+ git_runtime.shutil,
+ "which",
+ lambda *args, **kwargs: pytest.fail("explicit empty env must not search parent PATH"),
+ )
+
+ assert git_runtime.resolve_system_git_path(env={}) is None
+ assert git_runtime.resolve_system_git_path(env={"PATH": ""}) is None
+
+
+def test_macos_system_git_is_available_after_clt_check(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[list[str]] = []
+ monkeypatch.setattr(git_runtime.platform, "system", lambda: "Darwin")
+ monkeypatch.setattr(
+ git_runtime.shutil,
+ "which",
+ lambda name, path=None: "/usr/bin/git"
+ if name == "git"
+ else pytest.fail("unexpected PATH lookup for a support tool"),
+ )
+
+ def fake_run(argv, **kwargs):
+ calls.append(argv)
+
+ class Result:
+ returncode = 0
+ stdout = (
+ "/Library/Developer/CommandLineTools\n"
+ if argv[-1] == "-p"
+ else "git version 2.55.0\n"
+ )
+ stderr = ""
+
+ return Result()
+
+ monkeypatch.setattr(git_runtime.subprocess, "run", fake_run)
+
+ assert git_runtime.resolve_system_git_path(env={"PATH": "/usr/bin"}) == Path("/usr/bin/git")
+ assert calls == [["/usr/bin/xcode-select", "-p"]]
+
+
+def test_macos_system_git_ignores_decoy_xcode_select(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ decoy = tmp_path / "xcode-select"
+ marker = tmp_path / "decoy-ran"
+ decoy.write_text(f"#!/bin/sh\ntouch {marker}\n", encoding="utf-8")
+ decoy.chmod(decoy.stat().st_mode | stat.S_IXUSR)
+ target_path = os.pathsep.join([str(tmp_path), "/usr/bin"])
+ lookups: list[tuple[str, str | None]] = []
+ calls: list[list[str]] = []
+
+ monkeypatch.setattr(git_runtime.platform, "system", lambda: "Darwin")
+
+ def fake_which(name, path=None):
+ lookups.append((name, path))
+ if name == "git":
+ return "/usr/bin/git"
+ if name == "xcode-select":
+ return str(decoy)
+ return None
+
+ def fake_run(argv, **kwargs):
+ calls.append(argv)
+ if argv[0] == str(decoy):
+ marker.touch()
+
+ class Result:
+ returncode = 0
+ stdout = (
+ "/Library/Developer/CommandLineTools\n"
+ if argv[-1] == "-p"
+ else "git version 2.55.0\n"
+ )
+ stderr = ""
+
+ return Result()
+
+ monkeypatch.setattr(git_runtime.shutil, "which", fake_which)
+ monkeypatch.setattr(git_runtime.subprocess, "run", fake_run)
+
+ assert git_runtime.resolve_system_git_path(env={"PATH": target_path}) == Path("/usr/bin/git")
+ assert lookups == [("git", target_path)]
+ assert calls == [["/usr/bin/xcode-select", "-p"]]
+ assert not marker.exists()
+
+
+def test_macos_non_system_git_is_classified_without_execution(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[list[str]] = []
+ monkeypatch.setattr(git_runtime.platform, "system", lambda: "Darwin")
+ monkeypatch.setattr(
+ git_runtime.shutil,
+ "which",
+ lambda name, path=None: "/opt/homebrew/bin/git" if name == "git" else pytest.fail("unexpected CLT lookup"),
+ )
+
+ def fake_run(argv, **kwargs):
+ calls.append(argv)
+
+ class Result:
+ returncode = 0
+ stdout = "git version 2.55.0\n"
+ stderr = ""
+
+ return Result()
+
+ monkeypatch.setattr(git_runtime.subprocess, "run", fake_run)
+
+ assert git_runtime.resolve_system_git_path(env={"PATH": "/opt/homebrew/bin"}) == Path(
+ "/opt/homebrew/bin/git"
+ )
+ assert calls == []
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index 4f4f17e95..f353dd6bc 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -16,8 +16,15 @@ class _FakeShowRuntimeResult:
reason: str | None = None
-def _stub_runtime_prepare_dependencies(monkeypatch, *, askill_result=None, avault_result=None, tmux_result=None):
- calls = {"askill": [], "avault": [], "tmux": []}
+def _stub_runtime_prepare_dependencies(
+ monkeypatch,
+ *,
+ askill_result=None,
+ avault_result=None,
+ tmux_result=None,
+ git_result=None,
+):
+ calls = {"askill": [], "avault": [], "tmux": [], "git": []}
def fake_askill(offline=False):
calls["askill"].append({"offline": offline})
@@ -31,9 +38,14 @@ def _stub_runtime_prepare_dependencies(monkeypatch, *, askill_result=None, avaul
calls["tmux"].append({"offline": offline, "force": force})
return tmux_result or {"ok": True, "installed": True}
+ def fake_git(offline=None, force=False):
+ calls["git"].append({"offline": offline, "force": force})
+ return git_result or {"ok": True, "installed": True}
+
monkeypatch.setattr(cli, "_ensure_askill_during_prepare", fake_askill)
monkeypatch.setattr(cli, "_ensure_avault_during_prepare", fake_avault)
monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", fake_tmux)
+ monkeypatch.setattr(cli, "_ensure_git_during_prepare", fake_git)
return calls
@@ -85,7 +97,9 @@ def test_runtime_prepare_cli_reports_warning_only_failure(monkeypatch, capsys):
assert payload["askill"] == {"ok": True, "installed": True}
assert payload["avault"] == {"ok": True, "installed": True}
assert payload["tmux"] == {"ok": True, "installed": True}
+ assert payload["git"] == {"ok": True, "installed": True}
assert calls["tmux"] == [{"offline": False, "force": False}]
+ assert calls["git"] == [{"offline": None, "force": False}]
def test_runtime_prepare_cli_preserves_offline_environment(monkeypatch):
@@ -103,6 +117,7 @@ def test_runtime_prepare_cli_preserves_offline_environment(monkeypatch):
assert cli.cmd_runtime(args) == 0
assert calls["tmux"] == [{"offline": False, "force": False}]
+ assert calls["git"] == [{"offline": None, "force": False}]
def test_runtime_manager_from_args_preserves_offline_environment(monkeypatch, tmp_path):
@@ -116,6 +131,59 @@ def test_runtime_manager_from_args_preserves_offline_environment(monkeypatch, tm
assert manager.offline is True
+def test_runtime_status_reports_effective_git_resolution(monkeypatch, capsys):
+ parser = cli.build_parser()
+ args = parser.parse_args(["runtime", "status", "--json"])
+
+ class FakeRuntimeManager:
+ def status(self):
+ return {"provider": "manifest-cache", "installed": True}
+
+ monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ monkeypatch.setattr(
+ cli,
+ "_git_runtime_status",
+ lambda: {
+ "id": "git",
+ "resolution": "vendored",
+ "path": "/tmp/runtime/git/bin/git",
+ "version": "2.55.0",
+ "agent": {
+ "resolution": "system",
+ "path": "/usr/bin/git",
+ "version": "2.50.1",
+ },
+ },
+ )
+
+ assert cli.cmd_runtime(args) == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["git"]["resolution"] == "vendored"
+ assert payload["git"]["path"].endswith("/bin/git")
+ assert payload["git"]["agent"]["resolution"] == "system"
+
+
+def test_runtime_clean_cleans_git_runtime(monkeypatch, capsys):
+ parser = cli.build_parser()
+ args = parser.parse_args(["runtime", "clean", "--json", "--keep-previous", "2"])
+
+ class FakeRuntimeManager:
+ def clean(self, *, keep_previous=1):
+ assert keep_previous == 2
+ return {"ok": True, "removed": ["show-old"]}
+
+ monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ monkeypatch.setattr(
+ cli,
+ "_clean_git_runtime",
+ lambda *, keep_previous: {"ok": True, "removed": [f"git-old-{keep_previous}"]},
+ )
+
+ assert cli.cmd_runtime(args) == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["git"]["removed"] == ["git-old-2"]
+
+
def test_runtime_prepare_cli_strict_fails_when_prepare_fails(monkeypatch, capsys):
parser = cli.build_parser()
args = parser.parse_args(["runtime", "prepare", "--strict"])
@@ -132,10 +200,64 @@ def test_runtime_prepare_cli_strict_fails_when_prepare_fails(monkeypatch, capsys
assert calls["tmux"] == [{"offline": False, "force": False}]
+def test_runtime_prepare_cli_strict_fails_when_git_prepare_fails(monkeypatch, capsys):
+ parser = cli.build_parser()
+ args = parser.parse_args(["runtime", "prepare", "--strict"])
+
+ class FakeRuntimeManager:
+ def prepare(self, *, force=False, offline=None):
+ return {"ok": True}
+
+ monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ _stub_runtime_prepare_dependencies(
+ monkeypatch,
+ git_result={"ok": False, "reason": "git_archive_checksum_mismatch"},
+ )
+
+ assert cli.cmd_runtime(args) == 1
+ assert "git_archive_checksum_mismatch" in capsys.readouterr().err
+
+
+def test_runtime_prepare_cli_strict_allows_pending_git_publication(monkeypatch, capsys):
+ parser = cli.build_parser()
+ args = parser.parse_args(["runtime", "prepare", "--strict"])
+
+ class FakeRuntimeManager:
+ def prepare(self, *, force=False, offline=None):
+ return {"ok": True}
+
+ monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ _stub_runtime_prepare_dependencies(
+ monkeypatch,
+ git_result={"ok": False, "reason": "git_runtime_unpublished"},
+ )
+
+ assert cli.cmd_runtime(args) == 0
+ assert "git_runtime_unpublished" in capsys.readouterr().err
+
+
+def test_runtime_prepare_cli_strict_allows_unsupported_git_platform(monkeypatch, capsys):
+ parser = cli.build_parser()
+ args = parser.parse_args(["runtime", "prepare", "--strict"])
+
+ class FakeRuntimeManager:
+ def prepare(self, *, force=False, offline=None):
+ return {"ok": True}
+
+ monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ _stub_runtime_prepare_dependencies(
+ monkeypatch,
+ git_result={"ok": False, "reason": "git_platform_unsupported"},
+ )
+
+ assert cli.cmd_runtime(args) == 0
+ assert "git_platform_unsupported" in capsys.readouterr().err
+
+
def test_runtime_prepare_cli_skips_avault_offline(monkeypatch, capsys):
parser = cli.build_parser()
args = parser.parse_args(["runtime", "prepare", "--offline", "--json"])
- seen = {"askill": None, "avault": None, "tmux": None}
+ seen = {"askill": None, "avault": None, "tmux": None, "git": None}
class FakeRuntimeManager:
def prepare(self, *, force=False, offline=None):
@@ -154,16 +276,27 @@ def test_runtime_prepare_cli_skips_avault_offline(monkeypatch, capsys):
seen["tmux"] = {"offline": offline, "force": force}
return {"ok": True, "skipped": True, "reason": "offline"}
+ def fake_git(offline=None, force=False):
+ seen["git"] = {"offline": offline, "force": force}
+ return {"ok": True, "installed": True}
+
monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
monkeypatch.setattr(cli, "_ensure_askill_during_prepare", fake_askill)
monkeypatch.setattr(cli, "_ensure_avault_during_prepare", fake_avault)
monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", fake_tmux)
+ monkeypatch.setattr(cli, "_ensure_git_during_prepare", fake_git)
assert cli.cmd_runtime(args) == 0
payload = json.loads(capsys.readouterr().out)
- assert seen == {"askill": True, "avault": True, "tmux": {"offline": True, "force": False}}
+ assert seen == {
+ "askill": True,
+ "avault": True,
+ "tmux": {"offline": True, "force": False},
+ "git": {"offline": True, "force": False},
+ }
assert payload["avault"] == {"ok": True, "skipped": True, "reason": "offline"}
assert payload["tmux"] == {"ok": True, "skipped": True, "reason": "offline"}
+ assert payload["git"] == {"ok": True, "installed": True}
def test_runtime_prepare_cli_prints_status_skipped_tmux_as_skipped(monkeypatch, capsys):
diff --git a/vibe/cli.py b/vibe/cli.py
index 9c70bdf8a..f206189fa 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -10130,6 +10130,30 @@ def _show_runtime_manager_from_args(args):
)
+def _git_runtime_status() -> dict:
+ try:
+ from core.git_runtime import git_runtime_status
+
+ return git_runtime_status()
+ except Exception as exc: # noqa: BLE001
+ return {
+ "id": "git",
+ "resolution": "none",
+ "path": None,
+ "version": None,
+ "reason": str(exc),
+ }
+
+
+def _git_prepare_satisfies_strict(result: dict) -> bool:
+ if result.get("ok"):
+ return True
+ return result.get("reason") in {
+ "git_platform_unsupported",
+ "git_runtime_unpublished",
+ }
+
+
def _print_runtime_status(payload: dict) -> None:
print("Show Runtime:")
print(f" Provider: {payload.get('provider')}")
@@ -10149,6 +10173,19 @@ def _print_runtime_status(payload: dict) -> None:
print(f" Install dir: {payload.get('install_dir')}")
if payload.get("reason"):
print(f" Reason: {payload.get('reason')}")
+ git = payload.get("git") or {}
+ print("Git Runtime:")
+ print(f" Resolution: {git.get('resolution') or 'none'}")
+ print(f" Version: {git.get('version') or 'unknown'}")
+ if git.get("path"):
+ print(f" Path: {git['path']}")
+ agent_git = git.get("agent") or {}
+ print(f" Agent PATH resolution: {agent_git.get('resolution') or 'none'}")
+ if agent_git.get("path"):
+ print(f" Agent PATH: {agent_git['path']}")
+ managed_git = git.get("managed") or {}
+ if managed_git.get("reason"):
+ print(f" Managed runtime: {managed_git['reason']}")
def cmd_runtime(args) -> int:
@@ -10156,6 +10193,7 @@ def cmd_runtime(args) -> int:
command = getattr(args, "runtime_command", None)
if command == "status":
payload = manager.status()
+ payload["git"] = _git_runtime_status()
if getattr(args, "json", False):
print(json.dumps(payload, indent=2))
else:
@@ -10166,10 +10204,12 @@ def cmd_runtime(args) -> int:
payload = manager.prepare(force=getattr(args, "force", False), offline=offline)
askill = _ensure_askill_during_prepare(offline=bool(offline))
tmux = _ensure_tmux_during_prepare(offline=bool(offline), force=getattr(args, "force", False))
+ git = _ensure_git_during_prepare(offline=offline, force=getattr(args, "force", False))
avault = _ensure_avault_during_prepare(offline=bool(offline))
payload["askill"] = askill
payload["avault"] = avault
payload["tmux"] = tmux
+ payload["git"] = git
if getattr(args, "json", False):
print(json.dumps(payload, indent=2))
else:
@@ -10199,14 +10239,27 @@ def cmd_runtime(args) -> int:
print("tmux installed." if tmux.get("changed") else "tmux ready.")
else:
print(f"tmux not ready: {tmux.get('message') or tmux.get('reason') or 'install failed'}", file=sys.stderr)
- return 1 if getattr(args, "strict", False) and not payload.get("ok") else 0
+ if git.get("skipped"):
+ print(f"git runtime: skipped ({git.get('reason') or 'skipped'}).")
+ elif git.get("ok"):
+ print("git runtime installed." if git.get("changed") else "git runtime ready.")
+ else:
+ print(
+ f"git runtime not ready: {git.get('message') or git.get('reason') or 'install failed'}",
+ file=sys.stderr,
+ )
+ strict_ok = bool(payload.get("ok")) and _git_prepare_satisfies_strict(git)
+ return 1 if getattr(args, "strict", False) and not strict_ok else 0
if command == "clean":
payload = manager.clean(keep_previous=getattr(args, "keep_previous", 1))
+ git = _clean_git_runtime(keep_previous=getattr(args, "keep_previous", 1))
+ payload["git"] = git
if getattr(args, "json", False):
print(json.dumps(payload, indent=2))
else:
removed = payload.get("removed") or []
print(f"Removed {len(removed)} Show Runtime cache item(s).")
+ print(f"Removed {len(git.get('removed') or [])} Git Runtime cache item(s).")
return 0
raise TaskCliError("runtime command is required", code="invalid_arguments", help_command="vibe runtime --help")
@@ -10284,6 +10337,26 @@ def _ensure_tmux_during_prepare(offline: bool = False, force: bool = False) -> d
return {"ok": False, "message": str(exc)}
+def _ensure_git_during_prepare(offline: bool | None = None, force: bool = False) -> dict:
+ """Prepare verified vendored Git without making it a service-start requirement."""
+
+ try:
+ from core.git_runtime import GitRuntimeManager
+
+ return GitRuntimeManager(offline=offline).ensure(force=force)
+ except Exception as exc: # noqa: BLE001
+ return {"ok": False, "message": str(exc)}
+
+
+def _clean_git_runtime(*, keep_previous: int) -> dict:
+ try:
+ from core.git_runtime import get_git_runtime_manager
+
+ return get_git_runtime_manager().clean(keep_previous=keep_previous)
+ except Exception as exc: # noqa: BLE001
+ return {"ok": False, "removed": [], "message": str(exc)}
+
+
def _ensure_avault_during_prepare(offline: bool = False) -> dict:
"""Ensure avault (the Vault custody core) alongside other local deps."""
if offline:
@@ -10395,8 +10468,8 @@ def build_parser():
subparsers.add_parser("upgrade", help="Upgrade to latest version")
runtime_parser = subparsers.add_parser(
"runtime",
- help="Inspect and prepare the managed Show Runtime",
- description="Inspect, prepare, and clean the global Show Runtime cache used by Show Pages.",
+ help="Inspect and prepare managed runtimes",
+ description="Inspect, prepare, and clean the managed runtimes used by Avibe.",
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe runtime --help",
)
@@ -10413,7 +10486,7 @@ def build_parser():
manifest_group.add_argument("--manifest", help="Read a development manifest from a local path.")
manifest_group.add_argument("--manifest-url", help="Read a development manifest from a URL.")
- runtime_status_parser = runtime_subparsers.add_parser("status", help="Show managed Show Runtime status")
+ runtime_status_parser = runtime_subparsers.add_parser("status", help="Show managed runtime status")
add_runtime_provider_args(runtime_status_parser)
runtime_status_parser.add_argument("--offline", action="store_true", help="Do not fetch a remote manifest.")
runtime_status_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")
@@ -10428,7 +10501,7 @@ def build_parser():
runtime_prepare_parser.add_argument("--strict", action="store_true", help="Return a non-zero exit code when preparation fails.")
runtime_prepare_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")
- runtime_clean_parser = runtime_subparsers.add_parser("clean", help="Clean stale Show Runtime cache entries")
+ runtime_clean_parser = runtime_subparsers.add_parser("clean", help="Clean stale managed runtime cache entries")
runtime_clean_parser.add_argument("--keep-previous", type=int, default=1, help="Number of previous runtime versions to keep.")
runtime_clean_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")
remote_parser = subparsers.add_parser(
diff --git a/vibe/git_runtime_manifest.json b/vibe/git_runtime_manifest.json
new file mode 100644
index 000000000..8641a57cf
--- /dev/null
+++ b/vibe/git_runtime_manifest.json
@@ -0,0 +1,44 @@
+{
+ "schema_version": 1,
+ "git_version": "2.55.0",
+ "source": "kernel.org/git",
+ "source_url": "https://www.kernel.org/pub/software/scm/git/git-2.55.0.tar.xz",
+ "source_sha256": "457fdb04dc8728e007d4688695e6912e6f680727920f2a40bf11eacc17505357",
+ "release_tag": "git-runtime-v2.55.0-1",
+ "release_state": "pending",
+ "local_ops_only": true,
+ "archives": {
+ "darwin-arm64": {
+ "name": "git-2.55.0-darwin-arm64.tar.gz",
+ "url": "https://github.com/avibe-bot/avibe/releases/download/git-runtime-v2.55.0-1/git-2.55.0-darwin-arm64.tar.gz",
+ "sha256": "0000000000000000000000000000000000000000000000000000000000000000",
+ "binary_sha256": "0000000000000000000000000000000000000000000000000000000000000000",
+ "size": null,
+ "bin_path": "bin/git"
+ },
+ "darwin-x64": {
+ "name": "git-2.55.0-darwin-x64.tar.gz",
+ "url": "https://github.com/avibe-bot/avibe/releases/download/git-runtime-v2.55.0-1/git-2.55.0-darwin-x64.tar.gz",
+ "sha256": "0000000000000000000000000000000000000000000000000000000000000000",
+ "binary_sha256": "0000000000000000000000000000000000000000000000000000000000000000",
+ "size": null,
+ "bin_path": "bin/git"
+ },
+ "linux-arm64": {
+ "name": "git-2.55.0-linux-arm64.tar.gz",
+ "url": "https://github.com/avibe-bot/avibe/releases/download/git-runtime-v2.55.0-1/git-2.55.0-linux-arm64.tar.gz",
+ "sha256": "0000000000000000000000000000000000000000000000000000000000000000",
+ "binary_sha256": "0000000000000000000000000000000000000000000000000000000000000000",
+ "size": null,
+ "bin_path": "bin/git"
+ },
+ "linux-x64": {
+ "name": "git-2.55.0-linux-x64.tar.gz",
+ "url": "https://github.com/avibe-bot/avibe/releases/download/git-runtime-v2.55.0-1/git-2.55.0-linux-x64.tar.gz",
+ "sha256": "0000000000000000000000000000000000000000000000000000000000000000",
+ "binary_sha256": "0000000000000000000000000000000000000000000000000000000000000000",
+ "size": null,
+ "bin_path": "bin/git"
+ }
+ }
+}