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
+196
View File
@@ -0,0 +1,196 @@
use kigi_tools::types::{claude_names_for, kigi_names_for};
use regex::Regex;
/// A compiled hook matcher for tool names. The pattern semantics are chosen so that
/// `matcher` entries in hooks migrated from other agent CLIs keep firing unchanged:
///
/// - an empty pattern or `"*"` matches every tool;
/// - a "simple" pattern (only `[A-Za-z0-9_|]`, i.e. a plain name or `|`-list) is an
/// **exact** match against each name (after external→Grok alias expansion), NOT a regex;
/// - anything else is an **unanchored** regex (also tested against the tool's external
/// alias names, so e.g. `^Bash$` matches the Grok tool `run_terminal_command`).
///
/// The simple-vs-regex split is deliberate: it avoids anchoring a `|`-alternation (a
/// naive `^a|b|c$` anchors only the first/last term and silently over-matches). Whitespace
/// is significant (not trimmed): `" "` is a regex that matches nothing.
#[derive(Debug, Clone)]
pub struct HookMatcher {
kind: MatcherKind,
}
#[derive(Debug, Clone)]
enum MatcherKind {
All,
Exact(Vec<String>),
Regex(Regex),
}
impl HookMatcher {
/// Compile a matcher from a user pattern. Errors only when a regex-form pattern is
/// itself invalid regex (simple/empty/`*` forms never error).
pub fn new(pattern: &str) -> Result<Self, regex::Error> {
let kind = if pattern.is_empty() || pattern == "*" {
MatcherKind::All
} else if is_simple_form(pattern) {
MatcherKind::Exact(exact_names(pattern))
} else {
MatcherKind::Regex(Regex::new(pattern)?)
};
Ok(Self { kind })
}
pub fn is_match(&self, tool_name: &str) -> bool {
match &self.kind {
MatcherKind::All => true,
MatcherKind::Exact(names) => names.iter().any(|n| n == tool_name),
MatcherKind::Regex(regex) => {
regex.is_match(tool_name)
|| claude_names_for(tool_name).any(|alias| regex.is_match(alias))
}
}
}
}
/// A pattern is "simple" (exact/`|`-list, not regex) when it contains only
/// ASCII alphanumerics, `_`, and `|`.
fn is_simple_form(pattern: &str) -> bool {
!pattern.is_empty()
&& pattern
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'|')
}
/// Expand a simple-form pattern into the exact set of names it matches: each `|`-term
/// plus any Grok tool names that term aliases (so `"Bash"` also matches
/// `run_terminal_command`), per the shared external-name to Grok registry in
/// `kigi-tools`. Empty terms and duplicates are dropped.
fn exact_names(pattern: &str) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
let mut push = |name: &str| {
if !name.is_empty() && !names.iter().any(|n| n == name) {
names.push(name.to_string());
}
};
for term in pattern.split('|') {
push(term);
for kigi_name in kigi_names_for(term) {
push(kigi_name);
}
}
names
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exact_match() {
let m = HookMatcher::new("run_terminal_command").unwrap();
assert!(m.is_match("run_terminal_command"));
assert!(!m.is_match("run_terminal_command_v2"));
assert!(!m.is_match("other_tool"));
}
#[test]
fn pipe_list_is_exact_per_term() {
let m = HookMatcher::new("read_file|list_dir").unwrap();
assert!(m.is_match("read_file"));
assert!(m.is_match("list_dir"));
assert!(!m.is_match("grep"));
// Regression for the old `^a|b$` anchoring bug: terms must not substring-match.
assert!(!m.is_match("my_read_file"));
assert!(!m.is_match("list_dir_v2"));
}
#[test]
fn pipe_skips_empty_terms() {
// Leading/trailing/double pipes contribute no spurious empty-string match.
let m = HookMatcher::new("|read_file||grep|").unwrap();
assert!(m.is_match("read_file"));
assert!(m.is_match("grep"));
assert!(!m.is_match(""));
}
#[test]
fn regex_form_is_unanchored() {
// Contains regex metachars -> regex mode, unanchored.
let m = HookMatcher::new("run_.*").unwrap();
assert!(m.is_match("run_terminal_command"));
assert!(m.is_match("xrun_yyy")); // unanchored: substring match
assert!(!m.is_match("read_file"));
}
#[test]
fn anchored_regex_respects_user_anchors() {
let m = HookMatcher::new("^run_.*$").unwrap();
assert!(m.is_match("run_terminal_command"));
assert!(!m.is_match("xrun_yyy"));
assert!(!m.is_match("read_file"));
}
#[test]
fn invalid_regex_errors() {
assert!(HookMatcher::new("[invalid").is_err());
}
#[test]
fn star_and_empty_match_all() {
for pat in ["*", ""] {
let m = HookMatcher::new(pat).unwrap();
assert!(m.is_match("read_file"), "{pat:?} should match all");
assert!(m.is_match("anything_at_all"), "{pat:?} should match all");
}
}
#[test]
fn whitespace_matcher_matches_nothing() {
// Whitespace is NOT trimmed; `" "` is a regex that matches no
// real tool name (NOT match-all, which would turn a deny gate into deny-all).
let m = HookMatcher::new(" ").unwrap();
assert!(!m.is_match("read_file"));
assert!(!m.is_match("run_terminal_command"));
}
// ── External tool-name aliases ────────────────────────────────
#[test]
fn claude_bash_matches_grok_tool() {
let m = HookMatcher::new("Bash").unwrap();
assert!(m.is_match("Bash")); // external alias name
assert!(m.is_match("run_terminal_command")); // Grok name
assert!(!m.is_match("read_file"));
// Bug-fix regression: exact, not prefix.
assert!(!m.is_match("run_terminal_command_v2"));
}
#[test]
fn claude_edit_write_matches_grok_tool_exactly() {
let m = HookMatcher::new("Edit|Write").unwrap();
assert!(m.is_match("Edit"));
assert!(m.is_match("Write"));
assert!(m.is_match("search_replace")); // Grok equivalent
assert!(m.is_match("hashline_edit")); // second Grok alias
assert!(!m.is_match("read_file"));
// The old anchoring bug matched these; the exact-list mode must not.
assert!(!m.is_match("Editorial"));
assert!(!m.is_match("my_search_replace"));
}
#[test]
fn claude_read_matches_grok_tool() {
let m = HookMatcher::new("Read").unwrap();
assert!(m.is_match("Read"));
assert!(m.is_match("read_file"));
assert!(m.is_match("hashline_read"));
}
#[test]
fn regex_against_claude_alias_matches_grok_tool() {
// A regex written against an external alias still matches the Grok tool
// (legacy alias-name expansion).
let m = HookMatcher::new("^Bash$").unwrap();
assert!(m.is_match("run_terminal_command"));
assert!(m.is_match("Bash"));
}
}