rch-common 2.1.20

Shared types and utilities for Remote Compilation Helper
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! Remote Compilation Helper - Common Library
//!
//! Shared types, patterns, and utilities used by rch, rchd, and rch-wkr.

// Use deny instead of forbid to allow specific overrides for env var manipulation
// in tests and profile defaults (env::set_var/remove_var are unsafe in Rust 2024)
#![deny(unsafe_code)]

use std::sync::OnceLock;

/// Shared Linux launch and cancellation protocol; callers select their receipt.
pub const REMOTE_PROCESS_IDENTITY_SCRIPT: &str = include_str!("remote_process.sh");

pub mod admission_recommendation;
pub mod admission_rejection;
pub mod admit_preflight;
pub mod api;
pub mod artifact_cost;
pub mod artifact_pattern;
pub mod artifact_verify;
pub mod binary_hash;
pub mod bypass_record;
pub mod bypass_recovery;
pub mod capability_probe;
pub mod cargo_path_deps;
pub mod classifier_drift;
pub mod closure_explain;
pub mod config;
pub mod dependency_closure_planner;
pub mod discovery;
pub mod disk_pressure_report;
pub mod disk_reclaim;
pub mod e2e;
pub mod errors;
pub mod exec_misuse;
pub mod exec_policy;
pub mod exec_response;
pub mod fleet_diff;
pub mod fleet_provenance;
pub mod fleet_smoke_profile;
pub mod fleet_status;
pub mod force_resync;
pub mod gc_roots;
pub mod hooks;
pub mod incident;
pub mod incident_ledger;
pub mod job_identity;
pub mod job_recovery;
pub mod log_retention;
pub mod logging;
pub mod mock;
pub mod mock_worker;
pub mod orphan_quarantine;
pub mod path_topology;
pub mod patterns;
#[cfg(test)]
mod patterns_security_test;
pub mod placement;
pub mod pooled_target_key;
pub mod process_identity;
pub mod proof_handoff;
pub mod proof_intent;
pub mod proof_policy;
pub mod proof_replay;
#[cfg(test)]
mod proptest_tests;
pub mod protocol;
pub mod queue_contract;
pub mod readiness;
pub mod redaction;
pub mod remediation_config;
pub mod remediation_view;
#[cfg(unix)]
pub mod remote_compilation;
#[cfg(unix)]
pub mod remote_verification;
pub mod repo_updater_contract;
pub mod rsync_flavor;
pub mod schema_versions;
#[cfg(unix)]
pub mod ssh;
#[cfg(all(test, unix))]
mod ssh_timeout_test;
pub mod ssh_utils;
pub mod stale_target_reap;
pub mod storm_control;
pub mod telemetry_explain;
pub mod telemetry_freshness;
pub mod test_change;
pub mod testing;
pub mod toolchain;
pub mod transfer_hardening;
pub mod types;
pub mod ui;
pub mod util;
pub mod worker_config_validation;
pub mod worker_facts;

pub const BUILD_COMMIT_ENV_VARS: &[&str] = &[
    "RCH_GIT_COMMIT",
    "VERGEN_GIT_SHA",
    "GIT_COMMIT",
    "GITHUB_SHA",
];

/// The validated build revision stamped into this binary, if any.
///
/// `build.rs` validates the commit and blanks the ambient aliases; this
/// re-applies the same grammar so a value the build script rejected can never
/// be displayed as a build revision (issue #76).
pub fn build_commit() -> Option<&'static str> {
    first_build_commit([
        option_env!("RCH_GIT_COMMIT"),
        option_env!("VERGEN_GIT_SHA"),
        option_env!("GIT_COMMIT"),
        option_env!("GITHUB_SHA"),
    ])
}

fn first_build_commit<'a>(
    candidates: impl IntoIterator<Item = Option<&'a str>>,
) -> Option<&'a str> {
    candidates
        .into_iter()
        .flatten()
        .map(str::trim)
        .find(|value| is_build_commit_stamp(value))
}

