M0: compilable skeleton — Kigi 0.1.0 fork surgery

Hard fork of xai-org/grok-build (Apache-2.0) re-targeted as Kigi, an
unofficial Kimi Code CLI community build.

Rename & identity
- 72 xai-*/xai-grok-* crates -> kigi-* (explicit: xai-grok-pager-bin ->
  kigi-bin [binary `kigi`], xai-grok-pager -> kigi-tui; rest mechanical);
  ptyctl, ptyctl-cli, third_party/ unchanged; proto package
  xai.grok.tools.v1 -> kigi.tools.v1
- Config home ~/.kigi (KIGI_SHARE_DIR override), env prefix GROK_* ->
  KIGI_*, `kigi --version` carries the unofficial-community-build notice
- clap identity, help text, startup banner, prompt templates rebranded
  (templates re-encrypted)

Deletions (PRD removal list #5/#6/#7/#9/#10)
- voice input (xai-grok-voice) and all TUI wiring
- telemetry: Mixpanel client, external OTel stream, Sentry, OTLP layers,
  trace/GCS/S3 upload queues (kigi-file-utils halved), workspace upload
  module & dc_log, heap-profile uploader, auth-diagnostics uploader,
  session-analytics halves of feedback; local zero-egress observability
  preserved in new kigi-log crate (unified log, --debug firehose,
  subsystem file logs, opt-in instrumentation)
- announcements (crate, remote-settings fields, TUI surfaces)
- plugin marketplace (crate, sources/browse/CTA/extensions-modal tab);
  direct plugin install/uninstall/update via kigi-agent git_install kept
- relay/gateway/assets endpoints and features (agent relay, headless
  relay transport, gateway bridge, LeaderEnvUrls); leader IPC socket now
  ~/.kigi/leader.sock + KIGI_LEADER_SOCKET, no ws-url derivation
- functional types rehomed instead of deleted: PermissionMode ->
  kigi-config-types, McpInitStrategy -> kigi-mcp, PrCreationSource ->
  session signals, TerminalDiagnostics -> kigi-pager-render, agent_id ->
  shell util

Endpoints
- kigi-env rewritten: single production KigiEndpoints {coding_api_base_url
  https://api.kimi.com/coding/v1 (KIGI_CODE_BASE_URL), oauth_host
  https://auth.kimi.com (KIGI_OAUTH_HOST), update_base_url (GitHub
  Releases API), upgrade_page_url}; GrokBuildEnvironment enum deleted

Toolchain & workspace hygiene
- Rust 1.97.0 pinned; edition 2024; full cargo update; git2 hoisted to
  workspace at 0.21 (Option->Result API migration), quick-xml 0.41
- Root Cargo.toml hand-maintained (PRD §8.1): version 0.1.0 inherited by
  all members, members sorted, unused deps pruned
- cargo-deny advisories gate (deny.toml with documented transitive
  exceptions); CI workflow (check/clippy/fmt/deny/test, macOS+Linux)
- cross-crate test seams re-gated behind `test-support` cargo feature;
  insta snapshot baselines renamed to the kigi_tui prefix
- clippy --workspace --all-targets: zero warnings; fmt clean

Fixes surfaced by the port
- updater probe/installer divergence (bin/kigi vs bin/grok symlink set)
- idle model-metadata refresh dead under KIGI_CODE_BASE_URL override
  (new is_effective_coding_endpoint_url, loopback+override aware)
- macOS symlinked-TMPDIR fixture canonicalization (foreign_sessions,
  fast-worktree); RSS measurement tests serialized via serial_test

Docs & legal (Apache §4)
- NOTICE added (upstream attribution + change statement); THIRD-PARTY
  notices sustained; kigi-tools ported-code notices extended; README,
  CONTRIBUTING, SECURITY, AGENTS.md rewritten

