§9 acceptance: grep-zero sweep — every internal x.ai/grok identifier renamed
The PRD's first acceptance gate now holds: grep -RinE '\bx\.ai\b|grok' crates/ --include='*.rs' → 0 matches (exempt: NOTICE and third-party license archives, README provenance, and the required 'Based on Grok Build Open Source' attribution, now sourced from version_attribution.txt). Wire-visible renames (both sides in this repo, changed in lockstep): - Auth method id 'grok.com' → 'kimi-code' (AuthMethodKind::KimiCode). - Every x.ai/* and _x.ai/* ACP ext method and meta key → kigi/* / _kigi/* (~200 names; grokShell → kigiShell). Session-file replay keeps a read-side alias for the legacy '_x.ai/session/update' method so existing updates.jsonl histories load; writes emit only the new name (both directions test-pinned). - Agent types grok-build* → kigi* with a documented legacy-prefix alias at resolution time so persisted sessions keep resolving. - ToolNamespace/BuiltinAgentName GrokBuild* → Kigi* (wire snake_case kigi/kigi_concise/kigi_hashline; schema regenerated); grok_build implementation dirs renamed to kigi*. - x-grok-* headers → x-kigi-*, __GROK_* sentinels → __KIGI_*, themes grokday/groknight → kigiday/kiginight (old persisted values fall back to the default theme), web_fetch allowlist xAI hosts → kimi.com + moonshot platforms, changelog CDN → this repo, grok-build changelog archives deleted. - BYOK default endpoint removed: [endpoints] api_base_url is now truly optional with NO default — consumers fail fast with the flag name when unset (no silent x.ai egress). Mock harnesses inject it explicitly. - System-prompt identity fixed: 'released by xAI' → 'an unofficial community CLI for Kimi' (template + regenerated encrypted form). Also repaired pre-existing grok-era test debt found by the sweep: the stale trace_classify default-model pin, the grok-pager UA label test, pty-harness stale-binary reuse and non-hermetic moonshot routing (a PTY test could previously reach the real api.moonshot.cn), and the outdated oauth fixture scope key. Gates: §9 grep 0; fmt clean; workspace check/clippy 0/0 (-D warnings); FULL cargo test --workspace: 234 suites, 21,961 passed, 0 failed; deny advisories ok.
This commit is contained in:
@@ -3,7 +3,7 @@ license = "Apache-2.0"
|
||||
name = "kigi-test-support"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
description = "Shared test-support for grok-build crates: mock inference server, SSE generators, ACP stdio client, headless runner, env sandbox"
|
||||
description = "Shared test-support for kigi crates: mock inference server, SSE generators, ACP stdio client, headless runner, env sandbox"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# kigi-test-support
|
||||
|
||||
Shared test infrastructure for the grok-build crates: mock inference server,
|
||||
Shared test infrastructure for the kigi crates: mock inference server,
|
||||
SSE wire-format generators, ACP stdio clients, headless
|
||||
runner, and sandboxed process env. Consumed by `kigi-shell` integration
|
||||
tests, `kigi-pager-pty-harness` (`ContentController`), and `kigi-sampler`
|
||||
@@ -20,10 +20,10 @@ test-support surface.
|
||||
| `mock_server` | `MockInferenceServer` — `/v1/chat/completions`, `/v1/responses`, `/v1/messages`, `/v1/models`, `/v1/settings`, `/v1/user` on `127.0.0.1:0`. `/v1/models` entries are `MockModelEntry` (re-exported as `MockModel` for PTY tests): `new(id)` / `with_agent_type(id, ty)` plus chainable `with_api_backend`, `with_supports_backend_search(bool)` → `supportsBackendSearch`, `with_supports_reasoning_effort(bool)` → `supportsReasoningEffort`, `with_reasoning_effort(&str)` → `reasoningEffort`, `with_reasoning_efforts(Vec<Value>)` → `reasoningEfforts` (raw option tables/bare strings), all emitted top-level as `parse_remote_model_value` reads them. Three response modes for the inference endpoints, precedence **scripted > required-auth > mode**: (1) **echo** (default) streams `Echo: <last user message>`, whitespace-collapsing; (2) **fixed** via `set_response(text)`, byte-exact delta reconstruction (newlines preserved — fenced code blocks survive); (3) **scripted** via `enqueue_response`. Constructors (`start`, `start_with_models`, `start_with_required_auth`) return `anyhow::Result`. Settings are 404-until-set (`set_settings(impl Serialize)`, `preset_allow_access()` for the `{"allow_access": true}` gate); scripted `/v1/settings` one-shots (`enqueue_response`) take precedence over the steady-state value (stale-snapshot tests). `/v1/user` serves a minimal `UserInfo` whose `subscriptionTier` is controlled by `set_user_subscription_tier(Option<&str>)` (`None` = free); its log entries keep the query string (e.g. `/v1/user?include=subscription`) so subscription-check cadence is countable. Request log: `requests()` (`LogEntry` with body, `authorization`, full POST headers + `header(name)` accessor), `request_bodies()`, `request_count()`, `has_chat_completion_request()` / `has_responses_request()` (exact, per endpoint), `messages_request_count()`, `last_system_prompt()`, `request_log_summary()`. **Storage:** `POST /v1/storage` with flippable 401 (`set_storage_unauthorized`); accepted uploads via `storage_uploads()` → `StorageUpload { path, size, body, authorization }` (`body` retained up to 256 KiB, empty above; `authorization` is the raw header). Runtime knobs: `set_models`, `set_messages_stop_reason`. Shuts down on drop. |
|
||||
| `scripted` | Data-only scripting (no axum types in the surface): `SseEvent { event, data }` (`::data`, `::with_event`), `ScriptedBody::{Json, Sse, Raw}` (`Raw` = byte-controllable malformed SSE), `ScriptedResponse { status, headers, body }` (`::sse`, `::json`, `::text`). `enqueue_response(path, response)` queues FIFO **per path**; consumed by the three inference endpoints, falling back to the active mode when empty. Scripted SSE bodies honor the server's `set_chunk_delay` pacing, same as the echo/fixed modes. Validation is eager — bad status/header panics at the enqueue call site. Seed of the phase-2 scriptable-mock format. |
|
||||
| `sse` | The three wire formats as event-list builders: `chat_completion_events` / `responses_api_events` / `messages_api_events(text, model, stop_reason)` (echo-style, whitespace-collapsing) plus byte-exact variants `chat_completion_events_exact` / `responses_api_events_exact` (messages is single-delta, byte-exact by construction). The exact/echo split is load-bearing — see the in-module byte-exactness tests. Also the scripted-scenario builders returning `SseEvent`s (for `ScriptedResponse::sse`): `responses_api_reasoning_only_events(reasoning, model)` — reasoning summary deltas completing with a `reasoning` item but no message/output-text, so the shell collector classifies the turn `EmptyReason::ReasoningOnly` (the model-doomloop trigger); `responses_api_reasoning_and_text_events(reasoning, text, model)` — reasoning deltas then a normal text answer (the ordinary reasoning-model turn); `responses_api_reasoning_then_tool_call_events(reasoning, call_id, name, arguments, model)` + its Chat Completions twin `chat_completions_reasoning_then_tool_call_events(...)` — reasoning deltas then one tool call (the think-then-call turn whose tool call finishes the thought and keeps the turn non-empty); the doom-loop check trio: `responses_api_doom_loop_check_events(triggers, reasoning, model)` — a doomed reasoning-only turn with NAMED `response.doom_loop_check` frames re-sent per cumulative prefix of `triggers` plus the terminal `doom_loop_check.triggers` copy on `response.completed`, `responses_api_doom_loop_terminal_only_events(triggers, reasoning, text, model)` — a normal answer whose terminal response alone carries the field, and `responses_api_with_doom_loop_frame(check_frame_data, reasoning, text, model)` — splices one named check frame with a caller-supplied payload (byte-exact `kigi_sampling_types::doom_loop::SAMPLE_CHECK_EVENT_DATA{,_CUMULATIVE}` fixtures or malformed variants) into an ordinary turn. |
|
||||
| `acp_client` | `GrokStdioClient` — drives `grok agent stdio` over real pipes through `agent-client-protocol`: spawn variants (`spawn`, `spawn_with_home`, `spawn_with_home_and_env`, `spawn_with_home_env_and_args`), initialize/authenticate, session create/load, prompt, `*_with_timeout` wrappers, captured text + stderr. `RawStdioClient` — raw-wire sibling for bytes the typed `ClientSideConnection` can never produce (escaped-slash methods `"session\/prompt"`, string UUID ids — the Xcode/Foundation shape): `send_line` writes a line verbatim; `response_for_id` matches the response by exact string id (the match IS the id-echo assertion), skips notifications, auto-refuses agent→client requests with `-32601`, and panics on timeout with skipped-traffic diagnostics (count + last lines; `0 other messages` = true silence). Both spawn through one hermetic `spawn_agent_process` (sandbox env + debug-log kill-list exists once) atop `process::spawn_piped_with_stderr_capture` (crate-internal `process` module: pipes, `kill_on_drop`, stderr drain — also used by `leader::LeaderStdioClient`). |
|
||||
| `acp_client` | `KigiStdioClient` — drives `kigi agent stdio` over real pipes through `agent-client-protocol`: spawn variants (`spawn`, `spawn_with_home`, `spawn_with_home_and_env`, `spawn_with_home_env_and_args`), initialize/authenticate, session create/load, prompt, `*_with_timeout` wrappers, captured text + stderr. `RawStdioClient` — raw-wire sibling for bytes the typed `ClientSideConnection` can never produce (escaped-slash methods `"session\/prompt"`, string UUID ids — the Xcode/Foundation shape): `send_line` writes a line verbatim; `response_for_id` matches the response by exact string id (the match IS the id-echo assertion), skips notifications, auto-refuses agent→client requests with `-32601`, and panics on timeout with skipped-traffic diagnostics (count + last lines; `0 other messages` = true silence). Both spawn through one hermetic `spawn_agent_process` (sandbox env + debug-log kill-list exists once) atop `process::spawn_piped_with_stderr_capture` (crate-internal `process` module: pipes, `kill_on_drop`, stderr drain — also used by `leader::LeaderStdioClient`). |
|
||||
| `headless` | `run_headless(server, args, cwd)` / `run_headless_with_cmd(cmd)` → `HeadlessResult { status, stdout, stderr, timed_out }` (60s cap), `assert_headless_success`, `assert_no_crashes` (panic/SIGSEGV/linker patterns), `stderr_tail`. |
|
||||
| `env` | `grok_binary()` (`KIGI_BINARY` env → `CARGO_BIN_EXE` → local debug build of `kigi-tui`), `git_workdir()` (temp git repo, forces full libgit2 init), `test_env_cmd_tokio(cmd, mock_url, home)` (sandboxed HOME **and KIGI_SHARE_DIR** — Windows resolves `~` via USERPROFILE, so HOME alone doesn't sandbox — + mock endpoints + telemetry kill-switches). |
|
||||
| `leader` | Unix-only `LeaderStdioClient` (`grok agent --leader stdio`, `env_clear`-hermetic, sandboxed `KIGI_LEADER_SOCKET`; `spawn_with_binary` runs an explicit binary for version-skew lanes, per-role resolution via `leader_binary()` / `client_binary()` honoring `KIGI_BINARY_LEADER` / `KIGI_BINARY_CLIENT`) + lock-file helpers: `leader_lock_path`, `read_leader_pid`, `pid_alive`, `wait_for_live_leader`, `wait_for_new_leader`, `wait_for_replay_notifications`, `leader_log`. |
|
||||
| `env` | `kigi_binary()` (`KIGI_BINARY` env → `CARGO_BIN_EXE` → local debug build of `kigi-tui`), `git_workdir()` (temp git repo, forces full libgit2 init), `test_env_cmd_tokio(cmd, mock_url, home)` (sandboxed HOME **and KIGI_SHARE_DIR** — Windows resolves `~` via USERPROFILE, so HOME alone doesn't sandbox — + mock endpoints + telemetry kill-switches). |
|
||||
| `leader` | Unix-only `LeaderStdioClient` (`kigi agent --leader stdio`, `env_clear`-hermetic, sandboxed `KIGI_LEADER_SOCKET`; `spawn_with_binary` runs an explicit binary for version-skew lanes, per-role resolution via `leader_binary()` / `client_binary()` honoring `KIGI_BINARY_LEADER` / `KIGI_BINARY_CLIENT`) + lock-file helpers: `leader_lock_path`, `read_leader_pid`, `pid_alive`, `wait_for_live_leader`, `wait_for_new_leader`, `wait_for_replay_notifications`, `leader_log`. |
|
||||
| `uds_proxy` | Unix-only `UdsProxy` — frame-aware (4-byte BE length prefix) man-in-the-middle for leader IPC sockets. `UdsProxy::spawn(proxy_path, upstream_path, FaultPlan)`; `FaultPlan { direction, drop_frame, sever_mid_frame, delay, duplicate_frame }` (1-based frame index, per connection per direction); runtime `FaultHandle::sever_now()` + `forwarded(direction)` counters; frame bodies capped at 64 MiB (leader-transport parity — corrupt lengths error instead of allocating). Zero production changes: point `LeaderClient::connect` / `KIGI_LEADER_SOCKET` at the proxy path. |
|
||||
|
||||
## Consumer matrix
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! ACP stdio clients for testing grok sessions end-to-end: the typed
|
||||
//! [`GrokStdioClient`] (`agent-client-protocol::ClientSideConnection` —
|
||||
//! ACP stdio clients for testing kigi sessions end-to-end: the typed
|
||||
//! [`KigiStdioClient`] (`agent-client-protocol::ClientSideConnection` —
|
||||
//! authentication, session lifecycle, permissions, notification streaming) and
|
||||
//! the raw-wire [`RawStdioClient`] (verbatim JSON-RPC lines for shapes the
|
||||
//! typed client can't produce), plus the shared subprocess spawn/stderr-capture
|
||||
@@ -15,14 +15,14 @@ use kigi_acp_lib::LineBufferedRead;
|
||||
use tempfile::TempDir;
|
||||
use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};
|
||||
|
||||
use crate::env::{grok_binary, test_env_cmd_tokio};
|
||||
use crate::env::{kigi_binary, test_env_cmd_tokio};
|
||||
use crate::headless::stderr_tail;
|
||||
use crate::mock_server::MockInferenceServer;
|
||||
use crate::process::spawn_piped_with_stderr_capture;
|
||||
|
||||
/// Spawn `grok agent stdio` with the canonical hermetic test env: the sandbox
|
||||
/// Spawn `kigi agent stdio` with the canonical hermetic test env: the sandbox
|
||||
/// from [`test_env_cmd_tokio`] plus the debug-logging kill-list, so the
|
||||
/// hermeticity setup exists exactly once for the typed ([`GrokStdioClient`])
|
||||
/// hermeticity setup exists exactly once for the typed ([`KigiStdioClient`])
|
||||
/// and raw ([`RawStdioClient`]) harnesses. `leading_args` go before the
|
||||
/// `agent stdio` subcommand (global flags); `extra_env` is applied after the
|
||||
/// kill-list so a test can still set e.g. `KIGI_DEBUG_LOG=1` explicitly.
|
||||
@@ -33,7 +33,7 @@ fn spawn_agent_process(
|
||||
extra_env: &[(&str, &str)],
|
||||
leading_args: &[&str],
|
||||
) -> (tokio::process::Child, Arc<std::sync::Mutex<Vec<u8>>>) {
|
||||
let binary = grok_binary();
|
||||
let binary = kigi_binary();
|
||||
|
||||
let mut cmd = tokio::process::Command::new(&binary);
|
||||
cmd.args(leading_args)
|
||||
@@ -107,11 +107,11 @@ impl acp::Client for TestAcpClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drives `grok agent stdio` via the ACP protocol over pipes.
|
||||
/// Drives `kigi agent stdio` via the ACP protocol over pipes.
|
||||
///
|
||||
/// Handles the full lifecycle: spawn → initialize → authenticate → session → prompt.
|
||||
/// Child process is killed on drop.
|
||||
pub struct GrokStdioClient {
|
||||
pub struct KigiStdioClient {
|
||||
conn: acp::ClientSideConnection,
|
||||
_child: tokio::process::Child,
|
||||
home: Option<TempDir>,
|
||||
@@ -119,7 +119,7 @@ pub struct GrokStdioClient {
|
||||
stderr: Arc<std::sync::Mutex<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl GrokStdioClient {
|
||||
impl KigiStdioClient {
|
||||
pub async fn spawn(server: &MockInferenceServer, cwd: &Path) -> Self {
|
||||
let home = TempDir::new().expect("create temp home");
|
||||
Self::spawn_with_home(server, cwd, home).await
|
||||
@@ -396,9 +396,9 @@ impl GrokStdioClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drives `grok agent stdio` with verbatim newline-delimited JSON-RPC lines.
|
||||
/// Drives `kigi agent stdio` with verbatim newline-delimited JSON-RPC lines.
|
||||
///
|
||||
/// Exists for wire shapes the typed [`GrokStdioClient`] (`ClientSideConnection`,
|
||||
/// Exists for wire shapes the typed [`KigiStdioClient`] (`ClientSideConnection`,
|
||||
/// integer ids) can never produce — e.g. Xcode's Swift/Foundation `JSONEncoder`
|
||||
/// output: escaped-slash methods (`"session\/prompt"`) and string UUID request
|
||||
/// ids. Child process is killed on drop.
|
||||
|
||||
@@ -63,13 +63,13 @@ fn target_dir() -> PathBuf {
|
||||
.unwrap_or_else(|| workspace_root().join("target"))
|
||||
}
|
||||
|
||||
fn local_grok_binary_path() -> PathBuf {
|
||||
fn local_kigi_binary_path() -> PathBuf {
|
||||
target_dir()
|
||||
.join("debug")
|
||||
.join(format!("kigi-tui{}", std::env::consts::EXE_SUFFIX))
|
||||
}
|
||||
|
||||
fn ensure_local_grok_binary(binary: &Path) {
|
||||
fn ensure_local_kigi_binary(binary: &Path) {
|
||||
if binary.exists() {
|
||||
return;
|
||||
}
|
||||
@@ -95,8 +95,8 @@ fn ensure_local_grok_binary(binary: &Path) {
|
||||
);
|
||||
}
|
||||
|
||||
/// Resolve grok binary: `KIGI_BINARY` env (CI) or a locally built `kigi-tui` binary.
|
||||
pub fn grok_binary() -> PathBuf {
|
||||
/// Resolve kigi binary: `KIGI_BINARY` env (CI) or a locally built `kigi-tui` binary.
|
||||
pub fn kigi_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());
|
||||
@@ -110,8 +110,8 @@ pub fn grok_binary() -> PathBuf {
|
||||
}
|
||||
}
|
||||
|
||||
let binary = local_grok_binary_path();
|
||||
ensure_local_grok_binary(&binary);
|
||||
let binary = local_kigi_binary_path();
|
||||
ensure_local_kigi_binary(&binary);
|
||||
binary
|
||||
}
|
||||
|
||||
@@ -149,14 +149,14 @@ pub fn git_workdir() -> TempDir {
|
||||
dir
|
||||
}
|
||||
|
||||
/// Point grok at the mock server with a fake API key and telemetry disabled.
|
||||
/// Point kigi 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
|
||||
// HOME alone does not sandbox kigi 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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Headless mode (`grok -p`) test runner.
|
||||
//! Headless mode (`kigi -p`) test runner.
|
||||
//!
|
||||
//! Runs the grok binary as a subprocess with the mock server, captures output.
|
||||
//! Runs the kigi binary as a subprocess with the mock server, captures output.
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::ExitStatus;
|
||||
@@ -9,7 +9,7 @@ use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncReadExt as _;
|
||||
|
||||
use crate::env::{grok_binary, test_env_cmd_tokio};
|
||||
use crate::env::{kigi_binary, test_env_cmd_tokio};
|
||||
use crate::mock_server::MockInferenceServer;
|
||||
|
||||
pub struct HeadlessResult {
|
||||
@@ -21,7 +21,7 @@ pub struct HeadlessResult {
|
||||
|
||||
const HEADLESS_TIMEOUT_SECS: u64 = 60;
|
||||
|
||||
/// Run `grok` with the given args against the mock server, with a 60s timeout.
|
||||
/// Run `kigi` with the given args against the mock server, with a 60s timeout.
|
||||
/// Uses an isolated HOME and disables telemetry.
|
||||
pub async fn run_headless(
|
||||
server: &MockInferenceServer,
|
||||
@@ -29,7 +29,7 @@ pub async fn run_headless(
|
||||
cwd: &Path,
|
||||
) -> HeadlessResult {
|
||||
let home = TempDir::new().expect("create temp home");
|
||||
let mut cmd = tokio::process::Command::new(grok_binary());
|
||||
let mut cmd = tokio::process::Command::new(kigi_binary());
|
||||
cmd.args(args)
|
||||
.current_dir(cwd)
|
||||
.stdin(std::process::Stdio::null())
|
||||
@@ -41,10 +41,10 @@ pub async fn run_headless(
|
||||
}
|
||||
|
||||
pub async fn run_headless_with_cmd(mut cmd: tokio::process::Command) -> HeadlessResult {
|
||||
let binary = grok_binary();
|
||||
let binary = kigi_binary();
|
||||
let mut child = cmd
|
||||
.spawn()
|
||||
.unwrap_or_else(|e| panic!("failed to spawn grok binary at {}: {e}", binary.display()));
|
||||
.unwrap_or_else(|e| panic!("failed to spawn kigi binary at {}: {e}", binary.display()));
|
||||
|
||||
let stdout = child.stdout.take().expect("child stdout missing");
|
||||
let stderr = child.stderr.take().expect("child stderr missing");
|
||||
@@ -70,7 +70,7 @@ pub async fn run_headless_with_cmd(mut cmd: tokio::process::Command) -> Headless
|
||||
{
|
||||
Ok(result) => (
|
||||
result.unwrap_or_else(|e| {
|
||||
panic!("failed to wait for grok binary {}: {e}", binary.display())
|
||||
panic!("failed to wait for kigi binary {}: {e}", binary.display())
|
||||
}),
|
||||
false,
|
||||
),
|
||||
@@ -78,7 +78,7 @@ pub async fn run_headless_with_cmd(mut cmd: tokio::process::Command) -> Headless
|
||||
let _ = child.kill().await;
|
||||
let status = child.wait().await.unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"failed to kill timed out grok binary {}: {e}",
|
||||
"failed to kill timed out kigi binary {}: {e}",
|
||||
binary.display()
|
||||
)
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Leader-mode (`grok agent --leader stdio`) test harness.
|
||||
//! Leader-mode (`kigi agent --leader stdio`) test harness.
|
||||
//!
|
||||
//! Spawns the real binary as a stdio client whose bridge elects a leader
|
||||
//! subprocess hosting the actual sessions, speaks ACP over pipes, and
|
||||
@@ -14,16 +14,16 @@ use agent_client_protocol::{self as acp, Agent as _};
|
||||
use kigi_acp_lib::LineBufferedRead;
|
||||
use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};
|
||||
|
||||
use crate::env::grok_binary;
|
||||
use crate::env::kigi_binary;
|
||||
use crate::mock_server::MockInferenceServer;
|
||||
use crate::process::spawn_piped_with_stderr_capture;
|
||||
|
||||
/// Env var naming the binary that elects/hosts the leader in a two-binary
|
||||
/// (version-skew) test. Falls back to [`grok_binary`]'s resolution.
|
||||
/// (version-skew) test. Falls back to [`kigi_binary`]'s resolution.
|
||||
pub const LEADER_BINARY_ENV: &str = "KIGI_BINARY_LEADER";
|
||||
|
||||
/// Env var naming the binary for the second (usually newer) client in a
|
||||
/// two-binary test. Falls back to [`grok_binary`]'s resolution.
|
||||
/// two-binary test. Falls back to [`kigi_binary`]'s resolution.
|
||||
pub const CLIENT_BINARY_ENV: &str = "KIGI_BINARY_CLIENT";
|
||||
|
||||
fn role_binary(env_key: &str) -> PathBuf {
|
||||
@@ -32,17 +32,17 @@ fn role_binary(env_key: &str) -> PathBuf {
|
||||
assert!(p.exists(), "{env_key} does not exist: {}", p.display());
|
||||
return p;
|
||||
}
|
||||
grok_binary()
|
||||
kigi_binary()
|
||||
}
|
||||
|
||||
/// Binary for the leader-electing side of a version-skew test
|
||||
/// (`KIGI_BINARY_LEADER`, else the shared [`grok_binary`] resolution).
|
||||
/// (`KIGI_BINARY_LEADER`, else the shared [`kigi_binary`] resolution).
|
||||
pub fn leader_binary() -> PathBuf {
|
||||
role_binary(LEADER_BINARY_ENV)
|
||||
}
|
||||
|
||||
/// Binary for the client side of a version-skew test (`KIGI_BINARY_CLIENT`,
|
||||
/// else the shared [`grok_binary`] resolution).
|
||||
/// else the shared [`kigi_binary`] resolution).
|
||||
pub fn client_binary() -> PathBuf {
|
||||
role_binary(CLIENT_BINARY_ENV)
|
||||
}
|
||||
@@ -93,7 +93,7 @@ impl acp::Client for LeaderAcpClient {
|
||||
}
|
||||
|
||||
async fn ext_notification(&self, args: acp::ExtNotification) -> acp::Result<()> {
|
||||
if &*args.method == "x.ai/leader_reconnected" {
|
||||
if &*args.method == "kigi/leader_reconnected" {
|
||||
self.capture
|
||||
.reconnected_count
|
||||
.fetch_add(1, Ordering::SeqCst);
|
||||
@@ -102,7 +102,7 @@ impl acp::Client for LeaderAcpClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `grok agent --leader stdio` client subprocess speaking ACP over pipes.
|
||||
/// A `kigi agent --leader stdio` client subprocess speaking ACP over pipes.
|
||||
/// The leader subprocess it elects hosts the actual sessions.
|
||||
pub struct LeaderStdioClient {
|
||||
pub conn: acp::ClientSideConnection,
|
||||
@@ -114,7 +114,7 @@ pub struct LeaderStdioClient {
|
||||
|
||||
impl LeaderStdioClient {
|
||||
pub async fn spawn(server: &MockInferenceServer, cwd: &Path, home: &Path) -> Self {
|
||||
Self::spawn_with_binary(&grok_binary(), server, cwd, home).await
|
||||
Self::spawn_with_binary(&kigi_binary(), server, cwd, home).await
|
||||
}
|
||||
|
||||
/// [`Self::spawn`] with an explicit binary, for two-binary version-skew
|
||||
@@ -128,7 +128,7 @@ impl LeaderStdioClient {
|
||||
let mut cmd = tokio::process::Command::new(binary);
|
||||
cmd.args(["agent", "--leader", "stdio"])
|
||||
.current_dir(cwd)
|
||||
// Hermetic env: the developer's shell may export GROK_* vars
|
||||
// Hermetic env: the developer's shell may export KIGI_* vars
|
||||
// (e.g. KIGI_LEADER_SOCKET pointing at a REAL leader on this
|
||||
// machine). env_clear + explicit allowlist guarantees the test
|
||||
// can never touch a leader outside its sandbox home.
|
||||
@@ -330,8 +330,8 @@ pub async fn wait_for_new_leader(home: &Path, old_pid: u32, timeout: Duration) -
|
||||
|
||||
/// Wait for evidence that the bridge finished its reconnect replay.
|
||||
///
|
||||
/// The `x.ai/leader_reconnected` ext notification is dropped by the typed
|
||||
/// `ClientSideConnection` (bare `x.ai/*` methods are rejected by the ACP
|
||||
/// The `kigi/leader_reconnected` ext notification is dropped by the typed
|
||||
/// `ClientSideConnection` (bare `kigi/*` methods are rejected by the ACP
|
||||
/// decoder), so we wait for the replayed `session/load` to emit session
|
||||
/// notifications instead: the notification count rises above `baseline`.
|
||||
pub async fn wait_for_replay_notifications(
|
||||
|
||||
@@ -5,18 +5,18 @@
|
||||
unreachable_code,
|
||||
dead_code
|
||||
)]
|
||||
//! Shared test utilities for grok-build crates: mock inference server, SSE
|
||||
//! Shared test utilities for kigi crates: mock inference server, SSE
|
||||
//! generators, ACP stdio client, headless runner, env sandbox.
|
||||
//!
|
||||
//! Provides:
|
||||
//! - [`MockInferenceServer`] — Mock /v1/chat/completions + /v1/responses with request logging
|
||||
//! - [`GrokStdioClient`] — ACP client that drives `grok agent stdio` as a subprocess
|
||||
//! - [`KigiStdioClient`] — ACP client that drives `kigi agent stdio` as a subprocess
|
||||
//! - [`RawStdioClient`] — raw-wire ACP driver for bytes the typed client can't
|
||||
//! produce (Foundation `\/` methods, string UUID ids)
|
||||
//! - [`leader::LeaderStdioClient`] — ACP client that drives `grok agent --leader stdio` (unix)
|
||||
//! - [`run_headless`] — Run `grok -p` against the mock server and capture output
|
||||
//! - [`leader::LeaderStdioClient`] — ACP client that drives `kigi agent --leader stdio` (unix)
|
||||
//! - [`run_headless`] — Run `kigi -p` against the mock server and capture output
|
||||
//! - [`git_workdir`] — Create a temp directory with git repo (forces libgit2 init)
|
||||
//! - [`grok_binary`] — Resolve the grok binary path (KIGI_BINARY env or cargo_bin)
|
||||
//! - [`kigi_binary`] — Resolve the kigi binary path (KIGI_BINARY env or cargo_bin)
|
||||
//! - [`spawn_counting_server`] — Connection-counting HTTP/1.1 server for wire/pooling tests
|
||||
//! - [`uds_proxy::UdsProxy`] — Frame-aware fault-injection proxy for leader IPC sockets (unix)
|
||||
pub mod acp_client;
|
||||
@@ -31,9 +31,9 @@ pub mod scripted;
|
||||
pub mod sse;
|
||||
#[cfg(unix)]
|
||||
pub mod uds_proxy;
|
||||
pub use acp_client::{GrokStdioClient, RawStdioClient};
|
||||
pub use acp_client::{KigiStdioClient, RawStdioClient};
|
||||
pub use counting_server::spawn_counting_server;
|
||||
pub use env::{EnvGuard, git_workdir, grok_binary};
|
||||
pub use env::{EnvGuard, git_workdir, kigi_binary};
|
||||
pub use headless::{
|
||||
HeadlessResult, assert_headless_success, assert_no_crashes, run_headless,
|
||||
run_headless_with_cmd, stderr_tail,
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::sync::Arc;
|
||||
|
||||
/// Pipe all three stdio handles, `kill_on_drop`, spawn, and drain the child's
|
||||
/// stderr into the returned buffer on a background task. The one spawn path
|
||||
/// shared by every subprocess harness in this crate (`GrokStdioClient`,
|
||||
/// shared by every subprocess harness in this crate (`KigiStdioClient`,
|
||||
/// `RawStdioClient`, `leader::LeaderStdioClient`); env/args stay with the
|
||||
/// callers, whose hermeticity models differ (sandbox-inherit vs `env_clear`).
|
||||
/// The drain future is `Send`, so this works on and off a `LocalSet`.
|
||||
@@ -21,7 +21,7 @@ pub(crate) fn spawn_piped_with_stderr_capture(
|
||||
let program = cmd.as_std().get_program().to_string_lossy().into_owned();
|
||||
let mut child = cmd
|
||||
.spawn()
|
||||
.unwrap_or_else(|e| panic!("failed to spawn grok at {program}: {e}"));
|
||||
.unwrap_or_else(|e| panic!("failed to spawn kigi at {program}: {e}"));
|
||||
|
||||
let stderr = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let stderr_capture = stderr.clone();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! SSE stream generators for mock inference endpoints.
|
||||
//!
|
||||
//! These produce the exact wire format that the grok sampling client expects,
|
||||
//! These produce the exact wire format that the kigi sampling client expects,
|
||||
//! validated against the real sampling client.
|
||||
|
||||
use axum::response::sse::Event;
|
||||
|
||||
Reference in New Issue
Block a user