diff --git a/CHANGELOG.md b/CHANGELOG.md index d13af361..5270ff48 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,9 +19,20 @@ and listed with their assets on the folder of it), and so does the MCP tool `lane_stop` without `lane`. In the main working tree, or outside a worktree, they ask for the name as before. - -### Added - +- **Hooks for the end of a session: `lane-stop` and `session-end`.** A + pool's skill can now give text at the end of the work, not only at a + session's start or a prompt (ADR-0094, addendum 2026-11-06). A + `lane-stop` text follows the output of `devstack lane stop` and of the + MCP tool `lane_stop`, every time, for the lane's worktree. A + `session-end` text cannot reach a session that is over: when Claude + Code ends a session where such a hook applies, devstack keeps that it + ended, and the next session of the same agent in the same working tree + is given the text once, with a line naming the ended session and its + transcript. Codex reports no end of a session and gets none; `devstack + doctor` says so. A hub now skips a hook of an event it does not know + and keeps the skill's other hooks; a hub before this release leaves out + all hooks of such a skill, so keep end-of-session hooks in a skill of + their own while members run older releases. - **`devstack init` sets `PYTHONUTF8 = "1"` for Python apps.** On Windows a native Python process opens text files in the ANSI code page (cp1252) unless the code passes `encoding=`, while the same code in a container diff --git a/Cargo.lock b/Cargo.lock index 0607e288..8599313a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -916,6 +916,7 @@ dependencies = [ "hyper-util", "include_dir", "indexmap", + "jiff", "keyring", "rand 0.10.3", "regex", diff --git a/crates/devstack-hub/Cargo.toml b/crates/devstack-hub/Cargo.toml index 40652535..71ee63b8 100644 --- a/crates/devstack-hub/Cargo.toml +++ b/crates/devstack-hub/Cargo.toml @@ -24,6 +24,7 @@ hyper.workspace = true hyper-util.workspace = true include_dir.workspace = true indexmap.workspace = true +jiff.workspace = true regex.workspace = true keyring.workspace = true sha2.workspace = true diff --git a/crates/devstack-hub/src/agenthooks.rs b/crates/devstack-hub/src/agenthooks.rs index fee60cf2..35228bc8 100644 --- a/crates/devstack-hub/src/agenthooks.rs +++ b/crates/devstack-hub/src/agenthooks.rs @@ -35,6 +35,8 @@ const COMMAND: &str = "devstack hook "; const TIMEOUT: u64 = 5; /// The folder of what each session was given. const SESSIONS: &str = "hook-sessions"; +/// The folder of the sessions that ended, kept for the next start. +const ENDED: &str = "hook-ended"; /// What a session was given is forgotten after this long. const KEEP: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600); @@ -79,14 +81,28 @@ pub fn read_index(state: &Path) -> Index { .unwrap_or_default() } -/// An event's name in an agent's configuration. -fn event_name(format: HookFormat, e: Event) -> &'static str { +/// The events an agent's configuration can carry an entry for. +const AGENT_EVENTS: [Event; 3] = [Event::SessionStart, Event::PromptSubmit, Event::SessionEnd]; + +/// An event's name in an agent's configuration; `None`: the agent has no +/// such event. `lane-stop` is no agent's: its texts follow `devstack lane +/// stop`'s output. Codex documents no end of a session (#462). +fn event_name(format: HookFormat, e: Event) -> Option<&'static str> { match (format, e) { - (HookFormat::Claude | HookFormat::Codex, Event::SessionStart) => "SessionStart", - (HookFormat::Claude | HookFormat::Codex, Event::PromptSubmit) => "UserPromptSubmit", + (HookFormat::Claude | HookFormat::Codex, Event::SessionStart) => Some("SessionStart"), + (HookFormat::Claude | HookFormat::Codex, Event::PromptSubmit) => Some("UserPromptSubmit"), + (HookFormat::Claude, Event::SessionEnd) => Some("SessionEnd"), + (HookFormat::Codex, Event::SessionEnd) | (_, Event::LaneStop) => None, } } +/// Whether the agent `id` reports the end of a session (`session-end`). +pub fn has_session_end(id: &str) -> bool { + devstack_skills::agents::get(id) + .and_then(|a| a.hooks.as_ref()) + .is_some_and(|h| event_name(h.format, Event::SessionEnd).is_some()) +} + /// The hub's entry for `agent` on `event`. fn command(event: Event, agent: &str) -> String { format!("{COMMAND}{} --agent {agent}", event.as_str()) @@ -136,8 +152,10 @@ pub fn configure( None => IndexMap::new(), }; let mut changed = false; - for e in [Event::SessionStart, Event::PromptSubmit] { - let name = event_name(format, e); + for e in AGENT_EVENTS { + let Some(name) = event_name(format, e) else { + continue; + }; let before: Value = match hooks.get(name) { Some(r) => serde_json::from_str(r.get()).map_err(|e| e.to_string())?, None => Value::Null, @@ -227,7 +245,7 @@ pub fn apply( let mut errors = Vec::new(); let mut events: Vec = Vec::new(); for h in &hooks { - if !events.contains(&h.hook.event) { + if AGENT_EVENTS.contains(&h.hook.event) && !events.contains(&h.hook.event) { events.push(h.hook.event); } } @@ -283,6 +301,19 @@ struct Input { /// Why a session starts: `startup`, `resume`, `clear`, `compact`. #[serde(default)] source: Option, + /// The session's transcript (`session-end`): named at the next start. + #[serde(default, alias = "transcriptPath")] + transcript_path: Option, +} + +/// The end of a session, kept for the next start in its working tree. +#[derive(Debug, Serialize, Deserialize)] +struct Ended { + #[serde(default, skip_serializing_if = "Option::is_none")] + session_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + transcript_path: Option, + at: String, } /// Where the dispatcher looks things up: the hub's state and git. @@ -314,6 +345,12 @@ pub fn run(event: Event, agent: &str, input: &str, at: &Lookup<'_>) -> String { if !index.agents.iter().any(|a| a == agent) { return String::new(); } + let cwd = input.cwd.as_deref().map(PathBuf::from); + let mut origin: Option> = None; + if event == Event::SessionEnd { + end(agent, &input, &index, cwd.as_deref(), at); + return String::new(); + } let session = input .session_id .as_deref() @@ -331,26 +368,13 @@ pub fn run(event: Event, agent: &str, input: &str, at: &Lookup<'_>) -> String { given.clear(); } } - let cwd = input.cwd.as_deref().map(PathBuf::from); - let mut origin: Option> = None; let prompt = input.prompt.as_deref().unwrap_or(""); - let mut out: Vec<&str> = Vec::new(); + let mut out: Vec = Vec::new(); let before = given.len(); for h in index.hooks.iter().filter(|h| h.hook.event == event) { - if let Some(u) = &h.hook.upstream - && !(at.accepted)(&h.pool, u) - { + if !applies(h, cwd.as_deref(), &mut origin, at) { continue; } - if !h.repos.is_empty() { - let o = origin.get_or_insert_with(|| cwd.as_deref().and_then(|c| (at.origin)(c))); - if !o - .as_deref() - .is_some_and(|o| devstack_node::skills::repo_matches(&h.repos, o)) - { - continue; - } - } let matched = match &h.hook.pattern { Some(p) => match regex::Regex::new(p).ok().and_then(|r| r.find(prompt)) { Some(m) => Some(m.as_str().trim().to_string()), @@ -366,7 +390,13 @@ pub fn run(event: Event, agent: &str, input: &str, at: &Lookup<'_>) -> String { continue; } given.push(key); - out.push(&h.hook.context); + out.push(h.hook.context.clone()); + } + if event == Event::SessionStart + && let Some(cwd) = &cwd + && let Some(texts) = ended(agent, &index, cwd, &mut origin, at) + { + out.push(texts); } if let Some(p) = &session && (given.len() != before || event == Event::SessionStart) @@ -379,6 +409,149 @@ pub fn run(event: Event, agent: &str, input: &str, at: &Lookup<'_>) -> String { out.join("\n\n") } +/// Whether a hook applies in the working tree at `cwd`: its upstream +/// accepted, its skill's repositories matching the tree's `origin` (asked +/// once, kept in `origin`). +fn applies( + h: &Entry, + cwd: Option<&Path>, + origin: &mut Option>, + at: &Lookup<'_>, +) -> bool { + if let Some(u) = &h.hook.upstream + && !(at.accepted)(&h.pool, u) + { + return false; + } + if !h.repos.is_empty() { + let o = origin.get_or_insert_with(|| cwd.and_then(|c| (at.origin)(c))); + if !o + .as_deref() + .is_some_and(|o| devstack_node::skills::repo_matches(&h.repos, o)) + { + return false; + } + } + true +} + +/// The working tree a path is in: the nearest folder above it (or it) +/// holding `.git`; the path itself outside a repository. Written the same +/// way whatever case or separators the agent used. +fn tree_of(cwd: &Path) -> String { + let tree = cwd + .ancestors() + .find(|d| d.join(".git").exists()) + .unwrap_or(cwd); + let s = tree.to_string_lossy().replace('\\', "/"); + let s = s.trim_end_matches('/'); + if cfg!(windows) { + s.to_lowercase() + } else { + s.to_string() + } +} + +/// The file that keeps the end of `agent`'s last session in `tree`. +fn ended_file(state: &Path, agent: &str, tree: &str) -> PathBuf { + let h = Sha256::digest(format!("{agent}\0{tree}").as_bytes()); + state + .join(ENDED) + .join(format!("{}.json", &devstack_node::skills::hex(&h)[..32])) +} + +/// `session-end`: the session can be told nothing any more. Where a +/// `session-end` hook applies in its working tree, keep that it ended, for +/// the next start of the same agent there ([`ended`]). +fn end(agent: &str, input: &Input, index: &Index, cwd: Option<&Path>, at: &Lookup<'_>) { + let Some(cwd) = cwd else { return }; + let mut origin = None; + let any = index + .hooks + .iter() + .filter(|h| h.hook.event == Event::SessionEnd) + .any(|h| applies(h, Some(cwd), &mut origin, at)); + if !any { + return; + } + let file = ended_file(at.state, agent, &tree_of(cwd)); + let record = Ended { + session_id: input.session_id.clone().filter(|s| !s.is_empty()), + transcript_path: input.transcript_path.clone().filter(|s| !s.is_empty()), + at: jiff::Zoned::now() + .strftime("%Y-%m-%dT%H:%M:%S%:z") + .to_string(), + }; + let _ = std::fs::create_dir_all(file.parent().expect("in the folder of ends")); + if let Err(e) = write(&file, &serde_json::to_vec(&record).expect("serialises")) { + (at.warn)(e); + } +} + +/// At a session's start: the texts of the `session-end` hooks for the +/// previous session of `agent` in this working tree, if one ended there +/// since, with a line that names it. Given once: the record goes. +fn ended( + agent: &str, + index: &Index, + cwd: &Path, + origin: &mut Option>, + at: &Lookup<'_>, +) -> Option { + prune(&at.state.join(ENDED)); + let file = ended_file(at.state, agent, &tree_of(cwd)); + let record: Ended = serde_json::from_slice(&std::fs::read(&file).ok()?).ok()?; + let _ = std::fs::remove_file(&file); + let texts: Vec<&str> = index + .hooks + .iter() + .filter(|h| h.hook.event == Event::SessionEnd) + .filter(|h| applies(h, Some(cwd), origin, at)) + .map(|h| h.hook.context.as_str()) + .collect(); + if texts.is_empty() { + return None; + } + let mut which = Vec::new(); + if let Some(id) = &record.session_id { + which.push(format!("session `{id}`")); + } + if let Some(t) = &record.transcript_path { + which.push(format!("transcript `{t}`")); + } + let which = if which.is_empty() { + String::new() + } else { + format!(" ({})", which.join(", ")) + }; + Some(format!( + "The previous session in this working tree{which} ended at {}. What follows was meant for its end:\n\n{}", + record.at, + texts.join("\n\n") + )) +} + +/// The texts of the hooks of `event` that apply in the working tree at +/// `cwd`, for every agent: `lane-stop`, whose texts follow `devstack lane +/// stop`'s output. Empty when none, or on any error. +pub fn texts_for(event: Event, cwd: &Path, at: &Lookup<'_>) -> String { + let index = read_index(at.state); + let mut origin = None; + index + .hooks + .iter() + .filter(|h| h.hook.event == event) + .filter(|h| applies(h, Some(cwd), &mut origin, at)) + .map(|h| h.hook.context.as_str()) + .collect::>() + .join("\n\n") +} + +/// [`texts_for`] with this machine's hub state, its git, its upstreams. +pub fn texts_here(event: Event, cwd: &Path) -> String { + here(event, "-", |at| texts_for(event, cwd, at)) +} + /// The file of what `agent`'s session `id` was given. fn session_file(agent: &str, id: &str) -> String { let h = Sha256::digest(format!("{agent}\0{id}").as_bytes()); @@ -406,24 +579,24 @@ fn prune(dir: &Path) { /// The dispatcher as `devstack hook` runs it: this machine's hub state, /// its git, its upstreams. pub fn run_here(event: Event, agent: &str, input: &str) -> String { + here(event, agent, |at| run(event, agent, input, at)) +} + +/// This machine's hub state, its git and its upstreams, for `f`. +fn here(event: Event, agent: &str, f: impl FnOnce(&Lookup<'_>) -> R) -> R { let state = crate::state_dir(); - run( - event, - agent, - input, - &Lookup { - state: &state, - origin: &|p| crate::branches::origin(p), - accepted: &|pool, name| crate::upstreams::Upstreams::pool_accepted(&state, pool, name), - warn: &|error| { - devstack_daemon::diag::DiagLog::open(crate::log_path()).write( - "warn", - "agent_hook", - serde_json::json!({ "event": event.as_str(), "agent": agent, "error": error }), - ); - }, + f(&Lookup { + state: &state, + origin: &|p| crate::branches::origin(p), + accepted: &|pool, name| crate::upstreams::Upstreams::pool_accepted(&state, pool, name), + warn: &|error| { + devstack_daemon::diag::DiagLog::open(crate::log_path()).write( + "warn", + "agent_hook", + serde_json::json!({ "event": event.as_str(), "agent": agent, "error": error }), + ); }, - ) + }) } #[cfg(test)] @@ -510,6 +683,158 @@ mod tests { assert!(!none.exists()); } + /// `session-end` is Claude Code's `SessionEnd`; Codex documents no end + /// of a session, and `lane-stop` is no agent's (#462). + #[test] + fn the_end_of_a_session_has_an_entry_where_the_agent_has_the_event() { + let d = tempfile::tempdir().unwrap(); + let f = d.path().join("settings.json"); + let all = [Event::SessionStart, Event::SessionEnd, Event::LaneStop]; + configure(&f, HookFormat::Claude, "claude-code", &all).unwrap(); + let v: Value = serde_json::from_str(&std::fs::read_to_string(&f).unwrap()).unwrap(); + assert_eq!( + v["hooks"]["SessionEnd"][0]["hooks"][0]["command"], + "devstack hook session-end --agent claude-code" + ); + let names: Vec<&String> = v["hooks"].as_object().unwrap().keys().collect(); + assert_eq!(names, ["SessionEnd", "SessionStart"]); + let c = d.path().join("hooks.json"); + configure(&c, HookFormat::Codex, "codex", &all).unwrap(); + let v: Value = serde_json::from_str(&std::fs::read_to_string(&c).unwrap()).unwrap(); + let names: Vec<&String> = v["hooks"].as_object().unwrap().keys().collect(); + assert_eq!(names, ["SessionStart"]); + // Only `lane-stop` hooks: no entry at all. + let st = tempfile::tempdir().unwrap(); + let home = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(home.path().join(".claude")).unwrap(); + let file = + |a: &Agent| (a.id == "claude-code").then(|| home.path().join(".claude/settings.json")); + let lane = vec![entry( + "timer", + hook(Event::LaneStop, None, "Stop the timer."), + )]; + assert!(apply(st.path(), lane, &|_| true, &file).is_empty()); + assert!(!home.path().join(".claude/settings.json").exists()); + assert_eq!(read_index(st.path()).hooks.len(), 1); + } + + /// The end of a session is kept, and its texts are given once at the + /// next start of the same agent in the same working tree (#462). + #[test] + fn the_end_of_a_session_reaches_the_next_start_in_its_tree() { + let st = tempfile::tempdir().unwrap(); + let src = tempfile::tempdir().unwrap(); + let shop = src.path().join("shop"); + let blog = src.path().join("blog"); + for d in [&shop, &blog] { + std::fs::create_dir_all(d.join(".git")).unwrap(); + } + std::fs::create_dir_all(shop.join("apps/web")).unwrap(); + let mut review = entry("work", hook(Event::SessionEnd, None, "Review the session.")); + review.repos = vec!["acme/shop".into()]; + let start = entry("work", hook(Event::SessionStart, None, "Start the timer.")); + let index = Index { + hooks: vec![start, review], + agents: vec!["claude-code".into(), "codex".into()], + without: Vec::new(), + }; + std::fs::write(st.path().join(INDEX), serde_json::to_vec(&index).unwrap()).unwrap(); + let at = Lookup { + state: st.path(), + origin: &|p| { + p.ancestors() + .any(|a| a.ends_with("shop")) + .then(|| "https://github.com/acme/shop".into()) + }, + accepted: &|_, _| true, + warn: &|e| panic!("{e}"), + }; + let input = |sid: &str, cwd: &Path| { + serde_json::json!({ + "session_id": sid, + "cwd": cwd, + "transcript_path": format!("/t/{sid}.jsonl"), + "source": "startup", + }) + .to_string() + }; + // Ending prints nothing; in a tree where no hook applies, nothing is kept. + assert_eq!( + run(Event::SessionEnd, "claude-code", &input("a", &blog), &at), + "" + ); + assert!(!st.path().join(ENDED).exists()); + assert_eq!( + run( + Event::SessionEnd, + "claude-code", + &input("a", &shop.join("apps/web")), + &at + ), + "" + ); + // Another agent, another tree: not theirs. + assert_eq!( + run(Event::SessionStart, "codex", &input("b", &shop), &at), + "Start the timer." + ); + assert_eq!( + run(Event::SessionStart, "claude-code", &input("b", &blog), &at), + "Start the timer." + ); + // The same agent in the same tree, from another folder of it. + let next = run(Event::SessionStart, "claude-code", &input("c", &shop), &at); + assert!(next.starts_with("Start the timer.\n\nThe previous session in this working tree (session `a`, transcript `/t/a.jsonl`) ended at "), "{next}"); + assert!( + next.ends_with("was meant for its end:\n\nReview the session."), + "{next}" + ); + // Once. + assert_eq!( + run(Event::SessionStart, "claude-code", &input("d", &shop), &at), + "Start the timer." + ); + } + + /// `lane-stop`: the texts that apply in the lane's worktree, every time. + #[test] + fn a_lane_stop_gives_its_texts_every_time() { + let st = tempfile::tempdir().unwrap(); + let mut timer = entry("timer", hook(Event::LaneStop, None, "Stop the timer.")); + timer.hook.upstream = Some("timetrack".into()); + let mut shop = entry("shop", hook(Event::LaneStop, None, "Shop teardown.")); + shop.repos = vec!["acme/shop".into()]; + let index = Index { + hooks: vec![ + timer, + shop, + entry("x", hook(Event::SessionStart, None, "Start.")), + ], + agents: Vec::new(), + without: Vec::new(), + }; + std::fs::write(st.path().join(INDEX), serde_json::to_vec(&index).unwrap()).unwrap(); + let accepted = std::cell::Cell::new(true); + let at = Lookup { + state: st.path(), + origin: &|p| { + p.ends_with("shop") + .then(|| "git@github.com:acme/shop.git".into()) + }, + accepted: &|_, name| name == "timetrack" && accepted.get(), + warn: &|e| panic!("{e}"), + }; + let shop_tree = Path::new("/src/shop"); + for _ in 0..2 { + assert_eq!( + texts_for(Event::LaneStop, shop_tree, &at), + "Stop the timer.\n\nShop teardown." + ); + } + accepted.set(false); + assert_eq!(texts_for(Event::LaneStop, Path::new("/src/blog"), &at), ""); + } + #[test] fn the_index_reaches_the_agents_switched_on_that_have_hooks() { let (st, home) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); diff --git a/crates/devstack-node/src/hooks.rs b/crates/devstack-node/src/hooks.rs index 606a5853..418e7f51 100644 --- a/crates/devstack-node/src/hooks.rs +++ b/crates/devstack-node/src/hooks.rs @@ -4,7 +4,7 @@ //! //! ```toml //! [[hook]] -//! event = "prompt-submit" # or "session-start" +//! event = "prompt-submit" # "session-start", "session-end", "lane-stop" //! match = '(^|\W)ABC-[0-9]+\b' # a regex on the prompt; prompt-submit only //! once = "match" # "session" or "match" //! upstream = "tracker" # only while the pool's upstream is accepted @@ -12,7 +12,8 @@ //! ``` //! //! A hook only adds text to the agent's context: no command of a pool runs -//! on a member's machine. +//! on a member's machine. A hook of an event this devstack does not know (a +//! newer one's) is skipped, the skill's other hooks stay (#462). use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; @@ -35,6 +36,13 @@ pub enum Event { SessionStart, /// The user sent a prompt, before the model reads it. PromptSubmit, + /// A session ended. Its text cannot reach that session any more: it is + /// given once at the next session start of the same agent in the same + /// working tree (#462). + SessionEnd, + /// `devstack lane stop` (or the MCP tool `lane_stop`) stopped a lane: + /// its text follows the command's output, for whoever ran it (#462). + LaneStop, } impl Event { @@ -42,6 +50,8 @@ impl Event { match self { Event::SessionStart => "session-start", Event::PromptSubmit => "prompt-submit", + Event::SessionEnd => "session-end", + Event::LaneStop => "lane-stop", } } @@ -49,6 +59,8 @@ impl Event { match s { "session-start" => Some(Event::SessionStart), "prompt-submit" => Some(Event::PromptSubmit), + "session-end" => Some(Event::SessionEnd), + "lane-stop" => Some(Event::LaneStop), _ => None, } } @@ -104,8 +116,21 @@ pub struct Hook { } /// The hooks of a skill whose files are `files` (path → content); none -/// without a `hooks.toml`; why not, for one that is wrong. +/// without a `hooks.toml`; why not, for one that is wrong. A hook of an +/// event a newer devstack knows is left out (a hub reads what its +/// coordinator, perhaps newer, packed); [`check_files`] refuses it. pub fn of_files(files: &BTreeMap>) -> Result, String> { + read(files, false) +} + +/// As [`of_files`], but an event this devstack does not know is an error: +/// the coordinator's check when it packs a skill, where it is a mistake of +/// the skill's author. +pub fn check_files(files: &BTreeMap>) -> Result, String> { + read(files, true) +} + +fn read(files: &BTreeMap>, strict: bool) -> Result, String> { let Some(text) = files.get(FILE) else { return Ok(Vec::new()); }; @@ -117,13 +142,25 @@ pub fn of_files(files: &BTreeMap>) -> Result, String> raw.hook .into_iter() .enumerate() + // An event a newer devstack knows: not this one's to give (#462). + .filter(|(_, r)| strict || Event::parse(&r.event).is_some() || !is_event_name(&r.event)) .map(|(i, r)| check(r, files).map_err(|e| format!("{FILE}, hook {}: {e}", i + 1))) .collect() } +/// What an event a newer devstack may know looks like (`a-z` and `-`): a +/// value that does not is a mistake, and the file is wrong. +fn is_event_name(s: &str) -> bool { + !s.is_empty() && s.len() <= 32 && s.bytes().all(|b| b.is_ascii_lowercase() || b == b'-') +} + fn check(r: Raw, files: &BTreeMap>) -> Result { - let event = Event::parse(&r.event) - .ok_or_else(|| format!("`{}`: the event is session-start or prompt-submit", r.event))?; + let event = Event::parse(&r.event).ok_or_else(|| { + format!( + "`{}`: the event is session-start, prompt-submit, session-end or lane-stop", + r.event + ) + })?; if let Some(p) = &r.pattern { if event != Event::PromptSubmit { return Err("`match` is for prompt-submit only".into()); @@ -239,10 +276,53 @@ context_file = "hooks/ticket.md" assert!(of_files(&BTreeMap::new()).unwrap().is_empty()); } + /// A hub reads what a newer coordinator packed: a hook of an event it + /// does not know is left out, the skill's other hooks stay (#462). + #[test] + fn an_event_of_a_newer_devstack_is_skipped_not_the_skill() { + let text = r#" +[[hook]] +event = "session-start" +context = "Start." + +[[hook]] +event = "tool-use" +context = "Later." + +[[hook]] +event = "session-end" +context = "Review the last session." + +[[hook]] +event = "lane-stop" +upstream = "nuts-timetrack" +context = "Stop the timer." +"#; + let h = of_files(&files(text)).unwrap(); + let events: Vec = h.iter().map(|h| h.event).collect(); + assert_eq!( + events, + [Event::SessionStart, Event::SessionEnd, Event::LaneStop] + ); + assert!(check_files(&files(text)).unwrap_err().contains("hook 2")); + for e in [Event::SessionEnd, Event::LaneStop] { + assert_eq!(Event::parse(e.as_str()), Some(e)); + } + // `match` stays prompt-submit's. + let lane_match = "[[hook]]\nevent = \"lane-stop\"\nmatch = \"x\"\ncontext = \"x\""; + assert!( + of_files(&files(lane_match)) + .unwrap_err() + .contains("prompt-submit only") + ); + } + #[test] fn a_wrong_hook_is_refused_with_why() { let wrong = |s: &str| of_files(&files(s)).unwrap_err(); - assert!(wrong("[[hook]]\nevent = \"tool-use\"\ncontext = \"x\"").contains("event")); + let strict = |s: &str| check_files(&files(s)).unwrap_err(); + assert!(strict("[[hook]]\nevent = \"tool-use\"\ncontext = \"x\"").contains("event")); + assert!(wrong("[[hook]]\nevent = \"Session Start\"\ncontext = \"x\"").contains("event")); assert!( wrong("[[hook]]\nevent = \"session-start\"\nmatch = \"x\"\ncontext = \"x\"") .contains("prompt-submit only") diff --git a/crates/devstack-node/src/skills.rs b/crates/devstack-node/src/skills.rs index a07ae35c..57b8f602 100644 --- a/crates/devstack-node/src/skills.rs +++ b/crates/devstack-node/src/skills.rs @@ -672,7 +672,7 @@ fn pack( .iter() .map(|(k, (b, _))| (k.clone(), b.clone())) .collect(); - Ok((front, crate::hooks::of_files(&texts)?.len())) + Ok((front, crate::hooks::check_files(&texts)?.len())) }); match hooks { Ok((front, hooks)) => { diff --git a/crates/devstack/src/client.rs b/crates/devstack/src/client.rs index a12643d0..ed71ef0b 100644 --- a/crates/devstack/src/client.rs +++ b/crates/devstack/src/client.rs @@ -2044,9 +2044,32 @@ pub fn lane_stop(stack_file: &Path, name: &str) -> Result<()> { println!( "lane `{name}` stopped; `devstack lane start {name}` (or `devstack up` in its worktree) starts it again" ); + let texts = lane_stop_texts(&c, name); + if !texts.is_empty() { + println!("\n{texts}"); + } Ok(()) } +/// The texts of the pools' `lane-stop` hooks that apply in the worktree of +/// the lane `name` (its name or branch), for whoever stopped it (#462). +/// Empty when none, and on any error: the stop stands. +pub fn lane_stop_texts(c: &Client, name: &str) -> String { + let lanes: Vec = c + .get("/v1/lanes") + .ok() + .and_then(|b| serde_json::from_str(&b).ok()) + .unwrap_or_default(); + let Some(path) = lanes + .iter() + .find(|l| l["name"] == name || l["branch"] == name) + .and_then(|l| l["path"].as_str()) + else { + return String::new(); + }; + devstack_hub::agenthooks::texts_here(devstack_node::hooks::Event::LaneStop, Path::new(path)) +} + /// A lane started from wherever this runs (#103): its name and its /// node's version warning, if any; `client` then talks to it. pub struct StartedLane { diff --git a/crates/devstack/src/doctor.rs b/crates/devstack/src/doctor.rs index 51b19ff9..5e4cbd5b 100644 --- a/crates/devstack/src/doctor.rs +++ b/crates/devstack/src/doctor.rs @@ -618,6 +618,26 @@ fn agent_hooks() -> Vec { ), )); } + // An agent with hooks, but without an end of a session (#462). + let ends = index + .hooks + .iter() + .any(|h| h.hook.event == devstack_node::hooks::Event::SessionEnd); + let no_end: Vec = index + .agents + .iter() + .filter(|a| ends && !devstack_hub::agenthooks::has_session_end(a)) + .map(|a| name(a)) + .collect(); + if !no_end.is_empty() { + out.push(f( + Level::Info, + format!( + "agent hooks: {} get no session-end hooks (the agent reports no end of a session)", + no_end.join(", ") + ), + )); + } if !index.without.is_empty() { let with: Vec = devstack_skills::agents::all() .iter() diff --git a/crates/devstack/src/mcp.rs b/crates/devstack/src/mcp.rs index fdc3ee6e..262d8e1b 100644 --- a/crates/devstack/src/mcp.rs +++ b/crates/devstack/src/mcp.rs @@ -986,9 +986,13 @@ fn call(name: &str, args: &Value, file: &Path) -> Result { if status >= 400 { anyhow::bail!("{}", client::error_text(&text)); } - Ok(format!( - "lane `{lane}` stopped; `lane_start` starts it again" - )) + let mut out = format!("lane `{lane}` stopped; `lane_start` starts it again"); + let texts = client::lane_stop_texts(&c, lane); + if !texts.is_empty() { + out.push_str("\n\n"); + out.push_str(&texts); + } + Ok(out) } "lane_move" | "lane_share" | "promote_lane" => { let lane = name_arg(args, "lane")?; diff --git a/docs/adr/0094-a-skill-carries-hooks-that-give-text-to-the-agents.md b/docs/adr/0094-a-skill-carries-hooks-that-give-text-to-the-agents.md index c5997824..b3a6fdb3 100644 --- a/docs/adr/0094-a-skill-carries-hooks-that-give-text-to-the-agents.md +++ b/docs/adr/0094-a-skill-carries-hooks-that-give-text-to-the-agents.md @@ -1,6 +1,6 @@ # ADR-0094: A skill carries hooks that give text to the agents; the hub writes one entry per agent and event, `devstack hook` picks the texts -- **Status:** Accepted (card in the pull request); built +- **Status:** Accepted (card in the pull request); built; addendum 2026-11-06 (end-of-session events, #462) - **Date:** 2026-11-05 - **Deciders:** project owner - **Related:** [ADR-0074](0074-a-pool-hands-out-skill-sets-the-hub-installs-them-for-the-agents.md) (skill sets, acceptance, the agent table), [ADR-0077](0077-a-sets-skills-are-grouped-and-switched-one-by-one.md) (a skill switched on and off), [ADR-0079](0079-skills-local-to-a-working-tree.md) (a skill bound to repositories), [ADR-0083](0083-the-hub-takes-out-what-an-agent-switched-off-leaves.md) (an agent switched off leaves nothing), [ADR-0069](0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md) (a pool's upstreams, accepted per member), [ADR-0071](0071-the-dashboard-writes-no-file-of-a-repository.md), [ADR-0070](0070-a-review-card-comes-before-the-code-an-adr-records-what-was-built.md); issue #453 @@ -157,3 +157,59 @@ wanted), `crates/devstack-hub/src/upstreams.rs` (`pool_accepted`), `crates/devstack-skills/src/agents.rs`, `scripts/sync-agents.py`, `crates/devstack/src/main.rs` (`devstack hook`), `crates/devstack/src/doctor.rs` (`agent_hooks`), `ui/src/views/SkillsView.vue`. + +## Addendum 2026-11-06: two events for the end of a session + +Issue #462. A routine that belongs to a session's end (stop a timer, review +the session) had only a `prompt-submit` hook matching closing words: a +session that ends without one gets nothing, a closing word mid-session fires +early. The owner approved the review card in the conversation on +**2026-11-06**, all three points: + +| # | Category | Point | Beats | Reversing costs | +|---|---|---|---|---| +| 1 | contract | `event` gets two values, `lane-stop` and `session-end`; a hub from 0.42.0 skips a hook of an event it does not know instead of leaving out the skill's hooks, a hub before it still leaves them out, so the documentation advises a skill of their own while members run older releases. | A version per hook; a file of their own for the new events. | The format has users outside the maintainers: additive changes only. | +| 2 | concept | `lane-stop`: after `devstack lane stop` (CLI) or the MCP tool `lane_stop` succeeded, devstack appends the texts of the `lane-stop` hooks that apply to the lane's worktree (skill on, repository bound, upstream accepted) to the output, every time, whichever agent ran it. | An agent hook on the shell command (Claude Code's `PostToolUse` only). | Low. | +| 3 | concept | `session-end`: the hub writes an entry for Claude Code's `SessionEnd`; the dispatcher only records the end (agent, session id, transcript path, working tree, time), and the next `session-start` of the same agent in the same working tree gives the texts once, with a line naming the ended session; a record older than seven days is dropped. | Text at `SessionEnd` (it never reaches the model); the closing-words heuristic. | Medium: state on disk, one more agent entry. | + +As built: + +1. **The format.** `Event` has `session-end` and `lane-stop`; `match` stays + `prompt-submit`'s. `hooks::of_files` (the hub, reading an archive) skips + a hook whose `event` looks like an event's name (`a-z` and `-`) but is + not one it knows; `hooks::check_files` (the coordinator, packing) refuses + it, so an author's typo still leaves the skill out with why. +2. **The entries.** `configure` writes entries for `session-start`, + `prompt-submit` and `session-end` where the agent has the event: Claude + Code `SessionEnd`; Codex documents no end of a session and gets none. + `lane-stop` is no agent's event; hooks of only that event write no entry. +3. **The end.** `devstack hook session-end` prints nothing. Where a + `session-end` hook applies at `cwd`, it writes `hook-ended/.json` in the hub's state (session id, transcript path, + time). The working tree is the nearest folder holding `.git` above `cwd` + (no git asked; on Windows compared without case). The next + `session-start` of that agent there appends, after the session-start + texts, "The previous session in this working tree (session `…`, + transcript `…`) ended at …. What follows was meant for its end:" and the + texts of the `session-end` hooks that apply then, and removes the file. + Records not touched for seven days are removed. +4. **The lane stop.** `client::lane_stop_texts` looks up the lane's worktree + (`GET /v1/lanes`, by name or branch) and `agenthooks::texts_here` gives + the `lane-stop` texts that apply there; `devstack lane stop` prints them + after its line, `lane_stop` appends them to its result. An error gives + nothing; the stop stands. +5. **Visibility.** `devstack doctor` names the agents that get hooks but no + `session-end` ones. + +Decided while building, not on the card: + +- `lane-stop` gives its texts on every stop; `once` does not apply. +- The end is recorded only where a `session-end` hook applies; a record is + given whatever the next session's source (`startup`, `resume`, `clear`). +- The coordinator stays strict about events (`check_files`). + +*Enforced by, added:* `crates/devstack-node/src/hooks.rs` (`Event`, +`of_files`, `check_files`), `crates/devstack-hub/src/agenthooks.rs` +(`event_name`, `end`, `ended`, `texts_for`), `crates/devstack/src/client.rs` +(`lane_stop`, `lane_stop_texts`), `crates/devstack/src/mcp.rs` (`lane_stop`), +`crates/devstack/src/doctor.rs` (`agent_hooks`). diff --git a/docs/adr/README.md b/docs/adr/README.md index aa0bad93..31acf6c2 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -176,6 +176,6 @@ stay. | [0091](0091-public-links-through-the-users-own-named-tunnel.md) | Public links can go through the user's own named tunnel, at stable addresses; the hub runs its one connector | Accepted (card in the pull request); built; its step 3, the pool, built by ADR-0092 | | [0092](0092-public-links-through-the-pool.md) | A pool can give its members public links below a zone of its own; the coordinator holds the token, each machine gets its own tunnel | Accepted (card in the pull request); built | | [0093](0093-the-main-tree-takes-its-profile-when-it-starts.md) | The main working tree takes its profile when it starts; the daemon carries none | Accepted (card in the pull request); built | -| [0094](0094-a-skill-carries-hooks-that-give-text-to-the-agents.md) | A skill carries hooks that give text to the agents; the hub writes one entry per agent and event, `devstack hook` picks the texts | Accepted (card in the pull request); built | +| [0094](0094-a-skill-carries-hooks-that-give-text-to-the-agents.md) | A skill carries hooks that give text to the agents; the hub writes one entry per agent and event, `devstack hook` picks the texts | Accepted (card in the pull request); built; addendum 2026-11-06 (end-of-session events `lane-stop`, `session-end`) | | [0095](0095-the-daemon-ends-with-the-last-tree.md) | The daemon ends with the last tree; a stack has no start of its own, a stop always takes a tree's containers | Accepted (card in the pull request); built | | [0096](0096-a-port-held-now-refuses-the-start-one-up-of-a-tree-at-a-time.md) | A port held now refuses the start, whoever holds it (a stopped stack's containers too); one `up` of a tree at a time | Accepted (card in the pull request); built | diff --git a/docs/pool.md b/docs/pool.md index 170f24cc..6132e0de 100644 --- a/docs/pool.md +++ b/docs/pool.md @@ -859,13 +859,38 @@ event = "prompt-submit" # the user sent a prompt match = '(^|\W)ABC-[0-9]+\b' # a regex on the prompt once = "match" # once a session per ticket (the default with `match`); "session": once context_file = "hooks/ticket.md" # a file of the skill, instead of `context` + +[[hook]] +event = "lane-stop" # `devstack lane stop` or the MCP tool `lane_stop` stopped a lane +upstream = "timetrack" +context = "The lane is down: stop the session's timer now, then run the session review." + +[[hook]] +event = "session-end" # given at the next session start in the same working tree +upstream = "timetrack" +context = "Close that session's timer at its last activity and review it." ``` +Two events belong to the end of a session. A `lane-stop` text follows the +output of `devstack lane stop` and of the MCP tool `lane_stop`, every time, +whichever agent (or person) ran it; it applies by the lane's worktree. A +`session-end` text cannot reach a session that is over: when Claude Code +ends a session (exit, `/clear`, logout) in a working tree where such a hook +applies, devstack keeps that it ended, and the next session start of the +same agent in the same working tree gives the text once, after a line that +names the ended session and its transcript. An end not followed by a start +within a week is forgotten. Codex reports no end of a session and gets no +`session-end` hooks; `devstack doctor` says so. + A hook only gives text to the agent's context; no command of a pool runs on a member's machine. The text is 1 to 2000 characters, a skill has eight hooks at most, and a `hooks.toml` that is wrong (an unknown key, a pattern -that is no regex, a file not in the skill) leaves the skill out of the -fetch, with why. A hook comes and goes with its skill: accepted with the +that is no regex, a file not in the skill, an event the coordinator does +not know) leaves the skill out of the fetch, with why. A member's hub skips +a hook of an event it does not know yet and keeps the skill's others; a +hub before 0.42.0 leaves out all hooks of such a skill instead, so put +`lane-stop` and `session-end` hooks into a skill of their own while members +run older releases. A hook comes and goes with its skill: accepted with the set, switched on and off with the skill, bound to its repositories, and updated when the skill is (with updates waiting, the text stays as agreed to).