Skip to main content

ralph/
constants.rs

1//! Centralized constants for the Ralph CLI.
2//!
3//! This module consolidates all magic numbers, limits, and default values
4//! to improve maintainability and prevent drift between duplicated values.
5//!
6//! Responsibilities:
7//! - Provide a single source of truth for compile-time constants.
8//! - Organize constants by domain (buffers, limits, timeouts, UI, etc.).
9//! - Prevent accidental drift between duplicated constant definitions.
10//!
11//! Not handled here:
12//! - Runtime configuration values (see `crate::config`).
13//! - User-customizable thresholds (see `crate::contracts::Config`).
14//!
15//! Invariants/assumptions:
16//! - All constants are `pub` within their submodule; visibility is controlled by module exports.
17//! - Constants that appear in multiple places must be defined here and imported elsewhere.
18
19/// Buffer size limits for output handling and memory management.
20pub mod buffers {
21    /// Maximum size for ANSI buffer (10MB).
22    /// Reduced from 100MB to prevent memory pressure during runner execution.
23    pub const MAX_ANSI_BUFFER_SIZE: usize = 10 * 1024 * 1024;
24
25    /// Maximum line length before truncation (10MB).
26    /// Reduced from 100MB to prevent memory pressure with runaway runner output.
27    pub const MAX_LINE_LENGTH: usize = 10 * 1024 * 1024;
28
29    /// Maximum buffer size for stream processing (10MB).
30    /// Reduced from 100MB to prevent memory pressure during long-running tasks.
31    pub const MAX_BUFFER_SIZE: usize = 10 * 1024 * 1024;
32
33    /// Maximum log lines to retain for interactive log viewers.
34    pub const MAX_LOG_LINES: usize = 10_000;
35
36    /// Maximum tool value length before truncation.
37    pub const TOOL_VALUE_MAX_LEN: usize = 160;
38
39    /// Maximum instruction file size (128KB).
40    pub const MAX_INSTRUCTION_BYTES: usize = 128 * 1024;
41
42    /// Maximum stdout capture size for timeouts (128KB).
43    pub const TIMEOUT_STDOUT_CAPTURE_MAX_BYTES: usize = 128 * 1024;
44
45    /// Number of output tail lines to display.
46    pub const OUTPUT_TAIL_LINES: usize = 20;
47
48    /// Maximum characters per output tail line.
49    pub const OUTPUT_TAIL_LINE_MAX_CHARS: usize = 200;
50}
51
52/// Operational limits and thresholds.
53pub mod limits {
54    /// Auto-retry limit for CI gate failures.
55    pub const CI_GATE_AUTO_RETRY_LIMIT: u8 = 10;
56
57    /// Maximum automatic recovery attempts after runner signal termination.
58    pub const MAX_SIGNAL_RESUMES: u8 = 5;
59
60    /// Number of consecutive CI failures with the same error pattern before escalation.
61    /// After this many identical failures, Ralph stops retrying and requires intervention.
62    pub const CI_FAILURE_ESCALATION_THRESHOLD: u8 = 3;
63
64    /// Maximum consecutive failures before aborting run loop.
65    pub const MAX_CONSECUTIVE_FAILURES: u32 = 50;
66
67    /// Maximum IDs to generate per invocation.
68    pub const MAX_COUNT: usize = 100;
69
70    /// Maximum lock cleanup retry attempts.
71    pub const MAX_RETRIES: u32 = 3;
72
73    /// Minimum environment variable value length for redaction.
74    pub const MIN_ENV_VALUE_LEN: usize = 6;
75
76    /// Default queue file size warning threshold (KB).
77    pub const DEFAULT_SIZE_WARNING_THRESHOLD_KB: u32 = 500;
78
79    /// Default task count warning threshold.
80    pub const DEFAULT_TASK_COUNT_WARNING_THRESHOLD: u32 = 500;
81
82    /// Maximum LFS pointer file size (bytes).
83    pub const MAX_POINTER_SIZE: u64 = 1024;
84
85    /// Maximum number of queue backup files to retain in `.ralph/cache`.
86    pub const MAX_QUEUE_BACKUP_FILES: usize = 50;
87
88    /// Maximum number of undo snapshots to retain in `.ralph/cache/undo`.
89    pub const MAX_UNDO_SNAPSHOTS: usize = 20;
90}
91
92/// Timeout and interval durations.
93pub mod timeouts {
94    use std::time::Duration;
95
96    /// Default session timeout in hours.
97    pub const DEFAULT_SESSION_TIMEOUT_HOURS: u64 = 24;
98
99    /// Spinner animation update interval in milliseconds.
100    pub const SPINNER_UPDATE_INTERVAL_MS: u64 = 80;
101
102    /// Temporary file retention period (7 days).
103    ///
104    /// Files older than this are cleaned up:
105    /// - On CLI startup (main.rs)
106    /// - When building runner commands (with_temp_prompt_file)
107    /// - When running `ralph cleanup` command
108    ///
109    /// Default: 7 days. This balances keeping safeguard dumps available for
110    /// debugging against preventing indefinite accumulation.
111    pub const TEMP_RETENTION: Duration = Duration::from_secs(60 * 60 * 24 * 7);
112
113    /// Lock cleanup retry delays in milliseconds.
114    pub const DELAYS_MS: [u64; 3] = [10, 50, 100];
115
116    /// How long terminal worker records are retained before stale pruning.
117    ///
118    /// This prevents immediate task reselection while avoiding permanent capacity blockers.
119    pub const PARALLEL_TERMINAL_WORKER_TTL: Duration =
120        Duration::from_secs(60 * 60 * DEFAULT_SESSION_TIMEOUT_HOURS);
121}
122
123/// UI layout and dimension constants.
124pub mod ui {
125    /// Threshold for narrow layout mode.
126    pub const NARROW_LAYOUT_WIDTH: u16 = 90;
127
128    /// Minimum width for board view.
129    pub const BOARD_MIN_WIDTH: u16 = 100;
130
131    /// Gutter width between columns.
132    pub const COLUMN_GUTTER: u16 = 1;
133
134    /// Number of task builder fields.
135    pub const TASK_BUILDER_FIELD_COUNT: usize = 7;
136}
137
138/// Queue configuration constants.
139pub mod queue {
140    /// Default queue ID prefix.
141    pub const DEFAULT_ID_PREFIX: &str = "RQ";
142
143    /// Default queue file path (relative to repo root).
144    pub const DEFAULT_QUEUE_FILE: &str = ".ralph/queue.jsonc";
145
146    /// Default done file path (relative to repo root).
147    pub const DEFAULT_DONE_FILE: &str = ".ralph/done.jsonc";
148
149    /// Default config file path (relative to repo root).
150    pub const DEFAULT_CONFIG_FILE: &str = ".ralph/config.jsonc";
151
152    /// Default maximum dependency depth.
153    pub const DEFAULT_MAX_DEPENDENCY_DEPTH: u8 = 10;
154
155    /// Aging threshold: warning days (low priority).
156    pub const AGING_WARNING_DAYS: u32 = 7;
157
158    /// Aging threshold: stale days (medium priority).
159    pub const AGING_STALE_DAYS: u32 = 14;
160
161    /// Aging threshold: rotten days (high priority).
162    pub const AGING_ROTTEN_DAYS: u32 = 30;
163}
164
165/// Git-related constants.
166pub mod git {
167    /// Default branch prefix for parallel execution.
168    pub const DEFAULT_BRANCH_PREFIX: &str = "ralph/";
169
170    /// Sample task ID for branch validation.
171    pub const SAMPLE_TASK_ID: &str = "RQ-0001";
172}
173
174/// Runner-related constants.
175pub mod runner {
176    /// Default CI gate command.
177    pub const DEFAULT_CI_GATE_COMMAND: &str = "make ci";
178
179    /// Supported phase values (1-3).
180    pub const MIN_PHASES: u8 = 1;
181    pub const MAX_PHASES: u8 = 3;
182
183    /// Minimum iterations value.
184    pub const MIN_ITERATIONS: u8 = 1;
185    pub const MIN_ITERATIONS_U32: u32 = 1;
186
187    /// Minimum workers for parallel execution.
188    pub const MIN_PARALLEL_WORKERS: u8 = 2;
189
190    /// Minimum merge retries.
191    pub const MIN_MERGE_RETRIES: u8 = 1;
192}
193
194/// File paths and directory names.
195pub mod paths {
196    /// Session state filename.
197    pub const SESSION_FILENAME: &str = "session.jsonc";
198
199    /// Stop signal filename.
200    pub const STOP_SIGNAL_FILE: &str = "stop_requested";
201
202    /// Migration history file path.
203    pub const MIGRATION_HISTORY_PATH: &str = ".ralph/cache/migrations.jsonc";
204
205    /// Productivity stats filename.
206    pub const STATS_FILENAME: &str = "productivity.jsonc";
207
208    /// Ralph temp directory name.
209    pub const RALPH_TEMP_DIR_NAME: &str = "ralph";
210
211    /// Legacy prompt temp file prefix.
212    pub const LEGACY_PROMPT_PREFIX: &str = "ralph_prompt_";
213
214    /// Ralph temp file prefix.
215    pub const RALPH_TEMP_PREFIX: &str = "ralph_";
216
217    /// Worker prompt override path.
218    pub const WORKER_OVERRIDE_PATH: &str = ".ralph/prompts/worker.md";
219
220    /// Scan prompt override path.
221    pub const SCAN_OVERRIDE_PATH: &str = ".ralph/prompts/scan.md";
222
223    /// Task builder prompt override path.
224    pub const TASK_BUILDER_OVERRIDE_PATH: &str = ".ralph/prompts/task_builder.md";
225
226    /// Environment variable for raw dump mode.
227    pub const ENV_RAW_DUMP: &str = "RALPH_RAW_DUMP";
228
229    /// Environment variable for the runner actually used (set by Ralph when spawning runners).
230    /// Used for analytics tracking in task custom fields.
231    pub const ENV_RUNNER_USED: &str = "RALPH_RUNNER_USED";
232
233    /// Environment variable for the model actually used (set by Ralph when spawning runners).
234    /// Used for analytics tracking in task custom fields.
235    pub const ENV_MODEL_USED: &str = "RALPH_MODEL_USED";
236}
237
238/// Version constants for schemas and templates.
239pub mod versions {
240    /// README template version.
241    pub const README_VERSION: u32 = 6;
242
243    /// Session state schema version.
244    pub const SESSION_STATE_VERSION: u32 = 1;
245
246    /// Migration history schema version.
247    pub const HISTORY_VERSION: u32 = 1;
248
249    /// Productivity stats schema version.
250    pub const STATS_SCHEMA_VERSION: u32 = 1;
251
252    /// Execution history schema version.
253    pub const EXECUTION_HISTORY_VERSION: u32 = 1;
254
255    /// Template version string.
256    pub const TEMPLATE_VERSION: &str = "1.0.0";
257}
258
259/// Default values for models and configuration.
260pub mod defaults {
261    /// Default Gemini model name.
262    pub const DEFAULT_GEMINI_MODEL: &str = "gemini-3-flash-preview";
263
264    /// Default Claude model name.
265    pub const DEFAULT_CLAUDE_MODEL: &str = "sonnet";
266
267    /// Default Cursor model name.
268    pub const DEFAULT_CURSOR_MODEL: &str = "auto";
269
270    /// Opencode prompt file message.
271    pub const OPENCODE_PROMPT_FILE_MESSAGE: &str = "Follow the attached prompt file verbatim.";
272
273    /// Fallback message for Phase 2 final response.
274    pub const PHASE2_FINAL_RESPONSE_FALLBACK: &str = "(Phase 2 final response unavailable.)";
275
276    /// Git LFS pointer file prefix.
277    pub const LFS_POINTER_PREFIX: &str = "version https://git-lfs.github.com/spec/v1";
278
279    /// Redaction placeholder text.
280    pub const REDACTED: &str = "[REDACTED]";
281
282    /// Sentinel RFC3339 timestamp used only when formatting "now" fails.
283    ///
284    /// This value is intentionally "obviously wrong" in modern persisted data so
285    /// fallback usage is detectable during debugging/audits.
286    pub const FALLBACK_RFC3339: &str = "1970-01-01T00:00:00.000000000Z";
287
288    /// Default task ID width.
289    pub const DEFAULT_ID_WIDTH: usize = 4;
290}
291
292/// UI symbols and emoji.
293pub mod symbols {
294    /// Celebration sparkles emoji.
295    pub const SPARKLES: &str = "✨";
296
297    /// Streak fire emoji.
298    pub const FIRE: &str = "🔥";
299
300    /// Achievement star emoji.
301    pub const STAR: &str = "⭐";
302
303    /// Completion checkmark.
304    pub const CHECKMARK: &str = "✓";
305}
306
307/// Spinner animation frames.
308pub mod spinners {
309    /// Default braille spinner frames.
310    pub const DEFAULT_SPINNER_FRAMES: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
311}
312
313/// Milestone and achievement thresholds.
314pub mod milestones {
315    /// Task count milestones for achievements.
316    pub const MILESTONE_THRESHOLDS: &[u64] = &[10, 50, 100, 250, 500, 1000, 2500, 5000];
317}
318
319/// AGENTS.md section requirements.
320pub mod agents_md {
321    /// Required sections in AGENTS.md.
322    pub const REQUIRED_SECTIONS: &[&str] =
323        &["Non-Negotiables", "Repository Map", "Build, Test, and CI"];
324
325    /// Recommended sections for a complete AGENTS.md.
326    pub const RECOMMENDED_SECTIONS: &[&str] = &[
327        "Non-Negotiables",
328        "Repository Map",
329        "Build, Test, and CI",
330        "Testing",
331        "Workflow Contracts",
332        "Configuration",
333        "Git Hygiene",
334        "Documentation Maintenance",
335        "Troubleshooting",
336    ];
337}
338
339/// Custom field keys for analytics/observability data.
340pub mod custom_fields {
341    /// Key for the runner actually used (observational, not intent).
342    pub const RUNNER_USED: &str = "runner_used";
343
344    /// Key for the model actually used (observational, not intent).
345    pub const MODEL_USED: &str = "model_used";
346}
347
348/// Error message templates for consistent error formatting.
349pub mod error_messages {
350    /// Config update instruction suffix.
351    pub const CONFIG_UPDATE_INSTRUCTION: &str = "Update .ralph/config.jsonc";
352
353    /// Template for invalid config value errors.
354    pub fn invalid_config_value(
355        field: &str,
356        value: impl std::fmt::Display,
357        reason: &str,
358    ) -> String {
359        format!("Invalid {field}: {value}. {reason}. Update .ralph/config.jsonc.")
360    }
361}
362
363/// Status classification keywords for theme/styling.
364pub mod status_keywords {
365    /// Keywords indicating error status.
366    pub const ERROR: &[&str] = &[
367        "error", "fail", "failed", "denied", "timeout", "cancel", "canceled",
368    ];
369
370    /// Keywords indicating in-progress/warning status.
371    pub const IN_PROGRESS: &[&str] = &[
372        "running",
373        "started",
374        "pending",
375        "queued",
376        "in_progress",
377        "working",
378    ];
379
380    /// Keywords indicating success status.
381    pub const SUCCESS: &[&str] = &[
382        "completed",
383        "success",
384        "succeeded",
385        "ok",
386        "done",
387        "finished",
388    ];
389}