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
@@ -0,0 +1,65 @@
//! `pty-scenario` — scripted TUI regression runner for kigi-tui.
use std::path::PathBuf;
use std::process::ExitCode;
use anyhow::{Context, Result, bail};
use clap::Parser as ClapParser;
use kigi_pager_pty_harness::{
ScriptedRunConfig, ScriptedRunStatus, ScriptedScenario, ScriptedScenarioRunner, pager_binary,
};
#[derive(ClapParser, Debug)]
#[command(
name = "pty-scenario",
about = "Run declarative TUI regression scenarios against kigi-tui",
long_about = None,
)]
struct Cli {
/// Scenario file to run. Supports JSON, YAML, and YML.
#[arg(long, value_name = "PATH")]
scenario: PathBuf,
/// Pager binary. Defaults to PAGER_BINARY, CARGO_BIN_EXE_kigi-tui,
/// or a locally-built debug binary.
#[arg(long, value_name = "PATH")]
binary: Option<PathBuf>,
/// Directory for report.json, bugs.md, text/html/svg/styled-json captures.
#[arg(long, value_name = "DIR", default_value = "target/pty-scenarios")]
artifacts: PathBuf,
}
#[tokio::main(flavor = "multi_thread", worker_threads = 2)]
async fn main() -> ExitCode {
match run().await {
Ok(status) => status,
Err(error) => {
eprintln!("pty-scenario failed: {error:#}");
ExitCode::from(2)
}
}
}
async fn run() -> Result<ExitCode> {
let cli = Cli::parse();
let scenario = ScriptedScenario::from_file(&cli.scenario)
.with_context(|| format!("load scenario {}", cli.scenario.display()))?;
let binary = match cli.binary {
Some(path) => path,
None => pager_binary().context("resolve pager binary")?,
};
if !binary.exists() {
bail!("pager binary does not exist: {}", binary.display());
}
let runner = ScriptedScenarioRunner::new(ScriptedRunConfig::new(binary, cli.artifacts));
let report = runner.run(&scenario).await?;
let json = serde_json::to_string_pretty(&report).context("serialize final report")?;
println!("{json}");
match report.status {
ScriptedRunStatus::Passed | ScriptedRunStatus::Skipped => Ok(ExitCode::SUCCESS),
ScriptedRunStatus::Failed | ScriptedRunStatus::Running => Ok(ExitCode::from(1)),
}
}
@@ -0,0 +1,151 @@
//! `scroll-matrix` — scroll validation matrix sweep for kigi-tui.
//!
//! Runs matrix cells (`scroll_matrix::CELLS`) against a real pager binary in
//! a PTY, prints the per-cell verdict table, writes `report.json` into the
//! artifacts dir (next to each cell's recorder capture), and exits nonzero
//! iff any cell failed or an xfail cell passed. The curated tier also runs
//! in CI as `tests/scroll_matrix_curated.rs`; this binary is the local
//! entry point for the full sweep and for one-off cell reruns (`--filter`).
use std::path::PathBuf;
use std::process::ExitCode;
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use clap::{Parser as ClapParser, ValueEnum};
use kigi_pager_pty_harness::pager_binary;
use kigi_pager_pty_harness::scroll_matrix::{
CELLS, CellReport, MatrixCell, Tier, exit_code, run_cell, summary_table, write_report_json,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum TierArg {
/// The CI subset.
Curated,
/// Every cell (curated + full-tier rows).
Full,
}
#[derive(ClapParser, Debug)]
#[command(
name = "scroll-matrix",
about = "Run the scroll validation matrix against kigi-tui",
long_about = None,
)]
struct Cli {
/// Cell tier to run.
#[arg(long, value_enum, default_value_t = TierArg::Curated)]
tier: TierArg,
/// Only run cells whose id contains this substring.
#[arg(long, value_name = "SUBSTR")]
filter: Option<String>,
/// Concurrent cells. Default 1 because gestures are host-paced: parallel
/// cells contend for CPU and stretch the inter-report sleeps, which can
/// flip Auto-mode classifications. The invariant suite is stall-safe (it
/// judges timing from the recorder's clock), so raising this stays sound
/// — it just makes captures less representative of real gesture timing.
#[arg(long, value_name = "N", default_value_t = 1)]
jobs: usize,
/// Directory for report.json and the per-cell recorder captures.
#[arg(long, value_name = "DIR", default_value = "target/scroll-matrix")]
artifacts: PathBuf,
/// Pager binary. Defaults to PAGER_BINARY, CARGO_BIN_EXE_kigi-tui,
/// or a locally-built debug binary.
#[arg(long, value_name = "PATH")]
binary: Option<PathBuf>,
}
// Multi-thread runtime required: run_cell drives its blocking cell body via
// Handle::block_on on a spawn_blocking thread (see scroll_matrix::runner).
#[tokio::main(flavor = "multi_thread", worker_threads = 2)]
async fn main() -> ExitCode {
match run().await {
Ok(code) => code,
Err(error) => {
eprintln!("scroll-matrix failed: {error:#}");
ExitCode::from(2)
}
}
}
async fn run() -> Result<ExitCode> {
let cli = Cli::parse();
let binary = match cli.binary {
Some(path) => path,
None => pager_binary().context("resolve pager binary")?,
};
if !binary.exists() {
bail!("pager binary does not exist: {}", binary.display());
}
let cells: Vec<&'static MatrixCell> = CELLS
.iter()
.filter(|cell| cli.tier == TierArg::Full || cell.tier == Tier::Curated)
.filter(|cell| {
cli.filter
.as_deref()
.is_none_or(|needle| cell.id.contains(needle))
})
.collect();
if cells.is_empty() {
bail!(
"no cells match --tier {:?} --filter {:?}",
cli.tier,
cli.filter
);
}
// The pager child resolves KIGI_SCROLL_LOG against ITS cwd (the
// harness's temp workspace), so a relative artifacts dir — including
// the default — would scatter captures there and starve the finalize
// wait. Absolutize against the invoking cwd.
let artifacts = std::path::absolute(&cli.artifacts)
.with_context(|| format!("absolutize artifacts dir {}", cli.artifacts.display()))?;
let reports = run_cells(&cells, cli.jobs.max(1), &binary, &artifacts).await;
print!("{}", summary_table(&reports));
let report_path = write_report_json(&reports, &artifacts)?;
eprintln!("report: {}", report_path.display());
Ok(ExitCode::from(exit_code(&reports)))
}
/// Run every cell, preserving table order. `jobs == 1` runs inline (the
/// representative-timing default); higher values fan out over a semaphore.
async fn run_cells(
cells: &[&'static MatrixCell],
jobs: usize,
binary: &std::path::Path,
artifacts: &std::path::Path,
) -> Vec<CellReport> {
if jobs == 1 {
let mut reports = Vec::with_capacity(cells.len());
for (i, cell) in cells.iter().enumerate() {
eprintln!("[{}/{}] {}", i + 1, cells.len(), cell.id);
reports.push(run_cell(cell, binary, artifacts).await);
}
return reports;
}
let semaphore = Arc::new(tokio::sync::Semaphore::new(jobs));
let mut set = tokio::task::JoinSet::new();
for (index, &cell) in cells.iter().enumerate() {
let semaphore = semaphore.clone();
let (binary, artifacts) = (binary.to_path_buf(), artifacts.to_path_buf());
set.spawn(async move {
let _permit = semaphore.acquire_owned().await.expect("semaphore open");
eprintln!("running {}", cell.id);
(index, run_cell(cell, &binary, &artifacts).await)
});
}
let mut indexed = Vec::with_capacity(cells.len());
while let Some(joined) = set.join_next().await {
// run_cell converts cell panics into Fail reports itself.
indexed.push(joined.expect("cell task join"));
}
indexed.sort_by_key(|(index, _)| *index);
indexed.into_iter().map(|(_, report)| report).collect()
}