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
+171
View File
@@ -0,0 +1,171 @@
use std::path::{Path, PathBuf};
// Project-hook trust is no longer stored here: the shell's folder-trust store
// (`~/.kigi/trusted_folders.toml`) is the single authority for whether a repo's
// project hooks run (the same gate as repo-local MCP/LSP). The helpers below
// exist only to migrate prior grants out of the legacy file.
/// Path to the legacy project-hook trust file
/// (`<user_kigi_home>/trusted-hook-projects`), or `None` when no user grok home
/// resolves. Retained only for the one-time migration into folder-trust.
pub fn legacy_trust_file_path() -> Option<PathBuf> {
Some(kigi_config::user_kigi_home()?.join("trusted-hook-projects"))
}
/// Parse the legacy trusted-projects file into a list of project paths.
///
/// The legacy format is one canonical absolute path per line; blank and
/// `#`-comment lines are skipped. A missing file yields `Ok(empty)` (nothing to
/// migrate); any OTHER read error is returned as `Err` so the caller does not
/// mistake an unreadable file for an empty one and consume it. Consumed by the
/// one-time migration that seeds folder-trust from prior grants.
pub fn list_trusted_projects_with_file(trust_file: &Path) -> std::io::Result<Vec<PathBuf>> {
let content = match std::fs::read_to_string(trust_file) {
Ok(c) => c,
// A missing file is "nothing to migrate", not an error.
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(e),
};
Ok(content
.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.map(PathBuf::from)
.collect())
}
// ── Hook enable/disable ─────────────────────────────────────────────────
/// Check whether a hook is disabled by name.
///
/// Disabled hooks are listed in , one hook name per line.
pub fn is_hook_disabled(hook_name: &str) -> bool {
match disabled_hooks_file_path() {
Some(file) => is_hook_disabled_with_file(hook_name, &file),
None => false,
}
}
fn is_hook_disabled_with_file(hook_name: &str, file: &Path) -> bool {
let content = match std::fs::read_to_string(file) {
Ok(c) => c,
Err(_) => return false,
};
content
.lines()
.any(|l| !l.trim().is_empty() && !l.trim().starts_with('#') && l.trim() == hook_name)
}
/// Disable a hook by name. Adds to .
pub fn disable_hook(hook_name: &str) -> Result<(), String> {
let file = disabled_hooks_file_path()
.ok_or_else(|| "no user grok home (set $KIGI_SHARE_DIR or $HOME)".to_string())?;
disable_hook_with_file(hook_name, &file)
}
fn disable_hook_with_file(hook_name: &str, file: &Path) -> Result<(), String> {
if is_hook_disabled_with_file(hook_name, file) {
return Ok(()); // Already disabled.
}
if let Some(parent) = file.parent() {
let _ = std::fs::create_dir_all(parent);
}
use std::io::Write;
let mut f = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(file)
.map_err(|e| format!("failed to open disabled-hooks file: {e}"))?;
writeln!(f, "{hook_name}").map_err(|e| format!("failed to write disabled-hooks file: {e}"))?;
Ok(())
}
/// Enable a hook by name (remove from ).
pub fn enable_hook(hook_name: &str) -> Result<bool, String> {
match disabled_hooks_file_path() {
Some(file) => enable_hook_with_file(hook_name, &file),
None => Ok(false),
}
}
fn enable_hook_with_file(hook_name: &str, file: &Path) -> Result<bool, String> {
let content = match std::fs::read_to_string(file) {
Ok(c) => c,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(e) => return Err(format!("failed to read disabled-hooks file: {e}")),
};
let mut found = false;
let new_lines: Vec<&str> = content
.lines()
.filter(|line| {
let trimmed = line.trim();
if !trimmed.is_empty() && !trimmed.starts_with('#') && trimmed == hook_name {
found = true;
false
} else {
true
}
})
.collect();
if !found {
return Ok(false);
}
if let Some(parent) = file.parent() {
let _ = std::fs::create_dir_all(parent);
}
use std::io::Write;
let mut f = std::fs::File::create(file)
.map_err(|e| format!("failed to open disabled-hooks file: {e}"))?;
for line in new_lines {
writeln!(f, "{line}").map_err(|e| format!("failed to write disabled-hooks file: {e}"))?;
}
Ok(true)
}
/// Returns the path to `$KIGI_SHARE_DIR/disabled-hooks`, or `None` when no user grok
/// home resolves.
fn disabled_hooks_file_path() -> Option<PathBuf> {
Some(kigi_config::user_kigi_home()?.join("disabled-hooks"))
}
#[cfg(test)]
mod tests {
use super::*;
/// Each test creates its own legacy file in its own temp dir -- no shared state.
fn trust_file_in(dir: &Path) -> PathBuf {
let grok_dir = dir.join(".kigi");
std::fs::create_dir_all(&grok_dir).unwrap();
grok_dir.join("trusted-hook-projects")
}
#[test]
fn list_trusted_projects_parses_paths_skipping_comments_and_blanks() {
let home = tempfile::tempdir().unwrap();
let trust_file = trust_file_in(home.path());
std::fs::write(
&trust_file,
"# comment\n\n/abs/project/one\n /abs/project/two \n# trailing\n",
)
.unwrap();
let projects = list_trusted_projects_with_file(&trust_file).unwrap();
assert_eq!(
projects,
vec![
PathBuf::from("/abs/project/one"),
PathBuf::from("/abs/project/two"),
]
);
}
#[test]
fn list_trusted_projects_missing_file_is_empty() {
// A missing file is Ok(empty), NOT an error — so the migration treats it
// as "nothing to migrate" rather than as an unreadable file.
let projects =
list_trusted_projects_with_file(Path::new("/nonexistent/trusted-hook-projects"))
.expect("missing file resolves to Ok(empty)");
assert!(projects.is_empty());
}
}