/// Same grammar as `rch-common/build.rs`: a 7..=64 hex commit, optionally
/// suffixed `-dirty` or `-overlay-<64 hex fingerprint>` (build-source stamps).
fn is_build_commit_stamp(value: &str) -> bool {
    fn is_commit_hash(value: &str) -> bool {
        (7..=64).contains(&value.len()) && value.bytes().all(|byte| byte.is_ascii_hexdigit())
    }
    is_commit_hash(value)
        || value.strip_suffix("-dirty").is_some_and(is_commit_hash)
        || value
            .split_once("-overlay-")
            .is_some_and(|(commit, fingerprint)| {
                is_commit_hash(commit)
                    && fingerprint.len() == 64
                    && fingerprint.bytes().all(|byte| byte.is_ascii_hexdigit())
            })
}

pub fn build_version_value() -> String {
    build_version_value_with_commit(env!("CARGO_PKG_VERSION"), build_commit())
}

pub fn build_version_value_static() -> &'static str {
    static VERSION_VALUE: OnceLock<String> = OnceLock::new();

    VERSION_VALUE.get_or_init(build_version_value).as_str()
}

pub fn build_version_value_with_commit(package_version: &str, commit: Option<&str>) -> String {
    let mut value = package_version.to_string();

    if let Some(commit) = commit.map(str::trim).filter(|value| !value.is_empty()) {
        value.push_str(" (commit ");
        let (revision, suffix) = commit
            .split_once('-')
            .map_or((commit, None), |(revision, suffix)| {
                (revision, Some(suffix))
            });
        value.push_str(short_commit(revision));
        if let Some(suffix) = suffix {
            value.push('-');
            value.push_str(suffix);
        }
        value.push(')');
    }

    value
}

fn short_commit(commit: &str) -> &str {
    commit
        .char_indices()
        .nth(12)
        .map_or(commit, |(index, _)| &commit[..index])
}

