docs(comments): rewrite comments across all crates to the guidelines

Sweep every first-party crate source (1956 .rs files) to the project comment
guidelines: delete redundant restatements, decorative banners, change
narration, and end-of-line comments; keep and tighten the crucial ones
(invariants, bug rationale, SAFETY blocks, ported-source attribution).

No functional code changed. Every edit is proven comment-only against the
prior tree by a comment-stripping lexer (string/char/raw-string aware) plus a
separate doctest-fence check. Where removing a comment made rustfmt or clippy
want to re-lay-out adjacent code, the minimal triggering comment is restored so
code tokens stay byte-identical.

Gates green: cargo fmt --all --check (0 diffs), cargo check and cargo clippy
--workspace --all-targets (0 warnings).

Adds scripts/check_codegen_comment_guidelines.py — the enforcement gate for
these guidelines (flags banners, end-of-line comments, change narration, and
commented-out code).
This commit is contained in:
2026-07-23 16:55:39 -04:00
parent ff0fb56c67
commit a02b555e66
1458 changed files with 10729 additions and 21750 deletions
@@ -1,5 +1,4 @@
use std::fs;
// OpenOptions is only used by the Unix-only profiler implementation.
#[cfg(unix)]
use std::fs::OpenOptions;
use std::path::{Path, PathBuf};
@@ -20,8 +19,9 @@ const AUTO_PATH_RETRY_LIMIT: u32 = 32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProfileArtifactFormat {
/// Legacy: kept so new clients can still decode adverts from old leaders.
/// New binaries no longer produce SVG (that required inferno, CDDL-1.0).
/// Decode-only: kept so new clients can still read adverts from old
/// leaders. Nothing emits SVG — rendering one would pull in inferno
/// (CDDL-1.0).
Svg,
/// Folded stacks (`thread;frame;… count` per line). Not advertised yet —
/// see `platform::profile_formats()` for the two-phase wire migration.
@@ -180,9 +180,8 @@ pub struct CpuProfileManager {
stopping: Option<StoppingCpuProfile>,
stop_completion_tx: watch::Sender<bool>,
_stop_completion_guard: watch::Receiver<bool>,
/// When true, forces all capability queries to report unsupported regardless
/// of the actual platform. Used in tests to exercise the unsupported-build
/// code path deterministically on any host platform.
/// Test hook: forces every capability query to report unsupported so the
/// unsupported-build path can be exercised on any host platform.
force_unsupported: bool,
}
@@ -336,11 +335,9 @@ impl CpuProfileManager {
/// Finalize an active CPU profile synchronously during shutdown.
///
/// This is a local convenience helper for direct manager callers. It only
/// finalizes a currently active profile owned by this caller. If a stop is
/// already in progress, this returns `Ok(None)` and does not coordinate with
/// that in-flight stop. Callers that need process-wide shutdown coordination
/// must separately wait for stop completion.
/// A stop already in progress yields `Ok(None)` without coordinating with
/// that in-flight stop, so callers needing process-wide shutdown
/// coordination must also wait on [`Self::subscribe_stop_completion`].
pub fn finalize_on_shutdown(&mut self) -> Result<Option<CpuProfileStopResult>, ControlError> {
let stop_handle = self.take_shutdown_stop_handle()?;
match stop_handle {
@@ -428,10 +425,10 @@ fn resolve_svg_path(
}
fn derive_output_path(output: &Path, started_at: &str) -> Result<PathBuf, ControlError> {
// Honor explicit artifact paths (`.folded`/`.txt`). An explicit `.svg`
// path — from old client invocations or muscle memory — keeps its
// location but is redirected to `.folded`: the artifact is folded stacks
// now, and writing text into an `.svg`-named file would just corrupt it.
// Explicit `.folded`/`.txt` paths are honored as-is. An explicit `.svg`
// path — from old clients or muscle memory — keeps its directory but
// switches to a `.folded` extension, since the artifact is folded stacks
// and text in an `.svg`-named file would only mislead.
if output
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("folded") || ext.eq_ignore_ascii_case("txt"))
@@ -563,8 +560,8 @@ mod platform {
struct PprofProfilerEngine {
guard: pprof::ProfilerGuard<'static>,
// Named `svg_path` historically; now points at a `.folded` artifact.
// The wire protocol keeps the `svg_path` field name for compat.
// Points at a `.folded` artifact; the name tracks the wire protocol's
// `svg_path` field, which stays for compat with old clients.
svg_path: PathBuf,
}
@@ -654,11 +651,11 @@ mod platform {
}
pub(super) fn profile_formats() -> &'static [ProfileArtifactFormat] {
// Advertise nothing for now: old clients deserialize this enum
// strictly inside the Registered handshake, so a new variant (e.g.
// `folded`) would break their connect entirely. Start advertising
// `Folded` once binaries that know the variant have saturated the
// fleet. The artifact itself is already folded stacks.
// Advertise nothing: old clients deserialize this enum strictly inside
// the Registered handshake, so seeing `folded` breaks their connect
// entirely. Advertise `Folded` only once binaries that know the
// variant have saturated the fleet; the artifact is folded stacks
// either way.
&[]
}
+3 -6
View File
@@ -1,7 +1,4 @@
//! Environment helpers for the shell crate family.
//!
//! Kigi has exactly one environment; endpoint defaults live in the
//! [`kigi_env`] leaf crate so sibling crates can share them without
//! depending on this crate. This module re-exports the shared test
//! helper.
//! Endpoint defaults live in the [`kigi_env`] leaf crate so sibling crates can
//! share them without depending on this one; only the shared test helper is
//! re-exported here.
pub use kigi_env::EnvVarGuard;
+3 -3
View File
@@ -1,6 +1,6 @@
//! Foundation modules shared by the kigi shell crate family. Extracted from
//! `kigi-shell` (which re-exports them at their original paths) so they
//! build in parallel and stop rebuilding on shell edits.
//! Foundation modules shared by the kigi shell crate family. `kigi-shell`
//! re-exports them at their original paths; keeping them in a leaf crate lets
//! them build in parallel and avoids a rebuild on every shell edit.
pub mod cpu_profile;
pub mod env;
@@ -1,26 +1,12 @@
//! Event ID generation for session notifications.
//!
//! Provides a globally unique event ID format `{session_id}-{counter}` that is
//! used for deduplication in the relay. The counter is monotonically increasing
//! across the entire agent process, ensuring event IDs are always comparable.
//! Event IDs of the form `{session_id}-{counter}`, used for deduplication in
//! the relay. The counter is shared by every session in the agent process and
//! only ever increases, so the relay can order ids numerically by parsing the
//! counter suffix.
use std::sync::atomic::{AtomicU64, Ordering};
/// Global counter for event ID generation.
/// Shared across all sessions to ensure monotonically increasing IDs.
static EVENT_COUNTER: AtomicU64 = AtomicU64::new(0);
/// Generates a unique event ID for correlation across agent/relay/client.
///
/// Format: `{session_id}-{counter}` where counter is a monotonically increasing
/// global counter. This format allows the relay to compare event IDs numerically
/// by extracting the counter suffix.
///
/// # Arguments
/// * `session_id` - The session ID to include in the event ID
///
/// # Returns
/// A unique event ID string in the format `{session_id}-{counter}`
pub fn generate_event_id(session_id: &str) -> String {
let count = EVENT_COUNTER.fetch_add(1, Ordering::SeqCst);
format!("{}-{}", session_id, count)
@@ -91,16 +77,13 @@ mod tests {
fn test_generate_event_id_format() {
let id = generate_event_id("test-session-123");
assert!(id.starts_with("test-session-123-"));
// Should end with a valid number
let _counter: u64 = id.rsplit('-').next().unwrap().parse().unwrap();
}
#[test]
fn ensure_event_counter_at_least_only_raises() {
// Re-seeding to a high floor makes the next id continue past it — this
// is what keeps `--resume` from minting ids below the replayed maximum.
// Uses a very high floor so concurrent tests (which only ever raise the
// shared counter via fetch_add/fetch_max) cannot push it back down.
// The floor is huge so concurrent tests sharing the process-global
// counter cannot drift above it and invalidate the assertions.
ensure_event_counter_at_least(5_000_000);
let counter1: u64 = generate_event_id("sess")
.rsplit('-')
@@ -113,7 +96,6 @@ mod tests {
"next id must be at/above the seeded floor, got {counter1}"
);
// A lower floor is a no-op (fetch_max never decreases the counter).
ensure_event_counter_at_least(1);
let counter2: u64 = generate_event_id("sess")
.rsplit('-')
@@ -129,7 +111,6 @@ mod tests {
#[test]
fn ensure_event_id_meta_stamps_none_and_merges_existing() {
// None meta: a fresh object with eventId + timestamp is created.
let mut meta = None;
ensure_event_id_meta("sess-x", &mut meta);
let obj = meta.as_ref().unwrap();
@@ -140,7 +121,6 @@ mod tests {
);
assert!(obj["agentTimestampMs"].is_i64());
// Existing meta without eventId: fields are merged, not replaced.
let mut meta = serde_json::json!({ "custom": true }).as_object().cloned();
ensure_event_id_meta("sess-x", &mut meta);
let obj = meta.as_ref().unwrap();
@@ -173,7 +153,6 @@ mod tests {
let counter2: u64 = id2.rsplit('-').next().unwrap().parse().unwrap();
let counter3: u64 = id3.rsplit('-').next().unwrap().parse().unwrap();
// Counters should be monotonically increasing
assert!(counter2 > counter1);
assert!(counter3 > counter2);
}
@@ -64,7 +64,7 @@ pub fn matches_trusted_base_url(candidate: &str, trusted_base: &str) -> bool {
&& path_matches
}
/// True for subscription coding-API URLs (the compiled production endpoint;
/// deliberately NOT the env-overridable [`kigi_env::coding_api_base_url`] so a
/// Deliberately NOT the env-overridable [`kigi_env::coding_api_base_url`] so a
/// runtime override can't widen this trust set).
pub fn is_production_coding_api_url(url: &str) -> bool {
matches_trusted_base_url(url, kigi_env::PRODUCTION_ENDPOINTS.coding_api_base_url)
@@ -135,9 +135,10 @@ pub fn set_windows_secure_permissions(path: &Path) -> io::Result<()> {
// Create explicit access entry for current user only
// GENERIC_ALL = 0x10000000
let explicit_access = EXPLICIT_ACCESS_W {
grfAccessPermissions: 0x10000000, // GENERIC_ALL
grfAccessPermissions: 0x10000000,
grfAccessMode: SET_ACCESS,
grfInheritance: ACE_FLAGS(0), // No inheritance for files
// No inheritance for files
grfInheritance: ACE_FLAGS(0),
Trustee: TRUSTEE_W {
pMultipleTrustee: std::ptr::null_mut(),
MultipleTrusteeOperation:
@@ -168,8 +169,10 @@ pub fn set_windows_secure_permissions(path: &Path) -> io::Result<()> {
PCWSTR::from_raw(wide_path.as_ptr()),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
None, // psidOwner: not changing the owner
None, // psidGroup: not changing the primary group
// psidOwner: not changing the owner
None,
// psidGroup: not changing the primary group
None,
Some(new_acl),
None,
);
@@ -60,7 +60,7 @@ pub fn pick_and_advance(tips: &[String], kigi_home: &Path) -> Option<String> {
mod tests {
use super::*;
// ── pick_and_advance ──────────────────────────────────────────────────────
// pick_and_advance
#[test]
fn empty_list_returns_none() {
@@ -98,9 +98,11 @@ mod tests {
fn cursor_persists_across_calls() {
let dir = tempfile::tempdir().unwrap();
let tips = vec!["x".to_string(), "y".to_string()];
pick_and_advance(&tips, dir.path()); // cursor → 1
// cursor → 1
pick_and_advance(&tips, dir.path());
assert_eq!(load_cursor(dir.path()), 1);
pick_and_advance(&tips, dir.path()); // cursor → 2
// cursor → 2
pick_and_advance(&tips, dir.path());
assert_eq!(load_cursor(dir.path()), 2);
}
@@ -119,9 +121,12 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
// Start with 3 tips, advance cursor to 3
let tips3 = vec!["a".to_string(), "b".to_string(), "c".to_string()];
pick_and_advance(&tips3, dir.path()); // cursor 0 → 1
pick_and_advance(&tips3, dir.path()); // cursor 1 → 2
pick_and_advance(&tips3, dir.path()); // cursor 23
// cursor 0 → 1
pick_and_advance(&tips3, dir.path());
// cursor 12
pick_and_advance(&tips3, dir.path());
// cursor 2 → 3
pick_and_advance(&tips3, dir.path());
// remote settings pushes a 5-tip list; cursor=3, 3%5=3 → "d"
let tips5 = vec![
@@ -134,7 +139,7 @@ mod tests {
assert_eq!(pick_and_advance(&tips5, dir.path()).as_deref(), Some("d"));
}
// ── load_cursor / save_cursor ─────────────────────────────────────────────
// load_cursor / save_cursor
#[test]
fn load_cursor_returns_zero_for_corrupt_file() {
@@ -1,18 +1,12 @@
//! OS version string for the `<user_info>` preamble.
//!
//! Emits `OS Version: <kernel> <release>` (e.g. `darwin 24.6.0`,
//! `linux 6.5.0-...`).
//!
//! `std::env::consts::OS` returns `"macos"` / `"linux"` -- the OS *family*,
//! not the kernel name and not the release. This module wraps `libc::uname`
//! (Unix) with a `std::env::consts::OS` fallback (any non-unix platform or
//! syscall failure) so the result is always a non-empty string we can drop
//! into the placeholder bag.
//! `std::env::consts::OS` returns `"macos"` / `"linux"` -- the OS *family*, not
//! the kernel name and not the release. This module wraps `libc::uname` (Unix)
//! and keeps `std::env::consts::OS` only as the last-resort fallback, so the
//! result is always a non-empty string.
/// Return `"<kernel-lowercased> <release>"` for the `os_family` placeholder
/// (e.g. `"darwin 24.6.0"` on macOS Sonoma 14.6, `"linux 6.5.0-1024-aws"` on
/// Linux). Falls back to `std::env::consts::OS` when uname is unavailable
/// or fails -- callers always get a non-empty string.
/// Returns `"<kernel-lowercased> <release>"`, e.g. `"darwin 24.6.0"` or
/// `"linux 6.5.0-1024-aws"`.
pub fn os_kernel_and_release() -> String {
#[cfg(unix)]
{
@@ -52,9 +46,6 @@ fn uname_unix() -> Option<String> {
Some(format!("{sysname} {release}"))
}
/// Convert a NUL-terminated `c_char` array (as returned in `utsname` fields)
/// into an owned `String`. Returns `None` if the bytes are not valid UTF-8 or
/// the array lacks a NUL terminator.
#[cfg(unix)]
fn c_char_array_to_string(bytes: &[libc::c_char]) -> Option<String> {
use std::ffi::CStr;
@@ -72,9 +63,6 @@ fn c_char_array_to_lowercase_string(bytes: &[libc::c_char]) -> Option<String> {
c_char_array_to_string(bytes).map(|s| s.to_lowercase())
}
/// Return `"windows <major>.<minor>.<build>"` (e.g. `"windows 10.0.22631.4890"`)
/// by parsing the output of `cmd /C ver`. Falls back to `None` on any failure
/// so callers get the `std::env::consts::OS` default.
#[cfg(windows)]
fn windows_version() -> Option<String> {
use std::process::Command;
@@ -102,25 +90,19 @@ fn windows_version() -> Option<String> {
mod tests {
use super::*;
/// On any platform the function produces a non-empty string. Exact
/// content varies by host so we only assert the shape.
#[test]
fn os_kernel_and_release_is_non_empty() {
let s = os_kernel_and_release();
assert!(!s.is_empty(), "os_kernel_and_release returned empty");
}
/// On Unix hosts the format is `<kernel> <release>` -- two
/// whitespace-separated tokens, both non-empty, both lowercase for
/// the kernel half.
#[cfg(unix)]
#[test]
fn os_kernel_and_release_unix_shape() {
let s = os_kernel_and_release();
// Skip the assertion if uname failed and we fell back to
// `std::env::consts::OS` (single token, e.g. "macos"). The
// fallback is correct behavior; the test just can't tell which
// path produced the value without re-calling uname itself.
// A single token means uname failed and the `std::env::consts::OS`
// fallback produced the value -- correct behavior, but the two-token
// shape below does not apply to it.
if !s.contains(' ') {
return;
}
@@ -136,15 +118,14 @@ mod tests {
);
}
/// On macOS specifically the kernel name is `darwin`. This is the
/// regression guard for the original bug ("OS Version: macos" vs
/// "OS Version: darwin 24.6.0").
/// Regression guard: macOS must report `darwin 24.6.0`, not the family
/// name `macos`.
#[cfg(target_os = "macos")]
#[test]
fn os_kernel_and_release_macos_says_darwin() {
let s = os_kernel_and_release();
// Skip if uname failed (fallback returns "macos"). On real CI/dev
// hardware this branch is never taken.
// Single token means the uname call failed and the fallback returned
// "macos". Never taken on real CI/dev hardware.
if !s.contains(' ') {
return;
}