helen 0.1.0

Repository review gate.
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
//! Elenchus artifact paths and local retention.

use super::{
    error::{ElenchusError, Result},
    process::command_text,
};
use std::{
    collections::{BTreeMap, BTreeSet},
    fs,
    num::NonZeroUsize,
    path::{Path, PathBuf},
};

/// Root directory that stores local elenchus artifacts.
pub(super) const ARTIFACT_DIR: &str = ".helen/elenchus";

/// Directory that stores timestamped elenchus attempt artifacts.
pub(super) const ATTEMPT_DIR: &str = ".helen/elenchus/attempts";

/// Directory that stores reusable passing review cache artifacts.
pub(super) const REVIEW_CACHE_DIR: &str = ".helen/elenchus/reviews";

/// Default number of timestamped elenchus attempts kept in the attempt directory.
const DEFAULT_RETAINED_ATTEMPTS: usize = 12;

/// Count of elenchus attempts retained before archiving older attempts.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct RetainedAttemptCount {
    /// Non-zero attempt count.
    count: NonZeroUsize,
}

impl RetainedAttemptCount {
    /// Builds a retained-attempt count.
    pub(super) fn new(count: usize) -> Option<Self> {
        NonZeroUsize::new(count).map(|count| Self { count })
    }

    /// Returns the default retention count.
    pub(super) fn default_count() -> Self {
        Self::new(DEFAULT_RETAINED_ATTEMPTS).expect("default retention count is non-zero")
    }

    /// Returns the count as a plain integer.
    const fn get(self) -> usize {
        self.count.get()
    }
}

/// Creates the elenchus artifact directory layout.
pub(super) fn create_artifact_dirs() -> Result<()> {
    for dir in [ATTEMPT_DIR, REVIEW_CACHE_DIR] {
        fs::create_dir_all(dir).map_err(|error| {
            ElenchusError::failure(format!(
                "error: failed to create elenchus artifact directory {dir}: {error}"
            ))
        })?;
    }
    Ok(())
}

/// Paths for one elenchus attempt.
#[derive(Clone, Debug)]
pub(super) struct AttemptPaths {
    /// UTC-ish artifact timestamp.
    pub(super) stamp: String,
    /// Initial diff snapshot.
    pub(super) diff: PathBuf,
    /// Diff snapshot after local checks.
    pub(super) post_checks_diff: PathBuf,
    /// Prompt passed to the read-only reviewer.
    pub(super) review_prompt: PathBuf,
    /// Final reviewer message.
    pub(super) review_out: PathBuf,
    /// Reviewer stdout/stderr transcript.
    pub(super) review_transcript: PathBuf,
    /// Help output for `codex exec review`.
    pub(super) codex_exec_review_help: PathBuf,
    /// Help output for `codex exec`.
    pub(super) codex_exec_help: PathBuf,
    /// Diff snapshot after review.
    pub(super) post_review_diff: PathBuf,
    /// Summary artifact written after commit.
    pub(super) summary: PathBuf,
}

impl AttemptPaths {
    /// Creates artifact paths under [`ATTEMPT_DIR`].
    pub(super) fn new() -> Result<Self> {
        let stamp = command_text("date", ["-u", "+%Y%m%dT%H%M%SZ"])?;
        let root = PathBuf::from(ATTEMPT_DIR);
        Ok(Self {
            diff: root.join(format!("{stamp}.diff")),
            post_checks_diff: root.join(format!("{stamp}-after-checks.diff")),
            review_prompt: root.join(format!("{stamp}-review-prompt.md")),
            review_out: root.join(format!("{stamp}-review.md")),
            review_transcript: root.join(format!("{stamp}-review-transcript.txt")),
            codex_exec_review_help: root.join(format!("{stamp}-codex-exec-review-help.txt")),
            codex_exec_help: root.join(format!("{stamp}-codex-exec-help.txt")),
            post_review_diff: root.join(format!("{stamp}-after-review.diff")),
            summary: root.join(format!("{stamp}-summary.md")),
            stamp,
        })
    }
}

/// Summary of archived elenchus artifacts.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(super) struct ArchiveReport {
    /// Number of elenchus attempt groups moved.
    pub(super) attempts: usize,
    /// Number of files moved.
    pub(super) files: usize,
}

impl ArchiveReport {
    /// Returns true when any artifact was archived.
    pub(super) const fn archived_any(self) -> bool {
        self.files > 0
    }
}