pub use artifact_cost::{
    ArtifactCostReport, ArtifactPhaseTimings, GlobAdvice, RetrievalMode, assess_glob_expansion,
    compute_artifact_cost, is_broad_recursive_glob,
};
pub use artifact_pattern::{
    ARTIFACT_OUTPUT_ROOTS, ArtifactPatternRewrite, ArtifactRetrievalDiagnostics,
    artifact_dest_is_safe, rewrite_artifact_pattern,
};
pub use artifact_verify::{
    ArtifactManifest, FileHash, VerificationFailure, VerificationResult, compute_file_hash,
    create_manifest, verify_artifacts,
};
pub use binary_hash::{
    BinaryHashResult, binaries_equivalent, binary_contains_marker, compute_binary_hash,
};
pub use bypass_record::{
    AutoRejoinCriteria, BypassBackoff, BypassFailureClass, BypassRecord, BypassRecordStore,
    BypassState, DisabledMigration, DisabledWorkerSnapshot, MAX_DIAGNOSTIC_CHARS,
    bypass_record_schema, bypass_record_schema_version, classify_disable_reason,
    default_bypass_record_path, migrate_disabled_worker, truncate_diagnostic,
};
pub use bypass_recovery::{
    CanaryDecision, CanaryOutcome, ProbeDecision, RecoveryProbe, decide_canary, decide_probe,
};
pub use cargo_path_deps::{
    CargoPathDependencyEdge, CargoPathDependencyError, CargoPathDependencyErrorKind,
    CargoPathDependencyGraph, CargoPathDependencyPackage, CargoPathMaterializationClosure,
    resolve_cargo_path_dependency_graph, resolve_cargo_path_dependency_graph_with_policy,
    resolve_cargo_path_materialization_closure,
    resolve_cargo_path_materialization_closure_with_policy,
};
pub use closure_explain::{
    ClosureExplainEntry, ClosureExplainReport, RootConvergence, RootSyncOutcome, derive_outcome,
    explain_closure,
};
pub use dependency_closure_planner::{
    DependencyClosurePlan, DependencyClosurePlanState, DependencyPlanIssue, DependencyRiskClass,
    DependencySyncAction, DependencySyncMetadata, DependencySyncReason,
    build_dependency_closure_plan, build_dependency_closure_plan_with_policy,
    plan_dependency_closure_from_graph,
};
pub use force_resync::{
    ForceResyncPlan, ForceResyncReport, InvalidationAction, RefusedInvalidation, ResyncOutcome,
    StaleRoot, apply_force_resync, is_safe_invalidation_target, plan_force_resync,
};
pub use gc_roots::{
    RCH_CARGO_CACHE_PREFIX, RCH_CARGO_HOME_BASE_VAR, RCH_CARGO_HOME_PREFIX,
    remote_cargo_cache_expr, remote_cargo_home_base_prelude, remote_cargo_home_expr,
};
pub use logging::{LogConfig, LogFormat, LoggingGuards, init_logging, init_logging_with_layer};
pub use mock_worker::MockWorkerServer;
pub use path_topology::{
    DEFAULT_ALIAS_PROJECT_ROOT, DEFAULT_CANONICAL_PROJECT_ROOT, NormalizationDecision,
    NormalizedProjectPath, PathNormalizationError, PathNormalizationErrorKind, PathTopologyPolicy,
    normalize_project_path, normalize_project_path_with_policy,
};
pub use patterns::{
    Classification, ClassificationDetails, ClassificationTier, CompilationKind, TierDecision,
    classify_command, classify_command_detailed, compound_local_compilation_segments,
    declined_compilation_due_to_structure, split_shell_commands,
};
pub use protocol::{HookInput, HookOutput, ToolInput};
pub use queue_contract::{
    AdmissionState, QueueContractOutcome, QueueContractResponse, QueueOptions, StartState,
    WaitResult, resolve_queue_contract,
};
pub use repo_updater_contract::{
    MockRepoUpdaterAdapter, REPO_UPDATER_ALIAS_PROJECTS_ROOT, REPO_UPDATER_CANONICAL_PROJECTS_ROOT,
    REPO_UPDATER_CONTRACT_SCHEMA_VERSION, REPO_UPDATER_DEFAULT_BINARY,
    REPO_UPDATER_MIN_SUPPORTED_VERSION, RepoUpdaterAdapter, RepoUpdaterAdapterCommand,
    RepoUpdaterAdapterContract, RepoUpdaterAdapterRequest, RepoUpdaterAdapterResponse,
    RepoUpdaterFailure, RepoUpdaterFailureKind, RepoUpdaterFallbackMode,
    RepoUpdaterIdempotencyGuarantee, RepoUpdaterJsonEnvelope, RepoUpdaterOutputFormat,
    RepoUpdaterResponseStatus, RepoUpdaterVersionCompatibility, RepoUpdaterVersionPolicy,
    build_invocation, classify_exit_code, evaluate_version_compatibility,
    map_failure_kind_to_error_code, repo_updater_envelope_schema, repo_updater_request_schema,
    repo_updater_response_schema,
};
// Platform-independent SSH utilities (available everywhere)
pub use ssh_utils::{
    CommandResult, EnvPrefix, build_env_prefix, is_retryable_transport_error,
    is_retryable_transport_error_text, shell_escape_value,
};
// Unix-only SSH client (uses openssh crate)
#[cfg(unix)]
pub use ssh::{KnownHostsPolicy, SshClient, SshOptions, SshPool};
pub use test_change::{TestChangeGuard, TestCodeChange};
pub use toolchain::{ToolchainInfo, wrap_command_with_color, wrap_command_with_toolchain};
pub use transfer_hardening::{
    FirstFailure, RetryDecision, RsyncFailureClass, classify_rsync_outcome, is_ephemeral_path,
};
pub use types::{
    AffinityConfig, ApiConfig, BoxRole, BuildCancellationMetadata, BuildCancellationWorkerHealth,
    BuildHeartbeatPhase, BuildHeartbeatRequest, BuildLocation, BuildRecord, BuildStats,
    CircuitBreakerConfig, CircuitState, CircuitStats, ColorMode, CommandPriority,
    CommandTimingBreakdown, CompilationConfig, CompilationMetrics, CompilationTimer,
    CompilationTimingBreakdown, DashboardConfig, DoctorConfig, DoctorWebhookEndpoint,
    DoctorWebhookFormat, DoctorWebhooksConfig, EnvironmentConfig, ExecutionConfig, FairnessConfig,
    FleetConfig, GeneralConfig, MetricsAggregator, OS_TAG_PREFIX, OutputConfig, OutputVisibility,
    PathTopologyConfig, RchConfig, ReleaseRequest, RemoteBuildJobs, RequiredRuntime, RetryConfig,
    SELECTION_RESPONSE_PROTOCOL_VERSION, SavedTimeStats, SelectedWorker, SelectionConfig,
    SelectionDiagnostics, SelectionReason, SelectionRequest, SelectionResponse, SelectionStrategy,
    SelectionWeightConfig, SelfHealingConfig, SelfHealingLogLevel, SelfTestConfig,
    SelfTestFailureAction, SelfTestWorkers, TransferConfig, WorkerCapabilities, WorkerConfig,
    WorkerId, WorkerSelectionDiagnostic, WorkerSelectionDiagnosticDecision, WorkerStatus,
    declared_os, default_socket_path, os_tag, validate_remote_base,
    x86_64_microarch_level_from_flags,
};

