Skip to main content

lean_ctx_cloud/capture/
episode.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Episodes (SPEC-ENGINE §3.2.3): one node per ended session, built from
3//! its record — the goal (last task), the outcome (final progress or an
4//! explicit keyword), dead ends (`ctx_session finding tag=dead_end` and
5//! revert commits of the session window), the files it changed and the
6//! commits it made. An episode that fails the episode rules (§3.1.4) is not
7//! captured (`episode_shape`, or `no_reference` without files and commits);
8//! nothing of it leaves the machine then.
9
10use std::path::Path;
11use std::process::{Command, Stdio};
12
13use lean_ctx_time::UtcDateTime;
14use serde_json::{Map, Value, json};
15use sha2::{Digest as _, Sha256};
16
17use super::refs::Checkout;
18use super::{ReasonCode, rules};
19use crate::CloudError;
20use crate::events::build::{EVENT_SCHEMA, Place, Signer};
21use crate::events::hlc::Stamp;
22use crate::events::{ids, sign};
23use crate::knowledge::screening::Screen;
24use crate::session_ref::SessionRefs;
25use lean_ctx::core::session::SessionState;
26use lean_ctx_ext::core::import::git_history::{self, Commit, Kind};
27
28const TEXT_MAX: usize = 300;
29const GOAL_MIN: usize = 8;
30const MAX_DEAD_ENDS: usize = 5;
31const MAX_TOUCHED: usize = 50;
32const MAX_COMMITS: usize = 50;
33/// Commits of a session window read at most.
34const MAX_LOG_COMMITS: usize = 200;
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Outcome {
38    Succeeded,
39    Failed,
40    Abandoned,
41    Partial,
42}
43
44impl Outcome {
45    pub fn as_str(self) -> &'static str {
46        match self {
47            Self::Succeeded => "succeeded",
48            Self::Failed => "failed",
49            Self::Abandoned => "abandoned",
50            Self::Partial => "partial",
51        }
52    }
53
54    /// `100%` (or `[done]`/`[complete]`) succeeded; an explicit `failed` or
55    /// `abandoned` word wins over the percentage; anything else is partial.
56    fn of(description: &str, progress: Option<u8>) -> Self {
57        let lower = description.to_lowercase();
58        let has = |word: &str| {
59            lower
60                .split(|c: char| !c.is_alphanumeric())
61                .any(|token| token == word)
62        };
63        if has("failed") {
64            Self::Failed
65        } else if has("abandoned") {
66            Self::Abandoned
67        } else if progress == Some(100)
68            || lower.contains("[100%]")
69            || lower.contains("[done]")
70            || lower.contains("[complete]")
71        {
72            Self::Succeeded
73        } else {
74            Self::Partial
75        }
76    }
77}
78
79/// An episode as it is captured; [`Episode::body`] is its contract body.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct Episode {
82    pub goal: String,
83    pub outcome: Outcome,
84    pub summary: String,
85    pub dead_ends: Vec<String>,
86    /// Code anchors `{path, digest}` of the files the session changed, at `HEAD`.
87    pub touched: Vec<Value>,
88    pub commits: Vec<String>,
89    pub session_ref: String,
90    pub started_at: u64,
91    pub ended_at: u64,
92}
93
94/// `fix: retry [45%]` → `fix: retry`: the progress marker is no part of a goal.
95fn goal_of(description: &str) -> String {
96    let text = description.trim();
97    match text.rsplit_once('[') {
98        Some((head, tail)) if tail.ends_with(']') && !head.trim().is_empty() => {
99            head.trim().to_string()
100        }
101        _ => text.to_string(),
102    }
103}
104
105/// `path` relative to `root`, `None` outside it.
106fn relative(path: &str, root: &Path) -> Option<String> {
107    let p = Path::new(path);
108    let rel = if p.is_absolute() {
109        p.strip_prefix(root).ok()?
110    } else {
111        p
112    };
113    let text = rel.to_str()?.replace('\\', "/");
114    (!text.is_empty() && !text.starts_with("..")).then_some(text)
115}
116
117fn ms(t: UtcDateTime) -> u64 {
118    t.timestamp_millis().max(0).unsigned_abs()
119}
120
121/// The episode of `session`: `dead_ends` are its tagged findings,
122/// `commits` the commits of its window (newest first, as `git log` lists
123/// them). Texts that would break a rule are left out where the rules allow
124/// it (a dead end, the summary); the rest is checked by [`check`].
125pub fn assemble(
126    session: &SessionState,
127    root: &Path,
128    dead_ends: &[String],
129    commits: &[Commit],
130    checkout: &mut Checkout,
131) -> Result<Episode, ReasonCode> {
132    let task = session.task.as_ref().ok_or(ReasonCode::EpisodeShape)?;
133    let goal = goal_of(&task.description);
134    let outcome = Outcome::of(&task.description, task.progress_pct);
135    let fits = |t: &str| {
136        rules::check_length(t, 1, TEXT_MAX).is_ok()
137            && rules::check_single_line(t).is_ok()
138            && rules::check_log(t).is_ok()
139    };
140    let reverts = commits
141        .iter()
142        .filter(|c| git_history::classify(c) == Some(Kind::Revert))
143        .map(|c| git_history::statement(c, Kind::Revert));
144    let mut dead: Vec<String> = Vec::new();
145    for text in dead_ends.iter().cloned().chain(reverts) {
146        let text = text.trim().to_string();
147        if dead.len() < MAX_DEAD_ENDS && fits(&text) && !dead.contains(&text) {
148            dead.push(text);
149        }
150    }
151    let mut touched = Vec::new();
152    for file in session.files_touched.iter().filter(|f| f.modified) {
153        let Some(path) = relative(&file.path, root) else {
154            continue;
155        };
156        if touched.len() == MAX_TOUCHED || touched.iter().any(|t: &Value| t["path"] == *path) {
157            continue;
158        }
159        // Only what `HEAD` holds is anchored; a file the session deleted or
160        // never committed is no reference.
161        if let Some(bytes) = checkout.blob_bytes(&path) {
162            touched.push(json!({"path": path, "digest": hex::encode(Sha256::digest(bytes))}));
163        }
164    }
165    let commits: Vec<String> = commits
166        .iter()
167        .take(MAX_COMMITS)
168        .map(|c| c.sha.to_lowercase())
169        .collect();
170    let summary = session
171        .decisions
172        .last()
173        .map(|d| d.summary.trim().to_string())
174        .filter(|s| fits(s))
175        .unwrap_or_else(|| {
176            format!(
177                "{} after {} commit(s) changing {} file(s).",
178                match outcome {
179                    Outcome::Succeeded => "Succeeded",
180                    Outcome::Failed => "Failed",
181                    Outcome::Abandoned => "Abandoned",
182                    Outcome::Partial => "Partly done",
183                },
184                commits.len(),
185                touched.len()
186            )
187        });
188    let episode = Episode {
189        goal,
190        outcome,
191        summary,
192        dead_ends: dead,
193        touched,
194        commits,
195        session_ref: crate::knowledge::draft::session_ref(&session.id),
196        started_at: ms(session.started_at),
197        ended_at: ms(session.updated_at),
198    };
199    check(&episode)?;
200    Ok(episode)
201}
202
203/// The episode rules (SPEC-ENGINE §3.1.4).
204pub fn check(e: &Episode) -> Result<(), ReasonCode> {
205    let shape = |ok: bool| {
206        if ok {
207            Ok(())
208        } else {
209            Err(ReasonCode::EpisodeShape)
210        }
211    };
212    let line = |t: &str, min: usize| {
213        rules::check_length(t, min, TEXT_MAX).is_ok() && rules::check_single_line(t).is_ok()
214    };
215    shape(line(&e.goal, GOAL_MIN))?;
216    shape(line(&e.summary, 1))?;
217    shape(e.dead_ends.len() <= MAX_DEAD_ENDS)?;
218    for d in &e.dead_ends {
219        shape(line(d, 1) && rules::check_log(d).is_ok())?;
220    }
221    shape(e.touched.len() <= MAX_TOUCHED && e.commits.len() <= MAX_COMMITS)?;
222    shape(
223        e.commits
224            .iter()
225            .all(|c| (7..=64).contains(&c.len()) && c.chars().all(|c| c.is_ascii_hexdigit())),
226    )?;
227    shape(e.ended_at >= e.started_at)?;
228    if e.touched.is_empty() && e.commits.is_empty() {
229        return Err(ReasonCode::NoReference);
230    }
231    Ok(())
232}
233
234/// Screen every text of the episode (all node text is screened).
235pub fn screen(e: &Episode, screen: &mut Screen) -> Result<(), ReasonCode> {
236    let texts = [&e.goal, &e.summary].into_iter().chain(&e.dead_ends);
237    for text in texts {
238        screen.check(text).map_err(|b| ReasonCode::of_screen(&b))?;
239    }
240    Ok(())
241}
242
243impl Episode {
244    /// The contract body (`episode_body`).
245    pub fn body(&self) -> Result<Value, CloudError> {
246        let mut body = Map::new();
247        body.insert("body_nonce".into(), Value::String(sign::new_body_nonce()?));
248        body.insert("goal".into(), Value::from(self.goal.clone()));
249        body.insert("outcome".into(), Value::from(self.outcome.as_str()));
250        body.insert("summary".into(), Value::from(self.summary.clone()));
251        if !self.dead_ends.is_empty() {
252            body.insert("dead_ends".into(), json!(self.dead_ends));
253        }
254        if !self.touched.is_empty() {
255            body.insert("touched".into(), Value::Array(self.touched.clone()));
256        }
257        if !self.commits.is_empty() {
258            body.insert("commits".into(), json!(self.commits));
259        }
260        body.insert("session_ref".into(), Value::from(self.session_ref.clone()));
261        body.insert("started_at".into(), Value::from(self.started_at));
262        body.insert("ended_at".into(), Value::from(self.ended_at));
263        Ok(Value::Object(body))
264    }
265
266    /// A signed `node.add` of the episode. Returns the event and its node id.
267    /// `session` is the envelope `session_ref` (V9,
268    /// [`crate::session_ref::SessionRefs::event_ref`]), `None` when Cloud
269    /// does not accept one.
270    pub fn node_add(
271        &self,
272        place: &Place,
273        stamp: Stamp,
274        signer: &Signer<'_>,
275        session: Option<&str>,
276    ) -> Result<(Value, String), CloudError> {
277        let body = self.body()?;
278        let target = ids::new_random_id("n")?;
279        let body_commit = sign::body_commit(&place.pk_id, &body).map_err(CloudError::Local)?;
280        let rules = format!("leanctx.cloud.capture.v{}:episode", super::GATE_VERSION);
281        let mut event = json!({
282            "schema": EVENT_SCHEMA,
283            "event_id": ids::new_event_id(stamp.wall_ms)?,
284            "place": {"kind": place.kind, "id": place.id},
285            "op": "node.add",
286            "target": target,
287            "node_type": "episode",
288            "body": body,
289            "body_commit": body_commit,
290            "hlc": {"wall_ms": stamp.wall_ms, "counter": stamp.counter, "node": signer.hlc_node},
291            "causal_base": place.causal_base,
292            "actor": {"kind": "worker"},
293            "worker_id": signer.worker_id,
294            "provenance_claim": "own",
295            "capture": {
296                "gate_version": super::GATE_VERSION,
297                "evidence": "observed",
298                "reasons_passed_hash": blake3::hash(rules.as_bytes()).to_hex().to_string(),
299            },
300            "screening": {
301                "counts": {"forbidden": 0, "local_path": 0, "pii": 0, "redaction": 0, "secret": 0},
302                "scanner_version": crate::knowledge::screening::SCANNER_VERSION,
303            },
304        });
305        // V9: the envelope names the session by its keyed ref, like every
306        // other event of the session; the body's `session_ref` stays the
307        // episode's own contract field (keyed apart by `uploaded_refs`
308        // whenever an envelope ref is set).
309        crate::events::build::set_session(&mut event, session);
310        sign::sign(&mut event, signer.key).map_err(CloudError::Local)?;
311        Ok((event, target))
312    }
313}
314
315/// Commits the git user made in `root` between `since` and `until`
316/// (newest first). Empty when git, the user or the repository is missing.
317pub fn session_commits(root: &Path, since: UtcDateTime, until: UtcDateTime) -> Vec<Commit> {
318    let git = |args: &[&str]| {
319        Command::new("git")
320            .arg("-C")
321            .arg(root)
322            .args(args)
323            .env("GIT_TERMINAL_PROMPT", "0")
324            .stdin(Stdio::null())
325            .stderr(Stdio::null())
326            .output()
327            .ok()
328            .filter(|o| o.status.success())
329            .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
330    };
331    let Some(author) = git(&["config", "user.email"])
332        .map(|s| s.trim().to_string())
333        .filter(|s| !s.is_empty())
334    else {
335        return Vec::new();
336    };
337    git(&[
338        "log",
339        "--no-merges",
340        "--no-color",
341        &format!("--max-count={MAX_LOG_COMMITS}"),
342        &format!("--since={}", since.to_rfc3339()),
343        &format!("--until={}", until.to_rfc3339()),
344        &format!("--author={author}"),
345        "--format=%H%x1f%cI%x1f%s%x1f%b%x1e",
346    ])
347    .map(|log| git_history::parse_log(&log))
348    .unwrap_or_default()
349}
350
351fn dead_end_dir(data_dir: &Path) -> std::path::PathBuf {
352    data_dir.join("capture").join("dead_ends")
353}
354
355/// The dead ends recorded for a session (`ctx_session finding tag=dead_end`).
356pub fn dead_ends(data_dir: &Path, session_id: &str) -> Vec<String> {
357    let file = dead_end_dir(data_dir).join(format!(
358        "{}.json",
359        crate::knowledge::draft::session_ref(session_id)
360    ));
361    std::fs::read(file)
362        .ok()
363        .and_then(|b| serde_json::from_slice(&b).ok())
364        .unwrap_or_default()
365}
366
367/// Record a dead end of a session. Kept private beside the capture state;
368/// it leaves the machine only inside a gated, screened episode.
369pub fn record_dead_end(data_dir: &Path, session_id: &str, text: &str) -> Result<(), CloudError> {
370    let mut all = dead_ends(data_dir, session_id);
371    let text = text.trim().to_string();
372    if text.is_empty() || all.contains(&text) {
373        return Ok(());
374    }
375    all.push(text);
376    let bytes = serde_json::to_vec(&all).map_err(|e| CloudError::Local(e.to_string()))?;
377    crate::state::write_private(
378        &dead_end_dir(data_dir),
379        &format!("{}.json", crate::knowledge::draft::session_ref(session_id)),
380        &bytes,
381    )
382}
383
384/// A session not written for this long has ended.
385const ENDED_AFTER_MS: u64 = 30 * 60_000;
386/// Replica meta: sessions that ended before this are never turned into
387/// episodes (no back-fill of the history before the first run).
388const EPISODES_SINCE: &str = "episodes_since";
389
390fn done_key(session_ref: &str) -> String {
391    format!("episode:{session_ref}")
392}
393
394/// The refs an episode of session `session_id` is uploaded with: its body
395/// `ses_` ref and its envelope ref.
396///
397/// With the local key (`refs`), the body's `ses_` ref is keyed
398/// ([`SessionRefs::episode_ref`]) as the envelope ref is: the unsalted
399/// [`crate::knowledge::draft::session_ref`] of a guessable session id would
400/// let the server tie the envelope ref, and every write of the session,
401/// back to the raw id. Without `refs` (the Cloud did not announce
402/// `session_ref`) no envelope ref is set, and the body is still keyed under
403/// the local key in `data_dir` ([`crate::session_ref::uploaded_ses_ref`]);
404/// when that key cannot be read or created this is an error and no episode
405/// is uploaded. Local-only uses (the done marker, dead ends, `own_sources`)
406/// keep the unsalted ref.
407fn uploaded_refs(
408    refs: Option<&SessionRefs>,
409    data_dir: &Path,
410    session_id: &str,
411) -> Result<(String, Option<String>), CloudError> {
412    match refs {
413        Some(refs) => Ok((refs.episode_ref(session_id), refs.event_ref(session_id))),
414        None => Ok((
415            crate::session_ref::uploaded_ses_ref(data_dir, session_id)?,
416            None,
417        )),
418    }
419}
420
421/// What [`emit_ended`] queued.
422#[derive(Debug)]
423pub struct EndedEpisodes {
424    pub queued: usize,
425    pub clock: Stamp,
426    /// Why the remaining ended sessions got no episode this run: the local
427    /// receipts key is unavailable ([`crate::session_ref::NO_SESSION_KEY`]).
428    /// They are not marked done, so a later run emits them.
429    pub withheld: Option<CloudError>,
430}
431
432/// Queue a signed episode for each session of the checkout at `root` that
433/// ended since the last run (once per session). Refusals are counted in the
434/// run, never kept as text. Returns the number queued and the clock, and
435/// why the rest was withheld when the local key is unavailable.
436pub fn emit_ended(
437    target: &super::emit::Target<'_>,
438    root: &Path,
439    data_dir: &Path,
440    run: &mut super::CaptureRun<'_>,
441    mut clock: Stamp,
442    now_ms: u64,
443) -> Result<EndedEpisodes, CloudError> {
444    let replica = target.replica;
445    let Some(since) = replica
446        .meta(EPISODES_SINCE)?
447        .and_then(|v| std::str::from_utf8(&v).ok()?.parse::<u64>().ok())
448    else {
449        replica.set_meta(EPISODES_SINCE, now_ms.to_string().as_bytes())?;
450        return Ok(EndedEpisodes {
451            queued: 0,
452            clock,
453            withheld: None,
454        });
455    };
456    let root_text = root.to_string_lossy();
457    let mut queued = 0;
458    for summary in SessionState::list_sessions() {
459        let ended = ms(summary.updated_at);
460        if summary
461            .project_root
462            .as_deref()
463            .map(|r| r.trim_end_matches('/'))
464            != Some(root_text.trim_end_matches('/'))
465            || ended <= since
466            || ended + ENDED_AFTER_MS > now_ms
467        {
468            continue;
469        }
470        let session_ref = crate::knowledge::draft::session_ref(&summary.id);
471        if replica.meta(&done_key(&session_ref))?.is_some() {
472            continue;
473        }
474        let Some(session) = SessionState::load_by_id(&summary.id) else {
475            continue;
476        };
477        // Before the session is marked done: without the local key no
478        // episode names it, and a later run emits it.
479        let (body_ref, envelope) = match uploaded_refs(target.sessions, data_dir, &summary.id) {
480            Ok(refs) => refs,
481            Err(error) => {
482                return Ok(EndedEpisodes {
483                    queued,
484                    clock,
485                    withheld: Some(error),
486                });
487            }
488        };
489        run.counts.considered += 1;
490        let commits = session_commits(root, session.started_at, session.updated_at);
491        let built = assemble(
492            &session,
493            root,
494            &dead_ends(data_dir, &session.id),
495            &commits,
496            &mut run.checkout,
497        )
498        .and_then(|e| screen(&e, run.screen).map(|()| e));
499        replica.set_meta(&done_key(&session_ref), b"1")?;
500        let mut episode = match built {
501            Ok(e) => e,
502            Err(reason) => {
503                run.counts.reject(reason);
504                continue;
505            }
506        };
507        clock = crate::events::hlc::send(clock, now_ms);
508        episode.session_ref = body_ref;
509        let (event, node_id) =
510            episode.node_add(target.place, clock, target.signer, envelope.as_deref())?;
511        let event_id = event["event_id"]
512            .as_str()
513            .ok_or_else(|| CloudError::Local("built event without id".into()))?
514            .to_string();
515        let bytes = serde_json::to_vec(&event).map_err(|e| CloudError::Local(e.to_string()))?;
516        replica.add_pending(&event_id, clock.wall_ms, clock.counter, None, &bytes)?;
517        replica.put_own_source(
518            &node_id,
519            "episode",
520            &json!({"project_hash": target.project_hash, "session_ref": session_ref}),
521        )?;
522        run.counts.captured += 1;
523        queued += 1;
524    }
525    Ok(EndedEpisodes {
526        queued,
527        clock,
528        withheld: None,
529    })
530}
531
532/// `ctx_session action=finding tag=dead_end`: record it for the session's
533/// episode when this machine is connected to Cloud. Never an error for the
534/// caller (a failure is recorded for `cloud status`).
535pub fn note_dead_end(session_id: &str, text: &str) {
536    let Ok(store) = crate::state::CloudStore::open() else {
537        return;
538    };
539    if !matches!(store.instance(), Ok(Some(_))) {
540        return;
541    }
542    if let Err(error) = record_dead_end(store.data_dir(), session_id, text) {
543        store.record_error(&format!("dead end: {error}"));
544    }
545}
546
547#[cfg(test)]
548#[path = "episode_tests.rs"]
549mod tests;