Out of scope for M0 (tracked): Kimi auth/inference (M1), search/fetch,
command parity, config import (M2), Computer Hub excision & final
brand-token sweep (M2), distribution & self-update rewrite (M3).
This commit is contained in:
2026-07-17 05:31:01 -04:00
commit d6c20fc13f
2612 changed files with 1353757 additions and 0 deletions
+177
View File
@@ -0,0 +1,177 @@
//! Shared environment helpers: binary resolution, git workdirs, env var setup.
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::process::Command;
use tempfile::TempDir;
/// RAII guard for a single environment variable in `#[serial]` tests: snapshots
/// the prior value on construction, applies the change, then restores the prior
/// value (or unsets it) on drop — even if an assertion panics. Restoring rather
/// than always unsetting avoids clobbering vars a parent process/harness set
/// (e.g. `RUST_LOG`).
///
/// Callers MUST be `#[serial_test::serial]`: the `unsafe` `set_var`/`remove_var`
/// are sound only when no other thread accesses the environment concurrently.
pub struct EnvGuard {
key: &'static str,
prior: Option<OsString>,
}
impl EnvGuard {
/// Set `key` to `value` for the guard's lifetime. Accepts `&str`, `&Path`,
/// `String`, etc. via `AsRef<OsStr>`.
pub fn set(key: &'static str, value: impl AsRef<OsStr>) -> Self {
let prior = std::env::var_os(key);
// SAFETY: callers are `#[serial]`, so no other thread touches the env.
unsafe { std::env::set_var(key, value) };
Self { key, prior }
}
/// Unset `key` for the guard's lifetime.
pub fn unset(key: &'static str) -> Self {
let prior = std::env::var_os(key);
// SAFETY: see [`EnvGuard::set`].
unsafe { std::env::remove_var(key) };
Self { key, prior }
}
}
impl Drop for EnvGuard {
fn drop(&mut self) {
// SAFETY: see [`EnvGuard::set`].
match self.prior.take() {
Some(v) => unsafe { std::env::set_var(self.key, v) },
None => unsafe { std::env::remove_var(self.key) },
}
}
}
fn workspace_root() -> PathBuf {
// nth(3): crate is nested three levels below the cargo workspace root.
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.ancestors()
.nth(3)
.expect("workspace root")
.to_path_buf()
}
fn target_dir() -> PathBuf {
std::env::var_os("CARGO_TARGET_DIR")
.map(PathBuf::from)
.unwrap_or_else(|| workspace_root().join("target"))
}
fn local_grok_binary_path() -> PathBuf {
target_dir()
.join("debug")
.join(format!("kigi-tui{}", std::env::consts::EXE_SUFFIX))
}
fn ensure_local_grok_binary(binary: &Path) {
if binary.exists() {
return;
}
let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string());
let output = Command::new(&cargo)
.current_dir(workspace_root())
.args(["build", "-p", "kigi-tui", "--bin", "kigi-tui"])
.output()
.unwrap_or_else(|e| panic!("failed to spawn {cargo} to build kigi-tui: {e}"));
assert!(
output.status.success(),
"failed to build kigi-tui for lifecycle tests (exit {:?})\nstdout:\n{}\nstderr:\n{}",
output.status.code(),
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
assert!(
binary.exists(),
"kigi-tui build completed but binary missing at {}",
binary.display()
);
}
/// Resolve grok binary: `KIGI_BINARY` env (CI) or a locally built `kigi-tui` binary.
pub fn grok_binary() -> PathBuf {
if let Ok(path) = std::env::var("KIGI_BINARY") {
let p = PathBuf::from(path);
assert!(p.exists(), "KIGI_BINARY does not exist: {}", p.display());
return p;
}
if let Ok(path) = std::env::var("CARGO_BIN_EXE_kigi-tui") {
let p = PathBuf::from(path);
if p.exists() {
return p;
}
}
let binary = local_grok_binary_path();
ensure_local_grok_binary(&binary);
binary
}
/// Temp dir with a git repo + one committed file.
/// Forces libgit2 to fully init (the codepath that breaks with bad OpenSSL linking).
pub fn git_workdir() -> TempDir {
let dir = TempDir::new().expect("create temp dir");
let path = dir.path();
fn run_git(args: &[&str], dir: &Path) {
let output = Command::new("git")
.args(args)
.current_dir(dir)
.output()
.unwrap_or_else(|e| panic!("failed to spawn git {}: {e}", args.join(" ")));
assert!(
output.status.success(),
"git {} failed (exit {:?}):\n{}",
args.join(" "),
output.status.code(),
String::from_utf8_lossy(&output.stderr),
);
}
run_git(&["init"], path);
// Configure git user for commits (required in CI where no global config exists)
run_git(&["config", "user.email", "test@test.com"], path);
run_git(&["config", "user.name", "Test"], path);
std::fs::write(path.join("README.md"), "test file\n").expect("write test file");
run_git(&["add", "-A"], path);
run_git(&["commit", "-m", "init", "--no-gpg-sign"], path);
dir
}
/// Point grok at the mock server with a fake API key and telemetry disabled.
pub fn test_env_cmd_tokio(
cmd: &mut tokio::process::Command,
mock_url: &str,
home: &std::path::Path,
) {
cmd.env("HOME", home)
// HOME alone does not sandbox grok on Windows: the product resolves
// `~` via `USERPROFILE`/Known Folders (`std::env::home_dir()`), so
// without an explicit KIGI_SHARE_DIR every spawned child shares the real
// `%USERPROFILE%\.kigi` — test 1's models_cache.json (which embeds
// its per-test mock-server URL) then poisons every later test's
// prompt (the windows-x86_64 lifecycle "prompt timed out" failure).
// Mirrors `leader.rs` and the pty-harness `env_for_pager`.
.env("KIGI_SHARE_DIR", home.join(".kigi"))
.env("KIGI_CLI_CHAT_PROXY_BASE_URL", mock_url)
.env("KIGI_XAI_API_BASE_URL", mock_url)
.env("XAI_API_KEY", "test-key-for-ci")
.env("KIGI_TELEMETRY_ENABLED", "false")
.env("KIGI_FEEDBACK_ENABLED", "false")
.env("KIGI_TRACE_UPLOAD", "false")
.env("KIGI_INSTRUMENTATION", "disabled")
// Release binaries (CI lifecycle tests) otherwise spawn a background
// update check that hits the network and can add latency under Rosetta.
.env("KIGI_DISABLE_AUTOUPDATER", "1");
}