// Testing module re-exports
pub use testing::{TestLogEntry, TestLogger, TestPhase, TestResult};

// Config module re-exports
pub use config::{
    ConfigSource, ConfigValueSource, ConfigWarning, EnvError, EnvParser, Profile, Severity,
    Sourced, validate_config,
};

// Discovery module re-exports
pub use discovery::{
    DiscoveredHost, DiscoverySource, discover_all, parse_shell_aliases,
    parse_shell_aliases_content, parse_ssh_config, parse_ssh_config_content,
};

// UI module re-exports
pub use ui::{
    ErrorPanel, ErrorSeverity, Icons, IntoErrorPanel, OutputContext, RchTheme, ResultExt,
    anyhow_to_json, anyhow_to_panel, display_anyhow_error, display_error, display_error_with_code,
    error_to_json, error_to_panel,
};

// Incident schema re-exports
pub use capability_probe::{
    CapabilityRequirement, CapabilityVerdict, EligibilityVerdict, ProbeSpec, ProbedFacts,
    WorkerLiveness, assess_admissibility, assess_worker_eligibility, build_capability_probe_script,
    parse_capability_probe, remote_worker_binary_path,
};
pub use incident::{
    ControlState, IncidentEvent, IncidentEventType, IncidentReasonCode, IncidentSource,
    SelectedMode, incident_schema_version,
};
pub use incident_ledger::{
    IncidentFilter, IncidentLedger, IncidentLedgerConfig, LedgerReadStats, default_ledger_path,
};
pub use placement::{
    ControlDiagnostic, ControlDiagnosticLevel, ControlKind, PlacementControl, PlacementPlan,
    QueuePolicy, RequestedWorkerFacts, RequestedWorkerOutcome, RequestedWorkerStatus,
    StrictRemotePolicy, TargetDirPolicy, VisibilityMode, evaluate_requested_worker,
    placement_controls, resolve_placement,
};
pub use proof_intent::{
    ProofIntent, ProofIntentStore, ReplayConstraints, ReplayContext, ReplayDecision,
    SourceFingerprint, StaleSourcePolicy, derive_intent_id, proof_intent_schema,
    proof_intent_schema_version, validate_replay,
};
pub use telemetry_explain::{
    ProbeOutcome, TelemetrySignals, TelemetryUnavailabilityReason, WhyUnhealthy,
    explain_unavailability,
};
pub use telemetry_freshness::{
    FreshnessAssessment, FreshnessInputs, FreshnessVerdict, assess as assess_telemetry_freshness,
};
pub use worker_config_validation::{
    ConfigDriftFinding, ConfigDriftKind, LiveHostObservation, validate_worker_config,
};
pub use worker_facts::{
    DiskFacts, DiskRootFacts, HostFacts, RuntimeFacts, RustFacts, UserFacts, WorkerBinaryFacts,
    WorkerFacts, derive_target_triple, worker_facts_schema, worker_facts_schema_version,
};

