aristo-cli 0.2.6

Aristo CLI binary (the `aristo` command).
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
//! `aristo statusline` — ambient progress + staleness segment for the Claude
//! Code `statusLine` (Phase 18, statusline v2). Prints one line such as
//! `aristo  Apprentice · 3 review · 12/14 verified · ⚠ 2 stale`, or, while a
//! review session is open, `aristo  ⏸ intent-review 2/7 · stamp/verify paused`.
//!
//! This is the USER-facing ambient surface (the agent-facing nudges ride the
//! PostToolUse / UserPromptSubmit hooks). It is read-only and stays cheap: it
//! reads the index (counts), the git-untracked nudge-state (reviewed map +
//! the cached baseline tier), the active-session pointer, a `stat` of the
//! annotated source files (staleness), the config, and a local sign-in check.
//! It does NOT walk/parse source — the status bar re-renders constantly, so a
//! per-render source walk would be too expensive; the tier is therefore the
//! cached session-baseline label. Subject-only: every token is about the
//! user's own annotations / verification, never the internal model.

use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use aristo_core::index::{Status, VerifyLevel};

use crate::commands::show::read_index;
use crate::nudge::intents::{authored_intents, AuthoredIntent};
use crate::nudge::state::{NudgeState, STATE_FILENAME};
use crate::{CliResult, Workspace};

/// A one-line summary of the active review session, when one is open.
struct SessionView {
    /// The pipeline kind, e.g. `critique-review` / `proof-review` / `intent-review`.
    kind: String,
    /// Items still awaiting a decision.
    open: usize,
    /// Total items in the session (open + decided).
    total: usize,
}

/// Everything the pure renderer needs, filled by [`run`] from cheap reads.
#[derive(Default)]
struct BarView {
    /// Cached session-baseline tier label (may be stale mid-session).
    tier: Option<String>,
    /// Unreviewed authored intents (remaining).
    unreviewed: usize,
    /// Verifiable intents in a terminal-clean status.
    verified_clean: usize,
    /// Verifiable intents (verify != false): the coverage denominator.
    verifiable: usize,
    /// Intents whose proof is broken or drift-suspected (staleness warning).
    stale: usize,
    /// Pending canon matches/suggestions (signed-in only; 0 otherwise).
    canon: usize,
    /// The active review session, if one is open (takes over the bar).
    session: Option<SessionView>,
}

#[aristo::intent(
    "The statusline is read-only and TOLERANT: on any failure — no workspace, \
     an unreadable index, or nudges globally off — it prints nothing and exits \
     0. The status bar re-renders on every turn, so a statusline that errored \
     or wrote files would corrupt the bar or thrash the workspace on every \
     keystroke. Silence is the correct degraded state. It also stays CHEAP: \
     index + nudge-state + the session pointer + a stat of the annotated \
     files + a local sign-in check, never a source-tree walk.",
    verify = "test",
    id = "statusline_is_read_only_and_tolerant"
)]
pub(crate) fn run() -> CliResult<()> {
    // The Claude Code statusLine command receives a JSON payload on stdin with
    // the session's cwd; fall back to the process cwd.
    let start = cwd_from_stdin();
    let Ok(ws) = Workspace::find(start.as_deref()) else {
        return Ok(()); // not an aristo workspace → empty segment
    };
    if ws.load_config().nudges.aggressiveness.is_off() {
        return Ok(()); // honor the global opt-out
    }

    let mut view = BarView::default();

    // Cached baseline tier (cheap; possibly stale until a metrics cache lands).
    let state = NudgeState::load(&ws.aristo_dir().join(STATE_FILENAME));
    view.tier = state.baseline.as_ref().map(|b| b.tier.clone());

    // An active review session takes over the bar — the D11 guard has paused
    // stamp/verify, so the standing backlog counts would mislead.
    view.session = active_session_view(&ws);

    if view.session.is_none() {
        if let Ok(index) = read_index(&ws.index_path()) {
            let intents = authored_intents(&index);
            view.unreviewed = state.unreviewed_count(
                intents
                    .iter()
                    .map(|i| (i.id.as_str(), i.text_hash.as_str(), i.body_hash.as_str())),
            );
            let index_mtime = file_mtime(&ws.index_path());
            for i in &intents {
                if matches!(i.verify, VerifyLevel::Bool(false)) {
                    continue; // documentation-only: never verifiable
                }
                view.verifiable += 1;
                if i.status.is_terminal_clean() {
                    view.verified_clean += 1;
                }
                if is_stale(i, &ws, index_mtime) {
                    view.stale += 1;
                }
            }
        }
    }

    // Canon is paid (#10): only ever shown signed in (never an upsell when out).
    if aristo_core::auth::resolve_full().is_ok() {
        view.canon = crate::commands::canon::suggestions::pending_total(&ws);
    }

    if let Some(line) = statusline(&view) {
        let color = std::env::var_os("NO_COLOR").is_none();
        println!("{}", colorize(&line, &view, color));
    }
    Ok(())
}