/// Moves old timestamped elenchus attempts into archive subdirectories.
pub(super) fn archive_old_attempt_artifacts(
    log_dir: &Path,
    current_stamp: &str,
    retained_attempts: RetainedAttemptCount,
) -> Result<ArchiveReport> {
    if !log_dir.is_dir() {
        return Ok(ArchiveReport::default());
    }

    let current_stamp = AttemptStamp::new(current_stamp).ok_or_else(|| {
        super::error::ElenchusError::failure(format!(
            "error: invalid current elenchus stamp: {current_stamp}"
        ))
    })?;
    let groups = attempt_groups(log_dir)?;
    if groups.is_empty() {
        return Ok(ArchiveReport::default());
    }

    let mut retained = groups
        .keys()
        .rev()
        .take(retained_attempts.get())
        .cloned()
        .collect::<BTreeSet<_>>();
    let _inserted = retained.insert(current_stamp);

    let mut report = ArchiveReport::default();
    for (stamp, files) in groups {
        if retained.contains(&stamp) {
            continue;
        }

        let archive_dir = log_dir.join("archive").join(stamp.archive_month());
        fs::create_dir_all(&archive_dir).map_err(|error| {
            super::error::ElenchusError::failure(format!(
                "error: failed to create elenchus archive {}: {error}",
                archive_dir.display()
            ))
        })?;

        for file in files {
            let Some(name) = file.file_name() else {
                continue;
            };
            let target = unique_archive_path(&archive_dir.join(name));
            fs::rename(&file, &target).map_err(|error| {
                super::error::ElenchusError::failure(format!(
                    "error: failed to archive elenchus artifact {} to {}: {error}",
                    file.display(),
                    target.display()
                ))
            })?;
            report.files += 1;
        }
        report.attempts += 1;
    }

    Ok(report)
}

/// Returns timestamped attempt artifact groups in stamp order.
fn attempt_groups(log_dir: &Path) -> Result<BTreeMap<AttemptStamp, Vec<PathBuf>>> {
    let mut groups = BTreeMap::<AttemptStamp, Vec<PathBuf>>::new();
    let entries = fs::read_dir(log_dir).map_err(|error| {
        super::error::ElenchusError::failure(format!(
            "error: failed to read elenchus log directory {}: {error}",
            log_dir.display()
        ))
    })?;

    for entry in entries {
        let entry = entry.map_err(|error| {
            super::error::ElenchusError::failure(format!(
                "error: failed to read elenchus log entry: {error}"
            ))
        })?;
        let file_type = entry.file_type().map_err(|error| {
            super::error::ElenchusError::failure(format!(
                "error: failed to inspect elenchus log entry {}: {error}",
                entry.path().display()
            ))
        })?;
        if !file_type.is_file() {
            continue;
        }

        let name = entry.file_name();
        let Some(name) = name.to_str() else {
            continue;
        };
        let Some(stamp) = AttemptStamp::from_artifact_name(name) else {
            continue;
        };
        groups.entry(stamp).or_default().push(entry.path());
    }

    for files in groups.values_mut() {
        files.sort();
    }
    Ok(groups)
}

/// Returns a non-clobbering archive path.
fn unique_archive_path(path: &Path) -> PathBuf {
    if !path.exists() {
        return path.to_path_buf();
    }

    for index in 1.. {
        let candidate = PathBuf::from(format!("{}.{}", path.display(), index));
        if !candidate.exists() {
            return candidate;
        }
    }
    unreachable!("unbounded unique archive suffix search should always return")
}

/// Timestamp prefix used by one elenchus attempt.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
struct AttemptStamp(String);

impl AttemptStamp {
    /// Parses a elenchus stamp.
    fn new(stamp: &str) -> Option<Self> {
        is_elenchus_stamp(stamp).then(|| Self(stamp.to_owned()))
    }

    /// Parses the timestamp prefix from a elenchus artifact filename.
    fn from_artifact_name(name: &str) -> Option<Self> {
        let stamp = name.get(..16)?;
        let suffix = name.get(16..)?;
        if !(suffix.starts_with('-') || suffix.starts_with('.')) {
            return None;
        }
        Self::new(stamp)
    }

    /// Returns the archive month in `YYYYMM` form.
    fn archive_month(&self) -> &str {
        &self.0[..6]
    }
}

/// Returns true when text matches `YYYYMMDDTHHMMSSZ`.
fn is_elenchus_stamp(stamp: &str) -> bool {
    let bytes = stamp.as_bytes();
    stamp.len() == 16
        && bytes[8] == b'T'
        && bytes[15] == b'Z'
        && bytes[..8].iter().all(u8::is_ascii_digit)
        && bytes[9..15].iter().all(u8::is_ascii_digit)
}