// Errors module re-exports
pub use errors::{
    CodeExplanation, CodeNamespace, ErrorCategory, ErrorCode, ErrorEntry, ReliabilityCategoryKind,
    ReliabilityReasonCode, RunbookEntry,
};

// Schema-version registry re-exports
pub use schema_versions::current_version as schema_version;
pub use schema_versions::{ALL_COMPONENTS as SCHEMA_VERSION_COMPONENTS, SchemaComponent};

// API module re-exports (unified API types for CLI and daemon)
pub use api::{API_VERSION, ApiError, ApiResponse, ErrorContext, LegacyErrorCode};

// Hooks module re-exports (daemon self-healing)
pub use hooks::{HookResult, is_claude_code_installed, verify_and_install_claude_code_hook};

#[cfg(test)]
mod build_version_tests {
    use super::{BUILD_COMMIT_ENV_VARS, build_version_value_with_commit, first_build_commit};

    #[test]
    fn build_commit_skips_values_the_build_script_rejects() {
        // Issue #76: an alias build.rs refused must not surface in --version.
        assert_eq!(
            first_build_commit([None, None, Some("not-a-commit"), None]),
            None
        );
        let hash = "0123456789abcdef0123456789abcdef01234567";
        assert_eq!(
            first_build_commit([Some(""), None, Some("v2.0.0-3-gdeadbee"), Some(hash)]),
            Some(hash)
        );
        assert_eq!(first_build_commit([Some(" abc1234 ")]), Some("abc1234"));
        assert_eq!(first_build_commit([Some("abc123")]), None, "too short");
        let dirty = format!("{hash}-dirty");
        assert_eq!(
            first_build_commit([Some(dirty.as_str())]),
            Some(dirty.as_str())
        );
        let overlay = format!("{hash}-overlay-{}", "b".repeat(64));
        assert_eq!(
            first_build_commit([Some(overlay.as_str())]),
            Some(overlay.as_str())
        );
        let short_overlay = format!("{hash}-overlay-{}", "b".repeat(63));
        assert_eq!(first_build_commit([Some(short_overlay.as_str())]), None);
    }

    #[test]
    fn build_version_value_omits_missing_commit() {
        assert_eq!(build_version_value_with_commit("1.0.24", None), "1.0.24");
    }

    #[test]
    fn build_version_value_trims_and_shortens_commit() {
        assert_eq!(
            build_version_value_with_commit(
                "1.0.24",
                Some(" 2fa1249a18dfd05ae5e319e8d10bfd3c9ea1af55 "),
            ),
            "1.0.24 (commit 2fa1249a18df)"
        );
    }

    #[test]
    fn build_version_value_ignores_empty_commit() {
        assert_eq!(
            build_version_value_with_commit("1.0.24", Some("  ")),
            "1.0.24"
        );
    }

    #[test]
    fn build_source_stamp_version_preserves_nonclean_suffixes() {
        let hash = "a".repeat(40);
        for suffix in ["dirty".to_string(), format!("overlay-{}", "b".repeat(64))] {
            assert_eq!(
                build_version_value_with_commit("2.0.0", Some(&format!("{hash}-{suffix}"))),
                format!("2.0.0 (commit {}-{suffix})", "a".repeat(12))
            );
        }
    }

    #[test]
    fn build_commit_env_var_order_is_documented() {
        assert_eq!(
            BUILD_COMMIT_ENV_VARS,
            &[
                "RCH_GIT_COMMIT",
                "VERGEN_GIT_SHA",
                "GIT_COMMIT",
                "GITHUB_SHA"
            ]
        );
    }
}