/// Build the compact status segment in PLAIN text (color is layered on top by
/// [`colorize`]), or `None` when there is nothing worth showing.
fn statusline(view: &BarView) -> Option<String> {
    // Active session: lead with the resume cue; it replaces the (guard-paused)
    // backlog counts. Tier + canon may trail.
    if let Some(s) = &view.session {
        let mut parts = vec![
            format!("{} {}/{}", s.kind, s.open, s.total),
            "stamp/verify paused".to_string(),
        ];
        if let Some(t) = &view.tier {
            parts.push(t.clone());
        }
        if view.canon > 0 {
            parts.push(format!("{} canon", view.canon));
        }
        return Some(format!("aristo  {}", parts.join(" · ")));
    }

    // Clean + complete: collapse to the tier + a green check.
    let complete = view.unreviewed == 0
        && view.stale == 0
        && view.verifiable > 0
        && view.verified_clean == view.verifiable;
    if complete {
        if let Some(t) = &view.tier {
            return Some(format!("aristo  {t}"));
        }
    }

    let mut parts: Vec<String> = Vec::new();
    if let Some(t) = &view.tier {
        parts.push(t.clone());
    }
    if view.unreviewed > 0 {
        parts.push(format!("{} review", view.unreviewed));
    }
    if view.verifiable > 0 {
        parts.push(format!(
            "{}/{} verified",
            view.verified_clean, view.verifiable
        ));
    }
    if view.stale > 0 {
        parts.push(format!("{} stale", view.stale));
    }
    if view.canon > 0 {
        parts.push(format!("{} canon", view.canon));
    }

    if parts.is_empty() {
        None
    } else {
        Some(format!("aristo  {}", parts.join(" · ")))
    }
}

/// Layer ANSI color onto the plain bar. Decoration only: every glyph/word is
/// meaningful without it, so `color = false` (or `NO_COLOR`) returns the plain
/// string unchanged. Green for success (`✓` / fully-verified coverage), amber
/// for the staleness warning, bold for the session resume cue.
fn colorize(line: &str, view: &BarView, color: bool) -> String {
    if !color {
        return line.to_string();
    }
    let mut s = line.to_string();
    if view.stale > 0 {
        let tok = format!("{} stale", view.stale);
        s = s.replace(&tok, &format!("\x1b[33m{tok}\x1b[0m"));
    }
    s = s.replace("", " \x1b[32m✓\x1b[0m");
    if view.session.is_none() && view.verifiable > 0 && view.verified_clean == view.verifiable {
        let tok = format!("{}/{} verified", view.verified_clean, view.verifiable);
        s = s.replace(&tok, &format!("\x1b[32m{tok}\x1b[0m"));
    }
    if view.session.is_some() {
        s = s.replace('', "\x1b[1m⏸");
        s = s.replace(" · stamp/verify paused", "\x1b[0m · stamp/verify paused");
    }
    s
}

/// Read the active review session (if any) as a compact view. Cheap: a single
/// pointer read + one small TOML parse, no index or source walk. Tolerant: a
/// stale pointer (file missing) reads as "no session".
fn active_session_view(ws: &Workspace) -> Option<SessionView> {
    let id = crate::session::storage::read_active_pointer(ws)
        .ok()
        .flatten()?;
    let session = crate::session::storage::read_active_session(ws, &id)
        .ok()
        .flatten()?;
    let c = session.bucket_counts();
    let total = c.open + c.accepted + c.rejected + c.pending;
    Some(SessionView {
        kind: session.kind.clone(),
        open: c.open,
        total,
    })
}

/// Whether an intent's proof should be flagged stale in the bar.
fn is_stale(i: &AuthoredIntent, ws: &Workspace, index_mtime: Option<SystemTime>) -> bool {
    let src_mtime = file_mtime(&ws.root.join(&i.file));
    intent_is_stale(i.status, src_mtime, index_mtime)
}

#[aristo::intent(
    "The bar's staleness count is cheap and conservative: an intent is stale \
     if it is recorded broken (Status::Stale or Counterexample) OR it is \
     currently terminal-clean but its source file's mtime is newer than the \
     index's (edited since the last stamp, so its proof may be clobbered). The \
     mtime test is a FILE-level heuristic — it over-counts versus a per-\
     function body-hash recompute, which is the right bias for a 're-verify' \
     warning and avoids the per-render source parse the bar forbids. When \
     either mtime is unreadable it does NOT warn (tolerant: omission over a \
     false alarm). Unknown/Inconclusive are not stale, only unverified.",
    verify = "test",
    id = "statusline_staleness_is_cheap_and_conservative"
)]
fn intent_is_stale(
    status: Status,
    src_mtime: Option<SystemTime>,
    index_mtime: Option<SystemTime>,
) -> bool {
    match status {
        Status::Stale | Status::Counterexample => true,
        s if s.is_terminal_clean() => {
            matches!((src_mtime, index_mtime), (Some(src), Some(idx)) if src > idx)
        }
        _ => false,
    }
}

