diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a350c8f..04c0bd5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,22 @@ and listed with their assets on the ## [Unreleased] +### Added + +- **The Skills page shows what happens for your agent.** A new tab, Flow, + draws the hooks of the skills switched on by when they give their text: a + session starts, a prompt matches, a lane stops, a session ends. Hovering a + hook says when it applies, on what condition, how often, for which agents, + and how its text begins; a hook that is not given is greyed and says why + (an upstream neither accepted nor set up in the agent). Beside it is what + devstack did for the agent, by session: each hook it gave and each tool + call through `devstack mcp`, with how long it took and whether it failed; + a click on a hook narrows the list to it, and the tool calls show under + the skill whose upstream they use. Only what happened is kept, never a + prompt, a hook's text, a tool's arguments or its answer, on this machine, + for a week (ADR-0098). The agent's own tools (its shell, its edits) do + not pass devstack and are not shown. + ## [0.42.0] - 2026-11-06 A pool's skill can now speak at the end of the work: a `lane-stop` diff --git a/crates/devstack-hub/src/activity.rs b/crates/devstack-hub/src/activity.rs new file mode 100644 index 00000000..99dbcd37 --- /dev/null +++ b/crates/devstack-hub/src/activity.rs @@ -0,0 +1,462 @@ +//! What devstack did for the coding agents (#482): each hook it gave text +//! for, and each tool call that passed `devstack mcp`. The Skills page shows +//! it beside the flow of the hooks. +//! +//! - **Only what happened.** A record holds the event, the agent, its +//! session, the working tree, the hooks given (pool, set, skill, place) or +//! the tool's name, how long it took and whether it failed. Never the +//! prompt, a hook's text, a tool's arguments or its answer. It stays on +//! this machine (not in the pool's telemetry) and goes after a week. +//! - **One file per process and day.** The writers are short-lived +//! processes (`devstack hook`) and long-lived ones (`devstack mcp`), many +//! at once: each appends to its own `activity/-.jsonl`, so no +//! two write into one file. +//! - **A session** is the agent's `session_id` from a hook's input. A tool +//! call carries none: it belongs to the latest session that started in its +//! working tree before it. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; +use tokio::sync::watch; + +/// The folder in the hub's state. +const DIR: &str = "activity"; +/// How long a record is kept. +const KEEP: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600); +/// At most this many records an answer carries (the latest). +const MAX: usize = 500; + +/// A hook given, by where it is. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct HookRef { + pub pool: String, + pub set: String, + pub skill: String, + pub index: usize, +} + +/// One line of an activity file. Times are Unix ms as `u64`: an +/// internally tagged enum cannot read a `u128` back. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum Record { + /// The dispatcher ran for an event: the hooks it gave text for. + Hook { + at: u64, + event: String, + agent: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + session: Option, + tree: String, + #[serde(default)] + hooks: Vec, + /// `session-end`: the end was kept for the next start. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + recorded: bool, + }, + /// A tool call through `devstack mcp`. + Tool { + at: u64, + tool: String, + /// The MCP client's name (`clientInfo.name`). + #[serde(default, skip_serializing_if = "Option::is_none")] + client: Option, + tree: String, + pid: u32, + ms: u64, + ok: bool, + }, +} + +impl Record { + pub fn at(&self) -> u64 { + match self { + Record::Hook { at, .. } | Record::Tool { at, .. } => *at, + } + } + + fn tree(&self) -> &str { + match self { + Record::Hook { tree, .. } | Record::Tool { tree, .. } => tree, + } + } +} + +pub fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX)) +} + +/// 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 caller used. +pub 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() + } +} + +/// Append `r` to this process's file of today under `state`. +pub fn write(state: &Path, r: &Record) -> Result<(), String> { + let dir = state.join(DIR); + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let day = jiff::Zoned::now().strftime("%Y-%m-%d").to_string(); + let path = dir.join(format!("{day}-{}.jsonl", std::process::id())); + let mut line = serde_json::to_string(r).map_err(|e| e.to_string())?; + line.push('\n'); + std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .and_then(|mut f| f.write_all(line.as_bytes())) + .map_err(|e| format!("{}: {e}", path.display())) +} + +/// [`write`] into this machine's hub state; an error goes to the hub's +/// diagnostic log, never to the caller (a hook or a tool call goes on). +pub fn write_here(r: &Record) { + if let Err(e) = write(&crate::state_dir(), r) { + devstack_daemon::diag::DiagLog::open(crate::log_path()).write( + "warn", + "activity", + serde_json::json!({ "error": e }), + ); + } +} + +/// Every record kept under `state`, oldest first; files older than a week +/// go. +pub fn read(state: &Path) -> Vec { + let Ok(rd) = std::fs::read_dir(state.join(DIR)) else { + return Vec::new(); + }; + let mut out = Vec::new(); + for e in rd.flatten() { + let path = e.path(); + let old = e + .metadata() + .and_then(|m| m.modified()) + .ok() + .and_then(|t| t.elapsed().ok()) + .is_some_and(|age| age > KEEP); + if old { + let _ = std::fs::remove_file(&path); + continue; + } + if path.extension().is_none_or(|x| x != "jsonl") { + continue; + } + let Ok(text) = std::fs::read_to_string(&path) else { + continue; + }; + out.extend( + text.lines() + .filter_map(|l| serde_json::from_str::(l).ok()), + ); + } + out.sort_by_key(Record::at); + out +} + +/// A print of the activity folder: changes when a record is added. +fn print(state: &Path) -> (usize, u64) { + let Ok(rd) = std::fs::read_dir(state.join(DIR)) else { + return (0, 0); + }; + rd.flatten() + .filter_map(|e| e.metadata().ok()) + .fold((0, 0), |(n, len), m| (n + 1, len + m.len())) +} + +/// An agent's session, from its hooks' records. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Session { + pub agent: String, + pub session: String, + pub tree: String, + pub started: u64, + pub last: u64, + /// It reported its end (`session-end`). + pub ended: bool, +} + +/// What `GET /hub/activity` answers. +#[derive(Debug, Clone, Serialize)] +pub struct View { + pub sessions: Vec, + /// The records asked for, newest last; a tool call with the session it + /// is put to and, for an upstream's tool, the skills whose hooks name + /// that upstream. + pub records: Vec, +} + +/// Which upstream a tool belongs to: its prefix's (pool, name), for the +/// pools' upstreams. +pub type Prefixes = Vec<(String, String, String)>; + +/// Sessions and records, `tree` and `session` narrowing them, `since` (Unix +/// ms) leaving out older ones. `prefixes` gives an upstream tool's (pool, +/// name), `index` the skills whose hooks name an upstream. +pub fn view( + records: &[Record], + tree: Option<&str>, + session: Option<&str>, + since: Option, + prefixes: &Prefixes, + index: &crate::agenthooks::Index, +) -> View { + let mut sessions: Vec = Vec::new(); + for r in records { + let Record::Hook { + at, + agent, + session: Some(id), + tree, + event, + .. + } = r + else { + continue; + }; + match sessions + .iter_mut() + .find(|s| &s.agent == agent && &s.session == id) + { + Some(s) => { + s.last = s.last.max(*at); + s.ended |= event == "session-end"; + } + None => sessions.push(Session { + agent: agent.clone(), + session: id.clone(), + tree: tree.clone(), + started: *at, + last: *at, + ended: event == "session-end", + }), + } + } + let mut out = Vec::new(); + for r in records { + let mut v = serde_json::to_value(r).expect("serialises"); + // A record without a session of its own (a tool call, a lane's + // stop): the latest session that started in its tree before it. + let own = matches!( + r, + Record::Hook { + session: Some(_), + .. + } + ); + if !own + && let Some(s) = sessions + .iter_mut() + .filter(|s| s.tree == r.tree() && s.started <= r.at()) + .max_by_key(|s| s.started) + { + s.last = s.last.max(r.at()); + v["session"] = Value::String(s.session.clone()); + if matches!(r, Record::Tool { .. }) { + v["agent"] = Value::String(s.agent.clone()); + } + } + // A pool's upstream's tool: the upstream, and the skills whose hooks + // name it. + if let Record::Tool { tool, .. } = r + && let Some((prefix, _)) = tool.split_once("__") + && let Some((pool, name, _)) = prefixes.iter().find(|(_, _, p)| p == prefix) + { + v["upstream"] = Value::String(name.clone()); + let mut skills: Vec = index + .hooks + .iter() + .filter(|h| &h.pool == pool && h.hook.upstream.as_deref() == Some(name)) + .map(|h| h.skill.clone()) + .collect(); + skills.dedup(); + v["skills"] = serde_json::json!(skills); + } + if tree.is_some_and(|t| t != r.tree()) + || session.is_some_and(|s| v["session"].as_str() != Some(s)) + || since.is_some_and(|t| r.at() < t) + { + continue; + } + out.push(v); + } + if out.len() > MAX { + out.drain(..out.len() - MAX); + } + sessions.sort_by_key(|s| std::cmp::Reverse(s.last)); + View { + sessions, + records: out, + } +} + +static FEED: OnceLock> = OnceLock::new(); + +/// Look at the activity folder every two seconds while a dashboard +/// listens, and tell it when a record was added. +pub fn follow() { + if FEED.set(watch::channel(0).0).is_err() { + return; + } + let _ = std::thread::Builder::new() + .name("activity".into()) + .spawn(|| { + let state = crate::state_dir(); + let mut last = print(&state); + loop { + std::thread::sleep(std::time::Duration::from_secs(2)); + let tx = FEED.get().expect("set above"); + if tx.receiver_count() == 0 { + continue; + } + let now = print(&state); + if now != last { + last = now; + tx.send_replace(now_ms()); + } + } + }); +} + +/// When a record was last added (Unix ms; 0: not since the hub started). +pub fn subscribe() -> watch::Receiver { + match FEED.get() { + Some(f) => f.subscribe(), + None => watch::channel(0).1, + } +} + +/// The hub's state folder, for the handler. +pub fn state() -> PathBuf { + crate::state_dir() +} + +#[cfg(test)] +mod tests { + use super::*; + use devstack_node::hooks::{Event, Hook, Once}; + + fn hook(at: u64, event: &str, session: &str, tree: &str) -> Record { + Record::Hook { + at, + event: event.into(), + agent: "claude".into(), + session: Some(session.into()), + tree: tree.into(), + hooks: Vec::new(), + recorded: event == "session-end", + } + } + + fn tool(at: u64, name: &str, tree: &str) -> Record { + Record::Tool { + at, + tool: name.into(), + client: Some("claude-code".into()), + tree: tree.into(), + pid: 7, + ms: 12, + ok: true, + } + } + + #[test] + fn records_go_one_file_per_process_and_come_back_in_order() { + let d = tempfile::tempdir().unwrap(); + write(d.path(), &tool(20, "status", "/w")).unwrap(); + write(d.path(), &hook(10, "session-start", "s1", "/w")).unwrap(); + let files: Vec<_> = std::fs::read_dir(d.path().join(DIR)).unwrap().collect(); + assert_eq!(files.len(), 1, "one file for this process"); + let back = read(d.path()); + assert_eq!(back.iter().map(Record::at).collect::>(), [10, 20]); + } + + /// No prompt, text or argument can be written: the record has no field + /// for them. + #[test] + fn a_record_holds_what_happened_only() { + let v = serde_json::to_value(tool(1, "status", "/w")).unwrap(); + let keys: Vec<&str> = v.as_object().unwrap().keys().map(String::as_str).collect(); + for k in ["arguments", "prompt", "text", "result", "context"] { + assert!(!keys.contains(&k), "{keys:?}"); + } + } + + #[test] + fn a_tool_call_goes_to_the_latest_session_started_in_its_tree() { + let entry = |skill: &str, upstream: &str| crate::agenthooks::Entry { + pool: "default".into(), + set: "core".into(), + skill: skill.into(), + index: 0, + repos: Vec::new(), + hook: Hook { + event: Event::SessionStart, + pattern: None, + once: Once::Session, + upstream: Some(upstream.into()), + context: "x".into(), + }, + }; + let index = crate::agenthooks::Index { + hooks: vec![entry("work-session", "timetrack")], + agents: vec!["claude".into()], + without: Vec::new(), + }; + let prefixes = vec![( + "default".to_string(), + "timetrack".to_string(), + "nuts_timetrack".to_string(), + )]; + let records = vec![ + hook(10, "session-start", "s1", "/a"), + tool(15, "nuts_timetrack__start_timer", "/a"), + hook(20, "session-start", "s2", "/a"), + hook(21, "session-start", "s3", "/b"), + tool(25, "status", "/a"), + tool(26, "status", "/c"), + hook(30, "session-end", "s2", "/a"), + // A lane's stop has no session of its own. + Record::Hook { + at: 31, + event: "lane-stop".into(), + agent: "-".into(), + session: None, + tree: "/a".into(), + hooks: Vec::new(), + recorded: false, + }, + ]; + let v = view(&records, None, None, None, &prefixes, &index); + assert_eq!(v.records[1]["session"], "s1"); + assert_eq!(v.records[1]["upstream"], "timetrack"); + assert_eq!(v.records[1]["skills"], serde_json::json!(["work-session"])); + assert_eq!(v.records[4]["session"], "s2", "the later start in /a"); + assert!(v.records[5].get("session").is_none(), "no session in /c"); + let s2 = v.sessions.iter().find(|s| s.session == "s2").unwrap(); + assert!(s2.ended); + assert_eq!(s2.last, 31, "the lane's stop counts to it"); + assert_eq!(v.records[7]["session"], "s2", "the lane's stop"); + assert!(v.records[7].get("agent").unwrap() == "-"); + let only = view(&records, Some("/a"), Some("s2"), None, &prefixes, &index); + assert_eq!(only.records.len(), 4, "{:?}", only.records); + let since = view(&records, None, None, Some(25), &prefixes, &index); + assert_eq!(since.records.len(), 4); + } +} diff --git a/crates/devstack-hub/src/agenthooks.rs b/crates/devstack-hub/src/agenthooks.rs index 245852a1..dcd0b4fc 100644 --- a/crates/devstack-hub/src/agenthooks.rs +++ b/crates/devstack-hub/src/agenthooks.rs @@ -19,6 +19,7 @@ //! this session) and prints their texts. It never blocks a prompt: on //! any error it prints nothing. +use crate::activity::{HookRef, Record, tree_of}; use devstack_node::hooks::{Event, Hook, Once}; use devstack_skills::agents::{Agent, HookFormat}; use indexmap::IndexMap; @@ -60,6 +61,15 @@ impl Entry { fn key(&self) -> String { format!("{}/{}/{}#{}", self.pool, self.set, self.skill, self.index) } + + fn reference(&self) -> HookRef { + HookRef { + pool: self.pool.clone(), + set: self.set.clone(), + skill: self.skill.clone(), + index: self.index, + } + } } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -351,7 +361,9 @@ pub fn run(event: Event, agent: &str, input: &str, at: &Lookup<'_>) -> String { 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); + if let Some(refs) = end(agent, &input, &index, cwd.as_deref(), at) { + record(at, event, agent, &input, cwd.as_deref(), refs, true); + } return String::new(); } let session = input @@ -373,6 +385,7 @@ pub fn run(event: Event, agent: &str, input: &str, at: &Lookup<'_>) -> String { } let prompt = input.prompt.as_deref().unwrap_or(""); let mut out: Vec = Vec::new(); + let mut refs: Vec = Vec::new(); let before = given.len(); for h in index.hooks.iter().filter(|h| h.hook.event == event) { if !applies(h, cwd.as_deref(), &mut origin, at) { @@ -394,13 +407,19 @@ pub fn run(event: Event, agent: &str, input: &str, at: &Lookup<'_>) -> String { } given.push(key); out.push(h.hook.context.clone()); + refs.push(h.reference()); } if event == Event::SessionStart && let Some(cwd) = &cwd - && let Some(texts) = ended(agent, &index, cwd, &mut origin, at) + && let Some(texts) = ended(agent, &index, cwd, &mut origin, at, &mut refs) { out.push(texts); } + // A session's start always, to know the session; a prompt only when it + // was given something. + if event == Event::SessionStart || !refs.is_empty() { + record(at, event, agent, &input, cwd.as_deref(), refs, false); + } if let Some(p) = &session && (given.len() != before || event == Event::SessionStart) { @@ -438,23 +457,6 @@ fn applies( 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()); @@ -463,19 +465,52 @@ fn ended_file(state: &Path, agent: &str, tree: &str) -> PathBuf { .join(format!("{}.json", &devstack_node::skills::hex(&h)[..32])) } +/// What happened, into the activity (#482): never the prompt or a text. +fn record( + at: &Lookup<'_>, + event: Event, + agent: &str, + input: &Input, + cwd: Option<&Path>, + hooks: Vec, + recorded: bool, +) { + let r = Record::Hook { + at: crate::activity::now_ms(), + event: event.as_str().into(), + agent: agent.into(), + session: input.session_id.clone().filter(|s| !s.is_empty()), + tree: cwd.map(tree_of).unwrap_or_default(), + hooks, + recorded, + }; + if let Err(e) = crate::activity::write(at.state, &r) { + (at.warn)(e); + } +} + /// `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 }; +/// the next start of the same agent there ([`ended`]). The hooks it was +/// kept for; `None` when none applies. +fn end( + agent: &str, + input: &Input, + index: &Index, + cwd: Option<&Path>, + at: &Lookup<'_>, +) -> Option> { + let cwd = cwd?; let mut origin = None; - let any = index + let refs: Vec = index .hooks .iter() .filter(|h| h.hook.event == Event::SessionEnd) - .any(|h| applies(h, Some(cwd), &mut origin, at)); - if !any { - return; + .filter(|h| applies(h, Some(cwd), &mut origin, at)) + .map(Entry::reference) + .collect(); + if refs.is_empty() { + return None; } let file = ended_file(at.state, agent, &tree_of(cwd)); let record = Ended { @@ -489,6 +524,7 @@ fn end(agent: &str, input: &Input, index: &Index, cwd: Option<&Path>, at: &Looku if let Err(e) = write(&file, &serde_json::to_vec(&record).expect("serialises")) { (at.warn)(e); } + Some(refs) } /// At a session's start: the texts of the `session-end` hooks for the @@ -500,21 +536,23 @@ fn ended( cwd: &Path, origin: &mut Option>, at: &Lookup<'_>, + refs: &mut Vec, ) -> 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 + let given: Vec<&Entry> = 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() { + if given.is_empty() { return None; } + refs.extend(given.iter().map(|h| h.reference())); + let texts: Vec<&str> = given.iter().map(|h| h.hook.context.as_str()).collect(); let mut which = Vec::new(); if let Some(id) = &record.session_id { which.push(format!("session `{id}`")); @@ -540,11 +578,18 @@ fn ended( pub fn texts_for(event: Event, cwd: &Path, at: &Lookup<'_>) -> String { let index = read_index(at.state); let mut origin = None; - index + let given: Vec<&Entry> = index .hooks .iter() .filter(|h| h.hook.event == event) .filter(|h| applies(h, Some(cwd), &mut origin, at)) + .collect(); + if !given.is_empty() { + let refs = given.iter().map(|h| h.reference()).collect(); + record(at, event, "-", &Input::default(), Some(cwd), refs, false); + } + given + .iter() .map(|h| h.hook.context.as_str()) .collect::>() .join("\n\n") @@ -583,7 +628,7 @@ fn prune(dir: &Path) { /// read only then, configured in the agent itself at the pool's URL (#473: /// a member who added the server by its own setup hint got no hook). /// `own` reads the agent's servers. -fn upstream_there( +pub(crate) fn upstream_there( state: &Path, pool: &str, name: &str, @@ -1015,5 +1060,34 @@ mod tests { assert_eq!(prompt("now ABC-13"), "Ticket checklist."); // Input it cannot read: nothing, no error. assert_eq!(run(Event::PromptSubmit, "claude-code", "not json", &at), ""); + + // The activity (#482): each start, each prompt that was given + // something, with the hooks by where they are, never a text. + let records = crate::activity::read(st.path()); + let hooks: Vec<(String, Vec)> = records + .iter() + .map(|r| match r { + crate::activity::Record::Hook { event, hooks, .. } => ( + event.clone(), + hooks.iter().map(|h| h.skill.clone()).collect(), + ), + crate::activity::Record::Tool { .. } => unreachable!(), + }) + .collect(); + assert_eq!(hooks.len(), 6, "{hooks:?}"); + assert_eq!(hooks[1].1, ["shop", "timer"]); + assert_eq!( + hooks[4], + ("prompt-submit".to_string(), vec!["ticket".to_string()]) + ); + let text = std::fs::read_dir(st.path().join("activity")) + .unwrap() + .flatten() + .map(|e| std::fs::read_to_string(e.path()).unwrap()) + .collect::(); + assert!( + !text.contains("Ticket checklist") && !text.contains("ABC-12"), + "{text}" + ); } } diff --git a/crates/devstack-hub/src/lib.rs b/crates/devstack-hub/src/lib.rs index 962dad97..f4153873 100644 --- a/crates/devstack-hub/src/lib.rs +++ b/crates/devstack-hub/src/lib.rs @@ -34,6 +34,7 @@ use tokio_stream::StreamExt; static UI: Dir<'_> = include_dir!("$OUT_DIR/ui"); +pub mod activity; pub mod agenthooks; pub mod agentmcp; mod branches; @@ -82,7 +83,7 @@ pub struct HubInfo { pub started: u128, } -fn state_dir() -> PathBuf { +pub(crate) fn state_dir() -> PathBuf { devstack_daemon::token::token_path() .parent() .expect("token path has a parent") @@ -489,6 +490,9 @@ pub fn serve() -> Result<(), String> { // Every stack's worktrees, its daemon running or not (ADR-0078), // and the skills local to them (ADR-0079). worktrees::start(); + // What devstack did for the agents (#482), told while a dashboard + // listens. + activity::follow(); poolskills::follow(state.skills.clone()); // The lanes connected to, connected again when they or this hub // start again (ADR-0085). @@ -659,6 +663,7 @@ fn router(state: AppState) -> axum::Router { .route("/hub/pool/skills/refresh", post(pool::skills_refresh)) .route("/hub/pool/skills/{name}", delete(pool::skill_remove)) .route("/hub/skills", get(poolskills::get)) + .route("/hub/activity", get(activity_get)) .route("/hub/skills/sync", post(poolskills::sync)) .route("/hub/skills/agents/{id}", put(poolskills::agent)) .route("/hub/skills/sets/{pool}/{set}", put(poolskills::auto)) @@ -1576,6 +1581,10 @@ fn hub_events(s: &AppState) -> impl tokio_stream::Stream 0) + .map(|at| serde_json::json!({ "type": "activity", "at": at })); // What needs attention (ADR-0097): again when a stream's glance or the // stack list (a start failed, a stack stopped) changed, sent only when // the items did. @@ -1603,6 +1612,7 @@ fn hub_events(s: &AppState) -> impl tokio_stream::Stream, Json(b): Json) -> Re } } +#[derive(Deserialize)] +struct ActivityQuery { + #[serde(default)] + tree: Option, + #[serde(default)] + session: Option, + #[serde(default)] + since: Option, +} + +/// `GET /hub/activity`: what devstack did for the coding agents (#482), the +/// agents' sessions and the records, narrowed by `tree`, `session`, `since`. +async fn activity_get(State(s): State, Query(q): Query) -> Response { + let ups = s.upstreams.clone(); + let got = tokio::task::spawn_blocking(move || { + let state = activity::state(); + let records = activity::read(&state); + // A pool's upstream by the prefix of its tools. + let prefixes: activity::Prefixes = ups + .views() + .unwrap_or_default() + .into_iter() + .filter_map(|v| v.pool.map(|p| (p.pool, p.name, v.prefix))) + .collect(); + let index = agenthooks::read_index(&state); + activity::view( + &records, + q.tree.as_deref(), + q.session.as_deref(), + q.since, + &prefixes, + &index, + ) + }) + .await; + match got { + Ok(v) => Json(v).into_response(), + Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + } +} + /// `DELETE /hub/upstreams/{name}`: it and its credential go. async fn upstream_remove(State(s): State, Path(name): Path) -> Response { on_upstreams(&s, move |ups| { diff --git a/crates/devstack-hub/src/poolskills.rs b/crates/devstack-hub/src/poolskills.rs index 612a1f63..9f170d12 100644 --- a/crates/devstack-hub/src/poolskills.rs +++ b/crates/devstack-hub/src/poolskills.rs @@ -127,6 +127,98 @@ pub struct SkillView { /// How many hooks it carries (ADR-0094). #[serde(skip_serializing_if = "is_zero")] pub hooks: usize, + /// Its hooks as they are given (#482): only of a skill switched on and + /// installed, as the version agreed to has them. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub hook_details: Vec, +} + +/// A hook of a skill, for the Skills page's flow (#482). +#[derive(Debug, Clone, Serialize)] +pub struct HookDetail { + /// Its place in the skill's `hooks.toml`. + pub index: usize, + pub event: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + pub pattern: Option, + /// `session` or `match`. + pub once: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + pub upstream: Option, + /// The start of its text. + pub preview: String, + /// The agents that get it, by name. + pub agents: Vec, + /// Its upstream is there: accepted, or configured in an agent (#473). + pub applies: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub why: Option, +} + +/// How many characters of a hook's text the page shows. +const PREVIEW: usize = 160; + +/// The hooks of `skill` in the index, as the page shows them. +fn hook_details( + dir: &Path, + index: &crate::agenthooks::Index, + pool: &str, + set: &str, + skill: &str, +) -> Vec { + use devstack_node::hooks::{Event, Once}; + let agents = |event: Event| -> Vec { + index + .agents + .iter() + .filter(|a| event != Event::SessionEnd || crate::agenthooks::has_session_end(a)) + .map(|a| { + devstack_skills::agents::get(a) + .map(|x| x.name.clone()) + .unwrap_or_else(|| a.clone()) + }) + .collect() + }; + index + .hooks + .iter() + .filter(|h| h.pool == pool && h.set == set && h.skill == skill) + .map(|h| { + let there = h.hook.upstream.as_deref().is_none_or(|u| { + crate::agenthooks::upstream_there(dir, pool, u, &|| { + index + .agents + .iter() + .flat_map(|a| crate::agentmcp::of_agent(a, None)) + .collect() + }) + }); + let text = &h.hook.context; + let mut preview: String = text.chars().take(PREVIEW).collect(); + if text.chars().count() > PREVIEW { + preview.push('…'); + } + HookDetail { + index: h.index, + event: h.hook.event.as_str(), + pattern: h.hook.pattern.clone(), + once: match h.hook.once { + Once::Session => "session", + Once::Match => "match", + }, + upstream: h.hook.upstream.clone(), + preview, + agents: agents(h.hook.event), + applies: there, + why: (!there).then(|| { + format!( + "the upstream `{}` is neither accepted nor set up in an agent", + h.hook.upstream.as_deref().unwrap_or_default() + ) + }), + } + }) + .collect() } fn is_zero(n: &usize) -> bool { @@ -946,6 +1038,7 @@ impl PoolSkills { let lists = self.lists(); let agents = self.agents(&s); let trees = self.seen.lock().unwrap().clone(); + let index = crate::agenthooks::read_index(&self.dir); let mut sets = Vec::new(); for (pool, ms) in &lists { for m in ms { @@ -1026,6 +1119,11 @@ impl PoolSkills { t }, hooks: k.hooks, + hook_details: if enabled && k.hooks > 0 { + hook_details(&self.dir, &index, pool, &m.name, &k.name) + } else { + Vec::new() + }, } }) .collect(), diff --git a/crates/devstack/src/mcp.rs b/crates/devstack/src/mcp.rs index 262d8e1b..18ab2a84 100644 --- a/crates/devstack/src/mcp.rs +++ b/crates/devstack/src/mcp.rs @@ -345,14 +345,38 @@ fn handle(m: Value, file: &Path, out: &Out) { } let (file, out) = (file.to_path_buf(), out.clone()); std::thread::spawn(move || { + let tool = m["params"]["name"].as_str().unwrap_or("").to_string(); + let t0 = std::time::Instant::now(); let r = respond(m, &file); RUNNING.fetch_sub(1, Ordering::SeqCst); + record(&tool, t0.elapsed(), r.as_ref()); if let Some(r) = r { send(&out, r); } }); } +/// The MCP client's name, from its `initialize` (`clientInfo.name`). +static CLIENT: Mutex> = Mutex::new(None); + +/// A tool call into the agents' activity (#482): its name, how long it +/// took, whether it failed; never its arguments or its answer. +fn record(tool: &str, took: Duration, r: Option<&Value>) { + let ok = r.is_some_and(|r| r.get("error").is_none() && r["result"]["isError"] != true); + let tree = std::env::current_dir() + .map(|d| devstack_hub::activity::tree_of(&d)) + .unwrap_or_default(); + devstack_hub::activity::write_here(&devstack_hub::activity::Record::Tool { + at: devstack_hub::activity::now_ms(), + tool: tool.to_string(), + client: CLIENT.lock().unwrap_or_else(|e| e.into_inner()).clone(), + tree, + pid: std::process::id(), + ms: u64::try_from(took.as_millis()).unwrap_or(u64::MAX), + ok, + }); +} + /// The answer to one message, if it needs one. fn respond(m: Value, file: &Path) -> Option { if !m.is_object() { @@ -367,6 +391,9 @@ fn respond(m: Value, file: &Path) -> Option { let params = m.get("params").cloned().unwrap_or(Value::Null); Some(match method { "initialize" => { + if let Some(c) = params["clientInfo"]["name"].as_str() { + *CLIENT.lock().unwrap_or_else(|e| e.into_inner()) = Some(c.to_string()); + } let asked = params["protocolVersion"].as_str().unwrap_or(""); let version = VERSIONS .iter() diff --git a/docs/adr/0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md b/docs/adr/0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md new file mode 100644 index 00000000..67c523d7 --- /dev/null +++ b/docs/adr/0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md @@ -0,0 +1,96 @@ +# ADR-0098: The Skills page shows the flow of the hooks and the agents' activity; devstack keeps only what happened, on this machine, for a week + +- **Status:** Accepted (card in the pull request); built +- **Date:** 2026-11-06 +- **Deciders:** project owner +- **Related:** [ADR-0094](0094-a-skill-carries-hooks-that-give-text-to-the-agents.md) (hooks, and its addenda: `lane-stop`, `session-end`, an upstream set up in the agent), [ADR-0069](0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md) (upstreams through `devstack mcp`), [ADR-0037](0037-pool-telemetry.md) (the pool's telemetry, which this is not part of); issue #482 + +## Context + +A developer could not see what devstack does for their coding agent while +it works. The Skills page listed the skills and how many hooks each carries, +not when a hook gives its text, under which condition, or what followed. +A hook that stayed silent (an upstream not accepted, #473) said nothing +about why. devstack sees part of what an agent does: the hooks it gives, and +the tool calls through `devstack mcp` (its own tools and the upstreams'). +The agent's built-in tools (shell, editing, reading files) do not pass it. + +## Decision + +The owner approved the review card in the conversation on **2026-11-06**, +all four points: + +| # | Category | Point | Beats | Reversing costs | +|---|---|---|---|---| +| 1 | trust | The activity holds only what happened: the event, the skill, the hook's place or the tool's name, how long it took and whether it failed; never a prompt, a hook's text, a tool's arguments or its answer. It stays on this machine (not in the pool's telemetry) and goes after seven days. | Recording arguments and answers (a full trace); sending it to the pool | Low: a record could gain fields later, with a card of its own | +| 2 | concept | A session is the agent's `session_id` from a hook's input; a tool call (and a lane's stop) carries none and is put to the latest session that started in its working tree before it. | Asking the agent for a session id on the MCP connection (none known to be passed) | Medium: two agents in one working tree at once are not told apart | +| 3 | contract | `GET /hub/skills` carries per hook its event, condition and the start of its text (`hook_details`); `GET /hub/activity` gives the sessions and the records; `/hub/events` sends `activity` when a record was added. | Working the flow out in the browser from the archives | Low: additive fields and a new endpoint | +| 4 | term | The Skills page has a tab **Flow**, beside the sets. | A tab on a working tree's page ("what my agent does here") | Low: that can come as well | + +As built: + +1. **The records.** `devstack hook` writes one line per session start (to + know the session), per prompt it gave text for, per `session-end` it kept, + per `lane-stop` text given; `devstack mcp` one per `tools/call` (tool, + MCP client name, working tree from its folder, pid, ms, ok). Each process + appends to its own `activity/-.jsonl` in the hub's state, so no + two processes write one file; an error goes to the hub's log, never to + the hook or the call. Files older than seven days go when the hub reads + them. +2. **The answer.** `GET /hub/activity?tree=&session=&since=` reads the files, + builds the sessions from the hooks' records, puts each record without a + session to the latest session started in its tree before it, and names + for an upstream's tool the upstream (by the prefix the pool gives it) and + the skills whose hooks name that upstream. At most the latest 500 records. +3. **The event.** While a dashboard listens, the hub looks at the folder + every two seconds and sends `{"type":"activity","at"}` when it changed; + the page reads `/hub/activity` again. +4. **The details.** Per hook of a skill switched on: `index`, `event`, + `pattern`, `once`, `upstream`, the first 160 characters of its text, the + agents that get it, and whether its upstream is there (accepted, or set + up in an agent), with why not. +5. **The page.** The flow's phases (a session starts, a prompt matches, a + lane stops, a session ends) with each hook as a node in its skill's + colour; a tooltip says when, on what condition, how often, for which + agents, and the start of its text; a hook that is not given is greyed + with why. Beside it the activity, narrowed by a session and by a click on + a node; below the flow the tool calls by the skill whose upstream they + use. + +Decided while building, not on the card: + +- A prompt's hooks are grouped by their pattern within one phase, not split + into phases by guessing what a pattern means. +- A session start is recorded even when it gave no text: without it the + session and its tool calls could not be told. +- The record's times are Unix milliseconds as 64-bit numbers (a tagged + record cannot read a 128-bit one back). + +## Alternatives considered + +- **A full trace with arguments and answers.** It would show more, but it + holds what a user typed, file contents and tokens an upstream returned; + a log of that is a second copy of the user's work outside their control. +- **The agent's built-in tools through a `PostToolUse` hook.** The only way + to see the shell and the edits; its input carries commands and file + contents. Left for a card of its own, opt-in, names and durations only. +- **A tab on a working tree's page.** Where a developer looks for "what my + agent does here"; the Skills page first, because the hooks are the + skills'. + +## Consequences + +- Every session start and every tool call through `devstack mcp` writes a + line to disk; a busy week is a few thousand lines. +- Two agents working in one working tree at once share their tool calls in + the activity. +- What an agent does without devstack (its own shell, edits) is not shown. + +## Enforced by + +`crates/devstack-hub/src/activity.rs` (the record, the files, the view, the +event), `crates/devstack-hub/src/agenthooks.rs` (`record`), +`crates/devstack/src/mcp.rs` (`record`), `crates/devstack-hub/src/lib.rs` +(`activity_get`, the `activity` event), `crates/devstack-hub/src/poolskills.rs` +(`hook_details`), `ui/src/lib/flow.ts`, `ui/src/components/SkillsFlow.vue`, +`ui/src/views/SkillsView.vue`, `docs/dashboard-api.md`. diff --git a/docs/adr/README.md b/docs/adr/README.md index 379e117a..bd9aca89 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -180,3 +180,4 @@ stay. | [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 | | [0097](0097-the-dashboards-mark-says-what-needs-attention.md) | The dashboard's mark and favicon carry a red or yellow dot for what needs attention, from an `attention` event of the hub; the mark flips to the nut | Accepted (card in the pull request); built | +| [0098](0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md) | The Skills page shows the flow of the hooks and the agents' activity; devstack keeps only what happened, on this machine, for a week | Accepted (card in the pull request); built | diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index 5919921f..7cc5c3f5 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -59,7 +59,7 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `GET /hub/summary` | cookie or token | every registered stack at a glance, for the tray ([ADR-0060](adr/0060-the-tray-is-a-client-of-the-hub.md)): `{"state", "version", "stacks": [{id, name, repo, running, state, ready, total, lanes, attention: [{lane, service, text, detail}]}]}`. A stack's `state`: `stopped`, `starting`, `stopping` (a start or stop the hub runs), `ok` or `attention`; the whole `state` is the worst: `attention`, `starting`, `ok` (a stack runs) or `idle`. `ready` of `total`: the main tree's services running, healthy or done. `lanes`: started lanes. `attention`: what notifies (ADR-0045) and is still so, in the main tree and every started lane (`lane` names it): a failed service (not one the user stopped, not one held back by another's failure), a candidate `held` or whose build `failed`, a lane whose start or move on a node failed (`service` `null`); and a failed start from the dashboard (`service` `null`). Each item's `level` ([ADR-0097](adr/0097-the-dashboards-mark-says-what-needs-attention.md)): `warn` for a candidate held, `error` for the rest; older hubs leave it out. Containers are not in it. `version`: the hub's devstack | | `GET /hub/ports` | cookie or token | the ports of every registered stack on this machine and where two stacks meet ([ADR-0082](adr/0082-the-ports-of-a-machine.md)): `{"stacks": [{id, name, running, containers?, ports: [PortEntry]}], "overlaps": [{port, proto, stacks: [{id, name, lane, holder?, kind}]}]}`. A running stack's `ports` are its daemon's `GET /v1/ports` (see [Ports](#ports)); a stack whose daemon does not run, or does not answer it (an older devstack), has what its stack file declares for the main working tree, each `kind: "declared"`, `lane: "main"`, moved by its shift on this machine: its services' `port`, its Compose groups' `announced_ports` and the ports on this machine their `urls` name (other published ports of the Compose files are not read). What a stopped stack's containers publish that run all the same (Docker started them again by their restart policy, or a stop kept them) is asked of Docker: those ports are `kind: "published"`, `listening: true`, in place of a declared entry of the same port, and the stack has `containers: true` ([ADR-0096](adr/0096-a-port-held-now-refuses-the-start-one-up-of-a-tree-at-a-time.md)). A stopped stack whose stack file is gone is left out; one whose file does not load has no ports. An overlap is one `port` and `proto` in more than one stack, each use listed once; an `instance` port does not count (the OS hands it out). Computed on request, nothing is polled | | `GET /hub/ws?path=` | cookie + Origin | WebSocket that carries the server-sent event stream at `` (`/hub/events`, `/hub/stacks/{id}/api/v1/...`, or `/hub/pool/shared/{lease}/api/v1/...[?pool=]` for a lane shared with this machine), one text message per event's `data`; how the dashboard reads every stream (a browser allows six HTTP/1.1 connections per host across all its tabs, WebSockets do not count; ADR-0021). The upstream is opened before the upgrade: `503` for a stack not running, `400` for another path. When the stream ends the socket closes | -| `GET /hub/events` | cookie | SSE: `{"type":"stacks","stacks":[StackEntry]}` and `{"type":"docker","docker":DockerEngine}` and `{"type":"release","current","newer":string|null,"error":string|null}` (a newer devstack; checked at start, every 12 h by the clock and when a dashboard connects and the last answer is over an hour old, unless `DEVSTACK_NO_UPDATE_CHECK`; `error` why the last check failed, no network or GitHub's rate limit, tried again after an hour and `null` once one succeeds, while a `newer` found before stays; older hubs leave it out) and `{"type":"update","update":{"running":bool,"error":string|null,"installed":string|null,"finished":ms|null}}` (the dashboard's update; `finished` is when the last one ended, `installed` the version it installed, told by the hub it started) and `{"type":"guests","guests":[Guest]}` (lanes of other members on this machine, every pool: `{pool, lease, member, owner, repo, lane, state: "offered"\|"running", since: unix s, cpus, memory}`, the leases whose node is this machine; read when the pool's stream says its leases or nodes changed) and `{"type":"worktrees","worktrees":{"":""}}` (a version of each registered stack's worktrees, running or not, ADR-0078: the hub looks at their folder once a second; a stack's lanes are read again when its version changes; older hubs never send it. Since ADR-0088 the version also moves when a checked-out branch or its upstream moves: their loose ref files, `packed-refs` and `FETCH_HEAD`, looked at without running git; the dashboard reads `branches` again then) and `{"type":"attention","items":[{stack, lane, service, text, detail, level}]}` (what needs attention in every stack, the items of `/hub/summary` with their stack's id, [ADR-0097](adr/0097-the-dashboards-mark-says-what-needs-attention.md): sent again when one changed; the dashboard's dot on its mark and favicon; older hubs never send it) and `{"type":"pools","pools":{"":{"live":"connecting"\|"live"\|"lost"\|"old","error"?,"versions":{"members","nodes","leases","upstreams","telemetry"}}}}` (the pools this machine follows over their coordinators' streams, ADR-0073: `old` for a coordinator without one, whose parts are read when the pool area opens; `versions` of each part, read again when one is not the one read last; older hubs never send it), each first and on every change | +| `GET /hub/events` | cookie | SSE: `{"type":"stacks","stacks":[StackEntry]}` and `{"type":"docker","docker":DockerEngine}` and `{"type":"release","current","newer":string|null,"error":string|null}` (a newer devstack; checked at start, every 12 h by the clock and when a dashboard connects and the last answer is over an hour old, unless `DEVSTACK_NO_UPDATE_CHECK`; `error` why the last check failed, no network or GitHub's rate limit, tried again after an hour and `null` once one succeeds, while a `newer` found before stays; older hubs leave it out) and `{"type":"update","update":{"running":bool,"error":string|null,"installed":string|null,"finished":ms|null}}` (the dashboard's update; `finished` is when the last one ended, `installed` the version it installed, told by the hub it started) and `{"type":"guests","guests":[Guest]}` (lanes of other members on this machine, every pool: `{pool, lease, member, owner, repo, lane, state: "offered"\|"running", since: unix s, cpus, memory}`, the leases whose node is this machine; read when the pool's stream says its leases or nodes changed) and `{"type":"worktrees","worktrees":{"":""}}` (a version of each registered stack's worktrees, running or not, ADR-0078: the hub looks at their folder once a second; a stack's lanes are read again when its version changes; older hubs never send it. Since ADR-0088 the version also moves when a checked-out branch or its upstream moves: their loose ref files, `packed-refs` and `FETCH_HEAD`, looked at without running git; the dashboard reads `branches` again then) and `{"type":"activity","at":ms}` (a record was added to the agents' activity, [ADR-0098](adr/0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md): read `/hub/activity` again; looked at every two seconds while a dashboard listens; older hubs never send it) and `{"type":"attention","items":[{stack, lane, service, text, detail, level}]}` (what needs attention in every stack, the items of `/hub/summary` with their stack's id, [ADR-0097](adr/0097-the-dashboards-mark-says-what-needs-attention.md): sent again when one changed; the dashboard's dot on its mark and favicon; older hubs never send it) and `{"type":"pools","pools":{"":{"live":"connecting"\|"live"\|"lost"\|"old","error"?,"versions":{"members","nodes","leases","upstreams","telemetry"}}}}` (the pools this machine follows over their coordinators' streams, ADR-0073: `old` for a coordinator without one, whose parts are read when the pool area opens; `versions` of each part, read again when one is not the one read last; older hubs never send it), each first and on every change | | `POST /hub/update` | cookie + Origin | `202`: `devstack update` in the background (output in `hub/update.log`); on success it restarts the hub on the new version, so the dashboard reconnects to it, and the new hub's `update` event names the installed version (the old hub leaves `hub/update.json` for it; a hub that starts on the old version while the updater runs waits for it and reports a failure); on failure the `update` event carries the end of its output. `409` while one runs (checked and claimed in one step). Running stacks switch at their next restart | | `POST /hub/update/check` | cookie + Origin | look for a newer release now: `{"current", "newer": string\|null}`, the same as the next `release` event; asked again within 30 s, the last answer (GitHub allows 60 unauthenticated requests an hour). `409` with `DEVSTACK_NO_UPDATE_CHECK`, `502` when GitHub cannot be asked, `504` after 30 s | | `POST /hub/stacks/scan` | cookie + Origin | `{"path", "add"?, "depth"?, "git_only"?, "configured_only"?}`: the folders below a folder (default one level, `depth` is clamped to 1 to 6; a repository only at its root, linked worktrees skipped) that are git repositories (`git_only`, default `true`) and have a `devstack.toml` (`configured_only`, default `true`); both `false` is a 400 (ADR-0089). `[{repo, id, name, error, configured, registered, added}]`: `configured` false is a folder without a stack file, named after the folder; with `add` the valid new ones are registered | @@ -101,7 +101,8 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `POST /hub/pool/skills {name, source, to, repos?, folders?}` | cookie + Origin | admins only: add a set, or change the one of that name, and have it fetched; `400` with why; audited | | `DELETE /hub/pool/skills/{name}` | cookie + Origin | admins only: stop handing it out: `204`; audited | | `POST /hub/pool/skills/refresh[?set=]` | cookie + Origin | admins only: have the coordinator fetch the sets (or one) again: `202` | -| `GET /hub/skills` | cookie | the pools' skill sets on this machine (ADR-0074), the agents looked for again (one installed since shows, switched off) and the state told on `/hub/events` too: `{agents: [{id, name, dir, project?, enabled, hooks}], sets: [{pool, set, source, state: "offered"\|"accepted"\|"declined"\|"changed", auto, fetched?, commit?, error?, skills: [{name, description, sha256, installed, pending, enabled, group?, tags?, updated?, agents, repos?, trees?, hooks?}]}], conflicts: [{dir, name, reason}], errors?, synced?}`; also on `/hub/events` as `{"type":"skills","skills":...}`, first and on every change. Per skill ([ADR-0077](adr/0077-a-sets-skills-are-grouped-and-switched-one-by-one.md)): `enabled` (switched on; older hubs leave it out), `group` and `tags` (from `metadata` in its frontmatter), `updated` (when this hub wrote it, Unix ms), `agents` (the names of the agents whose folder holds it). [ADR-0079](adr/0079-skills-local-to-a-working-tree.md): an agent's `project` is its skill folder in a working tree; a skill's `repos` binds it to repositories (it goes into the agents' folders of their working trees, not the user folders), `trees` are the working trees it is in, and `installed` means in every folder it goes to. [ADR-0094](adr/0094-a-skill-carries-hooks-that-give-text-to-the-agents.md): a skill's `hooks` is how many hooks its `hooks.toml` has (left out when none), an agent's `hooks` whether it gets them | +| `GET /hub/skills` | cookie | the pools' skill sets on this machine (ADR-0074), the agents looked for again (one installed since shows, switched off) and the state told on `/hub/events` too: `{agents: [{id, name, dir, project?, enabled, hooks}], sets: [{pool, set, source, state: "offered"\|"accepted"\|"declined"\|"changed", auto, fetched?, commit?, error?, skills: [{name, description, sha256, installed, pending, enabled, group?, tags?, updated?, agents, repos?, trees?, hooks?}]}], conflicts: [{dir, name, reason}], errors?, synced?}`; also on `/hub/events` as `{"type":"skills","skills":...}`, first and on every change. Per skill ([ADR-0077](adr/0077-a-sets-skills-are-grouped-and-switched-one-by-one.md)): `enabled` (switched on; older hubs leave it out), `group` and `tags` (from `metadata` in its frontmatter), `updated` (when this hub wrote it, Unix ms), `agents` (the names of the agents whose folder holds it). [ADR-0079](adr/0079-skills-local-to-a-working-tree.md): an agent's `project` is its skill folder in a working tree; a skill's `repos` binds it to repositories (it goes into the agents' folders of their working trees, not the user folders), `trees` are the working trees it is in, and `installed` means in every folder it goes to. [ADR-0094](adr/0094-a-skill-carries-hooks-that-give-text-to-the-agents.md): a skill's `hooks` is how many hooks its `hooks.toml` has (left out when none), an agent's `hooks` whether it gets them. [ADR-0098](adr/0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md): a skill switched on carries `hook_details: [{index, event: "session-start"\|"prompt-submit"\|"lane-stop"\|"session-end", pattern?, once: "session"\|"match", upstream?, preview, agents, applies, why?}]` (`preview` the first 160 characters of its text; `agents` the names of the agents that get it; `applies` whether its upstream is there, accepted or set up in an agent, `why` when not); older hubs leave it out | +| `GET /hub/activity?tree=&session=&since=` | cookie | what devstack did for the coding agents ([ADR-0098](adr/0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md)), kept on this machine for seven days: `{sessions: [{agent, session, tree, started, last, ended}], records: [Record]}`, a record `{kind: "hook", at, event, agent, session?, tree, hooks: [{pool, set, skill, index}], recorded?}` (a hook given; `recorded`: a `session-end` kept for the next start) or `{kind: "tool", at, tool, client?, tree, pid, ms, ok, session?, agent?, upstream?, skills?}` (a tool call through `devstack mcp`; `upstream` and `skills` for a pool's upstream's tool: the skills whose hooks name it). Never a prompt, a hook's text, a tool's arguments or its answer. A record without a session (a tool call, a lane's stop) is put to the latest session that started in its working tree (`tree`, the folder holding `.git`, lower case on Windows) before it; `tree`, `session` and `since` (Unix ms) narrow the answer, at most the latest 500 records; on `/hub/events` `{"type":"activity","at"}` says a record was added | | `PUT /hub/skills/agents/{id} {enabled}` | cookie + Origin | install into that agent's user skill folder (and, for bound skills and devstack's generated ones, its folder in the working trees), or no longer (what devstack installed there goes); the state after it, `409` with why | | `PUT /hub/skills/sets/{pool}/{set}/skills/{name} {enabled}`, `PUT /hub/skills/sets/{pool}/{set}/groups/{group} {enabled}` | cookie + Origin | switch a skill of an accepted set, or every skill of a group (`-`: the skills without one), on or off (ADR-0077); off, it goes from the agents' folders unless changed there; the state after it, `409` with why | | `POST /hub/skills/sets/{pool}/{set}/accept {auto}`, `.../decline`, `.../update`; `PUT /hub/skills/sets/{pool}/{set} {auto}` | cookie + Origin | accept a set from its source (updates at once with `auto`, else they wait), decline or remove it, take its waiting updates, change `auto`; the state after it | diff --git a/docs/pool.md b/docs/pool.md index 21d722dc..18bc3897 100644 --- a/docs/pool.md +++ b/docs/pool.md @@ -920,6 +920,18 @@ change. The user's own hooks and the files' other keys stay as they are; an agent switched off loses the entry. The Skills page shows a skill's hooks and which agent switched on gets none; `devstack doctor` says so too. +The Skills page's tab **Flow** ([ADR-0098](adr/0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md)) +draws the hooks of the skills switched on by when they give their text (a +session starts, a prompt matches, a lane stops, a session ends); hovering a +hook says when, on what condition, how often, for which agents, and the +start of its text, and a hook that is not given says why. Beside it is what +devstack did for the agent: each hook it gave and each tool call through +`devstack mcp`, by session; a click on a hook narrows the list to it. Only +what happened is kept (the event, the hook or the tool, how long, whether +it failed), never a prompt, a text, an argument or an answer, on this +machine, for a week. The agent's own tools (its shell, its edits) do not +pass devstack and are not shown. + ## Several pools A machine can belong to several pools, a customer's beside the team's, each diff --git a/ui/src/api/mock/activity.ts b/ui/src/api/mock/activity.ts new file mode 100644 index 00000000..256c70ef --- /dev/null +++ b/ui/src/api/mock/activity.ts @@ -0,0 +1,94 @@ +// The agents' activity as the mock hub answers `GET /hub/activity` (#482): +// a session in shop's main tree half an hour ago, one in a lane now. +import type { ActivityRecord, ActivityView, HookDetail } from '../types'; + +const ref = (skill: string, index: number) => ({ pool: 'default', set: 'core', skill, index }); + +/** The hooks of the mock's skills, as `/hub/skills` describes them. */ +export const mockHookDetails: Record = { + 'work-session': [ + { + index: 0, + event: 'session-start', + once: 'session', + upstream: 'timetrack', + preview: 'Work session: load the skill work-session now, before the first task. It starts the timer. If its tools are not listed yet, search for them…', + agents: ['Claude Code'], + applies: true, + }, + { + index: 1, + event: 'prompt-submit', + pattern: '(?i)\\b(done|wrap up|lane (stop|prune))\\b', + once: 'match', + upstream: 'timetrack', + preview: 'End of the session in sight: if the work is done, stop the timer first, then review the session as the last step.', + agents: ['Claude Code'], + applies: true, + }, + ], + 'work-issue': [ + { + index: 0, + event: 'prompt-submit', + pattern: '(^|\\s)#[0-9]{2,}\\b|github\\.com/[^\\s/]+/[^\\s/]+/(issues|pull)/[0-9]+', + once: 'match', + preview: 'The prompt names a ticket or a pull request. Before the first change, load the skill work-issue and read its project file…', + agents: ['Claude Code'], + applies: true, + }, + ], + 'session-end': [ + { + index: 0, + event: 'lane-stop', + once: 'session', + upstream: 'timetrack', + preview: 'Lane stopped. If the work of this session ends here: stop the timer, then review the session.', + agents: ['Claude Code'], + applies: true, + }, + { + index: 1, + event: 'session-end', + once: 'session', + upstream: 'tracker', + preview: 'The previous session in this working tree ended without closing. Close its timer at its last activity…', + agents: ['Claude Code'], + applies: false, + why: 'the upstream `tracker` is neither accepted nor set up in an agent', + }, + ], +}; + +/** Two sessions of Claude Code, with what devstack gave and the tool calls through it. */ +export function mockActivity(session?: string): ActivityView { + const now = Date.now(); + const min = 60_000; + const main = '~/src/shop'; + const lane = '~/src/shop-feat-cart'; + const at = (m: number) => now - m * min; + const records: ActivityRecord[] = [ + { kind: 'hook', at: at(95), event: 'session-start', agent: 'claude-code', session: 'a1f3', tree: main, hooks: [ref('work-session', 0)] }, + { kind: 'tool', at: at(94), tool: 'timetrack__start_timer', client: 'claude-code', tree: main, pid: 4100, ms: 180, ok: true, session: 'a1f3', agent: 'claude-code', upstream: 'timetrack', skills: ['work-session', 'session-end'] }, + { kind: 'hook', at: at(93), event: 'prompt-submit', agent: 'claude-code', session: 'a1f3', tree: main, hooks: [ref('work-issue', 0)] }, + { kind: 'tool', at: at(90), tool: 'status', client: 'claude-code', tree: main, pid: 4100, ms: 35, ok: true, session: 'a1f3', agent: 'claude-code' }, + { kind: 'tool', at: at(70), tool: 'timetrack__append_to_timer', client: 'claude-code', tree: main, pid: 4100, ms: 95, ok: true, session: 'a1f3', agent: 'claude-code', upstream: 'timetrack', skills: ['work-session', 'session-end'] }, + { kind: 'hook', at: at(41), event: 'prompt-submit', agent: 'claude-code', session: 'a1f3', tree: main, hooks: [ref('work-session', 1)] }, + { kind: 'tool', at: at(40), tool: 'timetrack__stop_timer', client: 'claude-code', tree: main, pid: 4100, ms: 120, ok: true, session: 'a1f3', agent: 'claude-code', upstream: 'timetrack', skills: ['work-session', 'session-end'] }, + { kind: 'hook', at: at(25), event: 'session-start', agent: 'claude-code', session: 'b7c2', tree: lane, hooks: [ref('work-session', 0)] }, + { kind: 'tool', at: at(24), tool: 'timetrack__start_timer', client: 'claude-code', tree: lane, pid: 5200, ms: 210, ok: true, session: 'b7c2', agent: 'claude-code', upstream: 'timetrack', skills: ['work-session', 'session-end'] }, + { kind: 'hook', at: at(23), event: 'prompt-submit', agent: 'claude-code', session: 'b7c2', tree: lane, hooks: [ref('work-issue', 0)] }, + { kind: 'tool', at: at(18), tool: 'up', client: 'claude-code', tree: lane, pid: 5200, ms: 41_000, ok: true, session: 'b7c2', agent: 'claude-code' }, + { kind: 'tool', at: at(9), tool: 'logs', client: 'claude-code', tree: lane, pid: 5200, ms: 60, ok: true, session: 'b7c2', agent: 'claude-code' }, + { kind: 'tool', at: at(6), tool: 'lane_stop', client: 'claude-code', tree: lane, pid: 5200, ms: 2_300, ok: false, session: 'b7c2', agent: 'claude-code' }, + { kind: 'tool', at: at(4), tool: 'lane_stop', client: 'claude-code', tree: lane, pid: 5200, ms: 2_100, ok: true, session: 'b7c2', agent: 'claude-code' }, + { kind: 'hook', at: at(4), event: 'lane-stop', agent: '-', tree: lane, hooks: [ref('session-end', 0)] }, + { kind: 'tool', at: at(2), tool: 'timetrack__append_to_timer', client: 'claude-code', tree: lane, pid: 5200, ms: 88, ok: true, session: 'b7c2', agent: 'claude-code', upstream: 'timetrack', skills: ['work-session', 'session-end'] }, + ]; + const sessions = [ + { agent: 'claude-code', session: 'b7c2', tree: lane, started: at(25), last: at(2), ended: false }, + { agent: 'claude-code', session: 'a1f3', tree: main, started: at(95), last: at(40), ended: true }, + ]; + return { sessions, records: session ? records.filter((r) => (r.kind === 'hook' ? r.session === session || (!r.session && r.tree === sessions.find((s) => s.session === session)?.tree) : r.session === session)) : records }; +} diff --git a/ui/src/api/mock/index.ts b/ui/src/api/mock/index.ts index f8f1fc63..7c86cedb 100644 --- a/ui/src/api/mock/index.ts +++ b/ui/src/api/mock/index.ts @@ -20,6 +20,7 @@ import { persist } from '@/lib/persist'; import { crmSeed, docsSeed, failedReason, shopSeed, stamp } from './data'; import { Abort, MockStack, sleep, type Listener } from './stack'; import { MockPool } from './pool'; +import { mockActivity, mockHookDetails } from './activity'; import { autoShift, daemonPorts, hubPorts, refusal, type MockLane } from './ports'; import { runningHolders } from '@/lib/shift'; @@ -128,9 +129,12 @@ class MockHub { fetched: Math.floor(Date.now() / 1000) - 600, commit: 'a1b2c3d', skills: [ - { name: 'work-issue', description: 'Work on an issue from the tracker to a pull request', sha256: 'aa11', installed: true, pending: false, enabled: true, group: 'Development', tags: ['git', 'tracker'], updated: Date.now() - 3_600_000, agents: ['Claude Code'] }, + { name: 'work-issue', description: 'Work on an issue from the tracker to a pull request', sha256: 'aa11', installed: true, pending: false, enabled: true, group: 'Development', tags: ['git', 'tracker'], updated: Date.now() - 3_600_000, agents: ['Claude Code'], hooks: 1, hook_details: mockHookDetails['work-issue'] }, + // Hooks (ADR-0094) and the flow they make (#482). + { name: 'work-session', description: 'Run every work session with a timer, from its start to its review', sha256: 'aa12', installed: true, pending: false, enabled: true, group: 'Development', updated: Date.now() - 3_600_000, agents: ['Claude Code'], hooks: 2, hook_details: mockHookDetails['work-session'] }, + { name: 'session-end', description: 'Remind the agent of the timer when a lane stops or a session ended', sha256: 'aa13', installed: true, pending: false, enabled: true, group: 'Development', updated: Date.now() - 600_000, agents: ['Claude Code'], hooks: 2, hook_details: mockHookDetails['session-end'] }, { name: 'push-tag', description: 'Tag a release and push it', sha256: 'bb22', installed: true, pending: false, enabled: true, group: 'Development', tags: ['release'], updated: Date.now() - 3_600_000, agents: ['Claude Code'] }, - { name: 'timetrack', description: 'Book time entries from the commits of a day', sha256: 'cc33', installed: true, pending: false, enabled: true, group: 'Time', updated: Date.now() - 600_000, agents: ['Claude Code'], hooks: 1 }, + { name: 'timetrack', description: 'Book time entries from the commits of a day', sha256: 'cc33', installed: true, pending: false, enabled: true, group: 'Time', updated: Date.now() - 600_000, agents: ['Claude Code'] }, { name: 'idea-validate', description: 'Validate a business idea in six phases, as an HTML report', sha256: 'dd44', installed: false, pending: false, enabled: false, group: 'Business', tags: ['html'] }, { name: 'idea-overview', description: 'A one-page overview of a business idea', sha256: 'ee55', installed: false, pending: false, enabled: false, group: 'Business', tags: ['html'] }, // Bound to a repository (ADR-0079): in the working trees of shop only; crm's is no stack here. @@ -655,6 +659,7 @@ export class MockTransport implements Transport { } // Skill sets (ADR-0074). if (p === '/hub/skills' && method === 'GET') return json(200, this.hub.poolSkillState); + if (p === '/hub/activity' && method === 'GET') return json(200, mockActivity(url.searchParams.get('session') ?? undefined)); if (p === '/hub/skills/sync' && method === 'POST') return json(200, this.hub.poolSkillState); const sa = /^\/hub\/skills\/agents\/([^/]+)$/.exec(p); if (sa && method === 'PUT') { diff --git a/ui/src/api/transport.ts b/ui/src/api/transport.ts index 2e80badb..bc9025fe 100644 --- a/ui/src/api/transport.ts +++ b/ui/src/api/transport.ts @@ -123,6 +123,13 @@ export const paths = { poolSkill: (name: string) => `/hub/pool/skills/${enc(name)}`, poolSkillsRefresh: '/hub/pool/skills/refresh', hubSkills: '/hub/skills', + activity: (q: { tree?: string; session?: string } = {}) => { + const p = new URLSearchParams(); + if (q.tree) p.set('tree', q.tree); + if (q.session) p.set('session', q.session); + const s = p.toString(); + return `/hub/activity${s ? `?${s}` : ''}`; + }, /** Every registered stack's ports and their overlaps (ADR-0082). */ hubPorts: '/hub/ports', skillsSync: '/hub/skills/sync', diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index 523b266f..7e425925 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -55,6 +55,8 @@ export type HubEvent = | { type: 'skills'; skills: PoolSkillsState } /** A version of each stack's worktrees (ADR-0078): read a stack's lanes again when its version changes. Older hubs never send it. */ | { type: 'worktrees'; worktrees: Record } + /** A record was added to the agents' activity (`GET /hub/activity`): read it again. Older hubs never send it. */ + | { type: 'activity'; at: number } /** What needs attention in every stack (ADR-0097), first and on every change; older hubs never send it. */ | { type: 'attention'; items: AttentionItem[] } /** Something happened once in the hub that no request reports (ADR-0050): a toast. */ @@ -139,8 +141,62 @@ export type SkillState = { trees?: string[]; /** How many hooks its `hooks.toml` has (ADR-0094): texts given to the agents at a session's start or on a matching prompt. */ hooks?: number; + /** Its hooks as they are given, for the flow (#482); only a skill switched on, and newer hubs. */ + hook_details?: HookDetail[]; }; +/** When a hook gives its text. */ +export type HookEvent = 'session-start' | 'prompt-submit' | 'lane-stop' | 'session-end'; + +/** A hook of a skill as the hub gives it (#482). */ +export type HookDetail = { + /** Its place in the skill's `hooks.toml`. */ + index: number; + event: HookEvent; + /** A regex on the prompt (`prompt-submit`). */ + pattern?: string; + /** Once a session, or once per match. */ + once: 'session' | 'match'; + /** The pool's MCP upstream it is bound to. */ + upstream?: string; + /** The start of its text. */ + preview: string; + /** The agents that get it, by name. */ + agents: string[]; + /** Its upstream is there (accepted, or set up in an agent). */ + applies: boolean; + why?: string; +}; + +/** A hook given, by where it is. */ +export type HookRef = { pool: string; set: string; skill: string; index: number }; + +/** A record of the agents' activity (`GET /hub/activity`, #482): never a prompt, text, argument or answer. */ +export type ActivityRecord = + | { kind: 'hook'; at: number; event: HookEvent; agent: string; session?: string; tree: string; hooks: HookRef[]; recorded?: boolean } + | { + kind: 'tool'; + at: number; + /** With its upstream's prefix (`__`), or one of devstack's own. */ + tool: string; + client?: string; + tree: string; + pid: number; + ms: number; + ok: boolean; + /** The session it is put to: the latest that started in its working tree before it. */ + session?: string; + agent?: string; + /** A pool's upstream's tool: the upstream, and the skills whose hooks name it. */ + upstream?: string; + skills?: string[]; + }; + +/** An agent's session, from its hooks' records. */ +export type ActivitySession = { agent: string; session: string; tree: string; started: number; last: number; ended: boolean }; + +export type ActivityView = { sessions: ActivitySession[]; records: ActivityRecord[] }; + /** A pool's skill set as an admin names it (`/hub/pool/skills`). */ export type PoolSkillSet = { name: string; diff --git a/ui/src/components/SkillsFlow.test.ts b/ui/src/components/SkillsFlow.test.ts new file mode 100644 index 00000000..1fd1b188 --- /dev/null +++ b/ui/src/components/SkillsFlow.test.ts @@ -0,0 +1,65 @@ +// The Skills page's flow (#482): hooks as nodes with their tooltip, a hook +// that is not given greyed with why, a click narrowing the activity. +import { describe, expect, it } from 'vitest'; +import { createApp, h, nextTick } from 'vue'; +import type { PoolSkillsState } from '@/api/types'; +import { mockActivity, mockHookDetails } from '@/api/mock/activity'; +import SkillsFlow from './SkillsFlow.vue'; + +const skill = (name: string) => ({ name, description: '', sha256: name, installed: true, pending: false, enabled: true, hooks: mockHookDetails[name].length, hook_details: mockHookDetails[name] }); +const state: PoolSkillsState = { + agents: [], + sets: [{ pool: 'default', set: 'core', source: 'x', state: 'accepted', auto: true, skills: [skill('work-session'), skill('work-issue'), skill('session-end')] }], + conflicts: [], +}; + +async function mount(s: PoolSkillsState = state) { + const el = document.createElement('div'); + document.body.appendChild(el); + const app = createApp({ render: () => h(SkillsFlow, { state: s, activity: mockActivity(), session: '', now: Date.now() }) }); + app.mount(el); + await nextTick(); + return { el, unmount: () => (app.unmount(), el.remove()) }; +} + +describe('the flow tab', () => { + it('shows each hook in its phase, with a tooltip that says when, on what condition and how often', async () => { + const { el, unmount } = await mount(); + const phases = [...el.querySelectorAll('[data-testid="skills-flow-phase"]')].map((p) => p.dataset.phase); + expect(phases).toEqual(['start', 'prompt', 'lane-stop', 'end']); + const start = el.querySelector('[data-key="default/core/work-session#0"]')!; + const tip = start.querySelector('[data-testid="skills-flow-tip"]')!.textContent!; + expect(tip).toContain('at the start of a session'); + expect(tip).toContain('the upstream timetrack is there'); + expect(tip).toContain('once a session'); + expect(start.querySelector('[data-testid="skills-flow-fired"]')!.textContent).toContain('given'); + unmount(); + }); + + it('greys a hook that is not given and says why', async () => { + const { el, unmount } = await mount(); + const end = el.querySelector('[data-key="default/core/session-end#1"]')!; + expect(end.classList.contains('off')).toBe(true); + expect(end.querySelector('[data-testid="skills-flow-tip"]')!.textContent).toContain('neither accepted nor set up'); + unmount(); + }); + + it('narrows the activity to a hook on a click, and back', async () => { + const { el, unmount } = await mount(); + const count = () => el.querySelectorAll('[data-testid="skills-flow-record"]').length; + const all = count(); + el.querySelector('[data-key="default/core/work-issue#0"]')!.click(); + await nextTick(); + expect(count()).toBe(2); + el.querySelector('[data-testid="skills-flow-all"]')!.click(); + await nextTick(); + expect(count()).toBe(all); + unmount(); + }); + + it('says so when no skill switched on carries hooks', async () => { + const { el, unmount } = await mount({ ...state, sets: [] }); + expect(el.querySelector('[data-testid="skills-flow-empty"]')!.textContent).toContain('No skill switched on carries hooks'); + unmount(); + }); +}); diff --git a/ui/src/components/SkillsFlow.vue b/ui/src/components/SkillsFlow.vue new file mode 100644 index 00000000..0ef1802a --- /dev/null +++ b/ui/src/components/SkillsFlow.vue @@ -0,0 +1,385 @@ + + + + + diff --git a/ui/src/lib/flow.test.ts b/ui/src/lib/flow.test.ts new file mode 100644 index 00000000..84aafb3b --- /dev/null +++ b/ui/src/lib/flow.test.ts @@ -0,0 +1,83 @@ +// The Skills page's flow (#482): hooks by phase, grouped by pattern, and the +// activity tied to them. +import { describe, expect, it } from 'vitest'; +import type { PoolSkillsState } from '@/api/types'; +import { mockActivity, mockHookDetails } from '@/api/mock/activity'; +import { firings, flowNodes, phases, recordsFor, recordText, refKey, toolsByUpstream } from './flow'; + +const skill = (name: string, extra: Record = {}) => ({ + name, + description: '', + sha256: name, + installed: true, + pending: false, + enabled: true, + hooks: mockHookDetails[name]?.length, + hook_details: mockHookDetails[name], + ...extra, +}); + +const state: PoolSkillsState = { + agents: [], + sets: [ + { pool: 'default', set: 'core', source: 'x', state: 'accepted', auto: true, skills: [skill('work-session'), skill('work-issue'), skill('session-end'), skill('quiet', { enabled: false })] }, + { pool: 'default', set: 'other', source: 'y', state: 'offered', auto: false, skills: [skill('work-issue')] }, + ], + conflicts: [], +}; + +describe('the flow', () => { + it('puts each hook of a skill switched on of an accepted set into its phase, a colour per skill', () => { + const nodes = flowNodes(state); + expect(nodes.map((n) => n.key)).toEqual([ + 'default/core/work-session#0', + 'default/core/work-session#1', + 'default/core/work-issue#0', + 'default/core/session-end#0', + 'default/core/session-end#1', + ]); + expect(new Set(nodes.filter((n) => n.skill === 'work-session').map((n) => n.color)).size).toBe(1); + expect(nodes.find((n) => n.skill === 'work-issue')!.color).not.toBe(nodes[0].color); + const p = phases(nodes); + expect(p.map((x) => x.id)).toEqual(['start', 'prompt', 'lane-stop', 'end']); + // The prompt's hooks by pattern: closing words and ticket references apart. + const prompt = p.find((x) => x.id === 'prompt')!; + expect(prompt.groups.map((g) => g.nodes.map((n) => n.skill))).toEqual([['work-session'], ['work-issue']]); + expect(prompt.groups.every((g) => g.pattern)).toBe(true); + }); + + it('ties a hook to its firings and to the tool calls of its upstream', () => { + const { records } = mockActivity(); + const nodes = flowNodes(state); + const start = nodes.find((n) => n.key === 'default/core/work-session#0')!; + expect(firings(records, start.key)).toHaveLength(2); + const mine = recordsFor(records, start); + expect(mine.some((r) => r.kind === 'tool' && r.tool === 'timetrack__start_timer')).toBe(true); + expect(mine.some((r) => r.kind === 'tool' && r.tool === 'status')).toBe(false); + // A lane's stop belongs to the lane-stop hook, its failed try too. + const laneStop = nodes.find((n) => n.hook.event === 'lane-stop')!; + const stops = recordsFor(records, laneStop).filter((r) => r.kind === 'tool' && r.tool === 'lane_stop'); + expect(stops.map((r) => (r.kind === 'tool' ? r.ok : null))).toEqual([true, false]); + expect(recordsFor(records, null)).toHaveLength(records.length); + }); + + it('groups the tool calls by upstream, each call once however many skills name it, the rest last', () => { + const records = mockActivity().records; + const groups = toolsByUpstream(records); + expect(groups.at(-1)!.upstream).toBeNull(); + expect(groups.at(-1)!.skills).toEqual([]); + expect(groups.at(-1)!.tools.find((t) => t.tool === 'lane_stop')).toEqual({ tool: 'lane_stop', calls: 2, failed: 1 }); + const counted = groups.flatMap((g) => g.tools).reduce((n, t) => n + t.calls, 0); + expect(counted).toBe(records.filter((r) => r.kind === 'tool').length); + const tt = groups.find((g) => g.tools.some((t) => t.tool === 'timetrack__append_to_timer'))!; + expect(tt.skills.length).toBeGreaterThan(1); + expect(tt.tools.find((t) => t.tool === 'timetrack__append_to_timer')!.calls).toBe(2); + }); + + it('says what happened, never more', () => { + const r = mockActivity().records.find((x) => x.kind === 'hook' && x.event === 'prompt-submit')!; + const t = recordText(r, () => undefined); + expect(t.title).toBe('Hook: work-issue'); + expect(refKey({ pool: 'p', set: 's', skill: 'k', index: 2 })).toBe('p/s/k#2'); + }); +}); diff --git a/ui/src/lib/flow.ts b/ui/src/lib/flow.ts new file mode 100644 index 00000000..17b0c675 --- /dev/null +++ b/ui/src/lib/flow.ts @@ -0,0 +1,155 @@ +// The Skills page's flow (#482): the hooks of the skills switched on, by when +// they give their text, and what the agents' activity says about them. Pure, +// so the page and its tests share it. +import type { ActivityRecord, ActivitySession, HookDetail, HookEvent, HookRef, PoolSkillsState } from '@/api/types'; + +/** A hook in the flow. */ +export type FlowNode = { + key: string; + pool: string; + set: string; + skill: string; + hook: HookDetail; + /** Its skill's colour, 0 to 5. */ + color: number; +}; + +export type PhaseId = 'start' | 'prompt' | 'lane-stop' | 'end'; + +/** A phase of a session and the hooks that give their text in it. */ +export type Phase = { + id: PhaseId; + title: string; + trigger: string; + /** The prompt's hooks, by pattern; the others' in one group without one. */ + groups: { pattern: string | null; nodes: FlowNode[] }[]; +}; + +export const COLORS = 6; + +/** A hook's key: where it is. */ +export const refKey = (r: HookRef) => `${r.pool}/${r.set}/${r.skill}#${r.index}`; + +/** The hooks of every skill switched on of an accepted set, each skill in its own colour. */ +export function flowNodes(state: PoolSkillsState | null): FlowNode[] { + if (!state) return []; + const colors = new Map(); + const out: FlowNode[] = []; + for (const s of state.sets) { + if (s.state !== 'accepted') continue; + for (const k of s.skills) { + if (k.enabled === false || !k.hook_details?.length) continue; + if (!colors.has(k.name)) colors.set(k.name, colors.size % COLORS); + for (const hook of k.hook_details) { + out.push({ key: refKey({ pool: s.pool, set: s.set, skill: k.name, index: hook.index }), pool: s.pool, set: s.set, skill: k.name, hook, color: colors.get(k.name)! }); + } + } + } + return out; +} + +const PHASES: { id: PhaseId; event: HookEvent; title: string; trigger: string }[] = [ + { id: 'start', event: 'session-start', title: 'A session starts', trigger: 'every new session, and again after its context was cleared' }, + { id: 'prompt', event: 'prompt-submit', title: 'A prompt matches', trigger: 'you send a prompt that matches the hook\'s pattern' }, + { id: 'lane-stop', event: 'lane-stop', title: 'A lane stops', trigger: 'devstack lane stop, or the agent\'s lane_stop: the text follows its output' }, + { id: 'end', event: 'session-end', title: 'A session ends', trigger: 'the agent ends the session: devstack notes it, the next session in the same working tree gets the text' }, +]; + +/** The four phases with their hooks; a phase without any is left out. */ +export function phases(nodes: FlowNode[]): Phase[] { + const out: Phase[] = []; + for (const p of PHASES) { + const mine = nodes.filter((n) => n.hook.event === p.event); + if (!mine.length) continue; + const groups: Phase['groups'] = []; + for (const n of mine) { + const pattern = p.event === 'prompt-submit' ? (n.hook.pattern ?? null) : null; + const g = groups.find((x) => x.pattern === pattern); + if (g) g.nodes.push(n); + else groups.push({ pattern, nodes: [n] }); + } + out.push({ id: p.id, title: p.title, trigger: p.trigger, groups }); + } + return out; +} + +/** How often a hook gives its text, in words. */ +export function onceText(h: HookDetail): string { + if (h.event === 'lane-stop') return 'on every stop'; + if (h.event === 'session-end') return 'once, at the next start'; + return h.once === 'match' ? 'once a session for each match' : 'once a session'; +} + +/** What a hook waits for, in words. */ +export function conditionText(h: HookDetail): string { + const parts: string[] = []; + if (h.upstream) parts.push(`the upstream ${h.upstream} is there (accepted, or set up in the agent)`); + if (h.pattern) parts.push('the prompt matches its pattern'); + return parts.length ? parts.join('; ') : 'none'; +} + +/** The hook records that gave `key`, newest first. */ +export function firings(records: ActivityRecord[], key: string): Extract[] { + return records.filter((r): r is Extract => r.kind === 'hook' && r.hooks.some((h) => refKey(h) === key)).sort((a, b) => b.at - a.at); +} + +/** The records that belong to a hook: its firings, and the tool calls of its skill's upstream (or a lane's stop, for `lane-stop`). All without one. Newest first. */ +export function recordsFor(records: ActivityRecord[], node: FlowNode | null): ActivityRecord[] { + const all = [...records].sort((a, b) => b.at - a.at); + if (!node) return all; + return all.filter((r) => { + if (r.kind === 'hook') return r.hooks.some((h) => refKey(h) === node.key); + if (node.hook.event === 'lane-stop' && r.tool === 'lane_stop') return true; + return !!r.skills?.includes(node.skill); + }); +} + +export type ToolGroup = { + /** The pool's upstream the tools belong to; `null`: devstack's own, or an upstream no skill names. */ + upstream: string | null; + /** The skills whose hooks name that upstream. */ + skills: string[]; + tools: { tool: string; calls: number; failed: number }[]; +}; + +/** The tool calls, by the upstream they use, with the skills whose hooks name it; each call counted + * once, however many skills share the upstream. Those tied to a skill first, the rest last. */ +export function toolsByUpstream(records: ActivityRecord[]): ToolGroup[] { + const out: ToolGroup[] = []; + for (const r of records) { + if (r.kind !== 'tool') continue; + const skills = r.skills ?? []; + const upstream = skills.length ? (r.upstream ?? null) : null; + let g = out.find((x) => x.upstream === upstream); + if (!g) out.push((g = { upstream, skills: [], tools: [] })); + for (const s of skills) if (!g.skills.includes(s)) g.skills.push(s); + let t = g.tools.find((x) => x.tool === r.tool); + if (!t) g.tools.push((t = { tool: r.tool, calls: 0, failed: 0 })); + t.calls++; + if (!r.ok) t.failed++; + } + return out.sort((a, b) => (a.skills.length ? 0 : 1) - (b.skills.length ? 0 : 1)); +} + +/** A session in a line: its working tree's last folder, the agent, when it started. */ +export function sessionLabel(s: ActivitySession): string { + const tree = s.tree.split('/').filter(Boolean).pop() ?? s.tree; + return `${tree} · ${s.agent} · ${new Date(s.started).toLocaleString()}`; +} + +/** A record in words, for the activity list. */ +export function recordText(r: ActivityRecord, skillOf: (key: string) => string | undefined): { title: string; detail: string } { + if (r.kind === 'tool') { + return { title: r.tool, detail: `${r.ms} ms · ${r.ok ? 'ok' : 'failed'}${r.upstream ? ` · upstream ${r.upstream}` : ''}` }; + } + const event: Record = { + 'session-start': 'session start', + 'prompt-submit': 'prompt', + 'lane-stop': 'lane stop', + 'session-end': 'session end', + }; + const names = [...new Set(r.hooks.map((h) => skillOf(refKey(h)) ?? h.skill))]; + if (r.recorded) return { title: `End noted: ${names.join(', ')}`, detail: 'given at the next start in this working tree' }; + if (!names.length) return { title: `Hooks: nothing to give`, detail: event[r.event] }; + return { title: `Hook: ${names.join(', ')}`, detail: `${event[r.event]} · text given` }; +} diff --git a/ui/src/stores/hub.ts b/ui/src/stores/hub.ts index 42184af3..6b4d8f34 100644 --- a/ui/src/stores/hub.ts +++ b/ui/src/stores/hub.ts @@ -57,6 +57,8 @@ export const useHub = defineStore('hub', () => { ); /** What needs attention in every stack (ADR-0097); empty from an older hub. */ const attention = ref([]); + /** When a record was last added to the agents' activity (`activity` events, #482). */ + const activityAt = ref(0); /** A version of each stack's worktrees (ADR-0078); empty from an older hub. */ const worktrees = ref>({}); /** What this machine opens a stack's folder with (ADR-0046); null until asked. */ @@ -147,6 +149,10 @@ export const useHub = defineStore('hub', () => { skills.value = ev.skills; return; } + if (ev.type === 'activity') { + activityAt.value = ev.at; + return; + } if (ev.type === 'attention') { attention.value = ev.items; return; @@ -279,6 +285,7 @@ export const useHub = defineStore('hub', () => { skills, skillsWaiting, attention, + activityAt, worktrees, updating, lastCheck, diff --git a/ui/src/views/SkillsView.vue b/ui/src/views/SkillsView.vue index 19c1899a..0977d918 100644 --- a/ui/src/views/SkillsView.vue +++ b/ui/src/views/SkillsView.vue @@ -9,15 +9,20 @@ // installed and left unchanged: a skill of the user's own, or one changed // by hand, stays and is shown as a conflict. The user switches each agent // found on. The state arrives on `/hub/events`. -import { computed, onMounted, ref } from 'vue'; +// The tab Flow (#482) shows when the hooks of the skills switched on give +// their text, and what devstack did for the agents (`GET /hub/activity`, +// read again on each `activity` event). +import { computed, onMounted, ref, watch } from 'vue'; +import { useRoute, useRouter } from 'vue-router'; import { api, paths } from '@/api'; -import type { PoolSkillsState, SkillSetState, SkillState } from '@/api/types'; +import type { ActivityView, PoolSkillsState, SkillSetState, SkillState } from '@/api/types'; import { act } from '@/lib/actions'; import { persist } from '@/lib/persist'; import { ago, useNow } from '@/lib/format'; import { counts, filtered, groupOf, groups, NO_FILTER, rows, setKey, STATUS_LABEL, type SkillFilter, type SkillRow, type SkillStatus } from '@/lib/skills'; import { useHub } from '@/stores/hub'; import Icon from '@/components/icons/Icon.vue'; +import SkillsFlow from '@/components/SkillsFlow.vue'; const hub = useHub(); const now = useNow(); @@ -25,6 +30,29 @@ const problem = ref(null); const busy = ref(null); const state = computed(() => hub.skills); +// Tabs: the sets, or the flow (`?tab=flow`). +const route = useRoute(); +const router = useRouter(); +const tab = computed<'sets' | 'flow'>(() => (route.query.tab === 'flow' ? 'flow' : 'sets')); +function show(t: 'sets' | 'flow') { + void router.replace({ query: { ...route.query, tab: t === 'flow' ? 'flow' : undefined } }); +} +const flowCount = computed(() => (state.value?.sets ?? []).filter((s) => s.state === 'accepted').flatMap((s) => s.skills).filter((k) => k.enabled !== false).reduce((n, k) => n + (k.hooks ?? 0), 0)); + +// The agents' activity, while the flow shows; again on each `activity` event. +const activity = ref(null); +const session = ref(''); +async function readActivity() { + if (tab.value !== 'flow') return; + try { + const r = await api().request('GET', paths.activity({ session: session.value || undefined })); + if (r.ok && r.body && typeof r.body === 'object') activity.value = r.body; + } catch { + // The hub's state shows elsewhere; the list keeps what it had. + } +} +watch([tab, session, () => hub.activityAt], () => void readActivity(), { immediate: true }); + // Read when the page opens: the hub looks again which agents are on this // machine (one installed since shows) and tells every dashboard. onMounted(async () => { @@ -182,7 +210,16 @@ const hookAgents = computed(() => (state.value?.agents ?? []).filter((a) => a.en

{{ problem }}

Reading…

-