/// Review cache paths for a diff fingerprint.
#[derive(Clone, Debug)]
pub(super) struct ReviewCachePaths {
    /// Cached passing review output.
    pub(super) review: PathBuf,
    /// Cache metadata binding the review to diff, base, message, and token.
    pub(super) meta: PathBuf,
}

impl ReviewCachePaths {
    /// Creates cache paths for a diff fingerprint.
    pub(super) fn new(diff_fingerprint: &str) -> Self {
        let root = PathBuf::from(REVIEW_CACHE_DIR).join(diff_fingerprint);
        Self {
            review: root.join("review.md"),
            meta: root.join("meta"),
        }
    }

    /// Creates the directory that stores this review cache entry.
    pub(super) fn create_dir(&self) -> Result<()> {
        let Some(dir) = self.review.parent() else {
            return Err(ElenchusError::failure(
                "error: invalid elenchus review cache path",
            ));
        };
        fs::create_dir_all(dir).map_err(|error| {
            ElenchusError::failure(format!(
                "error: failed to create elenchus review cache directory {}: {error}",
                dir.display()
            ))
        })
    }
}

#[cfg(test)]
mod tests {
    //! Tests for elenchus artifact retention.

    use super::{RetainedAttemptCount, archive_old_attempt_artifacts};
    use std::{
        fs,
        path::{Path, PathBuf},
        process,
        sync::atomic::{AtomicU64, Ordering},
        time::{SystemTime, UNIX_EPOCH},
    };

    static NEXT_TEMP_ROOT: AtomicU64 = AtomicU64::new(0);

    #[test]
    fn archive_moves_old_attempt_groups_and_keeps_non_attempt_files() {
        let root = temp_root("archive-old-attempts");
        let log_dir = root.join("attempts");
        fs::create_dir_all(&log_dir).expect("create log dir");
        write_file(&log_dir.join("20260501T000000Z.diff"));
        write_file(&log_dir.join("20260501T000000Z-review.md"));
        write_file(&log_dir.join("20260502T000000Z.diff"));
        write_file(&log_dir.join("notes.txt"));

        let report = archive_old_attempt_artifacts(
            &log_dir,
            "20260502T000000Z",
            RetainedAttemptCount::new(1).expect("retention count"),
        )
        .expect("archive old artifacts");

        assert_eq!(report.attempts, 1);
        assert_eq!(report.files, 2);
        assert!(!log_dir.join("20260501T000000Z.diff").exists());
        assert!(log_dir.join("20260502T000000Z.diff").exists());
        assert!(log_dir.join("notes.txt").exists());
        assert!(
            log_dir
                .join("archive/202605/20260501T000000Z.diff")
                .exists()
        );
        assert!(
            log_dir
                .join("archive/202605/20260501T000000Z-review.md")
                .exists()
        );

        fs::remove_dir_all(root).expect("remove temp root");
    }

    #[test]
    fn archive_never_moves_current_attempt_even_when_newer_stamps_exist() {
        let root = temp_root("archive-current-attempt");
        let log_dir = root.join("attempts");
        fs::create_dir_all(&log_dir).expect("create log dir");
        write_file(&log_dir.join("20260501T000000Z.diff"));
        write_file(&log_dir.join("20260502T000000Z.diff"));
        write_file(&log_dir.join("20260503T000000Z.diff"));

        let report = archive_old_attempt_artifacts(
            &log_dir,
            "20260501T000000Z",
            RetainedAttemptCount::new(1).expect("retention count"),
        )
        .expect("archive old artifacts");

        assert_eq!(report.attempts, 1);
        assert!(log_dir.join("20260501T000000Z.diff").exists());
        assert!(log_dir.join("20260503T000000Z.diff").exists());
        assert!(
            log_dir
                .join("archive/202605/20260502T000000Z.diff")
                .exists()
        );

        fs::remove_dir_all(root).expect("remove temp root");
    }

    /// Writes a small artifact file.
    fn write_file(path: &Path) {
        fs::write(path, "artifact\n").expect("write artifact");
    }

    /// Returns a unique temporary test root.
    fn temp_root(label: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system clock should be after unix epoch")
            .as_nanos();
        let sequence = NEXT_TEMP_ROOT.fetch_add(1, Ordering::Relaxed);
        std::env::temp_dir().join(format!(
            "alma-elenchus-{label}-{}-{nanos}-{sequence}",
            process::id()
        ))
    }
}