fn file_mtime(path: &Path) -> Option<SystemTime> {
    std::fs::metadata(path).and_then(|m| m.modified()).ok()
}

/// Extract the session cwd from the statusLine stdin payload, if present.
fn cwd_from_stdin() -> Option<PathBuf> {
    let mut buf = String::new();
    if std::io::stdin().read_to_string(&mut buf).is_err() || buf.trim().is_empty() {
        return None;
    }
    let json: serde_json::Value = serde_json::from_str(&buf).ok()?;
    let dir = json
        .get("workspace")
        .and_then(|w| w.get("current_dir"))
        .and_then(|v| v.as_str())
        .or_else(|| json.get("cwd").and_then(|v| v.as_str()))?;
    Some(PathBuf::from(dir))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    fn view() -> BarView {
        BarView::default()
    }

    #[test]
    fn empty_when_nothing_to_surface() {
        assert_eq!(statusline(&view()), None);
    }

    #[test]
    fn clean_and_complete_collapses_to_tier_check() {
        let v = BarView {
            tier: Some("Adept".into()),
            verifiable: 14,
            verified_clean: 14,
            ..view()
        };
        assert_eq!(statusline(&v).as_deref(), Some("aristo  Adept ✓"));
    }

    #[test]
    fn typical_shows_review_and_coverage() {
        let v = BarView {
            tier: Some("Apprentice".into()),
            unreviewed: 3,
            verifiable: 14,
            verified_clean: 12,
            ..view()
        };
        assert_eq!(
            statusline(&v).as_deref(),
            Some("aristo  Apprentice · 3 review · 12/14 verified")
        );
    }

    #[test]
    fn drift_shows_amber_stale_token() {
        let v = BarView {
            tier: Some("Apprentice".into()),
            unreviewed: 3,
            verifiable: 14,
            verified_clean: 12,
            stale: 3,
            ..view()
        };
        assert_eq!(
            statusline(&v).as_deref(),
            Some("aristo  Apprentice · 3 review · 12/14 verified · ⚠ 3 stale")
        );
    }

    #[test]
    fn canon_shows_only_when_present_signed_in() {
        let v = BarView {
            tier: Some("Apprentice".into()),
            verifiable: 14,
            verified_clean: 12,
            canon: 4,
            ..view()
        };
        assert_eq!(
            statusline(&v).as_deref(),
            Some("aristo  Apprentice · 12/14 verified · 4 canon")
        );
        // Signed-out (canon = 0) drops the token entirely.
        let v0 = BarView { canon: 0, ..v };
        assert_eq!(
            statusline(&v0).as_deref(),
            Some("aristo  Apprentice · 12/14 verified")
        );
    }

    #[test]
    fn active_session_takes_over_and_suppresses_counts() {
        let v = BarView {
            tier: Some("Apprentice".into()),
            unreviewed: 3,
            verifiable: 14,
            verified_clean: 12,
            stale: 5,
            session: Some(SessionView {
                kind: "intent-review".into(),
                open: 2,
                total: 7,
            }),
            ..view()
        };
        assert_eq!(
            statusline(&v).as_deref(),
            Some("aristo  ⏸ intent-review 2/7 · stamp/verify paused · Apprentice")
        );
    }

    #[test]
    fn no_tier_still_shows_work() {
        let v = BarView {
            unreviewed: 2,
            ..view()
        };
        assert_eq!(statusline(&v).as_deref(), Some("aristo  2 review"));
    }

    #[test]
    fn color_is_decoration_and_degrades_to_plain() {
        let v = BarView {
            tier: Some("Apprentice".into()),
            verifiable: 14,
            verified_clean: 12,
            stale: 3,
            ..view()
        };
        let plain = statusline(&v).unwrap();
        assert_eq!(colorize(&plain, &v, false), plain);
        let colored = colorize(&plain, &v, true);
        assert!(colored.contains("⚠ 3 stale"));
        assert!(colored.contains("\x1b[33m"));
        assert!(colored.contains("\x1b[0m"));
    }

    #[test]
    fn stale_logic_recorded_and_drift() {
        let t0 = SystemTime::UNIX_EPOCH;
        let t1 = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
        // Recorded broken → stale regardless of mtimes.
        assert!(intent_is_stale(Status::Stale, None, None));
        assert!(intent_is_stale(Status::Counterexample, Some(t0), Some(t1)));
        // Terminal-clean but source edited since the index → drift-suspected.
        assert!(intent_is_stale(Status::Verified, Some(t1), Some(t0)));
        assert!(intent_is_stale(Status::Tested, Some(t1), Some(t0)));
        // Terminal-clean and fresh (source older than index) → not stale.
        assert!(!intent_is_stale(Status::Neural, Some(t0), Some(t1)));
        // Unreadable mtime → tolerant, no false alarm.
        assert!(!intent_is_stale(Status::Verified, None, Some(t1)));
        // Unknown is unverified, not stale.
        assert!(!intent_is_stale(Status::Unknown, Some(t1), Some(t0)));
    }
}