1use 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;
33const 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 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#[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 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
94fn 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
105fn 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
121pub 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 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
203pub 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
234pub 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 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 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 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
315pub 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
355pub 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
367pub 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
384const ENDED_AFTER_MS: u64 = 30 * 60_000;
386const EPISODES_SINCE: &str = "episodes_since";
389
390fn done_key(session_ref: &str) -> String {
391 format!("episode:{session_ref}")
392}
393
394fn 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#[derive(Debug)]
423pub struct EndedEpisodes {
424 pub queued: usize,
425 pub clock: Stamp,
426 pub withheld: Option<CloudError>,
430}
431
432pub 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 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
532pub 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;