From 487450defac175f7adfb98c330cbafbd998a2058 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 25 Nov 2026 21:19:34 +0530 Subject: [PATCH 01/54] [collect] Self Reports: MCP server, settings file and self_report events Adds fpai_collect::self_report (settings file, tool description/schema, Streamable HTTP MCP server with Host/Origin checks and a 64 KB body limit, server-side fallback recording in the SDK spool format) and teaches the hook-activity source to emit a self_report event for rows carrying selfReport, never rolling them up. Co-Authored-By: Claude Opus 5.5 --- crates/fpai-collect/src/lib.rs | 1 + crates/fpai-collect/src/self_report.rs | 1177 +++++++++++++++++ crates/fpai-collect/src/sources/hooks/mod.rs | 6 +- .../src/sources/hooks/transform.rs | 61 +- crates/fpai-collect/tests/hooks_source.rs | 107 ++ crates/fpai-collect/tests/self_report_mcp.rs | 385 ++++++ 6 files changed, 1734 insertions(+), 3 deletions(-) create mode 100644 crates/fpai-collect/src/self_report.rs create mode 100644 crates/fpai-collect/tests/self_report_mcp.rs diff --git a/crates/fpai-collect/src/lib.rs b/crates/fpai-collect/src/lib.rs index c32c2fa8a..06d13f213 100644 --- a/crates/fpai-collect/src/lib.rs +++ b/crates/fpai-collect/src/lib.rs @@ -20,6 +20,7 @@ pub mod health; pub mod org_boundary; pub mod otlp; pub mod redact; +pub mod self_report; pub mod sources; pub mod spool; #[cfg(feature = "sqlite")] diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs new file mode 100644 index 000000000..9ae61ba9f --- /dev/null +++ b/crates/fpai-collect/src/self_report.rs @@ -0,0 +1,1177 @@ +//! Self Reports: the `report` tool an agent calls when it is stuck. +//! +//! This module owns three things every other part reads the same way: +//! +//! - the effective settings file, `$FAILPROOFAI_HOME/self-report.json`, and the +//! tool built from it (name, description, input schema); +//! - the daemon's MCP server, Streamable HTTP on `127.0.0.1:/mcp`, +//! answering JSON (no SSE stream); +//! - the server-side fallback recording for agents whose hooks never see an +//! MCP call: such a call is written here as a `self_report` event in the SDK +//! spool format, so it reaches Cloud through the existing upload. +//! +//! The settings file is written by the daemon when the machine is Cloud +//! managed and by the TypeScript CLI otherwise. A missing or unparsable file +//! means the feature is off. +//! +//! The server binds loopback only and refuses any request whose `Host` or +//! `Origin` is not this port on `127.0.0.1` / `localhost`, so a web page in a +//! browser cannot reach it (DNS rebinding or a cross-origin POST). It has no +//! auth, on purpose: everything it can do is append one report. + +use std::fs; +use std::io::{self, Write}; +use std::net::{Ipv4Addr, SocketAddr}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use axum::Router; +use axum::body::{Body, to_bytes}; +use axum::extract::{Request, State}; +use axum::http::{HeaderMap, Method, StatusCode}; +use axum::response::Response; +use axum::routing::any; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::sources::hooks::transform::{self, HookRow}; +use crate::supervisor::{Shutdown, TaskError, TaskSpec}; + +/// The settings file under the failproofai home. +pub const SETTINGS_FILE: &str = "self-report.json"; +/// Default loopback port of the MCP server. +pub const DEFAULT_PORT: u16 = 4319; +/// Overrides [`DEFAULT_PORT`]; read by the daemon at start. +pub const PORT_ENV: &str = "FAILPROOFAI_SELF_REPORT_PORT"; +/// MCP server name, as registered in each agent. +pub const SERVER_NAME: &str = "failproofai"; +/// The tool's name inside the MCP server. +pub const TOOL_NAME: &str = "report"; +/// The one thing a call ever returns. +pub const RESULT_TEXT: &str = "Recorded."; +/// The settings file format version. +pub const SETTINGS_VERSION: u32 = 1; +/// Request body ceiling. +pub const MAX_BODY_BYTES: usize = 64 * 1024; +/// `detail` is cut to this many characters. +pub const MAX_DETAIL_CHARS: usize = 2000; +/// Limits on an org's own category list (CONTRACT §2). +pub const MAX_CATEGORIES: usize = 32; +pub const MAX_CATEGORY_NAME_CHARS: usize = 64; +pub const MAX_CATEGORY_DESCRIPTION_CHARS: usize = 500; +pub const MAX_GUIDANCE_CHARS: usize = 2000; +/// How far back a hook-activity session may be to own a fallback report. +pub const SESSION_LOOKBACK: Duration = Duration::from_secs(6 * 3600); +/// The session id a fallback report carries when no session matches. +pub const UNATTRIBUTED_SESSION: &str = "unattributed"; + +/// Integrations whose hooks do not see MCP calls, so the MCP server records +/// the report itself. Mirrors `SELF_REPORT_SERVER_RECORDS` in the TypeScript +/// CLI. claude, codex and cursor are recorded by their hooks and must not be +/// here, or each of their reports would arrive twice. +pub const SERVER_RECORDS: &[&str] = &[ + "openclaw", + "pi", + "devin", + "hermes", + "goose", + "factory", + "antigravity", + "copilot", + "opencode", +]; + +/// MCP protocol revisions this server answers in. The first is what it offers +/// a client asking for one it does not know. +const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05", "2025-11-25"]; + +const DESCRIPTION_HEAD: &str = "Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; do not call it for normal work, clarifying questions or a single error. One call per distinct problem.\nReporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user."; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Category { + pub name: String, + pub description: String, +} + +/// The six categories used when an org defines none of its own. +pub fn default_categories() -> Vec { + [ + ( + "looping", + "You keep repeating the same or circular steps without making progress.", + ), + ( + "cannot_do_request", + "The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating.", + ), + ( + "invalid_tool_or_credential", + "A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected.", + ), + ( + "missing_context", + "Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions.", + ), + ( + "repeated_tool_failure", + "A command or tool failed on several distinct attempts and is blocking you. A single error is not enough.", + ), + ( + "task_failure", + "You genuinely tried and could not complete the task. Not for refusals or policy blocks.", + ), + ] + .into_iter() + .map(|(name, description)| Category { + name: name.to_string(), + description: description.to_string(), + }) + .collect() +} + +/// `^[a-z][a-z0-9_]{0,63}$`. +pub fn is_valid_category_name(name: &str) -> bool { + let mut chars = name.chars(); + matches!(chars.next(), Some(c) if c.is_ascii_lowercase()) + && name.len() <= MAX_CATEGORY_NAME_CHARS + && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') +} + +/// An org's category list made usable: invalid entries and duplicate names +/// dropped, over-long descriptions cut, at most [`MAX_CATEGORIES`]. Falls back +/// to the defaults when nothing usable is left, because an enabled tool with +/// an empty enum could never be called. +pub fn sanitize_categories(categories: Option<&[Category]>) -> Vec { + let mut out: Vec = Vec::new(); + for category in categories.unwrap_or_default() { + let description = category.description.trim(); + if !is_valid_category_name(&category.name) + || description.is_empty() + || out.iter().any(|c| c.name == category.name) + { + continue; + } + out.push(Category { + name: category.name.clone(), + description: truncate_chars(description, MAX_CATEGORY_DESCRIPTION_CHARS), + }); + if out.len() == MAX_CATEGORIES { + break; + } + } + if out.is_empty() { + default_categories() + } else { + out + } +} + +/// Guidance trimmed and capped; empty becomes `None`. +pub fn sanitize_guidance(guidance: Option<&str>) -> Option { + guidance + .map(str::trim) + .filter(|g| !g.is_empty()) + .map(|g| truncate_chars(g, MAX_GUIDANCE_CHARS)) +} + +pub fn truncate_chars(s: &str, max: usize) -> String { + match s.char_indices().nth(max) { + Some((at, _)) => s[..at].to_string(), + None => s.to_string(), + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct McpEndpoint { + pub port: u16, + pub url: String, +} + +impl McpEndpoint { + pub fn on_port(port: u16) -> Self { + McpEndpoint { + port, + url: format!("http://127.0.0.1:{port}/mcp"), + } + } +} + +/// `self-report.json`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Settings { + pub version: u32, + pub enabled: bool, + /// `cloud` | `local`. + pub source: String, + pub categories: Vec, + pub guidance: Option, + pub mcp: McpEndpoint, + #[serde(rename = "updatedAt")] + pub updated_at: String, +} + +impl Settings { + /// Equal in everything but when it was written. + pub fn same_content(&self, other: &Settings) -> bool { + Settings { + updated_at: String::new(), + ..self.clone() + } == Settings { + updated_at: String::new(), + ..other.clone() + } + } +} + +pub fn settings_path(home: &Path) -> PathBuf { + home.join(SETTINGS_FILE) +} + +/// The file, or `None` when it is missing or does not parse (both: disabled). +pub fn read_settings(path: &Path) -> Option { + let text = fs::read_to_string(path).ok()?; + serde_json::from_str(&text).ok() +} + +/// Write the settings atomically (tmp + rename), mode 0644. +pub fn write_settings(path: &Path, settings: &Settings) -> io::Result<()> { + use std::os::unix::fs::OpenOptionsExt; + use std::os::unix::fs::PermissionsExt; + let dir = path + .parent() + .ok_or_else(|| io::Error::other("settings path has no parent"))?; + fs::create_dir_all(dir)?; + let mut text = serde_json::to_string_pretty(settings).map_err(io::Error::other)?; + text.push('\n'); + let tmp = dir.join(format!( + ".{SETTINGS_FILE}.{}.{}.tmp", + std::process::id(), + next_seq() + )); + let result = (|| { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o644) + .open(&tmp)?; + // The umask may have taken bits off the mode above; readers run as + // other users (a system daemon writes, an agent reads), so set it. + file.set_permissions(fs::Permissions::from_mode(0o644))?; + file.write_all(text.as_bytes())?; + file.sync_all()?; + fs::rename(&tmp, path) + })(); + if result.is_err() { + let _ = fs::remove_file(&tmp); + } + result +} + +/// The port from [`PORT_ENV`], else [`DEFAULT_PORT`]. A value that is not a +/// port number falls back to the default with a warning. +pub fn port_from_env() -> u16 { + port_from(std::env::var(PORT_ENV).ok().as_deref()) +} + +pub fn port_from(raw: Option<&str>) -> u16 { + match raw.map(str::trim).filter(|v| !v.is_empty()) { + None => DEFAULT_PORT, + Some(v) => match v.parse::() { + Ok(port) if port > 0 => port, + _ => { + tracing::warn!("{PORT_ENV}={v:?} is not a port number; using {DEFAULT_PORT}"); + DEFAULT_PORT + } + }, + } +} + +/// The tool description (identical text in every implementation). +pub fn describe(categories: &[Category], guidance: Option<&str>) -> String { + let mut text = String::from(DESCRIPTION_HEAD); + text.push_str("\n\nCategories:"); + for category in categories { + text.push_str(&format!("\n- {}: {}", category.name, category.description)); + } + if let Some(g) = guidance.filter(|g| !g.is_empty()) { + text.push_str("\n\n"); + text.push_str(g); + } + text +} + +pub fn input_schema(categories: &[Category]) -> Value { + let names: Vec<&str> = categories.iter().map(|c| c.name.as_str()).collect(); + json!({ + "type": "object", + "properties": { + "category": {"type": "string", "enum": names}, + "detail": {"type": "string", "description": "One factual sentence: what is blocking you."} + }, + "required": ["category", "detail"], + "additionalProperties": false + }) +} + +/// The MCP tool definition, or `None` when the feature is off. +pub fn tool_definition(settings: Option<&Settings>) -> Option { + let settings = settings.filter(|s| s.enabled)?; + let categories = if settings.categories.is_empty() { + default_categories() + } else { + settings.categories.clone() + }; + Some(json!({ + "name": TOOL_NAME, + "description": describe(&categories, settings.guidance.as_deref()), + "inputSchema": input_schema(&categories), + })) +} + +// ── Settings cache ─────────────────────────────────────────────────────────── + +/// `self-report.json`, re-read only when its mtime or size changes. +struct SettingsCache { + path: PathBuf, + state: Mutex)>>, +} + +impl SettingsCache { + fn new(path: PathBuf) -> Self { + SettingsCache { + path, + state: Mutex::new(None), + } + } + + fn current(&self) -> Option { + let meta = fs::metadata(&self.path).ok(); + let stamp = meta.and_then(|m| Some((m.modified().ok()?, m.len()))); + let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner()); + let Some((mtime, len)) = stamp else { + *state = None; + return None; + }; + if let Some((cached_mtime, cached_len, settings)) = state.as_ref() + && *cached_mtime == mtime + && *cached_len == len + { + return settings.clone(); + } + let settings = read_settings(&self.path); + *state = Some((mtime, len, settings.clone())); + settings + } +} + +// ── The HTTP server ────────────────────────────────────────────────────────── + +struct Server { + home: PathBuf, + port: u16, + settings: SettingsCache, +} + +/// The daemon's MCP task. Not gated on ingest: OSS machines use it too. +pub fn tasks(home: PathBuf, port: u16) -> Vec { + vec![TaskSpec::new("self-report-mcp", move |sd| { + let home = home.clone(); + async move { + let address = SocketAddr::from((Ipv4Addr::LOCALHOST, port)); + let listener = match tokio::net::TcpListener::bind(address).await { + Ok(listener) => listener, + Err(err) => { + tracing::warn!( + port, + %err, + "Self Reports MCP server off: loopback port unavailable; daemon continues" + ); + return Ok(()); // Clean exit: not restarted, not logged again. + } + }; + tracing::info!(port, "Self Reports MCP server listening on 127.0.0.1"); + serve(listener, home, sd).await + } + })] +} + +/// Serve on an already-bound listener until shutdown. The Host/Origin checks +/// use the listener's own port. +pub async fn serve( + listener: tokio::net::TcpListener, + home: PathBuf, + sd: Shutdown, +) -> Result<(), TaskError> { + let port = listener + .local_addr() + .map_err(|e| TaskError(e.to_string()))? + .port(); + let server = Arc::new(Server { + settings: SettingsCache::new(settings_path(&home)), + home, + port, + }); + let app = Router::new().route("/mcp", any(handle)).with_state(server); + axum::serve(listener, app) + .with_graceful_shutdown(async move { while sd.sleep(Duration::from_millis(100)).await {} }) + .await + .map_err(|e| TaskError(e.to_string())) +} + +fn status(code: StatusCode) -> Response { + Response::builder() + .status(code) + .body(Body::empty()) + .unwrap() +} + +fn json_response(code: StatusCode, body: &Value) -> Response { + Response::builder() + .status(code) + .header("Content-Type", "application/json") + .body(Body::from(body.to_string())) + .unwrap() +} + +/// `Host` must be this port on a loopback name; `Origin`, when sent, too. +fn allowed(headers: &HeaderMap, port: u16) -> bool { + let hosts = [format!("127.0.0.1:{port}"), format!("localhost:{port}")]; + let host_ok = headers + .get("host") + .and_then(|v| v.to_str().ok()) + .is_some_and(|h| hosts.iter().any(|ok| h.eq_ignore_ascii_case(ok))); + if !host_ok { + return false; + } + match headers.get("origin") { + None => true, + Some(origin) => origin.to_str().ok().is_some_and(|o| { + hosts + .iter() + .any(|ok| o.eq_ignore_ascii_case(&format!("http://{ok}"))) + }), + } +} + +/// `?agent=` and `?cwd=` from the request URI. +#[derive(Debug, Default, Clone)] +struct Caller { + agent: Option, + cwd: Option, +} + +impl Caller { + fn from_query(query: Option<&str>) -> Self { + let mut caller = Caller::default(); + for pair in query.unwrap_or_default().split('&') { + let (key, value) = pair.split_once('=').unwrap_or((pair, "")); + let value = percent_decode(value); + if value.is_empty() { + continue; + } + match key { + "agent" => caller.agent = Some(value), + "cwd" => caller.cwd = Some(value), + _ => {} + } + } + caller + } +} + +fn percent_decode(s: &str) -> String { + let bytes = s.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' => out.push(b' '), + b'%' if i + 2 < bytes.len() => { + let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok(); + match hex.and_then(|h| u8::from_str_radix(h, 16).ok()) { + Some(b) => { + out.push(b); + i += 2; + } + None => out.push(b'%'), + } + } + b => out.push(b), + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +async fn handle(State(server): State>, request: Request) -> Response { + if !allowed(request.headers(), server.port) { + return status(StatusCode::FORBIDDEN); + } + if request.method() != Method::POST { + // No SSE stream and no session to delete. + return Response::builder() + .status(StatusCode::METHOD_NOT_ALLOWED) + .header("Allow", "POST") + .body(Body::empty()) + .unwrap(); + } + let caller = Caller::from_query(request.uri().query()); + let Ok(body) = to_bytes(request.into_body(), MAX_BODY_BYTES).await else { + return status(StatusCode::PAYLOAD_TOO_LARGE); + }; + let Ok(message) = serde_json::from_slice::(&body) else { + return json_response( + StatusCode::BAD_REQUEST, + &rpc_error(Value::Null, -32700, "Parse error"), + ); + }; + let server2 = server.clone(); + let answer = tokio::task::spawn_blocking(move || match message { + Value::Array(batch) if !batch.is_empty() => { + let replies: Vec = batch + .into_iter() + .filter_map(|m| server2.dispatch(m, &caller)) + .collect(); + (!replies.is_empty()).then_some(Value::Array(replies)) + } + Value::Array(_) => Some(rpc_error(Value::Null, -32600, "Invalid Request")), + single => server2.dispatch(single, &caller), + }) + .await; + match answer { + Ok(Some(reply)) => json_response(StatusCode::OK, &reply), + // Only notifications (or responses) were sent. + Ok(None) => status(StatusCode::ACCEPTED), + Err(_) => status(StatusCode::INTERNAL_SERVER_ERROR), + } +} + +fn rpc_result(id: Value, result: Value) -> Value { + json!({"jsonrpc": "2.0", "id": id, "result": result}) +} + +fn rpc_error(id: Value, code: i64, message: &str) -> Value { + json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}}) +} + +impl Server { + /// One JSON-RPC message. `None` for a notification or a client response. + fn dispatch(&self, message: Value, caller: &Caller) -> Option { + let Some(obj) = message.as_object() else { + return Some(rpc_error(Value::Null, -32600, "Invalid Request")); + }; + let method = obj.get("method").and_then(Value::as_str); + let id = obj.get("id").cloned(); + let Some(method) = method else { + // A response to something we never asked, or garbage. + return id.map(|id| rpc_error(id, -32600, "Invalid Request")); + }; + // A notification (`notifications/initialized`, `notifications/cancelled`…) + // gets no reply. + let id = id?; + let params = obj.get("params").cloned().unwrap_or(Value::Null); + Some(match method { + "initialize" => { + let asked = params.get("protocolVersion").and_then(Value::as_str); + let version = asked + .filter(|v| PROTOCOL_VERSIONS.contains(v)) + .unwrap_or(PROTOCOL_VERSIONS[0]); + rpc_result( + id, + json!({ + "protocolVersion": version, + // listChanged is false: answers are plain JSON with no + // stream to push the notification on. A client sees a + // changed list on its next tools/list. + "capabilities": {"tools": {"listChanged": false}}, + "serverInfo": {"name": SERVER_NAME, "version": env!("CARGO_PKG_VERSION")}, + }), + ) + } + "ping" => rpc_result(id, json!({})), + "tools/list" => { + let tools: Vec = tool_definition(self.settings.current().as_ref()) + .into_iter() + .collect(); + rpc_result(id, json!({"tools": tools})) + } + "tools/call" => { + let name = params.get("name").and_then(Value::as_str); + if name != Some(TOOL_NAME) { + return Some(rpc_error(id, -32602, "Unknown tool")); + } + let args = params.get("arguments").cloned().unwrap_or(Value::Null); + self.record(&args, caller); + rpc_result( + id, + json!({"content": [{"type": "text", "text": RESULT_TEXT}], "isError": false}), + ) + } + _ => rpc_error(id, -32601, "Method not found"), + }) + } + + /// The fallback recording. A failure is logged and never reaches the agent: + /// the call's answer is `Recorded.` whatever happens here. + fn record(&self, args: &Value, caller: &Caller) { + let Some(agent) = caller + .agent + .as_deref() + .filter(|a| SERVER_RECORDS.contains(a)) + else { + return; + }; + let report = Report::from_args(args); + let event = fallback_event(&self.home, agent, caller.cwd.as_deref(), &report, now_ms()); + if let Err(err) = write_event_file(&self.home, &[event]) { + tracing::warn!(%err, agent, "could not record a self report"); + } + } +} + +// ── Recording ──────────────────────────────────────────────────────────────── + +/// A call's arguments, as recorded: an unknown category is kept as-is, a +/// missing one or a missing detail becomes "". +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Report { + pub category: String, + pub detail: String, +} + +impl Report { + pub fn from_args(args: &Value) -> Self { + let text = |key: &str| { + args.get(key) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + }; + Report { + category: text("category"), + detail: truncate_chars(&text("detail"), MAX_DETAIL_CHARS), + } + } +} + +/// The newest session for `integration` (and `cwd` when known) in hook +/// activity within [`SESSION_LOOKBACK`] of `now_ms`, with the cwd its row had. +pub fn find_session( + home: &Path, + integration: &str, + cwd: Option<&str>, + now_ms: i64, +) -> Option<(String, Option)> { + let dir = home.join("hook-activity"); + // `current.jsonl` rotates to a page every 25 rows, so the newest session + // may be in the newest page when current was just rotated. + let mut files = vec![dir.join("current.jsonl")]; + if let Ok(entries) = fs::read_dir(&dir) { + let mut pages: Vec = entries + .filter_map(Result::ok) + .map(|e| e.path()) + .filter(|p| { + p.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with("page-") && n.ends_with(".jsonl")) + }) + .collect(); + pages.sort(); + files.extend(pages.into_iter().rev().take(2)); + } + let oldest = now_ms - SESSION_LOOKBACK.as_millis() as i64; + let mut best: Option<(i64, String, Option)> = None; + for file in files { + let Ok(text) = read_tail(&file, 1024 * 1024) else { + continue; + }; + for line in text.lines() { + let Ok(row) = serde_json::from_str::(line.trim()) else { + continue; + }; + let Some(session) = row.session_id.as_deref().filter(|s| !s.is_empty()) else { + continue; + }; + if row.integration.as_deref() != Some(integration) + || row.timestamp < oldest + || cwd.is_some_and(|want| row.cwd.as_deref() != Some(want)) + || best.as_ref().is_some_and(|(at, _, _)| *at >= row.timestamp) + { + continue; + } + best = Some((row.timestamp, session.to_string(), row.cwd.clone())); + } + } + best.map(|(_, session, cwd)| (session, cwd)) +} + +/// The last `max` bytes of a file, from the first whole line in them. +fn read_tail(path: &Path, max: u64) -> io::Result { + use std::io::{Read, Seek, SeekFrom}; + let mut file = fs::File::open(path)?; + let len = file.metadata()?.len(); + let start = len.saturating_sub(max); + file.seek(SeekFrom::Start(start))?; + let mut buf = Vec::new(); + file.read_to_end(&mut buf)?; + let mut text = String::from_utf8_lossy(&buf).into_owned(); + if start > 0 + && let Some(nl) = text.find('\n') + { + text.drain(..=nl); + } + Ok(text) +} + +/// The collector's `environment` label, as the hook events carry it. +fn environment(home: &Path) -> (String, crate::config::Redact) { + match crate::config::load(home) { + Ok(cfg) => (cfg.settings.environment, cfg.settings.redact), + Err(_) => { + let defaults = crate::config::Settings::default(); + (defaults.environment, defaults.redact) + } + } +} + +/// The `self_report` event the MCP server writes for an integration in +/// [`SERVER_RECORDS`]. +pub fn fallback_event( + home: &Path, + integration: &str, + cwd: Option<&str>, + report: &Report, + now_ms: i64, +) -> Value { + let found = find_session(home, integration, cwd, now_ms); + let (session_id, row_cwd) = match found { + Some((session, row_cwd)) => (session, row_cwd), + None => (UNATTRIBUTED_SESSION.to_string(), None), + }; + let identity = HookRow { + integration: Some(integration.to_string()), + cwd: row_cwd.or_else(|| cwd.map(str::to_string)), + ..Default::default() + }; + let (environment, redact) = environment(home); + let mut event = json!({ + "type": "self_report", + "session_id": session_id, + "agent_id": transform::agent_id(&identity), + "timestamp": transform::to_rfc3339_micros(now_ms, 0).unwrap_or_default(), + "environment": environment, + "category": report.category, + "detail": report.detail, + "source": "mcp", + "integration": integration, + }); + crate::redact::scrub_value(&mut event, redact); + event +} + +static SEQ: AtomicU64 = AtomicU64::new(0); + +fn next_seq() -> u64 { + SEQ.fetch_add(1, Ordering::Relaxed) +} + +fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0) +} + +/// Write one batch into `/custom-agents/events/` in the SDK writer's +/// format: `event---.jsonl`, one JSON event +/// per line, written to `.tmp` (0600, exclusive), fsynced, then renamed. +pub fn write_event_file(home: &Path, events: &[Value]) -> io::Result { + use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; + let dir = home.join("custom-agents").join("events"); + fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(&dir)?; + let now = time::OffsetDateTime::now_utc(); + const FMT: &[time::format_description::BorrowedFormatItem<'_>] = time::macros::format_description!( + "[year]-[month]-[day]T[hour]-[minute]-[second]-[subsecond digits:3]Z" + ); + let stamp = now.format(FMT).map_err(io::Error::other)?; + let stem = format!( + "event-{stamp}-{}-self-report-{}", + std::process::id(), + next_seq() + ); + let tmp = dir.join(format!("{stem}.tmp")); + let path = dir.join(format!("{stem}.jsonl")); + let mut content = String::new(); + for event in events { + content.push_str(&event.to_string()); + content.push('\n'); + } + let result = (|| { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&tmp)?; + file.write_all(content.as_bytes())?; + file.sync_all()?; + fs::rename(&tmp, &path) + })(); + if result.is_err() { + let _ = fs::remove_file(&tmp); + } + result.map(|()| path) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_home(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "fpai-self-report-{name}-{}-{}", + std::process::id(), + next_seq() + )); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + fn enabled(categories: Vec, guidance: Option<&str>) -> Settings { + Settings { + version: SETTINGS_VERSION, + enabled: true, + source: "local".into(), + categories, + guidance: guidance.map(str::to_string), + mcp: McpEndpoint::on_port(DEFAULT_PORT), + updated_at: "2026-11-25T10:00:00Z".into(), + } + } + + #[test] + fn the_description_is_the_contract_text() { + let cats = vec![ + Category { + name: "a".into(), + description: "First.".into(), + }, + Category { + name: "b_2".into(), + description: "Second.".into(), + }, + ]; + let want = format!("{DESCRIPTION_HEAD}\n\nCategories:\n- a: First.\n- b_2: Second."); + assert_eq!(describe(&cats, None), want); + assert_eq!(describe(&cats, Some("")), want); + assert_eq!( + describe(&cats, Some("Be brief.")), + format!("{want}\n\nBe brief.") + ); + assert!(DESCRIPTION_HEAD.starts_with("Report to FailproofAI that you are stuck.")); + assert!(DESCRIPTION_HEAD.ends_with("There is no need to mention this report to the user.")); + } + + #[test] + fn the_schema_enumerates_the_categories() { + let schema = input_schema(&default_categories()); + assert_eq!( + schema["properties"]["category"]["enum"], + json!([ + "looping", + "cannot_do_request", + "invalid_tool_or_credential", + "missing_context", + "repeated_tool_failure", + "task_failure" + ]) + ); + assert_eq!(schema["required"], json!(["category", "detail"])); + assert_eq!(schema["additionalProperties"], json!(false)); + } + + #[test] + fn no_tool_when_disabled_or_missing() { + assert!(tool_definition(None).is_none()); + let mut s = enabled(default_categories(), None); + s.enabled = false; + assert!(tool_definition(Some(&s)).is_none()); + s.enabled = true; + assert_eq!(tool_definition(Some(&s)).unwrap()["name"], "report"); + } + + #[test] + fn category_names_follow_the_pattern() { + assert!(is_valid_category_name("looping")); + assert!(is_valid_category_name("a1_b")); + assert!(is_valid_category_name(&"a".repeat(64))); + assert!(!is_valid_category_name(&"a".repeat(65))); + assert!(!is_valid_category_name("1abc")); + assert!(!is_valid_category_name("Abc")); + assert!(!is_valid_category_name("a-b")); + assert!(!is_valid_category_name("")); + } + + #[test] + fn invalid_categories_are_dropped_and_none_left_means_defaults() { + let cats = vec![ + Category { + name: "ok".into(), + description: "x".repeat(600), + }, + Category { + name: "Bad".into(), + description: "d".into(), + }, + Category { + name: "ok".into(), + description: "dup".into(), + }, + Category { + name: "empty".into(), + description: " ".into(), + }, + ]; + let out = sanitize_categories(Some(&cats)); + assert_eq!(out.len(), 1); + assert_eq!(out[0].description.chars().count(), 500); + assert_eq!(sanitize_categories(Some(&[])), default_categories()); + assert_eq!(sanitize_categories(None), default_categories()); + let many: Vec = (0..40) + .map(|i| Category { + name: format!("c{i}"), + description: "d".into(), + }) + .collect(); + assert_eq!(sanitize_categories(Some(&many)).len(), MAX_CATEGORIES); + assert_eq!(sanitize_guidance(Some(" ")), None); + assert_eq!( + sanitize_guidance(Some(&"g".repeat(3000))) + .unwrap() + .chars() + .count(), + 2000 + ); + } + + #[test] + fn the_port_comes_from_the_environment_value() { + assert_eq!(port_from(None), 4319); + assert_eq!(port_from(Some("")), 4319); + assert_eq!(port_from(Some("5000")), 5000); + assert_eq!(port_from(Some("0")), 4319); + assert_eq!(port_from(Some("nope")), 4319); + assert_eq!(port_from(Some("70000")), 4319); + } + + #[test] + fn settings_round_trip_with_the_contract_keys() { + let home = temp_home("roundtrip"); + let path = settings_path(&home); + let s = enabled(default_categories(), Some("g")); + write_settings(&path, &s).unwrap(); + let raw: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap(); + assert_eq!(raw["version"], 1); + assert_eq!(raw["mcp"]["url"], "http://127.0.0.1:4319/mcp"); + assert_eq!(raw["updatedAt"], "2026-11-25T10:00:00Z"); + assert_eq!(read_settings(&path), Some(s.clone())); + use std::os::unix::fs::PermissionsExt; + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o644 + ); + fs::write(&path, "{not json").unwrap(); + assert_eq!(read_settings(&path), None); + let _ = fs::remove_dir_all(home); + } + + #[test] + fn the_cache_rereads_a_changed_file() { + let home = temp_home("cache"); + let path = settings_path(&home); + let cache = SettingsCache::new(path.clone()); + assert!(cache.current().is_none()); + write_settings(&path, &enabled(default_categories(), None)).unwrap(); + assert!(cache.current().unwrap().enabled); + let mut off = enabled(default_categories(), None); + off.enabled = false; + off.guidance = Some("a longer file so the size changes too".into()); + write_settings(&path, &off).unwrap(); + assert!(!cache.current().unwrap().enabled); + fs::remove_file(&path).unwrap(); + assert!(cache.current().is_none()); + let _ = fs::remove_dir_all(home); + } + + #[test] + fn host_and_origin_must_be_this_loopback_port() { + let headers = |host: Option<&str>, origin: Option<&str>| { + let mut h = HeaderMap::new(); + if let Some(v) = host { + h.insert("host", v.parse().unwrap()); + } + if let Some(v) = origin { + h.insert("origin", v.parse().unwrap()); + } + h + }; + assert!(allowed(&headers(Some("127.0.0.1:4319"), None), 4319)); + assert!(allowed(&headers(Some("localhost:4319"), None), 4319)); + assert!(allowed( + &headers(Some("localhost:4319"), Some("http://127.0.0.1:4319")), + 4319 + )); + assert!(!allowed(&headers(None, None), 4319)); + assert!(!allowed(&headers(Some("127.0.0.1:4320"), None), 4319)); + assert!(!allowed(&headers(Some("evil.example:4319"), None), 4319)); + assert!(!allowed( + &headers(Some("127.0.0.1:4319"), Some("http://evil.example")), + 4319 + )); + assert!(!allowed( + &headers(Some("127.0.0.1:4319"), Some("https://127.0.0.1:4319")), + 4319 + )); + assert!(!allowed( + &headers(Some("127.0.0.1:4319"), Some("null")), + 4319 + )); + } + + #[test] + fn the_query_names_the_agent_and_cwd() { + let c = Caller::from_query(Some("agent=openclaw&cwd=%2Fhome%2Fu%2Fproj&x=1")); + assert_eq!(c.agent.as_deref(), Some("openclaw")); + assert_eq!(c.cwd.as_deref(), Some("/home/u/proj")); + let c = Caller::from_query(None); + assert!(c.agent.is_none() && c.cwd.is_none()); + assert_eq!(percent_decode("a%2"), "a%2"); + assert_eq!(percent_decode("a%zzb"), "a%zzb"); + } + + #[test] + fn report_arguments_are_kept_as_given() { + let r = Report::from_args(&json!({"category": "made_up", "detail": "x".repeat(3000)})); + assert_eq!(r.category, "made_up"); + assert_eq!(r.detail.chars().count(), 2000); + let r = Report::from_args(&json!({})); + assert_eq!( + r, + Report { + category: String::new(), + detail: String::new() + } + ); + } + + #[test] + fn the_newest_matching_session_owns_the_report() { + let home = temp_home("session"); + let dir = home.join("hook-activity"); + fs::create_dir_all(&dir).unwrap(); + let now = 1_800_000_000_000_i64; + let row = |at: i64, integration: &str, session: &str, cwd: &str| { + json!({"timestamp": at, "eventType": "PreToolUse", "integration": integration, + "sessionId": session, "cwd": cwd, "toolName": "x", "decision": "allow"}) + .to_string() + }; + fs::write( + dir.join("page-1-0.jsonl"), + format!("{}\n", row(now - 1000, "openclaw", "s-page", "/w/a")), + ) + .unwrap(); + fs::write( + dir.join("current.jsonl"), + [ + row(now - 7 * 3600 * 1000, "openclaw", "s-old", "/w/a"), + row(now - 5000, "openclaw", "s-older", "/w/b"), + row(now - 100, "pi", "s-pi", "/w/a"), + String::from("not json"), + ] + .join("\n") + + "\n", + ) + .unwrap(); + assert_eq!( + find_session(&home, "openclaw", None, now), + Some(("s-page".to_string(), Some("/w/a".to_string()))) + ); + assert_eq!( + find_session(&home, "openclaw", Some("/w/b"), now).map(|s| s.0), + Some("s-older".to_string()) + ); + assert_eq!(find_session(&home, "goose", None, now), None); + assert_eq!( + find_session(&home, "openclaw", None, now + 8 * 3600 * 1000), + None + ); + + let event = fallback_event( + &home, + "openclaw", + None, + &Report { + category: "looping".into(), + detail: "stuck".into(), + }, + now, + ); + assert_eq!(event["type"], "self_report"); + assert_eq!(event["session_id"], "s-page"); + assert_eq!(event["agent_id"], "openclaw-a"); + assert_eq!(event["source"], "mcp"); + assert_eq!(event["integration"], "openclaw"); + assert_eq!(event["environment"], "local"); + assert!(event.get("tool_call_id").is_none()); + + let event = fallback_event( + &home, + "goose", + Some("/w/proj"), + &Report { + category: "c".into(), + detail: String::new(), + }, + now, + ); + assert_eq!(event["session_id"], UNATTRIBUTED_SESSION); + assert_eq!(event["agent_id"], "goose-proj"); + let _ = fs::remove_dir_all(home); + } + + #[test] + fn event_files_use_the_sdk_writer_format() { + use std::os::unix::fs::PermissionsExt; + let home = temp_home("writer"); + let path = write_event_file(&home, &[json!({"type": "self_report"})]).unwrap(); + let name = path.file_name().unwrap().to_str().unwrap().to_string(); + assert!( + name.starts_with("event-") && name.ends_with(".jsonl"), + "{name}" + ); + // event-YYYY-MM-DDTHH-MM-SS-mmmZ-... + assert_eq!(&name[16..17], "T"); + assert_eq!(&name[29..31], "Z-"); + assert_eq!(path.parent().unwrap(), home.join("custom-agents/events")); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + assert_eq!( + fs::read_to_string(&path).unwrap(), + "{\"type\":\"self_report\"}\n" + ); + let leftovers: Vec<_> = fs::read_dir(path.parent().unwrap()) + .unwrap() + .filter_map(Result::ok) + .filter(|e| e.path().extension().is_some_and(|x| x == "tmp")) + .collect(); + assert!(leftovers.is_empty()); + let _ = fs::remove_dir_all(home); + } +} diff --git a/crates/fpai-collect/src/sources/hooks/mod.rs b/crates/fpai-collect/src/sources/hooks/mod.rs index 8761513ef..933f52df8 100644 --- a/crates/fpai-collect/src/sources/hooks/mod.rs +++ b/crates/fpai-collect/src/sources/hooks/mod.rs @@ -245,11 +245,13 @@ async fn poll_once( // and erase the would-be verdict, which is the entire measurement // a trial exists to produce. Emit those exactly. The same holds // for an allow Jev produced by clearing a regex deny, and for a - // observe-mode allow Jev would have blocked. + // observe-mode allow Jev would have blocked, and for a self report. let aggregate = verbosity == HooksVerbosity::Decisions && row.is_allow() && !row.has_observation() - && !row.has_jev_signal(); + && !row.has_jev_signal() + // A self report is its own event and must reach Cloud whole. + && row.self_report.is_none(); if aggregate { if let Some(key) = bucket_key(&row) { buckets diff --git a/crates/fpai-collect/src/sources/hooks/transform.rs b/crates/fpai-collect/src/sources/hooks/transform.rs index 357764b97..1ea305b6a 100644 --- a/crates/fpai-collect/src/sources/hooks/transform.rs +++ b/crates/fpai-collect/src/sources/hooks/transform.rs @@ -159,6 +159,25 @@ pub struct HookRow { /// check, so Jev decided nothing. #[serde(rename = "jevChecks", default, deserialize_with = "lenient")] pub jev_checks: Option>, + + // ---- Self Reports ------------------------------------------------------ + /// Set on the row the hook wrote for a call to the `report` tool (the + /// agent said it is stuck). Emitted as its own `self_report` event, and the + /// row is never folded into an allow roll-up. + #[serde(rename = "selfReport", default, deserialize_with = "lenient")] + pub self_report: Option, +} + +/// `selfReport` on a hook-activity row. +#[derive(Debug, Clone, Default, Deserialize)] +pub struct SelfReportField { + #[serde(default, deserialize_with = "lenient")] + pub category: Option, + #[serde(default, deserialize_with = "lenient")] + pub detail: Option, + /// `mcp` | `sdk`. + #[serde(default, deserialize_with = "lenient")] + pub source: Option, } /// Deserialize `T`, or `None` when the value is absent, null, or the wrong @@ -965,7 +984,47 @@ pub fn to_events(row: &HookRow, offset: u64, environment: &str) -> Vec { ); } - vec![Value::Object(start), Value::Object(end)] + let mut events = vec![Value::Object(start), Value::Object(end)]; + if let Some(report) = self_report_event(row, session_id, environment) { + events.push(report); + } + events +} + +/// The `self_report` event for a row carrying `selfReport`. Same agent, +/// environment and session as the row's hook events; stamped just after them. +fn self_report_event(row: &HookRow, session_id: &str, environment: &str) -> Option { + let report = row.self_report.as_ref()?; + let mut m = base(row, session_id, environment, "self_report", 2)?; + m.insert( + "category".into(), + json!(report.category.as_deref().unwrap_or_default()), + ); + m.insert( + "detail".into(), + json!(crate::self_report::truncate_chars( + report.detail.as_deref().unwrap_or_default(), + crate::self_report::MAX_DETAIL_CHARS + )), + ); + m.insert( + "source".into(), + json!( + report + .source + .as_deref() + .filter(|s| !s.is_empty()) + .unwrap_or("mcp") + ), + ); + m.insert( + "integration".into(), + json!(row.integration.as_deref().unwrap_or("failproofai")), + ); + if let Some(id) = row.tool_call_id.as_deref().filter(|id| !id.is_empty()) { + m.insert("tool_call_id".into(), json!(id)); + } + Some(Value::Object(m)) } /// One rolled-up `allow` bucket. diff --git a/crates/fpai-collect/tests/hooks_source.rs b/crates/fpai-collect/tests/hooks_source.rs index f33638863..c02d04383 100644 --- a/crates/fpai-collect/tests/hooks_source.rs +++ b/crates/fpai-collect/tests/hooks_source.rs @@ -850,3 +850,110 @@ fn a_malformed_start_time_or_tool_call_id_never_drops_the_decision() { assert_eq!(events[1]["outcome"], "deny"); } } + +// ---- Self Reports ------------------------------------------------------------ + +fn self_report_row(ts: i64) -> String { + serde_json::json!({ + "timestamp": ts, + "eventType": "PreToolUse", + "integration": "claude", + "toolName": "mcp__failproofai__report", + "toolCallId": "toolu_01", + "decision": "allow", + "durationMs": 1, + "sessionId": "sess-a", + "cwd": "/home/u/repo", + "selfReport": {"category": "invalid_tool_or_credential", "detail": "tracker rejected its API key", "source": "mcp"} + }) + .to_string() +} + +#[test] +fn a_self_report_row_also_emits_a_self_report_event() { + let row = parse(&self_report_row(1785740912184)); + let events = transform::to_events(&row, 7, "prod"); + assert_eq!(events.len(), 3, "the hook pair plus the report"); + let hook = &events[1]; + let report = &events[2]; + assert_eq!(report["type"], "self_report"); + assert_eq!(report["session_id"], "sess-a"); + assert_eq!(report["agent_id"], hook["agent_id"]); + assert_eq!(report["agent_id"], "claude-repo"); + assert_eq!(report["environment"], "prod"); + assert_eq!(report["category"], "invalid_tool_or_credential"); + assert_eq!(report["detail"], "tracker rejected its API key"); + assert_eq!(report["source"], "mcp"); + assert_eq!(report["integration"], "claude"); + assert_eq!(report["tool_call_id"], "toolu_01"); + assert!( + report["timestamp"].as_str().unwrap() > hook["timestamp"].as_str().unwrap(), + "stamped after its own hook leg" + ); +} + +#[test] +fn a_self_report_with_missing_fields_is_still_recorded() { + let mut v: Value = serde_json::from_str(&self_report_row(1785740912184)).unwrap(); + v["selfReport"] = serde_json::json!({"category": "made_up", "detail": "x".repeat(2500)}); + v.as_object_mut().unwrap().remove("toolCallId"); + let events = transform::to_events(&parse(&v.to_string()), 0, "local"); + let report = &events[2]; + assert_eq!(report["category"], "made_up", "unknown categories are kept"); + assert_eq!(report["detail"].as_str().unwrap().chars().count(), 2000); + assert_eq!(report["source"], "mcp"); + assert!(report.get("tool_call_id").is_none()); + + // A malformed selfReport never drops the row. + v["selfReport"] = serde_json::json!("nonsense"); + let events = transform::to_events(&parse(&v.to_string()), 0, "local"); + assert_eq!(events.len(), 2); +} + +#[test] +fn a_row_without_self_report_emits_only_the_pair() { + assert_eq!( + transform::to_events(&parse(&allow_row(1785740912000, "Bash")), 0, "local").len(), + 2 + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_self_report_row_is_never_rolled_up() { + let store = tmpdir("sr-store"); + let state = tmpdir("sr-state"); + let spool = tmpdir("sr-spool"); + let mut lines: Vec = (0..5) + .map(|i| allow_row(1785740912000 + i * 100, "Bash")) + .collect(); + lines.push(self_report_row(1785740912700)); + fs::write(store.join("current.jsonl"), lines.join("\n") + "\n").unwrap(); + + run_once(&store, &state, &spool, HooksVerbosity::Decisions).await; + + let events = spooled(&spool); + let reports: Vec<_> = events + .iter() + .filter(|e| e["type"] == "self_report") + .collect(); + assert_eq!(reports.len(), 1); + assert_eq!(reports[0]["category"], "invalid_tool_or_credential"); + let agg = events + .iter() + .find(|e| e["type"] == "hook_completed" && e["failproofai_allow_count"].is_number()) + .expect("the plain allows still roll up"); + assert_eq!( + agg["failproofai_allow_count"], 5, + "the report row is not in it" + ); + assert!( + events + .iter() + .any(|e| e["type"] == "hook_completed" && e["tool_call_id"] == "toolu_01"), + "the report row keeps its exact hook pair" + ); + + fs::remove_dir_all(&store).ok(); + fs::remove_dir_all(&state).ok(); + fs::remove_dir_all(&spool).ok(); +} diff --git a/crates/fpai-collect/tests/self_report_mcp.rs b/crates/fpai-collect/tests/self_report_mcp.rs new file mode 100644 index 000000000..2c1e8f083 --- /dev/null +++ b/crates/fpai-collect/tests/self_report_mcp.rs @@ -0,0 +1,385 @@ +//! The daemon's Self Reports MCP server, driven over real HTTP on an ephemeral +//! loopback port: the JSON-RPC methods, the tool built from `self-report.json`, +//! the Host/Origin/body-size refusals and the fallback recording. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::{SystemTime, UNIX_EPOCH}; + +use fpai_collect::self_report::{self, Category, McpEndpoint, Settings}; +use fpai_collect::supervisor::Shutdown; +use serde_json::{Value, json}; + +fn tmpdir(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!( + "fpai-sr-mcp-{}-{}-{}", + name, + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&d).unwrap(); + d +} + +fn write_settings(home: &Path, enabled: bool, categories: Vec) { + self_report::write_settings( + &self_report::settings_path(home), + &Settings { + version: 1, + enabled, + source: "local".into(), + categories, + guidance: Some("Prefer one report.".into()), + mcp: McpEndpoint::on_port(4319), + updated_at: "2026-11-25T10:00:00Z".into(), + }, + ) + .unwrap(); +} + +struct Running { + port: u16, + stop: Arc, + task: tokio::task::JoinHandle<()>, + client: reqwest::Client, +} + +impl Running { + async fn start(home: &Path) -> Self { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let stop = Arc::new(AtomicBool::new(false)); + let sd = Shutdown::for_test(stop.clone()); + let home = home.to_path_buf(); + let task = tokio::spawn(async move { + self_report::serve(listener, home, sd).await.unwrap(); + }); + Running { + port, + stop, + task, + client: reqwest::Client::new(), + } + } + + fn url(&self, query: &str) -> String { + format!("http://127.0.0.1:{}/mcp{query}", self.port) + } + + async fn rpc(&self, query: &str, body: Value) -> (u16, Option) { + let response = self + .client + .post(self.url(query)) + .header("Accept", "application/json, text/event-stream") + .header("Content-Type", "application/json") + .body(body.to_string()) + .send() + .await + .unwrap(); + let status = response.status().as_u16(); + let content_type = response + .headers() + .get("content-type") + .map(|v| v.to_str().unwrap().to_string()); + let text = response.text().await.unwrap(); + if text.is_empty() { + return (status, None); + } + assert_eq!(content_type.as_deref(), Some("application/json")); + (status, Some(serde_json::from_str(&text).unwrap())) + } + + async fn stop(self) { + self.stop.store(true, std::sync::atomic::Ordering::Relaxed); + self.task.await.unwrap(); + } +} + +async fn list(server: &Running) -> Value { + let request = json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}); + server.rpc("", request).await.1.unwrap()["result"]["tools"].clone() +} + +fn event_files(home: &Path) -> Vec { + let dir = home.join("custom-agents").join("events"); + let Ok(entries) = fs::read_dir(&dir) else { + return Vec::new(); + }; + let mut out = Vec::new(); + for entry in entries.filter_map(Result::ok) { + if entry.path().extension().is_some_and(|x| x == "jsonl") { + for line in fs::read_to_string(entry.path()).unwrap().lines() { + out.push(serde_json::from_str(line).unwrap()); + } + } + } + out +} + +#[tokio::test(flavor = "multi_thread")] +async fn initialize_list_and_call_the_report_tool() { + let home = tmpdir("flow"); + write_settings(&home, true, self_report::default_categories()); + let server = Running::start(&home).await; + + let (status, reply) = server + .rpc( + "", + json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{ + "protocolVersion":"2025-06-18","capabilities":{}, + "clientInfo":{"name":"test","version":"0"}}}), + ) + .await; + assert_eq!(status, 200); + let reply = reply.unwrap(); + assert_eq!(reply["id"], 1); + assert_eq!(reply["result"]["protocolVersion"], "2025-06-18"); + assert_eq!(reply["result"]["serverInfo"]["name"], "failproofai"); + assert!(reply["result"]["capabilities"]["tools"].is_object()); + + // An unknown revision is answered in ours. + let (_, reply) = server + .rpc( + "", + json!({"jsonrpc":"2.0","id":"x","method":"initialize","params":{"protocolVersion":"1999-01-01"}}), + ) + .await; + assert_eq!(reply.unwrap()["result"]["protocolVersion"], "2025-06-18"); + + let (status, reply) = server + .rpc( + "", + json!({"jsonrpc":"2.0","method":"notifications/initialized"}), + ) + .await; + assert_eq!((status, reply), (202, None)); + + let (_, reply) = server + .rpc("", json!({"jsonrpc":"2.0","id":2,"method":"ping"})) + .await; + assert_eq!(reply.unwrap()["result"], json!({})); + + let (_, reply) = server + .rpc("", json!({"jsonrpc":"2.0","id":3,"method":"tools/list"})) + .await; + let tools = reply.unwrap()["result"]["tools"].clone(); + assert_eq!(tools.as_array().unwrap().len(), 1); + let tool = &tools[0]; + assert_eq!(tool["name"], "report"); + let categories = self_report::default_categories(); + assert_eq!( + tool["description"], + self_report::describe(&categories, Some("Prefer one report.")) + ); + assert_eq!(tool["inputSchema"], self_report::input_schema(&categories)); + + let (status, reply) = server + .rpc( + "", + json!({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{ + "name":"report","arguments":{"category":"looping","detail":"same edit three times"}}}), + ) + .await; + assert_eq!(status, 200); + let reply = reply.unwrap(); + assert_eq!(reply["id"], 4); + assert_eq!( + reply["result"]["content"], + json!([{"type":"text","text":"Recorded."}]) + ); + // No ?agent= (or a hook-recorded agent): nothing written server-side. + assert!(event_files(&home).is_empty()); + + let (_, reply) = server + .rpc( + "", + json!({"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"other","arguments":{}}}), + ) + .await; + assert_eq!(reply.unwrap()["error"]["code"], -32602); + let (_, reply) = server + .rpc( + "", + json!({"jsonrpc":"2.0","id":6,"method":"resources/list"}), + ) + .await; + assert_eq!(reply.unwrap()["error"]["code"], -32601); + + // A batch answers each request and skips the notification. + let (_, reply) = server + .rpc( + "", + json!([{"jsonrpc":"2.0","id":7,"method":"ping"},{"jsonrpc":"2.0","method":"notifications/initialized"}]), + ) + .await; + assert_eq!(reply.unwrap().as_array().unwrap().len(), 1); + + let response = server + .client + .post(server.url("")) + .body("{not json") + .send() + .await + .unwrap(); + assert_eq!(response.status().as_u16(), 400); + + let response = server.client.get(server.url("")).send().await.unwrap(); + assert_eq!(response.status().as_u16(), 405); + + server.stop().await; + fs::remove_dir_all(&home).ok(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_tool_list_follows_the_settings_file() { + let home = tmpdir("follow"); + let server = Running::start(&home).await; + assert_eq!(list(&server).await, json!([]), "no file: off"); + + write_settings( + &home, + true, + vec![Category { + name: "org_custom".into(), + description: "An org's own category.".into(), + }], + ); + let tools = list(&server).await; + assert_eq!( + tools[0]["inputSchema"]["properties"]["category"]["enum"], + json!(["org_custom"]) + ); + + write_settings(&home, false, self_report::default_categories()); + assert_eq!(list(&server).await, json!([]), "disabled: empty list"); + + fs::write(self_report::settings_path(&home), "garbage").unwrap(); + assert_eq!(list(&server).await, json!([]), "unparsable: off"); + + server.stop().await; + fs::remove_dir_all(&home).ok(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn foreign_hosts_and_origins_are_refused() { + let home = tmpdir("guard"); + write_settings(&home, true, self_report::default_categories()); + let server = Running::start(&home).await; + let body = json!({"jsonrpc":"2.0","id":1,"method":"ping"}).to_string(); + let send = |host: Option, origin: Option<&str>| { + let mut request = server.client.post(server.url("")).body(body.clone()); + if let Some(h) = host { + request = request.header("Host", h); + } + if let Some(o) = origin { + request = request.header("Origin", o); + } + async move { request.send().await.unwrap().status().as_u16() } + }; + let port = server.port; + assert_eq!(send(None, None).await, 200); + assert_eq!(send(Some(format!("localhost:{port}")), None).await, 200); + assert_eq!( + send(None, Some(&format!("http://localhost:{port}"))).await, + 200 + ); + assert_eq!(send(Some("evil.example".into()), None).await, 403); + assert_eq!(send(Some(format!("evil.example:{port}")), None).await, 403); + assert_eq!(send(None, Some("https://evil.example")).await, 403); + assert_eq!(send(None, Some("null")).await, 403); + + // A refused GET is refused for its Host, before its method. + let status = server + .client + .get(server.url("")) + .header("Origin", "http://evil.example") + .send() + .await + .unwrap() + .status() + .as_u16(); + assert_eq!(status, 403); + + let big = format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"ping","params":{{"pad":"{}"}}}}"#, + "x".repeat(70 * 1024) + ); + let status = server + .client + .post(server.url("")) + .body(big) + .send() + .await + .unwrap() + .status() + .as_u16(); + assert_eq!(status, 413); + + server.stop().await; + fs::remove_dir_all(&home).ok(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_server_recorded_agent_gets_its_report_written() { + let home = tmpdir("record"); + write_settings(&home, true, self_report::default_categories()); + let activity = home.join("hook-activity"); + fs::create_dir_all(&activity).unwrap(); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() as i64; + fs::write( + activity.join("current.jsonl"), + json!({"timestamp": now - 1000, "eventType": "PreToolUse", "integration": "openclaw", + "sessionId": "oc-session", "cwd": "/srv/agents/helpdesk", "decision": "allow"}) + .to_string() + + "\n", + ) + .unwrap(); + let server = Running::start(&home).await; + let call = |query: &'static str, category: &'static str| { + server.rpc( + query, + json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{ + "name":"report","arguments":{"category":category,"detail":"the ticket API returns 401"}}}), + ) + }; + + // Hook-recorded agents are never written here: their hook already does. + let (_, reply) = call("?agent=claude", "invalid_tool_or_credential").await; + assert_eq!(reply.unwrap()["result"]["content"][0]["text"], "Recorded."); + assert!(event_files(&home).is_empty()); + + let (_, reply) = call("?agent=openclaw", "invalid_tool_or_credential").await; + assert_eq!(reply.unwrap()["result"]["content"][0]["text"], "Recorded."); + let events = event_files(&home); + assert_eq!(events.len(), 1); + let event = &events[0]; + assert_eq!(event["type"], "self_report"); + assert_eq!(event["session_id"], "oc-session"); + assert_eq!(event["agent_id"], "openclaw-helpdesk"); + assert_eq!(event["integration"], "openclaw"); + assert_eq!(event["source"], "mcp"); + assert_eq!(event["category"], "invalid_tool_or_credential"); + assert_eq!(event["detail"], "the ticket API returns 401"); + assert_eq!(event["environment"], "local"); + + // No matching session: still recorded, unattributed. + let (_, _) = call("?agent=goose", "made_up").await; + let events = event_files(&home); + let goose = events + .iter() + .find(|e| e["integration"] == "goose") + .expect("recorded"); + assert_eq!(goose["session_id"], "unattributed"); + assert_eq!(goose["category"], "made_up"); + + server.stop().await; + fs::remove_dir_all(&home).ok(); +} From bb0e71647ff85eb5f176e29b11e5d1a14aded89c Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 25 Nov 2026 21:27:42 +0530 Subject: [PATCH 02/54] [daemon] Self Reports: desired-state field, settings writer, sync and MCP lane Reads the optional selfReport block off desired-state (absent = off, never refuses the response), writes self-report.json (0644, atomic, only on a content change) on Cloud-managed machines, removes a cloud-written file after a disconnect, runs `failproofai self-report sync --quiet` (60 s timeout, via FAILPROOFAI_CLI_CMD) when enabled or the port flips, and starts the MCP server on its own thread regardless of ingest. Co-Authored-By: Claude Opus 5.5 --- crates/failproofaid/src/audit_lane.rs | 2 +- crates/failproofaid/src/cloud_client.rs | 82 ++- crates/failproofaid/src/main.rs | 11 + crates/failproofaid/src/self_report.rs | 506 +++++++++++++++++++ crates/failproofaid/tests/self_report_e2e.rs | 175 +++++++ crates/fpai-collect/src/self_report.rs | 63 ++- crates/fpai-collect/src/supervisor.rs | 6 + 7 files changed, 822 insertions(+), 23 deletions(-) create mode 100644 crates/failproofaid/src/self_report.rs create mode 100644 crates/failproofaid/tests/self_report_e2e.rs diff --git a/crates/failproofaid/src/audit_lane.rs b/crates/failproofaid/src/audit_lane.rs index 0b37f68f1..2fe514a75 100644 --- a/crates/failproofaid/src/audit_lane.rs +++ b/crates/failproofaid/src/audit_lane.rs @@ -567,7 +567,7 @@ enum Outcome { /// system PATH. There is deliberately no fallback to a bare `failproofai`: one /// that resolved to a DIFFERENT installation than the one that wrote this unit /// would scan with a different build's audit engine, silently. -fn cli_command() -> Option { +pub(crate) fn cli_command() -> Option { usable_cli_command(std::env::var("FAILPROOFAI_CLI_CMD").ok()) } diff --git a/crates/failproofaid/src/cloud_client.rs b/crates/failproofaid/src/cloud_client.rs index becfb4d6e..bd93b3d12 100644 --- a/crates/failproofaid/src/cloud_client.rs +++ b/crates/failproofaid/src/cloud_client.rs @@ -882,7 +882,10 @@ impl CloudClient { // this daemon refuses (an unknown schemaVersion, a payload that // does not decode) must not turn troubleshooting back on or start // an upload, so the last valid answer keeps standing. - let (desired, consent) = decode_desired_state(raw)?; + let (desired, consent, self_report) = decode_desired_state(raw)?; + // Applied by the maintenance lane after this tick (see + // `self_report::tick`), so a refused response changes nothing. + crate::self_report::note_desired(self_report); // The org's troubleshooting switch: `machineLogs: false` means // send no daemon log (logship.rs). Absent, from a Cloud with it // on or one that predates the key, means send. @@ -1197,6 +1200,14 @@ pub fn spawn_maintenance( // `desired-state.json` through `reconcile`, which raises the floor // straight back to the old number. Replay protection resumes from // the new identity's first success. + // Self Reports follow enrolment: written from the response just + // accepted, or released when the machine left Cloud. Unknown + // (unreadable credential) changes nothing. + let self_report_enrolment = match &cloud { + Ok(Some(_)) => Some(true), + Ok(None) => Some(false), + Err(_) => None, + }; if maintenance_tick( &store, cloud, @@ -1206,6 +1217,7 @@ pub fn spawn_maintenance( ) { floor_reset_pending = false; } + crate::self_report::tick(self_report_enrolment, &enrolment_withdrawn); wait_until_shutdown( &shutdown, if enrolled { @@ -1333,7 +1345,20 @@ struct LogConsent { /// Validates a desired-state response and decodes it. The log-shipping fields /// come back only with a response that was accepted, so a refused one has /// nothing to apply. -fn decode_desired_state(raw: serde_json::Value) -> Result<(DesiredState, LogConsent), PollFailure> { +/// +/// The third value is the optional `selfReport` block (`None`: absent, which +/// means Self Reports are off). It is read leniently and never refuses the +/// response: a malformed block must not take the policies beside it down. +fn decode_desired_state( + raw: serde_json::Value, +) -> Result< + ( + DesiredState, + LogConsent, + Option, + ), + PollFailure, +> { // THE VERSION IS CHECKED BEFORE THE FIELDS, which is the whole // point of having one. `SUPPORTED_SCHEMA_VERSIONS` accepts 1 as // well, and its comment says that is "for files on DISK, never for @@ -1372,9 +1397,10 @@ fn decode_desired_state(raw: serde_json::Value) -> Result<(DesiredState, LogCons .and_then(serde_json::Value::as_str) .map(str::to_owned), }; + let self_report = crate::self_report::decode(&raw); let desired = serde_json::from_value::(raw) .map_err(|err| PollFailure::payload(format!("invalid desired-state response: {err}")))?; - Ok((desired, consent)) + Ok((desired, consent, self_report)) } /// One poll and its reconcile. `withdrawn` is asked right before anything is @@ -1809,12 +1835,62 @@ mod tests { } fn decode(body: &str) -> Result<(DesiredState, LogConsent), String> { + decode_with_self_report(body).map(|(desired, consent, _)| (desired, consent)) + } + + fn decode_with_self_report( + body: &str, + ) -> Result< + ( + DesiredState, + LogConsent, + Option, + ), + String, + > { decode_desired_state(serde_json::from_str(body).unwrap()).map_err(|f| { assert!(f.reportable, "a refused payload is the server's to see"); f.message }) } + /// `selfReport` rides an accepted response; absent stays absent, and a + /// malformed block never refuses the policies beside it. + #[test] + fn a_desired_state_response_carries_its_self_report_block() { + let (_, _, self_report) = decode_with_self_report( + r#"{"schemaVersion":2,"deployment":7,"policies":[], + "selfReport":{"enabled":true,"categories":[{"name":"x","description":"X."}],"guidance":"g"}}"#, + ) + .expect("a valid response is accepted"); + assert_eq!( + self_report, + Some(crate::self_report::Desired { + enabled: true, + categories: Some(vec![fpai_collect::self_report::Category { + name: "x".into(), + description: "X.".into(), + }]), + guidance: Some("g".into()), + }) + ); + + let (_, _, self_report) = + decode_with_self_report(r#"{"schemaVersion":2,"deployment":7,"policies":[]}"#) + .expect("an older server's response is accepted"); + assert_eq!(self_report, None, "absent means disabled"); + + let (desired, _, self_report) = decode_with_self_report( + r#"{"schemaVersion":2,"deployment":7,"policies":[],"selfReport":[1,2]}"#, + ) + .expect("a malformed block does not refuse the response"); + assert_eq!(desired.deployment, 7); + assert_eq!(self_report, None); + + decode_with_self_report(r#"{"schemaVersion":999,"selfReport":{"enabled":true}}"#) + .expect_err("a refused response carries nothing to apply"); + } + /// A response the daemon refuses carries no consent to apply: the refusal /// used to land AFTER `machineLogs` and `logRequest` were applied, so an /// unknown schemaVersion with no `machineLogs` read as "on", removed diff --git a/crates/failproofaid/src/main.rs b/crates/failproofaid/src/main.rs index 8ec543a1f..55e916cbb 100644 --- a/crates/failproofaid/src/main.rs +++ b/crates/failproofaid/src/main.rs @@ -9,6 +9,7 @@ mod lock; mod logfile; mod logship; mod paths; +mod self_report; mod server; mod telemetry; #[cfg(test)] @@ -272,6 +273,15 @@ fn run() -> Result<(), Box> { // WITHOUT root, against a system unit — takes effect without a restart. let mut audit_lane = audit_lane::spawn(shutdown.clone()); + // Self Reports: the `report` tool's MCP server on 127.0.0.1. Its own + // thread and runtime rather than a collector task, because the collector + // runs only with an ingest credential and an OSS machine needs this too. + // Always listening; `tools/list` is empty while `self-report.json` says + // off. A busy port logs a warning and the daemon carries on. + let mut self_report_mcp = paths::failproofai_home().ok().and_then(|home| { + fpai_collect::self_report::spawn(home, self_report::port(), shutdown.clone()) + }); + // Handled rather than `?`-ed, because a bare `?` here returns past every // join below — including the telemetry flush — so a daemon that cannot bind // its socket would buffer `daemon_started` and then take it to the grave. @@ -314,6 +324,7 @@ fn run() -> Result<(), Box> { // waits on its child and kills the process group rather than waiting the // scan out, so a `systemctl stop` is never held up by an audit. join_lane(&mut audit_lane); + join_lane(&mut self_report_mcp); // Joined BEFORE the stop event is recorded, so nothing contends with the // final send. `run_result` is what distinguishes the two ways this daemon diff --git a/crates/failproofaid/src/self_report.rs b/crates/failproofaid/src/self_report.rs new file mode 100644 index 000000000..b1b38d554 --- /dev/null +++ b/crates/failproofaid/src/self_report.rs @@ -0,0 +1,506 @@ +//! Self Reports on a Cloud-managed machine: the desired-state field, the +//! effective settings file the daemon writes from it, and the sync it runs when +//! the feature flips (CONTRACT §4–§6). +//! +//! The daemon owns `self-report.json` only while the machine is Cloud +//! enrolled. Off Cloud the TypeScript CLI writes it from the local config, so +//! nothing here touches it then — except a file this daemon itself wrote for an +//! org the machine has since left, which is removed (a departed org's toggle +//! must not keep the tool registered in every agent). + +use std::io; +use std::path::Path; +use std::process::{Child, Command, Stdio}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use fpai_collect::self_report::{self as sr, Category, McpEndpoint, Settings}; +use serde_json::Value; + +/// `sync` is bounded: a wedged CLI must not hold a sync slot forever. +const SYNC_TIMEOUT: Duration = Duration::from_secs(60); + +/// The `selfReport` block of a desired-state response, as the server sent it. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Desired { + pub enabled: bool, + /// `None`: the server sent none, so the defaults apply. + pub categories: Option>, + pub guidance: Option, +} + +/// Read `selfReport` off a desired-state body. Absent ⇒ `None` (disabled). +/// +/// Lenient on purpose: this rides the policy response, and a malformed block +/// must not refuse the policies beside it. An `enabled` that is not `true` +/// reads as off; a category without a string name and description is dropped. +pub fn decode(raw: &Value) -> Option { + let block = raw.get("selfReport")?.as_object()?; + let categories = block + .get("categories") + .and_then(Value::as_array) + .map(|items| { + items + .iter() + .filter_map(|item| { + Some(Category { + name: item.get("name")?.as_str()?.to_string(), + description: item.get("description")?.as_str()?.to_string(), + }) + }) + .collect() + }); + Some(Desired { + enabled: block.get("enabled").and_then(Value::as_bool) == Some(true), + categories, + guidance: block + .get("guidance") + .and_then(Value::as_str) + .map(str::to_string), + }) +} + +/// The last accepted response's block, waiting for the maintenance lane to +/// apply it. Outer `None`: no fresh response since the last apply. +static PENDING: Mutex>> = Mutex::new(None); + +/// Called with every ACCEPTED desired-state response. +pub fn note_desired(desired: Option) { + *PENDING.lock().unwrap_or_else(|p| p.into_inner()) = Some(desired); +} + +fn take_pending() -> Option> { + PENDING.lock().unwrap_or_else(|p| p.into_inner()).take() +} + +/// The settings the file should hold for this response. +pub fn effective(desired: Option<&Desired>, port: u16, updated_at: String) -> Settings { + let enabled = desired.is_some_and(|d| d.enabled); + Settings { + version: sr::SETTINGS_VERSION, + enabled, + source: "cloud".to_string(), + categories: sr::sanitize_categories(desired.and_then(|d| d.categories.as_deref())), + guidance: sr::sanitize_guidance(desired.and_then(|d| d.guidance.as_deref())), + mcp: McpEndpoint::on_port(port), + updated_at, + } +} + +/// What one apply did. +#[derive(Debug, PartialEq, Eq)] +pub struct Applied { + pub written: bool, + /// `enabled` or the port changed: agent configs need `self-report sync`. + pub needs_sync: bool, +} + +/// Write `path` for this response, only when its content (not `updatedAt`) +/// changed. +pub fn apply(path: &Path, desired: Option<&Desired>, port: u16) -> io::Result { + let previous = sr::read_settings(path); + let next = effective(desired, port, now_rfc3339()); + if previous.as_ref().is_some_and(|p| p.same_content(&next)) { + return Ok(Applied { + written: false, + needs_sync: false, + }); + } + sr::write_settings(path, &next)?; + let was_enabled = previous.as_ref().is_some_and(|p| p.enabled); + let port_changed = previous.as_ref().is_some_and(|p| p.mcp.port != port); + Ok(Applied { + written: true, + needs_sync: was_enabled != next.enabled || (next.enabled && port_changed), + }) +} + +/// The machine is not enrolled: remove a file this daemon wrote for Cloud. +/// Returns whether agent configs need a sync (the removed file was enabled). +pub fn release(path: &Path) -> io::Result { + let Some(previous) = sr::read_settings(path) else { + return Ok(false); + }; + if previous.source != "cloud" { + return Ok(false); + } + match std::fs::remove_file(path) { + Ok(()) => Ok(previous.enabled), + Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(false), + Err(err) => Err(err), + } +} + +/// One maintenance-lane pass. `enrolled`: `Some(true)` enrolled, `Some(false)` +/// definitely not, `None` unknown (credential unreadable: change nothing). +pub fn tick(enrolled: Option, withdrawn: &dyn Fn() -> bool) { + let Ok(home) = crate::paths::failproofai_home() else { + return; + }; + let path = sr::settings_path(&home); + match enrolled { + Some(true) => { + let Some(desired) = take_pending() else { + return; + }; + // A disconnect that landed during the poll: its answer is not ours + // to apply any more. + if withdrawn() { + return; + } + match apply(&path, desired.as_ref(), port()) { + Ok(Applied { + written: true, + needs_sync, + }) => { + tracing::info!( + "Self Reports {} by FailproofAI Cloud", + if desired.as_ref().is_some_and(|d| d.enabled) { + "enabled" + } else { + "disabled" + } + ); + if needs_sync { + spawn_sync(); + } + } + Ok(_) => {} + Err(err) => tracing::warn!( + "could not write {}: {err}; Self Reports settings unchanged", + path.display() + ), + } + } + Some(false) => { + // Drop any response still pending from before the disconnect. + let _ = take_pending(); + match release(&path) { + Ok(true) => { + tracing::info!("Self Reports settings from FailproofAI Cloud removed"); + spawn_sync(); + } + Ok(false) => {} + Err(err) => tracing::warn!("could not remove {}: {err}", path.display()), + } + } + None => {} + } +} + +/// The MCP port, from `FAILPROOFAI_SELF_REPORT_PORT` once per process. +pub fn port() -> u16 { + static PORT: std::sync::OnceLock = std::sync::OnceLock::new(); + *PORT.get_or_init(sr::port_from_env) +} + +fn now_rfc3339() -> String { + time::OffsetDateTime::now_utc() + .format(&time::format_description::well_known::Rfc3339) + .unwrap_or_default() +} + +// ── `failproofai self-report sync` ─────────────────────────────────────────── + +static SYNC_RUNNING: AtomicBool = AtomicBool::new(false); +static SYNC_AGAIN: AtomicBool = AtomicBool::new(false); + +/// Run `failproofai self-report sync --quiet` off the lane's thread. One at a +/// time: a flip while one runs queues exactly one more, since `sync` reads the +/// file afresh and is idempotent. +pub fn spawn_sync() { + SYNC_AGAIN.store(true, Ordering::SeqCst); + if SYNC_RUNNING.swap(true, Ordering::SeqCst) { + return; + } + let started = std::thread::Builder::new() + .name("fpai-self-report-sync".to_string()) + .spawn(|| { + loop { + while SYNC_AGAIN.swap(false, Ordering::SeqCst) { + run_sync_once(); + } + SYNC_RUNNING.store(false, Ordering::SeqCst); + // A request that arrived between the last swap and the store. + if !SYNC_AGAIN.load(Ordering::SeqCst) || SYNC_RUNNING.swap(true, Ordering::SeqCst) { + break; + } + } + }); + if let Err(err) = started { + SYNC_RUNNING.store(false, Ordering::SeqCst); + tracing::warn!("could not start the Self Reports sync: {err}"); + } +} + +fn run_sync_once() { + // The CLI the service unit names, the same way the audit lane runs it. + let Some(cli) = crate::audit_lane::cli_command() else { + tracing::warn!( + "Self Reports changed but this service unit carries no FAILPROOFAI_CLI_CMD, \ + so agent configs were not updated — run `failproofai self-report sync`" + ); + return; + }; + match run_with_timeout(&format!("{cli} self-report sync --quiet"), SYNC_TIMEOUT) { + Ok(Some(0)) => tracing::info!("Self Reports agent configs synced"), + Ok(Some(code)) => tracing::warn!("`failproofai self-report sync` failed (exit {code})"), + Ok(None) => tracing::warn!("`failproofai self-report sync` was killed (timeout or signal)"), + Err(err) => tracing::warn!("could not run `failproofai self-report sync`: {err}"), + } +} + +/// Run `command` under `sh -c` in its own process group; kill the group after +/// `timeout`. `Ok(None)`: it ended by a signal (including the timeout's). +fn run_with_timeout(command: &str, timeout: Duration) -> io::Result> { + use std::os::unix::process::CommandExt; + let mut child = Command::new("sh") + .arg("-c") + .arg(command) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .process_group(0) + .spawn()?; + for (label, pipe) in [ + ( + "stdout", + child + .stdout + .take() + .map(|p| Box::new(p) as Box), + ), + ( + "stderr", + child + .stderr + .take() + .map(|p| Box::new(p) as Box), + ), + ] { + if let Some(pipe) = pipe { + std::thread::spawn(move || { + use std::io::BufRead; + for line in io::BufReader::new(pipe).lines().map_while(Result::ok) { + tracing::info!("self-report sync {label}: {line}"); + } + }); + } + } + let started = Instant::now(); + loop { + if let Some(status) = child.try_wait()? { + return Ok(status.code()); + } + if started.elapsed() > timeout { + kill_group(&mut child); + return Ok(None); + } + std::thread::sleep(Duration::from_millis(100)); + } +} + +fn kill_group(child: &mut Child) { + unsafe { + libc::kill(-(child.id() as libc::pid_t), libc::SIGKILL); + } + let _ = child.wait(); +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use std::path::PathBuf; + + fn temp_path(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "fpaid-self-report-{name}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir.join("self-report.json") + } + + #[test] + fn the_block_is_read_leniently() { + assert_eq!(decode(&json!({"schemaVersion": 2})), None); + assert_eq!(decode(&json!({"selfReport": "on"})), None); + assert_eq!( + decode(&json!({"selfReport": {"enabled": true}})), + Some(Desired { + enabled: true, + categories: None, + guidance: None + }) + ); + let d = decode(&json!({"selfReport": { + "enabled": "yes", + "categories": [{"name": "a", "description": "A."}, {"name": 3}, "x"], + "guidance": "Be brief." + }})) + .unwrap(); + assert!(!d.enabled, "only a real true enables"); + assert_eq!( + d.categories, + Some(vec![Category { + name: "a".into(), + description: "A.".into() + }]) + ); + assert_eq!(d.guidance.as_deref(), Some("Be brief.")); + } + + #[test] + fn absent_means_disabled_with_the_defaults() { + let s = effective(None, 4319, "t".into()); + assert!(!s.enabled); + assert_eq!(s.source, "cloud"); + assert_eq!(s.categories, sr::default_categories()); + assert_eq!(s.guidance, None); + assert_eq!(s.mcp.url, "http://127.0.0.1:4319/mcp"); + + let s = effective( + Some(&Desired { + enabled: true, + categories: Some(vec![]), + guidance: Some(" ".into()), + }), + 5000, + "t".into(), + ); + assert!(s.enabled); + assert_eq!(s.categories, sr::default_categories(), "never empty"); + assert_eq!(s.guidance, None); + assert_eq!(s.mcp.port, 5000); + } + + #[test] + fn the_file_is_rewritten_only_when_its_content_changes() { + let path = temp_path("apply"); + let on = Desired { + enabled: true, + categories: None, + guidance: None, + }; + + // First write while off: nothing was registered, nothing to sync. + assert_eq!( + apply(&path, None, 4319).unwrap(), + Applied { + written: true, + needs_sync: false + } + ); + let first = std::fs::read_to_string(&path).unwrap(); + assert_eq!( + apply(&path, None, 4319).unwrap(), + Applied { + written: false, + needs_sync: false + } + ); + assert_eq!(std::fs::read_to_string(&path).unwrap(), first, "untouched"); + + assert_eq!( + apply(&path, Some(&on), 4319).unwrap(), + Applied { + written: true, + needs_sync: true + } + ); + assert!(sr::read_settings(&path).unwrap().enabled); + + // Categories changing rewrites but needs no sync: tools/list re-reads. + let custom = Desired { + enabled: true, + categories: Some(vec![Category { + name: "x".into(), + description: "X.".into(), + }]), + guidance: None, + }; + assert_eq!( + apply(&path, Some(&custom), 4319).unwrap(), + Applied { + written: true, + needs_sync: false + } + ); + // A new port does, while enabled. + assert_eq!( + apply(&path, Some(&custom), 4400).unwrap(), + Applied { + written: true, + needs_sync: true + } + ); + assert_eq!( + apply(&path, None, 4400).unwrap(), + Applied { + written: true, + needs_sync: true + } + ); + let s = sr::read_settings(&path).unwrap(); + assert!(!s.enabled); + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o644 + ); + } + + #[test] + fn leaving_cloud_removes_only_a_cloud_file() { + let path = temp_path("release"); + assert!(!release(&path).unwrap(), "no file"); + + let mut local = effective(None, 4319, "t".into()); + local.source = "local".into(); + local.enabled = true; + sr::write_settings(&path, &local).unwrap(); + assert!(!release(&path).unwrap()); + assert!(path.exists(), "the CLI's own file is kept"); + + apply( + &path, + Some(&Desired { + enabled: true, + ..Default::default() + }), + 4319, + ) + .unwrap(); + assert!( + release(&path).unwrap(), + "an enabled cloud file needs a sync" + ); + assert!(!path.exists()); + + apply(&path, None, 4319).unwrap(); + assert!(!release(&path).unwrap(), "a disabled one does not"); + assert!(!path.exists()); + } + + #[test] + fn a_sync_that_overruns_is_killed() { + let started = Instant::now(); + assert_eq!( + run_with_timeout("sleep 30", Duration::from_millis(300)).unwrap(), + None + ); + assert!(started.elapsed() < Duration::from_secs(5)); + assert_eq!( + run_with_timeout("exit 3", Duration::from_secs(5)).unwrap(), + Some(3) + ); + assert_eq!( + run_with_timeout("echo hi", Duration::from_secs(5)).unwrap(), + Some(0) + ); + } +} diff --git a/crates/failproofaid/tests/self_report_e2e.rs b/crates/failproofaid/tests/self_report_e2e.rs new file mode 100644 index 000000000..1973a68b1 --- /dev/null +++ b/crates/failproofaid/tests/self_report_e2e.rs @@ -0,0 +1,175 @@ +//! The real daemon binary serves the Self Reports MCP endpoint without any +//! ingest credential (an OSS machine), and a busy port never costs the +//! enforcement socket. +use std::io::BufRead; +use std::net::TcpListener; +use std::os::unix::net::UnixStream; +use std::path::PathBuf; +use std::process::{Child, Command, Stdio}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use fpai_ipc::{ClientMessage, PROTOCOL_VERSION, ServerMessage, read_message, write_message}; + +struct Daemon { + child: Child, + home: PathBuf, + log: Arc>, +} + +impl Drop for Daemon { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + let _ = std::fs::remove_dir_all(&self.home); + } +} + +fn spawn(port: u16) -> Daemon { + let home = std::env::temp_dir().join(format!( + "fpai-self-report-daemon-{}", + fpai_collect::uploader::new_request_id() + )); + std::fs::create_dir_all(&home).unwrap(); + std::fs::write( + home.join("config.json"), + r#"{"telemetry":{"enabled":false},"audit":{"auto":false}}"#, + ) + .unwrap(); + let mut child = Command::new(env!("CARGO_BIN_EXE_failproofaid")) + .env("HOME", &home) + .env("FAILPROOFAI_HOME", &home) + .env( + "FAILPROOFAI_DAEMON_SOCKET", + home.join("run/failproofaid.sock"), + ) + .env("FAILPROOFAI_TELEMETRY_DISABLED", "1") + .env("FAILPROOFAI_SELF_REPORT_PORT", port.to_string()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let log = Arc::new(Mutex::new(String::new())); + let sink = log.clone(); + let pipe = child.stderr.take().unwrap(); + std::thread::spawn(move || { + for line in std::io::BufReader::new(pipe).lines().map_while(Result::ok) { + let mut log = sink.lock().unwrap(); + log.push_str(&line); + log.push('\n'); + } + }); + Daemon { child, home, log } +} + +fn wait(what: &str, predicate: impl Fn() -> bool) { + let start = Instant::now(); + while !predicate() { + assert!( + start.elapsed() < Duration::from_secs(20), + "timed out: {what}" + ); + std::thread::sleep(Duration::from_millis(50)); + } +} + +fn ping(daemon: &Daemon) { + let mut stream = UnixStream::connect(daemon.home.join("run/failproofaid.sock")).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(2))) + .unwrap(); + write_message( + &mut stream, + &ClientMessage::Ping { + protocol_version: PROTOCOL_VERSION, + }, + ) + .unwrap(); + let response: ServerMessage = read_message(&mut stream).unwrap(); + assert!(matches!(response, ServerMessage::Pong { .. })); +} + +fn free_port() -> u16 { + TcpListener::bind(("127.0.0.1", 0)) + .unwrap() + .local_addr() + .unwrap() + .port() +} + +#[test] +fn an_oss_daemon_serves_the_report_tool() { + let port = free_port(); + let daemon = spawn(port); + fpai_collect::self_report::write_settings( + &daemon.home.join("self-report.json"), + &fpai_collect::self_report::Settings { + version: 1, + enabled: true, + source: "local".into(), + categories: fpai_collect::self_report::default_categories(), + guidance: None, + mcp: fpai_collect::self_report::McpEndpoint::on_port(port), + updated_at: "2026-11-25T10:00:00Z".into(), + }, + ) + .unwrap(); + let client = reqwest::blocking::Client::new(); + let url = format!("http://127.0.0.1:{port}/mcp"); + let list = || { + client + .post(&url) + .header("Content-Type", "application/json") + .body(r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#) + .send() + .ok() + .and_then(|r| r.json::().ok()) + }; + wait("the MCP endpoint", || list().is_some()); + let reply = list().unwrap(); + assert_eq!(reply["result"]["tools"][0]["name"], "report"); + let call = client + .post(&url) + .body(r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"report","arguments":{"category":"looping","detail":"d"}}}"#) + .send() + .unwrap() + .json::() + .unwrap(); + assert_eq!(call["result"]["content"][0]["text"], "Recorded."); + ping(&daemon); + // OSS: the daemon never writes the settings file itself. + let written = + fpai_collect::self_report::read_settings(&daemon.home.join("self-report.json")).unwrap(); + assert_eq!(written.source, "local"); +} + +#[test] +fn a_busy_self_report_port_never_costs_the_enforcement_socket() { + let holder = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = holder.local_addr().unwrap().port(); + let mut daemon = spawn(port); + wait("the busy-port warning", || { + daemon + .log + .lock() + .unwrap() + .contains("Self Reports MCP server off") + }); + wait("the socket", || { + daemon.home.join("run/failproofaid.sock").exists() + }); + ping(&daemon); + std::thread::sleep(Duration::from_millis(300)); + assert!(daemon.child.try_wait().unwrap().is_none(), "still running"); + assert_eq!( + daemon + .log + .lock() + .unwrap() + .matches("Self Reports MCP server off") + .count(), + 1, + "logged once, not restarted in a loop" + ); + drop(holder); +} diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index 9ae61ba9f..a365e1943 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -37,7 +37,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use crate::sources::hooks::transform::{self, HookRow}; -use crate::supervisor::{Shutdown, TaskError, TaskSpec}; +use crate::supervisor::{Shutdown, TaskError}; /// The settings file under the failproofai home. pub const SETTINGS_FILE: &str = "self-report.json"; @@ -374,27 +374,52 @@ struct Server { settings: SettingsCache, } -/// The daemon's MCP task. Not gated on ingest: OSS machines use it too. -pub fn tasks(home: PathBuf, port: u16) -> Vec { - vec![TaskSpec::new("self-report-mcp", move |sd| { - let home = home.clone(); - async move { - let address = SocketAddr::from((Ipv4Addr::LOCALHOST, port)); - let listener = match tokio::net::TcpListener::bind(address).await { - Ok(listener) => listener, +/// Start the daemon's MCP server on its own thread and its own small runtime. +/// +/// Not a collector task: the collector runs only with an ingest credential, +/// and OSS machines need this too. Not the collector's supervisor either, so it +/// never shows up in (or is cycled with) the collector's lifecycle. A busy +/// port logs one warning and the thread ends; the daemon carries on, as with +/// the OTLP relay. Stops when `shutdown` is set. +pub fn spawn( + home: PathBuf, + port: u16, + shutdown: Arc, +) -> Option> { + std::thread::Builder::new() + .name("fpai-self-report".to_string()) + .spawn(move || { + let runtime = match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(rt) => rt, Err(err) => { - tracing::warn!( - port, - %err, - "Self Reports MCP server off: loopback port unavailable; daemon continues" - ); - return Ok(()); // Clean exit: not restarted, not logged again. + tracing::warn!(%err, "Self Reports MCP server off: no runtime; daemon continues"); + return; } }; - tracing::info!(port, "Self Reports MCP server listening on 127.0.0.1"); - serve(listener, home, sd).await - } - })] + runtime.block_on(async move { + let address = SocketAddr::from((Ipv4Addr::LOCALHOST, port)); + let listener = match tokio::net::TcpListener::bind(address).await { + Ok(listener) => listener, + Err(err) => { + tracing::warn!( + port, + %err, + "Self Reports MCP server off: loopback port unavailable; daemon continues" + ); + return; + } + }; + tracing::info!(port, "Self Reports MCP server listening on 127.0.0.1"); + if let Err(err) = serve(listener, home, Shutdown::from_daemon(shutdown)).await { + tracing::warn!(%err, "Self Reports MCP server stopped"); + } + }); + }) + .inspect_err(|err| tracing::warn!(%err, "could not start the Self Reports MCP server")) + .ok() } /// Serve on an already-bound listener until shutdown. The Host/Origin checks diff --git a/crates/fpai-collect/src/supervisor.rs b/crates/fpai-collect/src/supervisor.rs index ca6999020..9c0da8a23 100644 --- a/crates/fpai-collect/src/supervisor.rs +++ b/crates/fpai-collect/src/supervisor.rs @@ -98,6 +98,12 @@ impl Shutdown { } } + /// Observe the daemon's flag alone, for a lane that runs outside the + /// collector (the Self Reports MCP server). + pub(crate) fn from_daemon(daemon: Arc) -> Self { + Self::for_test(daemon) + } + /// True once either the daemon or the collector has been asked to stop. pub fn is_set(&self) -> bool { self.daemon.load(Ordering::Relaxed) || self.collector.load(Ordering::Relaxed) From 65caf1c025c353cfca5045707e3231f8179010e7 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 25 Nov 2026 21:29:03 +0530 Subject: [PATCH 03/54] [hooks] Self Reports: allow and record the report tool, stdio MCP server, self-report CLI - src/hooks/self-report.ts (+ import-free self-report-names.ts): default categories, validation, describe()/inputSchema(), isSelfReportToolName(), SELF_REPORT_SERVER_RECORDS, self-report.json read/atomic 0644 write, local config.json selfReport block, Cloud-enrolment check. - handler.ts: the report tool short-circuits before fail-closed, pause, every policy layer and Jev; PreToolUse row carries selfReport (hook-recorded agents only), PermissionRequest/PostToolUse rows are persisted without it. - tool-name-canonicalize.ts: every agent spelling files as mcp__failproofai__report. - hook-activity-store.ts: optional selfReport field, sanitized on persist. - failproofai mcp [--agent]: stdio MCP server with server-side fallback recording into the custom-agents spool (SDK writer format). - failproofai self-report status|enable|disable|test (+ help rows). Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/help-index.test.ts | 2 +- __tests__/hooks/self-report-handler.test.ts | 200 ++++++++++ __tests__/hooks/self-report.test.ts | 413 ++++++++++++++++++++ bin/failproofai.mjs | 92 ++++- src/hooks/handler.ts | 83 ++++ src/hooks/hook-activity-store.ts | 32 +- src/hooks/self-report-cli.ts | 361 +++++++++++++++++ src/hooks/self-report-mcp.ts | 325 +++++++++++++++ src/hooks/self-report-names.ts | 79 ++++ src/hooks/self-report.ts | 392 +++++++++++++++++++ src/hooks/tool-name-canonicalize.ts | 5 + 11 files changed, 1981 insertions(+), 3 deletions(-) create mode 100644 __tests__/hooks/self-report-handler.test.ts create mode 100644 __tests__/hooks/self-report.test.ts create mode 100644 src/hooks/self-report-cli.ts create mode 100644 src/hooks/self-report-mcp.ts create mode 100644 src/hooks/self-report-names.ts create mode 100644 src/hooks/self-report.ts diff --git a/__tests__/hooks/help-index.test.ts b/__tests__/hooks/help-index.test.ts index 9b1baae78..aedca4dca 100644 --- a/__tests__/hooks/help-index.test.ts +++ b/__tests__/hooks/help-index.test.ts @@ -24,7 +24,7 @@ import { join, resolve } from "node:path"; const BINARY = resolve(__dirname, "..", "..", "bin", "failproofai.mjs"); /** The redesign's index, with room for a row or two more — not a second screen's worth. */ -const MAX_LINES = 36; +const MAX_LINES = 37; // +1: the Self Reports row (self-report) const MAX_COLUMNS = 80; const HEADINGS = ["GET STARTED", "SET UP", "ENFORCE", "OBSERVE", "LESS OFTEN", "EXAMPLES"]; diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts new file mode 100644 index 000000000..0fdcc72c3 --- /dev/null +++ b/__tests__/hooks/self-report-handler.test.ts @@ -0,0 +1,200 @@ +// @vitest-environment node +/** + * The Self Reports short-circuit in evaluateHookEvent: a call to the report + * tool is allowed before ANY policy, pause, fail-closed or Jev logic, and is + * recorded on its activity row. The control call in each case (a plain Bash + * call) shows the same setup really does deny, so an allow is not vacuous. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +vi.mock("../../src/hooks/hooks-config", () => ({ + readMergedHooksConfig: vi.fn(() => ({ enabledPolicies: [] })), +})); +vi.mock("../../src/hooks/custom-hooks-loader", () => ({ loadAllCustomHooks: vi.fn() })); +vi.mock("../../src/hooks/hook-telemetry", () => ({ + trackHookEvent: vi.fn(() => Promise.resolve()), + flushHookTelemetry: vi.fn(() => Promise.resolve()), +})); +vi.mock("../../lib/telemetry-id", () => ({ getInstanceId: vi.fn(() => "test-instance-id") })); +vi.mock("../../src/hooks/untraced-note", () => ({ noteUntracedAgent: vi.fn(() => false) })); +vi.mock("../../src/hooks/pack-manifest", () => ({ + readInstalledPacks: vi.fn(() => ({ packs: [], errors: [] })), + hasInstalledPacks: vi.fn(() => false), + hasInstalledRegexPacks: vi.fn(() => false), +})); +vi.mock("../../src/hooks/effective-reviewers", async (orig) => { + const real = await orig(); + // "Jev is configured": every gate that reaches the two-tier path asks this. + return { ...real, jevChecksInstalled: vi.fn(() => true), packJevChecksInstalled: vi.fn(() => true) }; +}); + +import { evaluateHookEvent } from "../../src/hooks/handler"; +import { loadAllCustomHooks } from "../../src/hooks/custom-hooks-loader"; +import { readMergedHooksConfig } from "../../src/hooks/hooks-config"; +import { jevChecksInstalled } from "../../src/hooks/effective-reviewers"; +import { writePause } from "../../src/hooks/session-pause"; +import { _resetForTest } from "../../src/hooks/hook-activity-store"; + +const SESSION = "sr-session"; +let home: string; + +function payload(toolName: string, toolInput: unknown, extra: Record = {}): string { + return JSON.stringify({ session_id: SESSION, cwd: "/tmp/project", tool_name: toolName, tool_input: toolInput, ...extra }); +} +const report = (extra: Record = {}) => + payload("mcp__failproofai__report", { category: "invalid_tool_or_credential", detail: "tracker rejected its API key" }, extra); +const bash = () => payload("Bash", { command: "echo hi" }); + +function rows(): Array> { + try { + return readFileSync(join(home, "hook-activity", "current.jsonl"), "utf8") + .split("\n") + .filter(Boolean) + .map((l) => JSON.parse(l) as Record); + } catch { + return []; + } +} + +beforeEach(() => { + vi.clearAllMocks(); + home = mkdtempSync(join(tmpdir(), "fpai-sr-handler-")); + process.env.FAILPROOFAI_HOME = home; + process.env.FAILPROOFAI_STATE_DIR = join(home, "state"); + _resetForTest(join(home, "hook-activity")); + // A custom policy that denies everything, on every event. + vi.mocked(loadAllCustomHooks).mockImplementation((async () => ({ + hooks: [ + Object.assign( + { name: "deny-all", description: "", match: {}, fn: async () => ({ decision: "deny", reason: "nothing passes" }) }, + { __policyId: "custom:/tmp/deny.mjs:deny-all" }, + ), + ], + conventionSources: [], + })) as never); +}); + +afterEach(() => { + delete process.env.FAILPROOFAI_HOME; + delete process.env.FAILPROOFAI_STATE_DIR; + _resetForTest(); + rmSync(home, { recursive: true, force: true }); +}); + +describe("Self Reports short-circuit", () => { + it("control: the deny-everything policy really denies an ordinary call", async () => { + const out = await evaluateHookEvent("PreToolUse", "claude", bash()); + expect(out.evaluation?.decision).toBe("deny"); + expect(out.stdout).toContain("deny"); + }); + + it("allows the report tool even with a deny-everything custom policy, and loads no policy at all", async () => { + const out = await evaluateHookEvent("PreToolUse", "claude", report()); + expect(out).toMatchObject({ exitCode: 0, stdout: "", stderr: "" }); + expect(out.evaluation?.decision).toBe("allow"); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + expect(readMergedHooksConfig).not.toHaveBeenCalled(); + }); + + it("records the report on its activity row", async () => { + await evaluateHookEvent("PreToolUse", "claude", report({ tool_use_id: "toolu_1" })); + const [row] = rows(); + expect(row).toMatchObject({ + eventType: "PreToolUse", + integration: "claude", + toolName: "mcp__failproofai__report", + decision: "allow", + policyName: null, + sessionId: SESSION, + toolCallId: "toolu_1", + selfReport: { category: "invalid_tool_or_credential", detail: "tracker rejected its API key", source: "mcp" }, + }); + }); + + it("allows it with fail-closed forced (daemon unreachable), while the control call is denied", async () => { + const force = { forceDecision: { decision: "deny" as const, reason: "daemon down" } }; + expect((await evaluateHookEvent("PreToolUse", "claude", bash(), force)).evaluation?.decision).toBe("deny"); + const out = await evaluateHookEvent("PreToolUse", "claude", report(), force); + expect(out.evaluation?.decision).toBe("allow"); + expect(out.stdout).toBe(""); + }); + + it("allows it while the session is paused, and the row carries no pause fields", async () => { + writePause({ sessionId: SESSION, durationMs: 600_000 }); + const out = await evaluateHookEvent("PreToolUse", "claude", report()); + expect(out.evaluation?.decision).toBe("allow"); + const row = rows().pop()!; + expect(row.pausedBy).toBeUndefined(); + expect(row.selfReport).toBeDefined(); + }); + + it("never reaches Jev, which a gate otherwise consults", async () => { + await evaluateHookEvent("PreToolUse", "claude", bash()); + expect(jevChecksInstalled).toHaveBeenCalled(); + vi.mocked(jevChecksInstalled).mockClear(); + await evaluateHookEvent("PreToolUse", "claude", report()); + expect(jevChecksInstalled).not.toHaveBeenCalled(); + }); + + it("allows on PermissionRequest too, persisting the row without a second report", async () => { + const out = await evaluateHookEvent("PermissionRequest", "claude", report()); + expect(out.evaluation?.decision).toBe("allow"); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + const row = rows().pop()!; + expect(row.eventType).toBe("PermissionRequest"); + expect(row.selfReport).toBeUndefined(); + }); + + it("one call (PreToolUse + PermissionRequest + PostToolUse) yields exactly one row with selfReport", async () => { + for (const ev of ["PreToolUse", "PermissionRequest", "PostToolUse"]) { + expect((await evaluateHookEvent(ev, "claude", report())).evaluation?.decision).toBe("allow"); + } + const all = rows(); + expect(all.map((r) => r.eventType)).toEqual(["PreToolUse", "PermissionRequest", "PostToolUse"]); + expect(all.filter((r) => r.selfReport !== undefined).map((r) => r.eventType)).toEqual(["PreToolUse"]); + }); + + it("records PostToolUse without evaluating it and without a second report", async () => { + const out = await evaluateHookEvent("PostToolUse", "claude", report()); + expect(out.evaluation?.decision).toBe("allow"); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + const row = rows().pop()!; + expect(row.eventType).toBe("PostToolUse"); + expect(row.selfReport).toBeUndefined(); + }); + + it("recognises Codex's snake_case event and its name for the tool", async () => { + const out = await evaluateHookEvent("pre_tool_use", "codex", report()); + expect(out.evaluation?.decision).toBe("allow"); + expect(rows().pop()!.selfReport).toMatchObject({ category: "invalid_tool_or_credential" }); + }); + + it("files another agent's spelling under the canonical name", async () => { + const out = await evaluateHookEvent("PreToolUse", "claude", payload("failproofai__report", { category: "looping", detail: "x" })); + expect(out.evaluation?.decision).toBe("allow"); + expect(rows().pop()!.toolName).toBe("mcp__failproofai__report"); + }); + + it("for an agent whose MCP server records, allows but leaves the report to the server", async () => { + const out = await evaluateHookEvent("PreToolUse", "factory", report()); + expect(out.evaluation?.decision).toBe("allow"); + const row = rows().pop()!; + expect(row.integration).toBe("factory"); + expect(row.selfReport).toBeUndefined(); + }); + + it("records an unknown category as-is, a missing detail as empty, and cuts detail at 2000", async () => { + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai__report", { category: "made_up" })); + expect(rows().pop()!.selfReport).toEqual({ category: "made_up", detail: "", source: "mcp" }); + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai__report", { category: "looping", detail: "y".repeat(5000) })); + expect((rows().pop()!.selfReport as { detail: string }).detail).toHaveLength(2000); + }); + + it("does not exempt a lookalike tool name", async () => { + const out = await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai__report_evil", {})); + expect(out.evaluation?.decision).toBe("deny"); + }); +}); diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts new file mode 100644 index 000000000..aeaa23e11 --- /dev/null +++ b/__tests__/hooks/self-report.test.ts @@ -0,0 +1,413 @@ +// @vitest-environment node +/** + * Self Reports: the shared text, names and settings (src/hooks/self-report.ts), + * the stdio MCP server spawned for real (`failproofai mcp`), and the + * `self-report status | enable | disable` commands. + */ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { spawn } from "node:child_process"; +import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, mkdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { + DEFAULT_CATEGORIES, + SELF_REPORT_SERVER_RECORDS, + describe as describeTool, + inputSchema, + isSelfReportToolName, + readEffectiveSelfReport, + selfReportArgs, + selfReportCloudManaged, + validateSelfReportCategories, + validateSelfReportGuidance, + writeEffectiveSelfReport, +} from "../../src/hooks/self-report"; +import { handleSelfReportRpc, selfReportAgentId, selfReportFindSession } from "../../src/hooks/self-report-mcp"; +import { runSelfReportCommand } from "../../src/hooks/self-report-cli"; + +const BINARY = resolve(__dirname, "..", "..", "bin", "failproofai.mjs"); + +const EXPECTED_DESCRIPTION = `Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; do not call it for normal work, clarifying questions or a single error. One call per distinct problem. +Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. + +Categories: +- looping: You keep repeating the same or circular steps without making progress. +- cannot_do_request: The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating. +- invalid_tool_or_credential: A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. +- missing_context: Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. +- repeated_tool_failure: A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. +- task_failure: You genuinely tried and could not complete the task. Not for refusals or policy blocks.`; + +let home: string; +const savedEnv: Record = {}; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "fpai-sr-")); + for (const k of ["FAILPROOFAI_HOME", "FAILPROOFAI_CLOUD_URL", "FAILPROOFAI_CLOUD_CREDENTIALS", "FAILPROOFAI_SELF_REPORT_PORT"]) { + savedEnv[k] = process.env[k]; + delete process.env[k]; + } + process.env.FAILPROOFAI_HOME = home; +}); + +afterEach(() => { + for (const [k, v] of Object.entries(savedEnv)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + rmSync(home, { recursive: true, force: true }); +}); + +describe("tool text and schema (contract §3)", () => { + it("describe() produces the exact contract text for the defaults", () => { + expect(describeTool(DEFAULT_CATEGORIES)).toBe(EXPECTED_DESCRIPTION); + }); + + it("appends guidance after a blank line, and only when there is some", () => { + expect(describeTool(DEFAULT_CATEGORIES, "Report tracker outages.")).toBe(`${EXPECTED_DESCRIPTION}\n\nReport tracker outages.`); + expect(describeTool(DEFAULT_CATEGORIES, null)).toBe(EXPECTED_DESCRIPTION); + expect(describeTool(DEFAULT_CATEGORIES, "")).toBe(EXPECTED_DESCRIPTION); + }); + + it("inputSchema() is the contract schema with the category names as the enum", () => { + expect(inputSchema([{ name: "a", description: "x" }, { name: "b_2", description: "y" }])).toEqual({ + type: "object", + properties: { + category: { type: "string", enum: ["a", "b_2"] }, + detail: { type: "string", description: "One factual sentence: what is blocking you." }, + }, + required: ["category", "detail"], + additionalProperties: false, + }); + }); + + it("selfReportArgs keeps unknown categories, defaults detail to empty, cuts at 2000, and unwraps arguments", () => { + expect(selfReportArgs({ category: "nope" })).toEqual({ category: "nope", detail: "" }); + expect(selfReportArgs({ category: "looping", detail: "z".repeat(3000) }).detail).toHaveLength(2000); + expect(selfReportArgs({ arguments: { category: "looping", detail: "d" } })).toEqual({ category: "looping", detail: "d" }); + expect(selfReportArgs({ arguments: '{"category":"looping","detail":"s"}' })).toEqual({ category: "looping", detail: "s" }); + expect(selfReportArgs(undefined)).toEqual({ category: "", detail: "" }); + }); +}); + +describe("tool-name matching (contract §1)", () => { + it.each(["mcp__failproofai__report", "failproofai__report", "failproofai_report", "failproofai.report", "failproofai/report", "MCP__FAILPROOFAI__REPORT"])( + "matches %s", + (name) => expect(isSelfReportToolName(name)).toBe(true), + ); + it.each(["report", "mcp__other__report", "mcp__failproofai__report2", "xfailproofai_report", "Bash", "", undefined, 7])( + "does not match %s", + (name) => expect(isSelfReportToolName(name)).toBe(false), + ); + it("lists the server-recorded integrations from the contract", () => { + expect(SELF_REPORT_SERVER_RECORDS).toEqual(["openclaw", "pi", "devin", "hermes", "goose", "factory", "antigravity", "copilot", "opencode"]); + for (const hookRecorded of ["claude", "codex", "cursor"]) expect(SELF_REPORT_SERVER_RECORDS).not.toContain(hookRecorded); + }); +}); + +describe("validation (contract §2)", () => { + it("accepts the defaults", () => { + expect(validateSelfReportCategories(DEFAULT_CATEGORIES).ok).toBe(true); + }); + it.each([ + [[], "empty"], + [Array.from({ length: 33 }, (_, i) => ({ name: `c${i}`, description: "d" })), "too many"], + [[{ name: "Bad", description: "d" }], "uppercase name"], + [[{ name: "a".repeat(65), description: "d" }], "long name"], + [[{ name: "ok", description: "" }], "empty description"], + [[{ name: "ok", description: "x".repeat(501) }], "long description"], + [[{ name: "ok", description: "a" }, { name: "ok", description: "b" }], "duplicate"], + ["nope", "not a list"], + ])("rejects %j (%s)", (input, _label) => { + expect(validateSelfReportCategories(input).ok).toBe(false); + }); + it("guidance: at most 2000 characters, blank is none", () => { + expect(validateSelfReportGuidance("x".repeat(2000)).ok).toBe(true); + expect(validateSelfReportGuidance("x".repeat(2001)).ok).toBe(false); + expect(validateSelfReportGuidance(" ")).toEqual({ ok: true, value: null }); + }); +}); + +describe("self-report.json (contract §4)", () => { + it("missing or unparsable reads as disabled (null)", () => { + expect(readEffectiveSelfReport()).toBeNull(); + writeFileSync(join(home, "self-report.json"), "{not json"); + expect(readEffectiveSelfReport()).toBeNull(); + writeFileSync(join(home, "self-report.json"), JSON.stringify({ version: 2, enabled: true })); + expect(readEffectiveSelfReport()).toBeNull(); + }); + + it("writes atomically at 0644 with the contract shape, and reads back", () => { + process.env.FAILPROOFAI_SELF_REPORT_PORT = "4400"; + writeEffectiveSelfReport({ enabled: true, guidance: "g" }); + const path = join(home, "self-report.json"); + expect(statSync(path).mode & 0o777).toBe(0o644); + const raw = JSON.parse(readFileSync(path, "utf8")); + expect(raw).toMatchObject({ + version: 1, + enabled: true, + source: "local", + guidance: "g", + mcp: { port: 4400, url: "http://127.0.0.1:4400/mcp" }, + }); + expect(raw.categories).toEqual(DEFAULT_CATEGORIES); + expect(raw.updatedAt).toMatch(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/); + expect(readdirSync(home).filter((f) => f.endsWith(".tmp"))).toEqual([]); + expect(readEffectiveSelfReport()).toMatchObject({ enabled: true, source: "local", guidance: "g" }); + }); + + it("an enabled file with an unusable category list falls back to the defaults", () => { + writeFileSync(join(home, "self-report.json"), JSON.stringify({ version: 1, enabled: true, source: "cloud", categories: [] })); + expect(readEffectiveSelfReport()).toMatchObject({ enabled: true, source: "cloud", categories: DEFAULT_CATEGORIES }); + }); +}); + +describe("Cloud enrolment", () => { + it("is off with no credential, on with FAILPROOFAI_CLOUD_URL", async () => { + expect(await selfReportCloudManaged()).toBe(false); + process.env.FAILPROOFAI_CLOUD_URL = "https://example.invalid"; + expect(await selfReportCloudManaged()).toBe(true); + }); + + it("is on with a stored cloud credential, off again once config says oss", async () => { + const creds = join(home, "cloud-creds.json"); + writeFileSync(creds, JSON.stringify({ schemaVersion: 1, url: "https://example.invalid", machineId: "m", token: "t" })); + process.env.FAILPROOFAI_CLOUD_CREDENTIALS = creds; + expect(await selfReportCloudManaged()).toBe(true); + writeFileSync(join(home, "config.json"), JSON.stringify({ mode: { kind: "oss" } })); + expect(await selfReportCloudManaged()).toBe(false); + }); +}); + +describe("MCP fallback recording helpers", () => { + it("agent id mirrors the collector's -", () => { + expect(selfReportAgentId("pi", "/home/u/My Repo/")).toBe("pi-My-Repo"); + expect(selfReportAgentId("hermes", undefined)).toBe("hermes"); + }); + + it("finds the newest session for the agent and cwd within 6 h", () => { + const now = 1_800_000_000_000; + mkdirSync(join(home, "hook-activity"), { recursive: true }); + const row = (o: Record) => JSON.stringify({ eventType: "PreToolUse", decision: "allow", ...o }); + writeFileSync( + join(home, "hook-activity", "current.jsonl"), + [ + row({ integration: "pi", cwd: "/p", sessionId: "old", timestamp: now - 7 * 3600_000 }), + row({ integration: "pi", cwd: "/p", sessionId: "s1", timestamp: now - 3600_000 }), + row({ integration: "pi", cwd: "/p", sessionId: "s2", timestamp: now - 60_000 }), + row({ integration: "pi", cwd: "/other", sessionId: "wrong-cwd", timestamp: now }), + row({ integration: "goose", cwd: "/p", sessionId: "wrong-agent", timestamp: now }), + ].join("\n") + "\n", + ); + expect(selfReportFindSession("pi", "/p", now)).toBe("s2"); + expect(selfReportFindSession("pi", "/nowhere", now)).toBeNull(); + expect(selfReportFindSession("pi", "/p", now + 10 * 3600_000)).toBeNull(); + }); + + it("an unknown method gets -32601; a notification gets no reply; an unknown tool is an error result", async () => { + expect(await handleSelfReportRpc({ jsonrpc: "2.0", id: 9, method: "resources/list" })).toMatchObject({ error: { code: -32601 } }); + expect(await handleSelfReportRpc({ jsonrpc: "2.0", method: "notifications/initialized" })).toBeNull(); + expect(await handleSelfReportRpc({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "other" } })).toMatchObject({ + result: { isError: true }, + }); + }); +}); + +/** Spawn `failproofai mcp`, send these messages, collect the replies. */ +function runMcp(agentArgs: string[], messages: unknown[], cwd: string): Promise<{ replies: Array>; code: number | null; stderr: string }> { + return new Promise((resolveRun, reject) => { + const child = spawn("bun", [BINARY, "mcp", ...agentArgs], { + cwd, + env: { ...process.env, HOME: home, FAILPROOFAI_HOME: home, FAILPROOFAI_TELEMETRY_DISABLED: "1" }, + stdio: ["pipe", "pipe", "pipe"], + }); + let out = ""; + let err = ""; + child.stdout.on("data", (b: Buffer) => (out += b.toString())); + child.stderr.on("data", (b: Buffer) => (err += b.toString())); + child.on("error", reject); + child.on("close", (code) => { + try { + resolveRun({ replies: out.split("\n").filter(Boolean).map((l) => JSON.parse(l)), code, stderr: err }); + } catch (e) { + reject(new Error(`non-JSON on stdout: ${out}\n${String(e)}`)); + } + }); + child.stdin.end(messages.map((m) => JSON.stringify(m)).join("\n") + "\n"); + }); +} + +const INIT = { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "t", version: "1" } } }; +const INITIALIZED = { jsonrpc: "2.0", method: "notifications/initialized" }; +const LIST = { jsonrpc: "2.0", id: 2, method: "tools/list" }; +const CALL = { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "report", arguments: { category: "looping", detail: "stuck in a retry loop" } } }; +const PING = { jsonrpc: "2.0", id: 4, method: "ping" }; + +describe("failproofai mcp (stdio, spawned)", () => { + it("answers initialize, ping, and an empty tools/list while disabled — with no daemon", async () => { + const { replies, code } = await runMcp([], [INIT, INITIALIZED, LIST, PING], home); + expect(code).toBe(0); + expect(replies.map((r) => r.id)).toEqual([1, 2, 4]); + expect(replies[0]).toMatchObject({ result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "failproofai" } } }); + expect(replies[1]).toEqual({ jsonrpc: "2.0", id: 2, result: { tools: [] } }); + expect(replies[2]).toEqual({ jsonrpc: "2.0", id: 4, result: {} }); + }, 30_000); + + it("lists the report tool from self-report.json and answers a call with exactly Recorded.", async () => { + writeEffectiveSelfReport({ enabled: true, categories: [{ name: "looping", description: "loops" }], guidance: "be terse" }); + const { replies } = await runMcp(["--agent", "claude"], [INIT, LIST, CALL], home); + const tools = (replies[1].result as { tools: Array> }).tools; + expect(tools).toHaveLength(1); + expect(tools[0].name).toBe("report"); + expect(tools[0].description).toBe(describeTool([{ name: "looping", description: "loops" }], "be terse")); + expect(tools[0].inputSchema).toEqual(inputSchema([{ name: "looping", description: "loops" }])); + expect(replies[2]).toEqual({ jsonrpc: "2.0", id: 3, result: { content: [{ type: "text", text: "Recorded." }] } }); + }, 30_000); + + it("writes no event for a hook-recorded agent (claude)", async () => { + writeEffectiveSelfReport({ enabled: true }); + await runMcp(["--agent", "claude"], [INIT, CALL], home); + expect(() => readdirSync(join(home, "custom-agents", "events"))).toThrow(); + }, 30_000); + + it("writes one self_report event in the SDK spool format for a server-recorded agent, attributed to its session", async () => { + writeEffectiveSelfReport({ enabled: true }); + const project = join(home, "proj"); + mkdirSync(project); + mkdirSync(join(home, "hook-activity"), { recursive: true }); + writeFileSync( + join(home, "hook-activity", "current.jsonl"), + JSON.stringify({ timestamp: Date.now() - 1000, eventType: "PreToolUse", integration: "pi", cwd: project, sessionId: "pi-sess", decision: "allow" }) + "\n", + ); + const { replies } = await runMcp(["--agent", "pi"], [INIT, CALL], project); + expect(replies[1]).toMatchObject({ result: { content: [{ type: "text", text: "Recorded." }] } }); + const dir = join(home, "custom-agents", "events"); + const files = readdirSync(dir); + expect(files).toHaveLength(1); + expect(files[0]).toMatch(/^event-\d{4}-\d\d-\d\dT[\d-]+Z-\d+-\d+\.jsonl$/); + expect(statSync(join(dir, files[0])).mode & 0o777).toBe(0o600); + expect(statSync(dir).mode & 0o777).toBe(0o700); + const lines = readFileSync(join(dir, files[0]), "utf8").split("\n").filter(Boolean); + expect(lines).toHaveLength(1); + const event = JSON.parse(lines[0]); + expect(event).toMatchObject({ + type: "self_report", + session_id: "pi-sess", + agent_id: "pi-proj", + environment: "local", + category: "looping", + detail: "stuck in a retry loop", + source: "mcp", + integration: "pi", + }); + expect(Number.isNaN(Date.parse(event.timestamp))).toBe(false); + }, 30_000); + + it("falls back to session \"unattributed\" when no live session matches", async () => { + writeEffectiveSelfReport({ enabled: true }); + await runMcp(["--agent", "hermes"], [INIT, CALL], home); + const dir = join(home, "custom-agents", "events"); + const event = JSON.parse(readFileSync(join(dir, readdirSync(dir)[0]), "utf8")); + expect(event.session_id).toBe("unattributed"); + }, 30_000); + + it("rejects a missing --agent value on stderr, never on stdout", async () => { + const { replies, code, stderr } = await runMcp(["--agent"], [INIT], home); + expect(code).toBe(1); + expect(replies).toEqual([]); + expect(stderr).toContain("--agent"); + }, 30_000); +}); + +describe("failproofai self-report enable | disable | status", () => { + const deps = { skipSync: true, probeEndpoint: async () => false }; + + it("enable writes config.json's selfReport and self-report.json; status shows it", async () => { + writeFileSync(join(home, "config.json"), JSON.stringify({ unrelated: { keep: true } })); + const enabled = await runSelfReportCommand(["enable", "--guidance", "say what tool"], deps); + expect(enabled.exitCode).toBe(0); + const config = JSON.parse(readFileSync(join(home, "config.json"), "utf8")); + expect(config.selfReport).toEqual({ enabled: true, guidance: "say what tool" }); + expect(config.unrelated).toEqual({ keep: true }); + expect(readEffectiveSelfReport()).toMatchObject({ enabled: true, source: "local", guidance: "say what tool", categories: DEFAULT_CATEGORIES }); + + const status = await runSelfReportCommand(["status"], deps); + expect(status.exitCode).toBe(0); + const text = status.lines.join("\n"); + expect(text).toContain("Self Reports: on"); + expect(text).toContain("this machine"); + expect(text).toContain("looping, cannot_do_request"); + expect(text).toContain("http://127.0.0.1:4319/mcp"); + }); + + it("enable --categories-file replaces the defaults; a bad file is refused and writes nothing", async () => { + const good = join(home, "cats.json"); + writeFileSync(good, JSON.stringify({ categories: [{ name: "tracker_down", description: "The tracker is down." }] })); + expect((await runSelfReportCommand(["enable", "--categories-file", good], deps)).exitCode).toBe(0); + expect(readEffectiveSelfReport()?.categories).toEqual([{ name: "tracker_down", description: "The tracker is down." }]); + + rmSync(join(home, "self-report.json")); + const bad = join(home, "bad.json"); + writeFileSync(bad, JSON.stringify([{ name: "Bad Name", description: "x" }])); + const refused = await runSelfReportCommand(["enable", "--categories-file", bad], deps); + expect(refused.exitCode).toBe(1); + expect(refused.lines.join(" ")).toContain("name must match"); + expect(readEffectiveSelfReport()).toBeNull(); + }); + + it("disable turns it off and keeps the categories for next time", async () => { + const cats = join(home, "cats.json"); + writeFileSync(cats, JSON.stringify([{ name: "x_y", description: "d" }])); + await runSelfReportCommand(["enable", "--categories-file", cats], deps); + const off = await runSelfReportCommand(["disable"], deps); + expect(off.exitCode).toBe(0); + expect(readEffectiveSelfReport()).toMatchObject({ enabled: false }); + expect(JSON.parse(readFileSync(join(home, "config.json"), "utf8")).selfReport).toEqual({ + enabled: false, + categories: [{ name: "x_y", description: "d" }], + }); + expect((await runSelfReportCommand(["enable"], deps)).exitCode).toBe(0); + expect(readEffectiveSelfReport()?.categories).toEqual([{ name: "x_y", description: "d" }]); + }); + + it("refuses enable and disable on a Cloud-managed machine and changes nothing", async () => { + process.env.FAILPROOFAI_CLOUD_URL = "https://example.invalid"; + for (const verb of ["enable", "disable"]) { + const r = await runSelfReportCommand([verb], deps); + expect(r.exitCode).toBe(1); + expect(r.lines.join(" ")).toContain("FailproofAI Cloud"); + } + expect(readEffectiveSelfReport()).toBeNull(); + expect(() => readFileSync(join(home, "config.json"))).toThrow(); + }); + + it("status with no settings file says it is off", async () => { + const r = await runSelfReportCommand(["status"], deps); + expect(r.exitCode).toBe(0); + expect(r.lines[0]).toContain("off"); + }); + + it("test refuses while disabled and rejects an unknown agent", async () => { + expect((await runSelfReportCommand(["test", "--agent", "claude"], deps)).exitCode).toBe(1); + writeEffectiveSelfReport({ enabled: true }); + const r = await runSelfReportCommand(["test", "--agent", "nope"], deps); + expect(r.exitCode).toBe(1); + expect(r.lines[0]).toContain("Not an agent"); + }); + + it("test --agent pi drives the real stdio server and reports the event file", async () => { + writeEffectiveSelfReport({ enabled: true }); + const r = await runSelfReportCommand(["test", "--agent", "pi"], { ...deps, cliCommand: ["bun", BINARY], cwd: home }); + expect(r.exitCode).toBe(0); + const dir = join(home, "custom-agents", "events"); + expect(r.lines.join("\n")).toContain(join(dir, readdirSync(dir)[0])); + }, 30_000); + + it("test --agent claude goes through --hook and lands in hook activity", async () => { + writeEffectiveSelfReport({ enabled: true }); + const r = await runSelfReportCommand(["test", "--agent", "claude"], { ...deps, cliCommand: ["bun", BINARY], cwd: home }); + expect(r.exitCode).toBe(0); + const rows = readFileSync(join(home, "hook-activity", "current.jsonl"), "utf8").trim().split("\n").map((l) => JSON.parse(l)); + expect(rows.pop()).toMatchObject({ toolName: "mcp__failproofai__report", decision: "allow", selfReport: { source: "mcp" } }); + }, 30_000); +}); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index e79a804d7..08a9ab6fb 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -314,6 +314,43 @@ if (hookIdx >= 0) { } } +// mcp [--agent ] — the Self Reports MCP server over stdio, spawned +// by an agent that registered it. Outside runCli() like --hook: stdout is the +// JSON-RPC stream, so nothing else (layout notices, onboarding, the install +// report) may run or print first, and it must work with no daemon. +const SELF_REPORT_MCP_HELP = { + name: "mcp", + usage: [["failproofai mcp [--agent ]", "Serve the Self Reports tool over stdio MCP"]], + options: [ + ["--agent ", "The agent this server was registered for"], + ["", "claude, codex, copilot, cursor, opencode, pi,"], + ["", "hermes, openclaw, factory, devin, antigravity, goose"], + ], +}; +if (args[0] === "mcp") { + if (args.includes("--help") || args.includes("-h")) { + await printHelp(SELF_REPORT_MCP_HELP); + await exitAfterFlush(0); + } + const agentIdx = args.indexOf("--agent"); + const agentArg = agentIdx >= 0 ? args[agentIdx + 1] : undefined; + const stray = args.slice(1).find((a, i) => a !== "--agent" && args[i] !== "--agent"); + if ((agentIdx >= 0 && (!agentArg || agentArg.startsWith("-"))) || stray) { + process.stderr.write( + `✕ ${stray ? `Unexpected argument: ${stray}.` : "Missing agent name after --agent."}\n Run failproofai help mcp for usage.\n`, + ); + await exitAfterFlush(1); + } + try { + const { runSelfReportMcpServer } = await import("../src/hooks/self-report-mcp"); + await runSelfReportMcpServer({ agent: agentArg }); + await exitAfterFlush(0); + } catch (err) { + process.stderr.write(`✕ failproofai mcp: ${err instanceof Error ? err.message : String(err)}\n`); + await exitAfterFlush(1); + } +} + /** * Centralised error handler for all CLI subcommands. * CliError → clean message, no stack trace, exit exitCode (1 or 2) @@ -469,7 +506,7 @@ async function runCli() { // at all, only the paragraph in the top-level dump that this rewrite moved. // `help` and `publish` are new. `policy` and `pack` are canonicalized to // `policies` above and never reach this list. - const SUBCOMMANDS = ["policies", "audit", "config", "uninstall", "backfill", "flush", "harness", "otel", "jev", "publish", "update", "migrate", "help"]; + const SUBCOMMANDS = ["policies", "audit", "config", "uninstall", "backfill", "flush", "harness", "otel", "jev", "self-report", "publish", "update", "migrate", "help"]; // ── help ───────────────────────────────────────────────────────────────── // // The index and the reference manual used to be the same document: 152 lines, @@ -500,6 +537,12 @@ async function runCli() { process.exit(0); process.exit(0); } + // `mcp` is machine-facing too (an agent spawns it), so like --hook it is a + // help topic rather than a row on the index. + if (helpTopic === "mcp") { + await printHelp(SELF_REPORT_MCP_HELP); + process.exit(0); + } // Canonicalize the topic the same way a typed command is canonicalized, so // `help pack` and `help policy` answer instead of erroring. const canonical = @@ -568,6 +611,7 @@ async function runCli() { ["(no args)", "Open the policy dashboard on localhost:8020"], ["audit", "Scan your agents' history for risky and wasteful patterns"], ["otel", "Opt in to OpenTelemetry from agents and apps"], + ["self-report", "Let agents report to you when they are stuck"], ]), ...section("Less often", [ ["harness", "Collect sessions from extra locations per agent"], @@ -983,6 +1027,52 @@ async function runCli() { return; } + // self-report status | enable | disable | test + // + // Self Reports: the `report` tool agents call when they are stuck. On a + // machine managed by FailproofAI Cloud the setting comes from Cloud and + // enable/disable refuse; otherwise they write config.json's `selfReport` and + // ~/.failproofai/self-report.json, then update the agents' MCP entries. + if (args[0] === "self-report") { + const subArgs = args.slice(1); + if (subArgs.length === 0 || subArgs.includes("--help") || subArgs.includes("-h")) { + await printHelp({ + name: "self-report", + usage: [ + ["failproofai self-report status", "Show whether it is on, and where that came from"], + ["failproofai self-report enable [options]", "Turn it on for this machine"], + ["failproofai self-report disable", "Turn it off for this machine"], + ["failproofai self-report test --agent ", "Send one test report end to end"], + // TODO(merge): the installer part adds its `sync` row here. + ], + options: [ + ["--categories-file ", "JSON list of {name, description}; replaces the defaults"], + ["--guidance ", "Extra instructions appended to the tool description"], + ["--agent ", "With test: the agent to send it as"], + ], + examples: [ + "failproofai self-report enable", + "failproofai self-report test --agent claude", + ], + }); + process.exit(0); + } + // TODO(merge): `self-report sync` (installer part) dispatches here, ahead + // of runSelfReportCommand, in its own hunk. + lastSubcommand = "self-report"; + const { runSelfReportCommand } = await import("../src/hooks/self-report-cli"); + const result = await runSelfReportCommand(subArgs); + await printReport(`self-report ${subArgs[0]}`, result.lines, { ok: result.exitCode === 0 }); + await track("cli_self_report", { + ok: result.exitCode === 0, + // The subcommand only — never a category, guidance text or a path. + sub: ["status", "enable", "disable", "test", "sync"].includes(subArgs[0]) ? subArgs[0] : "unknown", + }); + lastSubcommand = null; + await exitAfterFlush(result.exitCode); + return; + } + // jev --url | jev setup | status | test | remove // // The customer's own Jev endpoint and key (BYOK), the only opt-in to the diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 3ca7992ef..a89209839 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -55,6 +55,7 @@ import { } from "./policy-authority"; import type { CustomHook } from "./policy-types"; import { persistHookActivity } from "./hook-activity-store"; +import { isSelfReportToolName, selfReportArgs, SELF_REPORT_SERVER_RECORDS } from "./self-report"; import { deliveryHealth, deliveryHealthLine } from "./delivery-health"; import { trackHookEvent, flushHookTelemetry } from "./hook-telemetry"; import * as hookTelemetry from "./hook-telemetry"; @@ -656,6 +657,71 @@ async function captureJevIntent( } } +/** + * The Self Reports short-circuit's whole answer: one activity row, then allow. + * + * The row carries `selfReport` only on PreToolUse, and only for an agent whose + * hook is the recorder (contract §8). An agent in + * `SELF_REPORT_SERVER_RECORDS` has its report written by the MCP server + * instead, so a hook that turns out to see the call there must not file it a + * second time. A PostToolUse row is the call's completion, not a second report. + */ +function recordSelfReportCall( + canonicalEventType: string, + cli: IntegrationType, + parsed: Record, + session: SessionMetadata, + arrivedAt: number, + startTime: number, +): HookEventOutcome { + const durationMs = Math.round(performance.now() - startTime); + const writtenAt = Date.now(); + const toolCallId = toolCallIdOf(parsed); + // Only the PreToolUse row carries the report: the collector emits one + // `self_report` event per row that has it, and a call that also raises a + // PermissionRequest (or completes with a PostToolUse) is still one report. + const isReportRow = canonicalEventType === "PreToolUse"; + const hookRecords = !SELF_REPORT_SERVER_RECORDS.includes(cli); + try { + persistHookActivity({ + timestamp: writtenAt, + startedAt: Math.min(arrivedAt, writtenAt), + ...(toolCallId ? { toolCallId } : {}), + eventType: canonicalEventType, + integration: cli, + toolName: (parsed.tool_name as string) ?? null, + policyName: null, + matchedPolicies: [], + decision: "allow", + reason: null, + durationMs, + sessionId: session.sessionId, + transcriptPath: session.transcriptPath, + cwd: session.cwd, + permissionMode: session.permissionMode, + hookEventName: session.hookEventName, + ...(isReportRow && hookRecords ? { selfReport: { ...selfReportArgs(parsed.tool_input), source: "mcp" as const } } : {}), + }); + } catch { + hookLogWarn("activity persistence failed"); + } + hookLogInfo(`event=${canonicalEventType} cli=${cli} self-report allowed duration=${durationMs}ms`); + return { + exitCode: 0, + stdout: "", + stderr: "", + evaluation: { + decision: "allow", + policyName: null, + policyNames: [], + reason: null, + matchedPolicies: [], + durationMs, + toolName: (parsed.tool_name as string) ?? null, + }, + }; +} + /** * The core hook-evaluation logic, decoupled from process stdin/stdout so it * can be called repeatedly inside a long-lived process (the daemon's warm @@ -746,6 +812,23 @@ export async function evaluateHookEvent( rawHookEventName: eventType, cli, }; + + // Self Reports: the agent telling FailproofAI it is stuck. Answered HERE, + // ahead of the fail-closed branch, the session pause, every policy layer + // (builtin, custom, Cloud, pack) and Jev, so nothing can block, rewrite or + // delay a report — in the study our own `.env` policy blocked one. The + // allow is the same empty answer the evaluator gives every integration + // when no policy decides. PostToolUse for the tool is recorded, never + // evaluated; any other event for it takes the ordinary path. + if ( + isSelfReportToolName(parsed.tool_name) && + (canonicalEventType === "PreToolUse" || + canonicalEventType === "PermissionRequest" || + canonicalEventType === "PostToolUse") + ) { + return recordSelfReportCall(canonicalEventType, cli, parsed, session, arrivedAt, startTime); + } + const runtimeAgent = readRuntimeAgentIdentity( cli, opts?.agentSettingsPath ?? runtimeAgentSettingsPath(cli, session.cwd), ); diff --git a/src/hooks/hook-activity-store.ts b/src/hooks/hook-activity-store.ts index 4a15480ab..ed6dc8dc0 100644 --- a/src/hooks/hook-activity-store.ts +++ b/src/hooks/hook-activity-store.ts @@ -181,6 +181,14 @@ export interface HookActivityEntry { decision: "deny" | "instruct"; reason: string | null; }>; + /** + * Set only on a call to the Self Reports tool (`mcp__failproofai__report` and + * its per-agent spellings): what the agent reported. Such a row was allowed + * before any policy ran and was never evaluated, so its decision is always + * `allow` and it names no policy. The collector turns it into a + * `self_report` event. `detail` is at most 2000 characters. + */ + selfReport?: { category: string; detail: string; source: "mcp" }; } export interface HookActivityFilters { @@ -250,7 +258,7 @@ export function persistHookActivity(input: HookActivityEntry): void { // machine by the collector, and a fallback reason is the one field that can // carry free text (see jev-activity.ts). A row with no Jev fields is written // exactly as given. - const entry = sanitizeJevActivity(input); + const entry = sanitizeSelfReportActivity(sanitizeJevActivity(input)); ensureDir(); acquireLock(); try { @@ -275,6 +283,28 @@ export function persistHookActivity(input: HookActivityEntry): void { } } +/** + * Keep `selfReport` only in its declared shape: two strings of at most 2000 + * characters and `source: "mcp"`. Like the Jev fields it is shipped off the + * machine by the collector, so it is checked at this one door. + */ +function sanitizeSelfReportActivity(entry: HookActivityEntry): HookActivityEntry { + if (entry.selfReport === undefined) return entry; + const sr = entry.selfReport as unknown; + const out = { ...entry }; + if (!sr || typeof sr !== "object" || Array.isArray(sr)) { + delete out.selfReport; + return out; + } + const rec = sr as Record; + out.selfReport = { + category: typeof rec.category === "string" ? rec.category.slice(0, 2000) : "", + detail: typeof rec.detail === "string" ? rec.detail.slice(0, 2000) : "", + source: "mcp", + }; + return out; +} + function rotate(currentPath: string, countPath: string): void { const archiveName = `page-${Date.now()}-${rotateSeq++}.jsonl`; const archivePath = join(storeDirValue(), archiveName); diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts new file mode 100644 index 000000000..a8fd992a2 --- /dev/null +++ b/src/hooks/self-report-cli.ts @@ -0,0 +1,361 @@ +/** + * `failproofai self-report status | enable | disable | test`. + * + * `sync` is another part's (it registers the MCP server in every agent); this + * module only calls it, as the subprocess `failproofai self-report sync + * --quiet` that contract §6 defines, so the two halves meet at a command line + * rather than at a function name. + * + * Returns lines and an exit code like the other `*-cli.ts` modules; bin prints + * them. + */ +import { spawn } from "node:child_process"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { customAgentsEventsDir, hookActivityDir } from "./fp-home"; +import { + SELF_REPORT_DEFAULT_CATEGORIES, + SELF_REPORT_MCP_TOOL_NAME, + SELF_REPORT_RESULT_TEXT, + SELF_REPORT_SERVER_RECORDS, + readEffectiveSelfReport, + readLocalSelfReportConfig, + selfReportCloudManaged, + selfReportSettingsFile, + validateSelfReportCategories, + validateSelfReportGuidance, + writeEffectiveSelfReport, + writeLocalSelfReportConfig, + type SelfReportCategory, +} from "./self-report"; +import { INTEGRATION_TYPES } from "./types"; + +export interface SelfReportCliResult { + exitCode: number; + lines: string[]; +} + +export interface SelfReportCliDeps { + /** argv prefix that runs this CLI: `[node, dist/cli.mjs]`. */ + cliCommand?: string[]; + /** Health probe override (tests). */ + probeEndpoint?: (url: string, port: number) => Promise; + /** Skip the agent sync after enable/disable (tests). */ + skipSync?: boolean; + cwd?: string; +} + +const SELF_REPORT_CLOUD_REFUSAL = [ + "This machine is managed by FailproofAI Cloud, so Self Reports is set there.", + "Turn it on or off in the dashboard: Settings > Self Reports.", +]; + +function selfReportCliCommand(deps: SelfReportCliDeps): string[] { + return deps.cliCommand ?? [process.execPath, process.argv[1]]; +} + +/** Run the CLI as a child, feeding `stdin`; resolves with its output. */ +function selfReportRunChild( + argv: string[], + stdin: string, + timeoutMs: number, + cwd?: string, +): Promise<{ code: number | null; stdout: string; stderr: string }> { + return new Promise((resolveRun) => { + const [cmd, ...rest] = argv; + const child = spawn(cmd, rest, { cwd, stdio: ["pipe", "pipe", "pipe"], env: process.env }); + let stdout = ""; + let stderr = ""; + const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs); + child.stdout.on("data", (b: Buffer) => (stdout += b.toString("utf8"))); + child.stderr.on("data", (b: Buffer) => (stderr += b.toString("utf8"))); + child.on("error", (err) => { + clearTimeout(timer); + resolveRun({ code: null, stdout, stderr: stderr + String(err) }); + }); + child.on("close", (code) => { + clearTimeout(timer); + resolveRun({ code, stdout, stderr }); + }); + child.stdin.end(stdin); + }); +} + +/** POST a JSON-RPC ping to the daemon's MCP endpoint, with the Host it requires. */ +async function selfReportProbe(url: string): Promise { + try { + const res = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json", accept: "application/json, text/event-stream" }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }), + signal: AbortSignal.timeout(1500), + }); + return res.ok; + } catch { + return false; + } +} + +/** Per-agent registration, from the installer part once it is merged. */ +async function selfReportRegistrationLines(): Promise { + // TODO(merge): import "./self-report-install" statically once it exists. A + // computed specifier keeps the bundler from failing on a module this branch + // does not have yet. + const spec = "./self-report-install"; + try { + const mod = (await import(/* @vite-ignore */ spec)) as Record; + const fn = mod.selfReportRegistrationStatus; + if (typeof fn !== "function") return ["Agents: registration state not available in this build"]; + const rows = (await (fn as () => unknown)()) as Array<{ integration: string; state: string; transport?: string }>; + if (!Array.isArray(rows) || rows.length === 0) return ["Agents: none with failproofai hooks"]; + return [ + "Agents:", + ...rows.map((r) => ` ${String(r.integration).padEnd(12)} ${r.state}${r.transport ? ` (${r.transport})` : ""}`), + ]; + } catch { + return ["Agents: registration state not available in this build"]; + } +} + +async function selfReportStatus(deps: SelfReportCliDeps): Promise { + const settings = readEffectiveSelfReport(); + const cloud = await selfReportCloudManaged(); + const lines: string[] = []; + if (!settings) { + lines.push("Self Reports: off (no settings file)"); + lines.push(`Settings: ${selfReportSettingsFile()}`); + lines.push(cloud ? "Managed by: FailproofAI Cloud" : "Turn on: `failproofai self-report enable`"); + return { exitCode: 0, lines }; + } + lines.push(`Self Reports: ${settings.enabled ? "on" : "off"}`); + lines.push(`Source: ${settings.source === "cloud" ? "FailproofAI Cloud" : "this machine (config.json)"}`); + lines.push(`Settings: ${selfReportSettingsFile()}`); + if (settings.updatedAt) lines.push(`Updated: ${settings.updatedAt}`); + lines.push(`Categories: ${settings.categories.map((c) => c.name).join(", ")}`); + if (settings.guidance) lines.push(`Guidance: ${settings.guidance.length > 60 ? `${settings.guidance.slice(0, 57)}...` : settings.guidance}`); + const probe = deps.probeEndpoint ?? ((url: string) => selfReportProbe(url)); + const healthy = await probe(settings.mcp.url, settings.mcp.port); + lines.push(`Endpoint: ${settings.mcp.url} ${healthy ? "(answering)" : "(not answering; stdio `failproofai mcp` still works)"}`); + lines.push(...(await selfReportRegistrationLines())); + return { exitCode: 0, lines }; +} + +/** `failproofai self-report sync --quiet`, if this build has it. */ +async function selfReportSync(deps: SelfReportCliDeps): Promise { + if (deps.skipSync) return []; + const run = await selfReportRunChild([...selfReportCliCommand(deps), "self-report", "sync", "--quiet"], "", 60_000, deps.cwd); + if (run.code === 0) return ["Agents updated."]; + if (run.code === SELF_REPORT_SYNC_UNAVAILABLE) { + return ["Agent configs were not changed: this build cannot register the MCP server yet."]; + } + return [ + "▲ Could not update your agents' MCP settings. Run `failproofai self-report sync` to see why.", + ]; +} + +/** Exit code `self-report sync` returns in a build without the installer part. */ +export const SELF_REPORT_SYNC_UNAVAILABLE = 3; + +function selfReportFlag(args: string[], name: string): { value?: string; error?: string } { + const i = args.indexOf(name); + if (i < 0) return {}; + const v = args[i + 1]; + if (v === undefined || v.startsWith("--")) return { error: `Missing value after ${name}.` }; + return { value: v }; +} + +async function selfReportEnable(args: string[], deps: SelfReportCliDeps): Promise { + const known = new Set(["--categories-file", "--guidance"]); + const unknown = args.find((a, i) => a.startsWith("-") && !known.has(a) && !known.has(args[i - 1])); + if (unknown) return { exitCode: 1, lines: [`Unexpected argument: ${unknown}.`] }; + const stray = args.find((a, i) => !a.startsWith("-") && !known.has(args[i - 1])); + if (stray) return { exitCode: 1, lines: [`Unexpected argument: ${stray}.`] }; + if (await selfReportCloudManaged()) return { exitCode: 1, lines: SELF_REPORT_CLOUD_REFUSAL }; + + const file = selfReportFlag(args, "--categories-file"); + const guid = selfReportFlag(args, "--guidance"); + if (file.error) return { exitCode: 1, lines: [file.error] }; + if (guid.error) return { exitCode: 1, lines: [guid.error] }; + + const previous = await readLocalSelfReportConfig(); + let categories: SelfReportCategory[] | undefined = previous?.categories; + if (file.value) { + let parsed: unknown; + try { + parsed = JSON.parse(readFileSync(file.value, "utf8")); + } catch (err) { + return { exitCode: 1, lines: [`Could not read ${file.value}: ${err instanceof Error ? err.message : String(err)}`] }; + } + // A bare list, or `{ "categories": [...] }` (the shape of the org setting). + const list = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record).categories : parsed; + const checked = validateSelfReportCategories(list); + if (!checked.ok) return { exitCode: 1, lines: [`${file.value}: ${checked.error}`] }; + categories = checked.value; + } + let guidance: string | undefined = previous?.guidance; + if (guid.value !== undefined) { + const checked = validateSelfReportGuidance(guid.value); + if (!checked.ok) return { exitCode: 1, lines: [checked.error] }; + guidance = checked.value ?? undefined; + } + + await writeLocalSelfReportConfig({ enabled: true, categories, guidance }); + const written = writeEffectiveSelfReport({ enabled: true, categories, guidance }); + const lines = [ + "✓ Self Reports is on.", + ` Categories: ${written.categories.map((c) => c.name).join(", ")}${categories ? "" : " (defaults)"}`, + ` Settings: ${selfReportSettingsFile()}`, + ...(await selfReportSync(deps)).map((l) => (l.startsWith("▲") ? l : ` ${l}`)), + ]; + return { exitCode: 0, lines }; +} + +async function selfReportDisable(args: string[], deps: SelfReportCliDeps): Promise { + if (args.length > 0) return { exitCode: 1, lines: [`Unexpected argument: ${args[0]}.`] }; + if (await selfReportCloudManaged()) return { exitCode: 1, lines: SELF_REPORT_CLOUD_REFUSAL }; + const previous = await readLocalSelfReportConfig(); + // The category list and guidance are kept, so turning it back on restores them. + await writeLocalSelfReportConfig({ enabled: false, categories: previous?.categories, guidance: previous?.guidance }); + writeEffectiveSelfReport({ enabled: false, categories: previous?.categories, guidance: previous?.guidance }); + return { + exitCode: 0, + lines: ["✓ Self Reports is off.", ...(await selfReportSync(deps)).map((l) => (l.startsWith("▲") ? l : ` ${l}`))], + }; +} + +const SELF_REPORT_TEST_DETAIL = "failproofai self-report test: this is a test report, not a real problem."; + +async function selfReportTest(args: string[], deps: SelfReportCliDeps): Promise { + const agentFlag = selfReportFlag(args, "--agent"); + if (agentFlag.error || !agentFlag.value) { + return { exitCode: 1, lines: ["Missing --agent .", `Agents: ${INTEGRATION_TYPES.join(", ")}`] }; + } + const agent = agentFlag.value; + if (!(INTEGRATION_TYPES as readonly string[]).includes(agent)) { + return { exitCode: 1, lines: [`Not an agent: ${agent}.`, `Agents: ${INTEGRATION_TYPES.join(", ")}`] }; + } + const settings = readEffectiveSelfReport(); + if (!settings?.enabled) { + return { exitCode: 1, lines: ["Self Reports is off, so there is nothing to test.", "Turn it on with `failproofai self-report enable`."] }; + } + const category = settings.categories[0]?.name ?? SELF_REPORT_DEFAULT_CATEGORIES[0].name; + const cwd = deps.cwd ?? process.cwd(); + const cli = selfReportCliCommand(deps); + + if (SELF_REPORT_SERVER_RECORDS.includes(agent)) { + // This agent's hooks do not see MCP calls: the MCP server records. Drive + // the stdio server exactly as the agent would. + const dir = customAgentsEventsDir(); + const before = new Set(selfReportListDir(dir)); + const stdin = [ + { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "failproofai-self-report-test", version: "1" } } }, + { jsonrpc: "2.0", method: "notifications/initialized" }, + { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "report", arguments: { category, detail: SELF_REPORT_TEST_DETAIL } } }, + ] + .map((m) => JSON.stringify(m)) + .join("\n"); + const run = await selfReportRunChild([...cli, "mcp", "--agent", agent], `${stdin}\n`, 20_000, cwd); + const answered = run.stdout.includes(SELF_REPORT_RESULT_TEXT); + const landed = selfReportListDir(dir).filter((f) => !before.has(f) && f.endsWith(".jsonl")); + const hit = landed.find((f) => { + try { + return readFileSync(join(dir, f), "utf8").includes(SELF_REPORT_TEST_DETAIL); + } catch { + return false; + } + }); + if (!answered || !hit) { + return { + exitCode: 1, + lines: [ + `✕ The test report for ${agent} did not land.`, + ` MCP server ${answered ? "answered Recorded." : "did not answer"}${run.stderr.trim() ? `: ${run.stderr.trim().split("\n").pop()}` : ""}`, + ], + }; + } + // Possibly consumed by a running collector between write and read; the + // name is what we report. + return { + exitCode: 0, + lines: [ + `✓ Test report from ${agent} recorded by the MCP server.`, + ` Event file: ${join(dir, hit)}`, + " The collector uploads it to FailproofAI Cloud when this machine is connected.", + ], + }; + } + + // Hook-recorded agent: send the PreToolUse hook the agent would send, through + // the same `--hook` entry point (and so the daemon, when it is configured). + const sessionId = `failproofai-self-report-test-${Date.now()}`; + const payload = { + session_id: sessionId, + hook_event_name: "PreToolUse", + tool_name: SELF_REPORT_MCP_TOOL_NAME, + tool_input: { category, detail: SELF_REPORT_TEST_DETAIL }, + cwd, + }; + const run = await selfReportRunChild([...cli, "--hook", "PreToolUse", "--cli", agent], JSON.stringify(payload), 30_000, cwd); + const file = join(hookActivityDir(), "current.jsonl"); + let row: Record | undefined; + try { + row = readFileSync(file, "utf8") + .split("\n") + .filter((l) => l.includes(sessionId)) + .map((l) => JSON.parse(l) as Record) + .pop(); + } catch { + row = undefined; + } + if (run.code !== 0 || !row || !row.selfReport || row.decision !== "allow") { + return { + exitCode: 1, + lines: [ + `✕ The test report for ${agent} did not land.`, + ` Hook exit code: ${run.code ?? "none"}${row ? `, decision: ${String(row.decision)}` : ", no activity row"}`, + ...(run.stderr.trim() ? [` ${run.stderr.trim().split("\n").pop()}`] : []), + ], + }; + } + return { + exitCode: 0, + lines: [ + `✓ Test report from ${agent} allowed and recorded by the hook.`, + ` Activity row: ${file} (session ${sessionId})`, + " The collector uploads it to FailproofAI Cloud as a self_report event when this machine is connected.", + ], + }; +} + +function selfReportListDir(dir: string): string[] { + try { + return readdirSync(dir); + } catch { + return []; + } +} + +export async function runSelfReportCommand(args: string[], deps: SelfReportCliDeps = {}): Promise { + const [verb, ...rest] = args; + try { + switch (verb) { + case "status": + if (rest.length > 0) return { exitCode: 1, lines: [`Unexpected argument: ${rest[0]}.`] }; + return await selfReportStatus(deps); + case "enable": + return await selfReportEnable(rest, deps); + case "disable": + return await selfReportDisable(rest, deps); + case "test": + return await selfReportTest(rest, deps); + case "sync": + // TODO(merge): the installer part implements `sync` in bin; this is + // only reached in a build without it. + return { exitCode: SELF_REPORT_SYNC_UNAVAILABLE, lines: ["`self-report sync` is not available in this build."] }; + default: + return { exitCode: 1, lines: [verb ? `Unknown self-report command: ${verb}.` : "Missing self-report command.", "Use status, enable, disable or test."] }; + } + } catch (err) { + return { exitCode: 1, lines: [`✕ ${err instanceof Error ? err.message : String(err)}`] }; + } +} diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts new file mode 100644 index 000000000..4586f0efd --- /dev/null +++ b/src/hooks/self-report-mcp.ts @@ -0,0 +1,325 @@ +/** + * `failproofai mcp [--agent ]`: the Self Reports MCP server over + * stdio (newline-delimited JSON-RPC 2.0). + * + * The same server the daemon serves over HTTP, for agents that only speak stdio + * MCP and for environments with no reachable daemon (containers, CI). It needs + * no daemon: it reads `self-report.json` on every request and writes its + * fallback records straight into the custom-agents spool. + * + * Methods: `initialize`, `ping`, `tools/list` (the report tool, or nothing + * while the feature is off), `tools/call` (always answers `Recorded.`). + * + * Recording (contract §8): an agent whose hooks see MCP calls (Claude Code, + * Codex, Cursor) is recorded by its PreToolUse hook, so this server writes + * nothing for it. For an agent in `SELF_REPORT_SERVER_RECORDS` the server + * appends one `self_report` event itself, attributed to the newest session of + * that agent in this working directory seen by the hooks in the last 6 hours. + * + * Nothing but JSON-RPC goes to stdout: a stray byte there corrupts the agent's + * MCP stream. Diagnostics go to stderr. + * + * Top-level names are prefixed for the same bundle reason as self-report.ts. + */ +import { closeSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeSync, constants as fsConstants } from "node:fs"; +import { join } from "node:path"; +import { createInterface } from "node:readline"; +import type { Readable, Writable } from "node:stream"; +import { version as selfReportCliVersion } from "../../package.json"; +import { customAgentsEventsDir, hookActivityDir } from "./fp-home"; +import { + SELF_REPORT_RESULT_TEXT, + SELF_REPORT_SERVER_NAME, + SELF_REPORT_SERVER_RECORDS, + SELF_REPORT_TOOL_NAME, + describeSelfReportTool, + readEnabledSelfReport, + selfReportArgs, + selfReportInputSchema, +} from "./self-report"; + +/** How far back a hook-activity session may be and still own a report. */ +export const SELF_REPORT_SESSION_WINDOW_MS = 6 * 60 * 60 * 1000; +const SELF_REPORT_DEFAULT_PROTOCOL = "2025-06-18"; + +let selfReportBatchSeq = 0; + +export interface SelfReportMcpOptions { + /** The integration this server was registered for (`--agent`). */ + agent?: string; + /** Working directory used for session attribution; defaults to process.cwd(). */ + cwd?: string; + input?: Readable; + output?: Writable; + /** Clock override for tests. */ + now?: () => number; +} + +/** The tool list the server advertises right now. */ +export function selfReportToolList(): Array> { + const settings = readEnabledSelfReport(); + if (!settings) return []; + return [ + { + name: SELF_REPORT_TOOL_NAME, + description: describeSelfReportTool(settings.categories, settings.guidance), + inputSchema: selfReportInputSchema(settings.categories), + }, + ]; +} + +// ── Session attribution ───────────────────────────────────────────────────── + +/** + * Newest session id for `integration` in `cwd` seen by the hooks within the + * window, or null. Reads `current.jsonl` and, because it holds at most one + * page (25 rows) and may have just rotated, the newest archived page too. + */ +export function selfReportFindSession(integration: string, cwd: string, now: number = Date.now()): string | null { + const dir = hookActivityDir(); + const files: string[] = [join(dir, "current.jsonl")]; + try { + const pages = readdirSync(dir) + .filter((f) => f.startsWith("page-") && f.endsWith(".jsonl")) + .map((f) => ({ f, m: selfReportMtime(join(dir, f)) })) + .sort((a, b) => b.m - a.m); + if (pages[0]) files.push(join(dir, pages[0].f)); + } catch { + // No activity directory: nothing to attribute to. + } + let best: { ts: number; id: string } | null = null; + for (const file of files) { + let text: string; + try { + text = readFileSync(file, "utf8"); + } catch { + continue; + } + for (const line of text.split("\n")) { + if (!line.trim()) continue; + let row: Record; + try { + row = JSON.parse(line) as Record; + } catch { + continue; + } + const ts = typeof row.timestamp === "number" ? row.timestamp : NaN; + if ( + row.integration === integration && + row.cwd === cwd && + typeof row.sessionId === "string" && + row.sessionId && + Number.isFinite(ts) && + now - ts <= SELF_REPORT_SESSION_WINDOW_MS && + ts - now <= 60_000 && + (!best || ts > best.ts) + ) { + best = { ts, id: row.sessionId }; + } + } + } + return best ? best.id : null; +} + +function selfReportMtime(path: string): number { + try { + return statSync(path).mtimeMs; + } catch { + return 0; + } +} + +/** + * The agent id the collector files a hook event under (`agent_id` in + * crates/fpai-collect/src/sources/hooks/transform.rs): `-`, each part reduced to `[A-Za-z0-9._-]`, dashes collapsed, 48 + * characters. A report must land under the same agent as the session's hooks. + */ +export function selfReportAgentId(integration: string, cwd: string | undefined): string { + const clean = (s: string): string => + [...s] + .map((c) => (/[A-Za-z0-9._]/.test(c) ? c : "-")) + .join("") + .split("-") + .filter((p) => p !== "") + .join("-") + .slice(0, 48); + const base = clean(integration || "failproofai"); + const last = cwd?.replace(/\/+$/, "").split("/").filter((p) => p !== "").pop(); + const project = last ? clean(last) : ""; + return project ? `${base}-${project}` : base; +} + +/** `environment` as the collector stamps it: config.json's collector.environment, else "local". */ +async function selfReportEnvironment(): Promise { + try { + const { readConfig } = await import("./fp-config"); + return readConfig().collector.environment || "local"; + } catch { + return "local"; + } +} + +// ── The event file (SDK writer format) ────────────────────────────────────── + +export interface SelfReportEventInput { + integration: string; + category: string; + detail: string; + cwd: string; + now?: number; + /** Overrides session attribution (the `self-report test` command). */ + sessionId?: string; +} + +/** + * Write one `self_report` event as its own batch in the custom-agents spool, + * exactly as the SDK writers publish (`event---.jsonl`, written + * as `.tmp` with O_EXCL and 0600, fsynced, renamed; directory 0700). Returns + * the published path and the event. + */ +export async function writeSelfReportEvent(input: SelfReportEventInput): Promise<{ path: string; event: Record }> { + const now = input.now ?? Date.now(); + const sessionId = input.sessionId ?? selfReportFindSession(input.integration, input.cwd, now) ?? "unattributed"; + const event: Record = { + timestamp: new Date(now).toISOString(), + session_id: sessionId, + agent_id: selfReportAgentId(input.integration, input.cwd), + type: "self_report", + environment: await selfReportEnvironment(), + category: input.category, + detail: input.detail, + source: "mcp", + integration: input.integration, + }; + const dir = customAgentsEventsDir(); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + const stamp = new Date(now).toISOString().replace(/[:.]/g, "-"); + const stem = `event-${stamp}-${process.pid}-${selfReportBatchSeq++}`; + const tmp = join(dir, `${stem}.tmp`); + const finalPath = join(dir, `${stem}.jsonl`); + try { + const fd = openSync(tmp, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL, 0o600); + try { + writeSync(fd, `${JSON.stringify(event)}\n`); + fsyncSync(fd); + } finally { + closeSync(fd); + } + renameSync(tmp, finalPath); + } catch (err) { + rmSync(tmp, { force: true }); + throw err; + } + return { path: finalPath, event }; +} + +// ── JSON-RPC ──────────────────────────────────────────────────────────────── + +type SelfReportRpcResponse = Record | null; + +/** + * Answer one JSON-RPC message. Returns null for a notification (no reply). + * Exported so tests (and the daemon parity check) can drive it without a pipe. + */ +export async function handleSelfReportRpc( + message: unknown, + opts: { agent?: string; cwd?: string; now?: () => number } = {}, +): Promise { + if (!message || typeof message !== "object" || Array.isArray(message)) { + return { jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid Request" } }; + } + const req = message as { id?: unknown; method?: unknown; params?: unknown }; + const hasId = req.id !== undefined && req.id !== null; + const id = hasId ? req.id : null; + const method = typeof req.method === "string" ? req.method : ""; + const params = req.params && typeof req.params === "object" ? (req.params as Record) : {}; + const ok = (result: unknown) => ({ jsonrpc: "2.0", id, result }); + + if (!hasId) return null; // notifications/initialized and friends + + switch (method) { + case "initialize": + return ok({ + protocolVersion: typeof params.protocolVersion === "string" ? params.protocolVersion : SELF_REPORT_DEFAULT_PROTOCOL, + capabilities: { tools: {} }, + serverInfo: { name: SELF_REPORT_SERVER_NAME, version: selfReportCliVersion }, + }); + case "ping": + return ok({}); + case "tools/list": + return ok({ tools: selfReportToolList() }); + case "tools/call": { + if (params.name !== SELF_REPORT_TOOL_NAME) { + return ok({ content: [{ type: "text", text: `Unknown tool: ${String(params.name)}` }], isError: true }); + } + const agent = opts.agent; + if (agent && SELF_REPORT_SERVER_RECORDS.includes(agent) && readEnabledSelfReport()) { + const { category, detail } = selfReportArgs(params.arguments ?? {}); + try { + await writeSelfReportEvent({ + integration: agent, + category, + detail, + cwd: opts.cwd ?? process.cwd(), + now: opts.now?.(), + }); + } catch (err) { + // The agent still hears "Recorded.": a report changes no decision, + // and an error here would only make it retry. + process.stderr.write( + `[failproofai mcp] could not record a self report: ${err instanceof Error ? err.message : String(err)}\n`, + ); + } + } + return ok({ content: [{ type: "text", text: SELF_REPORT_RESULT_TEXT }] }); + } + default: + return { jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } }; + } +} + +/** + * Run the server until stdin closes. Requests are answered in arrival order. + * Resolves when the input ends and every reply has been written. + */ +export function runSelfReportMcpServer(opts: SelfReportMcpOptions = {}): Promise { + const input = opts.input ?? process.stdin; + const output = opts.output ?? process.stdout; + const handlerOpts = { agent: opts.agent, cwd: opts.cwd, now: opts.now }; + let chain: Promise = Promise.resolve(); + const send = (msg: unknown) => { + output.write(`${JSON.stringify(msg)}\n`); + }; + return new Promise((resolveRun) => { + const rl = createInterface({ input, crlfDelay: Infinity }); + rl.on("line", (line) => { + if (!line.trim()) return; + chain = chain.then(async () => { + let parsed: unknown; + try { + parsed = JSON.parse(line); + } catch { + send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }); + return; + } + try { + if (Array.isArray(parsed)) { + const replies = (await Promise.all(parsed.map((m) => handleSelfReportRpc(m, handlerOpts)))).filter( + (r) => r !== null, + ); + if (replies.length > 0) send(replies); + } else { + const reply = await handleSelfReportRpc(parsed, handlerOpts); + if (reply) send(reply); + } + } catch (err) { + process.stderr.write(`[failproofai mcp] ${err instanceof Error ? err.message : String(err)}\n`); + } + }); + }); + rl.on("close", () => { + void chain.then(() => resolveRun()); + }); + }); +} diff --git a/src/hooks/self-report-names.ts b/src/hooks/self-report-names.ts new file mode 100644 index 000000000..b337fb7ce --- /dev/null +++ b/src/hooks/self-report-names.ts @@ -0,0 +1,79 @@ +/** + * The Self Reports tool's names (contract §1), in a module that imports + * NOTHING. `tool-name-canonicalize.ts` needs `isSelfReportToolName` and is + * bundled ahead of the builtin policies; a module with imports placed there + * (self-report.ts pulls node:fs and lazily fp-config/safe-config-write) moves + * other modules ahead of builtin-policies.ts in the scope-hoisted CLI bundle + * and renames bindings inside the policy functions, which changes the audit + * cache's `engineVersion` and rescans every user's history at upgrade. Every + * name here is prefixed so it cannot collide with a local in a policy either. + * + * Re-exported from self-report.ts; import from there everywhere else. + */ + +/** MCP server name every installer registers. */ +export const SELF_REPORT_SERVER_NAME = "failproofai"; +/** The MCP tool's own name. */ +export const SELF_REPORT_TOOL_NAME = "report"; +/** How Claude Code and Codex spell it: `mcp____`. */ +export const SELF_REPORT_MCP_TOOL_NAME = "mcp__failproofai__report"; +/** The SDK tool's name. */ +export const SELF_REPORT_SDK_TOOL_NAME = "failproofai_report"; +/** Detail is truncated to this many characters (contract §3). */ +export const SELF_REPORT_DETAIL_MAX = 2000; +/** Default loopback port of the daemon's HTTP MCP server (contract §4, D5). */ +export const SELF_REPORT_DEFAULT_PORT = 4319; + +/** + * Every spelling of the report tool an agent's hook can deliver. Exact matches + * only: a prefix or substring match would let any tool whose name merely + * contains `failproofai` and `report` past every policy, and this name is the + * one thing that skips them all. + * + * - `mcp__failproofai__report`: Claude Code, Codex (and anything copying them). + * - `failproofai__report`: Goose's `__`. + * - `failproofai_report`: the SDK tool, and agents that join with one `_` + * (OpenCode, Copilot). + * - `failproofai.report`, `failproofai/report`, `failproofai:report`: dotted / + * slashed / coloned server-qualified forms other agents use. + * - `mcp_failproofai_report`, `mcp__failproofai_report`: single-underscore + * variants seen in agents that flatten MCP names. + * + * Cursor's preToolUse names MCP calls `MCP:` without the server, which + * cannot be told apart from another server's `report` tool, so it is not here. + */ +const SELF_REPORT_TOOL_SPELLINGS: ReadonlySet = new Set([ + SELF_REPORT_MCP_TOOL_NAME, + "failproofai__report", + SELF_REPORT_SDK_TOOL_NAME, + "failproofai.report", + "failproofai/report", + "failproofai:report", + "mcp_failproofai_report", + "mcp__failproofai_report", + "mcp:failproofai:report", + "mcp:failproofai/report", +]); + +/** True for the report tool under any agent's spelling of it (contract §1). */ +export function isSelfReportToolName(name: unknown): boolean { + return typeof name === "string" && SELF_REPORT_TOOL_SPELLINGS.has(name.toLowerCase()); +} + +/** + * Integrations whose hooks do not see MCP tool calls, so the MCP server itself + * records a report (contract §8). Claude Code, Codex and Cursor are recorded by + * the hook. Kept identical to the Rust list. + */ +export const SELF_REPORT_SERVER_RECORDS: readonly string[] = [ + "openclaw", + "pi", + "devin", + "hermes", + "goose", + "factory", + "antigravity", + "copilot", + "opencode", +]; + diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts new file mode 100644 index 000000000..17e885b3c --- /dev/null +++ b/src/hooks/self-report.ts @@ -0,0 +1,392 @@ +/** + * Self Reports: the `report` tool FailproofAI puts into every agent, so an + * agent that is stuck can say so. + * + * This module is the one TypeScript home for everything the feature shares: + * the default categories, the tool's description and input schema (identical + * text in every implementation — the daemon, the stdio server and both SDKs + * build the same string), the recognised tool names, and the effective + * settings file `self-report.json` every reader goes through. + * + * Every top-level name here starts with `selfReport` / `SELF_REPORT`, on + * purpose. The CLI ships as one scope-hoisted bundle, and a new top-level name + * that matches a local inside a builtin policy makes the bundler rename that + * local — which changes the function source the audit cache keys on (see the + * note on `screenKit` in tui.ts). The short names the brief asks for + * (`describe`, `inputSchema`, `DEFAULT_CATEGORIES`) are export aliases only. + * + * Only the name/description/settings-read half is used on the hook path, and it + * imports nothing beyond `node:fs` and the home resolver. The local-config and + * Cloud-enrolment helpers load their modules lazily. + */ +import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { randomBytes } from "node:crypto"; +import { failproofaiHome } from "./fp-home"; + +export { + SELF_REPORT_SERVER_NAME, + SELF_REPORT_TOOL_NAME, + SELF_REPORT_MCP_TOOL_NAME, + SELF_REPORT_SDK_TOOL_NAME, + SELF_REPORT_DETAIL_MAX, + SELF_REPORT_DEFAULT_PORT, + SELF_REPORT_SERVER_RECORDS, + isSelfReportToolName, +} from "./self-report-names"; +import { SELF_REPORT_DETAIL_MAX, SELF_REPORT_DEFAULT_PORT } from "./self-report-names"; + +// ── Categories (contract §2) ──────────────────────────────────────────────── + +export interface SelfReportCategory { + name: string; + description: string; +} + +const SELF_REPORT_DEFAULT_CATEGORIES: readonly SelfReportCategory[] = Object.freeze([ + { name: "looping", description: "You keep repeating the same or circular steps without making progress." }, + { + name: "cannot_do_request", + description: + "The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating.", + }, + { + name: "invalid_tool_or_credential", + description: "A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected.", + }, + { + name: "missing_context", + description: + "Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions.", + }, + { + name: "repeated_tool_failure", + description: + "A command or tool failed on several distinct attempts and is blocking you. A single error is not enough.", + }, + { + name: "task_failure", + description: "You genuinely tried and could not complete the task. Not for refusals or policy blocks.", + }, +].map((c) => Object.freeze(c))); + +export { SELF_REPORT_DEFAULT_CATEGORIES, SELF_REPORT_DEFAULT_CATEGORIES as DEFAULT_CATEGORIES }; + +const SELF_REPORT_NAME_RE = /^[a-z][a-z0-9_]{0,63}$/; +const SELF_REPORT_MAX_CATEGORIES = 32; +const SELF_REPORT_MAX_DESCRIPTION = 500; +export const SELF_REPORT_MAX_GUIDANCE = 2000; + +export type SelfReportValidation = { ok: true; value: T } | { ok: false; error: string }; + +/** + * Check an org's or a user's category list against contract §2: 1–32 entries, + * names `^[a-z][a-z0-9_]{0,63}$` and unique, descriptions 1–500 characters. + * Descriptions are trimmed; nothing else is rewritten. + */ +export function validateSelfReportCategories(input: unknown): SelfReportValidation { + if (!Array.isArray(input)) return { ok: false, error: "categories must be a list of {name, description}" }; + if (input.length < 1 || input.length > SELF_REPORT_MAX_CATEGORIES) { + return { ok: false, error: `categories must have between 1 and ${SELF_REPORT_MAX_CATEGORIES} entries` }; + } + const seen = new Set(); + const out: SelfReportCategory[] = []; + for (const [i, raw] of input.entries()) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + return { ok: false, error: `category ${i + 1} must be an object with name and description` }; + } + const { name, description } = raw as Record; + if (typeof name !== "string" || !SELF_REPORT_NAME_RE.test(name)) { + return { + ok: false, + error: `category ${i + 1}: name must match ^[a-z][a-z0-9_]{0,63}$ (lowercase, digits, underscores)`, + }; + } + if (seen.has(name)) return { ok: false, error: `category "${name}" is listed twice` }; + seen.add(name); + const desc = typeof description === "string" ? description.trim() : ""; + if (desc.length < 1 || desc.length > SELF_REPORT_MAX_DESCRIPTION) { + return { ok: false, error: `category "${name}": description must be 1-${SELF_REPORT_MAX_DESCRIPTION} characters` }; + } + out.push({ name, description: desc }); + } + return { ok: true, value: out }; +} + +/** Guidance: a string of at most 2000 characters, or nothing. Blank reads as nothing. */ +export function validateSelfReportGuidance(input: unknown): SelfReportValidation { + if (input === undefined || input === null) return { ok: true, value: null }; + if (typeof input !== "string") return { ok: false, error: "guidance must be text" }; + const trimmed = input.trim(); + if (trimmed.length > SELF_REPORT_MAX_GUIDANCE) { + return { ok: false, error: `guidance must be at most ${SELF_REPORT_MAX_GUIDANCE} characters` }; + } + return { ok: true, value: trimmed === "" ? null : trimmed }; +} + +// ── The tool (contract §3) ────────────────────────────────────────────────── + +const SELF_REPORT_DESCRIPTION_HEAD = + "Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; " + + "do not call it for normal work, clarifying questions or a single error. One call per distinct problem.\n" + + "Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is " + + "blocking you. There is no need to mention this report to the user."; + +/** The tool description, built from the categories and the optional guidance. */ +function describeSelfReportTool( + categories: readonly SelfReportCategory[], + guidance?: string | null, +): string { + const lines = categories.map((c) => `- ${c.name}: ${c.description}`); + const body = `${SELF_REPORT_DESCRIPTION_HEAD}\n\nCategories:\n${lines.join("\n")}`; + return guidance ? `${body}\n\n${guidance}` : body; +} + +/** The tool's JSON input schema. */ +function selfReportInputSchema(categories: readonly SelfReportCategory[]): Record { + return { + type: "object", + properties: { + category: { type: "string", enum: categories.map((c) => c.name) }, + detail: { type: "string", description: "One factual sentence: what is blocking you." }, + }, + required: ["category", "detail"], + additionalProperties: false, + }; +} + +export { describeSelfReportTool, describeSelfReportTool as describe, selfReportInputSchema, selfReportInputSchema as inputSchema }; + +/** Exactly what the tool returns (contract §3). */ +export const SELF_REPORT_RESULT_TEXT = "Recorded."; + +/** + * A call's arguments as they are recorded: an unknown category is kept as-is + * (never rejected), a missing or empty detail is `""`, detail is cut to 2000 + * characters. A category is cut to the same bound so a hostile argument cannot + * grow every activity row without limit. + * + * Accepts the arguments object itself, or a hook's `tool_input` that wraps it + * (`{arguments: {...}}`, `{args: {...}}`, or either as a JSON string), because + * agents differ in how they hand an MCP call to their hooks. + */ +export function selfReportArgs(input: unknown): { category: string; detail: string } { + let args: unknown = input; + if (typeof args === "string") args = selfReportParseJson(args); + if (args && typeof args === "object" && !Array.isArray(args)) { + const rec = args as Record; + if (rec.category === undefined && rec.detail === undefined) { + for (const key of ["arguments", "args", "input", "params"]) { + let inner = rec[key]; + if (typeof inner === "string") inner = selfReportParseJson(inner); + if (inner && typeof inner === "object" && !Array.isArray(inner)) { + args = inner; + break; + } + } + } + } + const rec = args && typeof args === "object" && !Array.isArray(args) ? (args as Record) : {}; + const cat = rec.category; + const det = rec.detail; + const category = cat === undefined || cat === null ? "" : typeof cat === "string" ? cat : JSON.stringify(cat); + const detail = det === undefined || det === null ? "" : typeof det === "string" ? det : JSON.stringify(det); + return { + category: category.slice(0, SELF_REPORT_DETAIL_MAX), + detail: detail.slice(0, SELF_REPORT_DETAIL_MAX), + }; +} + +function selfReportParseJson(text: string): unknown { + try { + return JSON.parse(text); + } catch { + return undefined; + } +} + +// ── The effective settings file (contract §4) ─────────────────────────────── + +export interface SelfReportEffective { + version: 1; + enabled: boolean; + source: "cloud" | "local"; + categories: SelfReportCategory[]; + guidance: string | null; + mcp: { port: number; url: string }; + updatedAt: string; +} + +/** `$FAILPROOFAI_HOME/self-report.json`. */ +export function selfReportSettingsFile(): string { + return join(failproofaiHome(), "self-report.json"); +} + +/** The port a local writer records: `FAILPROOFAI_SELF_REPORT_PORT`, else 4319. */ +export function selfReportPort(): number { + const raw = process.env.FAILPROOFAI_SELF_REPORT_PORT?.trim(); + if (raw && /^\d+$/.test(raw)) { + const n = Number(raw); + if (n > 0 && n < 65536) return n; + } + return SELF_REPORT_DEFAULT_PORT; +} + +export function selfReportMcpUrl(port: number): string { + return `http://127.0.0.1:${port}/mcp`; +} + +/** + * Read `self-report.json`. Missing, unparsable or not version 1 reads as + * `null`, which every caller treats as disabled. A file that says enabled but + * whose category list is unusable falls back to the defaults (contract §4: + * "never empty when enabled; defaults if none given"). + */ +export function readEffectiveSelfReport(path: string = selfReportSettingsFile()): SelfReportEffective | null { + let raw: unknown; + try { + raw = JSON.parse(readFileSync(path, "utf8")); + } catch { + return null; + } + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const rec = raw as Record; + if (rec.version !== 1) return null; + const cats = validateSelfReportCategories(rec.categories); + const guidance = validateSelfReportGuidance(rec.guidance); + const mcp = rec.mcp && typeof rec.mcp === "object" && !Array.isArray(rec.mcp) ? (rec.mcp as Record) : {}; + const port = + typeof mcp.port === "number" && Number.isInteger(mcp.port) && mcp.port > 0 && mcp.port < 65536 + ? mcp.port + : SELF_REPORT_DEFAULT_PORT; + return { + version: 1, + enabled: rec.enabled === true, + source: rec.source === "cloud" ? "cloud" : "local", + categories: cats.ok ? cats.value : SELF_REPORT_DEFAULT_CATEGORIES.map((c) => ({ ...c })), + guidance: guidance.ok ? guidance.value : null, + mcp: { port, url: typeof mcp.url === "string" && mcp.url ? mcp.url : selfReportMcpUrl(port) }, + updatedAt: typeof rec.updatedAt === "string" ? rec.updatedAt : "", + }; +} + +/** The settings only when the feature is on; `null` otherwise. */ +export function readEnabledSelfReport(path?: string): SelfReportEffective | null { + const s = readEffectiveSelfReport(path); + return s && s.enabled ? s : null; +} + +/** + * Write `self-report.json` atomically (tmp + fsync + rename), mode 0644. The + * non-Cloud writer; on a Cloud-managed machine the daemon owns this file. + * The mode is set explicitly rather than left to the umask: the SDKs read this + * file from agent processes that may run as another account. + */ +export function writeEffectiveSelfReport( + input: { enabled: boolean; categories?: readonly SelfReportCategory[] | null; guidance?: string | null }, + path: string = selfReportSettingsFile(), +): SelfReportEffective { + const port = selfReportPort(); + const value: SelfReportEffective = { + version: 1, + enabled: input.enabled, + source: "local", + categories: (input.categories && input.categories.length > 0 ? input.categories : SELF_REPORT_DEFAULT_CATEGORIES).map( + (c) => ({ name: c.name, description: c.description }), + ), + guidance: input.guidance ?? null, + mcp: { port, url: selfReportMcpUrl(port) }, + updatedAt: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"), + }; + const dir = dirname(path); + if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 }); + const tmp = join(dir, `.self-report.json.${process.pid}.${randomBytes(6).toString("hex")}.tmp`); + try { + const fd = openSync(tmp, "wx", 0o644); + try { + writeSync(fd, `${JSON.stringify(value, null, 2)}\n`); + fsyncSync(fd); + } finally { + closeSync(fd); + } + chmodSync(tmp, 0o644); + renameSync(tmp, path); + } catch (err) { + rmSync(tmp, { force: true }); + throw err; + } + return value; +} + +// ── Local config: `selfReport` in config.json (contract §4) ───────────────── + +export interface SelfReportLocalConfig { + enabled: boolean; + categories?: SelfReportCategory[]; + guidance?: string; +} + +/** The `selfReport` block of `~/.failproofai/config.json`, or `null` if absent. */ +export async function readLocalSelfReportConfig(): Promise { + const { readConfigRaw } = await import("./fp-config"); + const block = readConfigRaw().raw.selfReport; + if (!block || typeof block !== "object" || Array.isArray(block)) return null; + const rec = block as Record; + const cats = rec.categories === undefined || rec.categories === null ? null : validateSelfReportCategories(rec.categories); + const guidance = validateSelfReportGuidance(rec.guidance); + return { + enabled: rec.enabled === true, + ...(cats && cats.ok ? { categories: cats.value } : {}), + ...(guidance.ok && guidance.value ? { guidance: guidance.value } : {}), + }; +} + +/** + * Replace the `selfReport` block, keeping every other key in the file as it + * was (the same read-raw-then-write the OTEL settings use, so a key this build + * does not know survives). + */ +export async function writeLocalSelfReportConfig(block: SelfReportLocalConfig): Promise { + const [{ readConfigRaw }, { writeConfigFileAtomic }, { configFile }] = await Promise.all([ + import("./fp-config"), + import("./safe-config-write"), + import("./fp-home"), + ]); + const raw = { ...readConfigRaw().raw }; + raw.selfReport = { + enabled: block.enabled, + ...(block.categories ? { categories: block.categories } : {}), + ...(block.guidance ? { guidance: block.guidance } : {}), + }; + writeConfigFileAtomic(configFile(), `${JSON.stringify(raw, null, 2)}\n`, { backup: false }); +} + +// ── Cloud enrolment ───────────────────────────────────────────────────────── + +/** + * Whether the daemon takes this machine's settings from FailproofAI Cloud, in + * which case Cloud owns `self-report.json` and local enable/disable refuse. + * Mirrors the daemon's `Enrolment::resolve` (cloud_client.rs): the + * `FAILPROOFAI_CLOUD_URL` environment, or a stored cloud credential on a + * machine not switched back to open source (`mode.kind == "oss"`). + */ +export async function selfReportCloudManaged(): Promise { + if (process.env.FAILPROOFAI_CLOUD_URL?.trim()) return true; + try { + const { readCloudCredentials } = await import("./cloud-enrollment"); + if (!readCloudCredentials()) return false; + } catch { + return false; + } + try { + const { configFile } = await import("./fp-home"); + const raw: unknown = JSON.parse(readFileSync(configFile(), "utf8")); + const mode = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as { mode?: unknown }).mode : undefined; + if (mode && typeof mode === "object" && !Array.isArray(mode) && (mode as { kind?: unknown }).kind === "oss") { + return false; + } + } catch { + // Missing or unreadable config does not veto an enrolled machine (the daemon's rule). + } + return true; +} diff --git a/src/hooks/tool-name-canonicalize.ts b/src/hooks/tool-name-canonicalize.ts index b784d5d91..ac76bea26 100644 --- a/src/hooks/tool-name-canonicalize.ts +++ b/src/hooks/tool-name-canonicalize.ts @@ -6,6 +6,7 @@ * `src/audit/cli-adapters/*.ts` keeps the per-CLI maps in one place. */ import type { IntegrationType } from "./types"; +import { isSelfReportToolName, SELF_REPORT_MCP_TOOL_NAME } from "./self-report-names"; import { CODEX_TOOL_MAP, COPILOT_TOOL_MAP, @@ -37,6 +38,10 @@ export function canonicalizeToolName( cli: IntegrationType, ): string | undefined { if (!raw) return raw; + // The Self Reports tool, under whatever name this agent gives MCP tools, is + // filed under one name so the hook's short-circuit and the collector see it + // the same way on every agent. + if (isSelfReportToolName(raw)) return SELF_REPORT_MCP_TOOL_NAME; if (cli === "copilot") return COPILOT_TOOL_MAP[raw] ?? raw; if (cli === "cursor") return CURSOR_TOOL_MAP[raw] ?? raw; if (cli === "codex") return CODEX_TOOL_MAP[raw] ?? raw; From ddcdf779b3ca187558e97fbfd4b6cd8d8648d552 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 25 Nov 2026 21:31:01 +0530 Subject: [PATCH 04/54] [ts-sdk] Self Reports: self_report event, report tool helpers and framework tools Adds event.selfReport / selfReport(), the settings reader for $FAILPROOFAI_HOME/self-report.json, selfReportSpec / openaiTool / anthropicTool / handleToolCall / isSelfReportTool, and selfReportTool() on /ai, /langchain, /mastra and /llamaindex, with inert Edge versions. Co-Authored-By: Claude Opus 5.5 --- sdk/typescript/src/edge/ai.ts | 7 + sdk/typescript/src/edge/index.ts | 64 ++- sdk/typescript/src/edge/langchain.ts | 7 + sdk/typescript/src/edge/llamaindex.ts | 7 + sdk/typescript/src/edge/mastra.ts | 7 + sdk/typescript/src/edge/self-report-tool.ts | 55 ++ sdk/typescript/src/events.ts | 111 +++- sdk/typescript/src/index.ts | 28 +- sdk/typescript/src/integrations/ai.ts | 4 + sdk/typescript/src/integrations/langchain.ts | 4 + sdk/typescript/src/integrations/llamaindex.ts | 8 + sdk/typescript/src/integrations/mastra.ts | 4 + .../src/integrations/self-report-tools.ts | 264 ++++++++++ sdk/typescript/src/resolver.ts | 11 +- sdk/typescript/src/schema.ts | 34 ++ sdk/typescript/src/self-report-spec.ts | 231 ++++++++ sdk/typescript/src/self-report.ts | 169 ++++++ sdk/typescript/test/edge.test.ts | 13 +- sdk/typescript/test/self-report.test.ts | 498 ++++++++++++++++++ sdk/typescript/test/wire-format.test.ts | 1 + 20 files changed, 1518 insertions(+), 9 deletions(-) create mode 100644 sdk/typescript/src/edge/self-report-tool.ts create mode 100644 sdk/typescript/src/integrations/self-report-tools.ts create mode 100644 sdk/typescript/src/self-report-spec.ts create mode 100644 sdk/typescript/src/self-report.ts create mode 100644 sdk/typescript/test/self-report.test.ts diff --git a/sdk/typescript/src/edge/ai.ts b/sdk/typescript/src/edge/ai.ts index c8ab09cd3..f100231db 100644 --- a/sdk/typescript/src/edge/ai.ts +++ b/sdk/typescript/src/edge/ai.ts @@ -9,6 +9,7 @@ import { noopAdapter } from "./adapter.js"; import { notice } from "./notice.js"; +import { inertAiTool } from "./self-report-tool.js"; type AttributeValue = string | number | boolean | Array; @@ -114,3 +115,9 @@ export function wrapTools(tools: T): T { } export const adapter = noopAdapter("ai"); + +/** The Self Reports tool, answering `Recorded.` and recording nothing. */ +export function selfReportTool(...options: unknown[]): T { + void options; + return inertAiTool(); +} diff --git a/sdk/typescript/src/edge/index.ts b/sdk/typescript/src/edge/index.ts index ec508f60b..bc5639f57 100644 --- a/sdk/typescript/src/edge/index.ts +++ b/sdk/typescript/src/edge/index.ts @@ -36,9 +36,27 @@ import type { ToolCallFn, ToolCallOptions, } from "../scopes.js"; +import { + SELF_REPORT_RESULT, + buildSelfReportSpec, + defaultCategories, + isSelfReportTool, + toAnthropicTool, + toOpenAITool, + type AnthropicTool, + type OpenAITool, + type SelfReportSpec, +} from "../self-report-spec.js"; import { VERSION } from "../version.js"; import { notice } from "./notice.js"; +export { + DEFAULT_SELF_REPORT_CATEGORIES, + SELF_REPORT_RESULT, + SELF_REPORT_TOOL_NAME, + isSelfReportTool, +} from "../self-report-spec.js"; + export { VERSION as version }; export const DEFAULT_AGENT_ID = "main"; @@ -206,9 +224,10 @@ const EVENT_METHODS = [ "humanInput", "humanPause", "humanInterrupt", + "selfReport", ] as const; -/** The 15 event methods, each accepting its options and recording nothing. */ +/** The event methods, each accepting its options and recording nothing. */ export const event: EventNamespace = Object.freeze( Object.fromEntries(EVENT_METHODS.map((name) => [name, () => notice()])), ) as unknown as EventNamespace; @@ -245,3 +264,46 @@ export function availableFrameworks(): never[] { export function activeFrameworks(): never[] { return []; } + +// -- Self Reports: the same tool, recording nothing ---------------------------- +// +// No settings file can be read here, so the spec always carries the default +// categories. A report call still answers `Recorded.`: the model's loop must go +// on exactly as it would in Node. + +export function selfReportSettings(): { + enabled: false; + source: null; + categories: ReturnType; + guidance: null; + mcp: null; + updatedAt: null; +} { + return { enabled: false, source: null, categories: defaultCategories(), guidance: null, mcp: null, updatedAt: null }; +} + +export function selfReportSettingsPath(): string { + return "~/.failproofai/self-report.json"; +} + +export function selfReportSpec(): SelfReportSpec { + return buildSelfReportSpec(defaultCategories()); +} + +export function openaiTool(): OpenAITool { + return toOpenAITool(selfReportSpec()); +} + +export function anthropicTool(): AnthropicTool { + return toAnthropicTool(selfReportSpec()); +} + +export function selfReport(): void { + notice(); +} + +export function handleToolCall(name: string): string | null { + if (!isSelfReportTool(name)) return null; + notice(); + return SELF_REPORT_RESULT; +} diff --git a/sdk/typescript/src/edge/langchain.ts b/sdk/typescript/src/edge/langchain.ts index 968789975..6f1b4ca2d 100644 --- a/sdk/typescript/src/edge/langchain.ts +++ b/sdk/typescript/src/edge/langchain.ts @@ -2,6 +2,7 @@ import { noopAdapter } from "./adapter.js"; import { notice } from "./notice.js"; +import { inertNamedTool } from "./self-report-tool.js"; export const SESSION_METADATA_KEY = "failproofai_sdk_session_id"; @@ -16,3 +17,9 @@ export function langchainHandler(): Record { } export const adapter = noopAdapter("langchain"); + +/** The Self Reports tool, answering `Recorded.` and recording nothing. */ +export function selfReportTool(...options: unknown[]): T { + void options; + return inertNamedTool(); +} diff --git a/sdk/typescript/src/edge/llamaindex.ts b/sdk/typescript/src/edge/llamaindex.ts index b54121461..4c8c09e12 100644 --- a/sdk/typescript/src/edge/llamaindex.ts +++ b/sdk/typescript/src/edge/llamaindex.ts @@ -2,6 +2,7 @@ import { noopAdapter } from "./adapter.js"; import { notice } from "./notice.js"; +import { inertNamedTool } from "./self-report-tool.js"; /** Attaching to a LlamaIndex object records nothing here; returns a detach. */ export function attach(): () => void { @@ -10,3 +11,9 @@ export function attach(): () => void { } export const adapter = noopAdapter("llamaindex"); + +/** The Self Reports tool, answering `Recorded.` and recording nothing. */ +export function selfReportTool(...options: unknown[]): T { + void options; + return inertNamedTool(); +} diff --git a/sdk/typescript/src/edge/mastra.ts b/sdk/typescript/src/edge/mastra.ts index 5ae3bfb30..d11c3cde8 100644 --- a/sdk/typescript/src/edge/mastra.ts +++ b/sdk/typescript/src/edge/mastra.ts @@ -2,6 +2,7 @@ import { noopAdapter } from "./adapter.js"; import { notice } from "./notice.js"; +import { inertNamedTool } from "./self-report-tool.js"; export function wrapTool(tool: T): T { notice(); @@ -15,3 +16,9 @@ export function workflow(workflowName: string, body: () => T): T { } export const adapter = noopAdapter("mastra"); + +/** The Self Reports tool, answering `Recorded.` and recording nothing. */ +export function selfReportTool(...options: unknown[]): T { + void options; + return inertNamedTool(); +} diff --git a/sdk/typescript/src/edge/self-report-tool.ts b/sdk/typescript/src/edge/self-report-tool.ts new file mode 100644 index 000000000..a6885628c --- /dev/null +++ b/sdk/typescript/src/edge/self-report-tool.ts @@ -0,0 +1,55 @@ +/** + * The Self Reports tool for runtimes with no filesystem — see `./index.ts`. + * + * Each framework subpath's `selfReportTool()` returns a tool that offers the + * same name, description and schema and answers `Recorded.`, recording + * nothing. No framework is loaded: these are plain objects in the shape each + * framework reads. + */ + +import { + SELF_REPORT_RESULT, + SELF_REPORT_TOOL_NAME, + buildSelfReportSpec, + defaultCategories, +} from "../self-report-spec.js"; +import { notice } from "./notice.js"; + +export function inertSpec() { + return buildSelfReportSpec(defaultCategories()); +} + +export function inertAnswer(): Promise { + notice(); + return Promise.resolve(SELF_REPORT_RESULT); +} + +/** The AI SDK shape: a `jsonSchema()` result under both v4 and v5+ keys. */ +export function inertAiTool(): T { + const spec = inertSpec(); + const schema = { + [Symbol.for("vercel.ai.schema")]: true, + _type: undefined, + [Symbol.for("vercel.ai.validator")]: true, + jsonSchema: spec.inputSchema, + validate: undefined, + }; + return { description: spec.description, inputSchema: schema, parameters: schema, execute: inertAnswer } as T; +} + +/** A structured-tool-like object: `name`, `description`, `schema`, and every call entry point. */ +export function inertNamedTool(): T { + const spec = inertSpec(); + return { + name: SELF_REPORT_TOOL_NAME, + id: SELF_REPORT_TOOL_NAME, + description: spec.description, + schema: spec.inputSchema, + inputSchema: spec.inputSchema, + metadata: { name: SELF_REPORT_TOOL_NAME, description: spec.description, parameters: spec.inputSchema }, + invoke: inertAnswer, + call: inertAnswer, + func: inertAnswer, + execute: inertAnswer, + } as T; +} diff --git a/sdk/typescript/src/events.ts b/sdk/typescript/src/events.ts index 4f7e411f1..06ea00312 100644 --- a/sdk/typescript/src/events.ts +++ b/sdk/typescript/src/events.ts @@ -14,12 +14,14 @@ import { humanWaitEvent, modelRequestEvent, modelResponseEvent, + selfReportEvent, toolResultEvent, toolUseEvent, } from "./schema.js"; import type { EventWriter } from "./writer.js"; import { formatMicros, nowMicros } from "./clock.js"; import { fatalSuffix, onProcessExit, type OpenItem } from "./exit.js"; +import { SELF_REPORT_DETAIL_LIMIT, clipDetail, isSelfReportTool } from "./self-report-spec.js"; /** * `sessionId` and `agentId` are named options on every method, so a caller @@ -397,6 +399,27 @@ export interface HumanInterruptOptions extends BaseEventOptions { atStep?: string | null; } +/** + * The options `selfReport` takes beside its category and detail. `toolCallId` + * is the model's id for the report call, when there was one: it is recorded, + * and it is how a report made from inside a framework's tool loop finds the + * agent whose loop called it. + */ +export interface SelfReportOptions extends BaseEventOptions { + toolCallId?: string | null; +} + +/** + * The session a report goes to when nothing names one — the same placeholder + * the MCP server uses. A report is never dropped and never throws for want of + * a session: an agent that is stuck is precisely the one whose run may have + * lost its scope. + */ +export const UNATTRIBUTED_SESSION = "unattributed"; + +/** Keys `selfReport` sets itself; an extra of the same name would overwrite them. */ +const SELF_REPORT_OWN: ReadonlySet = new Set(["category", "detail", "source", "tool_call_id"]); + type Extras = Record; /** A tool call, hook or model call opened and not yet closed. */ @@ -802,6 +825,92 @@ export class EventNamespace { ); } + /** + * `self_report` — the agent says it is stuck (Self Reports). + * + * `category` is recorded as given, known or not; a missing `detail` is + * recorded as `""`, and a longer one is cut to 2000 characters. `source` is + * always `"sdk"`. + * + * Identity, most specific first: an explicit `sessionId`; the open + * `tool_use` for `toolCallId` (or, with no id, for a report-tool name) that + * an adapter or a `toolCall()` scope recorded — so a report made inside a + * framework's tool loop lands on the agent whose loop called it; the + * enclosing scope; and last `"unattributed"`, with one warning. Unlike every + * other event method a missing session never throws. + */ + selfReport(category: string, detail?: string | null, options: SelfReportOptions = {}): void { + const { sessionId, agentId, toolCallId, ...fields } = options; + const own = Object.keys(fields).filter((key) => SELF_REPORT_OWN.has(key)); + if (own.length > 0) { + throw new Error( + `selfReport sets ${JSON.stringify(own.sort())} itself; they cannot be passed as custom fields`, + ); + } + this.validateFields(fields); + const callId = typeof toolCallId === "string" && toolCallId !== "" ? toolCallId : undefined; + const [sid, aid] = this.reportIdentity(sessionId, agentId, callId); + this.writer.submit( + selfReportEvent({ + timestamp: this.fmtTs(this.now()), + sessionId: sid, + agentId: aid, + category: typeof category === "string" ? category : category === undefined || category === null ? "" : String(category), + detail: clipDetail(typeof detail === "string" ? detail : detail === undefined || detail === null ? "" : String(detail)), + source: "sdk", + toolCallId: callId, + extraFields: fields, + }), + ); + } + + private warnedUnattributed = false; + + private reportIdentity( + sessionId: string | null | undefined, + agentId: string | null | undefined, + toolCallId: string | undefined, + ): [string, string] { + if (sessionId !== undefined && sessionId !== null) return resolveIdentity(sessionId, agentId); + const ambient = context.sessionId(); + const leaf = this.openToolFor(toolCallId, ambient); + if (leaf !== undefined) { + const aid = agentId ?? leaf.agentId; + validateIdentity("agentId", aid); + return [leaf.sessionId, aid]; + } + if (ambient !== null) return resolveIdentity(null, agentId); + if (!this.warnedUnattributed) { + this.warnedUnattributed = true; + logger.warn( + `selfReport found no session to record into and filed it under "${UNATTRIBUTED_SESSION}". ` + + "Call it inside `failproofai.session(fn)` / `failproofai.agent('name', fn)`, or pass sessionId. " + + "This is logged once.", + ); + } + const aid = agentId ?? context.agentId(); + validateIdentity("agentId", aid); + return [UNATTRIBUTED_SESSION, aid]; + } + + /** + * The newest open tool call a report belongs to: the one with this id, else + * one named like the report tool (LlamaIndex gives a tool no id, and an + * adapter may have recorded its own id rather than the model's). Inside a + * scope only that scope's session is searched. + */ + private openToolFor(toolCallId: string | undefined, preferSession: string | null): OpenLeaf | undefined { + const leaves = [...this.openLeaves.values()].filter((leaf) => leaf.kind === "tool").reverse(); + const pick = (matches: (leaf: OpenLeaf) => boolean): OpenLeaf | undefined => { + const found = leaves.filter(matches); + return preferSession === null ? found[0] : found.find((leaf) => leaf.sessionId === preferSession); + }; + return ( + (toolCallId !== undefined ? pick((leaf) => leaf.id === toolCallId) : undefined) ?? + pick((leaf) => isSelfReportTool(leaf.name)) + ); + } + humanWait(opts: HumanWaitOptions): void { const { sessionId, agentId, inputId, prompt, options, reason, ...fields } = opts; this.validateFields(fields); @@ -876,4 +985,4 @@ export class EventNamespace { } } -export { RESERVED, PROMOTED_NUMERIC, PROMOTED_STRING, U32_MAX, PENDING_CAP }; +export { RESERVED, PROMOTED_NUMERIC, PROMOTED_STRING, U32_MAX, PENDING_CAP, SELF_REPORT_DETAIL_LIMIT }; diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts index db9ed6c86..8e51f60cd 100644 --- a/sdk/typescript/src/index.ts +++ b/sdk/typescript/src/index.ts @@ -9,8 +9,10 @@ * express. * * **Adapters** — `instrument()`. Wires LangChain/LangGraph, the Vercel AI * SDK, Mastra and LlamaIndex.TS to the scopes above. - * * **`event.*`** — the 15 event methods, for anything the adapters do not + * * **`event.*`** — the event methods, for anything the adapters do not * cover. + * * **Self Reports** — `selfReport()` and the report tool (`openaiTool()`, + * `anthropicTool()`, `handleToolCall()`), so an agent can say it is stuck. * * `sessionId` and `agentId` are optional on every event method: omitted, they * resolve from the enclosing scope. Nothing bound and nothing passed is an @@ -74,10 +76,32 @@ export type { HumanWaitOptions, ModelRequestOptions, ModelResponseOptions, + SelfReportOptions, ToolResultOptions, ToolUseOptions, } from "./events.js"; +export { + DEFAULT_SELF_REPORT_CATEGORIES, + SELF_REPORT_RESULT, + SELF_REPORT_TOOL_NAME, + anthropicTool, + handleToolCall, + isSelfReportTool, + openaiTool, + selfReport, + selfReportSettings, + selfReportSettingsPath, + selfReportSpec, +} from "./self-report.js"; +export type { + AnthropicTool, + OpenAITool, + SelfReportCategory, + SelfReportSettings, + SelfReportSpec, +} from "./self-report.js"; + export { setLogger, setLogLevel } from "./logger.js"; export type { Logger, LogLevel } from "./logger.js"; @@ -136,7 +160,7 @@ export function configure(options: ConfigureOptions = {}): void { } /** - * The 15 event methods. + * The event methods: the 15 shared event types, plus `selfReport`. * * A forwarding view of the process-wide namespace rather than a direct * reference, so a test can replace `runtime.event` with a recording namespace diff --git a/sdk/typescript/src/integrations/ai.ts b/sdk/typescript/src/integrations/ai.ts index ebe7fb127..14732cb24 100644 --- a/sdk/typescript/src/integrations/ai.ts +++ b/sdk/typescript/src/integrations/ai.ts @@ -1564,3 +1564,7 @@ export const _internals = { tracker: (): core.RunTracker | null => tracker, openCalls: (): number => calls.size, }; + +/** The Self Reports tool for this framework — see `./self-report-tools.ts`. */ +export { aiSelfReportTool as selfReportTool } from "./self-report-tools.js"; +export type { AiSelfReportToolOptions, AiSelfReportTool, AiModule } from "./self-report-tools.js"; diff --git a/sdk/typescript/src/integrations/langchain.ts b/sdk/typescript/src/integrations/langchain.ts index 4a6c7aab6..538922498 100644 --- a/sdk/typescript/src/integrations/langchain.ts +++ b/sdk/typescript/src/integrations/langchain.ts @@ -2338,3 +2338,7 @@ export function langchainHandler(options?: LangChainOptions): Record + values.find((value): value is string => typeof value === "string" && value !== ""); + +function identityOf(options: SelfReportToolOptions): { sessionId?: string; agentId?: string } { + return { + ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }), + ...(options.agentId === undefined ? {} : { agentId: options.agentId }), + }; +} + +function missing(framework: string, install: string): Error { + return new Error( + `selfReportTool() needs ${framework}, which could not be loaded from this application. ` + + `Install it (\`${install}\`), or pass the module: selfReportTool({ module: await import("${framework}") }).`, + ); +} + +// -- Vercel AI SDK ---------------------------------------------------------- + +/** The `ai` exports this builder uses. */ +export interface AiModule { + tool?: (definition: never) => unknown; + jsonSchema?: (schema: never) => unknown; +} + +export interface AiSelfReportToolOptions extends SelfReportToolOptions { + module?: AiModule; +} + +/** The shape `selfReportTool()` returns when nothing narrows it. */ +export interface AiSelfReportTool { + description: string; + inputSchema?: unknown; + parameters?: unknown; + execute: (input: unknown, options?: { toolCallId?: string }) => Promise; +} + +/** + * What `jsonSchema()` returns, built by hand when `ai` cannot be `require`d + * (v7 is ESM-only). Every major from 4 through 7 recognises a schema by these + * registered symbols and the `jsonSchema` / `validate` keys, so the result is + * the same object `jsonSchema()` would have made. + */ +function handMadeJsonSchema(schema: Record): Record { + return { + [Symbol.for("vercel.ai.schema")]: true, + _type: undefined, + [Symbol.for("vercel.ai.validator")]: true, + jsonSchema: schema, + validate: undefined, + }; +} + +/** + * The report tool for the Vercel AI SDK, majors 4–7: + * + * tools: { failproofai_report: selfReportTool(), ...yourTools } + * + * Built with `ai`'s own `tool()` and `jsonSchema()` (no zod). The schema goes + * under `parameters` on v4 and `inputSchema` from v5. The report lands on the + * agent whose loop called it: the model's `toolCallId` finds the `tool_use` + * the adapter recorded, else the enclosing `failproofai` scope. + */ +export function aiSelfReportTool(options: AiSelfReportToolOptions = {}): T { + const spec = selfReportSpec(); + const major = versionTuple("ai")?.[0]; + // v4–v6 ship CommonJS; v7 does not, and a `require` of it would print + // Node's require(esm) warning in the customer's process for nothing. + const ai = options.module ?? (major !== undefined && major <= 6 ? tryRequire("ai") : null); + const schema = + typeof ai?.jsonSchema === "function" + ? ai.jsonSchema(spec.inputSchema as never) + : handMadeJsonSchema(spec.inputSchema); + const identity = identityOf(options); + const definition: AiSelfReportTool = { + description: spec.description, + ...(major === undefined || major >= 5 ? { inputSchema: schema } : {}), + ...(major === undefined || major < 5 ? { parameters: schema } : {}), + execute: (input: unknown, callOptions?: { toolCallId?: string }) => + Promise.resolve(recordToolCall(input, { ...identity, toolCallId: pickId(callOptions?.toolCallId) })), + }; + return (typeof ai?.tool === "function" ? ai.tool(definition as never) : definition) as T; +} + +// -- LangChain ---------------------------------------------------------------- + +/** The `@langchain/core/tools` exports this builder uses. */ +export interface LangChainToolsModule { + tool?: (func: never, fields: never) => unknown; + DynamicStructuredTool?: new (fields: never) => unknown; +} + +export interface LangChainSelfReportToolOptions extends SelfReportToolOptions { + module?: LangChainToolsModule; +} + +/** + * The report tool for LangChain / LangGraph (`@langchain/core` ≥0.3), a + * structured tool with a JSON Schema — bind it with the rest: + * + * const model = chat.bindTools([selfReportTool(), ...tools]); + * createReactAgent({ llm, tools: [selfReportTool(), ...tools] }); + */ +export function langchainSelfReportTool(options: LangChainSelfReportToolOptions = {}): T { + const tools = options.module ?? tryRequire("@langchain/core/tools"); + const spec = selfReportSpec(); + const identity = identityOf(options); + const func = (input: unknown, runManager?: { runId?: unknown }, config?: { toolCall?: { id?: unknown } }) => + Promise.resolve( + recordToolCall(input, { ...identity, toolCallId: pickId(config?.toolCall?.id, runManager?.runId) }), + ); + const fields = { name: SELF_REPORT_TOOL_NAME, description: spec.description, schema: spec.inputSchema }; + if (typeof tools?.tool === "function") return tools.tool(func as never, fields as never) as T; + if (typeof tools?.DynamicStructuredTool === "function") { + return new tools.DynamicStructuredTool({ ...fields, func } as never) as T; + } + throw missing("@langchain/core/tools", "npm install @langchain/core"); +} + +// -- Mastra ------------------------------------------------------------------- + +/** The `@mastra/core/tools` export this builder uses. */ +export interface MastraToolsModule { + createTool?: (definition: never) => unknown; +} + +/** The `zod` export this builder uses. */ +export interface ZodModule { + z?: ZodLike; + object?: ZodLike["object"]; +} +interface ZodLike { + object(shape: Record): unknown; + string(): { describe(text: string): unknown }; + enum(values: [string, ...string[]]): unknown; +} + +export interface MastraSelfReportToolOptions extends SelfReportToolOptions { + module?: MastraToolsModule; + /** The application's `zod`, which Mastra tools need for their schema. */ + zod?: ZodModule; +} + +/** + * The input and call id of a Mastra `execute`, in either major's signature: + * 1.x `execute(input, { agent: { toolCallId } })`, 0.x + * `execute({ context: input, runtimeContext, … }, { toolCallId })`. + */ +function mastraCall(args: unknown[]): { input: unknown; toolCallId?: string } { + const [first, second] = args as [unknown, Record | undefined]; + if (typeof first === "object" && first !== null && "context" in first) { + const envelope = first as { context?: unknown; toolCallId?: unknown }; + return { input: envelope.context, toolCallId: pickId(second?.toolCallId, envelope.toolCallId) }; + } + const agentContext = second?.agent as { toolCallId?: unknown } | undefined; + return { input: first, toolCallId: pickId(agentContext?.toolCallId, second?.toolCallId) }; +} + +/** + * The report tool for Mastra (`@mastra/core` ≥0.20), made with `createTool`: + * + * new Agent({ ..., tools: { failproofai_report: selfReportTool(), ...tools } }); + * + * Mastra tools take a zod schema, so this uses the application's own `zod` + * (every Mastra install has it). + */ +export function mastraSelfReportTool(options: MastraSelfReportToolOptions = {}): T { + const tools = options.module ?? tryRequire("@mastra/core/tools"); + if (typeof tools?.createTool !== "function") throw missing("@mastra/core/tools", "npm install @mastra/core"); + const zodModule = options.zod ?? tryRequire("zod"); + const z = zodModule?.z ?? (zodModule as ZodLike | null); + if (typeof z?.object !== "function") throw missing("zod", "npm install zod"); + const spec = selfReportSpec(); + const names = ((spec.inputSchema.properties as { category: { enum: string[] } }).category.enum) as [ + string, + ...string[], + ]; + const inputSchema = z.object({ + category: z.enum(names), + detail: z.string().describe("One factual sentence: what is blocking you."), + }); + const identity = identityOf(options); + return tools.createTool({ + id: SELF_REPORT_TOOL_NAME, + description: spec.description, + inputSchema, + execute: (...args: unknown[]) => { + const { input, toolCallId } = mastraCall(args); + return Promise.resolve(recordToolCall(input, { ...identity, toolCallId })); + }, + } as never) as T; +} + +// -- LlamaIndex --------------------------------------------------------------- + +/** The `FunctionTool` export this builder can use (`llamaindex` or `@llamaindex/core/tools`). */ +export interface LlamaIndexToolsModule { + FunctionTool?: { from(fn: never, metadata: never): unknown }; +} + +export interface LlamaIndexSelfReportToolOptions extends SelfReportToolOptions { + /** Build it with this `FunctionTool` instead of as a plain `BaseTool`. */ + module?: LlamaIndexToolsModule; +} + +/** + * The report tool for LlamaIndex.TS (`llamaindex` ≥0.11.4): + * + * agent({ llm, tools: [selfReportTool(), ...tools] }); + * + * A LlamaIndex tool is any `BaseTool` — `{ metadata, call }` — so by default + * this is that plain object with a JSON Schema, and loads nothing: `require` + * of a second copy of `llamaindex` is what makes it print "already imported. + * This breaks constructor checks". Pass `module` (your `FunctionTool`) to get + * a `FunctionTool` instead. + * + * LlamaIndex hands a tool no call id, so the report finds its agent by the + * open `tool_use` named `failproofai_report`, else the enclosing scope. + */ +export function llamaindexSelfReportTool( + options: LlamaIndexSelfReportToolOptions = {}, +): T { + const spec = selfReportSpec(); + const identity = identityOf(options); + const call = (input: unknown) => Promise.resolve(recordToolCall(input, identity)); + const metadata = { name: SELF_REPORT_TOOL_NAME, description: spec.description, parameters: spec.inputSchema }; + if (typeof options.module?.FunctionTool?.from === "function") { + return options.module.FunctionTool.from(call as never, metadata as never) as T; + } + const tool: LlamaIndexSelfReportTool = { metadata, call }; + return tool as T; +} + +/** A LlamaIndex `BaseTool`, structurally. */ +export interface LlamaIndexSelfReportTool { + metadata: { name: string; description: string; parameters: Record }; + call: (input: unknown) => Promise; +} diff --git a/sdk/typescript/src/resolver.ts b/sdk/typescript/src/resolver.ts index 75f683f3f..beb082b19 100644 --- a/sdk/typescript/src/resolver.ts +++ b/sdk/typescript/src/resolver.ts @@ -72,10 +72,17 @@ export function getBaseDir(): string { * a first batch is written. */ export function failproofaiCustomAgentsDir(): string { + return join(failproofaiHome(), "custom-agents"); +} + +/** + * `~/.failproofai`, or `$FAILPROOFAI_HOME` when it is set — the umbrella every + * local failproofai file lives under (the spool above, `self-report.json`). + */ +export function failproofaiHome(): string { // Blank or whitespace-only means unset: otherwise it resolves against the cwd. const fpHome = process.env.FAILPROOFAI_HOME?.trim(); - const base = fpHome ? expandUser(fpHome) : join(homedir(), ".failproofai"); - return join(base, "custom-agents"); + return fpHome ? expandUser(fpHome) : join(homedir(), ".failproofai"); } /** diff --git a/sdk/typescript/src/schema.ts b/sdk/typescript/src/schema.ts index 5a564d2fe..4cfb88135 100644 --- a/sdk/typescript/src/schema.ts +++ b/sdk/typescript/src/schema.ts @@ -362,6 +362,37 @@ export function humanInterruptEvent(event: HumanInterruptEvent): Record { + return build( + identityBlock(event, "self_report", { + category: event.category, + detail: event.detail, + source: event.source, + }), + [["tool_call_id", event.toolCallId]], + event.extraFields ?? {}, + ); +} + /** * Every field name any event builder above declares, plus the wire names of the * identity block. `integrations/core.ts` derives its forbidden-extras set from @@ -407,4 +438,7 @@ export const DECLARED_FIELD_NAMES: ReadonlySet = new Set([ "options", "response", "at_step", + "category", + "detail", + "source", ]); diff --git a/sdk/typescript/src/self-report-spec.ts b/sdk/typescript/src/self-report-spec.ts new file mode 100644 index 000000000..46b74f4f6 --- /dev/null +++ b/sdk/typescript/src/self-report-spec.ts @@ -0,0 +1,231 @@ +/** + * Self Reports: the tool an agent calls to say it is stuck — the pure half. + * + * Everything here is data and string-building, and the module imports NOTHING, + * so the Edge build (`src/edge/`) can hand out the very same spec, the same + * OpenAI / Anthropic tool definitions and the same name check as the Node + * build. The Node half (`self-report.ts`) adds the two things that need a + * filesystem: reading `$FAILPROOFAI_HOME/self-report.json`, and recording. + * + * The tool name, the description text, the input schema and the result text + * are one contract across every implementation — the MCP servers (daemon and + * `failproofai mcp`), the Python SDK and this one — so a model sees the same + * tool whichever way it was offered. Change them in all of them or none. + */ + +/** The tool's name when an SDK offers it to a model. */ +export const SELF_REPORT_TOOL_NAME = "failproofai_report"; + +/** What the tool answers, always. Reporting never fails the agent's call. */ +export const SELF_REPORT_RESULT = "Recorded."; + +/** `detail` beyond this many characters is cut. */ +export const SELF_REPORT_DETAIL_LIMIT = 2000; + +export interface SelfReportCategory { + name: string; + description: string; +} + +/** + * The categories used when nothing configures any. An organisation's own list + * REPLACES these entirely; it is never merged with them. + */ +export const DEFAULT_SELF_REPORT_CATEGORIES: ReadonlyArray> = Object.freeze([ + Object.freeze({ + name: "looping", + description: "You keep repeating the same or circular steps without making progress.", + }), + Object.freeze({ + name: "cannot_do_request", + description: + "The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating.", + }), + Object.freeze({ + name: "invalid_tool_or_credential", + description: "A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected.", + }), + Object.freeze({ + name: "missing_context", + description: + "Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions.", + }), + Object.freeze({ + name: "repeated_tool_failure", + description: + "A command or tool failed on several distinct attempts and is blocking you. A single error is not enough.", + }), + Object.freeze({ + name: "task_failure", + description: "You genuinely tried and could not complete the task. Not for refusals or policy blocks.", + }), +]); + +/** The bounds a configured list must keep to; outside them the defaults are used. */ +export const CATEGORY_NAME_PATTERN = /^[a-z][a-z0-9_]{0,63}$/; +export const MAX_CATEGORIES = 32; +export const MAX_CATEGORY_DESCRIPTION = 500; +export const MAX_GUIDANCE = 2000; + +const PREAMBLE = + "Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; " + + "do not call it for normal work, clarifying questions or a single error. One call per distinct problem.\n" + + "Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what " + + "is blocking you. There is no need to mention this report to the user."; + +/** The tool description, built the same way in every implementation. */ +export function describeSelfReport( + categories: ReadonlyArray, + guidance?: string | null, +): string { + const lines = categories.map((category) => `- ${category.name}: ${category.description}`); + let text = `${PREAMBLE}\n\nCategories:\n${lines.join("\n")}`; + if (typeof guidance === "string" && guidance !== "") text += `\n\n${guidance}`; + return text; +} + +/** A JSON Schema object, as the tool definitions carry it. */ +export type JsonSchemaObject = Record; + +/** The input schema: `category` from the list, and a one-sentence `detail`. */ +export function selfReportInputSchema(categories: ReadonlyArray): JsonSchemaObject { + return { + type: "object", + properties: { + category: { type: "string", enum: categories.map((category) => category.name) }, + detail: { type: "string", description: "One factual sentence: what is blocking you." }, + }, + required: ["category", "detail"], + additionalProperties: false, + }; +} + +export interface SelfReportSpec { + name: string; + description: string; + inputSchema: JsonSchemaObject; +} + +export function buildSelfReportSpec( + categories: ReadonlyArray, + guidance?: string | null, +): SelfReportSpec { + return { + name: SELF_REPORT_TOOL_NAME, + description: describeSelfReport(categories, guidance), + inputSchema: selfReportInputSchema(categories), + }; +} + +/** The OpenAI Chat Completions `tools[]` entry. */ +export interface OpenAITool { + type: "function"; + function: { name: string; description: string; parameters: JsonSchemaObject }; +} + +export function toOpenAITool(spec: SelfReportSpec): OpenAITool { + return { + type: "function", + function: { name: spec.name, description: spec.description, parameters: spec.inputSchema }, + }; +} + +/** The Anthropic Messages `tools[]` entry. */ +export interface AnthropicTool { + name: string; + description: string; + input_schema: JsonSchemaObject; +} + +export function toAnthropicTool(spec: SelfReportSpec): AnthropicTool { + return { name: spec.name, description: spec.description, input_schema: spec.inputSchema }; +} + +/** + * Whether a tool name is the report tool, in any of the spellings an agent + * gives it: `failproofai_report` (the SDKs), `mcp__failproofai__report` + * (Claude Code, Codex), and the per-agent MCP spellings `failproofai__report`, + * `failproofai.report` and `failproofai/report`. + * + * Mirrors `isSelfReportToolName` in the CLI's `src/hooks/self-report.ts`; this + * package cannot import that, so the two lists must be kept equal by hand. + */ +export function isSelfReportTool(name: unknown): boolean { + if (typeof name !== "string") return false; + return /^(?:mcp__failproofai__report|failproofai(?:__|_|\.|\/)report)$/.test(name); +} + +/** + * The call's arguments as the event records them. + * + * Never rejects: a model that names an unknown category is still recorded + * under that name, a missing `detail` is recorded as `""`, and arguments that + * arrive as the JSON string a provider sent (OpenAI's `function.arguments`) + * are parsed first. Anything unreadable becomes the empty strings — the call + * itself always answers `Recorded.`. + */ +export function normalizeSelfReportArgs(args: unknown): { category: string; detail: string } { + let value = args; + if (typeof value === "string") { + try { + value = JSON.parse(value) as unknown; + } catch { + value = {}; + } + } + const record = typeof value === "object" && value !== null ? (value as Record) : {}; + return { category: asText(record.category), detail: clipDetail(asText(record.detail)) }; +} + +function asText(value: unknown): string { + if (value === undefined || value === null) return ""; + if (typeof value === "string") return value; + if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value); + try { + return JSON.stringify(value) ?? ""; + } catch { + return ""; + } +} + +/** `detail` cut to `SELF_REPORT_DETAIL_LIMIT`, never through a surrogate pair. */ +export function clipDetail(detail: string): string { + if (detail.length <= SELF_REPORT_DETAIL_LIMIT) return detail; + let cut = detail.slice(0, SELF_REPORT_DETAIL_LIMIT); + const last = cut.charCodeAt(cut.length - 1); + if (last >= 0xd800 && last <= 0xdbff) cut = cut.slice(0, -1); + return cut; +} + +/** + * A configured category list, or null when it is not one the contract allows + * (1–32 entries, names `^[a-z][a-z0-9_]{0,63}$` and unique, descriptions + * 1–500 characters). Null means "use the defaults" — a list that is half + * valid is not trimmed into a different list the organisation never wrote. + */ +export function validCategories(value: unknown): SelfReportCategory[] | null { + if (!Array.isArray(value) || value.length === 0 || value.length > MAX_CATEGORIES) return null; + const seen = new Set(); + const out: SelfReportCategory[] = []; + for (const entry of value) { + if (typeof entry !== "object" || entry === null) return null; + const { name, description } = entry as Record; + if (typeof name !== "string" || !CATEGORY_NAME_PATTERN.test(name) || seen.has(name)) return null; + if (typeof description !== "string" || description.length === 0 || description.length > MAX_CATEGORY_DESCRIPTION) { + return null; + } + seen.add(name); + out.push({ name, description }); + } + return out; +} + +/** Guidance as configured, or null when absent, empty, not a string or too long. */ +export function validGuidance(value: unknown): string | null { + if (typeof value !== "string" || value === "" || value.length > MAX_GUIDANCE) return null; + return value; +} + +export function defaultCategories(): SelfReportCategory[] { + return DEFAULT_SELF_REPORT_CATEGORIES.map((category) => ({ ...category })); +} diff --git a/sdk/typescript/src/self-report.ts b/sdk/typescript/src/self-report.ts new file mode 100644 index 000000000..77907c614 --- /dev/null +++ b/sdk/typescript/src/self-report.ts @@ -0,0 +1,169 @@ +/** + * Self Reports: the tool an agent calls to say it is stuck. + * + * Offer the tool to a model, and when the model calls it, record a + * `self_report` event in the current session and answer `Recorded.`: + * + * const tools = [failproofai.openaiTool()]; // or anthropicTool() + * ... + * const answer = failproofai.handleToolCall(call.name, call.arguments, { toolCallId: call.id }); + * if (answer !== null) { ...send `answer` back as the tool result... } + * + * The categories, and an optional paragraph of guidance appended to the + * description, come from `$FAILPROOFAI_HOME/self-report.json` — the one local + * settings file the daemon (Cloud-managed machines) or `failproofai + * self-report enable` writes. When the file is missing, unreadable or says the + * feature is off, the default categories are used: a developer who put the + * tool in their own agent's tool list has already decided to offer it. + * + * Framework tools built on these live on the adapter subpaths: + * `selfReportTool()` from `@failproofai/sdk/ai`, `/langchain`, `/mastra` and + * `/llamaindex`. + */ + +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +import { logger } from "./logger.js"; +import { failproofaiHome } from "./resolver.js"; +import { runtime } from "./runtime.js"; +import { + SELF_REPORT_RESULT, + buildSelfReportSpec, + defaultCategories, + isSelfReportTool, + normalizeSelfReportArgs, + toAnthropicTool, + toOpenAITool, + validCategories, + validGuidance, + type AnthropicTool, + type OpenAITool, + type SelfReportCategory, + type SelfReportSpec, +} from "./self-report-spec.js"; +import type { SelfReportOptions } from "./events.js"; + +export { + DEFAULT_SELF_REPORT_CATEGORIES, + SELF_REPORT_RESULT, + SELF_REPORT_TOOL_NAME, + describeSelfReport, + isSelfReportTool, +} from "./self-report-spec.js"; +export type { AnthropicTool, OpenAITool, SelfReportCategory, SelfReportSpec } from "./self-report-spec.js"; +export type { SelfReportOptions } from "./events.js"; + +/** What `self-report.json` says, with the defaults filled in. */ +export interface SelfReportSettings { + /** False when the file is missing, unreadable, or says so. */ + enabled: boolean; + /** Who wrote the file: `"cloud"` (the daemon) or `"local"` (the CLI); null without one. */ + source: "cloud" | "local" | null; + /** Never empty: the configured list when enabled and valid, else the defaults. */ + categories: SelfReportCategory[]; + guidance: string | null; + /** The local MCP server, when the file names one. */ + mcp: { port: number; url: string } | null; + updatedAt: string | null; +} + +/** `$FAILPROOFAI_HOME/self-report.json` (default `~/.failproofai/self-report.json`). */ +export function selfReportSettingsPath(): string { + return join(failproofaiHome(), "self-report.json"); +} + +/** + * Read the settings file. Never throws; read fresh on every call, so a change + * the daemon makes reaches the next spec without a restart. + */ +export function selfReportSettings(): SelfReportSettings { + const disabled: SelfReportSettings = { + enabled: false, + source: null, + categories: defaultCategories(), + guidance: null, + mcp: null, + updatedAt: null, + }; + let raw: unknown; + try { + raw = JSON.parse(readFileSync(selfReportSettingsPath(), "utf8")) as unknown; + } catch { + return disabled; + } + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return disabled; + const file = raw as Record; + const source = file.source === "cloud" || file.source === "local" ? file.source : null; + const mcp = mcpOf(file.mcp); + const updatedAt = typeof file.updatedAt === "string" ? file.updatedAt : null; + if (file.enabled !== true) return { ...disabled, source, mcp, updatedAt }; + return { + enabled: true, + source, + categories: validCategories(file.categories) ?? defaultCategories(), + guidance: validGuidance(file.guidance), + mcp, + updatedAt, + }; +} + +function mcpOf(value: unknown): { port: number; url: string } | null { + if (typeof value !== "object" || value === null) return null; + const { port, url } = value as Record; + if (typeof port !== "number" || !Number.isInteger(port) || typeof url !== "string") return null; + return { port, url }; +} + +/** `{ name, description, inputSchema }` for the report tool, from the current settings. */ +export function selfReportSpec(): SelfReportSpec { + const settings = selfReportSettings(); + return buildSelfReportSpec(settings.categories, settings.guidance); +} + +/** The report tool as an OpenAI Chat Completions `tools[]` entry. */ +export function openaiTool(): OpenAITool { + return toOpenAITool(selfReportSpec()); +} + +/** The report tool as an Anthropic Messages `tools[]` entry. */ +export function anthropicTool(): AnthropicTool { + return toAnthropicTool(selfReportSpec()); +} + +/** + * Record a report: a `self_report` event with `source: "sdk"`, in the current + * session and agent. See `event.selfReport` for how the session is found when + * none is bound — this never throws for want of one. + */ +export function selfReport(category: string, detail?: string | null, fields: SelfReportOptions = {}): void { + runtime.event.selfReport(category, detail, fields); +} + +/** + * Handle a model's tool call if it is the report tool. + * + * Returns `"Recorded."` after recording it, or null when `name` is some other + * tool, so it chains: `handleToolCall(name, args) ?? runMyTool(name, args)`. + * `args` may be the parsed object or the JSON string a provider sent. + * + * Never throws: whatever goes wrong while recording is logged and the call + * still answers `Recorded.`, because a report must never break the loop it + * reports on. + */ +export function handleToolCall(name: string, args: unknown, fields: SelfReportOptions = {}): string | null { + if (!isSelfReportTool(name)) return null; + recordToolCall(args, fields); + return SELF_REPORT_RESULT; +} + +/** The shared body of every report tool: record, swallow, answer. */ +export function recordToolCall(args: unknown, fields: SelfReportOptions = {}): string { + try { + const { category, detail } = normalizeSelfReportArgs(args); + runtime.event.selfReport(category, detail, fields); + } catch (error) { + logger.warn(`self report was not recorded: ${error instanceof Error ? error.message : String(error)}`); + } + return SELF_REPORT_RESULT; +} diff --git a/sdk/typescript/test/edge.test.ts b/sdk/typescript/test/edge.test.ts index cbb27b4ec..d632c0e1e 100644 --- a/sdk/typescript/test/edge.test.ts +++ b/sdk/typescript/test/edge.test.ts @@ -26,7 +26,7 @@ afterEach(() => { }); describe("the edge build's imports", () => { - it("imports no Node builtin and nothing from the Node build but VERSION and types", () => { + it("imports no Node builtin and nothing from the Node build but VERSION, the self-report spec and types", () => { for (const file of readdirSync(edgeDir).filter((name) => name.endsWith(".ts"))) { const source = readFileSync(join(edgeDir, file), "utf8"); const imports = [...source.matchAll(/^import\s+(type\s+)?[^;]*?from\s+"([^"]+)";/gms)].map((m) => ({ @@ -35,13 +35,20 @@ describe("the edge build's imports", () => { })); for (const { typeOnly, from } of imports) { if (typeOnly) continue; - const allowed = from.startsWith("./") || from === "../version.js"; + const allowed = from.startsWith("./") || from === "../version.js" || from === "../self-report-spec.js"; expect(allowed, `${file} imports ${from} at run time`).toBe(true); } expect(source, file).not.toMatch(/\bprocess\./); expect(source, file).not.toMatch(/require\(/); } }); + + it("shares a self-report spec module that itself imports nothing", () => { + const source = readFileSync(join(root, "src", "self-report-spec.ts"), "utf8"); + expect(source).not.toMatch(/^import\s/m); + expect(source).not.toMatch(/\bprocess\./); + expect(source).not.toMatch(/require\(/); + }); }); /** @@ -139,7 +146,7 @@ describe("the edge build's behaviour", () => { for (const method of Object.keys(edge.event)) { expect(() => (edge.event as unknown as Record void>)[method]!({})).not.toThrow(); } - expect(Object.keys(edge.event)).toHaveLength(15); + expect(Object.keys(edge.event)).toHaveLength(16); await expect(edge.flush()).resolves.toBeUndefined(); expect(await edge.instrument()).toEqual([]); expect(await (edge.instrument as (name: string) => Promise)("langchain")).toEqual([]); diff --git a/sdk/typescript/test/self-report.test.ts b/sdk/typescript/test/self-report.test.ts new file mode 100644 index 000000000..b78649a16 --- /dev/null +++ b/sdk/typescript/test/self-report.test.ts @@ -0,0 +1,498 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import * as edge from "../src/edge/index.js"; +import * as edgeAi from "../src/edge/ai.js"; +import * as edgeLangchain from "../src/edge/langchain.js"; +import * as edgeLlamaindex from "../src/edge/llamaindex.js"; +import * as edgeMastra from "../src/edge/mastra.js"; +import { resetNotice } from "../src/edge/notice.js"; +import { EventNamespace, UNATTRIBUTED_SESSION } from "../src/events.js"; +import * as failproofai from "../src/index.js"; +import { selfReportTool as aiTool } from "../src/integrations/ai.js"; +import { selfReportTool as langchainTool } from "../src/integrations/langchain.js"; +import { selfReportTool as llamaindexTool } from "../src/integrations/llamaindex.js"; +import { selfReportTool as mastraTool } from "../src/integrations/mastra.js"; +import { setLogger } from "../src/logger.js"; +import { runtime } from "../src/runtime.js"; +import * as schema from "../src/schema.js"; +import { agent, session, toolCall } from "../src/scopes.js"; +import { DEFAULT_SELF_REPORT_CATEGORIES } from "../src/self-report-spec.js"; +import { flushed, useSpool } from "./helpers.js"; +import type { Spool } from "./helpers.js"; + +/** + * Self Reports in the TypeScript SDK: the `self_report` event, the settings + * file, the raw tool helpers and the framework tools. The tool's name, + * description, schema and answer are a contract shared with the MCP servers and + * the Python SDK, so the texts below are asserted verbatim. + */ + +let spool: Spool; +let home: string; +let previousHome: string | undefined; + +beforeEach(() => { + spool = useSpool(); + home = mkdtempSync(join(tmpdir(), "failproofai-sr-home-")); + previousHome = process.env.FAILPROOFAI_HOME; + process.env.FAILPROOFAI_HOME = home; +}); + +afterEach(async () => { + await spool.cleanup(); + setLogger(null); + if (previousHome === undefined) delete process.env.FAILPROOFAI_HOME; + else process.env.FAILPROOFAI_HOME = previousHome; + rmSync(home, { recursive: true, force: true }); + resetNotice(); + vi.restoreAllMocks(); +}); + +const reports = async () => (await flushed(spool)).filter((e) => e.type === "self_report"); +const writeSettings = (value: unknown) => + writeFileSync(join(home, "self-report.json"), typeof value === "string" ? value : JSON.stringify(value)); +const quietLogger = () => { + const warn = vi.fn(); + setLogger({ debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() }); + return warn; +}; + +const DEFAULT_DESCRIPTION = [ + "Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; do not call it for normal work, clarifying questions or a single error. One call per distinct problem.", + "Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user.", + "", + "Categories:", + "- looping: You keep repeating the same or circular steps without making progress.", + "- cannot_do_request: The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating.", + "- invalid_tool_or_credential: A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected.", + "- missing_context: Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions.", + "- repeated_tool_failure: A command or tool failed on several distinct attempts and is blocking you. A single error is not enough.", + "- task_failure: You genuinely tried and could not complete the task. Not for refusals or policy blocks.", +].join("\n"); + +const DEFAULT_SCHEMA = { + type: "object", + properties: { + category: { + type: "string", + enum: [ + "looping", + "cannot_do_request", + "invalid_tool_or_credential", + "missing_context", + "repeated_tool_failure", + "task_failure", + ], + }, + detail: { type: "string", description: "One factual sentence: what is blocking you." }, + }, + required: ["category", "detail"], + additionalProperties: false, +}; + +describe("the self_report wire format", () => { + it("puts category, detail and source beside the identity, then environment, then tool_call_id", () => { + const event = schema.selfReportEvent({ + timestamp: "2026-01-01T00:00:00.000000Z", + sessionId: "s1", + agentId: "main", + category: "looping", + detail: "d", + source: "sdk", + toolCallId: "c1", + extraFields: { fw_x: 1 }, + }); + expect(Object.keys(event)).toEqual([ + "timestamp", + "session_id", + "agent_id", + "type", + "category", + "detail", + "source", + "environment", + "tool_call_id", + "fw_x", + ]); + expect(event.type).toBe("self_report"); + }); + + it("declares its fields, so an adapter extra cannot overwrite them", () => { + for (const name of ["category", "detail", "source"]) expect(schema.DECLARED_FIELD_NAMES.has(name)).toBe(true); + }); +}); + +describe("event.selfReport and selfReport()", () => { + it("records in the current session and agent with source sdk", async () => { + await session({ sessionId: "s1" }, () => + agent("planner", () => failproofai.selfReport("looping", "Going in circles.")), + ); + const [report] = await reports(); + expect(report).toMatchObject({ + session_id: "s1", + agent_id: "planner", + category: "looping", + detail: "Going in circles.", + source: "sdk", + }); + expect("tool_call_id" in report!).toBe(false); + }); + + it("records an unknown category as-is, a missing detail as empty, and cuts detail at 2000", async () => { + await session({ sessionId: "s1" }, () => { + failproofai.selfReport("not_a_category"); + failproofai.event.selfReport("looping", "x".repeat(2500)); + failproofai.selfReport("looping", `${"y".repeat(1999)}😀`); + }); + const [unknown, long, surrogate] = await reports(); + expect(unknown).toMatchObject({ category: "not_a_category", detail: "" }); + expect((long!.detail as string).length).toBe(2000); + expect(surrogate!.detail).toBe("y".repeat(1999)); + }); + + it("takes an explicit session, agent, tool call id and custom fields", async () => { + failproofai.selfReport("task_failure", "d", { sessionId: "s9", agentId: "worker", toolCallId: "c1", fw_note: "n" }); + expect((await reports())[0]).toMatchObject({ + session_id: "s9", + agent_id: "worker", + tool_call_id: "c1", + fw_note: "n", + }); + }); + + it("refuses reserved names and the fields it sets itself", () => { + expect(() => failproofai.selfReport("looping", "d", { sessionId: "s", timestamp: "t" })).toThrow(/Reserved/); + expect(() => failproofai.selfReport("looping", "d", { sessionId: "s", category: "x" })).toThrow(/itself/); + expect(() => failproofai.selfReport("looping", "d", { sessionId: "s", source: "mcp" })).toThrow(/itself/); + }); + + it("joins the open tool call it was made from, by id, even outside any scope", async () => { + await session({ sessionId: "framework-run" }, () => + agent("weather-agent", () => { + failproofai.event.toolUse({ toolName: "failproofai_report", toolCallId: "call-7" }); + }), + ); + failproofai.selfReport("looping", "d", { toolCallId: "call-7" }); + const [report] = await reports(); + expect(report).toMatchObject({ session_id: "framework-run", agent_id: "weather-agent", tool_call_id: "call-7" }); + }); + + it("joins an open report-tool call by name when there is no id", async () => { + await session({ sessionId: "s2" }, () => + agent("reporter", () => failproofai.event.toolUse({ toolName: "failproofai_report", toolCallId: "own-id" })), + ); + failproofai.selfReport("looping", "d"); + expect((await reports())[0]).toMatchObject({ session_id: "s2", agent_id: "reporter" }); + }); + + it("inside a scope, only looks at that scope's open tool calls", async () => { + await session({ sessionId: "other" }, () => + agent("elsewhere", () => failproofai.event.toolUse({ toolName: "failproofai_report", toolCallId: "c" })), + ); + await session({ sessionId: "mine" }, () => + toolCall("failproofai_report", { toolCallId: "c2" }, () => failproofai.selfReport("looping", "d")), + ); + const [report] = await reports(); + expect(report).toMatchObject({ session_id: "mine" }); + }); + + it("files a report with no session under unattributed and warns once, never throwing", async () => { + const warn = quietLogger(); + const namespace = new EventNamespace(runtime.writer); + namespace.selfReport("looping", "a"); + namespace.selfReport("looping", "b"); + const recorded = await reports(); + expect(recorded.map((e) => [e.session_id, e.agent_id])).toEqual([ + [UNATTRIBUTED_SESSION, "main"], + [UNATTRIBUTED_SESSION, "main"], + ]); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]![0])).toContain("unattributed"); + }); +}); + +describe("the settings file", () => { + it("is disabled, with the default categories, when the file is missing", () => { + expect(failproofai.selfReportSettingsPath()).toBe(join(home, "self-report.json")); + expect(failproofai.selfReportSettings()).toEqual({ + enabled: false, + source: null, + categories: DEFAULT_SELF_REPORT_CATEGORIES.map((c) => ({ ...c })), + guidance: null, + mcp: null, + updatedAt: null, + }); + }); + + it("is disabled when the file does not parse", () => { + writeSettings("{not json"); + expect(failproofai.selfReportSettings().enabled).toBe(false); + }); + + it("reads an enabled file: categories, guidance, mcp, source", () => { + writeSettings({ + version: 1, + enabled: true, + source: "cloud", + categories: [{ name: "tracker_down", description: "The ticket tracker is unreachable." }], + guidance: "Prefer tracker_down for anything about tickets.", + mcp: { port: 4319, url: "http://127.0.0.1:4319/mcp" }, + updatedAt: "2026-11-25T10:00:00Z", + }); + expect(failproofai.selfReportSettings()).toEqual({ + enabled: true, + source: "cloud", + categories: [{ name: "tracker_down", description: "The ticket tracker is unreachable." }], + guidance: "Prefer tracker_down for anything about tickets.", + mcp: { port: 4319, url: "http://127.0.0.1:4319/mcp" }, + updatedAt: "2026-11-25T10:00:00Z", + }); + const spec = failproofai.selfReportSpec(); + expect(spec.description.endsWith( + "Categories:\n- tracker_down: The ticket tracker is unreachable.\n\nPrefer tracker_down for anything about tickets.", + )).toBe(true); + expect((spec.inputSchema.properties as { category: { enum: string[] } }).category.enum).toEqual(["tracker_down"]); + }); + + it("uses the defaults when disabled, whatever categories the file lists", () => { + writeSettings({ enabled: false, categories: [{ name: "x", description: "y" }], guidance: "g" }); + const settings = failproofai.selfReportSettings(); + expect(settings.enabled).toBe(false); + expect(settings.categories.map((c) => c.name)).toEqual(DEFAULT_SELF_REPORT_CATEGORIES.map((c) => c.name)); + expect(settings.guidance).toBeNull(); + }); + + it.each([ + ["empty", []], + ["a bad name", [{ name: "Bad-Name", description: "d" }]], + ["a duplicate", [{ name: "a", description: "d" }, { name: "a", description: "e" }]], + ["an empty description", [{ name: "a", description: "" }]], + ["too many", Array.from({ length: 33 }, (_, i) => ({ name: `c${i}`, description: "d" }))], + ])("falls back to the default categories for %s list", (_label, categories) => { + writeSettings({ enabled: true, categories }); + expect(failproofai.selfReportSettings().categories.map((c) => c.name)).toEqual( + DEFAULT_SELF_REPORT_CATEGORIES.map((c) => c.name), + ); + }); + + it("drops guidance over 2000 characters", () => { + writeSettings({ enabled: true, guidance: "g".repeat(2001) }); + expect(failproofai.selfReportSettings().guidance).toBeNull(); + }); +}); + +describe("the raw tool helpers", () => { + it("builds the contract's spec from the defaults", () => { + expect(failproofai.selfReportSpec()).toEqual({ + name: "failproofai_report", + description: DEFAULT_DESCRIPTION, + inputSchema: DEFAULT_SCHEMA, + }); + }); + + it("shapes OpenAI and Anthropic tool entries", () => { + expect(failproofai.openaiTool()).toEqual({ + type: "function", + function: { name: "failproofai_report", description: DEFAULT_DESCRIPTION, parameters: DEFAULT_SCHEMA }, + }); + expect(failproofai.anthropicTool()).toEqual({ + name: "failproofai_report", + description: DEFAULT_DESCRIPTION, + input_schema: DEFAULT_SCHEMA, + }); + }); + + it.each([ + ["failproofai_report", true], + ["mcp__failproofai__report", true], + ["failproofai__report", true], + ["failproofai.report", true], + ["failproofai/report", true], + ["report", false], + ["failproofai_report_x", false], + ["mcp__other__report", false], + ])("isSelfReportTool(%j) is %s", (name, expected) => { + expect(failproofai.isSelfReportTool(name)).toBe(expected); + }); + + it("handles a report call: records it and answers Recorded.", async () => { + const answer = await session({ sessionId: "s1" }, () => + failproofai.handleToolCall("failproofai_report", '{"category":"missing_context","detail":"No repo access."}', { + toolCallId: "call_1", + }), + ); + expect(answer).toBe("Recorded."); + expect((await reports())[0]).toMatchObject({ + session_id: "s1", + category: "missing_context", + detail: "No repo access.", + tool_call_id: "call_1", + }); + }); + + it("returns null for any other tool, recording nothing", async () => { + expect(failproofai.handleToolCall("get_weather", { city: "Paris" })).toBeNull(); + expect(await reports()).toEqual([]); + }); + + it("never throws: unreadable arguments are recorded empty, a bad field is logged", async () => { + const warn = quietLogger(); + await session({ sessionId: "s1" }, () => { + expect(failproofai.handleToolCall("mcp__failproofai__report", "{oops")).toBe("Recorded."); + expect(failproofai.handleToolCall("failproofai_report", { category: "looping" }, { timestamp: "x" })).toBe( + "Recorded.", + ); + }); + const recorded = await reports(); + expect(recorded).toHaveLength(1); + expect(recorded[0]).toMatchObject({ category: "", detail: "" }); + expect(String(warn.mock.calls[0]![0])).toContain("not recorded"); + }); +}); + +describe("the framework tools", () => { + describe("/ai", () => { + it("is built with ai's own tool() and jsonSchema() when handed them", async () => { + const tool = vi.fn((definition: unknown) => ({ wrapped: definition })); + const jsonSchema = vi.fn((value: unknown) => ({ schemaOf: value })); + const built = aiTool<{ wrapped: { description: string; inputSchema: unknown; execute: (i: unknown, o: unknown) => Promise } }>({ + module: { tool, jsonSchema }, + }); + expect(jsonSchema).toHaveBeenCalledWith(DEFAULT_SCHEMA); + expect(built.wrapped.description).toBe(DEFAULT_DESCRIPTION); + expect(built.wrapped.inputSchema).toEqual({ schemaOf: DEFAULT_SCHEMA }); + const answer = await session({ sessionId: "s1" }, () => + built.wrapped.execute({ category: "looping", detail: "d" }, { toolCallId: "call-1" }), + ); + expect(answer).toBe("Recorded."); + expect((await reports())[0]).toMatchObject({ session_id: "s1", tool_call_id: "call-1", category: "looping" }); + }); + + it("makes the jsonSchema() object itself when ai cannot be required", () => { + // `ai` is not installed in this package, so neither the version nor the + // module resolves: the schema goes under both keys, by hand. + const built = aiTool(); + const schemaObject = built.inputSchema as Record; + expect(built.parameters).toBe(built.inputSchema); + expect(schemaObject[Symbol.for("vercel.ai.schema")]).toBe(true); + expect(schemaObject[Symbol.for("vercel.ai.validator")]).toBe(true); + expect(schemaObject.jsonSchema).toEqual(DEFAULT_SCHEMA); + expect("validate" in schemaObject).toBe(true); + }); + }); + + describe("/langchain", () => { + it("builds a structured tool with the JSON schema and records with the model's call id", async () => { + const tool = vi.fn((func: unknown, fields: unknown) => ({ func, fields })); + const built = langchainTool<{ + func: (input: unknown, runManager?: unknown, config?: unknown) => Promise; + fields: unknown; + }>({ module: { tool }, sessionId: "fixed", agentId: "lc" }); + expect(built.fields).toEqual({ name: "failproofai_report", description: DEFAULT_DESCRIPTION, schema: DEFAULT_SCHEMA }); + expect(await built.func({ category: "looping", detail: "d" }, { runId: "run-1" }, { toolCall: { id: "call_9" } })).toBe( + "Recorded.", + ); + expect((await reports())[0]).toMatchObject({ session_id: "fixed", agent_id: "lc", tool_call_id: "call_9" }); + }); + + it("falls back to DynamicStructuredTool", () => { + class DynamicStructuredTool { + constructor(readonly fields: Record) {} + } + const built = langchainTool({ module: { DynamicStructuredTool } }); + expect(built.fields.name).toBe("failproofai_report"); + expect(typeof built.fields.func).toBe("function"); + }); + + it("says how to install @langchain/core when it is missing", () => { + expect(() => langchainTool()).toThrow(/npm install @langchain\/core/); + }); + }); + + describe("/mastra", () => { + const fakeZod = { + object: (shape: Record) => ({ kind: "object", shape }), + string: () => ({ describe: (text: string) => ({ kind: "string", text }) }), + enum: (values: string[]) => ({ kind: "enum", values }), + }; + + it("uses createTool with a zod schema, in both execute signatures", async () => { + const createTool = vi.fn((definition: Record) => definition); + const built = mastraTool<{ + id: string; + inputSchema: { shape: { category: { values: string[] } } }; + execute: (...args: unknown[]) => Promise; + }>({ module: { createTool }, zod: { z: fakeZod } }); + expect(built.id).toBe("failproofai_report"); + expect(built.inputSchema.shape.category.values).toEqual(DEFAULT_SCHEMA.properties.category.enum); + await session({ sessionId: "s1" }, async () => { + // 1.x + expect(await built.execute({ category: "looping", detail: "one" }, { agent: { toolCallId: "c1" } })).toBe("Recorded."); + // 0.x + expect(await built.execute({ context: { category: "looping", detail: "zero" }, runtimeContext: {} }, { toolCallId: "c0" })).toBe( + "Recorded.", + ); + }); + const recorded = await reports(); + expect(recorded.map((e) => [e.detail, e.tool_call_id])).toEqual([ + ["one", "c1"], + ["zero", "c0"], + ]); + }); + + it("says how to install what is missing", () => { + expect(() => mastraTool()).toThrow(/npm install @mastra\/core/); + expect(() => mastraTool({ module: { createTool: (d: unknown) => d }, zod: {} })).toThrow(/npm install zod/); + }); + }); + + describe("/llamaindex", () => { + it("is a plain BaseTool by default, loading nothing", async () => { + const built = llamaindexTool(); + expect(built.metadata).toEqual({ name: "failproofai_report", description: DEFAULT_DESCRIPTION, parameters: DEFAULT_SCHEMA }); + await session({ sessionId: "s1" }, () => + agent("li", async () => { + failproofai.event.toolUse({ toolName: "failproofai_report", toolCallId: "li-1" }); + expect(await built.call({ category: "looping", detail: "d" })).toBe("Recorded."); + }), + ); + expect((await reports())[0]).toMatchObject({ session_id: "s1", agent_id: "li" }); + }); + + it("uses FunctionTool.from when handed one", () => { + const from = vi.fn((fn: unknown, metadata: unknown) => ({ fn, metadata })); + const built = llamaindexTool<{ metadata: { name: string } }>({ module: { FunctionTool: { from } } }); + expect(built.metadata.name).toBe("failproofai_report"); + }); + }); +}); + +describe("the edge build", () => { + it("offers the same spec and answers Recorded. without writing", async () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + expect(edge.selfReportSpec()).toEqual(failproofai.selfReportSpec()); + expect(edge.openaiTool()).toEqual(failproofai.openaiTool()); + expect(edge.anthropicTool()).toEqual(failproofai.anthropicTool()); + expect(edge.handleToolCall("failproofai_report")).toBe("Recorded."); + expect(edge.handleToolCall("other")).toBeNull(); + expect(edge.selfReportSettings().enabled).toBe(false); + edge.selfReport(); + edge.event.selfReport("looping", "d"); + + const ai = edgeAi.selfReportTool<{ execute: () => Promise; inputSchema: Record }>(); + expect(await ai.execute()).toBe("Recorded."); + expect(ai.inputSchema[Symbol.for("vercel.ai.schema")]).toBe(true); + for (const make of [edgeLangchain.selfReportTool, edgeMastra.selfReportTool, edgeLlamaindex.selfReportTool]) { + const tool = make<{ name: string; invoke: () => Promise; execute: () => Promise; call: () => Promise }>(); + expect(tool.name).toBe("failproofai_report"); + expect(await tool.invoke()).toBe("Recorded."); + expect(await tool.execute()).toBe("Recorded."); + expect(await tool.call()).toBe("Recorded."); + } + expect(await reports()).toEqual([]); + }); +}); diff --git a/sdk/typescript/test/wire-format.test.ts b/sdk/typescript/test/wire-format.test.ts index fe7fbc5be..a1ace5299 100644 --- a/sdk/typescript/test/wire-format.test.ts +++ b/sdk/typescript/test/wire-format.test.ts @@ -206,6 +206,7 @@ describe("event wire format", () => { schema.humanInputEvent({ ...identity, inputId: "i", response: "r", durationMs: 1 }), schema.humanPauseEvent({ ...identity, reason: "r", userId: "u" }), schema.humanInterruptEvent({ ...identity, reason: "r", userId: "u", atStep: "s" }), + schema.selfReportEvent({ ...identity, category: "c", detail: "d", source: "sdk", toolCallId: "c1" }), ]; for (const event of builders) for (const key of Object.keys(event)) declared.add(key); From 20bdfbdec8d08fa1395655b0d3e955cf48a35098 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 25 Nov 2026 21:31:01 +0530 Subject: [PATCH 05/54] [ts-sdk] Self Reports: integration scenarios, README and changelog Co-Authored-By: Claude Opus 5.5 --- sdk/typescript/CHANGELOG.md | 12 ++++ sdk/typescript/README.md | 68 +++++++++++++++++++ sdk/typescript/integration/ai.test.ts | 31 +++++++++ .../integration/fixtures/ai-4/agent.ts | 37 +++++++++- .../integration/fixtures/ai-5/agent.ts | 37 +++++++++- .../integration/fixtures/ai-6/agent.ts | 37 +++++++++- .../integration/fixtures/ai-7/agent.ts | 37 +++++++++- .../fixtures/langchain-0.3/agent.ts | 38 ++++++++++- .../integration/fixtures/langchain-1/agent.ts | 38 ++++++++++- .../fixtures/llamaindex-0.11/agent.ts | 10 +++ .../fixtures/llamaindex-0.12/agent.ts | 10 +++ .../integration/fixtures/mastra-0/agent.ts | 17 ++++- .../integration/fixtures/mastra-1/agent.ts | 17 ++++- sdk/typescript/integration/langchain.test.ts | 17 +++++ sdk/typescript/integration/llamaindex.test.ts | 19 ++++++ sdk/typescript/integration/mastra.test.ts | 19 ++++++ 16 files changed, 430 insertions(+), 14 deletions(-) diff --git a/sdk/typescript/CHANGELOG.md b/sdk/typescript/CHANGELOG.md index c7d1b111f..6f937b242 100644 --- a/sdk/typescript/CHANGELOG.md +++ b/sdk/typescript/CHANGELOG.md @@ -10,6 +10,18 @@ section is missing or empty is refused before anything is built. ## 0.0.1-beta.3 — 2026-11-24 +### Features + +- **Self Reports.** A `self_report` event (`event.selfReport` / `selfReport()`, + `source: "sdk"`) and the `failproofai_report` tool an agent calls when it is + stuck: `selfReportSpec()`, `openaiTool()`, `anthropicTool()`, `handleToolCall()` + and `isSelfReportTool()` in the core, and a ready-made `selfReportTool()` on + `/ai` (v4–v7, no zod), `/langchain`, `/mastra` and `/llamaindex`, inert in the + Edge build. Categories and guidance come from `$FAILPROOFAI_HOME/self-report.json` + (`selfReportSettings()`), with the six defaults when it is missing or disabled. + A report made inside a framework's tool loop joins the agent whose loop called + it, and never throws for want of a session. + ### Fixes - _Nothing yet._ diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index 26d8cf653..dbaaae7d6 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -341,6 +341,9 @@ The 15 event methods, for anything the adapters do not cover: `agentEnd` · `agentPause` · `agentResume` · `hookTriggered` · `hookCompleted` · `error` · `humanWait` · `humanInput` · `humanPause` · `humanInterrupt` +plus `selfReport(category, detail, options?)`, the `self_report` event (see +[Self Reports](#self-reports--let-the-agent-say-it-is-stuck)). + ```ts failproofai.event.humanWait({ inputId: "approval-1", prompt: "Ship it?" }); // …later, from anywhere in the same session: @@ -440,6 +443,71 @@ integration suite runs that file on every CI run, as an ES module and as CommonJS, against the real `openai` client — the example is proven, not just documented. +## Self Reports — let the agent say it is stuck + +Offer your agent one more tool, `failproofai_report`. When the model is blocked +(looping, a broken credential, a request it cannot do) it calls the tool, the SDK +records a `self_report` event in the current session and agent, and the call +answers `Recorded.`, so the loop carries on. The reports show up on the Self +Reports page in FailproofAI Cloud. + +With a framework, add the ready-made tool from its subpath: + +```ts +import { selfReportTool } from "@failproofai/sdk/ai"; // Vercel AI SDK 4–7 +await generateText({ model, prompt, tools: { failproofai_report: selfReportTool(), ...tools } }); + +import { selfReportTool } from "@failproofai/sdk/langchain"; // @langchain/core >=0.3 +createReactAgent({ llm, tools: [selfReportTool(), ...tools] }); + +import { selfReportTool } from "@failproofai/sdk/mastra"; // createTool + your zod +new Agent({ ...config, tools: { failproofai_report: selfReportTool(), ...tools } }); + +import { selfReportTool } from "@failproofai/sdk/llamaindex"; // a plain BaseTool +agent({ llm, tools: [selfReportTool(), ...tools] }); +``` + +With a provider SDK directly: + +```ts +const tools = [failproofai.openaiTool(), ...yours]; // or failproofai.anthropicTool() +// for each tool call the model makes: +const answer = failproofai.handleToolCall(call.name, call.arguments, { toolCallId: call.id }); +if (answer !== null) toolResults.push({ id: call.id, content: answer }); // "Recorded." +``` + +`handleToolCall` returns `null` for any other tool, accepts the arguments as an +object or as the JSON string a provider sent, and never throws. To record a +report from your own code, `failproofai.selfReport(category, detail)`. +`failproofai.selfReportSpec()` gives `{ name, description, inputSchema }` for any +other tool format. + +- **Categories.** The tool's categories, and an optional paragraph of guidance, + come from `~/.failproofai/self-report.json` (`$FAILPROOFAI_HOME` moves it), which + the daemon writes for a Cloud-managed machine and `failproofai self-report + enable` writes otherwise. A missing or disabled file means the six default + categories (`failproofai.DEFAULT_SELF_REPORT_CATEGORIES`). + `failproofai.selfReportSettings()` returns what the file says. +- **Where a report lands.** An explicit `sessionId`, else the open `tool_use` of + the report call that an adapter recorded (so inside a framework's tool loop it + joins that agent, even with no `failproofai` scope around it), else the + enclosing scope, else the session `unattributed` with one warning. A report + never throws for want of a session. +- **What is recorded.** `category` as the model gave it (an unknown one is kept), + `detail` cut to 2,000 characters, `source: "sdk"`, and `tool_call_id` when + there is one. +- **Frameworks stay optional.** Each tool loads its framework from your + application when you call it. Pass `{ module }` to use a specific copy (a + bundled one, or the ES-module copy in an ESM app): + `selfReportTool({ module: await import("@langchain/core/tools") })`. The AI SDK + tool needs no zod and works on v7, which cannot be `require`d, by building the + `jsonSchema()` object itself. The LangChain, Mastra and LlamaIndex tools return + `unknown` unless you name the type, as above. +- **Edge builds** offer the same spec and tools, which answer `Recorded.` and + record nothing. + +--- + ## Configuration ```ts diff --git a/sdk/typescript/integration/ai.test.ts b/sdk/typescript/integration/ai.test.ts index dd5921685..20b27e1cc 100644 --- a/sdk/typescript/integration/ai.test.ts +++ b/sdk/typescript/integration/ai.test.ts @@ -135,6 +135,37 @@ describe.each(FIXTURES)("%s", (fixture) => { expect(result.stdout).toContain("It is 20C in Paris."); }); + it("records a Self Report inside a scope, on the agent whose loop called the tool", () => { + const result = run("self-report"); + expect(result.stdout).toContain("It is 20C in Paris."); + const reports = ofType(result.events, "self_report"); + expect(reports, describeTrace(result)).toHaveLength(1); + expect(reports[0]).toMatchObject({ + session_id: "req-sr", + agent_id: "weather-agent", + category: "invalid_tool_or_credential", + detail: "The weather API rejected its key.", + source: "sdk", + tool_call_id: "call-r1", + }); + const done = ofType(result.events, "tool_result").find((e) => e.tool_name === "failproofai_report")!; + expect(JSON.stringify(done.output), describeTrace(result)).toContain("Recorded."); + expect(traceViolations(result.events), describeTrace(result)).toEqual([]); + }); + + it("attributes a Self Report with no scope to the run the adapter recorded", () => { + const result = run("self-report-bare"); + const [report] = ofType(result.events, "self_report"); + const use = ofType(result.events, "tool_use").find((e) => e.tool_name === "failproofai_report")!; + expect(report, describeTrace(result)).toMatchObject({ + session_id: use.session_id, + agent_id: "weather-agent", + tool_call_id: "call-r1", + source: "sdk", + }); + expect(report!.session_id).not.toBe("unattributed"); + }); + it("records streamText like generateText, and stamps the request when it is made", () => { const result = run("stream"); const { events } = result; diff --git a/sdk/typescript/integration/fixtures/ai-4/agent.ts b/sdk/typescript/integration/fixtures/ai-4/agent.ts index 2c556f23d..1fad9053c 100644 --- a/sdk/typescript/integration/fixtures/ai-4/agent.ts +++ b/sdk/typescript/integration/fixtures/ai-4/agent.ts @@ -12,7 +12,7 @@ import { createRequire } from "node:module"; import { join } from "node:path"; import * as failproofai from "@failproofai/sdk"; -import { middleware, telemetry, tracer, wrapModel } from "@failproofai/sdk/ai"; +import { middleware, selfReportTool, telemetry, tracer, wrapModel } from "@failproofai/sdk/ai"; import { generateObject, generateText, @@ -27,7 +27,7 @@ import { z } from "zod"; // --- version-specific: LanguageModelV1 (promptTokens/completionTokens, `text` + `toolCalls`) -type Script = "loop" | "answer" | "object" | "fail"; +type Script = "loop" | "answer" | "object" | "fail" | "report"; type StreamPart = Awaited>["stream"] extends ReadableStream ? P : never; const usage = (input: number, output: number) => ({ promptTokens: input, completionTokens: output }); @@ -45,6 +45,14 @@ function scripted(script: Script = "loop") { generated += 1; if (script === "fail") throw new Error("model exploded"); if (script === "object") return { text: '{"city":"Paris"}', finishReason: "stop", usage: usage(5, 3), rawCall }; + if (script === "report" && generated === 1) { + return { + toolCalls: [{ toolCallType: "function", toolCallId: "call-r1", toolName: "failproofai_report", args: '{"category":"invalid_tool_or_credential","detail":"The weather API rejected its key."}' }], + finishReason: "tool-calls", + usage: usage(11, 7), + rawCall, + }; + } if (script === "loop" && generated === 1) { return { toolCalls: [{ toolCallType: "function", toolCallId: "call-1", toolName: "weather", args: '{"city":"Paris"}' }], @@ -322,6 +330,31 @@ async function main(scenario: string): Promise { failproofai.agent("planner", { goal: "plan" }, () => ask(scripted(), { telemetry: telemetry({ functionId: "weather-agent" }) })), ); break; + case "self-report": + await failproofai.session({ sessionId: "req-sr" }, () => + failproofai.agent("planner", { goal: "plan" }, async () => { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool(), ...makeTools() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + }), + ); + break; + case "self-report-bare": { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + break; + } case "readme": await readme(); break; diff --git a/sdk/typescript/integration/fixtures/ai-5/agent.ts b/sdk/typescript/integration/fixtures/ai-5/agent.ts index 247d4fd99..3138590f7 100644 --- a/sdk/typescript/integration/fixtures/ai-5/agent.ts +++ b/sdk/typescript/integration/fixtures/ai-5/agent.ts @@ -12,7 +12,7 @@ import { createRequire } from "node:module"; import { join } from "node:path"; import * as failproofai from "@failproofai/sdk"; -import { middleware, telemetry, tracer, wrapModel } from "@failproofai/sdk/ai"; +import { middleware, selfReportTool, telemetry, tracer, wrapModel } from "@failproofai/sdk/ai"; import { generateObject, generateText, @@ -28,7 +28,7 @@ import { z } from "zod"; // --- version-specific: LanguageModelV2 (flat usage numbers, string finish reasons) -type Script = "loop" | "answer" | "object" | "fail"; +type Script = "loop" | "answer" | "object" | "fail" | "report"; type StreamPart = Awaited>["stream"] extends ReadableStream ? P : never; const usage = (input: number, output: number) => ({ inputTokens: input, outputTokens: output, totalTokens: input + output }); @@ -45,6 +45,14 @@ function scripted(script: Script = "loop") { if (script === "object") { return { content: [{ type: "text", text: '{"city":"Paris"}' }], finishReason: "stop", usage: usage(5, 3), warnings: [] }; } + if (script === "report" && generated === 1) { + return { + content: [{ type: "tool-call", toolCallId: "call-r1", toolName: "failproofai_report", input: '{"category":"invalid_tool_or_credential","detail":"The weather API rejected its key."}' }], + finishReason: "tool-calls", + usage: usage(11, 7), + warnings: [], + }; + } if (script === "loop" && generated === 1) { return { content: [{ type: "tool-call", toolCallId: "call-1", toolName: "weather", input: '{"city":"Paris"}' }], @@ -327,6 +335,31 @@ async function main(scenario: string): Promise { failproofai.agent("planner", { goal: "plan" }, () => ask(scripted(), { telemetry: telemetry({ functionId: "weather-agent" }) })), ); break; + case "self-report": + await failproofai.session({ sessionId: "req-sr" }, () => + failproofai.agent("planner", { goal: "plan" }, async () => { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool(), ...makeTools() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + }), + ); + break; + case "self-report-bare": { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + break; + } case "readme": await readme(); break; diff --git a/sdk/typescript/integration/fixtures/ai-6/agent.ts b/sdk/typescript/integration/fixtures/ai-6/agent.ts index 83ec01a7b..aca4a670c 100644 --- a/sdk/typescript/integration/fixtures/ai-6/agent.ts +++ b/sdk/typescript/integration/fixtures/ai-6/agent.ts @@ -12,7 +12,7 @@ import { createRequire } from "node:module"; import { join } from "node:path"; import * as failproofai from "@failproofai/sdk"; -import { middleware, telemetry, tracer, wrapModel } from "@failproofai/sdk/ai"; +import { middleware, selfReportTool, telemetry, tracer, wrapModel } from "@failproofai/sdk/ai"; import { generateObject, generateText, @@ -28,7 +28,7 @@ import { z } from "zod"; // --- version-specific: LanguageModelV3 (usage objects, finishReason objects) -type Script = "loop" | "answer" | "object" | "fail"; +type Script = "loop" | "answer" | "object" | "fail" | "report"; type StreamPart = Awaited>["stream"] extends ReadableStream ? P : never; const usage = (input: number, output: number) => ({ @@ -49,6 +49,14 @@ function scripted(script: Script = "loop") { if (script === "object") { return { content: [{ type: "text", text: '{"city":"Paris"}' }], finishReason: finish("stop"), usage: usage(5, 3), warnings: [] }; } + if (script === "report" && generated === 1) { + return { + content: [{ type: "tool-call", toolCallId: "call-r1", toolName: "failproofai_report", input: '{"category":"invalid_tool_or_credential","detail":"The weather API rejected its key."}' }], + finishReason: finish("tool-calls"), + usage: usage(11, 7), + warnings: [], + }; + } if (script === "loop" && generated === 1) { return { content: [{ type: "tool-call", toolCallId: "call-1", toolName: "weather", input: '{"city":"Paris"}' }], @@ -331,6 +339,31 @@ async function main(scenario: string): Promise { failproofai.agent("planner", { goal: "plan" }, () => ask(scripted(), { telemetry: telemetry({ functionId: "weather-agent" }) })), ); break; + case "self-report": + await failproofai.session({ sessionId: "req-sr" }, () => + failproofai.agent("planner", { goal: "plan" }, async () => { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool(), ...makeTools() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + }), + ); + break; + case "self-report-bare": { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + break; + } case "readme": await readme(); break; diff --git a/sdk/typescript/integration/fixtures/ai-7/agent.ts b/sdk/typescript/integration/fixtures/ai-7/agent.ts index c8049f764..d85450db1 100644 --- a/sdk/typescript/integration/fixtures/ai-7/agent.ts +++ b/sdk/typescript/integration/fixtures/ai-7/agent.ts @@ -13,7 +13,7 @@ import { createRequire } from "node:module"; import { join } from "node:path"; import * as failproofai from "@failproofai/sdk"; -import { middleware, telemetry, wrapModel } from "@failproofai/sdk/ai"; +import { middleware, selfReportTool, telemetry, wrapModel } from "@failproofai/sdk/ai"; import { generateObject, generateText, @@ -29,7 +29,7 @@ import { z } from "zod"; // --- version-specific: LanguageModelV4 (usage objects, finishReason objects) -type Script = "loop" | "answer" | "object" | "fail"; +type Script = "loop" | "answer" | "object" | "fail" | "report"; type StreamPart = Awaited>["stream"] extends ReadableStream ? P : never; const usage = (input: number, output: number) => ({ @@ -50,6 +50,14 @@ function scripted(script: Script = "loop") { if (script === "object") { return { content: [{ type: "text", text: '{"city":"Paris"}' }], finishReason: finish("stop"), usage: usage(5, 3), warnings: [] }; } + if (script === "report" && generated === 1) { + return { + content: [{ type: "tool-call", toolCallId: "call-r1", toolName: "failproofai_report", input: '{"category":"invalid_tool_or_credential","detail":"The weather API rejected its key."}' }], + finishReason: finish("tool-calls"), + usage: usage(11, 7), + warnings: [], + }; + } if (script === "loop" && generated === 1) { return { content: [{ type: "tool-call", toolCallId: "call-1", toolName: "weather", input: '{"city":"Paris"}' }], @@ -335,6 +343,31 @@ async function main(scenario: string): Promise { failproofai.agent("planner", { goal: "plan" }, () => ask(scripted(), { telemetry: telemetry({ functionId: "weather-agent" }) })), ); break; + case "self-report": + await failproofai.session({ sessionId: "req-sr" }, () => + failproofai.agent("planner", { goal: "plan" }, async () => { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool(), ...makeTools() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + }), + ); + break; + case "self-report-bare": { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + break; + } case "readme": await readme(); break; diff --git a/sdk/typescript/integration/fixtures/langchain-0.3/agent.ts b/sdk/typescript/integration/fixtures/langchain-0.3/agent.ts index 935224f11..9ada7a96f 100644 --- a/sdk/typescript/integration/fixtures/langchain-0.3/agent.ts +++ b/sdk/typescript/integration/fixtures/langchain-0.3/agent.ts @@ -14,7 +14,7 @@ import { spawnSync } from "node:child_process"; import { readFileSync, rmSync, writeFileSync } from "node:fs"; import * as failproofai from "@failproofai/sdk"; -import { langchainHandler } from "@failproofai/sdk/langchain"; +import { langchainHandler, selfReportTool } from "@failproofai/sdk/langchain"; import type { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager"; import { Document } from "@langchain/core/documents"; import { Embeddings } from "@langchain/core/embeddings"; @@ -35,7 +35,7 @@ import { RunnableSequence, type RunnableConfig, } from "@langchain/core/runnables"; -import { tool } from "@langchain/core/tools"; +import { tool, type StructuredToolInterface } from "@langchain/core/tools"; import { convertToOpenAITool } from "@langchain/core/utils/function_calling"; import { VectorStore } from "@langchain/core/vectorstores"; import { Annotation, Command, END, MemorySaver, MessagesAnnotation, START, StateGraph, interrupt } from "@langchain/langgraph"; @@ -80,6 +80,29 @@ class ScriptedModel extends BaseChatModel { } } +/** Calls the Self Reports tool once, then answers. */ +class ReportModel extends ScriptedModel { + override async _generate(messages: BaseMessage[]): Promise { + this.calls += 1; + const answered = messages.some((m) => m.getType() === "tool"); + const message = answered + ? new AIMessage({ content: "I could not reach the weather service.", response_metadata: { finish_reason: "stop" } }) + : new AIMessage({ + content: "", + tool_calls: [ + { + id: "call_r1", + name: "failproofai_report", + args: { category: "invalid_tool_or_credential", detail: "The weather API rejected its key." }, + type: "tool_call", + }, + ], + response_metadata: { finish_reason: "tool_calls" }, + }); + return { generations: [{ text: typeof message.content === "string" ? message.content : "", message }] }; + } +} + /** * A model that streams, the way a real provider integration does: one chunk * per piece, each reported through `handleLLMNewToken`. Five chunks, the same @@ -460,6 +483,17 @@ async function main(scenario: string): Promise { report({ answer: out.messages.at(-1)?.content }); break; } + case "self-report": { + const agent = createReactAgent({ + llm: new ReportModel(), + tools: [selfReportTool(), getWeather], + name: "react_bot", + }); + const out = await agent.invoke(question); + const toolMessage = out.messages.find((m) => m.getType() === "tool"); + report({ answer: out.messages.at(-1)?.content, toolResult: toolMessage?.content }); + break; + } case "error": { try { await buildGraph(new ScriptedModel({ fail: true })).invoke({ messages: [new HumanMessage("x")] }); diff --git a/sdk/typescript/integration/fixtures/langchain-1/agent.ts b/sdk/typescript/integration/fixtures/langchain-1/agent.ts index 935224f11..9ada7a96f 100644 --- a/sdk/typescript/integration/fixtures/langchain-1/agent.ts +++ b/sdk/typescript/integration/fixtures/langchain-1/agent.ts @@ -14,7 +14,7 @@ import { spawnSync } from "node:child_process"; import { readFileSync, rmSync, writeFileSync } from "node:fs"; import * as failproofai from "@failproofai/sdk"; -import { langchainHandler } from "@failproofai/sdk/langchain"; +import { langchainHandler, selfReportTool } from "@failproofai/sdk/langchain"; import type { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager"; import { Document } from "@langchain/core/documents"; import { Embeddings } from "@langchain/core/embeddings"; @@ -35,7 +35,7 @@ import { RunnableSequence, type RunnableConfig, } from "@langchain/core/runnables"; -import { tool } from "@langchain/core/tools"; +import { tool, type StructuredToolInterface } from "@langchain/core/tools"; import { convertToOpenAITool } from "@langchain/core/utils/function_calling"; import { VectorStore } from "@langchain/core/vectorstores"; import { Annotation, Command, END, MemorySaver, MessagesAnnotation, START, StateGraph, interrupt } from "@langchain/langgraph"; @@ -80,6 +80,29 @@ class ScriptedModel extends BaseChatModel { } } +/** Calls the Self Reports tool once, then answers. */ +class ReportModel extends ScriptedModel { + override async _generate(messages: BaseMessage[]): Promise { + this.calls += 1; + const answered = messages.some((m) => m.getType() === "tool"); + const message = answered + ? new AIMessage({ content: "I could not reach the weather service.", response_metadata: { finish_reason: "stop" } }) + : new AIMessage({ + content: "", + tool_calls: [ + { + id: "call_r1", + name: "failproofai_report", + args: { category: "invalid_tool_or_credential", detail: "The weather API rejected its key." }, + type: "tool_call", + }, + ], + response_metadata: { finish_reason: "tool_calls" }, + }); + return { generations: [{ text: typeof message.content === "string" ? message.content : "", message }] }; + } +} + /** * A model that streams, the way a real provider integration does: one chunk * per piece, each reported through `handleLLMNewToken`. Five chunks, the same @@ -460,6 +483,17 @@ async function main(scenario: string): Promise { report({ answer: out.messages.at(-1)?.content }); break; } + case "self-report": { + const agent = createReactAgent({ + llm: new ReportModel(), + tools: [selfReportTool(), getWeather], + name: "react_bot", + }); + const out = await agent.invoke(question); + const toolMessage = out.messages.find((m) => m.getType() === "tool"); + report({ answer: out.messages.at(-1)?.content, toolResult: toolMessage?.content }); + break; + } case "error": { try { await buildGraph(new ScriptedModel({ fail: true })).invoke({ messages: [new HumanMessage("x")] }); diff --git a/sdk/typescript/integration/fixtures/llamaindex-0.11/agent.ts b/sdk/typescript/integration/fixtures/llamaindex-0.11/agent.ts index 72266cd41..8fc752b8c 100644 --- a/sdk/typescript/integration/fixtures/llamaindex-0.11/agent.ts +++ b/sdk/typescript/integration/fixtures/llamaindex-0.11/agent.ts @@ -8,6 +8,7 @@ // assertions compare against the Python SDK's golden trace for the equivalent // `FunctionAgent` program. import * as failproofai from "@failproofai/sdk"; +import { selfReportTool } from "@failproofai/sdk/llamaindex"; import { wrapEventCaller, wrapLLMEvent } from "@llamaindex/core/decorator"; import { ToolCallLLM, @@ -334,6 +335,15 @@ async function main(scenario: string): Promise { const QUESTIONS = ["weather in Paris?", "weather in Rome?"]; switch (scenario) { + case "self-report": { + const turns: Turn[] = [ + { tool: { name: "failproofai_report", input: { category: "invalid_tool_or_credential", detail: "The weather API rejected its key." }, id: "call_r1" }, usage: { prompt_tokens: 12, completion_tokens: 5 } }, + { text: "I could not reach the weather service.", usage: { prompt_tokens: 30, completion_tokens: 7 } }, + ]; + const out = await agent({ llm: new ScriptedLLM(turns), tools: [selfReportTool(), getWeather] }).run(QUESTION); + report({ answer: out.data.result }); + break; + } case "workflow": { const out = await agent({ llm: new ScriptedLLM(), tools: [getWeather] }).run(QUESTION); report({ answer: out.data.result }); diff --git a/sdk/typescript/integration/fixtures/llamaindex-0.12/agent.ts b/sdk/typescript/integration/fixtures/llamaindex-0.12/agent.ts index 72266cd41..8fc752b8c 100644 --- a/sdk/typescript/integration/fixtures/llamaindex-0.12/agent.ts +++ b/sdk/typescript/integration/fixtures/llamaindex-0.12/agent.ts @@ -8,6 +8,7 @@ // assertions compare against the Python SDK's golden trace for the equivalent // `FunctionAgent` program. import * as failproofai from "@failproofai/sdk"; +import { selfReportTool } from "@failproofai/sdk/llamaindex"; import { wrapEventCaller, wrapLLMEvent } from "@llamaindex/core/decorator"; import { ToolCallLLM, @@ -334,6 +335,15 @@ async function main(scenario: string): Promise { const QUESTIONS = ["weather in Paris?", "weather in Rome?"]; switch (scenario) { + case "self-report": { + const turns: Turn[] = [ + { tool: { name: "failproofai_report", input: { category: "invalid_tool_or_credential", detail: "The weather API rejected its key." }, id: "call_r1" }, usage: { prompt_tokens: 12, completion_tokens: 5 } }, + { text: "I could not reach the weather service.", usage: { prompt_tokens: 30, completion_tokens: 7 } }, + ]; + const out = await agent({ llm: new ScriptedLLM(turns), tools: [selfReportTool(), getWeather] }).run(QUESTION); + report({ answer: out.data.result }); + break; + } case "workflow": { const out = await agent({ llm: new ScriptedLLM(), tools: [getWeather] }).run(QUESTION); report({ answer: out.data.result }); diff --git a/sdk/typescript/integration/fixtures/mastra-0/agent.ts b/sdk/typescript/integration/fixtures/mastra-0/agent.ts index 503fb8c04..cc56d6d3b 100644 --- a/sdk/typescript/integration/fixtures/mastra-0/agent.ts +++ b/sdk/typescript/integration/fixtures/mastra-0/agent.ts @@ -11,7 +11,7 @@ // the first call asks for a tool, the next one answers. Every agent gets its // own script so the token counts in the trace say which call they came from. import * as failproofai from "@failproofai/sdk"; -import { wrapTool } from "@failproofai/sdk/mastra"; +import { selfReportTool, wrapTool } from "@failproofai/sdk/mastra"; import { Agent } from "@mastra/core/agent"; import { createTool } from "@mastra/core/tools"; import { createStep, createWorkflow } from "@mastra/core/workflows"; @@ -414,6 +414,21 @@ async function main(scenario: string): Promise { report({ instrumented: await failproofai.instrument("mastra") }); switch (scenario) { + case "self-report": { + const reporting = new Agent({ + id: "weather-agent", + name: "weather-agent", + instructions: "Answer weather questions.", + model: scriptedModel([ + { tool: "failproofai_report", input: { category: "invalid_tool_or_credential", detail: "The weather API rejected its key." }, usage: [11, 7] }, + { text: "I could not reach the weather service.", usage: [23, 9] }, + ]) as never, + tools: { failproofai_report: selfReportTool() }, + }); + const out = await reporting.generate(question); + report({ answer: out.text }); + break; + } case "generate": { const out = await weatherAgent().generate(question); report({ answer: out.text }); diff --git a/sdk/typescript/integration/fixtures/mastra-1/agent.ts b/sdk/typescript/integration/fixtures/mastra-1/agent.ts index faefc8a01..8775f38b8 100644 --- a/sdk/typescript/integration/fixtures/mastra-1/agent.ts +++ b/sdk/typescript/integration/fixtures/mastra-1/agent.ts @@ -6,7 +6,7 @@ // the first call asks for a tool, the next one answers. Every agent gets its // own script so the token counts in the trace say which call they came from. import * as failproofai from "@failproofai/sdk"; -import { wrapTool } from "@failproofai/sdk/mastra"; +import { selfReportTool, wrapTool } from "@failproofai/sdk/mastra"; import { Agent } from "@mastra/core/agent"; import { createTool } from "@mastra/core/tools"; import { createStep, createWorkflow } from "@mastra/core/workflows"; @@ -409,6 +409,21 @@ async function main(scenario: string): Promise { report({ instrumented: await failproofai.instrument("mastra") }); switch (scenario) { + case "self-report": { + const reporting = new Agent({ + id: "weather-agent", + name: "weather-agent", + instructions: "Answer weather questions.", + model: scriptedModel([ + { tool: "failproofai_report", input: { category: "invalid_tool_or_credential", detail: "The weather API rejected its key." }, usage: [11, 7] }, + { text: "I could not reach the weather service.", usage: [23, 9] }, + ]) as never, + tools: { failproofai_report: selfReportTool() }, + }); + const out = await reporting.generate(question); + report({ answer: out.text }); + break; + } case "generate": { const out = await weatherAgent().generate(question); report({ answer: out.text }); diff --git a/sdk/typescript/integration/langchain.test.ts b/sdk/typescript/integration/langchain.test.ts index f45359645..501c48088 100644 --- a/sdk/typescript/integration/langchain.test.ts +++ b/sdk/typescript/integration/langchain.test.ts @@ -200,6 +200,23 @@ describe.each(FIXTURES)("%s", (fixture) => { expect(traceViolations(result.events), describeTrace(result)).toEqual([]); }); + it("records a Self Report on the agent whose loop called the tool", () => { + const result = run("self-report"); + expect(result.stdout).toContain('"toolResult":"Recorded."'); + const reports = ofType(result.events, "self_report"); + expect(reports, describeTrace(result)).toHaveLength(1); + const use = ofType(result.events, "tool_use").find((e) => e.tool_name === "failproofai_report")!; + expect(use, describeTrace(result)).toBeDefined(); + expect(reports[0]).toMatchObject({ + session_id: use.session_id, + agent_id: "react_bot", + category: "invalid_tool_or_credential", + detail: "The weather API rejected its key.", + source: "sdk", + }); + expect(traceViolations(result.events), describeTrace(result)).toEqual([]); + }); + it("records a failure once, where it happened", () => { const result = run("error"); expect(result.stdout).toContain("model exploded"); diff --git a/sdk/typescript/integration/llamaindex.test.ts b/sdk/typescript/integration/llamaindex.test.ts index c1ef8d864..1e83c1b83 100644 --- a/sdk/typescript/integration/llamaindex.test.ts +++ b/sdk/typescript/integration/llamaindex.test.ts @@ -97,6 +97,25 @@ describe.each(FIXTURES)("%s", (fixture) => { return result; }; + it("records a Self Report on the agent whose loop called the tool", () => { + const result = run("self-report"); + expect(result.stdout).toContain("I could not reach the weather service."); + const reports = ofType(result.events, "self_report"); + expect(reports, describeTrace(result)).toHaveLength(1); + const use = ofType(result.events, "tool_use").find((e) => e.tool_name === "failproofai_report")!; + expect(use, describeTrace(result)).toBeDefined(); + expect(reports[0]).toMatchObject({ + session_id: use.session_id, + agent_id: use.agent_id, + category: "invalid_tool_or_credential", + detail: "The weather API rejected its key.", + source: "sdk", + }); + const done = ofType(result.events, "tool_result").find((e) => e.tool_name === "failproofai_report")!; + expect(JSON.stringify(done.output), describeTrace(result)).toContain("Recorded."); + expect(traceViolations(result.events), describeTrace(result)).toEqual([]); + }); + it("records a workflow agent run as one agent with its steps as hooks", () => { const result = run("workflow"); expect(shape(result.events), describeTrace(result)).toEqual(WORKFLOW()); diff --git a/sdk/typescript/integration/mastra.test.ts b/sdk/typescript/integration/mastra.test.ts index 3ca46e00a..b72389a99 100644 --- a/sdk/typescript/integration/mastra.test.ts +++ b/sdk/typescript/integration/mastra.test.ts @@ -69,6 +69,25 @@ describe.each(FIXTURES)("%s", (fixture) => { return result; }; + it("records a Self Report on the agent whose loop called the tool", () => { + const result = run("self-report"); + expect(result.stdout).toContain("I could not reach the weather service."); + const reports = ofType(result.events, "self_report"); + expect(reports, describeTrace(result)).toHaveLength(1); + const use = ofType(result.events, "tool_use").find((e) => e.tool_name === "failproofai_report")!; + expect(use, describeTrace(result)).toBeDefined(); + expect(reports[0]).toMatchObject({ + session_id: use.session_id, + agent_id: use.agent_id, + category: "invalid_tool_or_credential", + detail: "The weather API rejected its key.", + source: "sdk", + }); + const done = ofType(result.events, "tool_result").find((e) => e.tool_name === "failproofai_report")!; + expect(JSON.stringify(done.output), describeTrace(result)).toContain("Recorded."); + expect(traceViolations(result.events), describeTrace(result)).toEqual([]); + }); + it("records generate() as one agent with one model pair per LLM step", () => { const result = run("generate"); expect(shape(result.events), describeTrace(result)).toEqual(LOOP); From fe6ac22b6164f8606e4653b899c3a699d9a65726 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 25 Nov 2026 21:31:41 +0530 Subject: [PATCH 06/54] [self-reports] Register the failproofai MCP server in every hooked agent syncSelfReportMcp reads ~/.failproofai/self-report.json and adds (enabled) or removes (disabled) a failproofai MCP server in each of the 12 agents' user-scope MCP config: HTTP to the daemon when its socket is present, else stdio via the hooks' failproofai CLI with `mcp --agent `. Entries are recognised by their shape, so a user's own failproofai server is never touched; Codex's table sits in a marker-delimited block in config.toml (new comment-preserving toml-managed-block helper), JSON edits go through jsonc-parser, YAML through the existing Document helpers, all via writeConfigFileAtomic with a backup. Wired into installHooks, failproofai config, removeHooks (user/all scope), failproofai uninstall, and a new `failproofai self-report sync [--quiet]`. selfReportRegistrationStatus() exposes per-agent state for the status command. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/manager.test.ts | 39 + __tests__/hooks/self-report-install.test.ts | 306 ++++++++ __tests__/hooks/uninstall-cli.test.ts | 21 + bin/failproofai.mjs | 47 ++ src/hooks/integrations.ts | 4 +- src/hooks/manager.ts | 26 + src/hooks/self-report-install.ts | 745 ++++++++++++++++++++ src/hooks/toml-managed-block.ts | 80 +++ src/hooks/uninstall-cli.ts | 14 + 9 files changed, 1280 insertions(+), 2 deletions(-) create mode 100644 __tests__/hooks/self-report-install.test.ts create mode 100644 src/hooks/self-report-install.ts create mode 100644 src/hooks/toml-managed-block.ts diff --git a/__tests__/hooks/manager.test.ts b/__tests__/hooks/manager.test.ts index cc52e8bb7..0635c89ce 100644 --- a/__tests__/hooks/manager.test.ts +++ b/__tests__/hooks/manager.test.ts @@ -90,6 +90,14 @@ const USER_SETTINGS_PATH = resolve(homedir(), ".claude", "settings.json"); const PROJECT_SETTINGS_PATH = resolve(process.cwd(), ".claude", "settings.json"); const LOCAL_SETTINGS_PATH = resolve(process.cwd(), ".claude", "settings.local.json"); +// Self Reports MCP registration has its own suite (self-report-install.test.ts); +// here only the calls into it are checked. +vi.mock("../../src/hooks/self-report-install", () => ({ + syncSelfReportMcp: vi.fn(() => []), + removeSelfReportMcp: vi.fn(() => []), + selfReportSyncLines: vi.fn(() => []), +})); + describe("hooks/manager", () => { beforeEach(() => { vi.resetAllMocks(); @@ -173,6 +181,21 @@ describe("hooks/manager", () => { } }); + it("syncs the Self Reports MCP server for the agents it just hooked, with the hooks' binary", async () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue("{}"); + const sr = await import("../../src/hooks/self-report-install"); + + const { installHooks } = await import("../../src/hooks/manager"); + await installHooks(); + + expect(sr.syncSelfReportMcp).toHaveBeenCalledWith({ + quiet: true, + alsoHooked: ["claude"], + binaryPath: "/usr/local/bin/failproofai", + }); + }); + // `--install` with no names WIRES HOOKS. It does not choose policies, and // it used to: a second picker opened here over BUILTIN_POLICIES — the // compiled catalog, which is not how policies arrive any more — and wrote @@ -824,6 +847,22 @@ describe("hooks/manager", () => { }); describe("removeHooks", () => { + it("removes the Self Reports MCP server for the agents whose user-scope hooks go", async () => { + vi.mocked(existsSync).mockReturnValue(false); + const sr = await import("../../src/hooks/self-report-install"); + const { removeHooks } = await import("../../src/hooks/manager"); + + await removeHooks(undefined, "all", undefined, { cli: ["claude", "codex"] }); + expect(sr.removeSelfReportMcp).toHaveBeenCalledWith({ agents: ["claude", "codex"], quiet: true }); + + vi.mocked(sr.removeSelfReportMcp).mockClear(); + await removeHooks(undefined, "project", undefined, { cli: ["claude"] }); + expect(sr.removeSelfReportMcp).not.toHaveBeenCalled(); + + await removeHooks(["block-sudo"], "user", undefined, { cli: ["claude"] }); + expect(sr.removeSelfReportMcp).not.toHaveBeenCalled(); + }); + it("removes only failproofai hooks, preserving others", async () => { vi.mocked(existsSync).mockReturnValue(true); const settings = { diff --git a/__tests__/hooks/self-report-install.test.ts b/__tests__/hooks/self-report-install.test.ts new file mode 100644 index 000000000..f30408643 --- /dev/null +++ b/__tests__/hooks/self-report-install.test.ts @@ -0,0 +1,306 @@ +// @vitest-environment node +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, resolve } from "node:path"; +import { parse as parseToml } from "smol-toml"; +import { parse as parseYaml } from "yaml"; +import { parse as parseJsonc } from "jsonc-parser/lib/esm/main.js"; +import { + SELF_REPORT_MCP_TARGETS, + isOurMcpEntry, + readSelfReportMcpSettings, + removeSelfReportMcp, + selfReportRegistrationStatus, + syncSelfReportMcp, + type SyncSelfReportMcpOptions, +} from "../../src/hooks/self-report-install"; +import { mergeTomlManagedBlock } from "../../src/hooks/toml-managed-block"; +import { INTEGRATION_TYPES, type IntegrationType } from "../../src/hooks/types"; + +const CLI = "/usr/local/bin/failproofai"; +let home: string; + +function enabledOpts(extra: Partial = {}, daemon = true): SyncSelfReportMcpOptions { + return { + quiet: true, + binaryPath: CLI, + ...extra, + deps: { + daemonSocketPresent: () => daemon, + hooksInstalled: () => true, + settings: { enabled: true, port: 4319 }, + ...extra.deps, + }, + }; +} + +function pathOf(agent: IntegrationType): string { + return SELF_REPORT_MCP_TARGETS[agent].paths()[0]; +} + +function put(path: string, text: string): void { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, text); +} + +function read(path: string): string { + return readFileSync(path, "utf8"); +} + +/** The parsed `failproofai` entry, whatever the agent's format. */ +function entryIn(agent: IntegrationType): Record | undefined { + const path = pathOf(agent); + if (!existsSync(path)) return undefined; + const text = read(path); + const t = SELF_REPORT_MCP_TARGETS[agent]; + const doc = (t.format === "toml" ? parseToml(text) : t.format === "yaml" ? parseYaml(text) ?? {} : parseJsonc(text)) as Record; + const container = t.container(doc); + let v: unknown = doc; + for (const k of [...container, "failproofai"]) v = (v as Record | undefined)?.[k]; + return v as Record | undefined; +} + +beforeEach(() => { + home = mkdtempSync(resolve(tmpdir(), "fp-selfreport-")); + vi.stubEnv("HOME", home); + vi.stubEnv("USERPROFILE", home); + for (const k of [ + "CLAUDE_CONFIG_DIR", "CODEX_HOME", "COPILOT_HOME", "PI_CODING_AGENT_DIR", "HERMES_HOME", + "OPENCLAW_STATE_DIR", "OPENCLAW_HOME", "OPENCLAW_CONFIG_PATH", "GOOSE_PATH_ROOT", "XDG_CONFIG_HOME", + "FAILPROOFAI_SELF_REPORT_PORT", + ]) vi.stubEnv(k, ""); + vi.stubEnv("FAILPROOFAI_HOME", resolve(home, ".failproofai")); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(home, { recursive: true, force: true }); +}); + +// A pre-existing user server and some other setting, per format. +const USER_JSON = (container: string[]) => { + const inner: Record = { mine: { command: "node", args: ["my-server.js"] } }; + let obj: Record = inner; + for (const k of [...container].reverse()) obj = { [k]: obj }; + return { theme: "dark", ...obj }; +}; + +describe("syncSelfReportMcp: every agent round-trips", () => { + for (const agent of INTEGRATION_TYPES) { + const target = SELF_REPORT_MCP_TARGETS[agent]; + it(`${agent}: adds, is idempotent, keeps the user's entries, removes only ours`, () => { + const path = pathOf(agent); + let original: string; + if (target.format === "toml") { + original = '# my codex config\nmodel = "gpt-5"\n\n[mcp_servers.mine]\ncommand = "node" # inline note\nargs = ["my-server.js"]\n'; + } else if (target.format === "yaml") { + const key = target.container({})[0]; + original = `# my config\nmodel: some-model\n${key}:\n # my server\n mine:\n command: node\n args: [my-server.js]\n`; + } else { + original = `// a comment\n${JSON.stringify(USER_JSON(target.container({})), null, 2)}\n`; + if (agent === "claude") original = JSON.stringify(USER_JSON(["mcpServers"]), null, 2) + "\n"; + } + put(path, original); + + const first = syncSelfReportMcp(enabledOpts({ agents: [agent] })); + expect(first.map((r) => [r.action, r.status, r.transport])).toEqual( + first.map(() => ["added", "ok", "http"]), + ); + const entry = entryIn(agent)!; + expect(isOurMcpEntry(entry)).toBe(true); + expect(JSON.stringify(entry)).toContain(`http://127.0.0.1:4319/mcp?agent=${agent}`); + const afterAdd = read(path); + // the user's things are still there, comments included + expect(afterAdd).toContain("mine"); + expect(afterAdd).toContain(target.format === "json" && agent === "claude" ? "dark" : target.format === "toml" ? "# inline note" : target.format === "yaml" ? "# my server" : "// a comment"); + + const second = syncSelfReportMcp(enabledOpts({ agents: [agent] })); + expect(second.every((r) => r.action === "unchanged" && r.status === "ok")).toBe(true); + expect(read(path)).toBe(afterAdd); + + const removed = removeSelfReportMcp({ agents: [agent], quiet: true }); + expect(removed.map((r) => r.action)).toEqual(removed.map(() => "removed")); + expect(entryIn(agent)).toBeUndefined(); + const afterRemove = read(path); + expect(afterRemove).toContain("mine"); + if (target.format === "toml") expect(afterRemove).toBe(original); + + const again = removeSelfReportMcp({ agents: [agent], quiet: true }); + expect(again.every((r) => r.action === "unchanged")).toBe(true); + expect(read(path)).toBe(afterRemove); + }); + } +}); + +describe("transport choice", () => { + it("uses stdio with the CLI path and --agent when no daemon socket is present", () => { + syncSelfReportMcp(enabledOpts({ agents: ["claude", "codex", "opencode", "goose"] }, false)); + expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"] }); + expect(entryIn("codex")).toEqual({ command: CLI, args: ["mcp", "--agent", "codex"] }); + expect(entryIn("opencode")).toEqual({ type: "local", command: [CLI, "mcp", "--agent", "opencode"], enabled: true }); + expect(entryIn("goose")).toMatchObject({ type: "stdio", cmd: CLI, args: ["mcp", "--agent", "goose"], enabled: true }); + }); + + it("switches an existing entry between transports in place", () => { + syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + const r = syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, true)); + expect(r[0]).toMatchObject({ action: "updated", transport: "http" }); + const text = read(pathOf("codex")); + expect(text.match(/\[mcp_servers\.failproofai\]/g)).toHaveLength(1); + expect(entryIn("codex")).toEqual({ url: "http://127.0.0.1:4319/mcp?agent=codex" }); + }); + + it("takes the port from self-report.json", () => { + const p = resolve(home, ".failproofai", "self-report.json"); + put(p, JSON.stringify({ version: 1, enabled: true, mcp: { port: 5555, url: "http://127.0.0.1:5555/mcp" } })); + expect(readSelfReportMcpSettings()).toEqual({ enabled: true, port: 5555 }); + syncSelfReportMcp({ quiet: true, agents: ["cursor"], deps: { daemonSocketPresent: () => true, hooksInstalled: () => true } }); + expect(entryIn("cursor")).toEqual({ url: "http://127.0.0.1:5555/mcp?agent=cursor" }); + }); + + it("reads a missing or broken settings file as disabled", () => { + expect(readSelfReportMcpSettings().enabled).toBe(false); + put(resolve(home, ".failproofai", "self-report.json"), "{nope"); + expect(readSelfReportMcpSettings()).toEqual({ enabled: false, port: 4319 }); + }); + + it("reports an error, writing nothing, when stdio is needed and no CLI is known", () => { + const base = enabledOpts({ agents: ["cursor"] }, false); + const r = syncSelfReportMcp({ ...base, binaryPath: undefined, deps: { ...base.deps, resolveCliPath: () => null } }); + expect(r[0]).toMatchObject({ status: "error", action: "skipped" }); + expect(existsSync(pathOf("cursor"))).toBe(false); + }); +}); + +describe("ownership", () => { + it("never touches a failproofai entry it did not write (e.g. the Cloud MCP gateway)", () => { + const path = pathOf("claude"); + const foreign = { mcpServers: { failproofai: { type: "http", url: "https://gateway.example.com/mcp" } } }; + put(path, JSON.stringify(foreign, null, 2) + "\n"); + const before = read(path); + expect(syncSelfReportMcp(enabledOpts({ agents: ["claude"] }))[0]).toMatchObject({ status: "conflict", action: "skipped" }); + expect(removeSelfReportMcp({ agents: ["claude"], quiet: true })[0]).toMatchObject({ status: "conflict" }); + expect(read(path)).toBe(before); + }); + + it("treats a hand-written codex [mcp_servers.failproofai] outside our markers as foreign", () => { + const path = pathOf("codex"); + put(path, '[mcp_servers.failproofai]\nurl = "http://127.0.0.1:4319/mcp?agent=codex"\n'); + const before = read(path); + expect(syncSelfReportMcp(enabledOpts({ agents: ["codex"] }))[0].status).toBe("conflict"); + expect(read(path)).toBe(before); + }); + + it("refuses a codex config whose inline mcp_servers table would collide, leaving it as is", () => { + const path = pathOf("codex"); + put(path, 'mcp_servers = { mine = { command = "node" } }\n'); + const before = read(path); + const r = syncSelfReportMcp(enabledOpts({ agents: ["codex"] }))[0]; + expect(r.status).toBe("error"); + expect(read(path)).toBe(before); + }); + + it("refuses an unparsable config", () => { + const path = pathOf("cursor"); + put(path, "{ not json"); + const r = syncSelfReportMcp(enabledOpts({ agents: ["cursor"] }))[0]; + expect(r.status).toBe("error"); + expect(read(path)).toBe("{ not json"); + }); + + it("recognises only our shapes", () => { + expect(isOurMcpEntry({ url: "http://127.0.0.1:4319/mcp?agent=claude" })).toBe(true); + expect(isOurMcpEntry({ serverUrl: "http://localhost:4319/mcp?agent=antigravity" })).toBe(true); + expect(isOurMcpEntry({ command: "/x/bin/failproofai", args: ["mcp", "--agent", "pi"] })).toBe(true); + expect(isOurMcpEntry({ url: "https://gateway.example.com/mcp" })).toBe(false); + expect(isOurMcpEntry({ command: "/x/bin/failproofai", args: ["--hook", "PreToolUse"] })).toBe(false); + expect(isOurMcpEntry({ command: "node", args: ["mcp", "--agent", "pi"] })).toBe(false); + }); +}); + +describe("which agents", () => { + it("enabled: only hooked agents get an entry; unhooked ones are left alone", () => { + const r = syncSelfReportMcp(enabledOpts({ deps: { hooksInstalled: (a) => a === "claude" } })); + expect(r.filter((x) => x.action === "added").map((x) => x.agent)).toEqual(["claude"]); + expect(r.filter((x) => x.agent !== "claude").every((x) => x.status === "not-hooked")).toBe(true); + expect(existsSync(pathOf("cursor"))).toBe(false); + }); + + it("alsoHooked registers agents installHooks just wrote", () => { + const r = syncSelfReportMcp(enabledOpts({ agents: ["cursor"], alsoHooked: ["cursor"], deps: { hooksInstalled: () => false } })); + expect(r[0].action).toBe("added"); + }); + + it("disabled: removes ours from every agent, hooked or not", () => { + syncSelfReportMcp(enabledOpts({ agents: ["claude", "factory"] })); + const r = syncSelfReportMcp({ quiet: true, deps: { settings: { enabled: false, port: 4319 }, hooksInstalled: () => false, daemonSocketPresent: () => true } }); + expect(r.filter((x) => x.action === "removed").map((x) => x.agent).sort()).toEqual(["claude", "factory"]); + expect(entryIn("claude")).toBeUndefined(); + }); + + it("writes every Hermes profile", () => { + put(resolve(home, ".hermes", "config.yaml"), "model: x\n"); + put(resolve(home, ".hermes", "profiles", "work", "config.yaml"), "model: y\n"); + const r = syncSelfReportMcp(enabledOpts({ agents: ["hermes"] })); + expect(r.map((x) => x.action)).toEqual(["added", "added"]); + for (const p of [resolve(home, ".hermes", "config.yaml"), resolve(home, ".hermes", "profiles", "work", "config.yaml")]) { + const doc = parseYaml(read(p)) as { mcp_servers: { failproofai: { url: string } } }; + expect(doc.mcp_servers.failproofai.url).toBe("http://127.0.0.1:4319/mcp?agent=hermes"); + expect(read(p)).toContain("failproofai self-report MCP server"); + } + }); + + it("honours CLAUDE_CONFIG_DIR, CODEX_HOME and COPILOT_HOME", () => { + vi.stubEnv("CLAUDE_CONFIG_DIR", resolve(home, "claude-work")); + vi.stubEnv("CODEX_HOME", resolve(home, "codex-x")); + vi.stubEnv("COPILOT_HOME", resolve(home, "cop")); + expect(pathOf("claude")).toBe(resolve(home, "claude-work", ".claude.json")); + expect(pathOf("codex")).toBe(resolve(home, "codex-x", "config.toml")); + expect(pathOf("copilot")).toBe(resolve(home, "cop", "mcp-config.json")); + }); + + it("uses OpenCode v2's mcp.servers when the file already has it", () => { + put(pathOf("opencode"), JSON.stringify({ mcp: { servers: { mine: { type: "local", command: ["node"] } } } })); + syncSelfReportMcp(enabledOpts({ agents: ["opencode"] })); + const doc = JSON.parse(read(pathOf("opencode"))); + expect(doc.mcp.servers.failproofai).toEqual({ type: "remote", url: "http://127.0.0.1:4319/mcp?agent=opencode" }); + expect(doc.mcp.failproofai).toBeUndefined(); + }); + + it("keeps a backup of the file it changed", () => { + put(pathOf("factory"), '{"mcpServers":{}}\n'); + syncSelfReportMcp(enabledOpts({ agents: ["factory"] })); + expect(read(`${pathOf("factory")}.failproofai-backup`)).toBe('{"mcpServers":{}}\n'); + }); +}); + +describe("selfReportRegistrationStatus", () => { + it("reports registered, transport, conflict and hooked per file without writing", () => { + syncSelfReportMcp(enabledOpts({ agents: ["claude"] }, false)); + put(pathOf("cursor"), JSON.stringify({ mcpServers: { failproofai: { url: "https://elsewhere" } } })); + const s = selfReportRegistrationStatus({ agents: ["claude", "cursor", "factory"], hooksInstalled: (a) => a === "claude" }); + expect(s).toEqual([ + expect.objectContaining({ agent: "claude", hooked: true, registered: true, transport: "stdio", conflict: false }), + expect.objectContaining({ agent: "cursor", hooked: false, registered: false, conflict: true }), + expect.objectContaining({ agent: "factory", hooked: false, registered: false, conflict: false }), + ]); + expect(existsSync(pathOf("factory"))).toBe(false); + }); +}); + +describe("mergeTomlManagedBlock", () => { + const M = { begin: "# >>> b >>>", end: "# <<< b <<<" }; + it("appends, replaces in place and removes byte for byte", () => { + const orig = 'a = 1\n[t]\nb = 2 # c\n'; + const one = mergeTomlManagedBlock(orig, "# >>> b >>>\nx = 1\n# <<< b <<<\n", M); + expect(one).toBe(`${orig}\n# >>> b >>>\nx = 1\n# <<< b <<<\n`); + const two = mergeTomlManagedBlock(one, "# >>> b >>>\nx = 2\n# <<< b <<<\n", M); + expect(two).toContain("x = 2"); + expect(two).not.toContain("x = 1"); + expect(mergeTomlManagedBlock(two, null, M)).toBe(orig); + }); + it("throws on a half block", () => { + expect(() => mergeTomlManagedBlock("# >>> b >>>\nx=1\n", null, M)).toThrow(); + }); +}); diff --git a/__tests__/hooks/uninstall-cli.test.ts b/__tests__/hooks/uninstall-cli.test.ts index 7d9b1dcaa..4d7f8277f 100644 --- a/__tests__/hooks/uninstall-cli.test.ts +++ b/__tests__/hooks/uninstall-cli.test.ts @@ -38,6 +38,11 @@ vi.mock("../../src/hooks/manager", () => ({ }), })); +// Self Reports MCP removal reads agent configs through the real integrations; +// its own behaviour is covered in self-report-install.test.ts. +vi.mock("../../src/hooks/self-report-install", () => ({ + removeSelfReportMcp: vi.fn(() => []), +})); vi.mock("../../src/hooks/agent-skill", () => ({ installedAgentSkillDirs: () => skillDirs, removeAgentSkill: vi.fn(() => { @@ -566,3 +571,19 @@ describe("hooks/uninstall-cli — the agent selection is not uninstall's to chan }); }); }); + +describe("hooks/uninstall-cli — Self Reports MCP server", () => { + it("removes failproofai's MCP server from every agent and says so", async () => { + const mod = await import("../../src/hooks/self-report-install"); + vi.mocked(mod.removeSelfReportMcp).mockReturnValueOnce([ + { agent: "claude", path: "/x/.claude.json", action: "removed", transport: "http", status: "ok" }, + { agent: "codex", path: "/x/.codex/config.toml", action: "unchanged", transport: null, status: "ok" }, + ]); + const { runUninstallCommand } = await import("../../src/hooks/uninstall-cli"); + const res = await runUninstallCommand({ yes: true, cwd: join(home, "project") }); + + expect(res.exitCode).toBe(0); + expect(vi.mocked(mod.removeSelfReportMcp)).toHaveBeenCalledWith({ quiet: true }); + expect(res.lines.join("\n")).toContain("Removed the Self Reports MCP server from 1 agent config."); + }); +}); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index e79a804d7..1df12a23e 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -743,6 +743,41 @@ async function runCli() { // over. Every precondition a person can get wrong is still checked HERE, // synchronously, because reporting success and leaving the real failure in the // journal is what already cost twenty minutes on a live machine. + // `failproofai self-report sync [--quiet]`: add or remove failproofai's + // Self Reports MCP server in every agent with failproofai hooks, from + // ~/.failproofai/self-report.json. The daemon runs it with --quiet whenever + // that file's `enabled` (or port) changes; it is idempotent. + // TODO(merge): "self-report" joins SUBCOMMANDS, the help index and its own + // help page with the `self-report status|enable|disable|test` hunk; until + // then `self-report sync --help` falls through to the index. + if (args[0] === "self-report" && args[1] === "sync") { + const subArgs = args.slice(2); + if (subArgs.includes("--help") || subArgs.includes("-h")) { + await printHelp({ + name: "self-report sync", + usage: [["failproofai self-report sync [--quiet]", "Register or remove the Self Reports MCP server in each hooked agent"]], + options: [["--quiet", "Print nothing; the exit code says whether every agent succeeded"]], + optionsCol: 12, + }); + process.exit(0); + } + const unknown = subArgs.find((a) => a !== "--quiet"); + if (unknown) { + throw new CliError(`Unexpected argument: ${unknown}.\nRun \`failproofai self-report sync --help\` for usage.`); + } + lastSubcommand = "self-report"; + const { syncSelfReportMcp, selfReportSyncLines } = await import("../src/hooks/self-report-install"); + const results = syncSelfReportMcp({ quiet: true }); + const failed = results.some((r) => r.status === "error"); + if (!subArgs.includes("--quiet")) { + const lines = selfReportSyncLines(results); + await printLines(lines.length > 0 ? lines : ["Self Reports MCP registration is already up to date."], !failed); + } + lastSubcommand = null; + await exitAfterFlush(failed ? 1 : 0); + return; + } + if (args[0] === "flush") { const subArgs = args.slice(1); if (subArgs.includes("--help") || subArgs.includes("-h")) { @@ -2073,6 +2108,18 @@ async function runCli() { else updateExit = 1; } } + // Self Reports: bring every hooked agent's MCP registration in line with + // self-report.json, also when setup found the machine already configured + // and wrote no hooks. Best-effort; prints only what changed. + if (result.applied) { + try { + const { syncSelfReportMcp, selfReportSyncLines } = await import("../src/hooks/self-report-install"); + const lines = selfReportSyncLines(syncSelfReportMcp({ quiet: true })); + if (lines.length > 0) process.stdout.write(`${lines.join("\n")}\n`); + } catch { + // never fail setup over it + } + } await warnTokenOnArgv(); await track("cli_configure_invoked", { applied: result.applied, diff --git a/src/hooks/integrations.ts b/src/hooks/integrations.ts index 4dcda2b6c..bbd0c61c6 100644 --- a/src/hooks/integrations.ts +++ b/src/hooks/integrations.ts @@ -116,7 +116,7 @@ function writeJsonFile(path: string, data: Record): void { * an empty Document; unreadable or unparseable → {@link UnreadableAgentConfigError}, * never an empty Document that the next write would put in the user's place. * Used by the Hermes integration, whose config lives in `~/.hermes/config.yaml`. */ -function readYamlDoc(path: string): Document { +export function readYamlDoc(path: string): Document { if (!existsSync(path)) return parseDocument(""); let text: string; try { @@ -141,7 +141,7 @@ function inspectYamlDoc(path: string): Document | null { } } -function writeYamlDoc(path: string, doc: Document): void { +export function writeYamlDoc(path: string, doc: Document): void { writeConfigFileAtomic(path, doc.toString()); } diff --git a/src/hooks/manager.ts b/src/hooks/manager.ts index a826eb215..195a52436 100644 --- a/src/hooks/manager.ts +++ b/src/hooks/manager.ts @@ -43,6 +43,7 @@ import { packPolicyParamKey } from "./policy-evaluator"; import { probeDaemonPolicyEvaluation } from "./daemon-service"; import { NO_PRINTED_COMMAND_REASON, sudoPath } from "./system-command"; import { keepAgentSelectionTrue } from "./agent-selection"; +import { removeSelfReportMcp, selfReportSyncLines, syncSelfReportMcp } from "./self-report-install"; import { INDENT, colorsEnabled, optsFor, printBlock, screenKit, type ScreenKitOpts } from "./tui"; const VALID_POLICY_NAMES = new Set(BUILTIN_POLICIES.map((p) => p.name)); @@ -1015,6 +1016,20 @@ async function installHooksImpl( const note = keepAgentSelectionTrue("installed", writtenSettingsPaths.map((written) => written.cli)); if (note) console.log(note); } + + // Self Reports: the agents that now have hooks get failproofai's MCP server + // when the feature is on (and lose a stale one when it is off). Best-effort: + // a config it cannot change is reported, never a failed install. + try { + const results = syncSelfReportMcp({ + quiet: true, + alsoHooked: writtenSettingsPaths.map((written) => written.cli), + binaryPath, + }); + for (const line of selfReportSyncLines(results)) console.log(line); + } catch { + // never block the install + } } /** @@ -1125,6 +1140,17 @@ export async function removeHooks(policyNames?: string[], scope: HookScope | "al if (note) say(note); }; + // Self Reports: an agent whose user-scope hooks go also loses failproofai's + // MCP server, whatever the setting says. Project/local removals leave it: + // the user-scope hooks that use it are still there. + if (scope === "user" || scope === "all") { + try { + for (const line of selfReportSyncLines(removeSelfReportMcp({ agents: selectedClis, quiet: true }))) say(line); + } catch { + // never block the removal + } + } + // Remove failproofai hooks from each selected CLI's settings file(s) let totalRemoved = 0; let nothingToReport = false; diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts new file mode 100644 index 000000000..6baba7637 --- /dev/null +++ b/src/hooks/self-report-install.ts @@ -0,0 +1,745 @@ +/** + * Self Reports: register failproofai's `report` MCP server in every agent that + * has failproofai hooks, and take it out again. + * + * The server is named `failproofai` everywhere (CONTRACT §1). It is served by + * the daemon over Streamable HTTP at `http://127.0.0.1:/mcp` when a + * daemon socket is present, and otherwise by `failproofai mcp` over stdio + * (CONTRACT §7). Both carry the agent, `?agent=` / `--agent `, so the + * server can record a report itself for agents whose hooks do not see MCP + * calls (CONTRACT §8). + * + * ## Where each agent keeps user-scope MCP servers (checked 2026-11-25) + * + * Sources are each agent's current official docs (and source where the docs + * are silent). "Hook sees MCP" is whether the hook failproofai installs fires + * for an MCP tool call, and the name it carries for server `failproofai`, + * tool `report`. + * + * | Agent | File (profile/env) | Key | HTTP entry | stdio entry | Hook sees MCP / name | + * |-------------|------------------------------------------------------|----------------------------|----------------------------------------------|-------------------------------------|----------------------| + * | claude | `$CLAUDE_CONFIG_DIR/.claude.json`, else `~/.claude.json` | `mcpServers` | `{type:"http", url}` | `{type:"stdio", command, args}` | yes, PreToolUse `mcp__failproofai__report` | + * | codex | `$CODEX_HOME/config.toml` (TOML) | `[mcp_servers.failproofai]`| `url = "…"` | `command`, `args` | yes, PreToolUse `mcp__failproofai__report` | + * | copilot | `$COPILOT_HOME/mcp-config.json`, else `~/.copilot/` | `mcpServers` | `{type:"http", url, tools:["*"]}` | `{type:"local", command, args, tools:["*"]}` | not documented | + * | cursor | `~/.cursor/mcp.json` (editor and cursor-agent) | `mcpServers` | `{url}` | `{type:"stdio", command, args}` | yes, `beforeMCPExecution` (tool_name `report` + mcp_server_name) and preToolUse `MCP:report` | + * | opencode | `~/.config/opencode/opencode.json` (as the hooks) | v1 `mcp.`; v2 `mcp.servers.` | `{type:"remote", url, enabled:true}` (v2: no `enabled`) | `{type:"local", command:[…]}` | yes, plugin `tool.execute.before` `failproofai_report` | + * | pi | `$PI_CODING_AGENT_DIR/mcp.json`, else `~/.pi/agent/` | `mcpServers` | `{url}` | `{command, args}` | yes per docs, `tool_call` `mcp__failproofai__report` | + * | hermes | every profile's `config.yaml` (YAML, HERMES_HOME) | `mcp_servers` | `{url}` | `{command, args}` | yes per source, `pre_tool_call` `mcp_failproofai_report` | + * | openclaw | every profile's `openclaw.json` | `mcp.servers` | `{url, transport:"streamable-http"}` | `{command, args}` | likely (source only), `before_tool_call` `failproofai__report` | + * | factory | `~/.factory/mcp.json` | `mcpServers` | `{type:"http", url}` | `{type:"stdio", command, args}` | yes, `mcp__failproofai__report` (regex sees `failproofai___report`) | + * | devin | `~/.config/devin/mcp_config.json` | `mcpServers` | `{url, transport:"http"}` | `{command, args}` | yes, `mcp__failproofai__report` | + * | antigravity | `~/.gemini/config/mcp_config.json` | `mcpServers` | `{serverUrl}` | `{command, args}` | not documented; eager tools `mcp_failproofai_report`, lazy (default) via `call_mcp_tool` | + * | goose | `$GOOSE_PATH_ROOT/config/config.yaml`, else `~/.config/goose/config.yaml` (YAML) | `extensions` | `{type:"streamable_http", name, enabled, uri, …}` | `{type:"stdio", name, enabled, cmd, args, …}` | not documented; would be `failproofai__report` | + * + * Every agent supports Streamable HTTP, so the transport choice is purely + * "is a daemon here". Every path is the user-scope one: MCP servers are a per + * user (per profile) setting even where failproofai's hooks are per project. + * Codex: user scope only. Its system config (`/etc/codex/config.toml`, where + * root installs put the hooks) is not documented to honour `[mcp_servers]`, so + * a root install still registers the server in `$CODEX_HOME/config.toml`. + * + * ## Ownership + * + * An entry is ours when it is named `failproofai` AND has our shape: a URL + * `http://127.0.0.1:/mcp?agent=`, or a command whose file name + * contains `failproofai` run with `mcp --agent `. That shape is the marker: + * the JSON agents validate their server schema and an extra marker key could + * make one reject the whole file. Codex's entry also sits between two marker + * comments; Hermes' and Goose's carry a marker comment. A `failproofai` entry of + * any other shape (for example the Cloud MCP gateway) is the user's: it is never + * changed and is reported as a conflict. + */ +import { existsSync, readFileSync, realpathSync } from "node:fs"; +import { execSync } from "node:child_process"; +import { homedir } from "node:os"; +import { basename, resolve } from "node:path"; +import { parse as parseToml } from "smol-toml"; +import { applyEdits, modify, parse as parseJsonc, type ParseError } from "jsonc-parser/lib/esm/main.js"; +import { isMap, type Document } from "yaml"; +import { writeConfigFileAtomic } from "./safe-config-write"; +import { codexHome } from "./codex-system-hooks"; +import { claudeConfigDir, getIntegration, readYamlDoc, writeYamlDoc, UnreadableAgentConfigError } from "./integrations"; +import { daemonSocketPresent } from "./daemon-client"; +import { failproofaiHome } from "./fp-home"; +import { listHermesProfiles } from "../../lib/hermes-profiles"; +import { listOpenClawProfiles } from "../../lib/openclaw-profiles"; +import { INTEGRATION_TYPES, type IntegrationType } from "./types"; +import { mergeTomlManagedBlock, readTomlManagedBlock, tomlString, type TomlBlockMarkers } from "./toml-managed-block"; + +// ── Settings (CONTRACT §4) ────────────────────────────────────────────────── + +/** The MCP server's name in every agent. */ +export const SELF_REPORT_MCP_SERVER_NAME = "failproofai"; +// TODO(merge): import from ./self-report +export const SELF_REPORT_DEFAULT_PORT = 4319; + +/** `$FAILPROOFAI_HOME/self-report.json`. TODO(merge): import from ./self-report (or fp-home). */ +export function selfReportSettingsPath(): string { + return resolve(failproofaiHome(), "self-report.json"); +} + +export interface SelfReportMcpSettings { + enabled: boolean; + port: number; +} + +/** + * The bits of self-report.json this module needs. Missing or unparsable file ⇒ + * disabled. TODO(merge): use the settings reader in ./self-report. + */ +export function readSelfReportMcpSettings(path = selfReportSettingsPath()): SelfReportMcpSettings { + const envPort = Number(process.env.FAILPROOFAI_SELF_REPORT_PORT); + const fallbackPort = Number.isInteger(envPort) && envPort > 0 && envPort < 65536 ? envPort : SELF_REPORT_DEFAULT_PORT; + let parsed: unknown; + try { + parsed = JSON.parse(readFileSync(path, "utf8")); + } catch { + return { enabled: false, port: fallbackPort }; + } + if (!parsed || typeof parsed !== "object") return { enabled: false, port: fallbackPort }; + const s = parsed as { enabled?: unknown; mcp?: { port?: unknown; url?: unknown } }; + let port = fallbackPort; + const filePort = s.mcp?.port; + if (typeof filePort === "number" && Number.isInteger(filePort) && filePort > 0 && filePort < 65536) port = filePort; + else if (typeof s.mcp?.url === "string") { + try { + const p = Number(new URL(s.mcp.url).port); + if (p > 0) port = p; + } catch { + // keep the fallback + } + } + return { enabled: s.enabled === true, port }; +} + +// ── Transports ────────────────────────────────────────────────────────────── + +export type SelfReportTransport = + | { kind: "http"; url: string } + | { kind: "stdio"; command: string; args: string[] }; + +export function selfReportHttpUrl(port: number, agent: IntegrationType): string { + return `http://127.0.0.1:${port}/mcp?agent=${agent}`; +} + +export function selfReportStdioArgs(agent: IntegrationType): string[] { + return ["mcp", "--agent", agent]; +} + +const OUR_URL_RE = /^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/mcp\?agent=[a-z][a-z0-9_-]*$/; + +function isOurCommand(command: unknown, args: unknown): boolean { + if (typeof command !== "string" || !basename(command).toLowerCase().includes("failproofai")) return false; + return Array.isArray(args) && args[0] === "mcp" && args[1] === "--agent" && typeof args[2] === "string"; +} + +/** Whether a server entry (any agent's shape) is one failproofai wrote. */ +export function isOurMcpEntry(entry: unknown): boolean { + if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false; + const e = entry as Record; + for (const key of ["url", "serverUrl", "uri"]) { + if (typeof e[key] === "string" && OUR_URL_RE.test(e[key] as string)) return true; + } + if (isOurCommand(e.command, e.args) || isOurCommand(e.cmd, e.args)) return true; + // OpenCode's local form: command is one array. + if (Array.isArray(e.command) && isOurCommand(e.command[0], e.command.slice(1))) return true; + return false; +} + +/** Which transport an entry of ours uses (for status), or null. */ +function transportOf(entry: unknown): "http" | "stdio" | null { + if (!isOurMcpEntry(entry)) return null; + const e = entry as Record; + return ["url", "serverUrl", "uri"].some((k) => typeof e[k] === "string") ? "http" : "stdio"; +} + +// ── Per-agent targets ─────────────────────────────────────────────────────── + +type Format = "json" | "toml" | "yaml"; + +interface McpTarget { + agent: IntegrationType; + format: Format; + /** Every file to write (one per profile for Hermes/OpenClaw). */ + paths(): string[]; + /** Whether the agent can reach a Streamable HTTP server. */ + http: boolean; + /** JSON/YAML key path of the servers map, given the parsed document. */ + container(parsed: Record): string[]; + /** The entry to write, given the container path chosen above. */ + entry(t: SelfReportTransport, container: string[]): Record; +} + +const plainEntry = (t: SelfReportTransport, urlKey = "url"): Record => + t.kind === "http" ? { [urlKey]: t.url } : { command: t.command, args: t.args }; + +function xdgConfigHome(): string { + const x = process.env.XDG_CONFIG_HOME?.trim(); + return x ? resolve(x) : resolve(homedir(), ".config"); +} + +function claudeUserConfigPath(): string { + // Claude Code keeps `.claude.json` inside CLAUDE_CONFIG_DIR when it is set, + // and beside `~/.claude` otherwise. + return process.env.CLAUDE_CONFIG_DIR?.trim() + ? resolve(claudeConfigDir(), ".claude.json") + : resolve(homedir(), ".claude.json"); +} + +function gooseConfigPath(): string { + const root = process.env.GOOSE_PATH_ROOT?.trim(); + if (root) return resolve(root, "config", "config.yaml"); + if (process.platform === "win32" && process.env.APPDATA) { + return resolve(process.env.APPDATA, "Block", "goose", "config", "config.yaml"); + } + return resolve(xdgConfigHome(), "goose", "config.yaml"); +} + +function opencodeUserConfigPath(): string { + // Same directory the hooks are written to (integrations.ts `opencode`). + const dir = resolve(homedir(), ".config", "opencode"); + const json = resolve(dir, "opencode.json"); + const jsonc = resolve(dir, "opencode.jsonc"); + return !existsSync(json) && existsSync(jsonc) ? jsonc : json; +} + +/** OpenCode v2 nests servers under `mcp.servers`; v1 puts them directly under `mcp`. */ +function opencodeIsV2(parsed: Record): boolean { + const mcp = parsed.mcp as Record | undefined; + const servers = mcp?.servers as Record | undefined; + return !!servers && typeof servers === "object" && !Array.isArray(servers) && !("type" in servers); +} + +export const SELF_REPORT_MCP_TARGETS: Record = { + claude: { + agent: "claude", format: "json", http: true, + paths: () => [claudeUserConfigPath()], + container: () => ["mcpServers"], + entry: (t) => (t.kind === "http" ? { type: "http", url: t.url } : { type: "stdio", command: t.command, args: t.args }), + }, + codex: { + agent: "codex", format: "toml", http: true, + paths: () => [resolve(codexHome(), "config.toml")], + container: () => ["mcp_servers"], + entry: (t) => plainEntry(t), + }, + copilot: { + agent: "copilot", format: "json", http: true, + paths: () => [resolve(process.env.COPILOT_HOME?.trim() || resolve(homedir(), ".copilot"), "mcp-config.json")], + container: () => ["mcpServers"], + entry: (t) => + t.kind === "http" + ? { type: "http", url: t.url, tools: ["*"] } + : { type: "local", command: t.command, args: t.args, tools: ["*"] }, + }, + cursor: { + agent: "cursor", format: "json", http: true, + paths: () => [resolve(homedir(), ".cursor", "mcp.json")], + container: () => ["mcpServers"], + entry: (t) => (t.kind === "http" ? { url: t.url } : { type: "stdio", command: t.command, args: t.args }), + }, + opencode: { + agent: "opencode", format: "json", http: true, + paths: () => [opencodeUserConfigPath()], + container: (parsed) => (opencodeIsV2(parsed) ? ["mcp", "servers"] : ["mcp"]), + entry: (t, container) => { + const v2 = container.length === 2; + const base = t.kind === "http" ? { type: "remote", url: t.url } : { type: "local", command: [t.command, ...t.args] }; + return v2 ? base : { ...base, enabled: true }; + }, + }, + pi: { + agent: "pi", format: "json", http: true, + paths: () => [resolve(process.env.PI_CODING_AGENT_DIR?.trim() || resolve(homedir(), ".pi", "agent"), "mcp.json")], + container: () => ["mcpServers"], + entry: (t) => plainEntry(t), + }, + hermes: { + agent: "hermes", format: "yaml", http: true, + paths: () => listHermesProfiles().map((p) => resolve(p.home, "config.yaml")), + container: () => ["mcp_servers"], + entry: (t) => plainEntry(t), + }, + openclaw: { + agent: "openclaw", format: "json", http: true, + paths: () => listOpenClawProfiles().map((p) => resolve(p.home, "openclaw.json")), + container: () => ["mcp", "servers"], + entry: (t) => (t.kind === "http" ? { url: t.url, transport: "streamable-http" } : { command: t.command, args: t.args }), + }, + factory: { + agent: "factory", format: "json", http: true, + paths: () => [resolve(homedir(), ".factory", "mcp.json")], + container: () => ["mcpServers"], + entry: (t) => (t.kind === "http" ? { type: "http", url: t.url } : { type: "stdio", command: t.command, args: t.args }), + }, + devin: { + agent: "devin", format: "json", http: true, + paths: () => [ + process.platform === "win32" && process.env.APPDATA + ? resolve(process.env.APPDATA, "devin", "mcp_config.json") + : resolve(homedir(), ".config", "devin", "mcp_config.json"), + ], + container: () => ["mcpServers"], + entry: (t) => (t.kind === "http" ? { url: t.url, transport: "http" } : { command: t.command, args: t.args }), + }, + antigravity: { + agent: "antigravity", format: "json", http: true, + paths: () => [resolve(homedir(), ".gemini", "config", "mcp_config.json")], + container: () => ["mcpServers"], + entry: (t) => plainEntry(t, "serverUrl"), + }, + goose: { + agent: "goose", format: "yaml", http: true, + paths: () => [gooseConfigPath()], + container: () => ["extensions"], + entry: (t) => + t.kind === "http" + ? { name: SELF_REPORT_MCP_SERVER_NAME, type: "streamable_http", enabled: true, uri: t.url, envs: {}, env_keys: [], timeout: 300 } + : { name: SELF_REPORT_MCP_SERVER_NAME, type: "stdio", enabled: true, cmd: t.command, args: t.args, envs: {}, env_keys: [], timeout: 300 }, + }, +}; + +// ── Reading and writing one file ──────────────────────────────────────────── + +const TOML_MARKERS: TomlBlockMarkers = { + begin: "# >>> failproofai self-report mcp >>>", + end: "# <<< failproofai self-report mcp <<<", +}; +const YAML_MARKER_COMMENT = " failproofai self-report MCP server (managed by failproofai; removed by `failproofai self-report disable`)"; + +type Current = + | { state: "absent" } + | { state: "ours"; entry: Record } + | { state: "foreign" }; + +interface FileOps { + current(): Current; + /** Desired entry → new file text; null entry removes ours. */ + write(entry: Record | null): void; + /** The container path the entry goes in (json/yaml only). */ + container: string[]; +} + +function readText(path: string): string { + if (!existsSync(path)) return ""; + try { + return readFileSync(path, "utf8"); + } catch (err) { + throw new UnreadableAgentConfigError(path, `it could not be read (${err instanceof Error ? err.message : String(err)})`); + } +} + +function getIn(obj: unknown, path: string[]): unknown { + let v: unknown = obj; + for (const k of path) { + if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; + v = (v as Record)[k]; + } + return v; +} + +function classify(value: unknown): Current { + if (value === undefined) return { state: "absent" }; + return isOurMcpEntry(value) ? { state: "ours", entry: value as Record } : { state: "foreign" }; +} + +function jsonOps(target: McpTarget, path: string): FileOps { + const text = readText(path); + let parsed: Record = {}; + if (text.trim() !== "") { + const errors: ParseError[] = []; + const value: unknown = parseJsonc(text, errors, { allowTrailingComma: true }); + if (errors.length > 0) throw new UnreadableAgentConfigError(path, "it is not valid JSON"); + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new UnreadableAgentConfigError(path, "its top level is not a JSON object"); + } + parsed = value as Record; + } + const container = target.container(parsed); + // A container that exists but is not an object cannot take our key. + const holder = getIn(parsed, container); + if (holder !== undefined && (typeof holder !== "object" || holder === null || Array.isArray(holder))) { + return { + container, + current: () => ({ state: "foreign" }), + write: () => { + throw new Error(`${container.join(".")} is not an object`); + }, + }; + } + const keyPath = [...container, SELF_REPORT_MCP_SERVER_NAME]; + return { + container, + current: () => classify(getIn(parsed, keyPath)), + write(entry) { + const base = text.trim() === "" ? "{}\n" : text; + const edits = modify(base, keyPath, entry ?? undefined, { + formattingOptions: { insertSpaces: true, tabSize: 2, eol: "\n" }, + }); + let next = applyEdits(base, edits); + if (!next.endsWith("\n")) next += "\n"; + writeConfigFileAtomic(path, next); + }, + }; +} + +function renderTomlBlock(entry: Record): string { + const lines = [ + TOML_MARKERS.begin, + "# Written by failproofai (Self Reports). `failproofai self-report disable` or", + "# `failproofai uninstall` removes it. Everything between the markers is replaced.", + `[mcp_servers.${SELF_REPORT_MCP_SERVER_NAME}]`, + ]; + for (const [k, v] of Object.entries(entry)) { + if (typeof v === "string") lines.push(`${k} = ${tomlString(v)}`); + else if (Array.isArray(v)) lines.push(`${k} = [${v.map((x) => tomlString(String(x))).join(", ")}]`); + } + lines.push(TOML_MARKERS.end); + return `${lines.join("\n")}\n`; +} + +function tomlOps(path: string): FileOps { + const text = readText(path); + let outside: string; + let ourBlock: string | null; + try { + ourBlock = readTomlManagedBlock(text, TOML_MARKERS); + outside = mergeTomlManagedBlock(text, null, TOML_MARKERS); + } catch (err) { + throw new UnreadableAgentConfigError(path, err instanceof Error ? err.message : String(err)); + } + let parsedOutside: Record; + let parsedAll: Record; + try { + parsedOutside = parseToml(outside) as Record; + parsedAll = parseToml(text) as Record; + } catch (err) { + throw new UnreadableAgentConfigError(path, `it does not parse as TOML (${err instanceof Error ? err.message.split("\n")[0] : String(err)})`); + } + const keyPath = ["mcp_servers", SELF_REPORT_MCP_SERVER_NAME]; + return { + container: ["mcp_servers"], + current() { + if (getIn(parsedOutside, keyPath) !== undefined) return { state: "foreign" }; + if (!ourBlock) return { state: "absent" }; + const entry = getIn(parsedAll, keyPath); + return entry && typeof entry === "object" ? { state: "ours", entry: entry as Record } : { state: "absent" }; + }, + write(entry) { + const next = mergeTomlManagedBlock(text, entry ? renderTomlBlock(entry) : null, TOML_MARKERS); + // Never hand Codex a file it cannot start with: an inline `mcp_servers = {…}` + // elsewhere would collide with our table header. + let check: Record; + try { + check = parseToml(next) as Record; + } catch (err) { + throw new Error(`the result would not be valid TOML (${err instanceof Error ? err.message.split("\n")[0] : String(err)})`); + } + if (entry && getIn(check, keyPath) === undefined) throw new Error("the written entry did not read back"); + writeConfigFileAtomic(path, next); + }, + }; +} + +function yamlOps(target: McpTarget, path: string): FileOps { + const doc: Document = readYamlDoc(path); + const js = (doc.toJS() ?? {}) as Record; + if (typeof js !== "object" || Array.isArray(js)) throw new UnreadableAgentConfigError(path, "its top level is not a mapping"); + const container = target.container(js); + const holder = doc.getIn(container); + const keyPath = [...container, SELF_REPORT_MCP_SERVER_NAME]; + if (holder !== undefined && holder !== null && !isMap(holder)) { + return { + container, + current: () => ({ state: "foreign" }), + write: () => { + throw new Error(`${container.join(".")} is not a mapping`); + }, + }; + } + return { + container, + current: () => classify(getIn(js, keyPath)), + write(entry) { + if (entry) { + const node = doc.createNode(entry); + node.commentBefore = YAML_MARKER_COMMENT; + if (holder === undefined || holder === null) doc.setIn(container, doc.createNode({})); + doc.setIn(keyPath, node); + } else { + doc.deleteIn(keyPath); + } + writeYamlDoc(path, doc); + }, + }; +} + +function opsFor(target: McpTarget, path: string): FileOps { + if (target.format === "toml") return tomlOps(path); + if (target.format === "yaml") return yamlOps(target, path); + return jsonOps(target, path); +} + +function sameEntry(a: unknown, b: unknown): boolean { + return JSON.stringify(a) === JSON.stringify(b); +} + +// ── Sync ──────────────────────────────────────────────────────────────────── + +export type SelfReportMcpAction = "added" | "updated" | "removed" | "unchanged" | "skipped"; +export type SelfReportMcpStatus = + /** The file now matches what was wanted. */ + | "ok" + /** Enabled, but this agent has no failproofai hooks; nothing written. */ + | "not-hooked" + /** A `failproofai` server that is not ours is there; left alone. */ + | "conflict" + /** The file could not be read or written; left as it was. */ + | "error" + /** The agent cannot take an MCP server this way. */ + | "unsupported"; + +export interface SelfReportMcpResult { + agent: IntegrationType; + path: string; + action: SelfReportMcpAction; + transport: "http" | "stdio" | null; + status: SelfReportMcpStatus; + detail?: string; +} + +export interface SyncSelfReportMcpOptions { + /** Override the settings file's `enabled`. `false` removes our entries everywhere. */ + enabled?: boolean; + /** Print one line per change (default: print nothing; callers print results). */ + quiet?: boolean; + /** Only these agents (default: every integration). */ + agents?: readonly IntegrationType[]; + /** + * When enabling, register in these agents even if their user-scope hooks are + * not detected (installHooks passes the agents it just wrote, at any scope). + */ + alsoHooked?: readonly IntegrationType[]; + /** The failproofai CLI the hooks use (stdio command). Default: resolved like the installer does. */ + binaryPath?: string; + /** Test seams. */ + deps?: { + daemonSocketPresent?: () => boolean; + hooksInstalled?: (agent: IntegrationType) => boolean; + settings?: SelfReportMcpSettings; + resolveCliPath?: () => string | null; + }; +} + +/** The failproofai CLI the hooks run: the installer's override, PATH, then this process's own bin. */ +export function resolveSelfReportCliPath(): string | null { + const override = process.env.FAILPROOFAI_BINARY_OVERRIDE?.trim(); + if (override) return override; + try { + const cmd = process.platform === "win32" ? "where failproofai" : "which failproofai"; + const found = execSync(cmd, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim().split("\n")[0]?.trim(); + if (found) return found; + } catch { + // not on PATH (a daemon's service environment, say) + } + const self = process.argv[1]; + if (self && basename(self).toLowerCase().includes("failproofai")) { + try { + return realpathSync(self); + } catch { + return resolve(self); + } + } + return null; +} + +function defaultHooksInstalled(agent: IntegrationType): boolean { + try { + const integration = getIntegration(agent); + return integration.scopes.includes("user") && integration.hooksInstalledInSettings("user"); + } catch { + return false; + } +} + +/** + * Add (enabled) or remove (disabled) our `failproofai` MCP server in every + * agent. Enabled: only agents with failproofai hooks get it, and agents without + * hooks are left as they are. Disabled: ours is removed from every agent's + * file, hooked or not. Idempotent; never touches an entry that is not ours; + * one agent's failure never stops the others. + */ +export function syncSelfReportMcp(opts: SyncSelfReportMcpOptions = {}): SelfReportMcpResult[] { + const settings = opts.deps?.settings ?? readSelfReportMcpSettings(); + const enabled = opts.enabled ?? settings.enabled; + const agents = opts.agents ?? INTEGRATION_TYPES; + const daemonHere = (opts.deps?.daemonSocketPresent ?? daemonSocketPresent)(); + const hooked = opts.deps?.hooksInstalled ?? defaultHooksInstalled; + const also = new Set(opts.alsoHooked ?? []); + let cliPath: string | null | undefined = opts.binaryPath; + const results: SelfReportMcpResult[] = []; + + for (const agent of agents) { + const target = SELF_REPORT_MCP_TARGETS[agent]; + if (!target) { + results.push({ agent, path: "", action: "skipped", transport: null, status: "unsupported" }); + continue; + } + let paths: string[]; + try { + paths = target.paths(); + } catch (err) { + results.push({ agent, path: "", action: "skipped", transport: null, status: "error", detail: errText(err) }); + continue; + } + const wantIt = enabled && (also.has(agent) || hooked(agent)); + + let transport: SelfReportTransport | null = null; + if (wantIt) { + if (daemonHere && target.http) { + transport = { kind: "http", url: selfReportHttpUrl(settings.port, agent) }; + } else { + if (cliPath === undefined) cliPath = (opts.deps?.resolveCliPath ?? resolveSelfReportCliPath)(); + if (cliPath) transport = { kind: "stdio", command: cliPath, args: selfReportStdioArgs(agent) }; + } + } + + for (const path of paths) { + if (enabled && !wantIt) { + results.push({ agent, path, action: "skipped", transport: null, status: "not-hooked" }); + continue; + } + if (wantIt && !transport) { + results.push({ + agent, path, action: "skipped", transport: null, status: "error", + detail: "no daemon is running here and the failproofai CLI was not found for stdio", + }); + continue; + } + try { + if (!wantIt && !existsSync(path)) { + results.push({ agent, path, action: "unchanged", transport: null, status: "ok" }); + continue; + } + const ops = opsFor(target, path); + const cur = ops.current(); + if (cur.state === "foreign") { + results.push({ + agent, path, action: "skipped", transport: null, status: "conflict", + detail: `a "${SELF_REPORT_MCP_SERVER_NAME}" MCP server that failproofai did not write is already configured`, + }); + continue; + } + if (!wantIt) { + if (cur.state === "absent") { + results.push({ agent, path, action: "unchanged", transport: null, status: "ok" }); + } else { + ops.write(null); + results.push({ agent, path, action: "removed", transport: transportOf(cur.entry), status: "ok" }); + } + continue; + } + const desired = target.entry(transport!, ops.container); + if (cur.state === "ours" && sameEntry(cur.entry, desired)) { + results.push({ agent, path, action: "unchanged", transport: transport!.kind, status: "ok" }); + continue; + } + ops.write(desired); + results.push({ agent, path, action: cur.state === "ours" ? "updated" : "added", transport: transport!.kind, status: "ok" }); + } catch (err) { + results.push({ agent, path, action: "skipped", transport: null, status: "error", detail: errText(err) }); + } + } + } + + if (!opts.quiet) for (const line of selfReportSyncLines(results)) console.log(line); + return results; +} + +/** Remove our entries from every agent (or `agents`), whatever the settings say. */ +export function removeSelfReportMcp(opts: Omit = {}): SelfReportMcpResult[] { + return syncSelfReportMcp({ ...opts, enabled: false }); +} + +function errText(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} + +/** One line per change, conflict or error; nothing for an agent left as it was. */ +export function selfReportSyncLines(results: readonly SelfReportMcpResult[]): string[] { + const out: string[] = []; + for (const r of results) { + const name = displayName(r.agent); + if (r.action === "added" || r.action === "updated") { + out.push(`✓ Self Reports MCP server ${r.action === "added" ? "added to" : "updated in"} ${name} (${r.transport}): ${r.path}`); + } else if (r.action === "removed") { + out.push(`✓ Self Reports MCP server removed from ${name}: ${r.path}`); + } else if (r.status === "conflict" || r.status === "error") { + out.push(`! ${name}: Self Reports MCP server not changed in ${r.path || "its config"}: ${r.detail ?? r.status}`); + } + } + return out; +} + +function displayName(agent: IntegrationType): string { + try { + return getIntegration(agent).displayName; + } catch { + return agent; + } +} + +// ── Status ────────────────────────────────────────────────────────────────── + +export interface SelfReportRegistration { + agent: IntegrationType; + path: string; + /** failproofai hooks are installed for this agent (user scope). */ + hooked: boolean; + /** Our entry is in this file. */ + registered: boolean; + transport: "http" | "stdio" | null; + /** A `failproofai` server that is not ours is there. */ + conflict: boolean; + /** The file could not be read. */ + error?: string; +} + +/** Per-agent, per-file registration state, for `failproofai self-report status`. Writes nothing. */ +export function selfReportRegistrationStatus( + opts: { agents?: readonly IntegrationType[]; hooksInstalled?: (agent: IntegrationType) => boolean } = {}, +): SelfReportRegistration[] { + const hooked = opts.hooksInstalled ?? defaultHooksInstalled; + const out: SelfReportRegistration[] = []; + for (const agent of opts.agents ?? INTEGRATION_TYPES) { + const target = SELF_REPORT_MCP_TARGETS[agent]; + if (!target) continue; + const isHooked = hooked(agent); + let paths: string[] = []; + try { + paths = target.paths(); + } catch (err) { + out.push({ agent, path: "", hooked: isHooked, registered: false, transport: null, conflict: false, error: errText(err) }); + continue; + } + for (const path of paths) { + if (!existsSync(path)) { + out.push({ agent, path, hooked: isHooked, registered: false, transport: null, conflict: false }); + continue; + } + try { + const cur = opsFor(target, path).current(); + out.push({ + agent, path, hooked: isHooked, + registered: cur.state === "ours", + transport: cur.state === "ours" ? transportOf(cur.entry) : null, + conflict: cur.state === "foreign", + }); + } catch (err) { + out.push({ agent, path, hooked: isHooked, registered: false, transport: null, conflict: false, error: errText(err) }); + } + } + } + return out; +} + diff --git a/src/hooks/toml-managed-block.ts b/src/hooks/toml-managed-block.ts new file mode 100644 index 000000000..97e87c4f3 --- /dev/null +++ b/src/hooks/toml-managed-block.ts @@ -0,0 +1,80 @@ +/** + * A comment-delimited block that failproofai owns inside someone else's TOML. + * + * There is no comment-preserving TOML writer in the dependency tree (smol-toml + * parses and stringifies, and stringifying drops every comment), and a full one + * is far more than failproofai needs: it only ever adds or removes ITS OWN + * table. So the table goes between two marker comments, appended at the end of + * the file, and every byte outside the markers is kept exactly as it was. + * Appending at the end is always valid placement for a `[table]` header: TOML + * root keys must come before the first table, so nothing of the user's can be + * captured by our header. + * + * Callers validate the merged text with smol-toml before writing it; this + * module only splices text. + */ + +export interface TomlBlockMarkers { + begin: string; + end: string; +} + +type BlockSpan = { start: number; end: number } | null | "malformed"; + +function escapeRe(s: string): string { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function findBlock(text: string, markers: TomlBlockMarkers): BlockSpan { + const begin = new RegExp(`^${escapeRe(markers.begin)}[ \\t]*\\r?$`, "m").exec(text); + if (!begin) { + return new RegExp(`^${escapeRe(markers.end)}[ \\t]*\\r?$`, "m").test(text) ? "malformed" : null; + } + const endRe = new RegExp(`^${escapeRe(markers.end)}[ \\t]*\\r?$`, "mg"); + endRe.lastIndex = begin.index + begin[0].length; + const end = endRe.exec(text); + if (!end) return "malformed"; + let stop = end.index + end[0].length; + if (text[stop] === "\n") stop++; + return { start: begin.index, end: stop }; +} + +/** Whether `text` holds a complete block. A half block (one marker) throws. */ +export function hasTomlManagedBlock(text: string, markers: TomlBlockMarkers): boolean { + const span = findBlock(text, markers); + if (span === "malformed") throw new Error(`a failproofai marker (${markers.begin}) is missing its pair`); + return span !== null; +} + +/** The block's own text (markers included), or null when there is none. */ +export function readTomlManagedBlock(text: string, markers: TomlBlockMarkers): string | null { + const span = findBlock(text, markers); + if (span === "malformed") throw new Error(`a failproofai marker (${markers.begin}) is missing its pair`); + return span ? text.slice(span.start, span.end) : null; +} + +/** + * Put `block` into `original` (replacing ours in place when it is there), or + * take ours out when `block` is null. A new block is appended after one blank + * line, which removal takes back out, so add-then-remove on a file that ended + * in a newline returns it byte for byte. + */ +export function mergeTomlManagedBlock(original: string, block: string | null, markers: TomlBlockMarkers): string { + const span = findBlock(original, markers); + if (span === "malformed") throw new Error(`a failproofai marker (${markers.begin}) is missing its pair`); + if (span) { + const before = original.slice(0, span.start); + const after = original.slice(span.end); + if (block !== null) return before + block + after; + const trimmed = before.endsWith("\n\n") && after === "" ? before.slice(0, -1) : before; + return trimmed + after; + } + if (block === null) return original; + if (original === "") return block; + return `${original}${original.endsWith("\n") ? "\n" : "\n\n"}${block}`; +} + +/** A TOML basic string. JSON's string escapes are a subset of TOML's. */ +export function tomlString(value: string): string { + return JSON.stringify(value); +} diff --git a/src/hooks/uninstall-cli.ts b/src/hooks/uninstall-cli.ts index 158e4225f..70362639c 100644 --- a/src/hooks/uninstall-cli.ts +++ b/src/hooks/uninstall-cli.ts @@ -48,6 +48,7 @@ import { import { listInstallableIds, getIntegration } from "./integrations"; import type { IntegrationType } from "./types"; import { removeHooks } from "./manager"; +import { removeSelfReportMcp } from "./self-report-install"; import { shellQuote } from "./shell-quote"; import { NO_PRINTED_COMMAND_REASON, sudoCommandLine } from "./system-command"; import { installedAgentSkillDirs, removeAgentSkill } from "./agent-skill"; @@ -338,6 +339,19 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< } } + // Self Reports: failproofai's MCP server comes out of every agent, hooked or + // not, so nothing is left pointing at a CLI or daemon this run removes. + try { + const mcp = removeSelfReportMcp({ quiet: true }); + const removedFrom = mcp.filter((r) => r.action === "removed").length; + if (removedFrom > 0) lines.push(kit.ok(`Removed the Self Reports MCP server from ${many(removedFrom, "agent config")}.`)); + for (const r of mcp.filter((x) => x.status === "error")) { + failures.push(`Could not remove the Self Reports MCP server from ${r.path}: ${r.detail ?? "unknown error"}`); + } + } catch (err) { + failures.push(`Could not remove the Self Reports MCP server: ${errText(err)}`); + } + if (found.skillDirs.length > 0) { const left = found.skillDirs.length - removeAgentSkill().length; if (left === 0) lines.push(kit.ok(`Removed the failproofai skill from ${many(found.skillDirs.length, "agent folder")}.`)); From ce7f64471d20e65e5e26851543d98df5a9a756b2 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 25 Nov 2026 21:41:18 +0530 Subject: [PATCH 07/54] [self-reports] Integrate the parts: shared settings reader, in-process sync, every tool spelling, golden files - Installer reads self-report.json through src/hooks/self-report.ts; the CLI calls syncSelfReportMcp / selfReportRegistrationStatus directly and lists `self-report sync` on its help page. - isSelfReportToolName and the SDK's isSelfReportTool cover each agent's spelling (incl. Factory's failproofai___report); Cursor's beforeMCPExecution matches on mcp_server_name and answers {permission: allow}. - test-fixtures/self-report/ golden files pin the description, schema, categories, tool names, server-recorded list and event fields across Rust, the CLI and the TS SDK; the stdio fallback writes fields in SDK wire order. - The daemon's sync child is refused unless the daemon runs as the owner of the failproofai home, and gets that home explicitly. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/self-report-golden.test.ts | 109 +++++++++++++++++ __tests__/hooks/self-report-handler.test.ts | 45 +++++++ bin/failproofai.mjs | 9 +- crates/failproofaid/src/self_report.rs | 95 ++++++++++++++- crates/fpai-collect/src/self_report.rs | 111 ++++++++++++++++++ sdk/typescript/src/self-report-spec.ts | 43 +++++-- .../test/self-report-golden.test.ts | 66 +++++++++++ src/hooks/handler.ts | 15 ++- src/hooks/self-report-cli.ts | 79 ++++++------- src/hooks/self-report-install.ts | 54 +++------ src/hooks/self-report-mcp.ts | 3 +- src/hooks/self-report-names.ts | 39 ++++-- src/hooks/self-report.ts | 1 + .../self-report/categories.golden.json | 26 ++++ .../description-guidance.golden.txt | 12 ++ .../self-report/description.golden.txt | 10 ++ .../self-report/event-fields.golden.json | 5 + .../self-report/input-schema.golden.json | 1 + .../self-report/server-records.golden.txt | 9 ++ .../self-report/tool-names.golden.txt | 11 ++ 20 files changed, 631 insertions(+), 112 deletions(-) create mode 100644 __tests__/hooks/self-report-golden.test.ts create mode 100644 sdk/typescript/test/self-report-golden.test.ts create mode 100644 test-fixtures/self-report/categories.golden.json create mode 100644 test-fixtures/self-report/description-guidance.golden.txt create mode 100644 test-fixtures/self-report/description.golden.txt create mode 100644 test-fixtures/self-report/event-fields.golden.json create mode 100644 test-fixtures/self-report/input-schema.golden.json create mode 100644 test-fixtures/self-report/server-records.golden.txt create mode 100644 test-fixtures/self-report/tool-names.golden.txt diff --git a/__tests__/hooks/self-report-golden.test.ts b/__tests__/hooks/self-report-golden.test.ts new file mode 100644 index 000000000..b70d2c17d --- /dev/null +++ b/__tests__/hooks/self-report-golden.test.ts @@ -0,0 +1,109 @@ +// @vitest-environment node +/** + * Self Reports: the CLI side of the shared golden files in + * test-fixtures/self-report/. The Rust daemon (crates/fpai-collect) and the + * TypeScript SDK (sdk/typescript) are tested against the same files, so the + * tool description, input schema, default categories, recognised tool names, + * server-recorded integrations and the `self_report` event's fields cannot + * drift apart between them. Change a golden file only together with every + * implementation. + */ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { + SELF_REPORT_DEFAULT_CATEGORIES, + SELF_REPORT_SERVER_RECORDS, + describeSelfReportTool, + isSelfReportCursorCall, + isSelfReportToolName, + selfReportInputSchema, +} from "../../src/hooks/self-report"; +import { writeSelfReportEvent } from "../../src/hooks/self-report-mcp"; + +const ROOT = resolve(__dirname, "..", ".."); +const GOLDEN = join(ROOT, "test-fixtures", "self-report"); +const golden = (name: string) => readFileSync(join(GOLDEN, name), "utf8"); +const lines = (name: string) => golden(name).split("\n").filter((l) => l !== ""); + +describe("Self Reports golden files (CLI)", () => { + it("builds the description byte for byte", () => { + expect(describeSelfReportTool(SELF_REPORT_DEFAULT_CATEGORIES, null)).toBe(golden("description.golden.txt")); + expect( + describeSelfReportTool(SELF_REPORT_DEFAULT_CATEGORIES, "Report a missing repository as missing_context."), + ).toBe(golden("description-guidance.golden.txt")); + }); + + it("builds the input schema byte for byte", () => { + expect(`${JSON.stringify(selfReportInputSchema(SELF_REPORT_DEFAULT_CATEGORIES))}\n`).toBe(golden("input-schema.golden.json")); + }); + + it("ships the six default categories", () => { + expect(SELF_REPORT_DEFAULT_CATEGORIES).toEqual(JSON.parse(golden("categories.golden.json"))); + }); + + it("recognises every per-agent spelling of the tool, and nothing near it", () => { + for (const name of lines("tool-names.golden.txt")) { + expect(isSelfReportToolName(name), name).toBe(true); + expect(isSelfReportToolName(name.toUpperCase()), name).toBe(true); + } + for (const name of ["report", "MCP:report", "mcp__other__report", "failproofai_report_x", "xfailproofai__report", "failproofai"]) { + expect(isSelfReportToolName(name), name).toBe(false); + } + }); + + it("recognises Cursor's MCP hook only with the failproofai server name", () => { + expect(isSelfReportCursorCall({ tool_name: "report", mcp_server_name: "failproofai" })).toBe(true); + expect(isSelfReportCursorCall({ tool_name: "MCP:report", mcp_server_name: "failproofai" })).toBe(true); + expect(isSelfReportCursorCall({ tool_name: "report", mcp_server_name: "linear" })).toBe(false); + expect(isSelfReportCursorCall({ tool_name: "report" })).toBe(false); + expect(isSelfReportCursorCall({ tool_name: "MCP:report" })).toBe(false); + expect(isSelfReportCursorCall({ tool_name: "search", mcp_server_name: "failproofai" })).toBe(false); + }); + + it("keeps the TypeScript SDK's tool-name list equal to the golden list", () => { + const src = readFileSync(join(ROOT, "sdk", "typescript", "src", "self-report-spec.ts"), "utf8"); + const block = src.match(/SELF_REPORT_TOOL_SPELLINGS[^=]*=\s*Object\.freeze\(\[([\s\S]*?)\]\)/); + expect(block, "SELF_REPORT_TOOL_SPELLINGS in the SDK").not.toBeNull(); + const names = [...block![1].matchAll(/"([^"]+)"/g)].map((m) => m[1]); + expect(names).toEqual(lines("tool-names.golden.txt")); + }); + + it("lists the same server-recorded integrations as the Rust daemon", () => { + expect([...SELF_REPORT_SERVER_RECORDS]).toEqual(lines("server-records.golden.txt")); + const rs = readFileSync(join(ROOT, "crates", "fpai-collect", "src", "self_report.rs"), "utf8"); + const block = rs.match(/pub const SERVER_RECORDS: &\[&str\] = &\[([\s\S]*?)\];/); + expect(block, "SERVER_RECORDS in self_report.rs").not.toBeNull(); + expect([...block![1].matchAll(/"([^"]+)"/g)].map((m) => m[1])).toEqual([...SELF_REPORT_SERVER_RECORDS]); + for (const hooked of ["claude", "codex", "cursor"]) expect(SELF_REPORT_SERVER_RECORDS).not.toContain(hooked); + }); + + describe("the stdio server's fallback event", () => { + let home: string; + let saved: string | undefined; + beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "fpai-sr-golden-")); + saved = process.env.FAILPROOFAI_HOME; + process.env.FAILPROOFAI_HOME = home; + }); + afterEach(() => { + if (saved === undefined) delete process.env.FAILPROOFAI_HOME; + else process.env.FAILPROOFAI_HOME = saved; + rmSync(home, { recursive: true, force: true }); + }); + + it("writes the golden fields in wire order", async () => { + const spec = JSON.parse(golden("event-fields.golden.json")) as { order: string[]; fallbackExtras: string[] }; + const { path, event } = await writeSelfReportEvent({ + integration: "hermes", + category: "looping", + detail: "Same step again.", + cwd: home, + now: Date.parse("2026-11-25T10:00:00Z"), + }); + expect(Object.keys(event)).toEqual([...spec.order, ...spec.fallbackExtras]); + expect(Object.keys(JSON.parse(readFileSync(path, "utf8").trim()))).toEqual([...spec.order, ...spec.fallbackExtras]); + }); + }); +}); diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index 0fdcc72c3..cc0db945d 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -197,4 +197,49 @@ describe("Self Reports short-circuit", () => { const out = await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai__report_evil", {})); expect(out.evaluation?.decision).toBe("deny"); }); + + it.each([ + ["factory", "failproofai___report"], + ["hermes", "mcp_failproofai_report"], + ["antigravity", "mcp_failproofai_report"], + ["opencode", "failproofai_report"], + ["openclaw", "failproofai__report"], + ["goose", "failproofai__report"], + ["pi", "mcp__failproofai__report"], + ["devin", "mcp__failproofai__report"], + ] as const)("allows %s's spelling %s past a deny-everything policy", async (cli, name) => { + const out = await evaluateHookEvent( + "PreToolUse", + cli, + payload(name, { category: "looping", detail: "again" }), + ); + expect(out.evaluation?.decision).toBe("allow"); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + }); + + it("allows and records Cursor's beforeMCPExecution for the failproofai server, with a schema-valid answer", async () => { + const out = await evaluateHookEvent( + "beforeMCPExecution", + "cursor", + payload("report", JSON.stringify({ category: "missing_context", detail: "no repo access" }), { + mcp_server_name: "failproofai", + url: "http://127.0.0.1:4319/mcp?agent=cursor", + }), + ); + expect(out.evaluation?.decision).toBe("allow"); + expect(JSON.parse(out.stdout)).toEqual({ permission: "allow" }); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + const [row] = rows(); + expect(row).toMatchObject({ + eventType: "PreToolUse", + integration: "cursor", + toolName: "mcp__failproofai__report", + selfReport: { category: "missing_context", detail: "no repo access", source: "mcp" }, + }); + }); + + it("does not early-allow Cursor's bare MCP:report without a server name", async () => { + const out = await evaluateHookEvent("preToolUse", "cursor", payload("MCP:report", { category: "looping", detail: "x" })); + expect(out.evaluation?.decision).toBe("deny"); + }); }); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index a20f2a19c..8a40af63d 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -791,9 +791,8 @@ async function runCli() { // Self Reports MCP server in every agent with failproofai hooks, from // ~/.failproofai/self-report.json. The daemon runs it with --quiet whenever // that file's `enabled` (or port) changes; it is idempotent. - // TODO(merge): "self-report" joins SUBCOMMANDS, the help index and its own - // help page with the `self-report status|enable|disable|test` hunk; until - // then `self-report sync --help` falls through to the index. + // Dispatched ahead of the status|enable|disable|test branch below, which + // lists it on the `self-report --help` page. if (args[0] === "self-report" && args[1] === "sync") { const subArgs = args.slice(2); if (subArgs.includes("--help") || subArgs.includes("-h")) { @@ -1078,7 +1077,7 @@ async function runCli() { ["failproofai self-report enable [options]", "Turn it on for this machine"], ["failproofai self-report disable", "Turn it off for this machine"], ["failproofai self-report test --agent ", "Send one test report end to end"], - // TODO(merge): the installer part adds its `sync` row here. + ["failproofai self-report sync [--quiet]", "Update each hooked agent's MCP entry (the daemon runs this)"], ], options: [ ["--categories-file ", "JSON list of {name, description}; replaces the defaults"], @@ -1092,8 +1091,6 @@ async function runCli() { }); process.exit(0); } - // TODO(merge): `self-report sync` (installer part) dispatches here, ahead - // of runSelfReportCommand, in its own hunk. lastSubcommand = "self-report"; const { runSelfReportCommand } = await import("../src/hooks/self-report-cli"); const result = await runSelfReportCommand(subArgs); diff --git a/crates/failproofaid/src/self_report.rs b/crates/failproofaid/src/self_report.rs index b1b38d554..78591952b 100644 --- a/crates/failproofaid/src/self_report.rs +++ b/crates/failproofaid/src/self_report.rs @@ -243,7 +243,30 @@ fn run_sync_once() { ); return; }; - match run_with_timeout(&format!("{cli} self-report sync --quiet"), SYNC_TIMEOUT) { + // The service runs as its user (`failproofaid@`, `User=` + an + // explicit `HOME=`), so the child inherits that account and home. Checked + // rather than assumed: a daemon started as root over someone else's home + // (`sudo -E`, a hand-written unit without `User=`) would have root rewrite + // that person's agent configs, and one whose home resolves to root's would + // register the server where the user's agents never look. + let home = match crate::paths::failproofai_home() { + Ok(home) => home, + Err(err) => { + tracing::warn!("Self Reports sync skipped: {err}"); + return; + } + }; + // SAFETY: geteuid has no preconditions and cannot fail. + let euid = unsafe { libc::geteuid() }; + if let Some(problem) = sync_identity_problem(&home, euid) { + tracing::warn!("Self Reports sync skipped: {problem}"); + return; + } + match run_with_timeout( + &format!("{cli} self-report sync --quiet"), + &home, + SYNC_TIMEOUT, + ) { Ok(Some(0)) => tracing::info!("Self Reports agent configs synced"), Ok(Some(code)) => tracing::warn!("`failproofai self-report sync` failed (exit {code})"), Ok(None) => tracing::warn!("`failproofai self-report sync` was killed (timeout or signal)"), @@ -253,11 +276,33 @@ fn run_sync_once() { /// Run `command` under `sh -c` in its own process group; kill the group after /// `timeout`. `Ok(None)`: it ended by a signal (including the timeout's). -fn run_with_timeout(command: &str, timeout: Duration) -> io::Result> { +/// Why `self-report sync` must not run as this process for `home`, if it must +/// not: the home (`~/.failproofai`, else the directory that would hold it) +/// belongs to another account than the one the daemon runs as. +fn sync_identity_problem(home: &Path, euid: u32) -> Option { + use std::os::unix::fs::MetadataExt; + let probe = if home.exists() { + home + } else { + home.parent().unwrap_or(home) + }; + let owner = std::fs::metadata(probe).ok()?.uid(); + (owner != euid).then(|| { + format!( + "{} belongs to uid {owner} but the daemon runs as uid {euid}; run the service as that user \ + (failproofaid@) or run `failproofai self-report sync` as them", + probe.display() + ) + }) +} + +fn run_with_timeout(command: &str, home: &Path, timeout: Duration) -> io::Result> { use std::os::unix::process::CommandExt; let mut child = Command::new("sh") .arg("-c") .arg(command) + // The CLI resolves the same home the daemon read self-report.json from. + .env("FAILPROOFAI_HOME", home) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -490,17 +535,57 @@ mod tests { fn a_sync_that_overruns_is_killed() { let started = Instant::now(); assert_eq!( - run_with_timeout("sleep 30", Duration::from_millis(300)).unwrap(), + run_with_timeout( + "sleep 30", + &std::env::temp_dir(), + Duration::from_millis(300) + ) + .unwrap(), None ); assert!(started.elapsed() < Duration::from_secs(5)); assert_eq!( - run_with_timeout("exit 3", Duration::from_secs(5)).unwrap(), + run_with_timeout("exit 3", &std::env::temp_dir(), Duration::from_secs(5)).unwrap(), Some(3) ); assert_eq!( - run_with_timeout("echo hi", Duration::from_secs(5)).unwrap(), + run_with_timeout("echo hi", &std::env::temp_dir(), Duration::from_secs(5)).unwrap(), Some(0) ); } + + #[test] + fn sync_runs_only_as_the_owner_of_the_home() { + use std::os::unix::fs::MetadataExt; + let dir = temp_path("sync-identity"); + let home = dir.parent().unwrap().to_path_buf(); + let me = std::fs::metadata(&home).unwrap().uid(); + assert_eq!(sync_identity_problem(&home, me), None); + // A home that does not exist yet is judged by its parent. + assert_eq!(sync_identity_problem(&home.join(".failproofai"), me), None); + let other = me.wrapping_add(1); + let problem = sync_identity_problem(&home, other).expect("a mismatch is refused"); + assert!(problem.contains(&format!("uid {me}")), "{problem}"); + assert!(problem.contains(&format!("uid {other}")), "{problem}"); + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn the_sync_child_gets_the_daemons_home() { + let dir = temp_path("sync-env"); + let home = dir.parent().unwrap().to_path_buf(); + let out = home.join("seen"); + let code = run_with_timeout( + &format!("printf %s \"$FAILPROOFAI_HOME\" > '{}'", out.display()), + &home, + Duration::from_secs(10), + ) + .unwrap(); + assert_eq!(code, Some(0)); + assert_eq!( + std::fs::read_to_string(&out).unwrap(), + home.display().to_string() + ); + let _ = std::fs::remove_dir_all(&home); + } } diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index a365e1943..2c3cf82b8 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -1199,4 +1199,115 @@ mod tests { assert!(leftovers.is_empty()); let _ = fs::remove_dir_all(home); } + + // ── Shared golden files (test-fixtures/self-report/) ─────────────────── + // + // The CLI (src/hooks/self-report*.ts) and the TypeScript SDK test against + // the same files, so the description, schema, categories, server-recorded + // list and event fields cannot drift between the three implementations. + + fn golden(name: &str) -> String { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../test-fixtures/self-report") + .join(name); + fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())) + } + + fn golden_lines(name: &str) -> Vec { + golden(name) + .lines() + .filter(|l| !l.is_empty()) + .map(str::to_string) + .collect() + } + + #[test] + fn golden_description_and_schema() { + let cats = default_categories(); + assert_eq!(describe(&cats, None), golden("description.golden.txt")); + assert_eq!( + describe( + &cats, + Some("Report a missing repository as missing_context.") + ), + golden("description-guidance.golden.txt") + ); + let want: Value = serde_json::from_str(&golden("input-schema.golden.json")).unwrap(); + assert_eq!(input_schema(&cats), want); + } + + #[test] + fn golden_default_categories() { + let want: Vec = serde_json::from_str(&golden("categories.golden.json")).unwrap(); + assert_eq!(default_categories(), want); + } + + #[test] + fn golden_server_records() { + let got: Vec = SERVER_RECORDS.iter().map(|s| s.to_string()).collect(); + assert_eq!(got, golden_lines("server-records.golden.txt")); + for hooked in ["claude", "codex", "cursor"] { + assert!(!SERVER_RECORDS.contains(&hooked), "{hooked}"); + } + } + + fn golden_fields() -> (Vec, Vec, Vec) { + let spec: Value = serde_json::from_str(&golden("event-fields.golden.json")).unwrap(); + let list = |k: &str| -> Vec { + spec[k] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_str().unwrap().to_string()) + .collect() + }; + (list("order"), list("optional"), list("fallbackExtras")) + } + + fn keys(v: &Value) -> std::collections::BTreeSet { + v.as_object().unwrap().keys().cloned().collect() + } + + #[test] + fn golden_event_fields_fallback_writer() { + let (order, _, extras) = golden_fields(); + let home = temp_home("golden-fallback"); + let report = Report { + category: "looping".into(), + detail: "Same step again.".into(), + }; + let event = fallback_event(&home, "hermes", Some("/tmp/p"), &report, 1_764_064_800_000); + let want: std::collections::BTreeSet = + order.iter().chain(extras.iter()).cloned().collect(); + assert_eq!(keys(&event), want); + let _ = fs::remove_dir_all(&home); + } + + #[test] + fn golden_event_fields_hook_row() { + let (order, optional, extras) = golden_fields(); + let row: crate::sources::hooks::transform::HookRow = serde_json::from_value(json!({ + "timestamp": 1_764_064_800_000_i64, + "sessionId": "s1", + "integration": "claude", + "eventType": "PreToolUse", + "toolName": "mcp__failproofai__report", + "decision": "allow", + "toolCallId": "toolu_1", + "selfReport": {"category": "looping", "detail": "again", "source": "mcp"} + })) + .unwrap(); + let events = crate::sources::hooks::transform::to_events(&row, 0, "local"); + let report = events + .iter() + .find(|e| e["type"] == "self_report") + .expect("a self_report event"); + let want: std::collections::BTreeSet = order + .iter() + .chain(optional.iter()) + .chain(extras.iter()) + .cloned() + .collect(); + assert_eq!(keys(report), want); + } } diff --git a/sdk/typescript/src/self-report-spec.ts b/sdk/typescript/src/self-report-spec.ts index 46b74f4f6..67c87e3f7 100644 --- a/sdk/typescript/src/self-report-spec.ts +++ b/sdk/typescript/src/self-report-spec.ts @@ -142,17 +142,44 @@ export function toAnthropicTool(spec: SelfReportSpec): AnthropicTool { } /** - * Whether a tool name is the report tool, in any of the spellings an agent - * gives it: `failproofai_report` (the SDKs), `mcp__failproofai__report` - * (Claude Code, Codex), and the per-agent MCP spellings `failproofai__report`, - * `failproofai.report` and `failproofai/report`. + * Every spelling an agent gives the report tool (case-insensitive, exact): + * `failproofai_report` (the SDKs, OpenCode), `mcp__failproofai__report` + * (Claude Code, Codex, Pi, Factory, Devin), `failproofai___report` (Factory's + * matcher form), `mcp_failproofai_report` (Hermes, Antigravity), + * `failproofai__report` (OpenClaw, Goose), and other server-qualified forms. * - * Mirrors `isSelfReportToolName` in the CLI's `src/hooks/self-report.ts`; this - * package cannot import that, so the two lists must be kept equal by hand. + * Mirrors `isSelfReportToolName` in the CLI's `src/hooks/self-report-names.ts`; + * this package cannot import that, so both are tested against the same golden + * list (`test-fixtures/self-report/tool-names.golden.txt` in the repo). */ -export function isSelfReportTool(name: unknown): boolean { +export const SELF_REPORT_TOOL_SPELLINGS: ReadonlyArray = Object.freeze([ + "mcp__failproofai__report", + "failproofai___report", + "failproofai__report", + "failproofai_report", + "failproofai.report", + "failproofai/report", + "failproofai:report", + "mcp_failproofai_report", + "mcp__failproofai_report", + "mcp:failproofai:report", + "mcp:failproofai/report", +]); + +const SPELLINGS = new Set(SELF_REPORT_TOOL_SPELLINGS); + +/** + * Whether a tool is the report tool. `server` is for hosts that name an MCP + * tool and its server separately (Cursor's `tool_name` + `mcp_server_name`): + * a bare `report` matches only when the server is `failproofai`. + */ +export function isSelfReportTool(name: unknown, server?: unknown): boolean { if (typeof name !== "string") return false; - return /^(?:mcp__failproofai__report|failproofai(?:__|_|\.|\/)report)$/.test(name); + const lower = name.toLowerCase(); + if (SPELLINGS.has(lower)) return true; + return ( + typeof server === "string" && server.toLowerCase() === "failproofai" && (lower === "report" || lower === "mcp:report") + ); } /** diff --git a/sdk/typescript/test/self-report-golden.test.ts b/sdk/typescript/test/self-report-golden.test.ts new file mode 100644 index 000000000..970dc9757 --- /dev/null +++ b/sdk/typescript/test/self-report-golden.test.ts @@ -0,0 +1,66 @@ +import { readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; + +import { describe, expect, it } from "vitest"; + +import * as schema from "../src/schema.js"; +import { + DEFAULT_SELF_REPORT_CATEGORIES, + SELF_REPORT_TOOL_SPELLINGS, + describeSelfReport, + isSelfReportTool, + selfReportInputSchema, +} from "../src/self-report-spec.js"; + +/** + * The SDK side of the shared golden files in the repository's + * test-fixtures/self-report/. The Rust daemon and the CLI are tested against + * the same files, so the tool description, input schema, default categories, + * tool names and `self_report` event fields cannot drift between them. + */ +const GOLDEN = resolve(__dirname, "..", "..", "..", "test-fixtures", "self-report"); +const golden = (name: string): string => readFileSync(join(GOLDEN, name), "utf8"); +const lines = (name: string): string[] => golden(name).split("\n").filter((l) => l !== ""); + +describe("Self Reports golden files (TypeScript SDK)", () => { + it("builds the description byte for byte", () => { + expect(describeSelfReport(DEFAULT_SELF_REPORT_CATEGORIES, null)).toBe(golden("description.golden.txt")); + expect( + describeSelfReport(DEFAULT_SELF_REPORT_CATEGORIES, "Report a missing repository as missing_context."), + ).toBe(golden("description-guidance.golden.txt")); + }); + + it("builds the input schema byte for byte", () => { + expect(`${JSON.stringify(selfReportInputSchema(DEFAULT_SELF_REPORT_CATEGORIES))}\n`).toBe( + golden("input-schema.golden.json"), + ); + }); + + it("ships the six default categories", () => { + expect(DEFAULT_SELF_REPORT_CATEGORIES).toEqual(JSON.parse(golden("categories.golden.json"))); + }); + + it("recognises every per-agent spelling of the tool", () => { + expect([...SELF_REPORT_TOOL_SPELLINGS]).toEqual(lines("tool-names.golden.txt")); + for (const name of lines("tool-names.golden.txt")) expect(isSelfReportTool(name), name).toBe(true); + expect(isSelfReportTool("report")).toBe(false); + expect(isSelfReportTool("MCP:report")).toBe(false); + expect(isSelfReportTool("report", "failproofai")).toBe(true); + expect(isSelfReportTool("MCP:report", "failproofai")).toBe(true); + expect(isSelfReportTool("report", "linear")).toBe(false); + }); + + it("writes the golden event fields in wire order", () => { + const spec = JSON.parse(golden("event-fields.golden.json")) as { order: string[]; optional: string[] }; + const base = { + timestamp: "2026-11-25T10:00:00.000000Z", + sessionId: "s1", + agentId: "a1", + category: "looping", + detail: "Same step again.", + source: "sdk", + }; + expect(Object.keys(schema.selfReportEvent(base))).toEqual(spec.order); + expect(Object.keys(schema.selfReportEvent({ ...base, toolCallId: "call_1" }))).toEqual([...spec.order, ...spec.optional]); + }); +}); diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index a89209839..de125a1c8 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -55,7 +55,7 @@ import { } from "./policy-authority"; import type { CustomHook } from "./policy-types"; import { persistHookActivity } from "./hook-activity-store"; -import { isSelfReportToolName, selfReportArgs, SELF_REPORT_SERVER_RECORDS } from "./self-report"; +import { isSelfReportCursorCall, isSelfReportToolName, selfReportArgs, SELF_REPORT_MCP_TOOL_NAME, SELF_REPORT_SERVER_RECORDS } from "./self-report"; import { deliveryHealth, deliveryHealthLine } from "./delivery-health"; import { trackHookEvent, flushHookTelemetry } from "./hook-telemetry"; import * as hookTelemetry from "./hook-telemetry"; @@ -777,6 +777,11 @@ export async function evaluateHookEvent( // filter and policy bodies (`ctx.toolName === "Bash"`) see the canonical // form. Mutating `parsed.tool_name` keeps the activity store + telemetry // tagging consistent (they read from `parsed.tool_name`). + // Cursor's MCP hook names our tool `report` and the server separately; + // file it under the one name before anything else reads the tool name. + if (cli === "cursor" && isSelfReportCursorCall(parsed)) { + parsed.tool_name = SELF_REPORT_MCP_TOOL_NAME; + } const rawToolName = parsed.tool_name as string | undefined; const canonicalToolName = canonicalizeToolName(rawToolName, cli); if (canonicalToolName !== rawToolName) { @@ -823,10 +828,16 @@ export async function evaluateHookEvent( if ( isSelfReportToolName(parsed.tool_name) && (canonicalEventType === "PreToolUse" || + (cli === "cursor" && eventType === "beforeMCPExecution") || canonicalEventType === "PermissionRequest" || canonicalEventType === "PostToolUse") ) { - return recordSelfReportCall(canonicalEventType, cli, parsed, session, arrivedAt, startTime); + const outcome = recordSelfReportCall( + canonicalEventType === "PostToolUse" || canonicalEventType === "PermissionRequest" ? canonicalEventType : "PreToolUse", + cli, parsed, session, arrivedAt, startTime, + ); + // beforeMCPExecution requires a schema-valid answer: anything else blocks the call. + return eventType === "beforeMCPExecution" ? { ...outcome, stdout: JSON.stringify({ permission: "allow" }) } : outcome; } const runtimeAgent = readRuntimeAgentIdentity( diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts index a8fd992a2..de1623dca 100644 --- a/src/hooks/self-report-cli.ts +++ b/src/hooks/self-report-cli.ts @@ -1,10 +1,9 @@ /** * `failproofai self-report status | enable | disable | test`. * - * `sync` is another part's (it registers the MCP server in every agent); this - * module only calls it, as the subprocess `failproofai self-report sync - * --quiet` that contract §6 defines, so the two halves meet at a command line - * rather than at a function name. + * `sync` (registering the MCP server in every agent) lives in + * self-report-install.ts; enable/disable call it in process, and bin keeps the + * `failproofai self-report sync --quiet` subcommand the daemon runs (contract §6). * * Returns lines and an exit code like the other `*-cli.ts` modules; bin prints * them. @@ -29,6 +28,7 @@ import { type SelfReportCategory, } from "./self-report"; import { INTEGRATION_TYPES } from "./types"; +import { selfReportRegistrationStatus, syncSelfReportMcp } from "./self-report-install"; export interface SelfReportCliResult { exitCode: number; @@ -96,25 +96,26 @@ async function selfReportProbe(url: string): Promise { } } -/** Per-agent registration, from the installer part once it is merged. */ -async function selfReportRegistrationLines(): Promise { - // TODO(merge): import "./self-report-install" statically once it exists. A - // computed specifier keeps the bundler from failing on a module this branch - // does not have yet. - const spec = "./self-report-install"; - try { - const mod = (await import(/* @vite-ignore */ spec)) as Record; - const fn = mod.selfReportRegistrationStatus; - if (typeof fn !== "function") return ["Agents: registration state not available in this build"]; - const rows = (await (fn as () => unknown)()) as Array<{ integration: string; state: string; transport?: string }>; - if (!Array.isArray(rows) || rows.length === 0) return ["Agents: none with failproofai hooks"]; - return [ - "Agents:", - ...rows.map((r) => ` ${String(r.integration).padEnd(12)} ${r.state}${r.transport ? ` (${r.transport})` : ""}`), - ]; - } catch { - return ["Agents: registration state not available in this build"]; - } +/** Per-agent registration state. */ +function selfReportRegistrationLines(): string[] { + const rows = selfReportRegistrationStatus(); + const hooked = rows.filter((r) => r.hooked || r.registered || r.conflict || r.error); + if (hooked.length === 0) return ["Agents: none with failproofai hooks"]; + return [ + "Agents:", + ...hooked.map((r) => { + const state = r.error + ? `unreadable (${r.error})` + : r.conflict + ? "another failproofai MCP server is configured; left alone" + : r.registered + ? `registered (${r.transport})` + : r.hooked + ? "not registered" + : "registered, no hooks"; + return ` ${r.agent.padEnd(12)} ${state}`; + }), + ]; } async function selfReportStatus(deps: SelfReportCliDeps): Promise { @@ -136,26 +137,24 @@ async function selfReportStatus(deps: SelfReportCliDeps): Promise selfReportProbe(url)); const healthy = await probe(settings.mcp.url, settings.mcp.port); lines.push(`Endpoint: ${settings.mcp.url} ${healthy ? "(answering)" : "(not answering; stdio `failproofai mcp` still works)"}`); - lines.push(...(await selfReportRegistrationLines())); + lines.push(...selfReportRegistrationLines()); return { exitCode: 0, lines }; } -/** `failproofai self-report sync --quiet`, if this build has it. */ -async function selfReportSync(deps: SelfReportCliDeps): Promise { +/** Update every hooked agent's MCP entry to match the settings just written. */ +function selfReportSync(deps: SelfReportCliDeps): string[] { if (deps.skipSync) return []; - const run = await selfReportRunChild([...selfReportCliCommand(deps), "self-report", "sync", "--quiet"], "", 60_000, deps.cwd); - if (run.code === 0) return ["Agents updated."]; - if (run.code === SELF_REPORT_SYNC_UNAVAILABLE) { - return ["Agent configs were not changed: this build cannot register the MCP server yet."]; + try { + const results = syncSelfReportMcp({ quiet: true }); + if (results.some((r) => r.status === "error")) { + return ["▲ Could not update every agent's MCP settings. Run `failproofai self-report sync` to see why."]; + } + return ["Agents updated."]; + } catch { + return ["▲ Could not update your agents' MCP settings. Run `failproofai self-report sync` to see why."]; } - return [ - "▲ Could not update your agents' MCP settings. Run `failproofai self-report sync` to see why.", - ]; } -/** Exit code `self-report sync` returns in a build without the installer part. */ -export const SELF_REPORT_SYNC_UNAVAILABLE = 3; - function selfReportFlag(args: string[], name: string): { value?: string; error?: string } { const i = args.indexOf(name); if (i < 0) return {}; @@ -205,7 +204,7 @@ async function selfReportEnable(args: string[], deps: SelfReportCliDeps): Promis "✓ Self Reports is on.", ` Categories: ${written.categories.map((c) => c.name).join(", ")}${categories ? "" : " (defaults)"}`, ` Settings: ${selfReportSettingsFile()}`, - ...(await selfReportSync(deps)).map((l) => (l.startsWith("▲") ? l : ` ${l}`)), + ...selfReportSync(deps).map((l) => (l.startsWith("▲") ? l : ` ${l}`)), ]; return { exitCode: 0, lines }; } @@ -219,7 +218,7 @@ async function selfReportDisable(args: string[], deps: SelfReportCliDeps): Promi writeEffectiveSelfReport({ enabled: false, categories: previous?.categories, guidance: previous?.guidance }); return { exitCode: 0, - lines: ["✓ Self Reports is off.", ...(await selfReportSync(deps)).map((l) => (l.startsWith("▲") ? l : ` ${l}`))], + lines: ["✓ Self Reports is off.", ...selfReportSync(deps).map((l) => (l.startsWith("▲") ? l : ` ${l}`))], }; } @@ -348,10 +347,6 @@ export async function runSelfReportCommand(args: string[], deps: SelfReportCliDe return await selfReportDisable(rest, deps); case "test": return await selfReportTest(rest, deps); - case "sync": - // TODO(merge): the installer part implements `sync` in bin; this is - // only reached in a build without it. - return { exitCode: SELF_REPORT_SYNC_UNAVAILABLE, lines: ["`self-report sync` is not available in this build."] }; default: return { exitCode: 1, lines: [verb ? `Unknown self-report command: ${verb}.` : "Missing self-report command.", "Use status, enable, disable or test."] }; } diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index 6baba7637..bec26de24 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -60,7 +60,7 @@ import { writeConfigFileAtomic } from "./safe-config-write"; import { codexHome } from "./codex-system-hooks"; import { claudeConfigDir, getIntegration, readYamlDoc, writeYamlDoc, UnreadableAgentConfigError } from "./integrations"; import { daemonSocketPresent } from "./daemon-client"; -import { failproofaiHome } from "./fp-home"; +import { readEffectiveSelfReport, selfReportPort, selfReportSettingsFile, SELF_REPORT_SERVER_NAME } from "./self-report"; import { listHermesProfiles } from "../../lib/hermes-profiles"; import { listOpenClawProfiles } from "../../lib/openclaw-profiles"; import { INTEGRATION_TYPES, type IntegrationType } from "./types"; @@ -69,13 +69,11 @@ import { mergeTomlManagedBlock, readTomlManagedBlock, tomlString, type TomlBlock // ── Settings (CONTRACT §4) ────────────────────────────────────────────────── /** The MCP server's name in every agent. */ -export const SELF_REPORT_MCP_SERVER_NAME = "failproofai"; -// TODO(merge): import from ./self-report -export const SELF_REPORT_DEFAULT_PORT = 4319; +export { SELF_REPORT_SERVER_NAME as SELF_REPORT_MCP_SERVER_NAME, SELF_REPORT_DEFAULT_PORT } from "./self-report"; -/** `$FAILPROOFAI_HOME/self-report.json`. TODO(merge): import from ./self-report (or fp-home). */ +/** `$FAILPROOFAI_HOME/self-report.json`. */ export function selfReportSettingsPath(): string { - return resolve(failproofaiHome(), "self-report.json"); + return selfReportSettingsFile(); } export interface SelfReportMcpSettings { @@ -84,32 +82,14 @@ export interface SelfReportMcpSettings { } /** - * The bits of self-report.json this module needs. Missing or unparsable file ⇒ - * disabled. TODO(merge): use the settings reader in ./self-report. + * The bits of self-report.json this module needs, through the one settings + * reader in ./self-report. Missing or unparsable file ⇒ disabled, on the port + * a local writer would record. */ export function readSelfReportMcpSettings(path = selfReportSettingsPath()): SelfReportMcpSettings { - const envPort = Number(process.env.FAILPROOFAI_SELF_REPORT_PORT); - const fallbackPort = Number.isInteger(envPort) && envPort > 0 && envPort < 65536 ? envPort : SELF_REPORT_DEFAULT_PORT; - let parsed: unknown; - try { - parsed = JSON.parse(readFileSync(path, "utf8")); - } catch { - return { enabled: false, port: fallbackPort }; - } - if (!parsed || typeof parsed !== "object") return { enabled: false, port: fallbackPort }; - const s = parsed as { enabled?: unknown; mcp?: { port?: unknown; url?: unknown } }; - let port = fallbackPort; - const filePort = s.mcp?.port; - if (typeof filePort === "number" && Number.isInteger(filePort) && filePort > 0 && filePort < 65536) port = filePort; - else if (typeof s.mcp?.url === "string") { - try { - const p = Number(new URL(s.mcp.url).port); - if (p > 0) port = p; - } catch { - // keep the fallback - } - } - return { enabled: s.enabled === true, port }; + const s = readEffectiveSelfReport(path); + if (!s) return { enabled: false, port: selfReportPort() }; + return { enabled: s.enabled, port: s.mcp.port }; } // ── Transports ────────────────────────────────────────────────────────────── @@ -294,8 +274,8 @@ export const SELF_REPORT_MCP_TARGETS: Record = { container: () => ["extensions"], entry: (t) => t.kind === "http" - ? { name: SELF_REPORT_MCP_SERVER_NAME, type: "streamable_http", enabled: true, uri: t.url, envs: {}, env_keys: [], timeout: 300 } - : { name: SELF_REPORT_MCP_SERVER_NAME, type: "stdio", enabled: true, cmd: t.command, args: t.args, envs: {}, env_keys: [], timeout: 300 }, + ? { name: SELF_REPORT_SERVER_NAME, type: "streamable_http", enabled: true, uri: t.url, envs: {}, env_keys: [], timeout: 300 } + : { name: SELF_REPORT_SERVER_NAME, type: "stdio", enabled: true, cmd: t.command, args: t.args, envs: {}, env_keys: [], timeout: 300 }, }, }; @@ -367,7 +347,7 @@ function jsonOps(target: McpTarget, path: string): FileOps { }, }; } - const keyPath = [...container, SELF_REPORT_MCP_SERVER_NAME]; + const keyPath = [...container, SELF_REPORT_SERVER_NAME]; return { container, current: () => classify(getIn(parsed, keyPath)), @@ -388,7 +368,7 @@ function renderTomlBlock(entry: Record): string { TOML_MARKERS.begin, "# Written by failproofai (Self Reports). `failproofai self-report disable` or", "# `failproofai uninstall` removes it. Everything between the markers is replaced.", - `[mcp_servers.${SELF_REPORT_MCP_SERVER_NAME}]`, + `[mcp_servers.${SELF_REPORT_SERVER_NAME}]`, ]; for (const [k, v] of Object.entries(entry)) { if (typeof v === "string") lines.push(`${k} = ${tomlString(v)}`); @@ -416,7 +396,7 @@ function tomlOps(path: string): FileOps { } catch (err) { throw new UnreadableAgentConfigError(path, `it does not parse as TOML (${err instanceof Error ? err.message.split("\n")[0] : String(err)})`); } - const keyPath = ["mcp_servers", SELF_REPORT_MCP_SERVER_NAME]; + const keyPath = ["mcp_servers", SELF_REPORT_SERVER_NAME]; return { container: ["mcp_servers"], current() { @@ -447,7 +427,7 @@ function yamlOps(target: McpTarget, path: string): FileOps { if (typeof js !== "object" || Array.isArray(js)) throw new UnreadableAgentConfigError(path, "its top level is not a mapping"); const container = target.container(js); const holder = doc.getIn(container); - const keyPath = [...container, SELF_REPORT_MCP_SERVER_NAME]; + const keyPath = [...container, SELF_REPORT_SERVER_NAME]; if (holder !== undefined && holder !== null && !isMap(holder)) { return { container, @@ -626,7 +606,7 @@ export function syncSelfReportMcp(opts: SyncSelfReportMcpOptions = {}): SelfRepo if (cur.state === "foreign") { results.push({ agent, path, action: "skipped", transport: null, status: "conflict", - detail: `a "${SELF_REPORT_MCP_SERVER_NAME}" MCP server that failproofai did not write is already configured`, + detail: `a "${SELF_REPORT_SERVER_NAME}" MCP server that failproofai did not write is already configured`, }); continue; } diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts index 4586f0efd..3f3db9ae5 100644 --- a/src/hooks/self-report-mcp.ts +++ b/src/hooks/self-report-mcp.ts @@ -186,10 +186,11 @@ export async function writeSelfReportEvent(input: SelfReportEventInput): Promise session_id: sessionId, agent_id: selfReportAgentId(input.integration, input.cwd), type: "self_report", - environment: await selfReportEnvironment(), category: input.category, detail: input.detail, source: "mcp", + // Wire order as the SDK writers build it: environment after the event's own fields. + environment: await selfReportEnvironment(), integration: input.integration, }; const dir = customAgentsEventsDir(); diff --git a/src/hooks/self-report-names.ts b/src/hooks/self-report-names.ts index b337fb7ce..2908cca69 100644 --- a/src/hooks/self-report-names.ts +++ b/src/hooks/self-report-names.ts @@ -30,20 +30,22 @@ export const SELF_REPORT_DEFAULT_PORT = 4319; * contains `failproofai` and `report` past every policy, and this name is the * one thing that skips them all. * - * - `mcp__failproofai__report`: Claude Code, Codex (and anything copying them). - * - `failproofai__report`: Goose's `__`. - * - `failproofai_report`: the SDK tool, and agents that join with one `_` - * (OpenCode, Copilot). - * - `failproofai.report`, `failproofai/report`, `failproofai:report`: dotted / - * slashed / coloned server-qualified forms other agents use. - * - `mcp_failproofai_report`, `mcp__failproofai_report`: single-underscore - * variants seen in agents that flatten MCP names. - * - * Cursor's preToolUse names MCP calls `MCP:` without the server, which - * cannot be told apart from another server's `report` tool, so it is not here. + * Per agent (installer research, 2026-11-25; see self-report-install.ts): + * - `mcp__failproofai__report`: Claude Code, Codex, Pi, Factory, Devin. + * - `failproofai___report`: Factory's matcher-regex form of the same name. + * - `mcp_failproofai_report`: Hermes, and Antigravity's eager tools. + * - `failproofai_report`: OpenCode (and the SDK tool). + * - `failproofai__report`: OpenClaw and Goose (`__`). + * - Cursor: see `isSelfReportCursorCall`; its preToolUse name `MCP:report` + * carries no server, so it is never matched by name alone. + * - `failproofai.report`, `failproofai/report`, `failproofai:report`, + * `mcp__failproofai_report`, `mcp:failproofai:report`, + * `mcp:failproofai/report`: other server-qualified forms, kept so a + * spelling change in an agent cannot route a report through the policies. */ const SELF_REPORT_TOOL_SPELLINGS: ReadonlySet = new Set([ SELF_REPORT_MCP_TOOL_NAME, + "failproofai___report", "failproofai__report", SELF_REPORT_SDK_TOOL_NAME, "failproofai.report", @@ -60,6 +62,21 @@ export function isSelfReportToolName(name: unknown): boolean { return typeof name === "string" && SELF_REPORT_TOOL_SPELLINGS.has(name.toLowerCase()); } +/** + * Cursor's MCP hook (`beforeMCPExecution`) names the tool bare (`report`) and + * the server separately, as `mcp_server_name` (its key in mcp.json). Only that + * pair identifies our tool: a bare `report`, or preToolUse's `MCP:report` + * without a server name, could be any server's tool and is NOT matched. + */ +export function isSelfReportCursorCall(payload: unknown): boolean { + if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false; + const p = payload as Record; + const server = p.mcp_server_name; + if (typeof server !== "string" || server.toLowerCase() !== SELF_REPORT_SERVER_NAME) return false; + const tool = typeof p.tool_name === "string" ? p.tool_name.toLowerCase() : ""; + return tool === SELF_REPORT_TOOL_NAME || tool === `mcp:${SELF_REPORT_TOOL_NAME}` || isSelfReportToolName(tool); +} + /** * Integrations whose hooks do not see MCP tool calls, so the MCP server itself * records a report (contract §8). Claude Code, Codex and Cursor are recorded by diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts index 17e885b3c..b29b39e15 100644 --- a/src/hooks/self-report.ts +++ b/src/hooks/self-report.ts @@ -33,6 +33,7 @@ export { SELF_REPORT_DEFAULT_PORT, SELF_REPORT_SERVER_RECORDS, isSelfReportToolName, + isSelfReportCursorCall, } from "./self-report-names"; import { SELF_REPORT_DETAIL_MAX, SELF_REPORT_DEFAULT_PORT } from "./self-report-names"; diff --git a/test-fixtures/self-report/categories.golden.json b/test-fixtures/self-report/categories.golden.json new file mode 100644 index 000000000..d319d11e6 --- /dev/null +++ b/test-fixtures/self-report/categories.golden.json @@ -0,0 +1,26 @@ +[ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + }, + { + "name": "cannot_do_request", + "description": "The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating." + }, + { + "name": "invalid_tool_or_credential", + "description": "A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected." + }, + { + "name": "missing_context", + "description": "Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions." + }, + { + "name": "repeated_tool_failure", + "description": "A command or tool failed on several distinct attempts and is blocking you. A single error is not enough." + }, + { + "name": "task_failure", + "description": "You genuinely tried and could not complete the task. Not for refusals or policy blocks." + } +] diff --git a/test-fixtures/self-report/description-guidance.golden.txt b/test-fixtures/self-report/description-guidance.golden.txt new file mode 100644 index 000000000..a6b185a2a --- /dev/null +++ b/test-fixtures/self-report/description-guidance.golden.txt @@ -0,0 +1,12 @@ +Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; do not call it for normal work, clarifying questions or a single error. One call per distinct problem. +Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. + +Categories: +- looping: You keep repeating the same or circular steps without making progress. +- cannot_do_request: The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating. +- invalid_tool_or_credential: A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. +- missing_context: Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. +- repeated_tool_failure: A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. +- task_failure: You genuinely tried and could not complete the task. Not for refusals or policy blocks. + +Report a missing repository as missing_context. \ No newline at end of file diff --git a/test-fixtures/self-report/description.golden.txt b/test-fixtures/self-report/description.golden.txt new file mode 100644 index 000000000..922c27eb9 --- /dev/null +++ b/test-fixtures/self-report/description.golden.txt @@ -0,0 +1,10 @@ +Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; do not call it for normal work, clarifying questions or a single error. One call per distinct problem. +Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. + +Categories: +- looping: You keep repeating the same or circular steps without making progress. +- cannot_do_request: The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating. +- invalid_tool_or_credential: A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. +- missing_context: Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. +- repeated_tool_failure: A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. +- task_failure: You genuinely tried and could not complete the task. Not for refusals or policy blocks. \ No newline at end of file diff --git a/test-fixtures/self-report/event-fields.golden.json b/test-fixtures/self-report/event-fields.golden.json new file mode 100644 index 000000000..c3e05f61f --- /dev/null +++ b/test-fixtures/self-report/event-fields.golden.json @@ -0,0 +1,5 @@ +{ + "order": ["timestamp", "session_id", "agent_id", "type", "category", "detail", "source", "environment"], + "optional": ["tool_call_id"], + "fallbackExtras": ["integration"] +} diff --git a/test-fixtures/self-report/input-schema.golden.json b/test-fixtures/self-report/input-schema.golden.json new file mode 100644 index 000000000..4b468f14c --- /dev/null +++ b/test-fixtures/self-report/input-schema.golden.json @@ -0,0 +1 @@ +{"type":"object","properties":{"category":{"type":"string","enum":["looping","cannot_do_request","invalid_tool_or_credential","missing_context","repeated_tool_failure","task_failure"]},"detail":{"type":"string","description":"One factual sentence: what is blocking you."}},"required":["category","detail"],"additionalProperties":false} diff --git a/test-fixtures/self-report/server-records.golden.txt b/test-fixtures/self-report/server-records.golden.txt new file mode 100644 index 000000000..65edc041c --- /dev/null +++ b/test-fixtures/self-report/server-records.golden.txt @@ -0,0 +1,9 @@ +openclaw +pi +devin +hermes +goose +factory +antigravity +copilot +opencode diff --git a/test-fixtures/self-report/tool-names.golden.txt b/test-fixtures/self-report/tool-names.golden.txt new file mode 100644 index 000000000..ee2992ff7 --- /dev/null +++ b/test-fixtures/self-report/tool-names.golden.txt @@ -0,0 +1,11 @@ +mcp__failproofai__report +failproofai___report +failproofai__report +failproofai_report +failproofai.report +failproofai/report +failproofai:report +mcp_failproofai_report +mcp__failproofai_report +mcp:failproofai:report +mcp:failproofai/report From 995f19973ee7f9836333f4c52abf7f208a269d23 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 25 Nov 2026 21:42:10 +0530 Subject: [PATCH 08/54] =?UTF-8?q?feat(failproofai-sdk):=20Self=20Reports?= =?UTF-8?q?=20=E2=80=94=20self=5Freport=20event,=20report=20tool=20helpers?= =?UTF-8?q?=20and=20framework=20tools?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the self_report event (category, detail, source=sdk, optional tool_call_id) with event.self_report()/failproofai_sdk.self_report(), self_report_spec() built from $FAILPROOFAI_HOME/self-report.json (defaults when missing, unparsable, disabled or invalid), openai_tool(), openai_responses_tool(), anthropic_tool(), handle_tool_call() and is_self_report_tool(); ready-made self_report_tool() for LangChain/LangGraph, CrewAI, LlamaIndex and Pydantic AI (plus FailproofAI(self_report=True)). Still zero runtime dependencies. Docs, skill references and changelog. Co-Authored-By: Claude Opus 5.5 --- sdk/python/CHANGELOG.md | 15 + sdk/python/README.md | 81 +++- sdk/python/docs/README.md | 8 +- sdk/python/docs/crewai/README.md | 24 + sdk/python/docs/langgraph/README.md | 26 ++ sdk/python/docs/llama_index/README.md | 24 + sdk/python/docs/manual/README.md | 32 +- sdk/python/docs/pydantic_ai/README.md | 31 ++ sdk/python/failproofai_sdk/__init__.py | 21 +- sdk/python/failproofai_sdk/_events.py | 129 ++++++ sdk/python/failproofai_sdk/_schema.py | 29 ++ sdk/python/failproofai_sdk/_self_report.py | 416 +++++++++++++++++ .../failproofai_sdk/integrations/crewai.py | 88 ++++ .../failproofai_sdk/integrations/langchain.py | 73 +++ .../integrations/llama_index.py | 79 ++++ .../integrations/pydantic_ai.py | 63 +++ sdk/python/skill/SKILL.md | 7 +- sdk/python/skill/references/events.md | 39 +- sdk/python/skill/references/frameworks.md | 18 + sdk/python/skill/references/integration.md | 2 +- sdk/python/skill/references/typescript.md | 2 +- sdk/python/tests/integrations/test_crewai.py | 51 +++ .../tests/integrations/test_langchain.py | 83 +++- .../tests/integrations/test_llama_index.py | 46 ++ .../tests/integrations/test_pydantic_ai.py | 86 +++- sdk/python/tests/test_self_report.py | 421 ++++++++++++++++++ sdk/python/tests/test_server_contract.py | 10 +- sdk/python/tests/test_wire_format.py | 2 + 28 files changed, 1887 insertions(+), 19 deletions(-) create mode 100644 sdk/python/failproofai_sdk/_self_report.py create mode 100644 sdk/python/tests/test_self_report.py diff --git a/sdk/python/CHANGELOG.md b/sdk/python/CHANGELOG.md index b46f1243b..4ee998511 100644 --- a/sdk/python/CHANGELOG.md +++ b/sdk/python/CHANGELOG.md @@ -11,6 +11,21 @@ see `scripts/changelog-section.py`. ## 0.0.1b7 — 2026-10-16 +### Features + +- **Self Reports.** A tool the agent calls when it is stuck, recorded as a new + `self_report` event (`category`, `detail`, `source: "sdk"`, optional + `tool_call_id`) in the current session and agent scope. New API: + `failproofai_sdk.self_report()` / `event.self_report()`, `self_report_spec()`, + `openai_tool()`, `openai_responses_tool()`, `anthropic_tool()`, + `handle_tool_call()` (always answers `Recorded.`, never raises into the agent + loop) and `is_self_report_tool()`. Ready-made tools: + `integrations..self_report_tool()`, + and the Pydantic AI capability adds it with `FailproofAI(self_report=True)` / + `instrument("pydantic_ai", self_report=True)`. Categories and guidance come from + `$FAILPROOFAI_HOME/self-report.json`, else six defaults. Still no runtime + dependencies. + ### Dependencies - **The CrewAI extra no longer brings ChromaDB.** crewai 1.15.44 made `chromadb` an diff --git a/sdk/python/README.md b/sdk/python/README.md index 5931ed9ab..63b922d70 100644 --- a/sdk/python/README.md +++ b/sdk/python/README.md @@ -74,6 +74,69 @@ standard library. See `skill/references/frameworks.md` for the per-framework mapping, and `docs/` for a per-framework integration guide with runnable examples beside it. +## Self Reports + +A tool your agent calls when it is stuck — looping, a broken tool or credential, +missing context, a request it cannot do, a task it failed. Each call becomes a +`self_report` event on the session, shown on the Self Reports page in +FailproofAI Cloud. The tool always answers `Recorded.` and changes nothing. + +Ready-made tools, one per framework (each imports its framework only when called): + +```python +from failproofai_sdk.integrations.langchain import self_report_tool # StructuredTool (LangChain / LangGraph) +from failproofai_sdk.integrations.crewai import self_report_tool # crewai BaseTool +from failproofai_sdk.integrations.llama_index import self_report_tool # FunctionTool +from failproofai_sdk.integrations.pydantic_ai import self_report_tool # pydantic_ai Tool + +tools = [*my_tools, self_report_tool()] +``` + +Pydantic AI can also add it through the capability, opt in: +`FailproofAI(self_report=True)` or `failproofai_sdk.instrument("pydantic_ai", self_report=True)`. + +With a raw provider API: + +```python +tools = [failproofai_sdk.openai_tool(), *my_tools] # or openai_responses_tool(), anthropic_tool() + +for call in message.tool_calls: + if failproofai_sdk.is_self_report_tool(call.function.name): + output = failproofai_sdk.handle_tool_call( + call.function.name, call.function.arguments, tool_call_id=call.id + ) # "Recorded."; arguments may be a dict or a JSON string +``` + +Or record one directly, in the current session and agent scope: + +```python +failproofai_sdk.self_report("invalid_tool_or_credential", "The search API rejects our key.") +``` + +- **Spec.** `failproofai_sdk.self_report_spec()` returns `{name: "failproofai_report", + description, input_schema}`. The categories (the `category` enum) and any extra + guidance come from `$FAILPROOFAI_HOME/self-report.json` — written by the daemon + from your org's Cloud setting, or by `failproofai self-report enable` — read each + time a spec is built. When that file is missing, unreadable or disabled, six + defaults are used (`looping`, `cannot_do_request`, `invalid_tool_or_credential`, + `missing_context`, `repeated_tool_failure`, `task_failure`): adding the tool is + itself the opt-in. Pass `categories=[...]` (and `guidance=`) to any helper to + override. +- **Event.** `{type: "self_report", category, detail, source: "sdk", tool_call_id?}` + plus the usual `session_id` / `agent_id` / `timestamp` / `environment`. An + unknown category is recorded as given; `detail` is cut to 2,000 characters. +- **Session.** Most specific first: an explicit `session_id=` (framework tools + also take one on the factory); the run the adapter is recording (framework + tools, when instrumented); the open `tool_use` for this call (by + `tool_call_id`, then the newest open report-tool call) within the enclosing + session; the enclosing `session()` / `agent()` scope; otherwise the report is + filed under `"unattributed"` with one warning. Unlike the other event methods, + a missing session never raises, and the tool helpers never raise into your + agent loop at all. +- **Hiding it.** `failproofai_sdk.is_self_report_tool(name)` is true for + `failproofai_report` and the coding-agent MCP spellings + (`mcp__failproofai__report`, `failproofai__report`, ...). + ## OpenTelemetry (opt in) Already emitting OpenTelemetry spans? Install `opentelemetry-sdk` separately, @@ -439,6 +502,22 @@ failproofai_sdk.event.error( --- +### `event.self_report()` + +The agent reports it is stuck. See [Self Reports](#self-reports). + +```python +failproofai_sdk.event.self_report( + "looping", # category: str, required (recorded as given) + "same search, third time", # detail: str | None, cut to 2000 chars + session_id="run-001", + agent_id="planner", + tool_call_id="call_1", # str | None +) +``` + +--- + ## Custom fields Any extra keyword arguments are appended to the event after the standard fields: @@ -501,7 +580,7 @@ uv run pytest tests/test_sdk.py -k duration -v | Suite | What it holds | |---|---| | `test_sdk.py` | The public API — every event method, unit and on-disk | -| `test_wire_format.py` | Golden bytes for all 15 event types, frozen | +| `test_wire_format.py` | Golden bytes for all 16 event types, frozen | | `test_server_contract.py` | The keys ingest promotes to indexed columns | | `test_spool_contract.py` | Agreement with the daemons that read the spool | | `test_durability.py` | Concurrency, crash and retry paths — nothing silently lost | diff --git a/sdk/python/docs/README.md b/sdk/python/docs/README.md index aa2e7aa04..6bbbbeb74 100644 --- a/sdk/python/docs/README.md +++ b/sdk/python/docs/README.md @@ -108,7 +108,7 @@ which is almost never what you want. --- -## the fifteen event types +## the sixteen event types | group | events | what they mean | |---|---|---| @@ -120,6 +120,7 @@ which is almost never what you want. | humans | `human_wait` `human_input` | you asked a person / they answered | | | `human_pause` `human_interrupt` | a person paused / stopped the agent | | failures | `error` | something went wrong | +| self reports | `self_report` | the agent said it is stuck (see below) | **Events come in pairs.** The closing event carries a `duration_ms` measured from the matching opening one. An opening event with no close renders as a span @@ -141,12 +142,17 @@ Measured from the real runs in this directory, not declared. | `human_wait` / `human_input` | yes | yes | yes | — | you | | `agent_pause` / `agent_resume` | yes | yes | yes | — | you | | `human_pause` / `human_interrupt` | — | — | — | — | you | +| `self_report` | tool | tool | tool | tool / capability | you | A dash means the framework has no such concept, not that it is missing. Pydantic AI has no node boundary and no built-in human pause, so there is nothing to map. `human_pause` and `human_interrupt` describe a *person* acting on the agent — a stop button — which no framework signals; emit those yourself. +`self_report` comes from the report tool the agent itself calls when it is +stuck. Add it with `self_report_tool()` from the framework's integration module +(each guide shows the line), or call `failproofai_sdk.self_report(...)` yourself. + --- ## running the examples diff --git a/sdk/python/docs/crewai/README.md b/sdk/python/docs/crewai/README.md index 6d0ad958f..adf1f7daf 100644 --- a/sdk/python/docs/crewai/README.md +++ b/sdk/python/docs/crewai/README.md @@ -254,6 +254,30 @@ never added. --- +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, +missing context, a request it cannot do. + +```python +from crewai import Agent +from failproofai_sdk.integrations.crewai import self_report_tool + +analyst = Agent(role="Analyst", goal="...", backstory="...", tools=[search, self_report_tool()]) +``` + +A CrewAI `BaseTool`. While the adapter is installed the report lands on the agent that ran the tool; otherwise on the enclosing `failproofai_sdk.session()`. + +The tool's description and its `category` enum come from +`~/.failproofai/self-report.json` (your org's categories when Self Reports is on +in FailproofAI Cloud, or set locally with `failproofai self-report enable`), and +fall back to six built-in categories. It always answers `Recorded.` and changes +nothing; the call becomes a `self_report` event on the agent's session. To keep +it out of a transcript you show users, filter on +`failproofai_sdk.is_self_report_tool(name)`. + +--- + ## Pitfalls ### Roles with ids in them wreck the facet diff --git a/sdk/python/docs/langgraph/README.md b/sdk/python/docs/langgraph/README.md index c8801076a..d34c9c508 100644 --- a/sdk/python/docs/langgraph/README.md +++ b/sdk/python/docs/langgraph/README.md @@ -361,6 +361,32 @@ The root agent span deliberately stays **open** across the gap, so the two --- +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, +missing context, a request it cannot do. + +```python +from failproofai_sdk.integrations.langchain import self_report_tool +from langgraph.prebuilt import ToolNode + +tools = [search, self_report_tool()] +model = model.bind_tools(tools) +graph.add_node("tools", ToolNode(tools)) +``` + +A `StructuredTool`. While the adapter is installed the report lands on the agent whose run called it, with the model's `tool_call_id`; otherwise on the enclosing `failproofai_sdk.session()`. + +The tool's description and its `category` enum come from +`~/.failproofai/self-report.json` (your org's categories when Self Reports is on +in FailproofAI Cloud, or set locally with `failproofai self-report enable`), and +fall back to six built-in categories. It always answers `Recorded.` and changes +nothing; the call becomes a `self_report` event on the agent's session. To keep +it out of a transcript you show users, filter on +`failproofai_sdk.is_self_report_tool(name)`. + +--- + ## Pitfalls ### A raising tool aborts the whole graph diff --git a/sdk/python/docs/llama_index/README.md b/sdk/python/docs/llama_index/README.md index 138b2ddc1..332ff42df 100644 --- a/sdk/python/docs/llama_index/README.md +++ b/sdk/python/docs/llama_index/README.md @@ -263,6 +263,30 @@ tool and is captured in full. --- +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, +missing context, a request it cannot do. + +```python +from llama_index.core.agent.workflow import FunctionAgent +from failproofai_sdk.integrations.llama_index import self_report_tool + +agent = FunctionAgent(name="researcher", llm=llm, tools=[search, self_report_tool()]) +``` + +A `FunctionTool`. While the adapter is installed the report lands on the agent whose tool span called it; otherwise on the enclosing `failproofai_sdk.session()`. + +The tool's description and its `category` enum come from +`~/.failproofai/self-report.json` (your org's categories when Self Reports is on +in FailproofAI Cloud, or set locally with `failproofai self-report enable`), and +fall back to six built-in categories. It always answers `Recorded.` and changes +nothing; the call becomes a `self_report` event on the agent's session. To keep +it out of a transcript you show users, filter on +`failproofai_sdk.is_self_report_tool(name)`. + +--- + ## Pitfalls ### Every token count is null diff --git a/sdk/python/docs/manual/README.md b/sdk/python/docs/manual/README.md index 39c628e81..2d9d4662d 100644 --- a/sdk/python/docs/manual/README.md +++ b/sdk/python/docs/manual/README.md @@ -9,7 +9,7 @@ adapters call underneath — they are translation tables over the same API. - [Install](#install) - [The three scopes](#the-three-scopes) - [What a scope does on the way out](#what-a-scope-does-on-the-way-out) -- [The fifteen event methods](#the-fifteen-event-methods) +- [The sixteen event methods](#the-sixteen-event-methods) - [A complete example](#a-complete-example) - [Threads and async](#threads-and-async) - [Instrumenting an unsupported framework](#instrumenting-an-unsupported-framework) @@ -105,7 +105,7 @@ is reported exactly once by the enclosing `agent()`. --- -## The fifteen event methods +## The sixteen event methods ### agents @@ -191,6 +191,32 @@ failproofai_sdk.event.error( Usually emitted for you by `agent()`. Call it directly for a failure that does not raise — a validation rejection, a guardrail trip. +### self reports + +```python +failproofai_sdk.self_report("missing_context", "The customer id was never provided.") +# the same event: failproofai_sdk.event.self_report(category=..., detail=...) +``` + +The agent saying it is stuck. Usually the MODEL makes this call, through the +report tool; with a raw provider API give it the tool and route the call: + +```python +tools = [failproofai_sdk.openai_tool(), *my_tools] # anthropic_tool() for Claude +... +for call in message.tool_calls: + if failproofai_sdk.is_self_report_tool(call.function.name): + result = failproofai_sdk.handle_tool_call( + call.function.name, call.function.arguments, tool_call_id=call.id + ) # always "Recorded." +``` + +`self_report_spec()` returns the bare `{name, description, input_schema}`. +Categories and wording come from `~/.failproofai/self-report.json`, else six +built-in defaults. `handle_tool_call` never raises into your loop. With no +session bound, a report is filed under `"unattributed"` (one warning) instead +of raising. + --- ## A complete example @@ -395,7 +421,7 @@ Instrumenting it means wrapping each agent at each construction site, which is a wrapper you paste into your own code — precisely the ergonomics the adapters exist to remove. -If AutoGen matters to you, the three seams above record the same fifteen event +If AutoGen matters to you, the three seams above record the same sixteen event types at the same fidelity. It just costs you the call sites. --- diff --git a/sdk/python/docs/pydantic_ai/README.md b/sdk/python/docs/pydantic_ai/README.md index b9d9d162e..40f51479e 100644 --- a/sdk/python/docs/pydantic_ai/README.md +++ b/sdk/python/docs/pydantic_ai/README.md @@ -214,6 +214,7 @@ failproofai_sdk.instrument( "pydantic_ai", session_id=None, # pin every run to one session id capture_content=True, # False drops prompts and completions from payloads + self_report=False, # True adds the report tool to every agent (see Self Reports) ) ``` @@ -241,6 +242,36 @@ error" rather than raising an `AttributeError` inside your run. --- +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, +missing context, a request it cannot do. + +```python +from pydantic_ai import Agent +from failproofai_sdk.integrations.pydantic_ai import FailproofAI, self_report_tool + +agent = Agent("openai:gpt-5.6-sol", tools=[self_report_tool()]) + +# or let the capability add it to the agent +agent = Agent("openai:gpt-5.6-sol", capabilities=[FailproofAI(self_report=True)]) + +# or to every agent built from now on +failproofai_sdk.instrument("pydantic_ai", self_report=True) +``` + +A Pydantic AI `Tool` whose JSON schema is exactly the spec, carrying the model's `tool_call_id`. `self_report=True` is opt-in: the capability otherwise only observes, and adding a tool changes what the model sees. + +The tool's description and its `category` enum come from +`~/.failproofai/self-report.json` (your org's categories when Self Reports is on +in FailproofAI Cloud, or set locally with `failproofai self-report enable`), and +fall back to six built-in categories. It always answers `Recorded.` and changes +nothing; the call becomes a `self_report` event on the agent's session. To keep +it out of a transcript you show users, filter on +`failproofai_sdk.is_self_report_tool(name)`. + +--- + ## Pitfalls ### An empty trace, no errors anywhere diff --git a/sdk/python/failproofai_sdk/__init__.py b/sdk/python/failproofai_sdk/__init__.py index 5291fcbae..29208fb6c 100644 --- a/sdk/python/failproofai_sdk/__init__.py +++ b/sdk/python/failproofai_sdk/__init__.py @@ -7,7 +7,10 @@ under `with` and `async with`. * **Adapters** — `instrument()`. Auto-detects LangChain/LangGraph, CrewAI, LlamaIndex and Pydantic AI in the process and wires them to the scopes above. -* **`event.*`** — the 15 event methods, for anything the adapters do not cover. +* **`event.*`** — the 16 event methods, for anything the adapters do not cover. +* **Self Reports** — `self_report()` and the report tool for the model + (`openai_tool()`, `anthropic_tool()`, `handle_tool_call()`, `is_self_report_tool()`); + ready-made framework tools are `integrations..self_report_tool()`. `session_id` and `agent_id` are optional on every event method: omitted, they resolve from the enclosing scope. Nothing bound and nothing passed is an error, @@ -25,6 +28,15 @@ from failproofai_sdk._environment import _reject_comma from failproofai_sdk._writer import _validated_interval from failproofai_sdk import _runtime +from failproofai_sdk._self_report import ( + anthropic_tool, + handle_tool_call, + is_self_report_tool, + openai_responses_tool, + openai_tool, + self_report, + self_report_spec, +) __all__ = [ "__version__", @@ -39,6 +51,13 @@ "instrument", "uninstrument", "OtelSpanExporter", + "self_report", + "self_report_spec", + "openai_tool", + "openai_responses_tool", + "anthropic_tool", + "handle_tool_call", + "is_self_report_tool", "_writer", ] diff --git a/sdk/python/failproofai_sdk/_events.py b/sdk/python/failproofai_sdk/_events.py index 0f8ade53b..77606e12e 100644 --- a/sdk/python/failproofai_sdk/_events.py +++ b/sdk/python/failproofai_sdk/_events.py @@ -18,6 +18,7 @@ HumanWaitEvent, ModelRequestEvent, ModelResponseEvent, + SelfReportEvent, ToolResultEvent, ToolUseEvent, ) @@ -63,6 +64,16 @@ _U32_MAX = 2**32 - 1 +#: Longest `detail` a `self_report` carries. The same limit every recorder of +#: the event applies (hook, MCP server, both SDKs), so a report reads the same +#: whichever path wrote it. +SELF_REPORT_DETAIL_LIMIT = 2000 + +#: The session a `self_report` is filed under when nothing else identifies one — +#: the same value the MCP server fallback uses. +UNATTRIBUTED_SESSION = "unattributed" +_warned_unattributed = False + def _validate_promoted_numeric(name: str, value) -> None: """Reject anything `pu32()` would silently turn into NULL. @@ -287,6 +298,11 @@ class EventNamespace: def __init__(self, writer) -> None: self._writer = writer self._pending: dict[str, datetime] = {} + # tool_call_id -> (session_id, agent_id, tool_name) for every tool_use + # not yet closed by its tool_result. Read only by `self_report`, so a + # report made from inside a tool the caller already brackets lands on + # that tool's session and agent. Same cap and eviction as `_pending`. + self._open_tools: dict[str, tuple[str, str, str]] = {} def _track_pending(self, key: str, ts: datetime) -> None: # Evicting has to tolerate another thread doing the same thing, because @@ -321,6 +337,60 @@ def _track_pending(self, key: str, ts: datetime) -> None: self._pending.pop(oldest, None) # may already be gone self._pending[key] = ts + def _track_open_tool(self, tool_call_id: str, entry: "tuple[str, str, str]") -> None: + # Tolerant for the reasons spelled out in `_track_pending`. + if len(self._open_tools) >= _PENDING_CAP: + try: + oldest = next(iter(self._open_tools)) + except (StopIteration, RuntimeError): + pass + else: + self._open_tools.pop(oldest, None) + self._open_tools.pop(tool_call_id, None) # re-insert at the end: newest last + self._open_tools[tool_call_id] = entry + + def _report_identity(self, tool_call_id: "str | None", agent_id: "str | None") -> "tuple[str, str]": + """Where a `self_report` with no explicit `session_id` belongs. + + Most specific first, within the ambient session when one is bound: + the open `tool_use` with this `tool_call_id`; then the newest open + `tool_use` of the report tool itself; then the enclosing scope; then + `"unattributed"` with one warning. Never raises: a report is evidence, + and losing it to a missing scope is the worse outcome. + """ + global _warned_unattributed + from failproofai_sdk._self_report import is_self_report_tool + + ambient = _context.session_id() + try: + open_tools = list(self._open_tools.items()) + except RuntimeError: # resized under us by another thread + open_tools = [] + candidates = [ + (call_id, entry) for call_id, entry in open_tools + if ambient is None or entry[0] == ambient + ] + match = None + if tool_call_id is not None: + match = next((e for c, e in candidates if c == tool_call_id), None) + if match is None: + match = next((e for _, e in reversed(candidates) if is_self_report_tool(e[2])), None) + if match is not None: + return match[0], agent_id if agent_id is not None else match[1] + if agent_id is None: + agent_id = _context.agent_id() + if ambient is not None: + return ambient, agent_id + if not _warned_unattributed: + _warned_unattributed = True + logger.warning( + "Failproof AI recorded a self report with no session bound; it is filed " + "under session_id=%r. Pass session_id=... or wrap the agent in " + "`failproofai_sdk.session()`.", + UNATTRIBUTED_SESSION, + ) + return UNATTRIBUTED_SESSION, agent_id + def _validate_fields(self, fields: dict) -> None: bad = _RESERVED & fields.keys() if bad: @@ -367,6 +437,7 @@ def tool_use( session_id, agent_id = _resolve_identity(session_id, agent_id) ts = self._now() self._track_pending(_tool_key(session_id, tool_call_id), ts) + self._track_open_tool(tool_call_id, (session_id, agent_id, tool_name)) self._writer.submit( ToolUseEvent( timestamp=self._fmt_ts(ts), @@ -396,6 +467,7 @@ def tool_result( session_id, agent_id = _resolve_identity(session_id, agent_id) ts = self._now() start_ts = self._pending.pop(_tool_key(session_id, tool_call_id), None) + self._open_tools.pop(tool_call_id, None) duration_ms = _measured_duration_ms(start_ts, ts) self._writer.submit( ToolResultEvent( @@ -770,3 +842,60 @@ def human_interrupt( extra_fields=fields, ).to_dict() ) + + def self_report( + self, + category: str, + detail: "str | None" = "", + *, + session_id: str | None = None, + agent_id: str | None = None, + tool_call_id: str | None = None, + **fields, + ) -> None: + """Record that the agent reported itself stuck (a `self_report` event). + + `category` is recorded as given, even if it is not one of the configured + categories: a report is evidence, and refusing one because the model + picked a stale name would lose exactly the signal this exists for. + `detail` of `None` is recorded as `""`; anything longer than + `SELF_REPORT_DETAIL_LIMIT` characters is cut to it. + + `source` is always `"sdk"` and cannot be overridden: it is how the + dashboard tells an SDK report from one the coding-agent hook recorded. + + Session, most specific first: an explicit `session_id`; the open + `tool_use` for this call (by `tool_call_id`, then the newest open + report-tool call) within the enclosing session; the enclosing scope; + otherwise `"unattributed"` with one warning. A missing session never + raises here, unlike the other event methods — the TypeError/ValueError + checks on the arguments themselves still apply. + """ + if "source" in fields: + raise ValueError("source is set by the SDK (always \"sdk\") and cannot be passed by the caller") + self._validate_fields(fields) + if not isinstance(category, str): + raise TypeError( + f"category must be a str, got {type(category).__name__}: {category!r}" + ) + if detail is None: + detail = "" + if not isinstance(detail, str): + raise TypeError(f"detail must be a str, got {type(detail).__name__}: {detail!r}") + if tool_call_id is not None: + _validate_promoted_string("tool_call_id", tool_call_id) + if session_id is None: + session_id, agent_id = self._report_identity(tool_call_id, agent_id) + session_id, agent_id = _resolve_identity(session_id, agent_id) + ts = self._now() + self._writer.submit( + SelfReportEvent( + timestamp=self._fmt_ts(ts), + session_id=session_id, + agent_id=agent_id, + category=category, + detail=detail[:SELF_REPORT_DETAIL_LIMIT], + tool_call_id=tool_call_id, + extra_fields=fields, + ).to_dict() + ) diff --git a/sdk/python/failproofai_sdk/_schema.py b/sdk/python/failproofai_sdk/_schema.py index c16d9ba9a..95d3e3e40 100644 --- a/sdk/python/failproofai_sdk/_schema.py +++ b/sdk/python/failproofai_sdk/_schema.py @@ -315,3 +315,32 @@ def to_dict(self) -> dict: [("reason", self.reason), ("user_id", self.user_id), ("at_step", self.at_step)], self.extra_fields, ) + + +@dataclass(kw_only=True) +class SelfReportEvent: + """The agent said it is stuck. See `failproofai_sdk.self_report`. + + `category` and `detail` are always present, even when empty: the report is + the event, and a row without them would render as a blank line on the Self + Reports page. `source` says which path recorded it (`"sdk"` here; the hook + and MCP paths write `"mcp"`). + """ + + timestamp: str + session_id: str + agent_id: str + category: str + detail: str + source: str = "sdk" + tool_call_id: str | None = None + extra_fields: dict = field(default_factory=dict) + + def to_dict(self) -> dict: + return _build( + {"timestamp": self.timestamp, "session_id": self.session_id, "agent_id": self.agent_id, + "type": "self_report", "category": self.category, "detail": self.detail, + "source": self.source}, + [("tool_call_id", self.tool_call_id)], + self.extra_fields, + ) diff --git a/sdk/python/failproofai_sdk/_self_report.py b/sdk/python/failproofai_sdk/_self_report.py new file mode 100644 index 000000000..4c797164f --- /dev/null +++ b/sdk/python/failproofai_sdk/_self_report.py @@ -0,0 +1,416 @@ +"""Self Reports: a tool the agent calls when it is stuck. + +The agent decides when to call it, from the tool's description alone. A call is +recorded as a `self_report` event on the agent's session and the tool answers +`Recorded.` — it never unblocks anything or changes a decision. + + import failproofai_sdk as fp + + tools = [fp.openai_tool(), *my_tools] # or anthropic_tool() + ... + if fp.is_self_report_tool(call.name): + result = fp.handle_tool_call(call.name, call.arguments) # "Recorded." + +Ready-made framework tools live next to each adapter, e.g. +`from failproofai_sdk.integrations.langchain import self_report_tool`. + +Categories and extra guidance come from `$FAILPROOFAI_HOME/self-report.json` +(written by the FailproofAI daemon from the org's Cloud setting, or by +`failproofai self-report enable`). When the file is missing, unreadable, or says +the feature is off, the defaults below are used: a developer who added this tool +to their agent asked for it explicitly, so it always has a usable spec. + +Stdlib only, like the rest of the core (`tests/test_zero_dependencies.py`). +""" + +from __future__ import annotations + +import copy +import json +import logging +import re +from pathlib import Path +from typing import Any + +from failproofai_sdk import _runtime +from failproofai_sdk._events import SELF_REPORT_DETAIL_LIMIT +from failproofai_sdk._resolver import failproofai_home + +logger = logging.getLogger(__name__) + +__all__ = [ + "TOOL_NAME", + "RESULT", + "DEFAULT_CATEGORIES", + "self_report", + "self_report_spec", + "describe", + "load_settings", + "settings_path", + "openai_tool", + "openai_responses_tool", + "anthropic_tool", + "handle_tool_call", + "is_self_report_tool", +] + +#: The SDK tool's name. The coding-agent MCP tool is `report` on server +#: `failproofai`; `is_self_report_tool` recognises every spelling of both. +TOOL_NAME = "failproofai_report" + +#: The tool's result text, exactly. Nothing else is ever returned to the model. +RESULT = "Recorded." + +#: Used when no org categories are configured. An org's own list REPLACES these. +DEFAULT_CATEGORIES: tuple[dict[str, str], ...] = ( + {"name": "looping", "description": "You keep repeating the same or circular steps without making progress."}, + {"name": "cannot_do_request", "description": "The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating."}, + {"name": "invalid_tool_or_credential", "description": "A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected."}, + {"name": "missing_context", "description": "Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions."}, + {"name": "repeated_tool_failure", "description": "A command or tool failed on several distinct attempts and is blocking you. A single error is not enough."}, + {"name": "task_failure", "description": "You genuinely tried and could not complete the task. Not for refusals or policy blocks."}, +) + +_PREAMBLE = ( + "Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot " + "make progress on your own; do not call it for normal work, clarifying questions or a " + "single error. One call per distinct problem.\n" + "Reporting does not unblock you and changes no decision: afterwards, work around the " + "problem or tell the user what is blocking you. There is no need to mention this report " + "to the user." +) + +_DETAIL_DESCRIPTION = "One factual sentence: what is blocking you." + +_NAME_PATTERN = r"[a-z][a-z0-9_]{0,63}" # compiled on first use: nothing runs at import +_MAX_CATEGORIES = 32 +_MAX_DESCRIPTION = 500 +_MAX_GUIDANCE = 2000 + +#: Every spelling the report tool reaches a host under: the SDK name, and the +#: MCP tool `report` on server `failproofai` as each agent prefixes it. +_TOOL_NAMES = frozenset( + { + TOOL_NAME, + "mcp__failproofai__report", + "failproofai__report", + "failproofai.report", + "failproofai/report", + } +) + + +# --------------------------------------------------------------------------- +# Settings +# --------------------------------------------------------------------------- + +def settings_path() -> Path: + """`$FAILPROOFAI_HOME/self-report.json` (default `~/.failproofai/self-report.json`).""" + return failproofai_home() / "self-report.json" + + +def _valid_category(entry: Any) -> bool: + if not isinstance(entry, dict): + return False + name, description = entry.get("name"), entry.get("description") + return ( + isinstance(name, str) + and re.fullmatch(_NAME_PATTERN, name) is not None + and isinstance(description, str) + and 1 <= len(description) <= _MAX_DESCRIPTION + ) + + +def _clean_categories(raw: Any) -> list[dict[str, str]] | None: + """`raw` as a clean category list, or None when it is not a valid one. + + All or nothing: 1-32 entries, every name `^[a-z][a-z0-9_]{0,63}$` and + unique, every description 1-500 chars. Anything else means the defaults — + the same rule the MCP server and the TypeScript SDK apply. + """ + if not isinstance(raw, list) or not 1 <= len(raw) <= _MAX_CATEGORIES: + return None + out: list[dict[str, str]] = [] + seen: set[str] = set() + for entry in raw: + if not _valid_category(entry) or entry["name"] in seen: + return None # one bad entry invalidates the list: defaults, as every reader does + seen.add(entry["name"]) + out.append({"name": entry["name"], "description": entry["description"]}) + return out + + +def load_settings() -> dict[str, Any]: + """The effective settings: `{"enabled", "categories", "guidance"}`. + + Read fresh on every call (the file is tiny, and the daemon rewrites it when + the org changes its categories). Missing or unparsable file: disabled, with + the default categories. File present but disabled: the default categories + and no guidance — the org's list only applies while the org has it on. + """ + result: dict[str, Any] = { + "enabled": False, + "categories": [dict(c) for c in DEFAULT_CATEGORIES], + "guidance": None, + } + try: + data = json.loads(settings_path().read_text(encoding="utf-8")) + except (OSError, ValueError): + return result + if not isinstance(data, dict) or data.get("enabled") is not True: + return result + result["enabled"] = True + categories = _clean_categories(data.get("categories")) + if categories: + result["categories"] = categories + guidance = data.get("guidance") + if isinstance(guidance, str) and guidance and len(guidance) <= _MAX_GUIDANCE: + result["guidance"] = guidance # over the limit: dropped, never cut mid-sentence + return result + + +# --------------------------------------------------------------------------- +# The spec +# --------------------------------------------------------------------------- + +def describe(categories: Any, guidance: str | None = None) -> str: + """The tool description. Identical text in every FailproofAI implementation.""" + lines = [_PREAMBLE, "", "Categories:"] + lines.extend(f"- {c['name']}: {c['description']}" for c in categories) + text = "\n".join(lines) + if guidance: + text += "\n\n" + guidance + return text + + +def _input_schema(names: list[str]) -> dict[str, Any]: + return { + "type": "object", + "properties": { + "category": {"type": "string", "enum": names}, + "detail": {"type": "string", "description": _DETAIL_DESCRIPTION}, + }, + "required": ["category", "detail"], + "additionalProperties": False, + } + + +def self_report_spec( + *, + categories: list[dict[str, str]] | None = None, + guidance: str | None = None, +) -> dict[str, Any]: + """`{"name", "description", "input_schema"}` for the report tool. + + Built from `self-report.json`, or the defaults. Pass `categories` (and + optionally `guidance`) to override both explicitly; an invalid list raises + `ValueError` rather than shipping a tool the model cannot call correctly. + """ + if categories is None: + settings = load_settings() + cats = settings["categories"] + if guidance is None: + guidance = settings["guidance"] + else: + cats = _clean_categories(categories) + if cats is None: + raise ValueError( + "categories must be a non-empty list (at most 32) of " + '{"name": <^[a-z][a-z0-9_]{0,63}$>, "description": <1-500 chars>} with unique names' + ) + if guidance is not None and not isinstance(guidance, str): + raise TypeError(f"guidance must be a str or None, got {type(guidance).__name__}") + return { + "name": TOOL_NAME, + "description": describe(cats, guidance), + "input_schema": _input_schema([c["name"] for c in cats]), + } + + +def openai_tool(**overrides: Any) -> dict[str, Any]: + """The tool for OpenAI Chat Completions `tools=[...]`.""" + spec = self_report_spec(**overrides) + return { + "type": "function", + "function": { + "name": spec["name"], + "description": spec["description"], + "parameters": spec["input_schema"], + }, + } + + +def openai_responses_tool(**overrides: Any) -> dict[str, Any]: + """The tool for the OpenAI Responses API `tools=[...]` (flat function shape).""" + spec = self_report_spec(**overrides) + return { + "type": "function", + "name": spec["name"], + "description": spec["description"], + "parameters": spec["input_schema"], + } + + +def anthropic_tool(**overrides: Any) -> dict[str, Any]: + """The tool for the Anthropic Messages API `tools=[...]`.""" + return copy.deepcopy(self_report_spec(**overrides)) + + +# --------------------------------------------------------------------------- +# Recording +# --------------------------------------------------------------------------- + +def self_report(category: str, detail: str | None = "", **fields: Any) -> None: + """Record a `self_report` event in the current session and agent scope. + + Same writer as every `event.*` method. `session_id=` / `agent_id=` may be + passed; otherwise the open `tool_use` for this call, then the enclosing + `failproofai_sdk.session()` / `agent()` scope, and with nothing bound the + report is filed under `"unattributed"` (one warning) rather than raising. + The event carries `source: "sdk"`. + """ + _runtime.event.self_report(category, detail, **fields) + + +def is_self_report_tool(name: Any) -> bool: + """True for the report tool under any of its names. + + Use it to hide the call from your UI or transcript: `failproofai_report` + (this SDK), and the MCP tool as agents spell it (`mcp__failproofai__report`, + `failproofai__report`, `failproofai.report`, ...). + """ + return isinstance(name, str) and name.strip() in _TOOL_NAMES + + +def _coerce_text(value: Any) -> str: + if value is None: + return "" + return value if isinstance(value, str) else str(value) + + +def parse_arguments(arguments: Any) -> tuple[str, str]: + """`(category, detail)` from a model's tool-call arguments. Never raises. + + Accepts a dict or a JSON string (OpenAI sends a string, Anthropic a dict). + A string that is not a JSON object is kept whole as the detail, so a model + that fumbled the arguments still leaves a readable report. + """ + if isinstance(arguments, (str, bytes, bytearray)): + text = arguments.decode("utf-8", "replace") if not isinstance(arguments, str) else arguments + if not text.strip(): + arguments = {} + else: + try: + arguments = json.loads(text) + except ValueError: + return "", text[:SELF_REPORT_DETAIL_LIMIT] + if arguments is None: + arguments = {} + if not isinstance(arguments, dict): + return "", _coerce_text(arguments)[:SELF_REPORT_DETAIL_LIMIT] + return _coerce_text(arguments.get("category")), _coerce_text(arguments.get("detail")) + + +_warned_unbound = False + + +def record_tool_call(arguments: Any, **fields: Any) -> str: + """Record a report from a model's tool call and return `"Recorded."`. + + Never raises into the agent loop. A report that cannot be recorded (a + writer fault, an invalid explicit id) is logged (once at WARNING, then at + DEBUG) and the model still gets `Recorded.`: the tool's contract is that it + changes nothing, and a raise here would turn a stuck agent into a crashed one. + """ + global _warned_unbound + category, detail = parse_arguments(arguments) + try: + self_report(category, detail, **fields) + except Exception as exc: # noqa: BLE001 - see docstring + level = logging.DEBUG if _warned_unbound else logging.WARNING + _warned_unbound = True + logger.log( + level, + "failproofai_sdk: a self report was not recorded (%s).", + exc, + ) + return RESULT + + +def handle_tool_call( + name: str, + arguments: Any = None, + *, + session_id: str | None = None, + agent_id: str | None = None, + tool_call_id: str | None = None, +) -> str: + """Handle a report tool call from a raw model API. Returns `"Recorded."`. + + for call in message.tool_calls: + if fp.is_self_report_tool(call.function.name): + out = fp.handle_tool_call(call.function.name, call.function.arguments, + tool_call_id=call.id) + + `arguments` may be a dict or a JSON string. Raises `ValueError` only when + `name` is not the report tool, so a dispatcher bug is loud; recording itself + never raises (see `record_tool_call`). + """ + if not is_self_report_tool(name): + raise ValueError( + f"{name!r} is not the FailproofAI report tool; check is_self_report_tool(name) first" + ) + fields: dict[str, Any] = {} + if session_id is not None: + fields["session_id"] = session_id + if agent_id is not None: + fields["agent_id"] = agent_id + if tool_call_id: + fields["tool_call_id"] = str(tool_call_id) + return record_tool_call(arguments, **fields) + + +# --------------------------------------------------------------------------- +# Shared by the framework tools in `integrations/.py` +# --------------------------------------------------------------------------- + +def record_framework_call( + category: Any, + detail: Any, + *, + identity: Any = None, + session_id: str | None = None, + agent_id: str | None = None, + tool_call_id: Any = None, + fields: dict | None = None, +) -> str: + """Record one framework tool call and return `"Recorded."`. Never raises. + + Identity, most explicit first: the `session_id` / `agent_id` the developer + gave the tool factory; then `identity`, which the adapter resolved from the + framework's own run tree (so the report lands on the agent that made the + call even when no `failproofai_sdk.session()` is open); then what + `event.self_report` resolves itself (the open `tool_use` for the call, the + ambient scope, else `"unattributed"`). + """ + out: dict[str, Any] = dict(fields or {}) + if session_id is None and identity is not None and getattr(identity, "session_id", None): + session_id = identity.session_id + if agent_id is None: + agent_id = getattr(identity, "agent_id", None) + if session_id is not None: + out["session_id"] = session_id + if agent_id is not None: + out["agent_id"] = agent_id + if tool_call_id: + out["tool_call_id"] = str(tool_call_id) + return record_tool_call({"category": category, "detail": detail}, **out) + + +def framework_signature(names: list[str]): + """`(category: Literal[...], detail: str)` annotations for frameworks that + derive a tool's JSON schema from a Python signature. Stdlib only: the enum + comes from `typing.Literal`, which every framework's pydantic understands.""" + from typing import Literal + + return {"category": Literal[tuple(names)], "detail": str, "return": str} # type: ignore[valid-type] diff --git a/sdk/python/failproofai_sdk/integrations/crewai.py b/sdk/python/failproofai_sdk/integrations/crewai.py index dadd0bced..ada7cda44 100644 --- a/sdk/python/failproofai_sdk/integrations/crewai.py +++ b/sdk/python/failproofai_sdk/integrations/crewai.py @@ -1667,3 +1667,91 @@ def _count(usage, keys): adapter = _CrewAIAdapter() + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool +# --------------------------------------------------------------------------- + +def _report_identity(): + """The identity of the CrewAI agent running this tool, if recorded. + + CrewAI keeps its own event-scope stack on a contextvar. Inside a tool's + `_run` the top is the tool usage (a leaf, not a node), so walk down to the + nearest scope this adapter has as a node: the agent execution that called + the tool. The stack itself is private to crewai, so a missing one falls + back to the public `get_current_parent_id()` and the adapter's own + root-fallback. + """ + tracker = adapter._tracker + if tracker is None: + return None + from crewai.events import event_context + + key = None + stack = getattr(event_context, "_event_id_stack", None) + if stack is not None: + with adapter._lock: + for entry in reversed(stack.get()): + event_id = entry[0] if isinstance(entry, tuple) else entry + if event_id in adapter._nodes: + key = event_id + break + if key is None: + key = adapter._parent_key(event_context.get_current_parent_id()) + if key is None: + return None + return tracker.identity(None, key, warn=False) + + +def self_report_tool( + *, + session_id: "str | None" = None, + agent_id: "str | None" = None, + categories: "list[dict] | None" = None, + guidance: "str | None" = None, +): + """The FailproofAI report tool as a CrewAI `BaseTool` instance. + + from failproofai_sdk.integrations.crewai import self_report_tool + Agent(role=..., goal=..., tools=[*my_tools, self_report_tool()]) + + The schema and description come from `self-report.json` (or the defaults), + read when the tool is built. Identity: the factory's `session_id` / + `agent_id`, else the crew run this adapter is recording (when instrumented), + else the ambient scope, else "unattributed". Always returns `"Recorded."`. + """ + from crewai.tools import BaseTool + + from failproofai_sdk import _self_report + + spec = _self_report.self_report_spec(categories=categories, guidance=guidance) + names = list(spec["input_schema"]["properties"]["category"]["enum"]) + extra = framework_fields(NAME, DIST) + + def _run(self, category, detail) -> str: + identity = None + try: + identity = _report_identity() + except Exception: # noqa: BLE001 - identity is best-effort; the report is not + logger.debug("failproofai_sdk: could not resolve the report's crew run", exc_info=True) + return _self_report.record_framework_call( + category, detail, identity=identity, session_id=session_id, + agent_id=agent_id, fields=extra, + ) + + _run.__annotations__ = _self_report.framework_signature(names) + + tool_cls = type( + "FailproofAIReportTool", + (BaseTool,), + { + "__module__": __name__, + "__doc__": "Report to FailproofAI that the agent is stuck.", + "__annotations__": {"name": str, "description": str}, + "name": spec["name"], + "description": spec["description"], + "_run": _run, + }, + ) + return tool_cls() diff --git a/sdk/python/failproofai_sdk/integrations/langchain.py b/sdk/python/failproofai_sdk/integrations/langchain.py index f998a3231..68f219bda 100644 --- a/sdk/python/failproofai_sdk/integrations/langchain.py +++ b/sdk/python/failproofai_sdk/integrations/langchain.py @@ -2149,3 +2149,76 @@ def _close_everything() -> None: adapter = _Adapter() + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool +# --------------------------------------------------------------------------- + +def _report_identity(callbacks: Any) -> "tuple[Any, str | None]": + """(identity, tool_call_id) for the tool run `callbacks` hangs off. + + `StructuredTool` hands a func that declares `callbacks` the tool run's child + manager, whose `parent_run_id` IS the tool run. While this adapter is + installed that run is in `_STATE`, so the report resolves to the agent the + model belongs to even with no `failproofai_sdk.session()` open. + """ + run_id = getattr(callbacks, "parent_run_id", None) + if run_id is None or not _STATE.enabled: + return None, None + key = str(run_id) + with _STATE.lock: + info = _STATE.runs.get(key) + tool_call_id = info.tool_call_id if info is not None else None + return _STATE.tracker.identity(None, key, warn=False), tool_call_id + + +def self_report_tool( + *, + session_id: str | None = None, + agent_id: str | None = None, + categories: "list[dict] | None" = None, + guidance: str | None = None, +): + """The FailproofAI report tool as a LangChain `StructuredTool`. + + from failproofai_sdk.integrations.langchain import self_report_tool + agent = create_agent(model, tools=[*my_tools, self_report_tool()]) + + Works in LangGraph's `ToolNode` and any tool-calling chain. The schema and + description come from `self-report.json` (or the defaults), read when the + tool is built. Identity: the factory's `session_id`/`agent_id`, else the run + this adapter is recording (when instrumented), else the ambient scope, else "unattributed". + Always returns `"Recorded."`. + """ + from langchain_core.tools import StructuredTool + + from failproofai_sdk import _self_report + + spec = _self_report.self_report_spec(categories=categories, guidance=guidance) + extra = framework_fields(NAME, DIST) + + def _record(category: Any = "", detail: Any = "", callbacks: Any = None) -> str: + identity, tool_call_id = None, None + try: + identity, tool_call_id = _report_identity(callbacks) + except Exception: # noqa: BLE001 - identity is best-effort; the report is not + logger.debug("failproofai_sdk: could not resolve the report's run", exc_info=True) + return _self_report.record_framework_call( + category, detail, identity=identity, session_id=session_id, + agent_id=agent_id, tool_call_id=tool_call_id, fields=extra, + ) + + def report(category: str = "", detail: str = "", callbacks: Any = None) -> str: + return _record(category, detail, callbacks) + + async def areport(category: str = "", detail: str = "", callbacks: Any = None) -> str: + return _record(category, detail, callbacks) + + return StructuredTool.from_function( + func=report, + coroutine=areport, + name=spec["name"], + description=spec["description"], + args_schema=spec["input_schema"], + ) diff --git a/sdk/python/failproofai_sdk/integrations/llama_index.py b/sdk/python/failproofai_sdk/integrations/llama_index.py index 827015b82..09bda0432 100644 --- a/sdk/python/failproofai_sdk/integrations/llama_index.py +++ b/sdk/python/failproofai_sdk/integrations/llama_index.py @@ -1586,3 +1586,82 @@ def uninstall(self) -> None: install: Callable[..., None] = adapter.install uninstall: Callable[..., None] = adapter.uninstall + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool +# --------------------------------------------------------------------------- + +def _active_span_id() -> "str | None": + try: + from llama_index_instrumentation.span import active_span_id + except ImportError: # older cores carry it in-tree + from llama_index.core.instrumentation.span import active_span_id + return active_span_id.get() + + +def _report_identity(): + """The identity of the LlamaIndex agent whose tool span is active, if recorded.""" + state = adapter.state + if state is None: + return None + span_id = _active_span_id() + if span_id is None: + return None + with state._lock: + run = state._run_of(span_id) + key = (run.sub_key or run.span_id) if run is not None else None + if key is not None: + return state.tracker.identity(key, warn=False) + return state.tracker.identity(None, span_id, warn=False) + + +def self_report_tool( + *, + session_id: "str | None" = None, + agent_id: "str | None" = None, + categories: "list[dict] | None" = None, + guidance: "str | None" = None, +): + """The FailproofAI report tool as a LlamaIndex `FunctionTool`. + + from failproofai_sdk.integrations.llama_index import self_report_tool + agent = FunctionAgent(tools=[*my_tools, self_report_tool()], llm=llm) + + The schema and description come from `self-report.json` (or the defaults), + read when the tool is built. Identity: the factory's `session_id` / + `agent_id`, else the agent run this adapter is recording (when + instrumented), else the ambient scope, else "unattributed". Always returns `"Recorded."`. + """ + from llama_index.core.tools import FunctionTool + + from failproofai_sdk import _self_report + + spec = _self_report.self_report_spec(categories=categories, guidance=guidance) + names = list(spec["input_schema"]["properties"]["category"]["enum"]) + extra = _core.framework_fields(FRAMEWORK, DIST) + + def failproofai_report(category, detail) -> str: + identity = None + try: + identity = _report_identity() + except Exception: # noqa: BLE001 - identity is best-effort; the report is not + logger.debug("failproofai_sdk: could not resolve the report's agent run", exc_info=True) + return _self_report.record_framework_call( + category, detail, identity=identity, session_id=session_id, + agent_id=agent_id, fields=extra, + ) + + failproofai_report.__annotations__ = _self_report.framework_signature(names) + + async def afailproofai_report(category, detail) -> str: + return failproofai_report(category, detail) + + afailproofai_report.__annotations__ = _self_report.framework_signature(names) + + return FunctionTool.from_defaults( + fn=failproofai_report, + async_fn=afailproofai_report, + name=spec["name"], + description=spec["description"], + ) diff --git a/sdk/python/failproofai_sdk/integrations/pydantic_ai.py b/sdk/python/failproofai_sdk/integrations/pydantic_ai.py index e62d5d67a..ab911e9cd 100644 --- a/sdk/python/failproofai_sdk/integrations/pydantic_ai.py +++ b/sdk/python/failproofai_sdk/integrations/pydantic_ai.py @@ -604,6 +604,7 @@ def __init__( capture_content: bool = True, session_id: str | None = None, id: str | None = None, + self_report: bool = False, ) -> None: # `AbstractCapability` is a `@dataclass(init=False)`, so it contributes # class-level defaults (`id`, `defer_loading`, …) and no `__init__` to @@ -611,6 +612,20 @@ def __init__( self.capture_content = capture_content self.session_id = session_id self.id = id + self.self_report = self_report + + def get_toolset(self): + """The FailproofAI report tool, when `self_report=True` was asked for. + + Opt-in, never default: adding a tool changes what the model sees, and + this capability is otherwise pure observation. Built per agent, so the + categories are the ones in `self-report.json` when the agent is built. + """ + if not self.self_report: + return None + from pydantic_ai.toolsets import FunctionToolset + + return FunctionToolset([self_report_tool()]) def get_ordering(self) -> CapabilityOrdering: """Outermost, so our spans bracket every other capability's work. @@ -951,6 +966,7 @@ def install(self, **options: Any) -> None: _capability = FailproofAI( capture_content=bool(options.get("capture_content", True)), session_id=options.get("session_id"), + self_report=bool(options.get("self_report", False)), ) _patcher.patch(Agent, "__init__", _wrap_init(Agent.__init__)) _enabled = True @@ -975,3 +991,50 @@ def uninstall(self) -> None: adapter = _Adapter() install = adapter.install uninstall = adapter.uninstall + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool +# --------------------------------------------------------------------------- + +def self_report_tool( + *, + session_id: str | None = None, + agent_id: str | None = None, + categories: "list[dict] | None" = None, + guidance: str | None = None, +): + """The FailproofAI report tool as a Pydantic AI `Tool`. + + from failproofai_sdk.integrations.pydantic_ai import self_report_tool + agent = Agent(model, tools=[self_report_tool()]) + + or let the capability add it: `capabilities=[FailproofAI(self_report=True)]` + / `failproofai_sdk.instrument("pydantic_ai", self_report=True)`. + + The JSON schema is exactly `self_report_spec()["input_schema"]` (built from + `self-report.json`, or the defaults). The call carries the model's + `tool_call_id`. Identity: the factory's `session_id`/`agent_id`, else the + run `FailproofAI` is recording (it binds the run's scope), else the ambient + scope, else "unattributed". Always returns `"Recorded."`. + """ + from pydantic_ai import Tool + + from failproofai_sdk import _self_report + + spec = _self_report.self_report_spec(categories=categories, guidance=guidance) + extra = framework_fields(NAME, DIST) + + def failproofai_report(ctx: Any, category: Any = "", detail: Any = "", **_: Any) -> str: + return _self_report.record_framework_call( + category, detail, session_id=session_id, agent_id=agent_id, + tool_call_id=getattr(ctx, "tool_call_id", None), fields=extra, + ) + + return Tool.from_schema( + failproofai_report, + name=spec["name"], + description=spec["description"], + json_schema=spec["input_schema"], + takes_ctx=True, + ) diff --git a/sdk/python/skill/SKILL.md b/sdk/python/skill/SKILL.md index 50683b35e..ac5488f0a 100644 --- a/sdk/python/skill/SKILL.md +++ b/sdk/python/skill/SKILL.md @@ -15,7 +15,7 @@ description: |- # Failproof AI SDK — Python and TypeScript Two packages, one pipe: `failproofai-sdk` (Python, imported as `failproofai_sdk`) -and `@failproofai/sdk` (TypeScript/JavaScript). They write the same 15 events in +and `@failproofai/sdk` (TypeScript/JavaScript). They write the same 16 events in the same wire format into the same spool directory. Everything in this file is language-neutral unless it says otherwise, and code blocks are Python. **For a TypeScript or JavaScript agent, read `references/typescript.md` alongside @@ -40,7 +40,7 @@ your agent calls failproofai_sdk.event.* about it: everything up to the `.jsonl` is yours to get right and yours to verify, and it is verifiable on a laptop with no server, no API key, and no network. -The API is small — 15 event methods, all keyword-only. The hard parts are +The API is small — 16 event methods, all keyword-only except `self_report`'s two leading arguments. The hard parts are **deciding where to call them** and **knowing which silences are bugs**, because this SDK does not raise when you get it wrong. Sections 1-3 are the plan, 4 is the code, 5-6 are the proof, 7 is scoring the runs. @@ -137,6 +137,7 @@ doesn't apply; there is no requirement to emit every type. | your `except` blocks | `error` | the Errors surface | | a policy/guard/middleware layer | `hook_triggered` / `hook_completed` | hook behaviour | | an approval gate or human handoff | `human_wait` / `human_input`, `human_pause`, `human_interrupt` | where runs sit waiting on people | +| the agent's tool list | the report tool (`self_report_tool()` / `openai_tool()`), which emits `self_report` | the agent telling you it is stuck, and why (Self Reports) | | a run that suspends and resumes — waiting for a human, throttled, user-paused | `agent_pause` / `agent_resume` | a real "paused" state: the agent isn't ended, the resume isn't a new agent, and wait time is excluded from active work | If the codebase has one tool dispatcher and one LLM wrapper, you have two edit @@ -155,7 +156,7 @@ recipe — `references/typescript.md` → *The contract, in TypeScript* and *Shu - **There IS an ambient session, and it is the ergonomic path.** `session()`, `agent()` and `tool_call()` bind identity on contextvars, so `session_id` and - `agent_id` are optional on all 15 event methods — omitted, they resolve from + `agent_id` are optional on all 16 event methods — omitted, they resolve from the enclosing scope. `current()` reads it; `propagate(fn)` carries it into a new thread, which contextvars do NOT do on their own. diff --git a/sdk/python/skill/references/events.md b/sdk/python/skill/references/events.md index ffcdb5159..a66cc601b 100644 --- a/sdk/python/skill/references/events.md +++ b/sdk/python/skill/references/events.md @@ -1,6 +1,6 @@ # Event catalog -> TypeScript/JavaScript: the same 15 events on `failproofai.event`, camelCase +> TypeScript/JavaScript: the same 16 events on `failproofai.event`, camelCase > (`toolUse({ toolName, toolCallId })`) taking one options object; the file written > is identical. Name map in `typescript.md`. Code below is Python, and where it > says `ValueError` or `TypeError`, TypeScript throws `TypeError` or a plain @@ -9,7 +9,7 @@ Every method lives on `failproofai_sdk.event`, is **keyword-only**, and returns `None`. Nothing here blocks or does I/O — the call queues the event and returns. -`session_id` and `agent_id` are optional on all fifteen: omit them and they come +`session_id` and `agent_id` are optional on all sixteen: omit them and they come from the enclosing `failproofai_sdk.session()` / `failproofai_sdk.agent()` scope. Pass them and your value wins. Omit `session_id` with nothing bound and you get a `TypeError` naming the fix; `agent_id` falls back to `"main"` and never raises. See @@ -19,7 +19,7 @@ Emit only what fits the agent. There is no requirement to use every type, and no penalty for skipping one — except `agent_start`, without which the session does not exist at all. -## The 15 events +## The 16 events Columns: **Required** is beyond `session_id` + `agent_id`, which every event carries and which you rarely pass by hand. @@ -43,6 +43,7 @@ not written as `null`. | `human_input` | `input_id` | `response` | `duration_ms` auto-computed — how long the human took. | | `human_pause` | — | `reason`, `user_id` | | | `human_interrupt` | — | `reason`, `user_id`, `at_step` | | +| `self_report` | `category`, `detail` (positional) | `tool_call_id` | The agent says it is stuck. Never raises for a missing session (see *Self Reports*). Always carries `source: "sdk"` (passing `source` raises `ValueError`). Category recorded as given; `detail` cut to 2,000 chars. Usually the model triggers it through the report tool — see *Self Reports* below. | ## Rules that apply to every event @@ -76,9 +77,9 @@ the optional names are silent. `agent_id`, `type`, `environment` — passing any as a custom field. (`session_id` and `agent_id` are already named args, so Python raises `TypeError` first.) -**`duration_ms` is yours to pass on eleven of the fifteen.** It is computed for you +**`duration_ms` is yours to pass on twelve of the sixteen.** It is computed for you on `tool_result`, `hook_completed`, `human_input`, and `agent_resume`, and passing -it to *those four* raises `ValueError`. On the other eleven there is no guard: +it to *those four* raises `ValueError`. On the other twelve there is no guard: `agent_end(..., duration_ms=5)` is accepted and stored as an ordinary custom field. Don't. The one place you *should* pass it is **`model_response`**, where nothing computes @@ -241,3 +242,31 @@ The agent span stays open across the pause (it is not ended); `agent_resume` carries the paused `duration_ms` when both halves run in the same process, and paused time is reported separately from active work. Persist `pause_id` if the resume happens in a different process so it reuses the same value. + + +## Self Reports + +Give the model a tool to report it is stuck instead of emitting `self_report` +yourself. The tool answers `Recorded.` and changes nothing. + +```python +import failproofai_sdk + +# a framework agent — one factory per adapter module +from failproofai_sdk.integrations.langchain import self_report_tool +tools = [*my_tools, self_report_tool()] + +# a raw provider API +tools = [failproofai_sdk.openai_tool(), *my_tools] # anthropic_tool(), openai_responses_tool() +if failproofai_sdk.is_self_report_tool(name): + output = failproofai_sdk.handle_tool_call(name, arguments, tool_call_id=call_id) +``` + +Tool name `failproofai_report`; description and `category` enum from +`~/.failproofai/self-report.json`, else six defaults +(`failproofai_sdk.self_report_spec()` shows the result). The same factory exists +in `integrations.crewai`, `integrations.llama_index` and +`integrations.pydantic_ai` (also `FailproofAI(self_report=True)`). Tool helpers +never raise into the agent loop. Unlike every other event, `self_report` never +raises for a missing session: it uses the open `tool_use` for the call, then the +enclosing scope, then files the report under `"unattributed"` with one warning. diff --git a/sdk/python/skill/references/frameworks.md b/sdk/python/skill/references/frameworks.md index a1e243cf5..01c94e1fd 100644 --- a/sdk/python/skill/references/frameworks.md +++ b/sdk/python/skill/references/frameworks.md @@ -230,6 +230,24 @@ from failproofai_sdk.integrations.pydantic_ai import FailproofAI agent = Agent("openai:gpt-5", capabilities=[FailproofAI()]) ``` +## The report tool (Self Reports) + +Each adapter module also ships `self_report_tool()`, the FailproofAI report +tool in that framework's own tool type. Add it to the agent's tools; it does not +need `instrument()`, but with the adapter installed the report lands on the +agent that called it. + +| Framework | Import | Type | +|---|---|---| +| LangChain / LangGraph | `from failproofai_sdk.integrations.langchain import self_report_tool` | `StructuredTool` | +| CrewAI | `from failproofai_sdk.integrations.crewai import self_report_tool` | `BaseTool` | +| LlamaIndex | `from failproofai_sdk.integrations.llama_index import self_report_tool` | `FunctionTool` | +| Pydantic AI | `from failproofai_sdk.integrations.pydantic_ai import self_report_tool` | `Tool` | + +Pydantic AI can add it for you, opt in only: `FailproofAI(self_report=True)` or +`instrument("pydantic_ai", self_report=True)`. Every factory takes +`session_id=`, `agent_id=`, `categories=` and `guidance=`. + ## Mixing adapters with hand-written events They compose, and this is the supported way to add detail an adapter cannot know diff --git a/sdk/python/skill/references/integration.md b/sdk/python/skill/references/integration.md index 9093e0803..6c707ab32 100644 --- a/sdk/python/skill/references/integration.md +++ b/sdk/python/skill/references/integration.md @@ -80,7 +80,7 @@ and one that propagates is reported exactly once, by the enclosing `agent()`. ## Explicit identity still works -`session_id` and `agent_id` are optional keyword arguments on all 15 `event.*` +`session_id` and `agent_id` are optional keyword arguments on all 16 `event.*` methods, not removed ones. Passing them explicitly still works, and still wins over whatever is bound: diff --git a/sdk/python/skill/references/typescript.md b/sdk/python/skill/references/typescript.md index 0a6dc75bd..41e66e64a 100644 --- a/sdk/python/skill/references/typescript.md +++ b/sdk/python/skill/references/typescript.md @@ -1,7 +1,7 @@ # TypeScript and JavaScript agents — `@failproofai/sdk` Everything in `SKILL.md` §2 (plan) and §6 (production) applies unchanged. The -TypeScript SDK writes the **same 15 events, the same wire format, into the same +TypeScript SDK writes the **same 16 events, the same wire format, into the same spool directory** as the Python one, and `failproofaid` ships both. A fleet running both languages writes into one pipe, and the dashboard cannot tell which language wrote what. This page is what differs: install, names, adapters, bundlers, runtimes, diff --git a/sdk/python/tests/integrations/test_crewai.py b/sdk/python/tests/integrations/test_crewai.py index 97f30fba6..d1006c321 100644 --- a/sdk/python/tests/integrations/test_crewai.py +++ b/sdk/python/tests/integrations/test_crewai.py @@ -1297,3 +1297,54 @@ def _raise(*args): with pytest.raises(KeyboardInterrupt) as excinfo: _provider()._prompt_input(None) assert excinfo.value is boom + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool +# --------------------------------------------------------------------------- + +USE_REPORT = ( + "Thought: I am stuck.\nAction: failproofai_report\n" + 'Action Input: {"category": "missing_context", "detail": "The input file is not provided."}' +) + + +class TestSelfReportTool: + def test_is_a_base_tool_with_the_spec(self): + from failproofai_sdk.integrations.crewai import self_report_tool + + tool = self_report_tool() + assert isinstance(tool, BaseTool) + assert tool.name == "failproofai_report" + assert failproofai_sdk.self_report_spec()["description"] in tool.description + schema = tool.args_schema.model_json_schema() + assert schema["properties"]["category"]["enum"] == ( + failproofai_sdk.self_report_spec()["input_schema"]["properties"]["category"]["enum"] + ) + assert set(schema["required"]) == {"category", "detail"} + + def test_records_on_the_instrumented_crew_agent(self, instrumented, emitted): + from failproofai_sdk.integrations.crewai import self_report_tool + + llm = ScriptedLLM(model="scripted/fake-1", responses=[USE_REPORT, FINAL]) + kickoff(build_crew(llm, tools=[self_report_tool()])) + events = emitted() + (report,) = [e for e in events if e["type"] == "self_report"] + starts = [e for e in events if e["type"] == "agent_start"] + assert report["session_id"] == starts[0]["session_id"] + assert report["agent_id"] == starts[1]["agent_id"] # the agent, not the crew + assert (report["category"], report["detail"], report["source"]) == ( + "missing_context", "The input file is not provided.", "sdk", + ) + assert report["framework"] == "crewai" + + def test_ambient_and_explicit_identity(self, emitted): + from failproofai_sdk.integrations.crewai import self_report_tool + + with failproofai_sdk.session("crew-ambient"): + assert self_report_tool().run(category="looping", detail="d") == "Recorded." + self_report_tool(session_id="crew-s", agent_id="crew-a").run(category="looping", detail="d") + reports = [e for e in emitted() if e["type"] == "self_report"] + assert [(r["session_id"], r["agent_id"]) for r in reports] == [ + ("crew-ambient", "main"), ("crew-s", "crew-a"), + ] diff --git a/sdk/python/tests/integrations/test_langchain.py b/sdk/python/tests/integrations/test_langchain.py index abbf149c7..d9271c436 100644 --- a/sdk/python/tests/integrations/test_langchain.py +++ b/sdk/python/tests/integrations/test_langchain.py @@ -404,10 +404,11 @@ def _declared_fields_by_type(): "tool_use", "tool_result", "model_request", "model_response", "hook_triggered", "hook_completed", "error", "human_wait", "human_input", "human_pause", "human_interrupt", + "self_report", } -def test_only_the_fifteen_known_event_types_are_emitted(tmp_path, instrumented): +def test_only_the_known_event_types_are_emitted(tmp_path, instrumented): app = build_graph(checkpointer=InMemorySaver()) config = {"configurable": {"thread_id": "vocab"}} app.invoke(empty_state(), config=config) @@ -2336,3 +2337,83 @@ def test_an_unrelated_runnable_invoked_with_none_is_not_the_humans_approval( beats = [e for e in only(rows, "agent_start") if e["agent_id"] == "RunnableLambda"] assert len(beats) == 1 assert beats[0]["session_id"] != "hitl-unrelated" + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool +# --------------------------------------------------------------------------- + +def _report_graph(report_tool): + model = fake_model( + AIMessage( + "stuck", + tool_calls=[{ + "name": "failproofai_report", + "args": {"category": "repeated_tool_failure", "detail": "The build fails every time."}, + "id": "call_report", + }], + ), + ) + + def plan(state): + return {"messages": [model.invoke(state["messages"])]} + + graph = StateGraph(State) + graph.add_node("plan", plan) + graph.add_node("tools", ToolNode([adder, report_tool])) + graph.add_edge(START, "plan") + graph.add_edge("plan", "tools") + graph.add_edge("tools", END) + return graph.compile(name="reporting_graph") + + +def test_self_report_tool_schema_matches_the_spec(): + from langchain_core.tools import StructuredTool + from langchain_core.utils.function_calling import convert_to_openai_tool + + tool_ = adapter.self_report_tool() + assert isinstance(tool_, StructuredTool) + spec = failproofai_sdk.self_report_spec() + converted = convert_to_openai_tool(tool_)["function"] + assert converted["name"] == "failproofai_report" + assert converted["description"] == spec["description"] + assert converted["parameters"]["properties"] == spec["input_schema"]["properties"] + assert converted["parameters"]["required"] == ["category", "detail"] + + +def test_self_report_tool_records_on_the_instrumented_run(tmp_path, instrumented): + app = _report_graph(adapter.self_report_tool()) + out = app.invoke(empty_state()) + rows = read_events(tmp_path) + (report,) = only(rows, "self_report") + root = only(rows, "agent_start")[0] + assert report["session_id"] == root["session_id"] + assert report["agent_id"] == root["agent_id"] + assert report["tool_call_id"] == "call_report" + assert (report["category"], report["detail"], report["source"]) == ( + "repeated_tool_failure", "The build fails every time.", "sdk", + ) + assert report["framework"] == "langchain" + tool_messages = [m for m in out["messages"] if isinstance(m, ToolMessage)] + assert [m.content for m in tool_messages] == ["Recorded."] + + +def test_self_report_tool_async_path(tmp_path, instrumented): + import asyncio + + asyncio.run(_report_graph(adapter.self_report_tool()).ainvoke(empty_state())) + (report,) = only(read_events(tmp_path), "self_report") + assert report["tool_call_id"] == "call_report" + + +def test_self_report_tool_ambient_scope_without_instrumentation(tmp_path): + with failproofai_sdk.session("lc-ambient"): + assert adapter.self_report_tool().invoke({"category": "looping", "detail": "d"}) == "Recorded." + (report,) = only(read_events(tmp_path), "self_report") + assert (report["session_id"], report["agent_id"]) == ("lc-ambient", "main") + + +def test_self_report_tool_explicit_identity_wins(tmp_path, instrumented): + _report_graph(adapter.self_report_tool(session_id="lc-s", agent_id="lc-a")).invoke(empty_state()) + (report,) = only(read_events(tmp_path), "self_report") + assert (report["session_id"], report["agent_id"]) == ("lc-s", "lc-a") diff --git a/sdk/python/tests/integrations/test_llama_index.py b/sdk/python/tests/integrations/test_llama_index.py index 50361f21a..dcfc19e09 100644 --- a/sdk/python/tests/integrations/test_llama_index.py +++ b/sdk/python/tests/integrations/test_llama_index.py @@ -1574,3 +1574,49 @@ def test_captured_values_are_not_capped_at_a_quarter_of_the_core_limit(): assert adapter_module._capture_limit(float("inf")) == _core.FIELD_LIMIT assert adapter_module._capture_limit("nope") == _core.FIELD_LIMIT assert adapter_module._capture_limit(0) == _core.FIELD_LIMIT + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool +# --------------------------------------------------------------------------- + +def test_self_report_tool_schema_matches_the_spec(): + from llama_index.core.tools import FunctionTool + + tool = adapter_module.self_report_tool() + spec = failproofai_sdk.self_report_spec() + assert isinstance(tool, FunctionTool) + assert tool.metadata.name == "failproofai_report" + assert tool.metadata.description == spec["description"] + params = tool.metadata.get_parameters_dict() + assert params["properties"]["category"]["enum"] == spec["input_schema"]["properties"]["category"]["enum"] + assert set(params["required"]) == {"category", "detail"} + + +def test_self_report_tool_records_on_the_instrumented_agent(instrumented, tmp_path): + llm = StubLLM(script=[("failproofai_report", {"category": "looping", "detail": "same step again"})], final="ok") + run_agent(calculator(llm, tools=[add, adapter_module.self_report_tool()]), "go") + events = read_events(tmp_path) + (report,) = only(events, "self_report") + start = only(events, "agent_start")[0] + assert report["session_id"] == start["session_id"] + assert report["agent_id"] == "calc" + assert (report["category"], report["detail"], report["source"]) == ("looping", "same step again", "sdk") + assert report["framework"] == "llama_index" + results = [e for e in only(events, "tool_result") if e["tool_name"] == "failproofai_report"] + assert results and "Recorded." in str(results[0].get("output")) + + +def test_self_report_tool_uses_the_ambient_scope_when_not_instrumented(tmp_path): + tool = adapter_module.self_report_tool() + with failproofai_sdk.session("li-ambient"): + assert str(tool.call(category="task_failure", detail="gave up")) == "Recorded." + (report,) = only(read_events(tmp_path), "self_report") + assert (report["session_id"], report["agent_id"]) == ("li-ambient", "main") + + +def test_self_report_tool_explicit_identity(tmp_path): + tool = adapter_module.self_report_tool(session_id="li-s", agent_id="li-a") + tool.call(category="looping", detail="x") + (report,) = only(read_events(tmp_path), "self_report") + assert (report["session_id"], report["agent_id"]) == ("li-s", "li-a") diff --git a/sdk/python/tests/integrations/test_pydantic_ai.py b/sdk/python/tests/integrations/test_pydantic_ai.py index 6e5838750..3491bda4f 100644 --- a/sdk/python/tests/integrations/test_pydantic_ai.py +++ b/sdk/python/tests/integrations/test_pydantic_ai.py @@ -325,7 +325,7 @@ def test_every_event_carries_the_framework_triple(instrumented, emitted): def test_the_type_table_covers_the_whole_schema(): # Guards the test below: a bad CamelCase split would make it vacuous. - assert len(TYPE_OF_DATACLASS) == 15 + assert len(TYPE_OF_DATACLASS) == 16 assert {"tool_use", "model_response", "agent_end", "hook_triggered", "error"} <= set( TYPE_OF_DATACLASS ) @@ -969,6 +969,7 @@ def test_the_override_set_is_not_empty(self): # Guards every test below: `for name in {}` passes vacuously. assert set(OVERRIDES) == { "get_ordering", + "get_toolset", # contributes the opt-in report tool "wrap_run", "wrap_model_request", "wrap_tool_execute", @@ -1100,3 +1101,86 @@ def reject(value: str) -> str: # Strictly before agent_end: the dashboard closes the agent span there and # anything after it is attributed to nothing. assert types_of(rows).index("error") < types_of(rows).index("agent_end") + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool, and the capability opt-in +# --------------------------------------------------------------------------- + +_REPORT_ARGS = {"category": "invalid_tool_or_credential", "detail": "The API key is rejected."} + + +def _tool_definitions(agent): + """The tool definitions the model is actually shown on the first request.""" + seen = {} + + def respond(messages, info): + seen["tools"] = {t.name: t for t in info.function_tools} + return ModelResponse(parts=[TextPart("done")]) + + agent.run_sync("go", model=FunctionModel(respond)) + return seen["tools"] + + +def test_self_report_tool_schema_is_exactly_the_spec(): + agent = Agent(TestModel(call_tools=[]), tools=[adapter.self_report_tool()]) + tools = _tool_definitions(agent) + spec = failproofai_sdk.self_report_spec() + definition = tools["failproofai_report"] + assert definition.description == spec["description"] + assert definition.parameters_json_schema == spec["input_schema"] + + +def test_self_report_tool_records_on_the_instrumented_run(instrumented, emitted): + agent = Agent( + one_shot_tool_model("failproofai_report", _REPORT_ARGS, tool_call_id="call-r"), + name="reporter_agent", + tools=[adapter.self_report_tool()], + ) + agent.run_sync("go") + rows = emitted() + (report,) = of_type(rows, "self_report") + start = of_type(rows, "agent_start")[0] + assert report["session_id"] == start["session_id"] + assert report["agent_id"] == "reporter_agent" + assert report["tool_call_id"] == "call-r" + assert (report["category"], report["detail"], report["source"]) == ( + "invalid_tool_or_credential", "The API key is rejected.", "sdk", + ) + assert report["framework"] == "pydantic_ai" + (result,) = [r for r in of_type(rows, "tool_result") if r["tool_name"] == "failproofai_report"] + assert result["output"] == "Recorded." + + +def test_self_report_tool_ambient_and_explicit_identity(emitted): + with failproofai_sdk.session("pai-ambient"): + Agent(one_shot_tool_model("failproofai_report", _REPORT_ARGS), + tools=[adapter.self_report_tool()]).run_sync("go") + Agent(one_shot_tool_model("failproofai_report", _REPORT_ARGS), + tools=[adapter.self_report_tool(session_id="pai-s", agent_id="pai-a")]).run_sync("go") + reports = of_type(emitted(), "self_report") + assert [(r["session_id"], r["agent_id"]) for r in reports] == [ + ("pai-ambient", "main"), ("pai-s", "pai-a"), + ] + + +def test_the_capability_adds_the_tool_only_when_asked(): + plain = _tool_definitions(Agent(TestModel(call_tools=[]), capabilities=[FailproofAI()])) + assert "failproofai_report" not in plain + opted = _tool_definitions(Agent(TestModel(call_tools=[]), capabilities=[FailproofAI(self_report=True)])) + assert "failproofai_report" in opted + + +def test_instrument_self_report_option_adds_the_tool(emitted): + _core.set_strict(False) + _compat.set_strict_integrations(False) + assert failproofai_sdk.instrument("pydantic_ai", self_report=True) == ("pydantic_ai",) + try: + agent = Agent( + one_shot_tool_model("failproofai_report", _REPORT_ARGS), name="auto_agent" + ) + agent.run_sync("go") + finally: + failproofai_sdk.uninstrument("pydantic_ai") + (report,) = of_type(emitted(), "self_report") + assert report["agent_id"] == "auto_agent" diff --git a/sdk/python/tests/test_self_report.py b/sdk/python/tests/test_self_report.py new file mode 100644 index 000000000..2356b2c97 --- /dev/null +++ b/sdk/python/tests/test_self_report.py @@ -0,0 +1,421 @@ +"""Self Reports in the core SDK: the event, the settings file, the raw tool helpers. + +Everything here is stdlib-only, like the code under test. The framework tools +are exercised against the real frameworks in tests/integrations/test_self_report_tools.py. +""" +import json +import logging + +import pytest + +import failproofai_sdk as fp +from failproofai_sdk import _runtime, _self_report +from failproofai_sdk._events import EventNamespace + +EXPECTED_DEFAULT_DESCRIPTION = """Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; do not call it for normal work, clarifying questions or a single error. One call per distinct problem. +Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. + +Categories: +- looping: You keep repeating the same or circular steps without making progress. +- cannot_do_request: The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating. +- invalid_tool_or_credential: A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. +- missing_context: Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. +- repeated_tool_failure: A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. +- task_failure: You genuinely tried and could not complete the task. Not for refusals or policy blocks.""" + +DEFAULT_NAMES = [ + "looping", + "cannot_do_request", + "invalid_tool_or_credential", + "missing_context", + "repeated_tool_failure", + "task_failure", +] + + +class _Recorder: + def __init__(self): + self.entries = [] + + def submit(self, entry): + self.entries.append(entry) + + +@pytest.fixture() +def recorded(monkeypatch): + """Swap the process namespace for one that records instead of spooling.""" + from failproofai_sdk import _runtime + + recorder = _Recorder() + monkeypatch.setattr(_runtime, "event", EventNamespace(recorder)) + return recorder.entries + + +@pytest.fixture() +def home(tmp_path, monkeypatch): + path = tmp_path / "fphome" + path.mkdir() + monkeypatch.setenv("FAILPROOFAI_HOME", str(path)) + return path + + +def write_settings(home, body): + (home / "self-report.json").write_text( + body if isinstance(body, str) else json.dumps(body), encoding="utf-8" + ) + + +# ───────────────────────────────────────────────────────────────────────────── +# The event +# ───────────────────────────────────────────────────────────────────────────── + + +def test_event_shape_in_session_and_agent_scope(recorded): + with fp.session("sess-1"): + with fp.agent("planner"): + fp.self_report("looping", "I keep retrying the same search.") + # `agent()` brackets itself with agent_start / agent_end. + (event,) = [e for e in recorded if e["type"] == "self_report"] + assert event["session_id"] == "sess-1" + assert event["agent_id"] == "planner" + assert event["category"] == "looping" + assert event["detail"] == "I keep retrying the same search." + assert event["source"] == "sdk" + assert "environment" in event and event["timestamp"].endswith("Z") + assert "tool_call_id" not in event + + +def test_session_without_agent_scope_uses_the_default_agent(recorded): + with fp.session("s"): + fp.self_report("task_failure", "x") + assert recorded[0]["agent_id"] == "main" + + +def test_explicit_identity_and_extra_fields(recorded): + fp.self_report("missing_context", "d", session_id="s2", agent_id="a2", tool_call_id="call_9", run="r1") + event = recorded[0] + assert (event["session_id"], event["agent_id"], event["tool_call_id"], event["run"]) == ( + "s2", "a2", "call_9", "r1", + ) + + +def test_nothing_bound_is_filed_as_unattributed_with_one_warning(recorded, monkeypatch, caplog): + from failproofai_sdk import _events + + monkeypatch.setattr(_events, "_warned_unattributed", False) + with caplog.at_level(logging.WARNING, logger="failproofai_sdk"): + fp.self_report("looping", "x") + fp.self_report("looping", "y") + assert [(e["session_id"], e["agent_id"]) for e in recorded] == [ + ("unattributed", "main"), ("unattributed", "main"), + ] + assert len([r for r in caplog.records if "unattributed" in r.getMessage()]) == 1 + + +def test_the_open_tool_use_for_this_call_wins_over_the_ambient_agent(recorded): + with fp.session("s-tools"): + with fp.agent("worker"): + _runtime.event.tool_use(tool_name="failproofai_report", tool_call_id="call_7") + # reported from a different agent scope, same session: the tool's agent wins + fp.self_report("looping", "d", tool_call_id="call_7") + (report,) = [e for e in recorded if e["type"] == "self_report"] + assert (report["session_id"], report["agent_id"]) == ("s-tools", "worker") + + +def test_the_open_tool_use_resolves_a_report_with_nothing_bound(recorded): + _runtime.event.tool_use(session_id="s-open", agent_id="a-open", + tool_name="failproofai_report", tool_call_id="call_8") + fp.self_report("looping", "by id", tool_call_id="call_8") + fp.self_report("looping", "by tool name") # no id: newest open report-tool call + reports = [e for e in recorded if e["type"] == "self_report"] + assert [(r["session_id"], r["agent_id"]) for r in reports] == [("s-open", "a-open")] * 2 + + +def test_a_closed_or_foreign_session_tool_use_is_not_used(recorded): + _runtime.event.tool_use(session_id="s-a", agent_id="a", tool_name="failproofai_report", tool_call_id="c1") + _runtime.event.tool_result(session_id="s-a", agent_id="a", tool_name="failproofai_report", tool_call_id="c1") + _runtime.event.tool_use(session_id="s-other", agent_id="b", tool_name="failproofai_report", tool_call_id="c2") + with fp.session("s-mine"): + fp.self_report("looping", "d", tool_call_id="c1") + fp.self_report("looping", "d", tool_call_id="c2") + reports = [e for e in recorded if e["type"] == "self_report"] + assert [r["session_id"] for r in reports] == ["s-mine", "s-mine"] + + +def test_written_to_the_spool_by_the_real_writer(tmp_path): + with fp.session("disk"): + fp.self_report("looping", "on disk") + fp._writer.flush_now() + rows = [ + json.loads(line) + for p in sorted((tmp_path / "events").glob("*.jsonl")) + for line in p.read_text().splitlines() + if line.strip() + ] + reports = [r for r in rows if r["type"] == "self_report"] + assert reports and reports[-1]["detail"] == "on disk" and reports[-1]["source"] == "sdk" + + +def test_detail_is_truncated_and_none_becomes_empty(recorded): + fp.self_report("looping", "x" * 5000, session_id="s") + fp.self_report("looping", None, session_id="s") + assert len(recorded[0]["detail"]) == 2000 + assert recorded[1]["detail"] == "" + + +def test_unknown_category_is_recorded_as_is(recorded): + fp.self_report("not_a_configured_one", "d", session_id="s") + assert recorded[0]["category"] == "not_a_configured_one" + + +@pytest.mark.parametrize("name", ["timestamp", "type", "environment", "source"]) +def test_reserved_and_sdk_owned_fields_are_rejected(recorded, name): + with pytest.raises(ValueError): + fp.self_report("looping", "d", session_id="s", **{name: "x"}) + + +def test_wrong_types_are_rejected(recorded): + with pytest.raises(TypeError): + fp.self_report(None, "d", session_id="s") + with pytest.raises(TypeError): + fp.self_report("looping", 5, session_id="s") + with pytest.raises(TypeError): + fp.self_report("looping", "d", session_id="s", tool_call_id=7) + + +def test_event_namespace_method_is_the_same_event(): + recorder = _Recorder() + EventNamespace(recorder).self_report("looping", "d", session_id="s", agent_id="a") + assert recorder.entries[0]["type"] == "self_report" + + +# ───────────────────────────────────────────────────────────────────────────── +# Settings and the spec +# ───────────────────────────────────────────────────────────────────────────── + + +def test_missing_file_gives_the_defaults(home): + spec = fp.self_report_spec() + assert spec["name"] == "failproofai_report" + assert spec["description"] == EXPECTED_DEFAULT_DESCRIPTION + assert spec["input_schema"] == { + "type": "object", + "properties": { + "category": {"type": "string", "enum": DEFAULT_NAMES}, + "detail": {"type": "string", "description": "One factual sentence: what is blocking you."}, + }, + "required": ["category", "detail"], + "additionalProperties": False, + } + assert _self_report.load_settings()["enabled"] is False + + +def test_settings_path_follows_failproofai_home(home): + assert _self_report.settings_path() == home / "self-report.json" + + +ORG = { + "version": 1, + "enabled": True, + "source": "cloud", + "categories": [ + {"name": "billing_blocked", "description": "A payment step is refused."}, + {"name": "looping", "description": "Going in circles."}, + ], + "guidance": "Report billing problems at once.", + "mcp": {"port": 4319, "url": "http://127.0.0.1:4319/mcp"}, + "updatedAt": "2026-11-25T10:00:00Z", +} + + +def test_enabled_file_replaces_categories_and_appends_guidance(home): + write_settings(home, ORG) + spec = fp.self_report_spec() + assert spec["input_schema"]["properties"]["category"]["enum"] == ["billing_blocked", "looping"] + assert spec["description"].endswith( + "Categories:\n- billing_blocked: A payment step is refused.\n- looping: Going in circles." + "\n\nReport billing problems at once." + ) + + +def test_settings_are_reread_on_every_call(home): + assert "billing_blocked" not in fp.self_report_spec()["description"] + write_settings(home, ORG) + assert "billing_blocked" in fp.self_report_spec()["description"] + + +def test_disabled_file_still_builds_the_default_spec(home): + write_settings(home, {**ORG, "enabled": False}) + spec = fp.self_report_spec() + assert spec["description"] == EXPECTED_DEFAULT_DESCRIPTION + + +@pytest.mark.parametrize("body", ["{not json", "[]", '"x"', ""]) +def test_unparsable_file_gives_the_defaults(home, body): + write_settings(home, body) + assert fp.self_report_spec()["description"] == EXPECTED_DEFAULT_DESCRIPTION + + +@pytest.mark.parametrize( + "categories", + [ + [], + None, + "looping", + [{"name": "Bad Name", "description": "x"}, {"name": "ok_one", "description": "fine"}], + [{"name": "ok_one", "description": "fine"}, {"name": "ok_one", "description": "dupe"}], + [{"name": "ok_one", "description": ""}], + [{"name": "ok_one", "description": "x" * 501}], + [{"name": f"c{i}", "description": "d"} for i in range(33)], + ], + ids=["empty", "null", "string", "bad-name", "duplicate", "empty-desc", "long-desc", "33"], +) +def test_an_invalid_category_list_means_all_six_defaults(home, categories): + write_settings(home, {**ORG, "categories": categories}) + assert fp.self_report_spec()["input_schema"]["properties"]["category"]["enum"] == DEFAULT_NAMES + + +def test_guidance_over_2000_chars_is_dropped_not_cut(home): + write_settings(home, {**ORG, "guidance": "g" * 2001}) + assert fp.self_report_spec()["description"].endswith("- looping: Going in circles.") + write_settings(home, {**ORG, "guidance": "g" * 2000}) + assert fp.self_report_spec()["description"].endswith("\n\n" + "g" * 2000) + + +def test_explicit_categories_override_the_file(home): + write_settings(home, ORG) + spec = fp.self_report_spec(categories=[{"name": "mine", "description": "Mine."}]) + assert spec["input_schema"]["properties"]["category"]["enum"] == ["mine"] + assert "Report billing problems" not in spec["description"] + with pytest.raises(ValueError): + fp.self_report_spec(categories=[{"name": "BAD", "description": "x"}]) + with pytest.raises(ValueError): + fp.self_report_spec(categories=[]) + + +def test_describe_matches_the_contract_layout(): + text = _self_report.describe([{"name": "a", "description": "A."}], "Extra.") + assert text.endswith("\n\nCategories:\n- a: A.\n\nExtra.") + assert _self_report.describe([{"name": "a", "description": "A."}], None).endswith("- a: A.") + + +# ───────────────────────────────────────────────────────────────────────────── +# Raw helpers +# ───────────────────────────────────────────────────────────────────────────── + + +def test_openai_chat_tool_shape(home): + tool = fp.openai_tool() + spec = fp.self_report_spec() + assert tool == { + "type": "function", + "function": {"name": spec["name"], "description": spec["description"], "parameters": spec["input_schema"]}, + } + + +def test_openai_responses_tool_shape(home): + tool = fp.openai_responses_tool() + spec = fp.self_report_spec() + assert tool == { + "type": "function", + "name": spec["name"], + "description": spec["description"], + "parameters": spec["input_schema"], + } + + +def test_anthropic_tool_shape(home): + assert fp.anthropic_tool() == fp.self_report_spec() + assert set(fp.anthropic_tool()) == {"name", "description", "input_schema"} + + +@pytest.mark.parametrize( + "name", + [ + "failproofai_report", + "mcp__failproofai__report", + "failproofai__report", + "failproofai.report", + "failproofai/report", + ], +) +def test_is_self_report_tool_accepts_every_spelling(name): + assert fp.is_self_report_tool(name) + + +@pytest.mark.parametrize( + "name", ["report", "bash", "mcp__other__report", "failproofai:report", "failproofai-report", "", None, 3] +) +def test_is_self_report_tool_rejects_others(name): + assert not fp.is_self_report_tool(name) + + +def test_handle_tool_call_with_a_json_string(recorded): + with fp.session("s"): + out = fp.handle_tool_call( + "failproofai_report", '{"category": "looping", "detail": "stuck"}', tool_call_id="call_1" + ) + assert out == "Recorded." + assert recorded[0]["category"] == "looping" + assert recorded[0]["detail"] == "stuck" + assert recorded[0]["tool_call_id"] == "call_1" + + +def test_handle_tool_call_with_a_dict_and_explicit_identity(recorded): + out = fp.handle_tool_call( + "mcp__failproofai__report", {"category": "x", "detail": "y"}, session_id="s", agent_id="a" + ) + assert out == "Recorded." + assert (recorded[0]["session_id"], recorded[0]["agent_id"]) == ("s", "a") + + +@pytest.mark.parametrize( + "arguments,expected", + [ + (None, ("", "")), + ("", ("", "")), + ({}, ("", "")), + ('{"category": "looping"}', ("looping", "")), + ("not json at all", ("", "not json at all")), + ('["a"]', ("", "['a']")), + ({"category": 5, "detail": None}, ("5", "")), + ], +) +def test_handle_tool_call_tolerates_bad_arguments(recorded, arguments, expected): + assert fp.handle_tool_call("failproofai_report", arguments, session_id="s") == "Recorded." + assert (recorded[0]["category"], recorded[0]["detail"]) == expected + + +def test_handle_tool_call_with_nothing_bound_records_unattributed(recorded): + assert fp.handle_tool_call("failproofai_report", {"category": "looping", "detail": "x"}) == "Recorded." + assert recorded[0]["session_id"] == "unattributed" + + +def test_handle_tool_call_never_raises_into_the_agent(recorded, caplog): + with caplog.at_level(logging.WARNING, logger="failproofai_sdk"): + # an invalid explicit id is refused by the event method; the helper swallows it + assert fp.handle_tool_call("failproofai_report", {"category": "looping"}, session_id=" ") == "Recorded." + assert recorded == [] + assert any("not recorded" in r.getMessage() for r in caplog.records) + + +def test_handle_tool_call_refuses_another_tool(): + with pytest.raises(ValueError, match="not the FailproofAI report tool"): + fp.handle_tool_call("bash", {}) + + +def test_importing_the_package_reads_no_settings(monkeypatch): + """The settings file is read when a spec is built, never at import.""" + import subprocess + import sys + + code = ( + "import builtins, pathlib\n" + "orig = pathlib.Path.read_text\n" + "def guard(self, *a, **k):\n" + " assert self.name != 'self-report.json', 'read at import'\n" + " return orig(self, *a, **k)\n" + "pathlib.Path.read_text = guard\n" + "import failproofai_sdk\n" + ) + subprocess.run([sys.executable, "-c", code], check=True) diff --git a/sdk/python/tests/test_server_contract.py b/sdk/python/tests/test_server_contract.py index 794404dbf..76441e5c3 100644 --- a/sdk/python/tests/test_server_contract.py +++ b/sdk/python/tests/test_server_contract.py @@ -82,6 +82,7 @@ def _emit_everything(): ns.human_input(**ids, input_id="i1", response="y") ns.human_pause(**ids, reason="r", user_id="u") ns.human_interrupt(**ids, reason="r", user_id="u", at_step="1") + ns.self_report("looping", "d", **ids, tool_call_id="tc") return recorder.entries @@ -203,7 +204,7 @@ def test_a_reserved_name_is_rejected_by_every_event_method(): """One method forgetting `_validate_fields` would let a caller rewrite `type`.""" ns = EventNamespace(_Recorder()) methods = [m for m in dir(ns) if not m.startswith("_") and callable(getattr(ns, m))] - assert len(methods) == 15, f"expected 15 event methods, found {len(methods)}: {sorted(methods)}" + assert len(methods) == 16, f"expected 16 event methods, found {len(methods)}: {sorted(methods)}" required = { "tool_use": dict(tool_name="t", tool_call_id="c"), @@ -215,6 +216,7 @@ def test_a_reserved_name_is_rejected_by_every_event_method(): "human_input": dict(input_id="i"), "agent_pause": dict(pause_id="p"), "agent_resume": dict(pause_id="p"), + "self_report": dict(category="looping", detail="d"), } for method in methods: with pytest.raises(ValueError, match="Reserved field names"): @@ -609,6 +611,7 @@ def test_the_measured_and_the_caller_supplied_paths_enforce_the_same_range(): ("error", {"error_type": "E", "message": "m"}), ("human_wait", {"input_id": "i"}), ("human_input", {"input_id": "i"}), ("human_pause", {}), ("human_interrupt", {}), + ("self_report", {"category": "looping", "detail": "d"}), ] @@ -630,6 +633,11 @@ def test_a_non_string_session_id_is_refused_on_every_event(method, extra, bad): success, the collector deletes the batch, and the event is gone. `None` is the realistic way in — an uninitialised variable, a lookup that missed. """ + if method == "self_report" and bad is None: + # `None` means "resolve" on every method, and `self_report` alone never + # raises when nothing resolves: it files the report as "unattributed" + # (tests/test_self_report.py). The non-None bad values still raise. + pytest.skip("self_report resolves a None session instead of raising") ns = EventNamespace(_Recorder()) with pytest.raises(TypeError, match="session_id"): getattr(ns, method)(session_id=bad, agent_id="a", **extra) diff --git a/sdk/python/tests/test_wire_format.py b/sdk/python/tests/test_wire_format.py index 64b98457a..918eb0e19 100644 --- a/sdk/python/tests/test_wire_format.py +++ b/sdk/python/tests/test_wire_format.py @@ -49,6 +49,7 @@ "human_input": '{"timestamp": "2026-01-02T03:04:05.678901Z", "session_id": "sess-1", "agent_id": "agent-1", "type": "human_input", "input_id": "i-1", "environment": "prod", "response": "y", "duration_ms": 78}', "human_pause": '{"timestamp": "2026-01-02T03:04:05.678901Z", "session_id": "sess-1", "agent_id": "agent-1", "type": "human_pause", "environment": "prod", "reason": "lunch", "user_id": "u-1"}', "human_interrupt": '{"timestamp": "2026-01-02T03:04:05.678901Z", "session_id": "sess-1", "agent_id": "agent-1", "type": "human_interrupt", "environment": "prod", "reason": "stop", "user_id": "u-1", "at_step": "3"}', + "self_report": '{"timestamp": "2026-01-02T03:04:05.678901Z", "session_id": "sess-1", "agent_id": "agent-1", "type": "self_report", "category": "looping", "detail": "same search again", "source": "sdk", "environment": "prod", "tool_call_id": "tc-1"}', } @@ -71,6 +72,7 @@ def _events(): "human_input": s.HumanInputEvent(**BASE, input_id="i-1", response="y", duration_ms=78), "human_pause": s.HumanPauseEvent(**BASE, reason="lunch", user_id="u-1"), "human_interrupt": s.HumanInterruptEvent(**BASE, reason="stop", user_id="u-1", at_step="3"), + "self_report": s.SelfReportEvent(**BASE, category="looping", detail="same search again", tool_call_id="tc-1"), } From b5984b1c5fc5a2cc8296505384adfe4aaf35c213 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 25 Nov 2026 21:52:07 +0530 Subject: [PATCH 09/54] [self-reports] Docs, changelog, and the Python SDK in the shared golden tests - docs/self-reports.mdx (enabling from Cloud or locally, categories, per-agent support, containers, SDKs, privacy) in the nav; mcp.mdx contrasts the local server with the Cloud gateway; events reference covers the self_report event and self-report.json; TS reference and Python integration pages get their Self Reports sections; README feature bullet; one CHANGELOG entry. - Python is_self_report_tool covers the same per-agent spellings as the CLI and TS SDK (plus the Cursor server-name form) and is tested against the golden files with the description, schema, categories and field order. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + CLAUDE.md | 4 +- README.md | 4 + docs/docs.json | 1 + docs/reference/custom-agents-typescript.mdx | 29 ++++++- docs/reference/events-and-configuration.mdx | 32 ++++++++ docs/reference/mcp.mdx | 17 ++++ docs/self-reports.mdx | 87 +++++++++++++++++++++ docs/start/integrations/crewai.mdx | 15 ++++ docs/start/integrations/custom-agents.mdx | 21 ++++- docs/start/integrations/langchain.mdx | 17 ++++ docs/start/integrations/llamaindex.mdx | 15 ++++ docs/start/integrations/pydantic-ai.mdx | 18 +++++ sdk/python/failproofai_sdk/_self_report.py | 49 +++++++++--- sdk/python/tests/test_self_report.py | 2 +- sdk/python/tests/test_self_report_golden.py | 83 ++++++++++++++++++++ sdk/typescript/README.md | 2 +- 17 files changed, 379 insertions(+), 21 deletions(-) create mode 100644 docs/self-reports.mdx create mode 100644 sdk/python/tests/test_self_report_golden.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 0da47b086..978683061 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## 1.0.18-beta.0 — 2026-11-24 +### Features + +- Self Reports: every hooked agent gets a `report` tool (MCP server `failproofai`, served by `failproofaid` at `http://127.0.0.1:4319/mcp` or by `failproofai mcp` over stdio) to say it is stuck, under six default categories or the organization's own; the hook allows the call before any policy, pause or Jev review and records it as a `self_report` event, the MCP server records it for agents whose hooks do not see MCP calls, the setting comes from Cloud (`selfReport` in desired-state) or `failproofai self-report enable|disable|status|test|sync` and lives in `~/.failproofai/self-report.json`, and both SDKs add `self_report()` / `selfReport()` with ready-made framework tools + ### Fixes - Retire the hook-sync agent and stop publishing its image: `docker-hook-sync/`, its prompt and `build-image.yml` (which pushed `ghcr.io/failproofai/hook-sync` publicly every day) are removed. The agent ran Claude Code with permission checks skipped, a GitHub write token and a Claude token in its environment and no failproofai hooks, after reading a third-party npm README. Nothing had run it since July (FailproofAI/agenteye#1797, #1055) diff --git a/CLAUDE.md b/CLAUDE.md index 6976c9625..26b6578d2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1370,7 +1370,7 @@ sdk/python/ The telemetry SDK (Python, uv, pytest). PyPI dist dependency we declare is a constraint they inherit. `sdk/` is a directory because more languages go beside `python/`, not inside it. - failproofai_sdk/_events.py The 15 public event methods, and the `_pending` map that + failproofai_sdk/_events.py The 16 public event methods, and the `_pending` map that auto-computes duration_ms by pairing start/end events failproofai_sdk/_schema.py One dataclass per event type; `to_dict()` IS the wire format. Frozen byte-for-byte by tests/test_wire_format.py @@ -1385,7 +1385,7 @@ sdk/python/ The telemetry SDK (Python, uv, pytest). PyPI dist on either side. tests/test_spool_contract.py checks the Rust and the TypeScript directly and never skips sdk/typescript/ The telemetry SDK (TypeScript, npm, vitest). npm package - `@failproofai/sdk`. The same 15 events, wire format, + `@failproofai/sdk`. The same 16 events, wire format, spool directory and Evaluator v2 protocol as sdk/python — a fleet running both writes into one pipe. Zero runtime dependencies for the same reason, diff --git a/README.md b/README.md index a23b283a9..ea1a8f266 100644 --- a/README.md +++ b/README.md @@ -284,6 +284,10 @@ hand an agent more autonomy, not less: - **One daemon, always in sync.** The same process ships every run to Cloud and keeps your policies current, so a policy you approve reaches every machine without a redeploy. +- **Agents that say when they're stuck.** [Self Reports](https://docs.befailproof.ai/self-reports) + gives every agent a `report` tool for looping, a broken credential, missing context or a + request it cannot do. No policy can block the call, and each report lands on its + session, so you see where agents get stuck without reading every transcript. --- diff --git a/docs/docs.json b/docs/docs.json index 907ce3131..8a3b30c17 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -152,6 +152,7 @@ "group": "Find and manage failures", "pages": [ "sessions/sentiment", + "self-reports", "audits/overview", "audits/local-audit", "audits/setup", diff --git a/docs/reference/custom-agents-typescript.mdx b/docs/reference/custom-agents-typescript.mdx index 39785bf81..c8ecec672 100644 --- a/docs/reference/custom-agents-typescript.mdx +++ b/docs/reference/custom-agents-typescript.mdx @@ -194,7 +194,7 @@ A `using` block that catches its own failure reports it with `span.fail(error)` ## Event catalog -The same fifteen methods as the Python SDK, in camelCase. Most come in **pairs** — you call the opener, then the closer, and the SDK times the gap. +The same sixteen methods as the Python SDK, in camelCase. Most come in **pairs** — you call the opener, then the closer, and the SDK times the gap. | | Opens | Closes | | --- | --- | --- | @@ -205,7 +205,7 @@ The same fifteen methods as the Python SDK, in camelCase. Most come in **pairs** | **Hooks** | `hookTriggered` | `hookCompleted` | | **Humans** | `humanWait` | `humanInput` | -Three stand alone: `error`, `humanPause`, `humanInterrupt`. +Four stand alone: `error`, `humanPause`, `humanInterrupt`, and `selfReport` (see [Self Reports](#self-reports)). @@ -228,6 +228,7 @@ Every method also takes `sessionId` and `agentId`, which the scopes fill in for | `humanInput` | `inputId` | `response` | | `humanPause` | — | `reason`, `userId` | | `humanInterrupt` | — | `reason`, `userId`, `atStep` | +| `selfReport` | `category` | `detail`, `toolCallId` | Any other key you add becomes a custom payload field. Namespace anything framework-specific `fw_*`; a name that collides with a declared field is refused rather than silently overwriting a promoted column. @@ -393,6 +394,30 @@ Identity is ambient: everything inside `agent()` lands on that run's session wit [`sdk/typescript/examples/research-agent.ts`](https://github.com/FailproofAI/failproofai/blob/main/sdk/typescript/examples/research-agent.ts) in the repository is the complete, runnable version: a real OpenAI tool loop instrumented exactly like this, run in CI on every change as an ES module and as CommonJS. +## Self Reports + +Offer your agent one more tool, `failproofai_report`, so the model can say it is stuck. The call records a `self_report` event in the current session and agent, with `source: "sdk"`, and answers `Recorded.`. See [Self Reports](/self-reports) for the categories. + +With a framework, add the ready-made tool from its subpath: + +```ts +import { selfReportTool } from "@failproofai/sdk/ai"; // Vercel AI SDK +await generateText({ model, prompt, tools: { failproofai_report: selfReportTool(), ...tools } }); + +import { selfReportTool } from "@failproofai/sdk/langchain"; // @langchain/core +createReactAgent({ llm, tools: [selfReportTool(), ...tools] }); +``` + +`@failproofai/sdk/mastra` and `@failproofai/sdk/llamaindex` export the same `selfReportTool()`. With a provider SDK directly: + +```ts +const tools = [failproofai.openaiTool(), ...yours]; // or failproofai.anthropicTool() +const answer = failproofai.handleToolCall(call.name, call.arguments, { toolCallId: call.id }); +if (answer !== null) toolResults.push({ id: call.id, content: answer }); // "Recorded." +``` + +`handleToolCall` returns `null` for any other tool and never throws. `failproofai.selfReport(category, detail)` records a report from your own code, `failproofai.selfReportSpec()` returns `{ name, description, inputSchema }` for any other tool format, and `failproofai.isSelfReportTool(name)` lets you hide the call in your UI. The categories come from `~/.failproofai/self-report.json`, else the six defaults. Edge builds offer the same tools, which answer `Recorded.` and record nothing. + ## Evaluations ```ts diff --git a/docs/reference/events-and-configuration.mdx b/docs/reference/events-and-configuration.mdx index 82e932b12..bafcedf26 100644 --- a/docs/reference/events-and-configuration.mdx +++ b/docs/reference/events-and-configuration.mdx @@ -12,9 +12,24 @@ icon: "list-tree" - Hook triggered and completed - Human wait, input, pause, and interrupt - Explicit errors +- Self reports (`self_report`): an agent saying it is stuck Every event carries a timestamp, session ID, agent ID, event type, and environment. Event-specific fields contain model, tool, correlation, outcome, content, duration, or error data. +### The `self_report` event + +Written when an agent calls the [Self Reports](/self-reports) tool. Besides the common fields it carries: + +| Field | Value | +| --- | --- | +| `category` | The category the agent chose, recorded as given even when it is not on the list | +| `detail` | The agent's one-sentence description of what blocks it, at most 2,000 characters; `""` when it gave none | +| `source` | `mcp` from a coding agent (its hook or failproofai's MCP server), `sdk` from the Python or TypeScript SDK | +| `tool_call_id` | The model's id for the call, when known | +| `integration` | The coding agent it came from, such as `claude` or `hermes` (not set by the SDKs) | + +A report the MCP server records itself is attributed to that agent's newest session in the same working directory within the last 6 hours, else to the session `unattributed`. + ## Inspect an event contract @@ -61,9 +76,26 @@ Do not use `timestamp`, `session_id`, `agent_id`, `type`, or `environment` as cu - `failproofai-sdk` always spools under `~/.failproofai/custom-agents`. `FAILPROOFAI_HOME` relocates that home; the `custom-agents` segment is always appended, so the spool cannot be placed outside it. Only the SDK's own `configure(base_dir=...)` writes elsewhere. `AGENTEYE_HOME` is read by the older `agenteye-collector` to choose what to watch, and no longer affects where the SDK writes. - Environment labels can be set through SDK configuration or `AGENTEYE_ENVIRONMENT`. - Daemon credentials are stored separately from non-secret settings. +- `~/.failproofai/self-report.json` holds the effective [Self Reports](/self-reports) setting every reader uses: the daemon's MCP server, `failproofai mcp`, both SDKs, and `failproofai self-report status`. A missing or unreadable file means off. Use stable, low-cardinality environment names. Commas are not supported in daemon environment labels. +### `self-report.json` + +```json +{ + "version": 1, + "enabled": true, + "source": "cloud", + "categories": [{ "name": "looping", "description": "You keep repeating the same or circular steps without making progress." }], + "guidance": null, + "mcp": { "port": 4319, "url": "http://127.0.0.1:4319/mcp" }, + "updatedAt": "2026-11-25T10:00:00Z" +} +``` + +`source` is `cloud` when `failproofaid` wrote it from your organization's setting, or `local` when `failproofai self-report enable` or `disable` did. The file is written atomically with mode 0644, so agent processes running as another account can read it. `FAILPROOFAI_HOME` moves it with the rest of `~/.failproofai`, and `FAILPROOFAI_SELF_REPORT_PORT`, read when the daemon starts, sets the port. + ## Change an environment label diff --git a/docs/reference/mcp.mdx b/docs/reference/mcp.mdx index 6923d6d3a..731de5d0d 100644 --- a/docs/reference/mcp.mdx +++ b/docs/reference/mcp.mdx @@ -14,6 +14,10 @@ There is one address for everyone, hosted or self-hosted: https://gateway.befailproof.ai/mcp ``` + + This page is about the **Cloud MCP gateway**, which lets you query Failproof AI Cloud from an AI tool. It is not the local `failproofai` MCP server that [Self Reports](#the-local-self-reports-server) adds to your agents. + + ## Connect a client Add the address to your client. The first time a tool is used, your browser opens. Choose where your Failproof AI Cloud is, sign in, pick one organization, and select **Allow**. **Cancel** connects nothing. @@ -116,6 +120,19 @@ Tool calls and their results pass through the hosted Failproof AI gateway on the Results go to the AI tool you connected, and that tool's provider handles them under its own terms. For each tool call, Failproof AI logs the tool's name, its outcome, how long it took, and the organization, never the arguments or results. See the [privacy policy](https://befailproof.ai/privacy/). +## The local Self Reports server + +[Self Reports](/self-reports) registers a different MCP server in your agents, also named `failproofai`. It runs on your machine, serves one tool, `report`, and needs no sign-in: + +| | Cloud MCP gateway | Local Self Reports server | +| --- | --- | --- | +| Address | `https://gateway.befailproof.ai/mcp` | `http://127.0.0.1:4319/mcp` (served by `failproofaid`), or `failproofai mcp` over stdio | +| Who adds it | You, in each client | failproofai, in every agent with failproofai hooks, while Self Reports is on | +| What it offers | Your organization's data, with your permissions | One `report` tool an agent calls when it is stuck | +| Sign-in | OAuth, one organization per connection | None. It answers only on `127.0.0.1` and refuses requests from web pages | + +Both use the name `failproofai`. If you added the gateway under that name in an agent failproofai hooks, failproofai leaves your entry alone and `failproofai self-report status` reports a conflict. To use both, rename the gateway entry, for example to `failproofai-cloud`, and run `failproofai self-report sync`. + ## Troubleshooting | What you see | What to do | diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx new file mode 100644 index 000000000..0d890a10a --- /dev/null +++ b/docs/self-reports.mdx @@ -0,0 +1,87 @@ +--- +title: "Self Reports" +description: "Let your agents tell you when they are stuck: looping, a broken credential, missing context, or a request they cannot do." +icon: "flag" +--- + +Self Reports gives every agent one extra tool, `report`. An agent that is blocked and cannot make progress on its own calls it with a category and one factual sentence. Failproof AI records the call as a `self_report` event on the agent's session, and the tool answers `Recorded.`. + +A report never unblocks the agent and never changes a decision. Afterwards the agent works around the problem or tells the user what is blocking it. No policy can block or rewrite a report: failproofai's hook allows the call before any policy, session pause, or Jev review runs. + +## Turn it on + + + + On a machine connected to Failproof AI Cloud, the setting comes from your organization. + + 1. Go to **settings → self reports**. + 2. Switch it on. Keep the default categories or write your own, and optionally add guidance for the agents. + + Every connected machine picks the change up on its next policy poll. `failproofaid` writes `~/.failproofai/self-report.json` and adds the `failproofai` MCP server to every agent that has failproofai hooks, or removes it when you switch the feature off. + + On a Cloud-managed machine, `failproofai self-report enable` and `disable` refuse and point you to the dashboard. + + + ```bash + failproofai self-report enable + failproofai self-report status + failproofai self-report test --agent claude + ``` + + `enable` writes the `selfReport` block of `~/.failproofai/config.json` and `~/.failproofai/self-report.json`, then registers the MCP server in every agent with failproofai hooks. To replace the default categories, pass `--categories-file `, a JSON list of `{name, description}`. To append instructions to the tool's description, pass `--guidance ""`. `failproofai self-report disable` turns it off and removes the MCP entries, keeping your categories for next time. + + `test` sends one report end to end as the agent you name and shows where it landed. + + + +## Categories + +An organization's own list replaces these entirely. Names are lowercase letters, digits, and underscores; a list holds 1 to 32 categories. + +| Category | Description shown to the agent | +| --- | --- | +| `looping` | You keep repeating the same or circular steps without making progress. | +| `cannot_do_request` | The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating. | +| `invalid_tool_or_credential` | A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. | +| `missing_context` | Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. | +| `repeated_tool_failure` | A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. | +| `task_failure` | You genuinely tried and could not complete the task. Not for refusals or policy blocks. | + +A report with a category that is not on the list is still recorded under the name the agent gave. The detail is cut to 2,000 characters. + +## Agent support + +failproofai registers one MCP server, named `failproofai`, in each agent's user-level MCP settings. When `failproofaid` runs on the machine, the entry points at the daemon's local server, `http://127.0.0.1:4319/mcp` (set `FAILPROOFAI_SELF_REPORT_PORT` to move it). Otherwise it runs `failproofai mcp` over stdio. Every entry is marked as failproofai's, so removing it never touches a server you added. + +Where an agent's hooks see MCP tool calls, the hook records the report. Where they do not, failproofai's MCP server records it and attributes it to that agent's newest session in the same working directory. + +| Agent | Where the server is registered | Recorded by | +| --- | --- | --- | +| Claude Code | `~/.claude.json` | Hook | +| Codex | `~/.codex/config.toml` | Hook | +| Cursor | `~/.cursor/mcp.json` | Hook, through Cursor's MCP hook (`beforeMCPExecution`). failproofai does not install that hook yet, so reports from Cursor are not recorded yet | +| Copilot CLI | `~/.copilot/mcp-config.json` | MCP server | +| OpenCode | `~/.config/opencode/opencode.json` | MCP server | +| Pi | `~/.pi/agent/mcp.json` | MCP server | +| Hermes | Each profile's `config.yaml` | MCP server | +| OpenClaw | Each profile's `openclaw.json` | MCP server | +| Factory | `~/.factory/mcp.json` | MCP server | +| Devin | `~/.config/devin/mcp_config.json` | MCP server | +| Antigravity | `~/.gemini/config/mcp_config.json` | MCP server | +| Goose | `~/.config/goose/config.yaml` | MCP server | + +`failproofai self-report status` shows, per agent, whether the server is registered and over which transport. If an MCP server named `failproofai` that failproofai did not write is already there, such as the [Cloud MCP gateway](/reference/mcp) added under that name, it is left alone and reported as a conflict. + +## Containers + +In a container, run `failproofaid` in the foreground as the container's main process, with the agent started beside it. Reports, like every other hook event, reach Failproof AI Cloud only through the daemon: without it, the agent still gets the tool over stdio, but reports stay on disk in the container. + +## Your own agents + +The Python and TypeScript SDKs offer the same tool, named `failproofai_report`, as ready-made tools for LangChain, LangGraph, CrewAI, LlamaIndex, Pydantic AI, the Vercel AI SDK and Mastra, and as raw OpenAI and Anthropic tool definitions. See [Python custom agents](/start/integrations/custom-agents#self-reports) and [TypeScript custom agents](/reference/custom-agents-typescript#self-reports). SDK reports carry `source: "sdk"`; reports from coding agents carry `source: "mcp"`. + +## Privacy + +The tool's description tells the agent there is no need to mention the report to the user. Terminal agents still show the tool call on screen; in your own UI, hide it with `is_self_report_tool(name)` (Python) or `isSelfReportTool(name)` (TypeScript). + +A report holds the category, the agent's one-sentence detail, and the session, agent, and environment it came from. It is uploaded with the session's other events. diff --git a/docs/start/integrations/crewai.mdx b/docs/start/integrations/crewai.mdx index abfcc0b42..fa80e5fbe 100644 --- a/docs/start/integrations/crewai.mdx +++ b/docs/start/integrations/crewai.mdx @@ -180,6 +180,21 @@ human_input the answer, with the wait measured Because the `Task(human_input=True)` path is a wrapper around CrewAI's input provider rather than an event subscription, it is restored on `uninstrument()` and re-raises whatever `input()` raises, `KeyboardInterrupt` included, unchanged. +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, missing context, a request it cannot do. + +```python +from crewai import Agent +from failproofai_sdk.integrations.crewai import self_report_tool + +analyst = Agent(role="Analyst", goal="...", backstory="...", tools=[search, self_report_tool()]) +``` + +A CrewAI `BaseTool`. While the adapter is installed the report lands on the agent that ran the tool; otherwise on the enclosing `failproofai_sdk.session()`. + +The tool's description and its `category` enum come from `~/.failproofai/self-report.json` (your organization's categories when Self Reports is on in Failproof AI Cloud, or set locally with `failproofai self-report enable`), and fall back to six built-in categories. It always answers `Recorded.` and changes nothing; the call becomes a `self_report` event on the agent's session. To keep it out of a transcript you show users, filter on `failproofai_sdk.is_self_report_tool(name)`. See [Self Reports](/self-reports). + ## Common problems diff --git a/docs/start/integrations/custom-agents.mdx b/docs/start/integrations/custom-agents.mdx index 778a69708..8e8d8fde5 100644 --- a/docs/start/integrations/custom-agents.mdx +++ b/docs/start/integrations/custom-agents.mdx @@ -74,7 +74,7 @@ The error is emitted before `agent_end`, because the dashboard closes the span a ## The event methods -Fifteen methods in six families. Most come in pairs — you emit the opener, then the closer, and the SDK measures the span between them. +Sixteen methods in seven families. Most come in pairs — you emit the opener, then the closer, and the SDK measures the span between them. | Family | Opens | Closes | Standalone | | --- | --- | --- | --- | @@ -85,6 +85,7 @@ Fifteen methods in six families. Most come in pairs — you emit the opener, the | **Hooks** | `hook_triggered` | `hook_completed` | — | | **Humans** | `human_wait` | `human_input` | `human_pause`, `human_interrupt` | | **Failures** | — | — | `error` | +| **Self Reports** | — | — | `self_report` | Prefer the scopes — `agent()` and `tool_call()` — wherever they fit. They guarantee the closing event even when the body raises. Reach for these methods directly when your control flow doesn't nest, such as a model call inside a helper. @@ -625,7 +626,7 @@ flowchart LR | Stage | Job | Runs in | | --- | --- | --- | -| Adapter | Translates a framework callback into one of 15 event types | Your process | +| Adapter | Translates a framework callback into one of 16 event types | Your process | | Writer | Queues, batches, writes JSONL atomically | Your process, background thread | | Spool | Durable handoff, survives your process exiting | Local disk | | Daemon | Watches the spool, ships batches, deletes what it shipped | Your machine | @@ -704,6 +705,22 @@ The default is right in production and wrong while debugging, because it can onl + +## Self Reports + +Give the model one more tool, so it can say when it is stuck. With a provider SDK directly, offer the tool and route the call: + +```python +tools = [failproofai_sdk.openai_tool(), *my_tools] # anthropic_tool() for Claude +for call in message.tool_calls: + if failproofai_sdk.is_self_report_tool(call.function.name): + result = failproofai_sdk.handle_tool_call( + call.function.name, call.function.arguments, tool_call_id=call.id + ) # always "Recorded." +``` + +To record a report from your own code, call `failproofai_sdk.self_report("missing_context", "The customer id was never provided.")`. The categories and the tool's wording come from `~/.failproofai/self-report.json`, else six built-in categories. See [Self Reports](/self-reports). + ## Common problems diff --git a/docs/start/integrations/langchain.mdx b/docs/start/integrations/langchain.mdx index 9d5427ddb..1b2893f98 100644 --- a/docs/start/integrations/langchain.mdx +++ b/docs/start/integrations/langchain.mdx @@ -191,6 +191,23 @@ with failproofai_sdk.session(): `human_wait` to `human_input` carries the prompt and the answer (both are dropped under `capture_content=False`, along with retrieval document sources — the document count survives). `agent_pause` to `agent_resume` is the only pair that feeds paused time, so without it a ten-minute human wait is billed as active agent time. The root span stays open across the gap, keeping both calls in one session. +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, missing context, a request it cannot do. + +```python +from failproofai_sdk.integrations.langchain import self_report_tool +from langgraph.prebuilt import ToolNode + +tools = [search, self_report_tool()] +model = model.bind_tools(tools) +graph.add_node("tools", ToolNode(tools)) +``` + +A `StructuredTool`. While the adapter is installed the report lands on the agent whose run called it, with the model's `tool_call_id`; otherwise on the enclosing `failproofai_sdk.session()`. + +The tool's description and its `category` enum come from `~/.failproofai/self-report.json` (your organization's categories when Self Reports is on in Failproof AI Cloud, or set locally with `failproofai self-report enable`), and fall back to six built-in categories. It always answers `Recorded.` and changes nothing; the call becomes a `self_report` event on the agent's session. To keep it out of a transcript you show users, filter on `failproofai_sdk.is_self_report_tool(name)`. See [Self Reports](/self-reports). + ## Common problems diff --git a/docs/start/integrations/llamaindex.mdx b/docs/start/integrations/llamaindex.mdx index 22a630bd4..cee11e008 100644 --- a/docs/start/integrations/llamaindex.mdx +++ b/docs/start/integrations/llamaindex.mdx @@ -210,6 +210,21 @@ async def ask_human(question: str) -> str: `ctx.wait_for_event` in a plain workflow step is not captured. The runtime catches the drop before it reaches the dispatcher, so the step exits and re-runs later with no signal to key a pause on. The FunctionAgent pattern, which LlamaIndex documents, waits inside a tool and is captured in full. +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, missing context, a request it cannot do. + +```python +from llama_index.core.agent.workflow import FunctionAgent +from failproofai_sdk.integrations.llama_index import self_report_tool + +agent = FunctionAgent(name="researcher", llm=llm, tools=[search, self_report_tool()]) +``` + +A `FunctionTool`. While the adapter is installed the report lands on the agent whose tool span called it; otherwise on the enclosing `failproofai_sdk.session()`. + +The tool's description and its `category` enum come from `~/.failproofai/self-report.json` (your organization's categories when Self Reports is on in Failproof AI Cloud, or set locally with `failproofai self-report enable`), and fall back to six built-in categories. It always answers `Recorded.` and changes nothing; the call becomes a `self_report` event on the agent's session. To keep it out of a transcript you show users, filter on `failproofai_sdk.is_self_report_tool(name)`. See [Self Reports](/self-reports). + ## Common problems diff --git a/docs/start/integrations/pydantic-ai.mdx b/docs/start/integrations/pydantic-ai.mdx index 88cf4736a..312e578e7 100644 --- a/docs/start/integrations/pydantic-ai.mdx +++ b/docs/start/integrations/pydantic-ai.mdx @@ -174,6 +174,24 @@ failproofai_sdk.instrument( ) ``` +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, missing context, a request it cannot do. + +```python +from pydantic_ai import Agent +from failproofai_sdk.integrations.pydantic_ai import FailproofAI, self_report_tool + +agent = Agent("openai:gpt-5.6-sol", tools=[self_report_tool()]) + +# or let the capability add it to the agent +agent = Agent("openai:gpt-5.6-sol", capabilities=[FailproofAI(self_report=True)]) +``` + +A Pydantic AI `Tool` carrying the model's `tool_call_id`. `self_report=True` is opt-in: the capability otherwise only observes, and adding a tool changes what the model sees. + +The tool's description and its `category` enum come from `~/.failproofai/self-report.json` (your organization's categories when Self Reports is on in Failproof AI Cloud, or set locally with `failproofai self-report enable`), and fall back to six built-in categories. It always answers `Recorded.` and changes nothing; the call becomes a `self_report` event on the agent's session. To keep it out of a transcript you show users, filter on `failproofai_sdk.is_self_report_tool(name)`. See [Self Reports](/self-reports). + ## Common problems diff --git a/sdk/python/failproofai_sdk/_self_report.py b/sdk/python/failproofai_sdk/_self_report.py index 4c797164f..40397a6af 100644 --- a/sdk/python/failproofai_sdk/_self_report.py +++ b/sdk/python/failproofai_sdk/_self_report.py @@ -87,17 +87,28 @@ _MAX_DESCRIPTION = 500 _MAX_GUIDANCE = 2000 -#: Every spelling the report tool reaches a host under: the SDK name, and the -#: MCP tool `report` on server `failproofai` as each agent prefixes it. -_TOOL_NAMES = frozenset( - { - TOOL_NAME, - "mcp__failproofai__report", - "failproofai__report", - "failproofai.report", - "failproofai/report", - } +#: Every spelling the report tool reaches a host under (case-insensitive, +#: exact): the SDK name (also OpenCode's), and the MCP tool `report` on server +#: `failproofai` as each agent prefixes it: Claude Code, Codex, Pi, Factory and +#: Devin `mcp__failproofai__report`, Factory's matcher form +#: `failproofai___report`, Hermes and Antigravity `mcp_failproofai_report`, +#: OpenClaw and Goose `failproofai__report`, plus other server-qualified forms. +#: The CLI and the TypeScript SDK test the same list against the repository's +#: test-fixtures/self-report/tool-names.golden.txt. +TOOL_SPELLINGS: tuple[str, ...] = ( + "mcp__failproofai__report", + "failproofai___report", + "failproofai__report", + "failproofai_report", + "failproofai.report", + "failproofai/report", + "failproofai:report", + "mcp_failproofai_report", + "mcp__failproofai_report", + "mcp:failproofai:report", + "mcp:failproofai/report", ) +_TOOL_NAMES = frozenset(TOOL_SPELLINGS) # --------------------------------------------------------------------------- @@ -272,14 +283,26 @@ def self_report(category: str, detail: str | None = "", **fields: Any) -> None: _runtime.event.self_report(category, detail, **fields) -def is_self_report_tool(name: Any) -> bool: +def is_self_report_tool(name: Any, server: Any = None) -> bool: """True for the report tool under any of its names. Use it to hide the call from your UI or transcript: `failproofai_report` (this SDK), and the MCP tool as agents spell it (`mcp__failproofai__report`, - `failproofai__report`, `failproofai.report`, ...). + `mcp_failproofai_report`, `failproofai__report`, ...). `server` is for + hosts that name an MCP tool and its server separately (Cursor's + `tool_name` + `mcp_server_name`): a bare `report` matches only when the + server is `failproofai`. """ - return isinstance(name, str) and name.strip() in _TOOL_NAMES + if not isinstance(name, str): + return False + lower = name.strip().lower() + if lower in _TOOL_NAMES: + return True + return ( + isinstance(server, str) + and server.strip().lower() == "failproofai" + and lower in ("report", "mcp:report") + ) def _coerce_text(value: Any) -> str: diff --git a/sdk/python/tests/test_self_report.py b/sdk/python/tests/test_self_report.py index 2356b2c97..dcc4b30fd 100644 --- a/sdk/python/tests/test_self_report.py +++ b/sdk/python/tests/test_self_report.py @@ -344,7 +344,7 @@ def test_is_self_report_tool_accepts_every_spelling(name): @pytest.mark.parametrize( - "name", ["report", "bash", "mcp__other__report", "failproofai:report", "failproofai-report", "", None, 3] + "name", ["report", "MCP:report", "bash", "mcp__other__report", "failproofai_report_x", "failproofai-report", "", None, 3] ) def test_is_self_report_tool_rejects_others(name): assert not fp.is_self_report_tool(name) diff --git a/sdk/python/tests/test_self_report_golden.py b/sdk/python/tests/test_self_report_golden.py new file mode 100644 index 000000000..933615603 --- /dev/null +++ b/sdk/python/tests/test_self_report_golden.py @@ -0,0 +1,83 @@ +"""Self Reports: the Python side of the repository's shared golden files. + +The Rust daemon, the CLI and the TypeScript SDK are tested against the same +files in test-fixtures/self-report/, so the tool description, input schema, +default categories, recognised tool names and the `self_report` event's field +order cannot drift between the four implementations. Change a golden file only +together with every implementation. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path + +import pytest + +import failproofai_sdk as fp +from failproofai_sdk import _self_report +from failproofai_sdk._schema import SelfReportEvent + +_HERE = Path(__file__).resolve() +REPO_ROOT = _HERE.parents[3] if len(_HERE.parents) > 3 else _HERE.parent +GOLDEN = REPO_ROOT / "test-fixtures" / "self-report" + +#: CI sets this, so a missing golden directory fails instead of skipping. +REQUIRE = os.environ.get("FAILPROOFAI_SDK_REQUIRE_CONTRACT", "").strip().lower() in {"1", "true", "yes"} + +pytestmark = pytest.mark.skipif( + not GOLDEN.is_dir() and not REQUIRE, + reason="the golden files live in the failproofai repository, not in the sdist", +) + + +def golden(name: str) -> str: + return (GOLDEN / name).read_text(encoding="utf-8") + + +def lines(name: str) -> list[str]: + return [line for line in golden(name).split("\n") if line] + + +def test_description_byte_for_byte(): + cats = [dict(c) for c in _self_report.DEFAULT_CATEGORIES] + assert _self_report.describe(cats) == golden("description.golden.txt") + assert _self_report.describe(cats, "Report a missing repository as missing_context.") == golden( + "description-guidance.golden.txt" + ) + + +def test_input_schema_byte_for_byte(): + spec = _self_report.self_report_spec(categories=[dict(c) for c in _self_report.DEFAULT_CATEGORIES]) + assert json.dumps(spec["input_schema"], separators=(",", ":"), ensure_ascii=False) + "\n" == golden( + "input-schema.golden.json" + ) + + +def test_default_categories(): + assert [dict(c) for c in _self_report.DEFAULT_CATEGORIES] == json.loads(golden("categories.golden.json")) + + +def test_tool_names(): + assert list(_self_report.TOOL_SPELLINGS) == lines("tool-names.golden.txt") + for name in lines("tool-names.golden.txt"): + assert fp.is_self_report_tool(name), name + assert fp.is_self_report_tool(name.upper()), name + assert fp.is_self_report_tool("report", "failproofai") + assert fp.is_self_report_tool("MCP:report", "failproofai") + assert not fp.is_self_report_tool("report", "linear") + assert not fp.is_self_report_tool("MCP:report") + + +def test_event_field_order(): + spec = json.loads(golden("event-fields.golden.json")) + base = dict( + timestamp="2026-11-25T10:00:00.000000Z", + session_id="s1", + agent_id="a1", + category="looping", + detail="Same step again.", + ) + assert list(SelfReportEvent(**base).to_dict()) == spec["order"] + assert list(SelfReportEvent(**base, tool_call_id="call_1").to_dict()) == spec["order"] + spec["optional"] diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index dbaaae7d6..58f845831 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -23,7 +23,7 @@ and `failproofaid` — the daemon the `failproofai` CLI installs — picks them Nothing here opens a socket, and nothing blocks your agent loop on the network. This is the TypeScript counterpart to the Python -[`failproofai-sdk`](https://pypi.org/project/failproofai-sdk/). Same 15 events, +[`failproofai-sdk`](https://pypi.org/project/failproofai-sdk/). Same 16 events, same wire format, same spool directory: a fleet running both writes into one pipe, and the dashboard cannot tell which language wrote what. From 6f595a9190110352eab9c1c00d1ede523fd990fd Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 26 Nov 2026 13:47:00 +0530 Subject: [PATCH 10/54] [self-reports] Live transport check, startup sync, status health, MCP server instructions - sync picks HTTP only when the daemon answers a Ping on its socket AND 127.0.0.1:/mcp answers an MCP initialize; otherwise stdio. A stale socket file no longer produces an HTTP entry pointing at a dead port. - failproofaid runs `failproofai self-report sync --quiet` once at startup, after its MCP server reports its bind, when self-report.json says enabled. - `self-report status` shows each agent's transport, endpoint and health, and re-syncs agents left on an HTTP endpoint that does not answer. - "Agents updated." only when a sync changed a file. - Both MCP servers return `instructions` in the initialize result (shared golden files); none while the feature is off. - Fix the hook-activity path in the hooks source's module comment. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/self-report-golden.test.ts | 9 + __tests__/hooks/self-report-install.test.ts | 209 ++++++++++++++---- __tests__/hooks/self-report.test.ts | 68 ++++++ bin/failproofai.mjs | 4 +- crates/failproofaid/src/main.rs | 13 +- crates/failproofaid/src/self_report.rs | 59 ++++- crates/fpai-collect/src/self_report.rs | 88 ++++++-- crates/fpai-collect/src/sources/hooks/mod.rs | 3 +- crates/fpai-collect/tests/self_report_mcp.rs | 58 +++++ docs/self-reports.mdx | 8 +- src/hooks/daemon-client.ts | 16 ++ src/hooks/manager.ts | 2 +- src/hooks/self-report-cli.ts | 118 +++++++--- src/hooks/self-report-install.ts | 126 +++++++++-- src/hooks/self-report-mcp.ts | 19 +- src/hooks/self-report.ts | 23 ++ .../instructions-guidance.golden.txt | 3 + .../self-report/instructions.golden.txt | 1 + 19 files changed, 709 insertions(+), 120 deletions(-) create mode 100644 test-fixtures/self-report/instructions-guidance.golden.txt create mode 100644 test-fixtures/self-report/instructions.golden.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 978683061..87ea94286 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Features -- Self Reports: every hooked agent gets a `report` tool (MCP server `failproofai`, served by `failproofaid` at `http://127.0.0.1:4319/mcp` or by `failproofai mcp` over stdio) to say it is stuck, under six default categories or the organization's own; the hook allows the call before any policy, pause or Jev review and records it as a `self_report` event, the MCP server records it for agents whose hooks do not see MCP calls, the setting comes from Cloud (`selfReport` in desired-state) or `failproofai self-report enable|disable|status|test|sync` and lives in `~/.failproofai/self-report.json`, and both SDKs add `self_report()` / `selfReport()` with ready-made framework tools +- Self Reports: every hooked agent gets a `report` tool (MCP server `failproofai`, served by `failproofaid` at `http://127.0.0.1:4319/mcp` or by `failproofai mcp` over stdio) to say it is stuck, under six default categories or the organization's own; the hook allows the call before any policy, pause or Jev review and records it as a `self_report` event, the MCP server records it for agents whose hooks do not see MCP calls, the setting comes from Cloud (`selfReport` in desired-state) or `failproofai self-report enable|disable|status|test|sync` and lives in `~/.failproofai/self-report.json`, and both SDKs add `self_report()` / `selfReport()` with ready-made framework tools; the server's initialize result carries short instructions (agents that defer MCP tools, like Claude Code, still see them), and HTTP vs stdio is chosen from a live daemon check that the daemon re-runs at startup ### Fixes diff --git a/__tests__/hooks/self-report-golden.test.ts b/__tests__/hooks/self-report-golden.test.ts index b70d2c17d..328335d26 100644 --- a/__tests__/hooks/self-report-golden.test.ts +++ b/__tests__/hooks/self-report-golden.test.ts @@ -19,6 +19,7 @@ import { isSelfReportCursorCall, isSelfReportToolName, selfReportInputSchema, + selfReportInstructions, } from "../../src/hooks/self-report"; import { writeSelfReportEvent } from "../../src/hooks/self-report-mcp"; @@ -35,6 +36,14 @@ describe("Self Reports golden files (CLI)", () => { ).toBe(golden("description-guidance.golden.txt")); }); + it("builds the MCP server instructions byte for byte", () => { + expect(selfReportInstructions(SELF_REPORT_DEFAULT_CATEGORIES, null)).toBe(golden("instructions.golden.txt")); + expect( + selfReportInstructions(SELF_REPORT_DEFAULT_CATEGORIES, "Report a missing repository as missing_context."), + ).toBe(golden("instructions-guidance.golden.txt")); + expect(golden("instructions.golden.txt").length).toBeLessThan(600); + }); + it("builds the input schema byte for byte", () => { expect(`${JSON.stringify(selfReportInputSchema(SELF_REPORT_DEFAULT_CATEGORIES))}\n`).toBe(golden("input-schema.golden.json")); }); diff --git a/__tests__/hooks/self-report-install.test.ts b/__tests__/hooks/self-report-install.test.ts index f30408643..8d7815911 100644 --- a/__tests__/hooks/self-report-install.test.ts +++ b/__tests__/hooks/self-report-install.test.ts @@ -6,9 +6,14 @@ import { dirname, resolve } from "node:path"; import { parse as parseToml } from "smol-toml"; import { parse as parseYaml } from "yaml"; import { parse as parseJsonc } from "jsonc-parser/lib/esm/main.js"; +import { createServer as createHttpServer, type Server as HttpServer } from "node:http"; +import { createServer as createNetServer, type Server as NetServer } from "node:net"; import { SELF_REPORT_MCP_TARGETS, isOurMcpEntry, + probeSelfReportHttp, + selfReportDaemonLive, + selfReportSyncChanged, readSelfReportMcpSettings, removeSelfReportMcp, selfReportRegistrationStatus, @@ -27,7 +32,7 @@ function enabledOpts(extra: Partial = {}, daemon = tru binaryPath: CLI, ...extra, deps: { - daemonSocketPresent: () => daemon, + daemonLive: async () => daemon, hooksInstalled: () => true, settings: { enabled: true, port: 4319 }, ...extra.deps, @@ -89,7 +94,7 @@ const USER_JSON = (container: string[]) => { describe("syncSelfReportMcp: every agent round-trips", () => { for (const agent of INTEGRATION_TYPES) { const target = SELF_REPORT_MCP_TARGETS[agent]; - it(`${agent}: adds, is idempotent, keeps the user's entries, removes only ours`, () => { + it(`${agent}: adds, is idempotent, keeps the user's entries, removes only ours`, async () => { const path = pathOf(agent); let original: string; if (target.format === "toml") { @@ -103,7 +108,7 @@ describe("syncSelfReportMcp: every agent round-trips", () => { } put(path, original); - const first = syncSelfReportMcp(enabledOpts({ agents: [agent] })); + const first = await syncSelfReportMcp(enabledOpts({ agents: [agent] })); expect(first.map((r) => [r.action, r.status, r.transport])).toEqual( first.map(() => ["added", "ok", "http"]), ); @@ -115,7 +120,7 @@ describe("syncSelfReportMcp: every agent round-trips", () => { expect(afterAdd).toContain("mine"); expect(afterAdd).toContain(target.format === "json" && agent === "claude" ? "dark" : target.format === "toml" ? "# inline note" : target.format === "yaml" ? "# my server" : "// a comment"); - const second = syncSelfReportMcp(enabledOpts({ agents: [agent] })); + const second = await syncSelfReportMcp(enabledOpts({ agents: [agent] })); expect(second.every((r) => r.action === "unchanged" && r.status === "ok")).toBe(true); expect(read(path)).toBe(afterAdd); @@ -134,82 +139,82 @@ describe("syncSelfReportMcp: every agent round-trips", () => { }); describe("transport choice", () => { - it("uses stdio with the CLI path and --agent when no daemon socket is present", () => { - syncSelfReportMcp(enabledOpts({ agents: ["claude", "codex", "opencode", "goose"] }, false)); + it("uses stdio with the CLI path and --agent when no daemon is live", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["claude", "codex", "opencode", "goose"] }, false)); expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"] }); expect(entryIn("codex")).toEqual({ command: CLI, args: ["mcp", "--agent", "codex"] }); expect(entryIn("opencode")).toEqual({ type: "local", command: [CLI, "mcp", "--agent", "opencode"], enabled: true }); expect(entryIn("goose")).toMatchObject({ type: "stdio", cmd: CLI, args: ["mcp", "--agent", "goose"], enabled: true }); }); - it("switches an existing entry between transports in place", () => { - syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); - const r = syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, true)); + it("switches an existing entry between transports in place", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, true)); expect(r[0]).toMatchObject({ action: "updated", transport: "http" }); const text = read(pathOf("codex")); expect(text.match(/\[mcp_servers\.failproofai\]/g)).toHaveLength(1); expect(entryIn("codex")).toEqual({ url: "http://127.0.0.1:4319/mcp?agent=codex" }); }); - it("takes the port from self-report.json", () => { + it("takes the port from self-report.json", async () => { const p = resolve(home, ".failproofai", "self-report.json"); put(p, JSON.stringify({ version: 1, enabled: true, mcp: { port: 5555, url: "http://127.0.0.1:5555/mcp" } })); expect(readSelfReportMcpSettings()).toEqual({ enabled: true, port: 5555 }); - syncSelfReportMcp({ quiet: true, agents: ["cursor"], deps: { daemonSocketPresent: () => true, hooksInstalled: () => true } }); + await syncSelfReportMcp({ quiet: true, agents: ["cursor"], deps: { daemonLive: async () => true, hooksInstalled: () => true } }); expect(entryIn("cursor")).toEqual({ url: "http://127.0.0.1:5555/mcp?agent=cursor" }); }); - it("reads a missing or broken settings file as disabled", () => { + it("reads a missing or broken settings file as disabled", async () => { expect(readSelfReportMcpSettings().enabled).toBe(false); put(resolve(home, ".failproofai", "self-report.json"), "{nope"); expect(readSelfReportMcpSettings()).toEqual({ enabled: false, port: 4319 }); }); - it("reports an error, writing nothing, when stdio is needed and no CLI is known", () => { + it("reports an error, writing nothing, when stdio is needed and no CLI is known", async () => { const base = enabledOpts({ agents: ["cursor"] }, false); - const r = syncSelfReportMcp({ ...base, binaryPath: undefined, deps: { ...base.deps, resolveCliPath: () => null } }); + const r = await syncSelfReportMcp({ ...base, binaryPath: undefined, deps: { ...base.deps, resolveCliPath: () => null } }); expect(r[0]).toMatchObject({ status: "error", action: "skipped" }); expect(existsSync(pathOf("cursor"))).toBe(false); }); }); describe("ownership", () => { - it("never touches a failproofai entry it did not write (e.g. the Cloud MCP gateway)", () => { + it("never touches a failproofai entry it did not write (e.g. the Cloud MCP gateway)", async () => { const path = pathOf("claude"); const foreign = { mcpServers: { failproofai: { type: "http", url: "https://gateway.example.com/mcp" } } }; put(path, JSON.stringify(foreign, null, 2) + "\n"); const before = read(path); - expect(syncSelfReportMcp(enabledOpts({ agents: ["claude"] }))[0]).toMatchObject({ status: "conflict", action: "skipped" }); + expect((await syncSelfReportMcp(enabledOpts({ agents: ["claude"] })))[0]).toMatchObject({ status: "conflict", action: "skipped" }); expect(removeSelfReportMcp({ agents: ["claude"], quiet: true })[0]).toMatchObject({ status: "conflict" }); expect(read(path)).toBe(before); }); - it("treats a hand-written codex [mcp_servers.failproofai] outside our markers as foreign", () => { + it("treats a hand-written codex [mcp_servers.failproofai] outside our markers as foreign", async () => { const path = pathOf("codex"); put(path, '[mcp_servers.failproofai]\nurl = "http://127.0.0.1:4319/mcp?agent=codex"\n'); const before = read(path); - expect(syncSelfReportMcp(enabledOpts({ agents: ["codex"] }))[0].status).toBe("conflict"); + expect((await syncSelfReportMcp(enabledOpts({ agents: ["codex"] })))[0].status).toBe("conflict"); expect(read(path)).toBe(before); }); - it("refuses a codex config whose inline mcp_servers table would collide, leaving it as is", () => { + it("refuses a codex config whose inline mcp_servers table would collide, leaving it as is", async () => { const path = pathOf("codex"); put(path, 'mcp_servers = { mine = { command = "node" } }\n'); const before = read(path); - const r = syncSelfReportMcp(enabledOpts({ agents: ["codex"] }))[0]; + const r = (await syncSelfReportMcp(enabledOpts({ agents: ["codex"] })))[0]; expect(r.status).toBe("error"); expect(read(path)).toBe(before); }); - it("refuses an unparsable config", () => { + it("refuses an unparsable config", async () => { const path = pathOf("cursor"); put(path, "{ not json"); - const r = syncSelfReportMcp(enabledOpts({ agents: ["cursor"] }))[0]; + const r = (await syncSelfReportMcp(enabledOpts({ agents: ["cursor"] })))[0]; expect(r.status).toBe("error"); expect(read(path)).toBe("{ not json"); }); - it("recognises only our shapes", () => { + it("recognises only our shapes", async () => { expect(isOurMcpEntry({ url: "http://127.0.0.1:4319/mcp?agent=claude" })).toBe(true); expect(isOurMcpEntry({ serverUrl: "http://localhost:4319/mcp?agent=antigravity" })).toBe(true); expect(isOurMcpEntry({ command: "/x/bin/failproofai", args: ["mcp", "--agent", "pi"] })).toBe(true); @@ -220,29 +225,29 @@ describe("ownership", () => { }); describe("which agents", () => { - it("enabled: only hooked agents get an entry; unhooked ones are left alone", () => { - const r = syncSelfReportMcp(enabledOpts({ deps: { hooksInstalled: (a) => a === "claude" } })); + it("enabled: only hooked agents get an entry; unhooked ones are left alone", async () => { + const r = await syncSelfReportMcp(enabledOpts({ deps: { hooksInstalled: (a) => a === "claude" } })); expect(r.filter((x) => x.action === "added").map((x) => x.agent)).toEqual(["claude"]); expect(r.filter((x) => x.agent !== "claude").every((x) => x.status === "not-hooked")).toBe(true); expect(existsSync(pathOf("cursor"))).toBe(false); }); - it("alsoHooked registers agents installHooks just wrote", () => { - const r = syncSelfReportMcp(enabledOpts({ agents: ["cursor"], alsoHooked: ["cursor"], deps: { hooksInstalled: () => false } })); + it("alsoHooked registers agents installHooks just wrote", async () => { + const r = await syncSelfReportMcp(enabledOpts({ agents: ["cursor"], alsoHooked: ["cursor"], deps: { hooksInstalled: () => false } })); expect(r[0].action).toBe("added"); }); - it("disabled: removes ours from every agent, hooked or not", () => { - syncSelfReportMcp(enabledOpts({ agents: ["claude", "factory"] })); - const r = syncSelfReportMcp({ quiet: true, deps: { settings: { enabled: false, port: 4319 }, hooksInstalled: () => false, daemonSocketPresent: () => true } }); + it("disabled: removes ours from every agent, hooked or not", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["claude", "factory"] })); + const r = await syncSelfReportMcp({ quiet: true, deps: { settings: { enabled: false, port: 4319 }, hooksInstalled: () => false, daemonLive: async () => true } }); expect(r.filter((x) => x.action === "removed").map((x) => x.agent).sort()).toEqual(["claude", "factory"]); expect(entryIn("claude")).toBeUndefined(); }); - it("writes every Hermes profile", () => { + it("writes every Hermes profile", async () => { put(resolve(home, ".hermes", "config.yaml"), "model: x\n"); put(resolve(home, ".hermes", "profiles", "work", "config.yaml"), "model: y\n"); - const r = syncSelfReportMcp(enabledOpts({ agents: ["hermes"] })); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["hermes"] })); expect(r.map((x) => x.action)).toEqual(["added", "added"]); for (const p of [resolve(home, ".hermes", "config.yaml"), resolve(home, ".hermes", "profiles", "work", "config.yaml")]) { const doc = parseYaml(read(p)) as { mcp_servers: { failproofai: { url: string } } }; @@ -251,7 +256,7 @@ describe("which agents", () => { } }); - it("honours CLAUDE_CONFIG_DIR, CODEX_HOME and COPILOT_HOME", () => { + it("honours CLAUDE_CONFIG_DIR, CODEX_HOME and COPILOT_HOME", async () => { vi.stubEnv("CLAUDE_CONFIG_DIR", resolve(home, "claude-work")); vi.stubEnv("CODEX_HOME", resolve(home, "codex-x")); vi.stubEnv("COPILOT_HOME", resolve(home, "cop")); @@ -260,28 +265,148 @@ describe("which agents", () => { expect(pathOf("copilot")).toBe(resolve(home, "cop", "mcp-config.json")); }); - it("uses OpenCode v2's mcp.servers when the file already has it", () => { + it("uses OpenCode v2's mcp.servers when the file already has it", async () => { put(pathOf("opencode"), JSON.stringify({ mcp: { servers: { mine: { type: "local", command: ["node"] } } } })); - syncSelfReportMcp(enabledOpts({ agents: ["opencode"] })); + await syncSelfReportMcp(enabledOpts({ agents: ["opencode"] })); const doc = JSON.parse(read(pathOf("opencode"))); expect(doc.mcp.servers.failproofai).toEqual({ type: "remote", url: "http://127.0.0.1:4319/mcp?agent=opencode" }); expect(doc.mcp.failproofai).toBeUndefined(); }); - it("keeps a backup of the file it changed", () => { + it("keeps a backup of the file it changed", async () => { put(pathOf("factory"), '{"mcpServers":{}}\n'); - syncSelfReportMcp(enabledOpts({ agents: ["factory"] })); + await syncSelfReportMcp(enabledOpts({ agents: ["factory"] })); expect(read(`${pathOf("factory")}.failproofai-backup`)).toBe('{"mcpServers":{}}\n'); }); }); +// ── Live transport check ──────────────────────────────────────────────────── + +/** A fake daemon socket: answers every framed request with a framed pong. */ +function fakeDaemon(path: string, answer = true): Promise { + const server = createNetServer((sock) => { + let buf = Buffer.alloc(0); + sock.on("data", (chunk) => { + buf = Buffer.concat([buf, chunk as Buffer]); + if (buf.length < 4 || buf.length < 4 + buf.readUInt32BE(0)) return; + if (!answer) return; // accepted, never answered + const req = JSON.parse(buf.subarray(4, 4 + buf.readUInt32BE(0)).toString("utf8")); + const body = Buffer.from(JSON.stringify({ type: "pong", protocolVersion: req.protocolVersion })); + const head = Buffer.alloc(4); + head.writeUInt32BE(body.length, 0); + sock.end(Buffer.concat([head, body])); + }); + }); + return new Promise((ok) => server.listen(path, () => ok(server))); +} + +/** A fake MCP endpoint on an ephemeral loopback port. */ +function fakeMcp(serverName = "failproofai"): Promise<{ server: HttpServer; port: number }> { + const server = createHttpServer((req, res) => { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", () => { + const msg = JSON.parse(body || "{}"); + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify({ jsonrpc: "2.0", id: msg.id, result: { protocolVersion: "2025-06-18", capabilities: {}, serverInfo: { name: serverName, version: "1" } } })); + }); + }); + return new Promise((ok) => server.listen(0, "127.0.0.1", () => ok({ server, port: (server.address() as { port: number }).port }))); +} + +/** A loopback port nothing listens on. */ +async function deadPort(): Promise { + const { server, port } = await fakeMcp(); + await new Promise((ok) => server.close(ok)); + return port; +} + +const closeAll: Array<() => Promise> = []; +afterEach(async () => { + while (closeAll.length) await closeAll.pop()!(); +}); +function track void): unknown }>(server: T): T { + closeAll.push(() => new Promise((ok) => server.close(() => ok(undefined)))); + return server; +} + +describe("live transport check", () => { + const socket = () => resolve(home, "daemon.sock"); + + it("a leftover socket file with no daemon behind it gives stdio, not a dead HTTP entry", async () => { + // What a hard-killed daemon leaves: the path exists, nothing listens on it. + writeFileSync(socket(), ""); + vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); + const port = await deadPort(); + expect(await selfReportDaemonLive(port)).toBe(false); + const r = await syncSelfReportMcp({ + quiet: true, agents: ["claude"], binaryPath: CLI, + deps: { hooksInstalled: () => true, settings: { enabled: true, port } }, + }); + expect(r[0]).toMatchObject({ action: "added", transport: "stdio" }); + expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"] }); + }); + + it("a daemon answering ping AND an MCP initialize gives http; a later sync moves it back once it is gone", async () => { + vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); + const daemon = await fakeDaemon(socket()); + const { server, port } = await fakeMcp(); + expect(await selfReportDaemonLive(port)).toBe(true); + const opts = { quiet: true, agents: ["claude"] as IntegrationType[], binaryPath: CLI, deps: { hooksInstalled: () => true, settings: { enabled: true, port } } }; + expect((await syncSelfReportMcp(opts))[0]).toMatchObject({ action: "added", transport: "http" }); + expect(entryIn("claude")).toEqual({ type: "http", url: `http://127.0.0.1:${port}/mcp?agent=claude` }); + + await new Promise((ok) => daemon.close(ok)); + await new Promise((ok) => server.close(ok)); + expect((await syncSelfReportMcp(opts))[0]).toMatchObject({ action: "updated", transport: "stdio" }); + }); + + it("needs both halves: a ping without the endpoint, or the endpoint without a ping, is stdio", async () => { + vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); + const daemon = track(await fakeDaemon(socket())); + expect(await selfReportDaemonLive(await deadPort())).toBe(false); + await new Promise((ok) => daemon.close(ok)); + closeAll.pop(); + const { server, port } = await fakeMcp(); + track(server); + expect(await selfReportDaemonLive(port)).toBe(false); + }); + + it("a daemon that accepts but never answers the ping is not live", async () => { + vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); + track(await fakeDaemon(socket(), false)); + const { server, port } = await fakeMcp(); + track(server); + expect(await selfReportDaemonLive(port)).toBe(false); + }, 10_000); + + it("another server on the port is not ours", async () => { + const { server, port } = await fakeMcp("someone-else"); + track(server); + expect(await probeSelfReportHttp(port)).toBe(false); + }); + + it("is not asked when the feature is off or no agent would get an entry", async () => { + const daemonLive = vi.fn(async () => true); + await syncSelfReportMcp({ quiet: true, deps: { daemonLive, hooksInstalled: () => true, settings: { enabled: false, port: 4319 } } }); + await syncSelfReportMcp({ quiet: true, binaryPath: CLI, deps: { daemonLive, hooksInstalled: () => false, settings: { enabled: true, port: 4319 } } }); + expect(daemonLive).not.toHaveBeenCalled(); + }); + + it("selfReportSyncChanged is true only for an add, update or remove", async () => { + const first = await syncSelfReportMcp(enabledOpts({ agents: ["claude"] })); + expect(selfReportSyncChanged(first)).toBe(true); + expect(selfReportSyncChanged(await syncSelfReportMcp(enabledOpts({ agents: ["claude"] })))).toBe(false); + }); +}); + describe("selfReportRegistrationStatus", () => { - it("reports registered, transport, conflict and hooked per file without writing", () => { - syncSelfReportMcp(enabledOpts({ agents: ["claude"] }, false)); + it("reports registered, transport, conflict and hooked per file without writing", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["claude"] }, false)); put(pathOf("cursor"), JSON.stringify({ mcpServers: { failproofai: { url: "https://elsewhere" } } })); const s = selfReportRegistrationStatus({ agents: ["claude", "cursor", "factory"], hooksInstalled: (a) => a === "claude" }); expect(s).toEqual([ - expect.objectContaining({ agent: "claude", hooked: true, registered: true, transport: "stdio", conflict: false }), + expect.objectContaining({ agent: "claude", hooked: true, registered: true, transport: "stdio", endpoint: CLI, conflict: false }), expect.objectContaining({ agent: "cursor", hooked: false, registered: false, conflict: true }), expect.objectContaining({ agent: "factory", hooked: false, registered: false, conflict: false }), ]); @@ -291,7 +416,7 @@ describe("selfReportRegistrationStatus", () => { describe("mergeTomlManagedBlock", () => { const M = { begin: "# >>> b >>>", end: "# <<< b <<<" }; - it("appends, replaces in place and removes byte for byte", () => { + it("appends, replaces in place and removes byte for byte", async () => { const orig = 'a = 1\n[t]\nb = 2 # c\n'; const one = mergeTomlManagedBlock(orig, "# >>> b >>>\nx = 1\n# <<< b <<<\n", M); expect(one).toBe(`${orig}\n# >>> b >>>\nx = 1\n# <<< b <<<\n`); @@ -300,7 +425,7 @@ describe("mergeTomlManagedBlock", () => { expect(two).not.toContain("x = 1"); expect(mergeTomlManagedBlock(two, null, M)).toBe(orig); }); - it("throws on a half block", () => { + it("throws on a half block", async () => { expect(() => mergeTomlManagedBlock("# >>> b >>>\nx=1\n", null, M)).toThrow(); }); }); diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index aeaa23e11..3a28c1c91 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -21,6 +21,7 @@ import { validateSelfReportCategories, validateSelfReportGuidance, writeEffectiveSelfReport, + selfReportInstructions, } from "../../src/hooks/self-report"; import { handleSelfReportRpc, selfReportAgentId, selfReportFindSession } from "../../src/hooks/self-report-mcp"; import { runSelfReportCommand } from "../../src/hooks/self-report-cli"; @@ -249,6 +250,7 @@ describe("failproofai mcp (stdio, spawned)", () => { expect(code).toBe(0); expect(replies.map((r) => r.id)).toEqual([1, 2, 4]); expect(replies[0]).toMatchObject({ result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "failproofai" } } }); + expect((replies[0].result as Record)).not.toHaveProperty("instructions"); expect(replies[1]).toEqual({ jsonrpc: "2.0", id: 2, result: { tools: [] } }); expect(replies[2]).toEqual({ jsonrpc: "2.0", id: 4, result: {} }); }, 30_000); @@ -256,6 +258,9 @@ describe("failproofai mcp (stdio, spawned)", () => { it("lists the report tool from self-report.json and answers a call with exactly Recorded.", async () => { writeEffectiveSelfReport({ enabled: true, categories: [{ name: "looping", description: "loops" }], guidance: "be terse" }); const { replies } = await runMcp(["--agent", "claude"], [INIT, LIST, CALL], home); + expect((replies[0].result as Record).instructions).toBe( + selfReportInstructions([{ name: "looping", description: "loops" }], "be terse"), + ); const tools = (replies[1].result as { tools: Array> }).tools; expect(tools).toHaveLength(1); expect(tools[0].name).toBe("report"); @@ -381,6 +386,69 @@ describe("failproofai self-report enable | disable | status", () => { expect(() => readFileSync(join(home, "config.json"))).toThrow(); }); + const row = (o: Record) => ({ + agent: "claude", path: "/x", hooked: true, registered: true, transport: "http", endpoint: null, conflict: false, ...o, + }) as never; + + it("status shows each agent's actual transport and whether its endpoint answers", async () => { + writeEffectiveSelfReport({ enabled: true }); + const runnable = join(home, "failproofai"); + writeFileSync(runnable, "#!/bin/sh\n", { mode: 0o755 }); + const r = await runSelfReportCommand(["status"], { + skipSync: true, + probeEndpoint: async (_url, port) => port === 4319, + registrations: () => [ + row({ agent: "claude", transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" }), + row({ agent: "codex", transport: "http", endpoint: "http://127.0.0.1:4999/mcp?agent=codex" }), + row({ agent: "cursor", transport: "stdio", endpoint: runnable }), + row({ agent: "factory", transport: "stdio", endpoint: join(home, "missing", "failproofai") }), + ], + }); + const text = r.lines.join("\n"); + expect(text).not.toContain("still works"); + expect(text).toContain("Daemon MCP: http://127.0.0.1:4319/mcp (answering)"); + expect(text).toMatch(/claude +http +http:\/\/127\.0\.0\.1:4319\/mcp\?agent=claude \(answering\)/); + expect(text).toMatch(/codex +http +http:\/\/127\.0\.0\.1:4999\/mcp\?agent=codex \(NOT answering\)/); + expect(text).toMatch(new RegExp(`cursor +stdio +${runnable} \\(runnable\\)`)); + expect(text).toMatch(/factory +stdio +.*\(NOT runnable\)/); + }); + + it("status re-syncs agents left on an HTTP endpoint that is not answering", async () => { + writeEffectiveSelfReport({ enabled: true }); + let synced = 0; + let rows = [row({ transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" })]; + const r = await runSelfReportCommand(["status"], { + probeEndpoint: async () => false, + registrations: () => rows, + sync: async () => { + synced++; + rows = [row({ transport: "stdio", endpoint: "/usr/bin/failproofai" })]; + return [{ agent: "claude", path: "/x", action: "updated", transport: "stdio", status: "ok" }]; + }, + }); + expect(synced).toBe(1); + const text = r.lines.join("\n"); + expect(text).toContain("Repaired:"); + expect(text).toContain("updated in Claude Code (stdio)"); + expect(text).toMatch(/claude +stdio/); + + // Healthy, or skipSync: no write. + synced = 0; + rows = [row({ transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" })]; + await runSelfReportCommand(["status"], { probeEndpoint: async () => true, registrations: () => rows, sync: async () => (synced++, []) }); + await runSelfReportCommand(["status"], { skipSync: true, probeEndpoint: async () => false, registrations: () => rows, sync: async () => (synced++, []) }); + expect(synced).toBe(0); + }); + + it("enable says \"Agents updated.\" only when a sync changed something", async () => { + const quiet = await runSelfReportCommand(["enable"], { probeEndpoint: async () => false, sync: async () => [{ agent: "claude", path: "/x", action: "unchanged", transport: "http", status: "ok" }] }); + expect(quiet.lines.join("\n")).not.toContain("Agents updated."); + const changed = await runSelfReportCommand(["enable"], { probeEndpoint: async () => false, sync: async () => [{ agent: "claude", path: "/x", action: "added", transport: "http", status: "ok" }] }); + expect(changed.lines.join("\n")).toContain("Agents updated."); + const off = await runSelfReportCommand(["disable"], { sync: async () => [] }); + expect(off.lines).toEqual(["✓ Self Reports is off."]); + }); + it("status with no settings file says it is off", async () => { const r = await runSelfReportCommand(["status"], deps); expect(r.exitCode).toBe(0); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index 8a40af63d..bfc55a259 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -810,7 +810,7 @@ async function runCli() { } lastSubcommand = "self-report"; const { syncSelfReportMcp, selfReportSyncLines } = await import("../src/hooks/self-report-install"); - const results = syncSelfReportMcp({ quiet: true }); + const results = await syncSelfReportMcp({ quiet: true }); const failed = results.some((r) => r.status === "error"); if (!subArgs.includes("--quiet")) { const lines = selfReportSyncLines(results); @@ -2201,7 +2201,7 @@ async function runCli() { if (result.applied) { try { const { syncSelfReportMcp, selfReportSyncLines } = await import("../src/hooks/self-report-install"); - const lines = selfReportSyncLines(syncSelfReportMcp({ quiet: true })); + const lines = selfReportSyncLines(await syncSelfReportMcp({ quiet: true })); if (lines.length > 0) process.stdout.write(`${lines.join("\n")}\n`); } catch { // never fail setup over it diff --git a/crates/failproofaid/src/main.rs b/crates/failproofaid/src/main.rs index 55e916cbb..fcc3c65ec 100644 --- a/crates/failproofaid/src/main.rs +++ b/crates/failproofaid/src/main.rs @@ -278,8 +278,14 @@ fn run() -> Result<(), Box> { // runs only with an ingest credential and an OSS machine needs this too. // Always listening; `tools/list` is empty while `self-report.json` says // off. A busy port logs a warning and the daemon carries on. + let (self_report_listening, self_report_ready) = std::sync::mpsc::channel(); let mut self_report_mcp = paths::failproofai_home().ok().and_then(|home| { - fpai_collect::self_report::spawn(home, self_report::port(), shutdown.clone()) + fpai_collect::self_report::spawn( + home, + self_report::port(), + shutdown.clone(), + self_report_listening, + ) }); // Handled rather than `?`-ed, because a bare `?` here returns past every @@ -303,6 +309,11 @@ fn run() -> Result<(), Box> { } }; tracing::info!("listening on {}", socket_path.display()); + // Self Reports: once the MCP server is listening and this socket is bound, + // re-run the agent sync so agents registered over stdio while the daemon + // was down move to its HTTP server (the sync's live check pings this + // socket and the MCP port). Only when self-report.json says enabled. + self_report::spawn_startup_sync(self_report_ready, shutdown.clone()); let run_result = srv.run_until(shutdown); diff --git a/crates/failproofaid/src/self_report.rs b/crates/failproofaid/src/self_report.rs index 78591952b..185cd299c 100644 --- a/crates/failproofaid/src/self_report.rs +++ b/crates/failproofaid/src/self_report.rs @@ -203,6 +203,46 @@ fn now_rfc3339() -> String { // ── `failproofai self-report sync` ─────────────────────────────────────────── +/// How long the startup sync waits for the MCP server to report its bind. +const STARTUP_LISTEN_WAIT: Duration = Duration::from_secs(10); + +/// Whether the startup sync should run: `self-report.json` says enabled. +fn enabled_on_disk(home: &Path) -> bool { + sr::read_settings(&sr::settings_path(home)).is_some_and(|s| s.enabled) +} + +/// Run `failproofai self-report sync --quiet` once at startup, after the MCP +/// server has bound its port (or failed to: then the sync's live check finds +/// no endpoint and keeps agents on stdio, which is right), when the feature is +/// on. Off its own thread: the accept loop starts right after this returns, +/// and the sync child's ping waits in the socket's backlog until it does. +pub fn spawn_startup_sync( + listening: std::sync::mpsc::Receiver, + shutdown: std::sync::Arc, +) { + let started = std::thread::Builder::new() + .name("fpai-self-report-startup".to_string()) + .spawn(move || { + let bound = listening.recv_timeout(STARTUP_LISTEN_WAIT); + if shutdown.load(Ordering::Relaxed) { + return; + } + let Ok(home) = crate::paths::failproofai_home() else { + return; + }; + if !enabled_on_disk(&home) { + return; + } + if bound != Ok(true) { + tracing::warn!("Self Reports MCP server is not listening; syncing agents to stdio"); + } + spawn_sync(); + }); + if let Err(err) = started { + tracing::warn!("could not start the Self Reports startup sync: {err}"); + } +} + static SYNC_RUNNING: AtomicBool = AtomicBool::new(false); static SYNC_AGAIN: AtomicBool = AtomicBool::new(false); @@ -238,8 +278,8 @@ fn run_sync_once() { // The CLI the service unit names, the same way the audit lane runs it. let Some(cli) = crate::audit_lane::cli_command() else { tracing::warn!( - "Self Reports changed but this service unit carries no FAILPROOFAI_CLI_CMD, \ - so agent configs were not updated — run `failproofai self-report sync`" + "this service unit carries no FAILPROOFAI_CLI_CMD, so Self Reports agent \ + configs were not synced — run `failproofai self-report sync`" ); return; }; @@ -554,6 +594,21 @@ mod tests { ); } + #[test] + fn the_startup_sync_runs_only_when_the_file_says_enabled() { + let home = temp_path("startup").parent().unwrap().to_path_buf(); + assert!(!enabled_on_disk(&home), "no file: off"); + let mut s = effective(None, 4319, "2026-11-26T00:00:00Z".into()); + sr::write_settings(&sr::settings_path(&home), &s).unwrap(); + assert!(!enabled_on_disk(&home), "disabled"); + s.enabled = true; + sr::write_settings(&sr::settings_path(&home), &s).unwrap(); + assert!(enabled_on_disk(&home), "enabled"); + std::fs::write(sr::settings_path(&home), "garbage").unwrap(); + assert!(!enabled_on_disk(&home), "unparsable: off"); + let _ = std::fs::remove_dir_all(&home); + } + #[test] fn sync_runs_only_as_the_owner_of_the_home() { use std::os::unix::fs::MetadataExt; diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index 2c3cf82b8..49ce86640 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -315,14 +315,47 @@ pub fn input_schema(categories: &[Category]) -> Value { }) } -/// The MCP tool definition, or `None` when the feature is off. -pub fn tool_definition(settings: Option<&Settings>) -> Option { - let settings = settings.filter(|s| s.enabled)?; - let categories = if settings.categories.is_empty() { +/// The MCP server's `instructions` (identical text in the TypeScript stdio +/// server, `selfReportInstructions`). Claude Code defers MCP tools behind tool +/// search, so the model never reads the tool description up front; a server's +/// instructions go into the system prompt. +pub fn instructions(categories: &[Category], guidance: Option<&str>) -> String { + let names: Vec<&str> = categories.iter().map(|c| c.name.as_str()).collect(); + let mut text = format!( + "FailproofAI records when an agent is stuck. If you get stuck ({}), call this server's \ + `report` tool once with the matching category and one factual sentence. It does not \ + unblock you: continue, or tell the user what is blocking you. There is no need to \ + mention the report to the user.", + names.join(", ") + ); + if let Some(g) = guidance.filter(|g| !g.is_empty()) { + text.push_str("\n\n"); + text.push_str(g); + } + text +} + +fn effective_categories(settings: &Settings) -> Vec { + if settings.categories.is_empty() { default_categories() } else { settings.categories.clone() - }; + } +} + +/// The initialize result's `instructions`, or `None` when the feature is off. +pub fn server_instructions(settings: Option<&Settings>) -> Option { + let settings = settings.filter(|s| s.enabled)?; + Some(instructions( + &effective_categories(settings), + settings.guidance.as_deref(), + )) +} + +/// The MCP tool definition, or `None` when the feature is off. +pub fn tool_definition(settings: Option<&Settings>) -> Option { + let settings = settings.filter(|s| s.enabled)?; + let categories = effective_categories(settings); Some(json!({ "name": TOOL_NAME, "description": describe(&categories, settings.guidance.as_deref()), @@ -381,10 +414,15 @@ struct Server { /// never shows up in (or is cycled with) the collector's lifecycle. A busy /// port logs one warning and the thread ends; the daemon carries on, as with /// the OTLP relay. Stops when `shutdown` is set. +/// +/// `listening` hears `true` once the port is bound (connections are accepted +/// from then on) or `false` when it could not be; the daemon waits on it to +/// run its startup `self-report sync` against a server that is really there. pub fn spawn( home: PathBuf, port: u16, shutdown: Arc, + listening: std::sync::mpsc::Sender, ) -> Option> { std::thread::Builder::new() .name("fpai-self-report".to_string()) @@ -396,6 +434,7 @@ pub fn spawn( Ok(rt) => rt, Err(err) => { tracing::warn!(%err, "Self Reports MCP server off: no runtime; daemon continues"); + let _ = listening.send(false); return; } }; @@ -409,10 +448,12 @@ pub fn spawn( %err, "Self Reports MCP server off: loopback port unavailable; daemon continues" ); + let _ = listening.send(false); return; } }; tracing::info!(port, "Self Reports MCP server listening on 127.0.0.1"); + let _ = listening.send(true); if let Err(err) = serve(listener, home, Shutdown::from_daemon(shutdown)).await { tracing::warn!(%err, "Self Reports MCP server stopped"); } @@ -603,17 +644,18 @@ impl Server { let version = asked .filter(|v| PROTOCOL_VERSIONS.contains(v)) .unwrap_or(PROTOCOL_VERSIONS[0]); - rpc_result( - id, - json!({ - "protocolVersion": version, - // listChanged is false: answers are plain JSON with no - // stream to push the notification on. A client sees a - // changed list on its next tools/list. - "capabilities": {"tools": {"listChanged": false}}, - "serverInfo": {"name": SERVER_NAME, "version": env!("CARGO_PKG_VERSION")}, - }), - ) + let mut result = json!({ + "protocolVersion": version, + // listChanged is false: answers are plain JSON with no + // stream to push the notification on. A client sees a + // changed list on its next tools/list. + "capabilities": {"tools": {"listChanged": false}}, + "serverInfo": {"name": SERVER_NAME, "version": env!("CARGO_PKG_VERSION")}, + }); + if let Some(text) = server_instructions(self.settings.current().as_ref()) { + result["instructions"] = Value::String(text); + } + rpc_result(id, result) } "ping" => rpc_result(id, json!({})), "tools/list" => { @@ -1236,6 +1278,20 @@ mod tests { assert_eq!(input_schema(&cats), want); } + #[test] + fn golden_instructions() { + let cats = default_categories(); + assert_eq!(instructions(&cats, None), golden("instructions.golden.txt")); + assert_eq!( + instructions( + &cats, + Some("Report a missing repository as missing_context.") + ), + golden("instructions-guidance.golden.txt") + ); + assert!(golden("instructions.golden.txt").chars().count() < 600); + } + #[test] fn golden_default_categories() { let want: Vec = serde_json::from_str(&golden("categories.golden.json")).unwrap(); diff --git a/crates/fpai-collect/src/sources/hooks/mod.rs b/crates/fpai-collect/src/sources/hooks/mod.rs index 933f52df8..f9989857a 100644 --- a/crates/fpai-collect/src/sources/hooks/mod.rs +++ b/crates/fpai-collect/src/sources/hooks/mod.rs @@ -1,6 +1,7 @@ //! The hook-activity source. //! -//! Tails `~/.failproofai/cache/hook-activity/*.jsonl` and turns each row into +//! Tails `~/.failproofai/hook-activity/*.jsonl` (`$FAILPROOFAI_HOME/hook-activity`; +//! layout 1 kept it under `cache/hook-activity`) and turns each row into //! AgentEye hook events. This is the capability `agenteye-collector` //! structurally cannot have: failproofai already sits in the hook path of //! every supported agent CLI, and nothing else on the machine does. diff --git a/crates/fpai-collect/tests/self_report_mcp.rs b/crates/fpai-collect/tests/self_report_mcp.rs index 2c1e8f083..0a9a12d7e 100644 --- a/crates/fpai-collect/tests/self_report_mcp.rs +++ b/crates/fpai-collect/tests/self_report_mcp.rs @@ -141,6 +141,15 @@ async fn initialize_list_and_call_the_report_tool() { assert_eq!(reply["result"]["protocolVersion"], "2025-06-18"); assert_eq!(reply["result"]["serverInfo"]["name"], "failproofai"); assert!(reply["result"]["capabilities"]["tools"].is_object()); + // The instructions Claude Code puts in the system prompt (its tools are + // deferred behind tool search, so the description alone is never seen). + assert_eq!( + reply["result"]["instructions"], + self_report::instructions( + &self_report::default_categories(), + Some("Prefer one report.") + ) + ); // An unknown revision is answered in ours. let (_, reply) = server @@ -240,6 +249,13 @@ async fn the_tool_list_follows_the_settings_file() { let home = tmpdir("follow"); let server = Running::start(&home).await; assert_eq!(list(&server).await, json!([]), "no file: off"); + let init = json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}); + let instructions = |reply: Option| reply.unwrap()["result"].get("instructions").cloned(); + assert_eq!( + instructions(server.rpc("", init.clone()).await.1), + None, + "no file: no instructions field" + ); write_settings( &home, @@ -254,9 +270,20 @@ async fn the_tool_list_follows_the_settings_file() { tools[0]["inputSchema"]["properties"]["category"]["enum"], json!(["org_custom"]) ); + let text = instructions(server.rpc("", init.clone()).await.1).unwrap(); + assert!(text.as_str().unwrap().contains("(org_custom)"), "{text}"); + assert!( + text.as_str().unwrap().ends_with("\n\nPrefer one report."), + "{text}" + ); write_settings(&home, false, self_report::default_categories()); assert_eq!(list(&server).await, json!([]), "disabled: empty list"); + assert_eq!( + instructions(server.rpc("", init.clone()).await.1), + None, + "disabled: no instructions field" + ); fs::write(self_report::settings_path(&home), "garbage").unwrap(); assert_eq!(list(&server).await, json!([]), "unparsable: off"); @@ -383,3 +410,34 @@ async fn a_server_recorded_agent_gets_its_report_written() { server.stop().await; fs::remove_dir_all(&home).ok(); } + +#[test] +fn spawn_reports_whether_it_is_listening() { + let home = tmpdir("spawn"); + let stop = Arc::new(AtomicBool::new(false)); + + // Bound: `true`, and the port answers. + let holder = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = holder.local_addr().unwrap().port(); + drop(holder); + let (tx, rx) = std::sync::mpsc::channel(); + let handle = self_report::spawn(home.clone(), port, stop.clone(), tx).unwrap(); + assert_eq!( + rx.recv_timeout(std::time::Duration::from_secs(10)), + Ok(true) + ); + assert!(std::net::TcpStream::connect(("127.0.0.1", port)).is_ok()); + + // Busy port: `false`, and the daemon carries on. + let (tx2, rx2) = std::sync::mpsc::channel(); + let busy = self_report::spawn(home.clone(), port, stop.clone(), tx2).unwrap(); + assert_eq!( + rx2.recv_timeout(std::time::Duration::from_secs(10)), + Ok(false) + ); + busy.join().unwrap(); + + stop.store(true, std::sync::atomic::Ordering::Relaxed); + handle.join().unwrap(); + fs::remove_dir_all(&home).ok(); +} diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index 0d890a10a..9a5212463 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -51,7 +51,11 @@ A report with a category that is not on the list is still recorded under the nam ## Agent support -failproofai registers one MCP server, named `failproofai`, in each agent's user-level MCP settings. When `failproofaid` runs on the machine, the entry points at the daemon's local server, `http://127.0.0.1:4319/mcp` (set `FAILPROOFAI_SELF_REPORT_PORT` to move it). Otherwise it runs `failproofai mcp` over stdio. Every entry is marked as failproofai's, so removing it never touches a server you added. +failproofai registers one MCP server, named `failproofai`, in each agent's user-level MCP settings. When `failproofaid` is answering on the machine, the entry points at the daemon's local server, `http://127.0.0.1:4319/mcp` (set `FAILPROOFAI_SELF_REPORT_PORT` to move it). Otherwise it runs `failproofai mcp` over stdio. Every entry is marked as failproofai's, so removing it never touches a server you added. + +The transport is chosen when the entries are written, from a live check: the daemon must answer on its socket and its MCP endpoint must answer. When the daemon starts, it re-runs `failproofai self-report sync`, so agents move to HTTP. If the daemon stops, `failproofai self-report status` finds agents pointing at an endpoint that does not answer and moves them back to stdio. A running agent keeps the server it loaded at startup. + +Both transports send the model short server instructions in the MCP handshake: when to report, the category names, and your guidance. Some agents, Claude Code among them, load MCP tools only on demand. They add a server's instructions to the system prompt, though, so the model knows the tool exists. Where an agent's hooks see MCP tool calls, the hook records the report. Where they do not, failproofai's MCP server records it and attributes it to that agent's newest session in the same working directory. @@ -70,7 +74,7 @@ Where an agent's hooks see MCP tool calls, the hook records the report. Where th | Antigravity | `~/.gemini/config/mcp_config.json` | MCP server | | Goose | `~/.config/goose/config.yaml` | MCP server | -`failproofai self-report status` shows, per agent, whether the server is registered and over which transport. If an MCP server named `failproofai` that failproofai did not write is already there, such as the [Cloud MCP gateway](/reference/mcp) added under that name, it is left alone and reported as a conflict. +`failproofai self-report status` shows, per agent, whether the server is registered, over which transport, and whether that endpoint answers (HTTP) or the command can run (stdio). If an MCP server named `failproofai` that failproofai did not write is already there, such as the [Cloud MCP gateway](/reference/mcp) added under that name, it is left alone and reported as a conflict. ## Containers diff --git a/src/hooks/daemon-client.ts b/src/hooks/daemon-client.ts index ac2c80365..b61690342 100644 --- a/src/hooks/daemon-client.ts +++ b/src/hooks/daemon-client.ts @@ -173,6 +173,22 @@ export async function daemonAcceptsConnections( }); } +/** + * Whether a daemon answers a `ping` with a `pong` within `responseTimeoutMs`. + * + * Unlike `daemonSocketPresent()` this proves a live daemon: a socket file left + * behind by a daemon that was killed hard refuses the connection. Used where a + * stale answer writes something lasting (the Self Reports transport choice), + * never on the hook path. + */ +export async function daemonAnswersPing(responseTimeoutMs = 1000): Promise { + const attempt = await attemptDaemonRequest( + (protocolVersion) => ({ type: "ping", protocolVersion }), + { responseTimeoutMs }, + ); + return attempt.ok && attempt.message.type === "pong"; +} + function socketPath(): string { if (process.env.FAILPROOFAI_DAEMON_SOCKET) return process.env.FAILPROOFAI_DAEMON_SOCKET; return daemonSocketPath(); diff --git a/src/hooks/manager.ts b/src/hooks/manager.ts index 195a52436..0df127d3b 100644 --- a/src/hooks/manager.ts +++ b/src/hooks/manager.ts @@ -1021,7 +1021,7 @@ async function installHooksImpl( // when the feature is on (and lose a stale one when it is off). Best-effort: // a config it cannot change is reported, never a failed install. try { - const results = syncSelfReportMcp({ + const results = await syncSelfReportMcp({ quiet: true, alsoHooked: writtenSettingsPaths.map((written) => written.cli), binaryPath, diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts index de1623dca..23a7bd7d0 100644 --- a/src/hooks/self-report-cli.ts +++ b/src/hooks/self-report-cli.ts @@ -28,7 +28,15 @@ import { type SelfReportCategory, } from "./self-report"; import { INTEGRATION_TYPES } from "./types"; -import { selfReportRegistrationStatus, syncSelfReportMcp } from "./self-report-install"; +import { + probeSelfReportHttp, + selfReportCommandRunnable, + selfReportRegistrationStatus, + selfReportSyncChanged, + selfReportSyncLines, + syncSelfReportMcp, + type SelfReportRegistration, +} from "./self-report-install"; export interface SelfReportCliResult { exitCode: number; @@ -38,8 +46,12 @@ export interface SelfReportCliResult { export interface SelfReportCliDeps { /** argv prefix that runs this CLI: `[node, dist/cli.mjs]`. */ cliCommand?: string[]; - /** Health probe override (tests). */ + /** Health probe override (tests): does the HTTP endpoint on this port answer? */ probeEndpoint?: (url: string, port: number) => Promise; + /** Registration rows override (tests). */ + registrations?: () => SelfReportRegistration[]; + /** Sync override (tests). */ + sync?: () => Promise; /** Skip the agent sync after enable/disable (tests). */ skipSync?: boolean; cwd?: string; @@ -81,43 +93,63 @@ function selfReportRunChild( }); } -/** POST a JSON-RPC ping to the daemon's MCP endpoint, with the Host it requires. */ -async function selfReportProbe(url: string): Promise { +/** The port of one of our endpoint URLs, or null. */ +function selfReportUrlPort(url: string | null): number | null { + if (!url) return null; try { - const res = await fetch(url, { - method: "POST", - headers: { "content-type": "application/json", accept: "application/json, text/event-stream" }, - body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }), - signal: AbortSignal.timeout(1500), - }); - return res.ok; + const port = Number(new URL(url).port); + return Number.isInteger(port) && port > 0 ? port : null; } catch { - return false; + return null; + } +} + +/** Probe each distinct HTTP port among the rows once. */ +async function selfReportHttpHealth(rows: readonly SelfReportRegistration[], deps: SelfReportCliDeps): Promise> { + const probe = deps.probeEndpoint ?? ((_url: string, port: number) => probeSelfReportHttp(port)); + const ports = new Set(); + for (const r of rows) { + const port = r.registered && r.transport === "http" ? selfReportUrlPort(r.endpoint) : null; + if (port !== null) ports.add(port); } + const health = new Map(); + await Promise.all( + [...ports].map(async (port) => health.set(port, await probe(`http://127.0.0.1:${port}/mcp`, port))), + ); + return health; } -/** Per-agent registration state. */ -function selfReportRegistrationLines(): string[] { - const rows = selfReportRegistrationStatus(); +/** Per-agent registration state: transport, endpoint and whether it answers. */ +function selfReportRegistrationLines(rows: readonly SelfReportRegistration[], health: ReadonlyMap): string[] { const hooked = rows.filter((r) => r.hooked || r.registered || r.conflict || r.error); if (hooked.length === 0) return ["Agents: none with failproofai hooks"]; return [ "Agents:", ...hooked.map((r) => { - const state = r.error - ? `unreadable (${r.error})` - : r.conflict - ? "another failproofai MCP server is configured; left alone" - : r.registered - ? `registered (${r.transport})` - : r.hooked - ? "not registered" - : "registered, no hooks"; + let state: string; + if (r.error) state = `unreadable (${r.error})`; + else if (r.conflict) state = "another failproofai MCP server is configured; left alone"; + else if (r.registered && r.transport === "http") { + const port = selfReportUrlPort(r.endpoint); + const ok = port !== null && health.get(port) === true; + state = `http ${r.endpoint ?? "?"} ${ok ? "(answering)" : "(NOT answering)"}`; + } else if (r.registered) { + const ok = !!r.endpoint && selfReportCommandRunnable(r.endpoint); + state = `stdio ${r.endpoint ?? "?"} ${ok ? "(runnable)" : "(NOT runnable)"}`; + } else state = r.hooked ? "not registered" : "registered, no hooks"; + if (r.registered && !r.hooked) state += ", no hooks"; return ` ${r.agent.padEnd(12)} ${state}`; }), ]; } +/** Whether a row is registered over HTTP at an endpoint that is not answering. */ +function selfReportStranded(r: SelfReportRegistration, health: ReadonlyMap): boolean { + if (!r.registered || r.transport !== "http") return false; + const port = selfReportUrlPort(r.endpoint); + return port === null || health.get(port) !== true; +} + async function selfReportStatus(deps: SelfReportCliDeps): Promise { const settings = readEffectiveSelfReport(); const cloud = await selfReportCloudManaged(); @@ -134,22 +166,42 @@ async function selfReportStatus(deps: SelfReportCliDeps): Promise c.name).join(", ")}`); if (settings.guidance) lines.push(`Guidance: ${settings.guidance.length > 60 ? `${settings.guidance.slice(0, 57)}...` : settings.guidance}`); - const probe = deps.probeEndpoint ?? ((url: string) => selfReportProbe(url)); - const healthy = await probe(settings.mcp.url, settings.mcp.port); - lines.push(`Endpoint: ${settings.mcp.url} ${healthy ? "(answering)" : "(not answering; stdio `failproofai mcp` still works)"}`); - lines.push(...selfReportRegistrationLines()); + const readRows = deps.registrations ?? (() => selfReportRegistrationStatus()); + let rows = readRows(); + let health = await selfReportHttpHealth(rows, deps); + // An agent left on the daemon's HTTP endpoint after the daemon died would + // have no report tool. Move it (live check: stdio unless a daemon answers). + if (settings.enabled && !deps.skipSync && rows.some((r) => selfReportStranded(r, health))) { + try { + const results = await (deps.sync ?? (() => syncSelfReportMcp({ quiet: true })))(); + if (selfReportSyncChanged(results)) { + lines.push("Repaired: agents pointed at an HTTP endpoint that is not answering were re-synced:"); + lines.push(...selfReportSyncLines(results).map((l) => ` ${l}`)); + rows = readRows(); + health = await selfReportHttpHealth(rows, deps); + } + } catch { + lines.push("▲ Could not re-sync agents whose HTTP endpoint is not answering. Run `failproofai self-report sync`."); + } + } + if (!health.has(settings.mcp.port)) { + const probe = deps.probeEndpoint ?? ((_url: string, port: number) => probeSelfReportHttp(port)); + health.set(settings.mcp.port, await probe(settings.mcp.url, settings.mcp.port)); + } + lines.push(`Daemon MCP: ${settings.mcp.url} (${health.get(settings.mcp.port) ? "answering" : "not answering"})`); + lines.push(...selfReportRegistrationLines(rows, health)); return { exitCode: 0, lines }; } /** Update every hooked agent's MCP entry to match the settings just written. */ -function selfReportSync(deps: SelfReportCliDeps): string[] { +async function selfReportSync(deps: SelfReportCliDeps): Promise { if (deps.skipSync) return []; try { - const results = syncSelfReportMcp({ quiet: true }); + const results = await (deps.sync ?? (() => syncSelfReportMcp({ quiet: true })))(); if (results.some((r) => r.status === "error")) { return ["▲ Could not update every agent's MCP settings. Run `failproofai self-report sync` to see why."]; } - return ["Agents updated."]; + return selfReportSyncChanged(results) ? ["Agents updated."] : []; } catch { return ["▲ Could not update your agents' MCP settings. Run `failproofai self-report sync` to see why."]; } @@ -204,7 +256,7 @@ async function selfReportEnable(args: string[], deps: SelfReportCliDeps): Promis "✓ Self Reports is on.", ` Categories: ${written.categories.map((c) => c.name).join(", ")}${categories ? "" : " (defaults)"}`, ` Settings: ${selfReportSettingsFile()}`, - ...selfReportSync(deps).map((l) => (l.startsWith("▲") ? l : ` ${l}`)), + ...(await selfReportSync(deps)).map((l) => (l.startsWith("▲") ? l : ` ${l}`)), ]; return { exitCode: 0, lines }; } @@ -218,7 +270,7 @@ async function selfReportDisable(args: string[], deps: SelfReportCliDeps): Promi writeEffectiveSelfReport({ enabled: false, categories: previous?.categories, guidance: previous?.guidance }); return { exitCode: 0, - lines: ["✓ Self Reports is off.", ...selfReportSync(deps).map((l) => (l.startsWith("▲") ? l : ` ${l}`))], + lines: ["✓ Self Reports is off.", ...(await selfReportSync(deps)).map((l) => (l.startsWith("▲") ? l : ` ${l}`))], }; } diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index bec26de24..f73f1bf31 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -4,8 +4,10 @@ * * The server is named `failproofai` everywhere (CONTRACT §1). It is served by * the daemon over Streamable HTTP at `http://127.0.0.1:/mcp` when a - * daemon socket is present, and otherwise by `failproofai mcp` over stdio - * (CONTRACT §7). Both carry the agent, `?agent=` / `--agent `, so the + * daemon is live here (it answers a ping on its socket AND the endpoint + * answers an MCP initialize), and otherwise by `failproofai mcp` over stdio + * (CONTRACT §7). The daemon runs `self-report sync` once it is listening, so + * agents move to HTTP when it comes up. Both carry the agent, `?agent=` / `--agent `, so the * server can record a report itself for agents whose hooks do not see MCP * calls (CONTRACT §8). * @@ -32,7 +34,7 @@ * | goose | `$GOOSE_PATH_ROOT/config/config.yaml`, else `~/.config/goose/config.yaml` (YAML) | `extensions` | `{type:"streamable_http", name, enabled, uri, …}` | `{type:"stdio", name, enabled, cmd, args, …}` | not documented; would be `failproofai__report` | * * Every agent supports Streamable HTTP, so the transport choice is purely - * "is a daemon here". Every path is the user-scope one: MCP servers are a per + * "is a daemon live here". Every path is the user-scope one: MCP servers are a per * user (per profile) setting even where failproofai's hooks are per project. * Codex: user scope only. Its system config (`/etc/codex/config.toml`, where * root installs put the hooks) is not documented to honour `[mcp_servers]`, so @@ -49,7 +51,7 @@ * any other shape (for example the Cloud MCP gateway) is the user's: it is never * changed and is reported as a conflict. */ -import { existsSync, readFileSync, realpathSync } from "node:fs"; +import { accessSync, constants as fsConstants, existsSync, readFileSync, realpathSync } from "node:fs"; import { execSync } from "node:child_process"; import { homedir } from "node:os"; import { basename, resolve } from "node:path"; @@ -59,7 +61,7 @@ import { isMap, type Document } from "yaml"; import { writeConfigFileAtomic } from "./safe-config-write"; import { codexHome } from "./codex-system-hooks"; import { claudeConfigDir, getIntegration, readYamlDoc, writeYamlDoc, UnreadableAgentConfigError } from "./integrations"; -import { daemonSocketPresent } from "./daemon-client"; +import { daemonAnswersPing } from "./daemon-client"; import { readEffectiveSelfReport, selfReportPort, selfReportSettingsFile, SELF_REPORT_SERVER_NAME } from "./self-report"; import { listHermesProfiles } from "../../lib/hermes-profiles"; import { listOpenClawProfiles } from "../../lib/openclaw-profiles"; @@ -133,6 +135,69 @@ function transportOf(entry: unknown): "http" | "stdio" | null { return ["url", "serverUrl", "uri"].some((k) => typeof e[k] === "string") ? "http" : "stdio"; } +/** The URL (http) or command (stdio) an entry of ours points at, for status. */ +function endpointOf(entry: unknown): string | null { + if (!isOurMcpEntry(entry)) return null; + const e = entry as Record; + for (const key of ["url", "serverUrl", "uri"]) if (typeof e[key] === "string") return e[key] as string; + if (typeof e.command === "string") return e.command; + if (typeof e.cmd === "string") return e.cmd; + if (Array.isArray(e.command) && typeof e.command[0] === "string") return e.command[0]; + return null; +} + +// ── Liveness ──────────────────────────────────────────────────────────────── + +/** How long the endpoint may take to answer an MCP initialize. */ +const SELF_REPORT_PROBE_TIMEOUT_MS = 1500; + +/** + * Whether `http://127.0.0.1:/mcp` answers an MCP `initialize` as + * failproofai's server, within the timeout. Anything else (refused, timed out, + * a different server on the port) is false. + */ +export async function probeSelfReportHttp(port: number, timeoutMs = SELF_REPORT_PROBE_TIMEOUT_MS): Promise { + try { + const res = await fetch(`http://127.0.0.1:${port}/mcp`, { + method: "POST", + headers: { "content-type": "application/json", accept: "application/json, text/event-stream" }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "failproofai-probe", version: "1" } }, + }), + signal: AbortSignal.timeout(timeoutMs), + }); + if (!res.ok) return false; + const body = (await res.json()) as { result?: { serverInfo?: { name?: unknown } } }; + return body?.result?.serverInfo?.name === SELF_REPORT_SERVER_NAME; + } catch { + return false; + } +} + +/** + * Whether agents should be pointed at the daemon's HTTP server: the daemon + * answers a ping on its socket AND its MCP endpoint answers an initialize. A + * socket file alone is not enough (a hard-killed daemon leaves one behind), + * and neither is the port alone (something else may hold it). + */ +export async function selfReportDaemonLive(port: number): Promise { + const [ping, http] = await Promise.all([daemonAnswersPing(), probeSelfReportHttp(port)]); + return ping && http; +} + +/** Whether a stdio command can be run (exists and is executable). */ +export function selfReportCommandRunnable(command: string): boolean { + try { + accessSync(command, fsConstants.X_OK); + return true; + } catch { + return false; + } +} + // ── Per-agent targets ─────────────────────────────────────────────────────── type Format = "json" | "toml" | "yaml"; @@ -504,7 +569,8 @@ export interface SyncSelfReportMcpOptions { binaryPath?: string; /** Test seams. */ deps?: { - daemonSocketPresent?: () => boolean; + /** The live check (default `selfReportDaemonLive`); asked only when an agent wants the server. */ + daemonLive?: (port: number) => Promise; hooksInstalled?: (agent: IntegrationType) => boolean; settings?: SelfReportMcpSettings; resolveCliPath?: () => string | null; @@ -545,15 +611,33 @@ function defaultHooksInstalled(agent: IntegrationType): boolean { /** * Add (enabled) or remove (disabled) our `failproofai` MCP server in every * agent. Enabled: only agents with failproofai hooks get it, and agents without - * hooks are left as they are. Disabled: ours is removed from every agent's - * file, hooked or not. Idempotent; never touches an entry that is not ours; - * one agent's failure never stops the others. + * hooks are left as they are; HTTP when the daemon is live right now (see + * `selfReportDaemonLive`), stdio otherwise. Disabled: ours is removed from + * every agent's file, hooked or not. Idempotent; never touches an entry that + * is not ours; one agent's failure never stops the others. */ -export function syncSelfReportMcp(opts: SyncSelfReportMcpOptions = {}): SelfReportMcpResult[] { +export async function syncSelfReportMcp(opts: SyncSelfReportMcpOptions = {}): Promise { const settings = opts.deps?.settings ?? readSelfReportMcpSettings(); const enabled = opts.enabled ?? settings.enabled; const agents = opts.agents ?? INTEGRATION_TYPES; - const daemonHere = (opts.deps?.daemonSocketPresent ?? daemonSocketPresent)(); + const seen = new Map(); + const isHooked = opts.deps?.hooksInstalled ?? defaultHooksInstalled; + const hooked = (a: IntegrationType): boolean => { + if (!seen.has(a)) seen.set(a, isHooked(a)); + return seen.get(a)!; + }; + // The live check costs up to a couple of seconds against a wedged daemon, so + // it runs only when some agent will get an HTTP-capable entry. + const also = opts.alsoHooked ?? []; + const wanted = + enabled && agents.some((a) => SELF_REPORT_MCP_TARGETS[a]?.http && (also.includes(a) || hooked(a))); + const daemonHere = wanted ? await (opts.deps?.daemonLive ?? selfReportDaemonLive)(settings.port) : false; + return applySelfReportMcp({ ...opts, deps: { ...opts.deps, settings, hooksInstalled: hooked } }, enabled, daemonHere); +} + +function applySelfReportMcp(opts: SyncSelfReportMcpOptions, enabled: boolean, daemonHere: boolean): SelfReportMcpResult[] { + const settings = opts.deps?.settings ?? readSelfReportMcpSettings(); + const agents = opts.agents ?? INTEGRATION_TYPES; const hooked = opts.deps?.hooksInstalled ?? defaultHooksInstalled; const also = new Set(opts.alsoHooked ?? []); let cliPath: string | null | undefined = opts.binaryPath; @@ -592,7 +676,7 @@ export function syncSelfReportMcp(opts: SyncSelfReportMcpOptions = {}): SelfRepo if (wantIt && !transport) { results.push({ agent, path, action: "skipped", transport: null, status: "error", - detail: "no daemon is running here and the failproofai CLI was not found for stdio", + detail: "no daemon is answering here and the failproofai CLI was not found for stdio", }); continue; } @@ -636,9 +720,14 @@ export function syncSelfReportMcp(opts: SyncSelfReportMcpOptions = {}): SelfRepo return results; } -/** Remove our entries from every agent (or `agents`), whatever the settings say. */ +/** Remove our entries from every agent (or `agents`), whatever the settings say. Needs no live check. */ export function removeSelfReportMcp(opts: Omit = {}): SelfReportMcpResult[] { - return syncSelfReportMcp({ ...opts, enabled: false }); + return applySelfReportMcp({ ...opts, enabled: false }, false, false); +} + +/** Whether a sync changed any agent's file. */ +export function selfReportSyncChanged(results: readonly SelfReportMcpResult[]): boolean { + return results.some((r) => r.action === "added" || r.action === "updated" || r.action === "removed"); } function errText(err: unknown): string { @@ -679,6 +768,8 @@ export interface SelfReportRegistration { /** Our entry is in this file. */ registered: boolean; transport: "http" | "stdio" | null; + /** The URL (http) or command (stdio) our entry points at. */ + endpoint: string | null; /** A `failproofai` server that is not ours is there. */ conflict: boolean; /** The file could not be read. */ @@ -699,12 +790,12 @@ export function selfReportRegistrationStatus( try { paths = target.paths(); } catch (err) { - out.push({ agent, path: "", hooked: isHooked, registered: false, transport: null, conflict: false, error: errText(err) }); + out.push({ agent, path: "", hooked: isHooked, registered: false, transport: null, endpoint: null, conflict: false, error: errText(err) }); continue; } for (const path of paths) { if (!existsSync(path)) { - out.push({ agent, path, hooked: isHooked, registered: false, transport: null, conflict: false }); + out.push({ agent, path, hooked: isHooked, registered: false, transport: null, endpoint: null, conflict: false }); continue; } try { @@ -713,10 +804,11 @@ export function selfReportRegistrationStatus( agent, path, hooked: isHooked, registered: cur.state === "ours", transport: cur.state === "ours" ? transportOf(cur.entry) : null, + endpoint: cur.state === "ours" ? endpointOf(cur.entry) : null, conflict: cur.state === "foreign", }); } catch (err) { - out.push({ agent, path, hooked: isHooked, registered: false, transport: null, conflict: false, error: errText(err) }); + out.push({ agent, path, hooked: isHooked, registered: false, transport: null, endpoint: null, conflict: false, error: errText(err) }); } } } diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts index 3f3db9ae5..7d2326924 100644 --- a/src/hooks/self-report-mcp.ts +++ b/src/hooks/self-report-mcp.ts @@ -7,7 +7,7 @@ * no daemon: it reads `self-report.json` on every request and writes its * fallback records straight into the custom-agents spool. * - * Methods: `initialize`, `ping`, `tools/list` (the report tool, or nothing + * Methods: `initialize` (with `instructions` while the feature is on), `ping`, `tools/list` (the report tool, or nothing * while the feature is off), `tools/call` (always answers `Recorded.`). * * Recording (contract §8): an agent whose hooks see MCP calls (Claude Code, @@ -36,6 +36,7 @@ import { readEnabledSelfReport, selfReportArgs, selfReportInputSchema, + selfReportInstructions, } from "./self-report"; /** How far back a hook-activity session may be and still own a report. */ @@ -68,6 +69,17 @@ export function selfReportToolList(): Array> { ]; } +/** + * The initialize result's `instructions`, or undefined while the feature is + * off (the field is then left out). Read at initialize time: a client reads it + * once per connection. + */ +export function selfReportServerInstructions(): string | undefined { + const settings = readEnabledSelfReport(); + if (!settings) return undefined; + return selfReportInstructions(settings.categories, settings.guidance); +} + // ── Session attribution ───────────────────────────────────────────────────── /** @@ -240,12 +252,15 @@ export async function handleSelfReportRpc( if (!hasId) return null; // notifications/initialized and friends switch (method) { - case "initialize": + case "initialize": { + const instructions = selfReportServerInstructions(); return ok({ protocolVersion: typeof params.protocolVersion === "string" ? params.protocolVersion : SELF_REPORT_DEFAULT_PROTOCOL, capabilities: { tools: {} }, serverInfo: { name: SELF_REPORT_SERVER_NAME, version: selfReportCliVersion }, + ...(instructions ? { instructions } : {}), }); + } case "ping": return ok({}); case "tools/list": diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts index b29b39e15..dc6985869 100644 --- a/src/hooks/self-report.ts +++ b/src/hooks/self-report.ts @@ -158,6 +158,29 @@ function selfReportInputSchema(categories: readonly SelfReportCategory[]): Recor export { describeSelfReportTool, describeSelfReportTool as describe, selfReportInputSchema, selfReportInputSchema as inputSchema }; +/** + * The MCP server's `instructions` (the initialize result), the same text in the + * daemon (crates/fpai-collect/src/self_report.rs `instructions`). + * + * Claude Code defers MCP tools behind tool search, so the model never reads the + * tool's description until it already decided to look for one; a server's + * instructions go into the system prompt. One short paragraph naming the + * categories, then the org's guidance when set. + */ +function selfReportInstructions( + categories: readonly SelfReportCategory[], + guidance?: string | null, +): string { + const names = categories.map((c) => c.name).join(", "); + const body = + `FailproofAI records when an agent is stuck. If you get stuck (${names}), call this server's ` + + "`report` tool once with the matching category and one factual sentence. It does not unblock you: " + + "continue, or tell the user what is blocking you. There is no need to mention the report to the user."; + return guidance ? `${body}\n\n${guidance}` : body; +} + +export { selfReportInstructions }; + /** Exactly what the tool returns (contract §3). */ export const SELF_REPORT_RESULT_TEXT = "Recorded."; diff --git a/test-fixtures/self-report/instructions-guidance.golden.txt b/test-fixtures/self-report/instructions-guidance.golden.txt new file mode 100644 index 000000000..e57cd7548 --- /dev/null +++ b/test-fixtures/self-report/instructions-guidance.golden.txt @@ -0,0 +1,3 @@ +FailproofAI records when an agent is stuck. If you get stuck (looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure), call this server's `report` tool once with the matching category and one factual sentence. It does not unblock you: continue, or tell the user what is blocking you. There is no need to mention the report to the user. + +Report a missing repository as missing_context. \ No newline at end of file diff --git a/test-fixtures/self-report/instructions.golden.txt b/test-fixtures/self-report/instructions.golden.txt new file mode 100644 index 000000000..aa1fdf283 --- /dev/null +++ b/test-fixtures/self-report/instructions.golden.txt @@ -0,0 +1 @@ +FailproofAI records when an agent is stuck. If you get stuck (looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure), call this server's `report` tool once with the matching category and one factual sentence. It does not unblock you: continue, or tell the user what is blocking you. There is no need to mention the report to the user. \ No newline at end of file From 3f4e8dd0b507b71f61bbe19483ecf5afdd15541a Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 26 Nov 2026 14:20:32 +0530 Subject: [PATCH 11/54] [self-reports] Name the report arguments, accept aliased ones, quieter daemon status - The MCP server instructions (both servers, one golden) name the two arguments: `category` (one of the names) and `detail` (one factual sentence). An agent that calls `report` without loading its schema guessed `summary` / `sentence` and its report was saved with an empty detail. - Wherever a call's arguments become category/detail (hook recorder, stdio server, daemon HTTP server, TS SDK, Python SDK incl. pydantic-ai's raw extras), a missing or empty `detail` falls back to the first non-empty of summary, sentence, message, description, reason, text, details, and `category` to type, kind. Unknown keys stay ignored; nothing is rejected. The list and shared cases live in test-fixtures/self-report/arg-aliases.json, tested from TS (CLI + SDK), Rust and Python. - `self-report status` shows "Daemon MCP: not running (agents use stdio)" when no daemon is configured and no socket file exists; "not answering" only when a daemon is expected but its endpoint does not answer. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/self-report-golden.test.ts | 17 ++++++ __tests__/hooks/self-report.test.ts | 50 +++++++++++++++- crates/fpai-collect/src/self_report.rs | 59 +++++++++++++++---- crates/fpai-collect/tests/self_report_mcp.rs | 17 ++++++ docs/self-reports.mdx | 4 +- sdk/python/failproofai_sdk/_self_report.py | 31 +++++++++- .../integrations/pydantic_ai.py | 3 +- sdk/python/tests/test_self_report.py | 16 +++++ sdk/python/tests/test_self_report_golden.py | 10 ++++ sdk/typescript/src/self-report-spec.ts | 28 ++++++++- .../test/self-report-golden.test.ts | 15 +++++ sdk/typescript/test/self-report.test.ts | 7 +++ src/hooks/self-report-cli.ts | 18 +++++- src/hooks/self-report.ts | 44 +++++++++++--- test-fixtures/self-report/arg-aliases.json | 58 ++++++++++++++++++ .../instructions-guidance.golden.txt | 2 +- .../self-report/instructions.golden.txt | 2 +- 18 files changed, 352 insertions(+), 31 deletions(-) create mode 100644 test-fixtures/self-report/arg-aliases.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 87ea94286..7f703e7be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Features -- Self Reports: every hooked agent gets a `report` tool (MCP server `failproofai`, served by `failproofaid` at `http://127.0.0.1:4319/mcp` or by `failproofai mcp` over stdio) to say it is stuck, under six default categories or the organization's own; the hook allows the call before any policy, pause or Jev review and records it as a `self_report` event, the MCP server records it for agents whose hooks do not see MCP calls, the setting comes from Cloud (`selfReport` in desired-state) or `failproofai self-report enable|disable|status|test|sync` and lives in `~/.failproofai/self-report.json`, and both SDKs add `self_report()` / `selfReport()` with ready-made framework tools; the server's initialize result carries short instructions (agents that defer MCP tools, like Claude Code, still see them), and HTTP vs stdio is chosen from a live daemon check that the daemon re-runs at startup +- Self Reports: every hooked agent gets a `report` tool (MCP server `failproofai`, served by `failproofaid` at `http://127.0.0.1:4319/mcp` or by `failproofai mcp` over stdio) to say it is stuck, under six default categories or the organization's own; the hook allows the call before any policy, pause or Jev review and records it as a `self_report` event, the MCP server records it for agents whose hooks do not see MCP calls, the setting comes from Cloud (`selfReport` in desired-state) or `failproofai self-report enable|disable|status|test|sync` and lives in `~/.failproofai/self-report.json`, and both SDKs add `self_report()` / `selfReport()` with ready-made framework tools; the server's initialize result carries short instructions (agents that defer MCP tools, like Claude Code, still see them), and HTTP vs stdio is chosen from a live daemon check that the daemon re-runs at startup; the instructions name the `category` and `detail` arguments, and a call that sends the detail under another name (`summary`, `sentence`, `message`, ...) still records it ### Fixes diff --git a/__tests__/hooks/self-report-golden.test.ts b/__tests__/hooks/self-report-golden.test.ts index 328335d26..2b182a961 100644 --- a/__tests__/hooks/self-report-golden.test.ts +++ b/__tests__/hooks/self-report-golden.test.ts @@ -13,8 +13,10 @@ import { mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { + SELF_REPORT_ARG_ALIASES, SELF_REPORT_DEFAULT_CATEGORIES, SELF_REPORT_SERVER_RECORDS, + selfReportArgs, describeSelfReportTool, isSelfReportCursorCall, isSelfReportToolName, @@ -44,6 +46,21 @@ describe("Self Reports golden files (CLI)", () => { expect(golden("instructions.golden.txt").length).toBeLessThan(600); }); + it("reads argument aliases from the shared list, for raw and hook-wrapped arguments", () => { + const fixture = JSON.parse(golden("arg-aliases.json")) as { + aliases: { category: string[]; detail: string[] }; + cases: { args: Record; category: string; detail: string }[]; + }; + expect(SELF_REPORT_ARG_ALIASES).toEqual(fixture.aliases); + for (const c of fixture.cases) { + const want = { category: c.category, detail: c.detail }; + expect(selfReportArgs(c.args), JSON.stringify(c.args)).toEqual(want); + expect(selfReportArgs(JSON.stringify(c.args)), JSON.stringify(c.args)).toEqual(want); + expect(selfReportArgs({ arguments: c.args }), JSON.stringify(c.args)).toEqual(want); + expect(selfReportArgs({ args: JSON.stringify(c.args) }), JSON.stringify(c.args)).toEqual(want); + } + }); + it("builds the input schema byte for byte", () => { expect(`${JSON.stringify(selfReportInputSchema(SELF_REPORT_DEFAULT_CATEGORIES))}\n`).toBe(golden("input-schema.golden.json")); }); diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index 3a28c1c91..3cd476085 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -308,6 +308,16 @@ describe("failproofai mcp (stdio, spawned)", () => { expect(Number.isNaN(Date.parse(event.timestamp))).toBe(false); }, 30_000); + it("records the detail a model sent under an alias (sentence) instead of an empty one", async () => { + writeEffectiveSelfReport({ enabled: true }); + const aliased = { ...CALL, params: { name: "report", arguments: { category: "looping", sentence: "retrying the same fix", extra: 1 } } }; + const { replies } = await runMcp(["--agent", "hermes"], [INIT, aliased], home); + expect(replies[1]).toMatchObject({ result: { content: [{ type: "text", text: "Recorded." }] } }); + const dir = join(home, "custom-agents", "events"); + const event = JSON.parse(readFileSync(join(dir, readdirSync(dir)[0]), "utf8")); + expect(event).toMatchObject({ category: "looping", detail: "retrying the same fix" }); + }, 30_000); + it("falls back to session \"unattributed\" when no live session matches", async () => { writeEffectiveSelfReport({ enabled: true }); await runMcp(["--agent", "hermes"], [INIT, CALL], home); @@ -342,7 +352,7 @@ describe("failproofai self-report enable | disable | status", () => { expect(text).toContain("Self Reports: on"); expect(text).toContain("this machine"); expect(text).toContain("looping, cannot_do_request"); - expect(text).toContain("http://127.0.0.1:4319/mcp"); + expect(text).toContain("Daemon MCP: not running (agents use stdio)"); }); it("enable --categories-file replaces the defaults; a bad file is refused and writes nothing", async () => { @@ -413,6 +423,44 @@ describe("failproofai self-report enable | disable | status", () => { expect(text).toMatch(/factory +stdio +.*\(NOT runnable\)/); }); + it("status says the daemon is not running, not \"not answering\", when there is no daemon", async () => { + writeEffectiveSelfReport({ enabled: true }); + const status = (expected: boolean) => + runSelfReportCommand(["status"], { + skipSync: true, + probeEndpoint: async () => false, + daemonExpected: () => expected, + registrations: () => [row({ agent: "claude", transport: "stdio", endpoint: "/usr/bin/failproofai" })], + }); + const none = (await status(false)).lines.join("\n"); + expect(none).toContain("Daemon MCP: not running (agents use stdio)"); + expect(none).not.toContain("not answering"); + const down = (await status(true)).lines.join("\n"); + expect(down).toContain("Daemon MCP: http://127.0.0.1:4319/mcp (not answering)"); + expect(down).not.toContain("not running"); + }); + + it("status expects a daemon when setup configured one or its socket file is there", async () => { + writeEffectiveSelfReport({ enabled: true }); + const status = async () => + (await runSelfReportCommand(["status"], { + skipSync: true, + probeEndpoint: async () => false, + registrations: () => [], + })).lines.join("\n"); + const sock = join(home, "fake-daemon.sock"); + const prev = process.env.FAILPROOFAI_DAEMON_SOCKET; + process.env.FAILPROOFAI_DAEMON_SOCKET = sock; + try { + expect(await status()).toContain("Daemon MCP: not running (agents use stdio)"); + writeFileSync(sock, ""); + expect(await status()).toContain("(not answering)"); + } finally { + if (prev === undefined) delete process.env.FAILPROOFAI_DAEMON_SOCKET; + else process.env.FAILPROOFAI_DAEMON_SOCKET = prev; + } + }); + it("status re-syncs agents left on an HTTP endpoint that is not answering", async () => { writeEffectiveSelfReport({ enabled: true }); let synced = 0; diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index 49ce86640..d9ed4bdbd 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -323,9 +323,9 @@ pub fn instructions(categories: &[Category], guidance: Option<&str>) -> String { let names: Vec<&str> = categories.iter().map(|c| c.name.as_str()).collect(); let mut text = format!( "FailproofAI records when an agent is stuck. If you get stuck ({}), call this server's \ - `report` tool once with the matching category and one factual sentence. It does not \ - unblock you: continue, or tell the user what is blocking you. There is no need to \ - mention the report to the user.", + `report` tool once with two arguments: `category` (one of those names) and `detail` \ + (one factual sentence). It does not unblock you: continue, or tell the user what is \ + blocking you. There is no need to mention the report to the user.", names.join(", ") ); if let Some(g) = guidance.filter(|g| !g.is_empty()) { @@ -700,8 +700,25 @@ impl Server { // ── Recording ──────────────────────────────────────────────────────────────── -/// A call's arguments, as recorded: an unknown category is kept as-is, a -/// missing one or a missing detail becomes "". +/// Other names a model uses for `category` when it calls the tool without +/// loading its schema. Identical in the CLI (`SELF_REPORT_ARG_ALIASES`) and +/// both SDKs; test-fixtures/self-report/arg-aliases.json holds the list. +pub const CATEGORY_ALIASES: &[&str] = &["type", "kind"]; + +/// Other names for `detail` (seen live: `summary` and `sentence`). +pub const DETAIL_ALIASES: &[&str] = &[ + "summary", + "sentence", + "message", + "description", + "reason", + "text", + "details", +]; + +/// A call's arguments, as recorded: an unknown category is kept as-is; a +/// missing or empty argument falls back to its first non-empty alias, else ""; +/// unknown keys are ignored. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Report { pub category: String, @@ -710,15 +727,17 @@ pub struct Report { impl Report { pub fn from_args(args: &Value) -> Self { - let text = |key: &str| { - args.get(key) - .and_then(Value::as_str) + let text = |key: &str, aliases: &[&str]| { + std::iter::once(key) + .chain(aliases.iter().copied()) + .filter_map(|k| args.get(k).and_then(Value::as_str)) + .find(|v| !v.is_empty()) .unwrap_or_default() .to_string() }; Report { - category: text("category"), - detail: truncate_chars(&text("detail"), MAX_DETAIL_CHARS), + category: text("category", CATEGORY_ALIASES), + detail: truncate_chars(&text("detail", DETAIL_ALIASES), MAX_DETAIL_CHARS), } } } @@ -1292,6 +1311,26 @@ mod tests { assert!(golden("instructions.golden.txt").chars().count() < 600); } + #[test] + fn golden_arg_aliases() { + let fixture: Value = serde_json::from_str(&golden("arg-aliases.json")).unwrap(); + assert_eq!(fixture["aliases"]["category"], json!(CATEGORY_ALIASES)); + assert_eq!(fixture["aliases"]["detail"], json!(DETAIL_ALIASES)); + let cases = fixture["cases"].as_array().unwrap(); + assert!(!cases.is_empty()); + for case in cases { + assert_eq!( + Report::from_args(&case["args"]), + Report { + category: case["category"].as_str().unwrap().to_string(), + detail: case["detail"].as_str().unwrap().to_string(), + }, + "{}", + case["args"] + ); + } + } + #[test] fn golden_default_categories() { let want: Vec = serde_json::from_str(&golden("categories.golden.json")).unwrap(); diff --git a/crates/fpai-collect/tests/self_report_mcp.rs b/crates/fpai-collect/tests/self_report_mcp.rs index 0a9a12d7e..2cfdf1373 100644 --- a/crates/fpai-collect/tests/self_report_mcp.rs +++ b/crates/fpai-collect/tests/self_report_mcp.rs @@ -407,6 +407,23 @@ async fn a_server_recorded_agent_gets_its_report_written() { assert_eq!(goose["session_id"], "unattributed"); assert_eq!(goose["category"], "made_up"); + // A model that guessed the argument names: the detail is kept, extras ignored. + let (_, reply) = server + .rpc( + "?agent=pi", + json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{ + "name":"report","arguments":{"category":"looping","sentence":"same edit again","extra":1}}}), + ) + .await; + assert_eq!(reply.unwrap()["result"]["content"][0]["text"], "Recorded."); + let events = event_files(&home); + let pi = events + .iter() + .find(|e| e["integration"] == "pi") + .expect("recorded"); + assert_eq!(pi["category"], "looping"); + assert_eq!(pi["detail"], "same edit again"); + server.stop().await; fs::remove_dir_all(&home).ok(); } diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index 9a5212463..c19dcf61a 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -47,7 +47,7 @@ An organization's own list replaces these entirely. Names are lowercase letters, | `repeated_tool_failure` | A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. | | `task_failure` | You genuinely tried and could not complete the task. Not for refusals or policy blocks. | -A report with a category that is not on the list is still recorded under the name the agent gave. The detail is cut to 2,000 characters. +A report with a category that is not on the list is still recorded under the name the agent gave. The detail is cut to 2,000 characters. An agent that calls the tool without loading its schema sometimes guesses the argument names, so when `detail` is missing or empty the first non-empty of `summary`, `sentence`, `message`, `description`, `reason`, `text` and `details` is recorded instead, and when `category` is, `type` or `kind`. Other unknown arguments are ignored; a call is never rejected. ## Agent support @@ -74,7 +74,7 @@ Where an agent's hooks see MCP tool calls, the hook records the report. Where th | Antigravity | `~/.gemini/config/mcp_config.json` | MCP server | | Goose | `~/.config/goose/config.yaml` | MCP server | -`failproofai self-report status` shows, per agent, whether the server is registered, over which transport, and whether that endpoint answers (HTTP) or the command can run (stdio). If an MCP server named `failproofai` that failproofai did not write is already there, such as the [Cloud MCP gateway](/reference/mcp) added under that name, it is left alone and reported as a conflict. +`failproofai self-report status` shows whether the daemon's endpoint answers (`not running (agents use stdio)` when no daemon is set up here) and, per agent, whether the server is registered, over which transport, and whether that endpoint answers (HTTP) or the command can run (stdio). If an MCP server named `failproofai` that failproofai did not write is already there, such as the [Cloud MCP gateway](/reference/mcp) added under that name, it is left alone and reported as a conflict. ## Containers diff --git a/sdk/python/failproofai_sdk/_self_report.py b/sdk/python/failproofai_sdk/_self_report.py index 40397a6af..77ca3f2b1 100644 --- a/sdk/python/failproofai_sdk/_self_report.py +++ b/sdk/python/failproofai_sdk/_self_report.py @@ -311,12 +311,32 @@ def _coerce_text(value: Any) -> str: return value if isinstance(value, str) else str(value) +# Other names a model uses for an argument when it calls the tool without +# loading its schema (seen live: `summary` and `sentence` for `detail`). The +# first non-empty one is used when the real argument is missing or empty; +# unknown keys are ignored. The same list as the CLI and the daemon: +# test-fixtures/self-report/arg-aliases.json. +ARG_ALIASES: dict[str, tuple[str, ...]] = { + "category": ("type", "kind"), + "detail": ("summary", "sentence", "message", "description", "reason", "text", "details"), +} + + +def _first_text(arguments: dict, key: str) -> str: + for name in (key, *ARG_ALIASES[key]): + text = _coerce_text(arguments.get(name)) + if text: + return text + return "" + + def parse_arguments(arguments: Any) -> tuple[str, str]: """`(category, detail)` from a model's tool-call arguments. Never raises. Accepts a dict or a JSON string (OpenAI sends a string, Anthropic a dict). A string that is not a JSON object is kept whole as the detail, so a model - that fumbled the arguments still leaves a readable report. + that fumbled the arguments still leaves a readable report. A missing or + empty argument falls back to its first non-empty alias (`ARG_ALIASES`). """ if isinstance(arguments, (str, bytes, bytearray)): text = arguments.decode("utf-8", "replace") if not isinstance(arguments, str) else arguments @@ -331,7 +351,7 @@ def parse_arguments(arguments: Any) -> tuple[str, str]: arguments = {} if not isinstance(arguments, dict): return "", _coerce_text(arguments)[:SELF_REPORT_DETAIL_LIMIT] - return _coerce_text(arguments.get("category")), _coerce_text(arguments.get("detail")) + return _first_text(arguments, "category"), _first_text(arguments, "detail") _warned_unbound = False @@ -406,6 +426,7 @@ def record_framework_call( agent_id: str | None = None, tool_call_id: Any = None, fields: dict | None = None, + extra_args: dict | None = None, ) -> str: """Record one framework tool call and return `"Recorded."`. Never raises. @@ -427,7 +448,11 @@ def record_framework_call( out["agent_id"] = agent_id if tool_call_id: out["tool_call_id"] = str(tool_call_id) - return record_tool_call({"category": category, "detail": detail}, **out) + # `extra_args`: any other arguments the framework passed through raw, so + # an aliased detail (`summary`, `sentence`, ...) is not lost. + arguments = {k: v for k, v in (extra_args or {}).items() if isinstance(k, str)} + arguments.update(category=category, detail=detail) + return record_tool_call(arguments, **out) def framework_signature(names: list[str]): diff --git a/sdk/python/failproofai_sdk/integrations/pydantic_ai.py b/sdk/python/failproofai_sdk/integrations/pydantic_ai.py index ab911e9cd..7120dd364 100644 --- a/sdk/python/failproofai_sdk/integrations/pydantic_ai.py +++ b/sdk/python/failproofai_sdk/integrations/pydantic_ai.py @@ -1025,10 +1025,11 @@ def self_report_tool( spec = _self_report.self_report_spec(categories=categories, guidance=guidance) extra = framework_fields(NAME, DIST) - def failproofai_report(ctx: Any, category: Any = "", detail: Any = "", **_: Any) -> str: + def failproofai_report(ctx: Any, category: Any = "", detail: Any = "", **raw: Any) -> str: return _self_report.record_framework_call( category, detail, session_id=session_id, agent_id=agent_id, tool_call_id=getattr(ctx, "tool_call_id", None), fields=extra, + extra_args=raw, ) return Tool.from_schema( diff --git a/sdk/python/tests/test_self_report.py b/sdk/python/tests/test_self_report.py index dcc4b30fd..51bf91b2b 100644 --- a/sdk/python/tests/test_self_report.py +++ b/sdk/python/tests/test_self_report.py @@ -386,6 +386,22 @@ def test_handle_tool_call_tolerates_bad_arguments(recorded, arguments, expected) assert (recorded[0]["category"], recorded[0]["detail"]) == expected +def test_handle_tool_call_keeps_an_aliased_detail(recorded): + out = fp.handle_tool_call( + "failproofai_report", '{"kind": "looping", "sentence": "same fix again", "extra": 1}', session_id="s" + ) + assert out == "Recorded." + assert (recorded[0]["category"], recorded[0]["detail"]) == ("looping", "same fix again") + + +def test_framework_calls_keep_a_detail_passed_through_raw(recorded): + out = _self_report.record_framework_call( + "looping", "", session_id="s", extra_args={"summary": "retrying the same edit", "other": 1} + ) + assert out == "Recorded." + assert (recorded[0]["category"], recorded[0]["detail"]) == ("looping", "retrying the same edit") + + def test_handle_tool_call_with_nothing_bound_records_unattributed(recorded): assert fp.handle_tool_call("failproofai_report", {"category": "looping", "detail": "x"}) == "Recorded." assert recorded[0]["session_id"] == "unattributed" diff --git a/sdk/python/tests/test_self_report_golden.py b/sdk/python/tests/test_self_report_golden.py index 933615603..ab959caf3 100644 --- a/sdk/python/tests/test_self_report_golden.py +++ b/sdk/python/tests/test_self_report_golden.py @@ -81,3 +81,13 @@ def test_event_field_order(): ) assert list(SelfReportEvent(**base).to_dict()) == spec["order"] assert list(SelfReportEvent(**base, tool_call_id="call_1").to_dict()) == spec["order"] + spec["optional"] + + +def test_argument_aliases_match_the_shared_list(): + fixture = json.loads(golden("arg-aliases.json")) + assert {k: list(v) for k, v in _self_report.ARG_ALIASES.items()} == fixture["aliases"] + assert fixture["cases"] + for case in fixture["cases"]: + want = (case["category"], case["detail"]) + assert _self_report.parse_arguments(case["args"]) == want, case["args"] + assert _self_report.parse_arguments(json.dumps(case["args"])) == want, case["args"] diff --git a/sdk/typescript/src/self-report-spec.ts b/sdk/typescript/src/self-report-spec.ts index 67c87e3f7..4adeea3f2 100644 --- a/sdk/typescript/src/self-report-spec.ts +++ b/sdk/typescript/src/self-report-spec.ts @@ -186,7 +186,8 @@ export function isSelfReportTool(name: unknown, server?: unknown): boolean { * The call's arguments as the event records them. * * Never rejects: a model that names an unknown category is still recorded - * under that name, a missing `detail` is recorded as `""`, and arguments that + * under that name, a missing or empty argument falls back to its first + * non-empty alias (`SELF_REPORT_ARG_ALIASES`) else `""`, and arguments that * arrive as the JSON string a provider sent (OpenAI's `function.arguments`) * are parsed first. Anything unreadable becomes the empty strings — the call * itself always answers `Recorded.`. @@ -201,7 +202,30 @@ export function normalizeSelfReportArgs(args: unknown): { category: string; deta } } const record = typeof value === "object" && value !== null ? (value as Record) : {}; - return { category: asText(record.category), detail: clipDetail(asText(record.detail)) }; + return { + category: firstText(record, "category", SELF_REPORT_ARG_ALIASES.category), + detail: clipDetail(firstText(record, "detail", SELF_REPORT_ARG_ALIASES.detail)), + }; +} + +/** + * Other names a model uses for an argument when it calls the tool without + * loading its schema (seen live: `summary` and `sentence` for `detail`). The + * first non-empty one is used when the real argument is missing or empty; + * unknown keys are ignored. The same list as the CLI and the daemon: + * test-fixtures/self-report/arg-aliases.json. + */ +export const SELF_REPORT_ARG_ALIASES = Object.freeze({ + category: Object.freeze(["type", "kind"]), + detail: Object.freeze(["summary", "sentence", "message", "description", "reason", "text", "details"]), +}); + +function firstText(record: Record, key: string, aliases: readonly string[]): string { + for (const name of [key, ...aliases]) { + const text = asText(record[name]); + if (text) return text; + } + return ""; } function asText(value: unknown): string { diff --git a/sdk/typescript/test/self-report-golden.test.ts b/sdk/typescript/test/self-report-golden.test.ts index 970dc9757..e5798c17e 100644 --- a/sdk/typescript/test/self-report-golden.test.ts +++ b/sdk/typescript/test/self-report-golden.test.ts @@ -6,9 +6,11 @@ import { describe, expect, it } from "vitest"; import * as schema from "../src/schema.js"; import { DEFAULT_SELF_REPORT_CATEGORIES, + SELF_REPORT_ARG_ALIASES, SELF_REPORT_TOOL_SPELLINGS, describeSelfReport, isSelfReportTool, + normalizeSelfReportArgs, selfReportInputSchema, } from "../src/self-report-spec.js"; @@ -30,6 +32,19 @@ describe("Self Reports golden files (TypeScript SDK)", () => { ).toBe(golden("description-guidance.golden.txt")); }); + it("reads argument aliases from the shared list", () => { + const fixture = JSON.parse(golden("arg-aliases.json")) as { + aliases: { category: string[]; detail: string[] }; + cases: { args: Record; category: string; detail: string }[]; + }; + expect(SELF_REPORT_ARG_ALIASES).toEqual(fixture.aliases); + for (const c of fixture.cases) { + const want = { category: c.category, detail: c.detail }; + expect(normalizeSelfReportArgs(c.args), JSON.stringify(c.args)).toEqual(want); + expect(normalizeSelfReportArgs(JSON.stringify(c.args)), JSON.stringify(c.args)).toEqual(want); + } + }); + it("builds the input schema byte for byte", () => { expect(`${JSON.stringify(selfReportInputSchema(DEFAULT_SELF_REPORT_CATEGORIES))}\n`).toBe( golden("input-schema.golden.json"), diff --git a/sdk/typescript/test/self-report.test.ts b/sdk/typescript/test/self-report.test.ts index b78649a16..7f24ffe92 100644 --- a/sdk/typescript/test/self-report.test.ts +++ b/sdk/typescript/test/self-report.test.ts @@ -334,6 +334,13 @@ describe("the raw tool helpers", () => { }); }); + it("keeps the detail a model sent under an alias (summary), ignoring unknown keys", async () => { + await session({ sessionId: "s1" }, () => + failproofai.handleToolCall("failproofai_report", { type: "looping", summary: "Same fix three times.", extra: 1 }), + ); + expect((await reports())[0]).toMatchObject({ category: "looping", detail: "Same fix three times." }); + }); + it("returns null for any other tool, recording nothing", async () => { expect(failproofai.handleToolCall("get_weather", { city: "Paris" })).toBeNull(); expect(await reports()).toEqual([]); diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts index 23a7bd7d0..ca10a70fa 100644 --- a/src/hooks/self-report-cli.ts +++ b/src/hooks/self-report-cli.ts @@ -28,6 +28,7 @@ import { type SelfReportCategory, } from "./self-report"; import { INTEGRATION_TYPES } from "./types"; +import { daemonSocketPresent, isDaemonConfigured } from "./daemon-client"; import { probeSelfReportHttp, selfReportCommandRunnable, @@ -52,6 +53,8 @@ export interface SelfReportCliDeps { registrations?: () => SelfReportRegistration[]; /** Sync override (tests). */ sync?: () => Promise; + /** Override (tests): is a daemon configured here, or its socket file present? */ + daemonExpected?: () => boolean; /** Skip the agent sync after enable/disable (tests). */ skipSync?: boolean; cwd?: string; @@ -188,11 +191,24 @@ async function selfReportStatus(deps: SelfReportCliDeps): Promise probeSelfReportHttp(port)); health.set(settings.mcp.port, await probe(settings.mcp.url, settings.mcp.port)); } - lines.push(`Daemon MCP: ${settings.mcp.url} (${health.get(settings.mcp.port) ? "answering" : "not answering"})`); + lines.push(selfReportDaemonLine(settings.mcp.url, health.get(settings.mcp.port) === true, deps)); lines.push(...selfReportRegistrationLines(rows, health)); return { exitCode: 0, lines }; } +/** + * The daemon's MCP endpoint, for `status`. "not answering" reads as a fault, so + * it is shown only where a daemon is expected: one is configured (setup ran) or + * its socket file is there. With neither, there is no daemon and agents use + * stdio, which is a normal setup. + */ +function selfReportDaemonLine(url: string, answering: boolean, deps: SelfReportCliDeps): string { + if (answering) return `Daemon MCP: ${url} (answering)`; + const expected = deps.daemonExpected ?? (() => isDaemonConfigured() || daemonSocketPresent()); + if (expected()) return `Daemon MCP: ${url} (not answering)`; + return "Daemon MCP: not running (agents use stdio)"; +} + /** Update every hooked agent's MCP entry to match the settings just written. */ async function selfReportSync(deps: SelfReportCliDeps): Promise { if (deps.skipSync) return []; diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts index dc6985869..630e47f55 100644 --- a/src/hooks/self-report.ts +++ b/src/hooks/self-report.ts @@ -174,8 +174,9 @@ function selfReportInstructions( const names = categories.map((c) => c.name).join(", "); const body = `FailproofAI records when an agent is stuck. If you get stuck (${names}), call this server's ` + - "`report` tool once with the matching category and one factual sentence. It does not unblock you: " + - "continue, or tell the user what is blocking you. There is no need to mention the report to the user."; + "`report` tool once with two arguments: `category` (one of those names) and `detail` (one factual " + + "sentence). It does not unblock you: continue, or tell the user what is blocking you. There is no " + + "need to mention the report to the user."; return guidance ? `${body}\n\n${guidance}` : body; } @@ -186,7 +187,8 @@ export const SELF_REPORT_RESULT_TEXT = "Recorded."; /** * A call's arguments as they are recorded: an unknown category is kept as-is - * (never rejected), a missing or empty detail is `""`, detail is cut to 2000 + * (never rejected), a missing or empty argument falls back to its first + * non-empty alias (`SELF_REPORT_ARG_ALIASES`), else `""`; unknown keys are ignored; detail is cut to 2000 * characters. A category is cut to the same bound so a hostile argument cannot * grow every activity row without limit. * @@ -199,7 +201,7 @@ export function selfReportArgs(input: unknown): { category: string; detail: stri if (typeof args === "string") args = selfReportParseJson(args); if (args && typeof args === "object" && !Array.isArray(args)) { const rec = args as Record; - if (rec.category === undefined && rec.detail === undefined) { + if (!SELF_REPORT_ARG_KEYS.some((key) => rec[key] !== undefined)) { for (const key of ["arguments", "args", "input", "params"]) { let inner = rec[key]; if (typeof inner === "string") inner = selfReportParseJson(inner); @@ -211,16 +213,42 @@ export function selfReportArgs(input: unknown): { category: string; detail: stri } } const rec = args && typeof args === "object" && !Array.isArray(args) ? (args as Record) : {}; - const cat = rec.category; - const det = rec.detail; - const category = cat === undefined || cat === null ? "" : typeof cat === "string" ? cat : JSON.stringify(cat); - const detail = det === undefined || det === null ? "" : typeof det === "string" ? det : JSON.stringify(det); + const category = selfReportArg(rec, "category", SELF_REPORT_ARG_ALIASES.category); + const detail = selfReportArg(rec, "detail", SELF_REPORT_ARG_ALIASES.detail); return { category: category.slice(0, SELF_REPORT_DETAIL_MAX), detail: detail.slice(0, SELF_REPORT_DETAIL_MAX), }; } +/** + * Other names a model uses for an argument when it calls the tool without + * loading its schema (seen live: `summary` and `sentence` for `detail`). The + * first non-empty one is used when the real argument is missing or empty. + * Identical in the daemon (crates/fpai-collect/src/self_report.rs) and both + * SDKs; test-fixtures/self-report/arg-aliases.json holds the list for all of them. + */ +export const SELF_REPORT_ARG_ALIASES = { + category: ["type", "kind"], + detail: ["summary", "sentence", "message", "description", "reason", "text", "details"], +} as const; + +const SELF_REPORT_ARG_KEYS: readonly string[] = [ + "category", + "detail", + ...SELF_REPORT_ARG_ALIASES.category, + ...SELF_REPORT_ARG_ALIASES.detail, +]; + +function selfReportArg(rec: Record, key: string, aliases: readonly string[]): string { + for (const name of [key, ...aliases]) { + const value = rec[name]; + const text = value === undefined || value === null ? "" : typeof value === "string" ? value : JSON.stringify(value); + if (text) return text; + } + return ""; +} + function selfReportParseJson(text: string): unknown { try { return JSON.parse(text); diff --git a/test-fixtures/self-report/arg-aliases.json b/test-fixtures/self-report/arg-aliases.json new file mode 100644 index 000000000..1c0b73bae --- /dev/null +++ b/test-fixtures/self-report/arg-aliases.json @@ -0,0 +1,58 @@ +{ + "aliases": { + "category": ["type", "kind"], + "detail": ["summary", "sentence", "message", "description", "reason", "text", "details"] + }, + "cases": [ + { + "args": {"category": "looping", "detail": "Same test fails after three fixes."}, + "category": "looping", + "detail": "Same test fails after three fixes." + }, + { + "args": {"category": "missing_context", "summary": "No access to the staging database."}, + "category": "missing_context", + "detail": "No access to the staging database." + }, + { + "args": {"category": "task_failure", "sentence": "The build never finishes."}, + "category": "task_failure", + "detail": "The build never finishes." + }, + { + "args": {"category": "looping", "detail": "", "sentence": "", "message": "Going in circles."}, + "category": "looping", + "detail": "Going in circles." + }, + { + "args": {"category": "looping", "detail": "Kept.", "summary": "Ignored."}, + "category": "looping", + "detail": "Kept." + }, + { + "args": {"type": "invalid_tool_or_credential", "details": "The API key is rejected."}, + "category": "invalid_tool_or_credential", + "detail": "The API key is rejected." + }, + { + "args": {"category": "", "kind": "cannot_do_request", "reason": "No deploy permission."}, + "category": "cannot_do_request", + "detail": "No deploy permission." + }, + { + "args": {"category": "looping", "type": "ignored", "text": "Later in the list.", "description": "Earlier in the list."}, + "category": "looping", + "detail": "Earlier in the list." + }, + { + "args": {"category": "looping", "unknown": "Not an alias.", "priority": "high"}, + "category": "looping", + "detail": "" + }, + { + "args": {}, + "category": "", + "detail": "" + } + ] +} diff --git a/test-fixtures/self-report/instructions-guidance.golden.txt b/test-fixtures/self-report/instructions-guidance.golden.txt index e57cd7548..cc0b0dfad 100644 --- a/test-fixtures/self-report/instructions-guidance.golden.txt +++ b/test-fixtures/self-report/instructions-guidance.golden.txt @@ -1,3 +1,3 @@ -FailproofAI records when an agent is stuck. If you get stuck (looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure), call this server's `report` tool once with the matching category and one factual sentence. It does not unblock you: continue, or tell the user what is blocking you. There is no need to mention the report to the user. +FailproofAI records when an agent is stuck. If you get stuck (looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure), call this server's `report` tool once with two arguments: `category` (one of those names) and `detail` (one factual sentence). It does not unblock you: continue, or tell the user what is blocking you. There is no need to mention the report to the user. Report a missing repository as missing_context. \ No newline at end of file diff --git a/test-fixtures/self-report/instructions.golden.txt b/test-fixtures/self-report/instructions.golden.txt index aa1fdf283..69d973551 100644 --- a/test-fixtures/self-report/instructions.golden.txt +++ b/test-fixtures/self-report/instructions.golden.txt @@ -1 +1 @@ -FailproofAI records when an agent is stuck. If you get stuck (looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure), call this server's `report` tool once with the matching category and one factual sentence. It does not unblock you: continue, or tell the user what is blocking you. There is no need to mention the report to the user. \ No newline at end of file +FailproofAI records when an agent is stuck. If you get stuck (looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure), call this server's `report` tool once with two arguments: `category` (one of those names) and `detail` (one factual sentence). It does not unblock you: continue, or tell the user what is blocking you. There is no need to mention the report to the user. \ No newline at end of file From cc064fd19904f9d56b057fb60e28e78bd3b70e99 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 26 Nov 2026 16:40:45 +0530 Subject: [PATCH 12/54] [self-reports] Fix the harness and SDK test-round bugs Harness side - Cursor is server-recorded: its installed preToolUse hook names an MCP call `MCP:report` with no server, so the MCP server records Cursor's reports (TS, Rust and golden lists). A bare `MCP:report` is still not exempt; only a payload with `mcp_server_name: "failproofai"` is. cursor-agent approvals are per project root and entry hash, so none is written; sync and status print "run `cursor-agent mcp enable failproofai`" for Cursor. - Antigravity's lazy path: `call_mcp_tool` is unwrapped and allowed ahead of the policies only when ServerName is `failproofai` and ToolName `report`. - Copilot's likely spelling `failproofai-report` is exempt everywhere (CLI, both SDKs, golden). - Server-recorded attribution (stdio and the daemon's HTTP fallback, same rules): exact cwd, else an ancestor/descendant cwd, else the agent's newest session within 6 h; agent_id comes from the matched hook row's cwd. - A hand-started daemon's startup sync falls back to `failproofai` on PATH and the npm/bun global bins when FAILPROOFAI_CLI_CMD is unset. - Pi's entry sets `exposure: "direct"`. Hermes/OpenClaw have no per-server direct option (global tool search only), so nothing is set there. - The native policy-evaluation probe uses the shared probe marker and is answered (allow) before any activity row: no phantom `hermes` SessionStart. - Docs: Copilot passes server instructions only for allowlisted servers; HTTP attribution has no cwd (concurrent sessions of one agent can swap reports); container setup (CLI on PATH, FAILPROOFAI_WORKER_CMD for Hermes/OpenClaw). SDK side - TS `/langchain`: the call id is read from `config.toolCall.id` (2nd argument for `tool()`, 3rd for DynamicStructuredTool); a run id is never used. - Both SDKs: a report without a call id takes the id of the open report-tool `tool_use` it is matched to (also with an explicit session), so LlamaIndex (Py+TS) reports join their call; CrewAI reads its tool-usage scope id. - Pydantic AI: a hand-added `FailproofAI(...)` records its run without `instrument()`; only the injected capability goes inert on uninstrument. - Python LangChain `self_report_tool` takes the ToolCall's id with no adapter. - TS `openaiResponsesTool()`, matching Python's `openai_responses_tool()`. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/self-report-golden.test.ts | 2 +- __tests__/hooks/self-report-handler.test.ts | 89 +++++++++++++-- __tests__/hooks/self-report-install.test.ts | 19 +++ __tests__/hooks/self-report.test.ts | 68 ++++++++++- crates/failproofaid/src/self_report.rs | 108 +++++++++++++++++- crates/fpai-collect/src/self_report.rs | 108 +++++++++++++++--- docs/reference/custom-agents-typescript.mdx | 2 +- docs/self-reports.mdx | 24 +++- sdk/python/failproofai_sdk/_events.py | 49 ++++++-- sdk/python/failproofai_sdk/_self_report.py | 4 +- .../failproofai_sdk/integrations/crewai.py | 27 ++++- .../failproofai_sdk/integrations/langchain.py | 46 +++++++- .../integrations/pydantic_ai.py | 28 +++-- sdk/python/tests/integrations/test_crewai.py | 3 + .../tests/integrations/test_langchain.py | 27 +++++ .../tests/integrations/test_llama_index.py | 3 + .../tests/integrations/test_pydantic_ai.py | 16 +++ sdk/python/tests/test_self_report.py | 15 ++- sdk/typescript/README.md | 2 +- sdk/typescript/src/edge/index.ts | 6 + sdk/typescript/src/events.ts | 25 ++-- sdk/typescript/src/index.ts | 4 +- .../src/integrations/self-report-tools.ts | 14 ++- sdk/typescript/src/self-report-spec.ts | 16 ++- sdk/typescript/src/self-report.ts | 17 ++- sdk/typescript/test/self-report.test.ts | 45 +++++++- src/hooks/daemon-service.ts | 4 +- src/hooks/handler.ts | 37 +++++- src/hooks/health-probe.ts | 11 +- src/hooks/self-report-cli.ts | 6 +- src/hooks/self-report-install.ts | 29 ++++- src/hooks/self-report-mcp.ts | 80 ++++++++++--- src/hooks/self-report-names.ts | 46 +++++++- src/hooks/self-report.ts | 1 + .../self-report/server-records.golden.txt | 1 + .../self-report/tool-names.golden.txt | 1 + 37 files changed, 874 insertions(+), 111 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f703e7be..6c0146eaa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Features -- Self Reports: every hooked agent gets a `report` tool (MCP server `failproofai`, served by `failproofaid` at `http://127.0.0.1:4319/mcp` or by `failproofai mcp` over stdio) to say it is stuck, under six default categories or the organization's own; the hook allows the call before any policy, pause or Jev review and records it as a `self_report` event, the MCP server records it for agents whose hooks do not see MCP calls, the setting comes from Cloud (`selfReport` in desired-state) or `failproofai self-report enable|disable|status|test|sync` and lives in `~/.failproofai/self-report.json`, and both SDKs add `self_report()` / `selfReport()` with ready-made framework tools; the server's initialize result carries short instructions (agents that defer MCP tools, like Claude Code, still see them), and HTTP vs stdio is chosen from a live daemon check that the daemon re-runs at startup; the instructions name the `category` and `detail` arguments, and a call that sends the detail under another name (`summary`, `sentence`, `message`, ...) still records it +- Self Reports: every hooked agent gets a `report` tool (MCP server `failproofai`, served by `failproofaid` at `http://127.0.0.1:4319/mcp` or by `failproofai mcp` over stdio) to say it is stuck, under six default categories or the organization's own; the hook allows the call before any policy, pause or Jev review and records it as a `self_report` event, the MCP server records it for agents whose hooks do not see MCP calls, the setting comes from Cloud (`selfReport` in desired-state) or `failproofai self-report enable|disable|status|test|sync` and lives in `~/.failproofai/self-report.json`, and both SDKs add `self_report()` / `selfReport()` with ready-made framework tools; the server's initialize result carries short instructions (agents that defer MCP tools, like Claude Code, still see them), and HTTP vs stdio is chosen from a live daemon check that the daemon re-runs at startup; the instructions name the `category` and `detail` arguments, and a call that sends the detail under another name (`summary`, `sentence`, `message`, ...) still records it; Cursor reports are recorded by the MCP server (its tool hook does not name the server), Antigravity's `call_mcp_tool` wrapper for `failproofai`/`report` is allowed ahead of the policies, Copilot's likely `failproofai-report` spelling is exempt, Pi's entry is exposed directly, server-recorded reports find their session by an exact, then related, then any working directory and take the session's own agent, and a hand-started daemon finds `failproofai` on PATH for its startup sync ### Fixes diff --git a/__tests__/hooks/self-report-golden.test.ts b/__tests__/hooks/self-report-golden.test.ts index 2b182a961..af8787751 100644 --- a/__tests__/hooks/self-report-golden.test.ts +++ b/__tests__/hooks/self-report-golden.test.ts @@ -102,7 +102,7 @@ describe("Self Reports golden files (CLI)", () => { const block = rs.match(/pub const SERVER_RECORDS: &\[&str\] = &\[([\s\S]*?)\];/); expect(block, "SERVER_RECORDS in self_report.rs").not.toBeNull(); expect([...block![1].matchAll(/"([^"]+)"/g)].map((m) => m[1])).toEqual([...SELF_REPORT_SERVER_RECORDS]); - for (const hooked of ["claude", "codex", "cursor"]) expect(SELF_REPORT_SERVER_RECORDS).not.toContain(hooked); + for (const hooked of ["claude", "codex"]) expect(SELF_REPORT_SERVER_RECORDS).not.toContain(hooked); }); describe("the stdio server's fallback event", () => { diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index cc0db945d..431b8ffc3 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -37,6 +37,7 @@ import { readMergedHooksConfig } from "../../src/hooks/hooks-config"; import { jevChecksInstalled } from "../../src/hooks/effective-reviewers"; import { writePause } from "../../src/hooks/session-pause"; import { _resetForTest } from "../../src/hooks/hook-activity-store"; +import { HEALTH_PROBE_SOURCE } from "../../src/hooks/health-probe"; const SESSION = "sr-session"; let home: string; @@ -207,6 +208,8 @@ describe("Self Reports short-circuit", () => { ["goose", "failproofai__report"], ["pi", "mcp__failproofai__report"], ["devin", "mcp__failproofai__report"], + ["copilot", "failproofai-report"], + ["copilot", "failproofai/report"], ] as const)("allows %s's spelling %s past a deny-everything policy", async (cli, name) => { const out = await evaluateHookEvent( "PreToolUse", @@ -217,7 +220,7 @@ describe("Self Reports short-circuit", () => { expect(loadAllCustomHooks).not.toHaveBeenCalled(); }); - it("allows and records Cursor's beforeMCPExecution for the failproofai server, with a schema-valid answer", async () => { + it("allows Cursor's beforeMCPExecution for the failproofai server, with a schema-valid answer, leaving the report to the server", async () => { const out = await evaluateHookEvent( "beforeMCPExecution", "cursor", @@ -230,16 +233,88 @@ describe("Self Reports short-circuit", () => { expect(JSON.parse(out.stdout)).toEqual({ permission: "allow" }); expect(loadAllCustomHooks).not.toHaveBeenCalled(); const [row] = rows(); - expect(row).toMatchObject({ - eventType: "PreToolUse", - integration: "cursor", - toolName: "mcp__failproofai__report", - selfReport: { category: "missing_context", detail: "no repo access", source: "mcp" }, - }); + // Cursor is server-recorded: the MCP server writes the report, so the + // hook row must not carry a second one. + expect(row).toMatchObject({ eventType: "PreToolUse", integration: "cursor", toolName: "mcp__failproofai__report" }); + expect(row.selfReport).toBeUndefined(); }); it("does not early-allow Cursor's bare MCP:report without a server name", async () => { const out = await evaluateHookEvent("preToolUse", "cursor", payload("MCP:report", { category: "looping", detail: "x" })); expect(out.evaluation?.decision).toBe("deny"); }); + + it("early-allows Cursor's preToolUse MCP:report only when the payload names server failproofai", async () => { + const ours = await evaluateHookEvent( + "preToolUse", + "cursor", + payload("MCP:report", { category: "looping", detail: "x" }, { mcp_server_name: "failproofai" }), + ); + expect(ours.evaluation?.decision).toBe("allow"); + expect(rows().pop()!.selfReport).toBeUndefined(); + const theirs = await evaluateHookEvent( + "preToolUse", + "cursor", + payload("MCP:report", { category: "looping", detail: "x" }, { mcp_server_name: "linear" }), + ); + expect(theirs.evaluation?.decision).toBe("deny"); + }); + + describe("Antigravity's lazy MCP path (call_mcp_tool)", () => { + const agy = (args: Record) => + JSON.stringify({ conversationId: SESSION, workspacePaths: ["/tmp/project"], toolCall: { name: "call_mcp_tool", args } }); + + it("early-allows the wrapper when it names server failproofai and tool report", async () => { + const out = await evaluateHookEvent( + "PreToolUse", + "antigravity", + agy({ ServerName: "failproofai", ToolName: "report", Arguments: { category: "looping", detail: "again" } }), + ); + expect(out.evaluation?.decision).toBe("allow"); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + const row = rows().pop()!; + expect(row).toMatchObject({ integration: "antigravity", toolName: "mcp__failproofai__report", sessionId: SESSION }); + // Antigravity is server-recorded: the MCP server writes the report. + expect(row.selfReport).toBeUndefined(); + }); + + it("accepts the wrapped arguments as a JSON string", async () => { + const out = await evaluateHookEvent( + "PreToolUse", + "antigravity", + agy({ ServerName: "failproofai", ToolName: "report", Arguments: JSON.stringify({ category: "looping", detail: "x" }) }), + ); + expect(out.evaluation?.decision).toBe("allow"); + }); + + it.each([ + [{ ServerName: "linear", ToolName: "report", Arguments: {} }], + [{ ServerName: "failproofai", ToolName: "search", Arguments: {} }], + [{ ToolName: "report", Arguments: {} }], + [{ ServerName: "failproofai-evil", ToolName: "report" }], + ])("keeps any other wrapped call on the policy path: %j", async (args) => { + const out = await evaluateHookEvent("PreToolUse", "antigravity", agy(args)); + expect(out.evaluation?.decision).toBe("deny"); + }); + + it("does not unwrap call_mcp_tool for any other agent", async () => { + const out = await evaluateHookEvent( + "PreToolUse", + "claude", + payload("call_mcp_tool", { ServerName: "failproofai", ToolName: "report", Arguments: {} }), + ); + expect(out.evaluation?.decision).toBe("deny"); + }); + }); + + it("answers the native policy-evaluation health probe with an allow and writes no activity row", async () => { + const out = await evaluateHookEvent( + "on_session_start", + "hermes", + JSON.stringify({ hook_event_name: "on_session_start", source: HEALTH_PROBE_SOURCE }), + ); + expect(out.evaluation?.decision).toBe("allow"); + expect(rows()).toEqual([]); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + }); }); diff --git a/__tests__/hooks/self-report-install.test.ts b/__tests__/hooks/self-report-install.test.ts index 8d7815911..44ef92ec7 100644 --- a/__tests__/hooks/self-report-install.test.ts +++ b/__tests__/hooks/self-report-install.test.ts @@ -147,6 +147,25 @@ describe("transport choice", () => { expect(entryIn("goose")).toMatchObject({ type: "stdio", cmd: CLI, args: ["mcp", "--agent", "goose"], enabled: true }); }); + it("exposes Pi's entry directly, on both transports, and moves an old entry to it", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["pi"] }, false)); + expect(entryIn("pi")).toEqual({ command: CLI, args: ["mcp", "--agent", "pi"], exposure: "direct" }); + // An entry written before `exposure` was set is ours and gets updated. + put(pathOf("pi"), JSON.stringify({ mcpServers: { failproofai: { url: "http://127.0.0.1:4319/mcp?agent=pi" } } })); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["pi"] }, true)); + expect(r[0]).toMatchObject({ action: "updated", transport: "http" }); + expect(entryIn("pi")).toEqual({ url: "http://127.0.0.1:4319/mcp?agent=pi", exposure: "direct" }); + }); + + it("tells the user how cursor-agent approves the server when Cursor's entry is written", async () => { + const { selfReportSyncLines } = await import("../../src/hooks/self-report-install"); + const lines = selfReportSyncLines(await syncSelfReportMcp(enabledOpts({ agents: ["cursor", "claude"] }))); + expect(lines.filter((l) => l.includes("cursor-agent mcp enable failproofai"))).toHaveLength(1); + expect(lines.findIndex((l) => l.includes("cursor-agent mcp enable"))).toBe( + lines.findIndex((l) => l.includes("Cursor")) + 1, + ); + }); + it("switches an existing entry between transports in place", async () => { await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); const r = await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, true)); diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index 3cd476085..38a5391c4 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -23,7 +23,13 @@ import { writeEffectiveSelfReport, selfReportInstructions, } from "../../src/hooks/self-report"; -import { handleSelfReportRpc, selfReportAgentId, selfReportFindSession } from "../../src/hooks/self-report-mcp"; +import { + handleSelfReportRpc, + selfReportAgentId, + selfReportCwdAffinity, + selfReportFindSession, + selfReportFindSessionMatch, +} from "../../src/hooks/self-report-mcp"; import { runSelfReportCommand } from "../../src/hooks/self-report-cli"; const BINARY = resolve(__dirname, "..", "..", "bin", "failproofai.mjs"); @@ -101,8 +107,10 @@ describe("tool-name matching (contract §1)", () => { (name) => expect(isSelfReportToolName(name)).toBe(false), ); it("lists the server-recorded integrations from the contract", () => { - expect(SELF_REPORT_SERVER_RECORDS).toEqual(["openclaw", "pi", "devin", "hermes", "goose", "factory", "antigravity", "copilot", "opencode"]); - for (const hookRecorded of ["claude", "codex", "cursor"]) expect(SELF_REPORT_SERVER_RECORDS).not.toContain(hookRecorded); + expect(SELF_REPORT_SERVER_RECORDS).toEqual([ + "openclaw", "pi", "devin", "hermes", "goose", "factory", "antigravity", "copilot", "opencode", "cursor", + ]); + for (const hookRecorded of ["claude", "codex"]) expect(SELF_REPORT_SERVER_RECORDS).not.toContain(hookRecorded); }); }); @@ -201,10 +209,57 @@ describe("MCP fallback recording helpers", () => { ].join("\n") + "\n", ); expect(selfReportFindSession("pi", "/p", now)).toBe("s2"); - expect(selfReportFindSession("pi", "/nowhere", now)).toBeNull(); + // No row in or around this cwd: the agent's newest session anywhere. + expect(selfReportFindSession("pi", "/nowhere", now)).toBe("wrong-cwd"); + expect(selfReportFindSession("goose", "/nowhere", now)).toBe("wrong-agent"); + expect(selfReportFindSession("hermes", "/p", now)).toBeNull(); expect(selfReportFindSession("pi", "/p", now + 10 * 3600_000)).toBeNull(); }); + it("prefers an exact cwd, then an ancestor or descendant, then any session, and returns the row's cwd", () => { + const now = 1_800_000_000_000; + mkdirSync(join(home, "hook-activity"), { recursive: true }); + const row = (o: Record) => JSON.stringify({ eventType: "PreToolUse", decision: "allow", integration: "hermes", ...o }); + writeFileSync( + join(home, "hook-activity", "current.jsonl"), + [ + row({ cwd: "/root/.hermes/hermes-agent", sessionId: "below", timestamp: now - 5000 }), + row({ cwd: "/srv/elsewhere", sessionId: "unrelated-newest", timestamp: now - 10 }), + row({ cwd: "/", sessionId: "root-row", timestamp: now - 9000 }), + ].join("\n") + "\n", + ); + // Server in /root, the agent's rows below it: the descendant wins over a newer unrelated one. + expect(selfReportFindSessionMatch("hermes", "/root", now)).toEqual({ sessionId: "below", cwd: "/root/.hermes/hermes-agent" }); + // `/` is an ancestor of everything; the newest related row wins. + expect(selfReportFindSessionMatch("hermes", "/srv/elsewhere/sub", now)?.sessionId).toBe("unrelated-newest"); + expect(selfReportFindSessionMatch("hermes", "/srv/elsewhere/", now)?.sessionId).toBe("unrelated-newest"); + // Nothing related except `/`, which counts as an ancestor. + expect(selfReportFindSessionMatch("hermes", "/work/ws", now)?.sessionId).toBe("root-row"); + expect(selfReportCwdAffinity("/a/b", "/a/bc")).toBe(0); + expect(selfReportCwdAffinity("/a/b", "/a/b/")).toBe(2); + expect(selfReportCwdAffinity("/a/b", "/a")).toBe(1); + expect(selfReportCwdAffinity("/a/b", undefined)).toBe(0); + }); + + it("files a fallback report under the matched row's agent, not the server's cwd", async () => { + writeEffectiveSelfReport({ enabled: true }); + const now = Date.now(); + mkdirSync(join(home, "hook-activity"), { recursive: true }); + writeFileSync( + join(home, "hook-activity", "current.jsonl"), + JSON.stringify({ timestamp: now - 1000, eventType: "PreToolUse", integration: "openclaw", cwd: "/root/.openclaw/workspace", sessionId: "oc-1", decision: "allow" }) + "\n", + ); + const reply = await handleSelfReportRpc( + { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "report", arguments: { category: "looping", detail: "d" } } }, + { agent: "openclaw", cwd: "/work/ws", now: () => now }, + ); + expect(reply).toMatchObject({ result: { content: [{ text: "Recorded." }] } }); + const dir = join(home, "custom-agents", "events"); + const [file] = readdirSync(dir); + const event = JSON.parse(readFileSync(join(dir, file), "utf8").trim()); + expect(event).toMatchObject({ session_id: "oc-1", agent_id: "openclaw-workspace", integration: "openclaw" }); + }); + it("an unknown method gets -32601; a notification gets no reply; an unknown tool is an error result", async () => { expect(await handleSelfReportRpc({ jsonrpc: "2.0", id: 9, method: "resources/list" })).toMatchObject({ error: { code: -32601 } }); expect(await handleSelfReportRpc({ jsonrpc: "2.0", method: "notifications/initialized" })).toBeNull(); @@ -421,6 +476,11 @@ describe("failproofai self-report enable | disable | status", () => { expect(text).toMatch(/codex +http +http:\/\/127\.0\.0\.1:4999\/mcp\?agent=codex \(NOT answering\)/); expect(text).toMatch(new RegExp(`cursor +stdio +${runnable} \\(runnable\\)`)); expect(text).toMatch(/factory +stdio +.*\(NOT runnable\)/); + // Cursor's line is followed by how to approve the server in cursor-agent; nobody else's is. + const lines = text.split("\n"); + const at = lines.findIndex((l) => /^ +cursor +stdio/.test(l)); + expect(lines[at + 1]).toContain("cursor-agent mcp enable failproofai"); + expect(lines.filter((l) => l.includes("cursor-agent mcp enable"))).toHaveLength(1); }); it("status says the daemon is not running, not \"not answering\", when there is no daemon", async () => { diff --git a/crates/failproofaid/src/self_report.rs b/crates/failproofaid/src/self_report.rs index 185cd299c..b942d7676 100644 --- a/crates/failproofaid/src/self_report.rs +++ b/crates/failproofaid/src/self_report.rs @@ -9,7 +9,7 @@ //! must not keep the tool registered in every agent). use std::io; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; use std::sync::Mutex; use std::sync::atomic::{AtomicBool, Ordering}; @@ -274,12 +274,69 @@ pub fn spawn_sync() { } } +/// The command that runs the CLI for `self-report sync`: the service unit's +/// `FAILPROOFAI_CLI_CMD` (the same one the audit lane runs), else a +/// `failproofai` found on `PATH` or in the npm/bun global bin directories. A +/// daemon started by hand in a container has no unit and so no +/// `FAILPROOFAI_CLI_CMD`, while the CLI an `npm install -g` put there is right +/// beside it. +fn sync_cli_command() -> Option { + crate::audit_lane::cli_command().or_else(|| { + let home = std::env::var_os("HOME").map(PathBuf::from); + let dirs = global_bin_dirs( + std::env::var_os("NPM_CONFIG_PREFIX") + .or_else(|| std::env::var_os("npm_config_prefix")) + .map(PathBuf::from), + home.as_deref(), + ); + find_cli(std::env::var_os("PATH").as_deref(), &dirs).map(|path| shell_quote(&path)) + }) +} + +/// npm's (and bun's) global bin directories, beyond `PATH`: `$NPM_CONFIG_PREFIX/bin`, +/// `~/.npm-global/bin`, `/usr/local/bin` (npm's default prefix in the Node +/// images), `~/.bun/bin`. +fn global_bin_dirs(npm_prefix: Option, home: Option<&Path>) -> Vec { + let mut dirs = Vec::new(); + if let Some(prefix) = npm_prefix.filter(|p| !p.as_os_str().is_empty()) { + dirs.push(prefix.join("bin")); + } + if let Some(home) = home { + dirs.push(home.join(".npm-global").join("bin")); + } + dirs.push(PathBuf::from("/usr/local/bin")); + if let Some(home) = home { + dirs.push(home.join(".bun").join("bin")); + } + dirs +} + +/// The first executable `failproofai` in `PATH`, then in `extra`. +fn find_cli(path_var: Option<&std::ffi::OsStr>, extra: &[PathBuf]) -> Option { + use std::os::unix::fs::PermissionsExt; + let on_path = path_var.map(|p| std::env::split_paths(p).collect::>()); + on_path + .unwrap_or_default() + .into_iter() + .chain(extra.iter().cloned()) + .filter(|dir| dir.is_absolute()) + .map(|dir| dir.join("failproofai")) + .find(|candidate| { + std::fs::metadata(candidate) + .is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) + }) +} + +/// `path` as one `sh` word. +fn shell_quote(path: &Path) -> String { + format!("'{}'", path.display().to_string().replace('\'', "'\\''")) +} + fn run_sync_once() { - // The CLI the service unit names, the same way the audit lane runs it. - let Some(cli) = crate::audit_lane::cli_command() else { + let Some(cli) = sync_cli_command() else { tracing::warn!( - "this service unit carries no FAILPROOFAI_CLI_CMD, so Self Reports agent \ - configs were not synced — run `failproofai self-report sync`" + "no FAILPROOFAI_CLI_CMD and no `failproofai` on PATH or in the npm global bin, \ + so Self Reports agent configs were not synced — run `failproofai self-report sync`" ); return; }; @@ -625,6 +682,47 @@ mod tests { let _ = std::fs::remove_dir_all(&home); } + #[test] + fn the_cli_is_found_on_path_then_in_the_global_bins() { + use std::os::unix::fs::PermissionsExt; + let root = temp_path("find-cli").parent().unwrap().to_path_buf(); + let (a, b, global) = (root.join("a"), root.join("b"), root.join("g/bin")); + for d in [&a, &b, &global] { + std::fs::create_dir_all(d).unwrap(); + } + let make = |dir: &Path, mode: u32| { + let f = dir.join("failproofai"); + std::fs::write(&f, "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&f, std::fs::Permissions::from_mode(mode)).unwrap(); + f + }; + // Not executable in `a`: skipped. Executable in `b`: found. + make(&a, 0o644); + let in_b = make(&b, 0o755); + let path = std::env::join_paths([&a, &b]).unwrap(); + assert_eq!(find_cli(Some(path.as_os_str()), &[]), Some(in_b)); + // Nothing on PATH: the global bin. + let in_global = make(&global, 0o755); + let empty = std::env::join_paths([&a]).unwrap(); + assert_eq!( + find_cli(Some(empty.as_os_str()), std::slice::from_ref(&global)), + Some(in_global) + ); + assert_eq!(find_cli(None, std::slice::from_ref(&a)), None); + // A relative PATH entry is never used. + assert_eq!(find_cli(Some(std::ffi::OsStr::new("relative")), &[]), None); + + let dirs = global_bin_dirs(Some(root.join("g")), Some(Path::new("/home/u"))); + assert_eq!(dirs[0], global); + assert!(dirs.contains(&PathBuf::from("/home/u/.npm-global/bin"))); + assert!(dirs.contains(&PathBuf::from("/usr/local/bin"))); + assert_eq!( + shell_quote(Path::new("/x/it's/failproofai")), + "'/x/it'\\''s/failproofai'" + ); + let _ = std::fs::remove_dir_all(&root); + } + #[test] fn the_sync_child_gets_the_daemons_home() { let dir = temp_path("sync-env"); diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index d9ed4bdbd..93c320fcc 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -67,10 +67,12 @@ pub const SESSION_LOOKBACK: Duration = Duration::from_secs(6 * 3600); /// The session id a fallback report carries when no session matches. pub const UNATTRIBUTED_SESSION: &str = "unattributed"; -/// Integrations whose hooks do not see MCP calls, so the MCP server records -/// the report itself. Mirrors `SELF_REPORT_SERVER_RECORDS` in the TypeScript -/// CLI. claude, codex and cursor are recorded by their hooks and must not be -/// here, or each of their reports would arrive twice. +/// Integrations whose hooks do not see MCP calls (or not which server a call +/// is for), so the MCP server records the report itself. Mirrors +/// `SELF_REPORT_SERVER_RECORDS` in the TypeScript CLI. claude and codex are +/// recorded by their hooks and must not be here, or each of their reports +/// would arrive twice. cursor is here: the hook failproofai installs names an +/// MCP call `MCP:` with no server. pub const SERVER_RECORDS: &[&str] = &[ "openclaw", "pi", @@ -81,6 +83,7 @@ pub const SERVER_RECORDS: &[&str] = &[ "antigravity", "copilot", "opencode", + "cursor", ]; /// MCP protocol revisions this server answers in. The first is what it offers @@ -742,8 +745,36 @@ impl Report { } } -/// The newest session for `integration` (and `cwd` when known) in hook -/// activity within [`SESSION_LOOKBACK`] of `now_ms`, with the cwd its row had. +/// How closely a hook row's cwd matches the caller's: 2 the same directory, +/// 1 an ancestor or descendant of it, 0 unrelated or unknown. Trailing slashes +/// are ignored; `/` is an ancestor of every absolute path. Same as +/// `selfReportCwdAffinity` in the CLI's stdio server. +pub fn cwd_affinity(want: &str, have: Option<&str>) -> u8 { + let Some(have) = have.filter(|h| !h.is_empty()) else { + return 0; + }; + let a = want.trim_end_matches('/'); + let b = have.trim_end_matches('/'); + if a == b { + return 2; + } + if a.is_empty() || b.is_empty() { + return 1; + } + let under = |child: &str, parent: &str| { + child + .strip_prefix(parent) + .is_some_and(|rest| rest.starts_with('/')) + }; + u8::from(under(b, a) || under(a, b)) +} + +/// The session a report from `integration` belongs to, in hook activity +/// within [`SESSION_LOOKBACK`] of `now_ms`, with the cwd its row had. Most +/// specific first when `cwd` is known: the newest session in exactly that +/// directory, else in one above or below it, else the newest of that +/// integration anywhere. The CLI's stdio server (`selfReportFindSessionMatch`) +/// does the same. pub fn find_session( home: &Path, integration: &str, @@ -768,7 +799,7 @@ pub fn find_session( files.extend(pages.into_iter().rev().take(2)); } let oldest = now_ms - SESSION_LOOKBACK.as_millis() as i64; - let mut best: Option<(i64, String, Option)> = None; + let mut best: Option<(u8, i64, String, Option)> = None; for file in files { let Ok(text) = read_tail(&file, 1024 * 1024) else { continue; @@ -780,17 +811,20 @@ pub fn find_session( let Some(session) = row.session_id.as_deref().filter(|s| !s.is_empty()) else { continue; }; - if row.integration.as_deref() != Some(integration) - || row.timestamp < oldest - || cwd.is_some_and(|want| row.cwd.as_deref() != Some(want)) - || best.as_ref().is_some_and(|(at, _, _)| *at >= row.timestamp) + if row.integration.as_deref() != Some(integration) || row.timestamp < oldest { + continue; + } + let rank = cwd.map_or(0, |want| cwd_affinity(want, row.cwd.as_deref())); + if best + .as_ref() + .is_some_and(|(r, at, _, _)| (*r, *at) >= (rank, row.timestamp)) { continue; } - best = Some((row.timestamp, session.to_string(), row.cwd.clone())); + best = Some((rank, row.timestamp, session.to_string(), row.cwd.clone())); } } - best.map(|(_, session, cwd)| (session, cwd)) + best.map(|(_, _, session, cwd)| (session, cwd)) } /// The last `max` bytes of a file, from the first whole line in them. @@ -1191,6 +1225,17 @@ mod tests { find_session(&home, "openclaw", Some("/w/b"), now).map(|s| s.0), Some("s-older".to_string()) ); + // A descendant beats a newer unrelated row; no relation at all falls + // back to the newest session anywhere. + assert_eq!( + find_session(&home, "openclaw", Some("/w/b/sub"), now), + Some(("s-older".to_string(), Some("/w/b".to_string()))) + ); + assert_eq!( + find_session(&home, "openclaw", Some("/elsewhere"), now), + Some(("s-page".to_string(), Some("/w/a".to_string()))) + ); + assert_eq!(find_session(&home, "goose", Some("/w/a"), now), None); assert_eq!(find_session(&home, "goose", None, now), None); assert_eq!( find_session(&home, "openclaw", None, now + 8 * 3600 * 1000), @@ -1230,6 +1275,41 @@ mod tests { let _ = fs::remove_dir_all(home); } + #[test] + fn cwd_affinity_ranks_exact_then_related() { + assert_eq!(cwd_affinity("/a/b", Some("/a/b/")), 2); + assert_eq!(cwd_affinity("/a/b", Some("/a")), 1); + assert_eq!(cwd_affinity("/a", Some("/a/b/c")), 1); + assert_eq!(cwd_affinity("/a/b", Some("/a/bc")), 0); + assert_eq!(cwd_affinity("/root", Some("/")), 1); + assert_eq!(cwd_affinity("/a", None), 0); + assert_eq!(cwd_affinity("/a", Some("")), 0); + } + + #[test] + fn a_fallback_report_takes_the_matched_rows_agent() { + let home = temp_home("row-agent"); + let dir = home.join("hook-activity"); + fs::create_dir_all(&dir).unwrap(); + let now = 1_800_000_000_000_i64; + fs::write( + dir.join("current.jsonl"), + json!({"timestamp": now - 1000, "eventType": "PreToolUse", "integration": "hermes", + "sessionId": "local-1", "cwd": "/root/.hermes/hermes-agent", "decision": "allow"}) + .to_string() + + "\n", + ) + .unwrap(); + let report = Report { + category: "looping".into(), + detail: "d".into(), + }; + let event = fallback_event(&home, "hermes", Some("/root"), &report, now); + assert_eq!(event["session_id"], "local-1"); + assert_eq!(event["agent_id"], "hermes-hermes-agent"); + let _ = fs::remove_dir_all(home); + } + #[test] fn event_files_use_the_sdk_writer_format() { use std::os::unix::fs::PermissionsExt; @@ -1341,7 +1421,7 @@ mod tests { fn golden_server_records() { let got: Vec = SERVER_RECORDS.iter().map(|s| s.to_string()).collect(); assert_eq!(got, golden_lines("server-records.golden.txt")); - for hooked in ["claude", "codex", "cursor"] { + for hooked in ["claude", "codex"] { assert!(!SERVER_RECORDS.contains(&hooked), "{hooked}"); } } diff --git a/docs/reference/custom-agents-typescript.mdx b/docs/reference/custom-agents-typescript.mdx index c8ecec672..247ea8c19 100644 --- a/docs/reference/custom-agents-typescript.mdx +++ b/docs/reference/custom-agents-typescript.mdx @@ -411,7 +411,7 @@ createReactAgent({ llm, tools: [selfReportTool(), ...to `@failproofai/sdk/mastra` and `@failproofai/sdk/llamaindex` export the same `selfReportTool()`. With a provider SDK directly: ```ts -const tools = [failproofai.openaiTool(), ...yours]; // or failproofai.anthropicTool() +const tools = [failproofai.openaiTool(), ...yours]; // or openaiResponsesTool(), anthropicTool() const answer = failproofai.handleToolCall(call.name, call.arguments, { toolCallId: call.id }); if (answer !== null) toolResults.push({ id: call.id, content: answer }); // "Recorded." ``` diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index c19dcf61a..119912e4e 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -55,15 +55,19 @@ failproofai registers one MCP server, named `failproofai`, in each agent's user- The transport is chosen when the entries are written, from a live check: the daemon must answer on its socket and its MCP endpoint must answer. When the daemon starts, it re-runs `failproofai self-report sync`, so agents move to HTTP. If the daemon stops, `failproofai self-report status` finds agents pointing at an endpoint that does not answer and moves them back to stdio. A running agent keeps the server it loaded at startup. -Both transports send the model short server instructions in the MCP handshake: when to report, the category names, and your guidance. Some agents, Claude Code among them, load MCP tools only on demand. They add a server's instructions to the system prompt, though, so the model knows the tool exists. +Both transports send the model short server instructions in the MCP handshake: when to report, the category names, and your guidance. Some agents, Claude Code among them, load MCP tools only on demand. They add a server's instructions to the system prompt, though, so the model knows the tool exists. Copilot CLI passes a server's instructions to the model only for servers on its allowlist (or with `--allow-all-mcp-server-instructions`), so on Copilot the model may see only the tool's own description. -Where an agent's hooks see MCP tool calls, the hook records the report. Where they do not, failproofai's MCP server records it and attributes it to that agent's newest session in the same working directory. +Pi shows the model only a server's name by default. failproofai's Pi entry sets `"exposure": "direct"`, so `report` and its description reach the model like a built-in tool. Hermes and OpenClaw defer MCP tools behind their tool search (`tools.tool_search` / `tools.toolSearch`). Neither has a per-server setting to load one server directly, so failproofai leaves that setting alone, and the model sees `report` in the deferred tool listing. + +Where an agent's hooks see MCP tool calls and the server they belong to, the hook records the report. Where they do not, failproofai's MCP server records it. It attributes the report to that agent's newest session seen by the hooks in the last 6 hours: in the server's working directory if there is one, else in a directory above or below it, else anywhere on the machine. The agent the report is filed under comes from that session's own hook events. + +Over HTTP, the server does not know the agent's working directory: the MCP entry is per user, not per project, so its URL carries only `?agent=`. So the report goes to that agent's newest session on the machine. If two sessions of one such agent run at the same time, in different projects, a report can land on the other session. Over stdio, the working directory narrows the match first. | Agent | Where the server is registered | Recorded by | | --- | --- | --- | | Claude Code | `~/.claude.json` | Hook | | Codex | `~/.codex/config.toml` | Hook | -| Cursor | `~/.cursor/mcp.json` | Hook, through Cursor's MCP hook (`beforeMCPExecution`). failproofai does not install that hook yet, so reports from Cursor are not recorded yet | +| Cursor | `~/.cursor/mcp.json` | MCP server. Cursor's tool hook names the call `MCP:report`, without the server, so it cannot tell our `report` from another server's | | Copilot CLI | `~/.copilot/mcp-config.json` | MCP server | | OpenCode | `~/.config/opencode/opencode.json` | MCP server | | Pi | `~/.pi/agent/mcp.json` | MCP server | @@ -74,12 +78,26 @@ Where an agent's hooks see MCP tool calls, the hook records the report. Where th | Antigravity | `~/.gemini/config/mcp_config.json` | MCP server | | Goose | `~/.config/goose/config.yaml` | MCP server | +If `cursor-agent mcp list` shows `failproofai` as "not loaded (needs approval)", run `cursor-agent mcp enable failproofai`. cursor-agent asks for approval of servers in a project's `.cursor/mcp.json`, so this happens, for example, when it runs with your home directory as the project. The approval is per project and per entry, so failproofai does not write it for you. The sync and `status` output say so for Cursor. + +On Antigravity, an MCP call can come through its `call_mcp_tool` wrapper. The hook lets that call through ahead of the policies only when the wrapper names server `failproofai` and tool `report`. A wrapped call to any other server goes through the policies as usual. + `failproofai self-report status` shows whether the daemon's endpoint answers (`not running (agents use stdio)` when no daemon is set up here) and, per agent, whether the server is registered, over which transport, and whether that endpoint answers (HTTP) or the command can run (stdio). If an MCP server named `failproofai` that failproofai did not write is already there, such as the [Cloud MCP gateway](/reference/mcp) added under that name, it is left alone and reported as a conflict. ## Containers In a container, run `failproofaid` in the foreground as the container's main process, with the agent started beside it. Reports, like every other hook event, reach Failproof AI Cloud only through the daemon: without it, the agent still gets the tool over stdio, but reports stay on disk in the container. +A daemon you start by hand has no service unit, so it has none of the commands the unit would give it: + +- **The startup sync** runs the CLI named by `FAILPROOFAI_CLI_CMD`. Without it, the daemon looks for `failproofai` on `PATH`, then in npm's global bin (`$NPM_CONFIG_PREFIX/bin`, `~/.npm-global/bin`, `/usr/local/bin`) and `~/.bun/bin`. After an `npm install -g failproofai`, agents therefore move to HTTP when the daemon starts. If the CLI is somewhere else, set `FAILPROOFAI_CLI_CMD` to the command that runs it, or run `failproofai self-report sync` once the daemon is up. +- **Hermes and OpenClaw** need the daemon's policy worker. Without `FAILPROOFAI_WORKER_CMD`, the daemon looks for `dist/worker.mjs` relative to its working directory, and `policies --install --cli hermes` (or `openclaw`) refuses. Set it to the worker in the installed package: + + ```bash + export FAILPROOFAI_WORKER_CMD="node $(npm root -g)/failproofai/dist/worker.mjs" + failproofaid & + ``` + ## Your own agents The Python and TypeScript SDKs offer the same tool, named `failproofai_report`, as ready-made tools for LangChain, LangGraph, CrewAI, LlamaIndex, Pydantic AI, the Vercel AI SDK and Mastra, and as raw OpenAI and Anthropic tool definitions. See [Python custom agents](/start/integrations/custom-agents#self-reports) and [TypeScript custom agents](/reference/custom-agents-typescript#self-reports). SDK reports carry `source: "sdk"`; reports from coding agents carry `source: "mcp"`. diff --git a/sdk/python/failproofai_sdk/_events.py b/sdk/python/failproofai_sdk/_events.py index 77606e12e..4ef59d90e 100644 --- a/sdk/python/failproofai_sdk/_events.py +++ b/sdk/python/failproofai_sdk/_events.py @@ -349,14 +349,20 @@ def _track_open_tool(self, tool_call_id: str, entry: "tuple[str, str, str]") -> self._open_tools.pop(tool_call_id, None) # re-insert at the end: newest last self._open_tools[tool_call_id] = entry - def _report_identity(self, tool_call_id: "str | None", agent_id: "str | None") -> "tuple[str, str]": - """Where a `self_report` with no explicit `session_id` belongs. + def _report_identity( + self, tool_call_id: "str | None", agent_id: "str | None" + ) -> "tuple[str, str, str | None]": + """Where a `self_report` with no explicit `session_id` belongs, and its call id. Most specific first, within the ambient session when one is bound: the open `tool_use` with this `tool_call_id`; then the newest open `tool_use` of the report tool itself; then the enclosing scope; then `"unattributed"` with one warning. Never raises: a report is evidence, and losing it to a missing scope is the worse outcome. + + The third item is the `tool_call_id` to record: the caller's, else the + matched `tool_use`'s own id, so a tool that cannot see the model's call + id (LlamaIndex, CrewAI) still joins the call the adapter recorded. """ global _warned_unattributed from failproofai_sdk._self_report import is_self_report_tool @@ -372,15 +378,20 @@ def _report_identity(self, tool_call_id: "str | None", agent_id: "str | None") - ] match = None if tool_call_id is not None: - match = next((e for c, e in candidates if c == tool_call_id), None) + match = next(((c, e) for c, e in candidates if c == tool_call_id), None) if match is None: - match = next((e for _, e in reversed(candidates) if is_self_report_tool(e[2])), None) + match = next(((c, e) for c, e in reversed(candidates) if is_self_report_tool(e[2])), None) if match is not None: - return match[0], agent_id if agent_id is not None else match[1] + call_id, entry = match + return ( + entry[0], + agent_id if agent_id is not None else entry[1], + tool_call_id if tool_call_id is not None else call_id, + ) if agent_id is None: agent_id = _context.agent_id() if ambient is not None: - return ambient, agent_id + return ambient, agent_id, tool_call_id if not _warned_unattributed: _warned_unattributed = True logger.warning( @@ -389,7 +400,20 @@ def _report_identity(self, tool_call_id: "str | None", agent_id: "str | None") - "`failproofai_sdk.session()`.", UNATTRIBUTED_SESSION, ) - return UNATTRIBUTED_SESSION, agent_id + return UNATTRIBUTED_SESSION, agent_id, tool_call_id + + def _open_report_call_id(self, session_id: str) -> "str | None": + """The id of the newest open report-tool `tool_use` in this session, or None.""" + from failproofai_sdk._self_report import is_self_report_tool + + try: + open_tools = list(self._open_tools.items()) + except RuntimeError: # resized under us by another thread + return None + return next( + (c for c, e in reversed(open_tools) if e[0] == session_id and is_self_report_tool(e[2])), + None, + ) def _validate_fields(self, fields: dict) -> None: bad = _RESERVED & fields.keys() @@ -869,7 +893,10 @@ def self_report( report-tool call) within the enclosing session; the enclosing scope; otherwise `"unattributed"` with one warning. A missing session never raises here, unlike the other event methods — the TypeError/ValueError - checks on the arguments themselves still apply. + checks on the arguments themselves still apply. With no `tool_call_id` + given, the report takes the id of the open report-tool `tool_use` it + was matched to (or, with an explicit `session_id`, the newest one open + in that session). """ if "source" in fields: raise ValueError("source is set by the SDK (always \"sdk\") and cannot be passed by the caller") @@ -885,7 +912,11 @@ def self_report( if tool_call_id is not None: _validate_promoted_string("tool_call_id", tool_call_id) if session_id is None: - session_id, agent_id = self._report_identity(tool_call_id, agent_id) + session_id, agent_id, tool_call_id = self._report_identity(tool_call_id, agent_id) + elif tool_call_id is None: + # A framework tool that resolved its session from the adapter's run + # (LlamaIndex, CrewAI) but cannot see the model's call id. + tool_call_id = self._open_report_call_id(session_id) session_id, agent_id = _resolve_identity(session_id, agent_id) ts = self._now() self._writer.submit( diff --git a/sdk/python/failproofai_sdk/_self_report.py b/sdk/python/failproofai_sdk/_self_report.py index 77ca3f2b1..954680491 100644 --- a/sdk/python/failproofai_sdk/_self_report.py +++ b/sdk/python/failproofai_sdk/_self_report.py @@ -92,7 +92,8 @@ #: `failproofai` as each agent prefixes it: Claude Code, Codex, Pi, Factory and #: Devin `mcp__failproofai__report`, Factory's matcher form #: `failproofai___report`, Hermes and Antigravity `mcp_failproofai_report`, -#: OpenClaw and Goose `failproofai__report`, plus other server-qualified forms. +#: OpenClaw and Goose `failproofai__report`, Copilot CLI (likely, unverified) +#: `failproofai-report` / `failproofai/report`, plus other server-qualified forms. #: The CLI and the TypeScript SDK test the same list against the repository's #: test-fixtures/self-report/tool-names.golden.txt. TOOL_SPELLINGS: tuple[str, ...] = ( @@ -107,6 +108,7 @@ "mcp__failproofai_report", "mcp:failproofai:report", "mcp:failproofai/report", + "failproofai-report", ) _TOOL_NAMES = frozenset(TOOL_SPELLINGS) diff --git a/sdk/python/failproofai_sdk/integrations/crewai.py b/sdk/python/failproofai_sdk/integrations/crewai.py index ada7cda44..a08dbad92 100644 --- a/sdk/python/failproofai_sdk/integrations/crewai.py +++ b/sdk/python/failproofai_sdk/integrations/crewai.py @@ -1704,6 +1704,29 @@ def _report_identity(): return tracker.identity(None, key, warn=False) +def _report_call_id() -> "str | None": + """The id of the CrewAI tool usage running this tool, or None. + + CrewAI pushes a `tool_usage_started` scope (its event's `event_id`) + synchronously when it emits the event, before the tool runs; that id is + the `tool_call_id` this adapter records the `tool_use` under. It is read + here because the adapter's own handler runs on CrewAI's event bus and may + record that `tool_use` after the report. + """ + if adapter._tracker is None: + # Not instrumented: no `tool_use` carries this id, so it joins nothing. + return None + from crewai.events import event_context + + stack = getattr(event_context, "_event_id_stack", None) + if stack is None: + return None + for entry in reversed(stack.get()): + if isinstance(entry, tuple) and len(entry) == 2 and entry[1] == "tool_usage_started": + return entry[0] if isinstance(entry[0], str) and entry[0] else None + return None + + def self_report_tool( *, session_id: "str | None" = None, @@ -1731,13 +1754,15 @@ def self_report_tool( def _run(self, category, detail) -> str: identity = None + tool_call_id = None try: identity = _report_identity() + tool_call_id = _report_call_id() except Exception: # noqa: BLE001 - identity is best-effort; the report is not logger.debug("failproofai_sdk: could not resolve the report's crew run", exc_info=True) return _self_report.record_framework_call( category, detail, identity=identity, session_id=session_id, - agent_id=agent_id, fields=extra, + agent_id=agent_id, tool_call_id=tool_call_id, fields=extra, ) _run.__annotations__ = _self_report.framework_signature(names) diff --git a/sdk/python/failproofai_sdk/integrations/langchain.py b/sdk/python/failproofai_sdk/integrations/langchain.py index 68f219bda..ba3e74a94 100644 --- a/sdk/python/failproofai_sdk/integrations/langchain.py +++ b/sdk/python/failproofai_sdk/integrations/langchain.py @@ -2173,6 +2173,43 @@ def _report_identity(callbacks: Any) -> "tuple[Any, str | None]": return _STATE.tracker.identity(None, key, warn=False), tool_call_id +#: The model's tool-call id of the report call running in this context. LangChain +#: hands `BaseTool.run`/`arun` the id of a `ToolCall` input, but a tool with a +#: JSON-schema `args_schema` cannot have it injected into its function, so the +#: report tool's own `run`/`arun` put it here for the function to read. +_REPORT_TOOL_CALL_ID: "contextvars.ContextVar[str | None]" = contextvars.ContextVar( + "failproofai_langchain_report_tool_call_id", default=None +) + +_REPORT_TOOL_CLASS: Any = None + + +def _report_tool_class() -> Any: + """`StructuredTool` with `run`/`arun` that keep the call's `tool_call_id`.""" + global _REPORT_TOOL_CLASS + if _REPORT_TOOL_CLASS is not None: + return _REPORT_TOOL_CLASS + from langchain_core.tools import StructuredTool + + class _SelfReportTool(StructuredTool): + def run(self, tool_input: Any, *args: Any, tool_call_id: "str | None" = None, **kwargs: Any) -> Any: + token = _REPORT_TOOL_CALL_ID.set(tool_call_id) + try: + return super().run(tool_input, *args, tool_call_id=tool_call_id, **kwargs) + finally: + _REPORT_TOOL_CALL_ID.reset(token) + + async def arun(self, tool_input: Any, *args: Any, tool_call_id: "str | None" = None, **kwargs: Any) -> Any: + token = _REPORT_TOOL_CALL_ID.set(tool_call_id) + try: + return await super().arun(tool_input, *args, tool_call_id=tool_call_id, **kwargs) + finally: + _REPORT_TOOL_CALL_ID.reset(token) + + _REPORT_TOOL_CLASS = _SelfReportTool + return _REPORT_TOOL_CLASS + + def self_report_tool( *, session_id: str | None = None, @@ -2189,10 +2226,11 @@ def self_report_tool( description come from `self-report.json` (or the defaults), read when the tool is built. Identity: the factory's `session_id`/`agent_id`, else the run this adapter is recording (when instrumented), else the ambient scope, else "unattributed". + `tool_call_id` is the model's call id: from the instrumented run, else the + `ToolCall` LangChain invoked the tool with (as `ToolNode` and + `create_agent` do), with or without instrumentation. Always returns `"Recorded."`. """ - from langchain_core.tools import StructuredTool - from failproofai_sdk import _self_report spec = _self_report.self_report_spec(categories=categories, guidance=guidance) @@ -2204,6 +2242,8 @@ def _record(category: Any = "", detail: Any = "", callbacks: Any = None) -> str: identity, tool_call_id = _report_identity(callbacks) except Exception: # noqa: BLE001 - identity is best-effort; the report is not logger.debug("failproofai_sdk: could not resolve the report's run", exc_info=True) + if tool_call_id is None: + tool_call_id = _REPORT_TOOL_CALL_ID.get() return _self_report.record_framework_call( category, detail, identity=identity, session_id=session_id, agent_id=agent_id, tool_call_id=tool_call_id, fields=extra, @@ -2215,7 +2255,7 @@ def report(category: str = "", detail: str = "", callbacks: Any = None) -> str: async def areport(category: str = "", detail: str = "", callbacks: Any = None) -> str: return _record(category, detail, callbacks) - return StructuredTool.from_function( + return _report_tool_class().from_function( func=report, coroutine=areport, name=spec["name"], diff --git a/sdk/python/failproofai_sdk/integrations/pydantic_ai.py b/sdk/python/failproofai_sdk/integrations/pydantic_ai.py index 7120dd364..625f2580a 100644 --- a/sdk/python/failproofai_sdk/integrations/pydantic_ai.py +++ b/sdk/python/failproofai_sdk/integrations/pydantic_ai.py @@ -62,7 +62,9 @@ built before `uninstrument()` stops recording rather than recording into a half-dismantled adapter. By the same token, agents constructed *before* `instrument()` are not instrumented; construct them after, or pass -`capabilities=[FailproofAI()]` yourself. +`capabilities=[FailproofAI()]` yourself. A capability you pass yourself is +yours: it records whether or not `instrument()` ran, and `uninstrument()` does +not stop it. What is deliberately not captured --------------------------------- @@ -132,7 +134,9 @@ # Flipped by install()/uninstall(). Agents built while instrumented keep the # capability instance, so this flag — not the patch — is what actually stops the -# recording. Read on every hook, written only under the registry lock. +# recording of the capability install() injected. A `FailproofAI()` the user +# passed in `capabilities=` records regardless. Read on every hook, written +# only under the registry lock. _enabled = False _capability: "FailproofAI | None" = None _patcher = _core.Patcher() @@ -613,6 +617,13 @@ def __init__( self.session_id = session_id self.id = id self.self_report = self_report + # False for one you construct yourself: it records whether or not + # `instrument()` ran. `install()` sets True on the one it injects, which + # then records only while instrumented (so `uninstrument()` stops it). + self._installed = False + + def _recording(self) -> bool: + return _enabled or not getattr(self, "_installed", False) def get_toolset(self): """The FailproofAI report tool, when `self_report=True` was asked for. @@ -638,7 +649,7 @@ def get_ordering(self) -> CapabilityOrdering: # -- run -------------------------------------------------------------- async def wrap_run(self, ctx, *, handler): - if not _enabled: + if not self._recording(): return await handler() state = self._begin_run(ctx) try: @@ -745,7 +756,7 @@ def _end_run(self, state: "_RunState | None", result: Any, exc: "BaseException | # -- model ------------------------------------------------------------ async def wrap_model_request(self, ctx, *, request_context, handler): - if not _enabled: + if not self._recording(): return await handler(request_context) state = self._begin_model(ctx, request_context) try: @@ -849,7 +860,7 @@ def _end_model(self, ctx, state: "_SpanState | None", response: Any, exc: "BaseE # -- tools ------------------------------------------------------------ async def wrap_tool_execute(self, ctx, *, call, tool_def, args, handler): - if not _enabled: + if not self._recording(): return await handler(args) state = self._begin_tool(ctx, call, tool_def, args) try: @@ -968,6 +979,7 @@ def install(self, **options: Any) -> None: session_id=options.get("session_id"), self_report=bool(options.get("self_report", False)), ) + _capability._installed = True _patcher.patch(Agent, "__init__", _wrap_init(Agent.__init__)) _enabled = True @@ -1015,8 +1027,10 @@ def self_report_tool( The JSON schema is exactly `self_report_spec()["input_schema"]` (built from `self-report.json`, or the defaults). The call carries the model's `tool_call_id`. Identity: the factory's `session_id`/`agent_id`, else the - run `FailproofAI` is recording (it binds the run's scope), else the ambient - scope, else "unattributed". Always returns `"Recorded."`. + run a `FailproofAI` capability on the agent is recording (it binds the run's + scope; `FailproofAI(self_report=True)` alone does, with or without + `instrument()`), else the ambient scope, else "unattributed". Always + returns `"Recorded."`. """ from pydantic_ai import Tool diff --git a/sdk/python/tests/integrations/test_crewai.py b/sdk/python/tests/integrations/test_crewai.py index d1006c321..d7bd1cfa1 100644 --- a/sdk/python/tests/integrations/test_crewai.py +++ b/sdk/python/tests/integrations/test_crewai.py @@ -1337,6 +1337,9 @@ def test_records_on_the_instrumented_crew_agent(self, instrumented, emitted): "missing_context", "The input file is not provided.", "sdk", ) assert report["framework"] == "crewai" + # CrewAI's tool sees no call id: the report takes the open call's. + (use,) = [e for e in events if e["type"] == "tool_use" and e["tool_name"] == "failproofai_report"] + assert use["tool_call_id"] and report["tool_call_id"] == use["tool_call_id"] def test_ambient_and_explicit_identity(self, emitted): from failproofai_sdk.integrations.crewai import self_report_tool diff --git a/sdk/python/tests/integrations/test_langchain.py b/sdk/python/tests/integrations/test_langchain.py index d9271c436..6c4af3791 100644 --- a/sdk/python/tests/integrations/test_langchain.py +++ b/sdk/python/tests/integrations/test_langchain.py @@ -2413,6 +2413,33 @@ def test_self_report_tool_ambient_scope_without_instrumentation(tmp_path): assert (report["session_id"], report["agent_id"]) == ("lc-ambient", "main") +def test_self_report_tool_takes_the_tool_call_id_without_instrumentation(tmp_path): + # ToolNode invokes the tool with the model's ToolCall; the id comes from it. + with failproofai_sdk.session("lc-plain"): + _report_graph(adapter.self_report_tool()).invoke(empty_state()) + (report,) = only(read_events(tmp_path), "self_report") + assert (report["session_id"], report["tool_call_id"]) == ("lc-plain", "call_report") + + +def test_self_report_tool_takes_the_tool_call_id_on_the_async_path_without_instrumentation(tmp_path): + import asyncio + + with failproofai_sdk.session("lc-plain-async"): + asyncio.run(_report_graph(adapter.self_report_tool()).ainvoke(empty_state())) + (report,) = only(read_events(tmp_path), "self_report") + assert report["tool_call_id"] == "call_report" + + +def test_self_report_tool_invoked_with_a_tool_call_dict_records_its_id(tmp_path): + tool_ = adapter.self_report_tool(session_id="lc-direct") + tool_.invoke({"name": "failproofai_report", "args": {"category": "looping", "detail": "d"}, + "id": "call_direct", "type": "tool_call"}) + tool_.invoke({"category": "looping", "detail": "plain args"}) + first, second = only(read_events(tmp_path), "self_report") + assert first["tool_call_id"] == "call_direct" + assert "tool_call_id" not in second + + def test_self_report_tool_explicit_identity_wins(tmp_path, instrumented): _report_graph(adapter.self_report_tool(session_id="lc-s", agent_id="lc-a")).invoke(empty_state()) (report,) = only(read_events(tmp_path), "self_report") diff --git a/sdk/python/tests/integrations/test_llama_index.py b/sdk/python/tests/integrations/test_llama_index.py index dcfc19e09..9e95aecfa 100644 --- a/sdk/python/tests/integrations/test_llama_index.py +++ b/sdk/python/tests/integrations/test_llama_index.py @@ -1605,6 +1605,9 @@ def test_self_report_tool_records_on_the_instrumented_agent(instrumented, tmp_pa assert report["framework"] == "llama_index" results = [e for e in only(events, "tool_result") if e["tool_name"] == "failproofai_report"] assert results and "Recorded." in str(results[0].get("output")) + # LlamaIndex hands the tool no call id: the report takes the open call's. + (use,) = [e for e in only(events, "tool_use") if e["tool_name"] == "failproofai_report"] + assert use["tool_call_id"] and report["tool_call_id"] == use["tool_call_id"] def test_self_report_tool_uses_the_ambient_scope_when_not_instrumented(tmp_path): diff --git a/sdk/python/tests/integrations/test_pydantic_ai.py b/sdk/python/tests/integrations/test_pydantic_ai.py index 3491bda4f..ff66a628e 100644 --- a/sdk/python/tests/integrations/test_pydantic_ai.py +++ b/sdk/python/tests/integrations/test_pydantic_ai.py @@ -1171,6 +1171,22 @@ def test_the_capability_adds_the_tool_only_when_asked(): assert "failproofai_report" in opted +def test_a_hand_added_self_report_capability_records_the_run_without_instrument(emitted): + agent = Agent( + one_shot_tool_model("failproofai_report", _REPORT_ARGS, tool_call_id="call-cap"), + name="cap_agent", + capabilities=[FailproofAI(self_report=True)], + ) + agent.run_sync("go") + rows = emitted() + assert types_of(rows)[0] == "agent_start" and types_of(rows)[-1] == "agent_end" + (start,) = of_type(rows, "agent_start") + (report,) = of_type(rows, "self_report") + assert report["session_id"] == start["session_id"] != "unattributed" + assert report["agent_id"] == "cap_agent" + assert report["tool_call_id"] == "call-cap" + + def test_instrument_self_report_option_adds_the_tool(emitted): _core.set_strict(False) _compat.set_strict_integrations(False) diff --git a/sdk/python/tests/test_self_report.py b/sdk/python/tests/test_self_report.py index 51bf91b2b..a9b89dcf4 100644 --- a/sdk/python/tests/test_self_report.py +++ b/sdk/python/tests/test_self_report.py @@ -129,6 +129,18 @@ def test_the_open_tool_use_resolves_a_report_with_nothing_bound(recorded): fp.self_report("looping", "by tool name") # no id: newest open report-tool call reports = [e for e in recorded if e["type"] == "self_report"] assert [(r["session_id"], r["agent_id"]) for r in reports] == [("s-open", "a-open")] * 2 + # A report with no id takes the matched call's id. + assert [r["tool_call_id"] for r in reports] == ["call_8", "call_8"] + + +def test_the_callers_tool_call_id_beats_the_matched_calls(recorded): + _runtime.event.tool_use(session_id="s-own", agent_id="a", tool_name="failproofai_report", tool_call_id="adapter-id") + fp.self_report("looping", "d", tool_call_id="model-id") + with fp.session("s-none"): + fp.self_report("looping", "no open call") + first, second = [e for e in recorded if e["type"] == "self_report"] + assert (first["session_id"], first["tool_call_id"]) == ("s-own", "model-id") + assert second["session_id"] == "s-none" and "tool_call_id" not in second def test_a_closed_or_foreign_session_tool_use_is_not_used(recorded): @@ -337,6 +349,7 @@ def test_anthropic_tool_shape(home): "failproofai__report", "failproofai.report", "failproofai/report", + "failproofai-report", ], ) def test_is_self_report_tool_accepts_every_spelling(name): @@ -344,7 +357,7 @@ def test_is_self_report_tool_accepts_every_spelling(name): @pytest.mark.parametrize( - "name", ["report", "MCP:report", "bash", "mcp__other__report", "failproofai_report_x", "failproofai-report", "", None, 3] + "name", ["report", "MCP:report", "bash", "mcp__other__report", "failproofai_report_x", "other-report", "failproofai-reports", "", None, 3] ) def test_is_self_report_tool_rejects_others(name): assert not fp.is_self_report_tool(name) diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index 58f845831..5ddb3993e 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -470,7 +470,7 @@ agent({ llm, tools: [selfReportTool(), ...tools] }); With a provider SDK directly: ```ts -const tools = [failproofai.openaiTool(), ...yours]; // or failproofai.anthropicTool() +const tools = [failproofai.openaiTool(), ...yours]; // or openaiResponsesTool(), anthropicTool() // for each tool call the model makes: const answer = failproofai.handleToolCall(call.name, call.arguments, { toolCallId: call.id }); if (answer !== null) toolResults.push({ id: call.id, content: answer }); // "Recorded." diff --git a/sdk/typescript/src/edge/index.ts b/sdk/typescript/src/edge/index.ts index bc5639f57..5061766e1 100644 --- a/sdk/typescript/src/edge/index.ts +++ b/sdk/typescript/src/edge/index.ts @@ -42,8 +42,10 @@ import { defaultCategories, isSelfReportTool, toAnthropicTool, + toOpenAIResponsesTool, toOpenAITool, type AnthropicTool, + type OpenAIResponsesTool, type OpenAITool, type SelfReportSpec, } from "../self-report-spec.js"; @@ -294,6 +296,10 @@ export function openaiTool(): OpenAITool { return toOpenAITool(selfReportSpec()); } +export function openaiResponsesTool(): OpenAIResponsesTool { + return toOpenAIResponsesTool(selfReportSpec()); +} + export function anthropicTool(): AnthropicTool { return toAnthropicTool(selfReportSpec()); } diff --git a/sdk/typescript/src/events.ts b/sdk/typescript/src/events.ts index 06ea00312..becb6d96a 100644 --- a/sdk/typescript/src/events.ts +++ b/sdk/typescript/src/events.ts @@ -837,7 +837,9 @@ export class EventNamespace { * an adapter or a `toolCall()` scope recorded — so a report made inside a * framework's tool loop lands on the agent whose loop called it; the * enclosing scope; and last `"unattributed"`, with one warning. Unlike every - * other event method a missing session never throws. + * other event method a missing session never throws. With no `toolCallId` + * given, the report takes the id of the open report-tool `tool_use` it was + * matched to (with an explicit `sessionId`, the newest one open there). */ selfReport(category: string, detail?: string | null, options: SelfReportOptions = {}): void { const { sessionId, agentId, toolCallId, ...fields } = options; @@ -849,7 +851,7 @@ export class EventNamespace { } this.validateFields(fields); const callId = typeof toolCallId === "string" && toolCallId !== "" ? toolCallId : undefined; - const [sid, aid] = this.reportIdentity(sessionId, agentId, callId); + const [sid, aid, matchedCallId] = this.reportIdentity(sessionId, agentId, callId); this.writer.submit( selfReportEvent({ timestamp: this.fmtTs(this.now()), @@ -858,7 +860,7 @@ export class EventNamespace { category: typeof category === "string" ? category : category === undefined || category === null ? "" : String(category), detail: clipDetail(typeof detail === "string" ? detail : detail === undefined || detail === null ? "" : String(detail)), source: "sdk", - toolCallId: callId, + toolCallId: callId ?? matchedCallId, extraFields: fields, }), ); @@ -870,16 +872,23 @@ export class EventNamespace { sessionId: string | null | undefined, agentId: string | null | undefined, toolCallId: string | undefined, - ): [string, string] { - if (sessionId !== undefined && sessionId !== null) return resolveIdentity(sessionId, agentId); + ): [string, string, string | undefined] { + if (sessionId !== undefined && sessionId !== null) { + // An explicit session (a tool that resolved it itself) still takes the + // id of the report-tool call open in that session, when it has none. + const open = toolCallId === undefined ? this.openToolFor(undefined, sessionId) : undefined; + return [...resolveIdentity(sessionId, agentId), open?.id]; + } const ambient = context.sessionId(); const leaf = this.openToolFor(toolCallId, ambient); if (leaf !== undefined) { const aid = agentId ?? leaf.agentId; validateIdentity("agentId", aid); - return [leaf.sessionId, aid]; + // The matched call's own id, so a tool that cannot see the model's call + // id (LlamaIndex) still joins the `tool_use` the adapter recorded. + return [leaf.sessionId, aid, leaf.id]; } - if (ambient !== null) return resolveIdentity(null, agentId); + if (ambient !== null) return [...resolveIdentity(null, agentId), undefined]; if (!this.warnedUnattributed) { this.warnedUnattributed = true; logger.warn( @@ -890,7 +899,7 @@ export class EventNamespace { } const aid = agentId ?? context.agentId(); validateIdentity("agentId", aid); - return [UNATTRIBUTED_SESSION, aid]; + return [UNATTRIBUTED_SESSION, aid, undefined]; } /** diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts index 8e51f60cd..49dca6eb5 100644 --- a/sdk/typescript/src/index.ts +++ b/sdk/typescript/src/index.ts @@ -11,7 +11,7 @@ * SDK, Mastra and LlamaIndex.TS to the scopes above. * * **`event.*`** — the event methods, for anything the adapters do not * cover. - * * **Self Reports** — `selfReport()` and the report tool (`openaiTool()`, + * * **Self Reports** — `selfReport()` and the report tool (`openaiTool()`, `openaiResponsesTool()`, * `anthropicTool()`, `handleToolCall()`), so an agent can say it is stuck. * * `sessionId` and `agentId` are optional on every event method: omitted, they @@ -88,6 +88,7 @@ export { anthropicTool, handleToolCall, isSelfReportTool, + openaiResponsesTool, openaiTool, selfReport, selfReportSettings, @@ -96,6 +97,7 @@ export { } from "./self-report.js"; export type { AnthropicTool, + OpenAIResponsesTool, OpenAITool, SelfReportCategory, SelfReportSettings, diff --git a/sdk/typescript/src/integrations/self-report-tools.ts b/sdk/typescript/src/integrations/self-report-tools.ts index d767236ad..00d56c444 100644 --- a/sdk/typescript/src/integrations/self-report-tools.ts +++ b/sdk/typescript/src/integrations/self-report-tools.ts @@ -131,9 +131,14 @@ export function langchainSelfReportTool(options: LangChainSelfRepor const tools = options.module ?? tryRequire("@langchain/core/tools"); const spec = selfReportSpec(); const identity = identityOf(options); - const func = (input: unknown, runManager?: { runId?: unknown }, config?: { toolCall?: { id?: unknown } }) => + // `tool()` calls `func(input, config)`, with the model's call at + // `config.toolCall`; a `DynamicStructuredTool` calls `func(input, runManager, + // config)`. Read the id from whichever argument carries it. A run id is not + // the model's call id, so it is never used. + type WithToolCall = { toolCall?: { id?: unknown } } | undefined; + const func = (input: unknown, second?: WithToolCall, third?: WithToolCall) => Promise.resolve( - recordToolCall(input, { ...identity, toolCallId: pickId(config?.toolCall?.id, runManager?.runId) }), + recordToolCall(input, { ...identity, toolCallId: pickId(second?.toolCall?.id, third?.toolCall?.id) }), ); const fields = { name: SELF_REPORT_TOOL_NAME, description: spec.description, schema: spec.inputSchema }; if (typeof tools?.tool === "function") return tools.tool(func as never, fields as never) as T; @@ -240,8 +245,9 @@ export interface LlamaIndexSelfReportToolOptions extends SelfReportToolOptions { * This breaks constructor checks". Pass `module` (your `FunctionTool`) to get * a `FunctionTool` instead. * - * LlamaIndex hands a tool no call id, so the report finds its agent by the - * open `tool_use` named `failproofai_report`, else the enclosing scope. + * LlamaIndex hands a tool no call id, so the report finds its agent, and + * takes its call id, from the open `tool_use` named `failproofai_report` + * (recorded by `instrument("llamaindex")`), else the enclosing scope. */ export function llamaindexSelfReportTool( options: LlamaIndexSelfReportToolOptions = {}, diff --git a/sdk/typescript/src/self-report-spec.ts b/sdk/typescript/src/self-report-spec.ts index 4adeea3f2..a7f124909 100644 --- a/sdk/typescript/src/self-report-spec.ts +++ b/sdk/typescript/src/self-report-spec.ts @@ -130,6 +130,18 @@ export function toOpenAITool(spec: SelfReportSpec): OpenAITool { }; } +/** The OpenAI Responses API `tools[]` entry: the flat function shape. */ +export interface OpenAIResponsesTool { + type: "function"; + name: string; + description: string; + parameters: JsonSchemaObject; +} + +export function toOpenAIResponsesTool(spec: SelfReportSpec): OpenAIResponsesTool { + return { type: "function", name: spec.name, description: spec.description, parameters: spec.inputSchema }; +} + /** The Anthropic Messages `tools[]` entry. */ export interface AnthropicTool { name: string; @@ -146,7 +158,8 @@ export function toAnthropicTool(spec: SelfReportSpec): AnthropicTool { * `failproofai_report` (the SDKs, OpenCode), `mcp__failproofai__report` * (Claude Code, Codex, Pi, Factory, Devin), `failproofai___report` (Factory's * matcher form), `mcp_failproofai_report` (Hermes, Antigravity), - * `failproofai__report` (OpenClaw, Goose), and other server-qualified forms. + * `failproofai__report` (OpenClaw, Goose), `failproofai-report` (Copilot CLI, + * likely), and other server-qualified forms. * * Mirrors `isSelfReportToolName` in the CLI's `src/hooks/self-report-names.ts`; * this package cannot import that, so both are tested against the same golden @@ -164,6 +177,7 @@ export const SELF_REPORT_TOOL_SPELLINGS: ReadonlyArray = Object.freeze([ "mcp__failproofai_report", "mcp:failproofai:report", "mcp:failproofai/report", + "failproofai-report", ]); const SPELLINGS = new Set(SELF_REPORT_TOOL_SPELLINGS); diff --git a/sdk/typescript/src/self-report.ts b/sdk/typescript/src/self-report.ts index 77907c614..4be1c0879 100644 --- a/sdk/typescript/src/self-report.ts +++ b/sdk/typescript/src/self-report.ts @@ -4,7 +4,7 @@ * Offer the tool to a model, and when the model calls it, record a * `self_report` event in the current session and answer `Recorded.`: * - * const tools = [failproofai.openaiTool()]; // or anthropicTool() + * const tools = [failproofai.openaiTool()]; // or openaiResponsesTool(), anthropicTool() * ... * const answer = failproofai.handleToolCall(call.name, call.arguments, { toolCallId: call.id }); * if (answer !== null) { ...send `answer` back as the tool result... } @@ -34,10 +34,12 @@ import { isSelfReportTool, normalizeSelfReportArgs, toAnthropicTool, + toOpenAIResponsesTool, toOpenAITool, validCategories, validGuidance, type AnthropicTool, + type OpenAIResponsesTool, type OpenAITool, type SelfReportCategory, type SelfReportSpec, @@ -51,7 +53,13 @@ export { describeSelfReport, isSelfReportTool, } from "./self-report-spec.js"; -export type { AnthropicTool, OpenAITool, SelfReportCategory, SelfReportSpec } from "./self-report-spec.js"; +export type { + AnthropicTool, + OpenAIResponsesTool, + OpenAITool, + SelfReportCategory, + SelfReportSpec, +} from "./self-report-spec.js"; export type { SelfReportOptions } from "./events.js"; /** What `self-report.json` says, with the defaults filled in. */ @@ -126,6 +134,11 @@ export function openaiTool(): OpenAITool { return toOpenAITool(selfReportSpec()); } +/** The report tool as an OpenAI Responses API `tools[]` entry (flat function shape). */ +export function openaiResponsesTool(): OpenAIResponsesTool { + return toOpenAIResponsesTool(selfReportSpec()); +} + /** The report tool as an Anthropic Messages `tools[]` entry. */ export function anthropicTool(): AnthropicTool { return toAnthropicTool(selfReportSpec()); diff --git a/sdk/typescript/test/self-report.test.ts b/sdk/typescript/test/self-report.test.ts index 7f24ffe92..aec6da1b0 100644 --- a/sdk/typescript/test/self-report.test.ts +++ b/sdk/typescript/test/self-report.test.ts @@ -186,7 +186,20 @@ describe("event.selfReport and selfReport()", () => { agent("reporter", () => failproofai.event.toolUse({ toolName: "failproofai_report", toolCallId: "own-id" })), ); failproofai.selfReport("looping", "d"); - expect((await reports())[0]).toMatchObject({ session_id: "s2", agent_id: "reporter" }); + expect((await reports())[0]).toMatchObject({ session_id: "s2", agent_id: "reporter", tool_call_id: "own-id" }); + }); + + it("keeps the caller's call id over the matched tool call's", async () => { + await session({ sessionId: "s3" }, () => + agent("reporter", () => failproofai.event.toolUse({ toolName: "failproofai_report", toolCallId: "adapter-id" })), + ); + failproofai.selfReport("looping", "d", { toolCallId: "model-id" }); + expect((await reports())[0]).toMatchObject({ session_id: "s3", tool_call_id: "model-id" }); + }); + + it("records no call id when no open tool call matches", async () => { + await session({ sessionId: "s4" }, () => failproofai.selfReport("looping", "d")); + expect((await reports())[0]!.tool_call_id).toBeUndefined(); }); it("inside a scope, only looks at that scope's open tool calls", async () => { @@ -306,6 +319,16 @@ describe("the raw tool helpers", () => { }); }); + it("shapes the OpenAI Responses API entry flat, like Python's openai_responses_tool()", () => { + expect(failproofai.openaiResponsesTool()).toEqual({ + type: "function", + name: "failproofai_report", + description: DEFAULT_DESCRIPTION, + parameters: DEFAULT_SCHEMA, + }); + expect(edge.openaiResponsesTool()).toEqual(failproofai.openaiResponsesTool()); + }); + it.each([ ["failproofai_report", true], ["mcp__failproofai__report", true], @@ -400,12 +423,23 @@ describe("the framework tools", () => { fields: unknown; }>({ module: { tool }, sessionId: "fixed", agentId: "lc" }); expect(built.fields).toEqual({ name: "failproofai_report", description: DEFAULT_DESCRIPTION, schema: DEFAULT_SCHEMA }); - expect(await built.func({ category: "looping", detail: "d" }, { runId: "run-1" }, { toolCall: { id: "call_9" } })).toBe( - "Recorded.", - ); + // `tool()` calls `func(input, config)`: the call is on the 2nd argument. + expect(await built.func({ category: "looping", detail: "d" }, { toolCall: { id: "call_9" } })).toBe("Recorded."); expect((await reports())[0]).toMatchObject({ session_id: "fixed", agent_id: "lc", tool_call_id: "call_9" }); }); + it("reads the call id from the 3rd argument for DynamicStructuredTool, never a run id", async () => { + class DynamicStructuredTool { + constructor(readonly fields: { func: (...args: unknown[]) => Promise }) {} + } + const built = langchainTool({ module: { DynamicStructuredTool }, sessionId: "fixed" }); + await built.fields.func({ category: "looping", detail: "d" }, { runId: "run-1" }, { toolCall: { id: "call_3" } }); + await built.fields.func({ category: "looping", detail: "d" }, { runId: "run-2" }); + const recorded = await reports(); + expect(recorded[0]).toMatchObject({ tool_call_id: "call_3" }); + expect(recorded[1]!.tool_call_id).toBeUndefined(); + }); + it("falls back to DynamicStructuredTool", () => { class DynamicStructuredTool { constructor(readonly fields: Record) {} @@ -467,7 +501,8 @@ describe("the framework tools", () => { expect(await built.call({ category: "looping", detail: "d" })).toBe("Recorded."); }), ); - expect((await reports())[0]).toMatchObject({ session_id: "s1", agent_id: "li" }); + // LlamaIndex hands the tool no call id: it takes the open call's. + expect((await reports())[0]).toMatchObject({ session_id: "s1", agent_id: "li", tool_call_id: "li-1" }); }); it("uses FunctionTool.from when handed one", () => { diff --git a/src/hooks/daemon-service.ts b/src/hooks/daemon-service.ts index 4fb780b15..aedc336c3 100644 --- a/src/hooks/daemon-service.ts +++ b/src/hooks/daemon-service.ts @@ -1603,7 +1603,9 @@ export async function probeDaemonPolicyEvaluation(): Promise { event: "on_session_start", payload: { hook_event_name: "on_session_start", - source: "failproofai-native-policy-health-probe", + // The shared probe marker: the worker answers it before any activity + // row is written, and the daemon's hook watch does not count it. + source: HEALTH_PROBE_SOURCE, }, }, { responseTimeoutMs: DAEMON_PROBE_TIMEOUT_MS }, diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index de125a1c8..b77d816ce 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -55,7 +55,14 @@ import { } from "./policy-authority"; import type { CustomHook } from "./policy-types"; import { persistHookActivity } from "./hook-activity-store"; -import { isSelfReportCursorCall, isSelfReportToolName, selfReportArgs, SELF_REPORT_MCP_TOOL_NAME, SELF_REPORT_SERVER_RECORDS } from "./self-report"; +import { + isSelfReportCursorCall, + isSelfReportToolName, + selfReportAntigravityWrappedArgs, + selfReportArgs, + SELF_REPORT_MCP_TOOL_NAME, + SELF_REPORT_SERVER_RECORDS, +} from "./self-report"; import { deliveryHealth, deliveryHealthLine } from "./delivery-health"; import { trackHookEvent, flushHookTelemetry } from "./hook-telemetry"; import * as hookTelemetry from "./hook-telemetry"; @@ -764,8 +771,23 @@ export async function evaluateHookEvent( // The daemon health probe: proof the worker answers, not an agent event. // Answered before anything records scope errors or activity (B3). + // The allow `evaluation` is what the native policy-evaluation probe needs: + // the daemon answers a PolicyEvaluation only from a worker decision. if (isHealthProbe(eventType, parsed)) { - return { exitCode: 0, stdout: "", stderr: "" }; + return { + exitCode: 0, + stdout: "", + stderr: "", + evaluation: { + decision: "allow", + policyName: null, + policyNames: [], + reason: null, + matchedPolicies: [], + durationMs: Math.round(performance.now() - startTime), + toolName: null, + }, + }; } normalizeCliPayload(cli, parsed); @@ -779,9 +801,20 @@ export async function evaluateHookEvent( // tagging consistent (they read from `parsed.tool_name`). // Cursor's MCP hook names our tool `report` and the server separately; // file it under the one name before anything else reads the tool name. + // Cursor's preToolUse names one `MCP:report` with no server; only a payload + // that also names the server (`mcp_server_name: "failproofai"`) is ours. if (cli === "cursor" && isSelfReportCursorCall(parsed)) { parsed.tool_name = SELF_REPORT_MCP_TOOL_NAME; } + // Antigravity's lazy MCP path wraps the call in `call_mcp_tool`; unwrap it + // only when the wrapper names server `failproofai` and tool `report`. + if (cli === "antigravity") { + const wrapped = selfReportAntigravityWrappedArgs(parsed.tool_name, parsed.tool_input); + if (wrapped) { + parsed.tool_name = SELF_REPORT_MCP_TOOL_NAME; + parsed.tool_input = wrapped.args; + } + } const rawToolName = parsed.tool_name as string | undefined; const canonicalToolName = canonicalizeToolName(rawToolName, cli); if (canonicalToolName !== rawToolName) { diff --git a/src/hooks/health-probe.ts b/src/hooks/health-probe.ts index 5199187b0..07df52b07 100644 --- a/src/hooks/health-probe.ts +++ b/src/hooks/health-probe.ts @@ -9,7 +9,16 @@ */ export const HEALTH_PROBE_SOURCE = "failproofai-health-probe"; +/** + * The events a probe is sent as: the shell-hook probe's `SessionStart`, and the + * native policy-evaluation probe's Hermes `on_session_start` + * (`probeDaemonPolicyEvaluation`), which also carries this source so it writes + * no activity row either (it used to leave a phantom `hermes` SessionStart on + * machines with no Hermes). + */ +const HEALTH_PROBE_EVENTS: ReadonlySet = new Set(["SessionStart", "on_session_start"]); + /** Whether a parsed hook payload is the daemon health probe. */ export function isHealthProbe(eventType: string, parsed: Record): boolean { - return eventType === "SessionStart" && parsed.source === HEALTH_PROBE_SOURCE && parsed.session_id === undefined; + return HEALTH_PROBE_EVENTS.has(eventType) && parsed.source === HEALTH_PROBE_SOURCE && parsed.session_id === undefined; } diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts index ca10a70fa..7c3d3b96c 100644 --- a/src/hooks/self-report-cli.ts +++ b/src/hooks/self-report-cli.ts @@ -30,6 +30,7 @@ import { import { INTEGRATION_TYPES } from "./types"; import { daemonSocketPresent, isDaemonConfigured } from "./daemon-client"; import { + SELF_REPORT_CURSOR_APPROVAL_HINT, probeSelfReportHttp, selfReportCommandRunnable, selfReportRegistrationStatus, @@ -141,8 +142,9 @@ function selfReportRegistrationLines(rows: readonly SelfReportRegistration[], he state = `stdio ${r.endpoint ?? "?"} ${ok ? "(runnable)" : "(NOT runnable)"}`; } else state = r.hooked ? "not registered" : "registered, no hooks"; if (r.registered && !r.hooked) state += ", no hooks"; - return ` ${r.agent.padEnd(12)} ${state}`; - }), + const line = ` ${r.agent.padEnd(12)} ${state}`; + return r.agent === "cursor" && r.registered ? [line, ` ${"".padEnd(12)} ${SELF_REPORT_CURSOR_APPROVAL_HINT}`] : [line]; + }).flat(), ]; } diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index f73f1bf31..208b9dfd5 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -22,10 +22,10 @@ * |-------------|------------------------------------------------------|----------------------------|----------------------------------------------|-------------------------------------|----------------------| * | claude | `$CLAUDE_CONFIG_DIR/.claude.json`, else `~/.claude.json` | `mcpServers` | `{type:"http", url}` | `{type:"stdio", command, args}` | yes, PreToolUse `mcp__failproofai__report` | * | codex | `$CODEX_HOME/config.toml` (TOML) | `[mcp_servers.failproofai]`| `url = "…"` | `command`, `args` | yes, PreToolUse `mcp__failproofai__report` | - * | copilot | `$COPILOT_HOME/mcp-config.json`, else `~/.copilot/` | `mcpServers` | `{type:"http", url, tools:["*"]}` | `{type:"local", command, args, tools:["*"]}` | not documented | - * | cursor | `~/.cursor/mcp.json` (editor and cursor-agent) | `mcpServers` | `{url}` | `{type:"stdio", command, args}` | yes, `beforeMCPExecution` (tool_name `report` + mcp_server_name) and preToolUse `MCP:report` | + * | copilot | `$COPILOT_HOME/mcp-config.json`, else `~/.copilot/` | `mcpServers` | `{type:"http", url, tools:["*"]}` | `{type:"local", command, args, tools:["*"]}` | not documented; likely `failproofai-report` (exempt, with `failproofai/report`) | + * | cursor | `~/.cursor/mcp.json` (editor and cursor-agent) | `mcpServers` | `{url}` | `{type:"stdio", command, args}` | `beforeMCPExecution` (tool_name `report` + mcp_server_name; not installed) and preToolUse `MCP:report` with no server, so the server records | * | opencode | `~/.config/opencode/opencode.json` (as the hooks) | v1 `mcp.`; v2 `mcp.servers.` | `{type:"remote", url, enabled:true}` (v2: no `enabled`) | `{type:"local", command:[…]}` | yes, plugin `tool.execute.before` `failproofai_report` | - * | pi | `$PI_CODING_AGENT_DIR/mcp.json`, else `~/.pi/agent/` | `mcpServers` | `{url}` | `{command, args}` | yes per docs, `tool_call` `mcp__failproofai__report` | + * | pi | `$PI_CODING_AGENT_DIR/mcp.json`, else `~/.pi/agent/` | `mcpServers` | `{url, exposure:"direct"}` | `{command, args, exposure:"direct"}` | yes per docs, `tool_call` `mcp__failproofai__report` | * | hermes | every profile's `config.yaml` (YAML, HERMES_HOME) | `mcp_servers` | `{url}` | `{command, args}` | yes per source, `pre_tool_call` `mcp_failproofai_report` | * | openclaw | every profile's `openclaw.json` | `mcp.servers` | `{url, transport:"streamable-http"}` | `{command, args}` | likely (source only), `before_tool_call` `failproofai__report` | * | factory | `~/.factory/mcp.json` | `mcpServers` | `{type:"http", url}` | `{type:"stdio", command, args}` | yes, `mcp__failproofai__report` (regex sees `failproofai___report`) | @@ -33,6 +33,20 @@ * | antigravity | `~/.gemini/config/mcp_config.json` | `mcpServers` | `{serverUrl}` | `{command, args}` | not documented; eager tools `mcp_failproofai_report`, lazy (default) via `call_mcp_tool` | * | goose | `$GOOSE_PATH_ROOT/config/config.yaml`, else `~/.config/goose/config.yaml` (YAML) | `extensions` | `{type:"streamable_http", name, enabled, uri, …}` | `{type:"stdio", name, enabled, cmd, args, …}` | not documented; would be `failproofai__report` | * + * Cursor approval (cursor-agent 2026.11): servers from a *project* + * `.cursor/mcp.json` load only once approved; approvals live per project root + * in `~/.cursor/projects//mcp-approvals.json`, keyed by a hash of the + * root and the entry. `~/.cursor/mcp.json` is user scope and needs none, except + * when cursor-agent runs with the home directory as its project, where it is + * also the project file. That key changes with every project and transport, so + * failproofai writes no approval; sync and status point at + * `cursor-agent mcp enable failproofai` instead. + * + * Deferred tools: Pi's entry sets `exposure: "direct"` (its default `codemode` + * shows the model only the server's name). Hermes (`tools.tool_search`) and + * OpenClaw (`tools.toolSearch`) defer MCP tools with a global switch only; + * neither has a per-server "always load" option, so their entries set none. + * * Every agent supports Streamable HTTP, so the transport choice is purely * "is a daemon live here". Every path is the user-scope one: MCP servers are a per * user (per profile) setting even where failproofai's hooks are per project. @@ -297,7 +311,9 @@ export const SELF_REPORT_MCP_TARGETS: Record = { agent: "pi", format: "json", http: true, paths: () => [resolve(process.env.PI_CODING_AGENT_DIR?.trim() || resolve(homedir(), ".pi", "agent"), "mcp.json")], container: () => ["mcpServers"], - entry: (t) => plainEntry(t), + // Pi's default exposure, `codemode`, puts only the server's name in the + // prompt; `direct` declares `report` and its description like a built-in. + entry: (t) => ({ ...plainEntry(t), exposure: "direct" }), }, hermes: { agent: "hermes", format: "yaml", http: true, @@ -734,6 +750,10 @@ function errText(err: unknown): string { return err instanceof Error ? err.message : String(err); } +/** What to do when cursor-agent has not loaded the server yet. */ +export const SELF_REPORT_CURSOR_APPROVAL_HINT = + "cursor-agent: if `cursor-agent mcp list` shows failproofai as needing approval, run `cursor-agent mcp enable failproofai`"; + /** One line per change, conflict or error; nothing for an agent left as it was. */ export function selfReportSyncLines(results: readonly SelfReportMcpResult[]): string[] { const out: string[] = []; @@ -741,6 +761,7 @@ export function selfReportSyncLines(results: readonly SelfReportMcpResult[]): st const name = displayName(r.agent); if (r.action === "added" || r.action === "updated") { out.push(`✓ Self Reports MCP server ${r.action === "added" ? "added to" : "updated in"} ${name} (${r.transport}): ${r.path}`); + if (r.agent === "cursor") out.push(` ${SELF_REPORT_CURSOR_APPROVAL_HINT}`); } else if (r.action === "removed") { out.push(`✓ Self Reports MCP server removed from ${name}: ${r.path}`); } else if (r.status === "conflict" || r.status === "error") { diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts index 7d2326924..879b8bfac 100644 --- a/src/hooks/self-report-mcp.ts +++ b/src/hooks/self-report-mcp.ts @@ -14,7 +14,8 @@ * Codex, Cursor) is recorded by its PreToolUse hook, so this server writes * nothing for it. For an agent in `SELF_REPORT_SERVER_RECORDS` the server * appends one `self_report` event itself, attributed to the newest session of - * that agent in this working directory seen by the hooks in the last 6 hours. + * that agent seen by the hooks in the last 6 hours: in this working directory, + * else in one above or below it, else anywhere (`selfReportFindSessionMatch`). * * Nothing but JSON-RPC goes to stdout: a stray byte there corrupts the agent's * MCP stream. Diagnostics go to stderr. @@ -83,11 +84,43 @@ export function selfReportServerInstructions(): string | undefined { // ── Session attribution ───────────────────────────────────────────────────── /** - * Newest session id for `integration` in `cwd` seen by the hooks within the - * window, or null. Reads `current.jsonl` and, because it holds at most one - * page (25 rows) and may have just rotated, the newest archived page too. + * How closely a hook row's cwd matches the server's: 2 the same directory, 1 an + * ancestor or descendant of it, 0 unrelated (or unknown). Trailing slashes are + * ignored; `/` is an ancestor of every absolute path. */ -export function selfReportFindSession(integration: string, cwd: string, now: number = Date.now()): string | null { +export function selfReportCwdAffinity(want: string, have: unknown): 0 | 1 | 2 { + if (typeof have !== "string" || have === "") return 0; + const a = want.replace(/\/+$/, ""); + const b = have.replace(/\/+$/, ""); + if (a === b) return 2; + if (a === "" || b === "") return 1; + return b.startsWith(`${a}/`) || a.startsWith(`${b}/`) ? 1 : 0; +} + +/** A hook session that owns a report, and the cwd its row had. */ +export interface SelfReportSessionMatch { + sessionId: string; + cwd: string | undefined; +} + +/** + * The hook-activity session a report from `integration` belongs to, seen by + * the hooks within the window (6 h), or null. Most specific first: the newest + * session whose row has exactly this `cwd`; else the newest whose cwd is an + * ancestor or descendant of it; else the newest session of that integration + * anywhere. The stdio server's cwd is wherever the agent started it, which is + * often not the project (Hermes runs it from its own directory), so an exact + * match alone left those reports unattributed. The daemon's HTTP fallback + * (crates/fpai-collect/src/self_report.rs `find_session`) does the same. + * + * Reads `current.jsonl` and, because it holds at most one page (25 rows) and + * may have just rotated, the newest archived page too. + */ +export function selfReportFindSessionMatch( + integration: string, + cwd: string | undefined, + now: number = Date.now(), +): SelfReportSessionMatch | null { const dir = hookActivityDir(); const files: string[] = [join(dir, "current.jsonl")]; try { @@ -99,7 +132,7 @@ export function selfReportFindSession(integration: string, cwd: string, now: num } catch { // No activity directory: nothing to attribute to. } - let best: { ts: number; id: string } | null = null; + let best: { rank: number; ts: number; id: string; cwd: string | undefined } | null = null; for (const file of files) { let text: string; try { @@ -117,20 +150,27 @@ export function selfReportFindSession(integration: string, cwd: string, now: num } const ts = typeof row.timestamp === "number" ? row.timestamp : NaN; if ( - row.integration === integration && - row.cwd === cwd && - typeof row.sessionId === "string" && - row.sessionId && - Number.isFinite(ts) && - now - ts <= SELF_REPORT_SESSION_WINDOW_MS && - ts - now <= 60_000 && - (!best || ts > best.ts) + row.integration !== integration || + typeof row.sessionId !== "string" || + !row.sessionId || + !Number.isFinite(ts) || + now - ts > SELF_REPORT_SESSION_WINDOW_MS || + ts - now > 60_000 ) { - best = { ts, id: row.sessionId }; + continue; + } + const rank = cwd ? selfReportCwdAffinity(cwd, row.cwd) : 0; + if (!best || rank > best.rank || (rank === best.rank && ts > best.ts)) { + best = { rank, ts, id: row.sessionId, cwd: typeof row.cwd === "string" && row.cwd ? row.cwd : undefined }; } } } - return best ? best.id : null; + return best ? { sessionId: best.id, cwd: best.cwd } : null; +} + +/** The session id of `selfReportFindSessionMatch`, or null. */ +export function selfReportFindSession(integration: string, cwd: string, now: number = Date.now()): string | null { + return selfReportFindSessionMatch(integration, cwd, now)?.sessionId ?? null; } function selfReportMtime(path: string): number { @@ -192,11 +232,15 @@ export interface SelfReportEventInput { */ export async function writeSelfReportEvent(input: SelfReportEventInput): Promise<{ path: string; event: Record }> { const now = input.now ?? Date.now(); - const sessionId = input.sessionId ?? selfReportFindSession(input.integration, input.cwd, now) ?? "unattributed"; + const match = input.sessionId === undefined ? selfReportFindSessionMatch(input.integration, input.cwd, now) : null; + const sessionId = input.sessionId ?? match?.sessionId ?? "unattributed"; const event: Record = { timestamp: new Date(now).toISOString(), session_id: sessionId, - agent_id: selfReportAgentId(input.integration, input.cwd), + // The agent the session's hook rows are filed under: from the matched + // row's cwd, not the server's own (they differ when the agent starts the + // server elsewhere). + agent_id: selfReportAgentId(input.integration, match?.cwd ?? input.cwd), type: "self_report", category: input.category, detail: input.detail, diff --git a/src/hooks/self-report-names.ts b/src/hooks/self-report-names.ts index 2908cca69..b6b1cd1a8 100644 --- a/src/hooks/self-report-names.ts +++ b/src/hooks/self-report-names.ts @@ -38,6 +38,11 @@ export const SELF_REPORT_DEFAULT_PORT = 4319; * - `failproofai__report`: OpenClaw and Goose (`__`). * - Cursor: see `isSelfReportCursorCall`; its preToolUse name `MCP:report` * carries no server, so it is never matched by name alone. + * - Antigravity's lazy path, `call_mcp_tool`: see + * `selfReportAntigravityWrappedArgs`; matched only on its server and tool. + * - `failproofai-report` (`-`) and `failproofai/report`: Copilot + * CLI's likely forms. Its hook spelling of an MCP tool is not documented and + * could not be observed without a signed-in run, so both are exempt. * - `failproofai.report`, `failproofai/report`, `failproofai:report`, * `mcp__failproofai_report`, `mcp:failproofai:report`, * `mcp:failproofai/report`: other server-qualified forms, kept so a @@ -55,6 +60,7 @@ const SELF_REPORT_TOOL_SPELLINGS: ReadonlySet = new Set([ "mcp__failproofai_report", "mcp:failproofai:report", "mcp:failproofai/report", + "failproofai-report", ]); /** True for the report tool under any agent's spelling of it (contract §1). */ @@ -78,9 +84,42 @@ export function isSelfReportCursorCall(payload: unknown): boolean { } /** - * Integrations whose hooks do not see MCP tool calls, so the MCP server itself - * records a report (contract §8). Claude Code, Codex and Cursor are recorded by - * the hook. Kept identical to the Rust list. + * Antigravity's lazy (default) MCP path: the model calls the built-in + * `call_mcp_tool` wrapper with `{ServerName, ToolName, Arguments}` (agy 1.5's + * own description says to judge it by ServerName + ToolName). Returns the + * wrapped call's arguments when, and only when, the wrapper names server + * `failproofai` and tool `report`; `undefined` for any other server or tool, + * whose calls keep going through the policies. + */ +export function selfReportAntigravityWrappedArgs(toolName: unknown, toolInput: unknown): { args: unknown } | undefined { + if (typeof toolName !== "string" || toolName.toLowerCase() !== "call_mcp_tool") return undefined; + let input: unknown = toolInput; + if (typeof input === "string") { + try { + input = JSON.parse(input); + } catch { + return undefined; + } + } + if (!input || typeof input !== "object" || Array.isArray(input)) return undefined; + const i = input as Record; + const pick = (...keys: string[]): unknown => keys.map((k) => i[k]).find((v) => v !== undefined); + const server = pick("ServerName", "serverName", "server_name"); + const tool = pick("ToolName", "toolName", "tool_name"); + if (typeof server !== "string" || server.toLowerCase() !== SELF_REPORT_SERVER_NAME) return undefined; + if (typeof tool !== "string") return undefined; + const t = tool.toLowerCase(); + if (t !== SELF_REPORT_TOOL_NAME && !isSelfReportToolName(t)) return undefined; + return { args: pick("Arguments", "arguments", "args") ?? {} }; +} + +/** + * Integrations whose hooks do not see MCP tool calls, or do not see which + * server a call is for, so the MCP server itself records a report (contract + * §8). Claude Code and Codex are recorded by the hook. Cursor is here because + * the hook failproofai installs (preToolUse) names an MCP call `MCP:` + * with no server, and its MCP hook (beforeMCPExecution) is not installed. + * Kept identical to the Rust list. */ export const SELF_REPORT_SERVER_RECORDS: readonly string[] = [ "openclaw", @@ -92,5 +131,6 @@ export const SELF_REPORT_SERVER_RECORDS: readonly string[] = [ "antigravity", "copilot", "opencode", + "cursor", ]; diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts index 630e47f55..e326cb9e3 100644 --- a/src/hooks/self-report.ts +++ b/src/hooks/self-report.ts @@ -34,6 +34,7 @@ export { SELF_REPORT_SERVER_RECORDS, isSelfReportToolName, isSelfReportCursorCall, + selfReportAntigravityWrappedArgs, } from "./self-report-names"; import { SELF_REPORT_DETAIL_MAX, SELF_REPORT_DEFAULT_PORT } from "./self-report-names"; diff --git a/test-fixtures/self-report/server-records.golden.txt b/test-fixtures/self-report/server-records.golden.txt index 65edc041c..5c7de041d 100644 --- a/test-fixtures/self-report/server-records.golden.txt +++ b/test-fixtures/self-report/server-records.golden.txt @@ -7,3 +7,4 @@ factory antigravity copilot opencode +cursor diff --git a/test-fixtures/self-report/tool-names.golden.txt b/test-fixtures/self-report/tool-names.golden.txt index ee2992ff7..5243c6ac1 100644 --- a/test-fixtures/self-report/tool-names.golden.txt +++ b/test-fixtures/self-report/tool-names.golden.txt @@ -9,3 +9,4 @@ mcp_failproofai_report mcp__failproofai_report mcp:failproofai:report mcp:failproofai/report +failproofai-report From fb102d16c308fa6fe68723640c19984e36d3048d Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 26 Nov 2026 21:26:13 +0530 Subject: [PATCH 13/54] [self-reports] Address review: daemon identity, HTTP gating, attribution, SDK fixes - HTTP transport only when the endpoint answers with the instance id of the daemon behind this home's socket (new optional Pong.selfReport + MCP serverInfo.instanceId); a daemon whose MCP bind failed names none -> stdio - HTTP fallback records nothing unless self-report.json says enabled (read from disk on every call) - HTTP only for hook-recorded agents (claude, codex); every server-recorded agent stays on stdio, status moves old HTTP entries; the Rust fallback never guesses across projects (unattributed instead) - Cursor: a failed server check keeps the tool name and goes through policies - self-report sync takes the non-migrating unattended layout gate - sync keeps and repairs an owned registration with project-only hooks - uninstall surveys orphan MCP registrations - Python SDK: open tool calls keyed by session, no cross-session guess; CrewAI report tool never cached and runs in the caller's context - TS SDK: no cross-session recency guess; AI SDK tool carries both schema keys for a passed module; Edge LangChain tool builds with a passed module - Docs, skill, changelogs Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/self-report-handler.test.ts | 23 ++ __tests__/hooks/self-report-install.test.ts | 133 ++++++++-- __tests__/hooks/self-report.test.ts | 42 ++++ __tests__/hooks/uninstall-cli.test.ts | 29 +++ bin/failproofai.mjs | 9 +- crates/PROTOCOL.md | 5 + crates/failproofaid/src/server.rs | 18 +- crates/failproofaid/tests/daemon_e2e.rs | 56 +++-- crates/failproofaid/tests/self_report_e2e.rs | 62 ++++- crates/fpai-collect/src/self_report.rs | 228 ++++++++++++++++-- crates/fpai-ipc/src/envelope.rs | 58 ++++- crates/fpai-ipc/src/lib.rs | 2 +- docs/reference/mcp.mdx | 2 +- docs/self-reports.mdx | 6 +- sdk/python/CHANGELOG.md | 7 +- sdk/python/failproofai_sdk/_events.py | 51 ++-- .../failproofai_sdk/integrations/crewai.py | 44 +++- sdk/python/skill/SKILL.md | 3 + sdk/python/skill/references/integration.md | 5 + sdk/python/tests/integrations/test_crewai.py | 44 ++++ sdk/python/tests/test_self_report.py | 36 +++ sdk/typescript/CHANGELOG.md | 6 +- sdk/typescript/README.md | 8 +- sdk/typescript/src/edge/langchain.ts | 14 +- sdk/typescript/src/edge/self-report-tool.ts | 26 ++ sdk/typescript/src/events.ts | 8 +- .../src/integrations/self-report-tools.ts | 11 +- .../test/self-report-ai-module.test.ts | 44 ++++ sdk/typescript/test/self-report.test.ts | 58 ++++- src/hooks/daemon-client.ts | 29 ++- src/hooks/handler.ts | 16 +- src/hooks/self-report-cli.ts | 11 +- src/hooks/self-report-install.ts | 146 ++++++++--- src/hooks/self-report-mcp.ts | 7 +- src/hooks/uninstall-cli.ts | 26 +- 36 files changed, 1109 insertions(+), 166 deletions(-) create mode 100644 sdk/typescript/test/self-report-ai-module.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c0146eaa..ceb962327 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Features -- Self Reports: every hooked agent gets a `report` tool (MCP server `failproofai`, served by `failproofaid` at `http://127.0.0.1:4319/mcp` or by `failproofai mcp` over stdio) to say it is stuck, under six default categories or the organization's own; the hook allows the call before any policy, pause or Jev review and records it as a `self_report` event, the MCP server records it for agents whose hooks do not see MCP calls, the setting comes from Cloud (`selfReport` in desired-state) or `failproofai self-report enable|disable|status|test|sync` and lives in `~/.failproofai/self-report.json`, and both SDKs add `self_report()` / `selfReport()` with ready-made framework tools; the server's initialize result carries short instructions (agents that defer MCP tools, like Claude Code, still see them), and HTTP vs stdio is chosen from a live daemon check that the daemon re-runs at startup; the instructions name the `category` and `detail` arguments, and a call that sends the detail under another name (`summary`, `sentence`, `message`, ...) still records it; Cursor reports are recorded by the MCP server (its tool hook does not name the server), Antigravity's `call_mcp_tool` wrapper for `failproofai`/`report` is allowed ahead of the policies, Copilot's likely `failproofai-report` spelling is exempt, Pi's entry is exposed directly, server-recorded reports find their session by an exact, then related, then any working directory and take the session's own agent, and a hand-started daemon finds `failproofai` on PATH for its startup sync +- Self Reports: every hooked agent gets a `report` tool (MCP server `failproofai`, served by `failproofaid` at `http://127.0.0.1:4319/mcp` or by `failproofai mcp` over stdio) to say it is stuck, under six default categories or the organization's own; the hook allows the call before any policy, pause or Jev review and records it as a `self_report` event, the MCP server records it for agents whose hooks do not see MCP calls, the setting comes from Cloud (`selfReport` in desired-state) or `failproofai self-report enable|disable|status|test|sync` and lives in `~/.failproofai/self-report.json`, and both SDKs add `self_report()` / `selfReport()` with ready-made framework tools; the server's initialize result carries short instructions (agents that defer MCP tools, like Claude Code, still see them), and HTTP vs stdio is chosen from a live daemon check that the daemon re-runs at startup; the instructions name the `category` and `detail` arguments, and a call that sends the detail under another name (`summary`, `sentence`, `message`, ...) still records it; Cursor reports are recorded by the MCP server (its tool hook does not name the server), Antigravity's `call_mcp_tool` wrapper for `failproofai`/`report` is allowed ahead of the policies, Copilot's likely `failproofai-report` spelling is exempt, Pi's entry is exposed directly, server-recorded reports find their session by an exact, then related, then any working directory and take the session's own agent, and a hand-started daemon finds `failproofai` on PATH for its startup sync; HTTP is used only for Claude Code and Codex (hook-recorded) and only when the endpoint answers with the instance id of the daemon behind this home's socket, every server-recorded agent stays on stdio, the HTTP server records nothing while Self Reports is off and never attributes a report across projects, a Cursor call that fails the server check always goes through the policies, `self-report sync` refuses a stale home instead of migrating it unattended, and `uninstall` also finds an orphan MCP registration ### Fixes diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index 431b8ffc3..229f9303b 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -260,6 +260,29 @@ describe("Self Reports short-circuit", () => { expect(theirs.evaluation?.decision).toBe("deny"); }); + it("never lets a Cursor call that fails the server check through by its name alone", async () => { + // Another server's tool, or one with no server named, spelled like ours: + // it keeps its own name, is not recorded as a report, and the policies run. + for (const name of ["mcp__failproofai__report", "failproofai__report", "failproofai-report", "mcp_failproofai_report"]) { + for (const extra of [{ mcp_server_name: "linear" }, {}]) { + vi.mocked(loadAllCustomHooks).mockClear(); + for (const event of ["preToolUse", "beforeMCPExecution"]) { + const out = await evaluateHookEvent(event, "cursor", payload(name, { category: "looping", detail: "x" }, extra)); + expect(out.evaluation?.decision, `${event} ${name} ${JSON.stringify(extra)}`).toBe("deny"); + expect(out.evaluation?.toolName).toBe(name); + } + expect(loadAllCustomHooks).toHaveBeenCalled(); + } + } + expect(rows().some((r) => r.selfReport !== undefined)).toBe(false); + // The same spelling WITH our server is still ours. + const ours = await evaluateHookEvent( + "preToolUse", "cursor", + payload("mcp__failproofai__report", { category: "looping", detail: "x" }, { mcp_server_name: "failproofai" }), + ); + expect(ours.evaluation?.decision).toBe("allow"); + }); + describe("Antigravity's lazy MCP path (call_mcp_tool)", () => { const agy = (args: Record) => JSON.stringify({ conversationId: SESSION, workspacePaths: ["/tmp/project"], toolCall: { name: "call_mcp_tool", args } }); diff --git a/__tests__/hooks/self-report-install.test.ts b/__tests__/hooks/self-report-install.test.ts index 44ef92ec7..9a45e047e 100644 --- a/__tests__/hooks/self-report-install.test.ts +++ b/__tests__/hooks/self-report-install.test.ts @@ -12,7 +12,9 @@ import { SELF_REPORT_MCP_TARGETS, isOurMcpEntry, probeSelfReportHttp, + probeSelfReportHttpInstance, selfReportDaemonLive, + selfReportHttpAllowed, selfReportSyncChanged, readSelfReportMcpSettings, removeSelfReportMcp, @@ -22,6 +24,7 @@ import { } from "../../src/hooks/self-report-install"; import { mergeTomlManagedBlock } from "../../src/hooks/toml-managed-block"; import { INTEGRATION_TYPES, type IntegrationType } from "../../src/hooks/types"; +import { SELF_REPORT_SERVER_RECORDS } from "../../src/hooks/self-report"; const CLI = "/usr/local/bin/failproofai"; let home: string; @@ -108,13 +111,18 @@ describe("syncSelfReportMcp: every agent round-trips", () => { } put(path, original); + // With a live daemon: HTTP for a hook-recorded agent, stdio for one the + // server records (it must know the caller's cwd). + const want = selfReportHttpAllowed(agent) ? "http" : "stdio"; const first = await syncSelfReportMcp(enabledOpts({ agents: [agent] })); expect(first.map((r) => [r.action, r.status, r.transport])).toEqual( - first.map(() => ["added", "ok", "http"]), + first.map(() => ["added", "ok", want]), ); const entry = entryIn(agent)!; expect(isOurMcpEntry(entry)).toBe(true); - expect(JSON.stringify(entry)).toContain(`http://127.0.0.1:4319/mcp?agent=${agent}`); + expect(JSON.stringify(entry)).toContain( + want === "http" ? `http://127.0.0.1:4319/mcp?agent=${agent}` : JSON.stringify(["mcp", "--agent", agent]).slice(1, -1), + ); const afterAdd = read(path); // the user's things are still there, comments included expect(afterAdd).toContain("mine"); @@ -139,6 +147,31 @@ describe("syncSelfReportMcp: every agent round-trips", () => { }); describe("transport choice", () => { + it("uses HTTP only for hook-recorded agents; every server-recorded agent stays on stdio", async () => { + expect(INTEGRATION_TYPES.filter((a) => selfReportHttpAllowed(a))).toEqual(["claude", "codex"]); + for (const a of SELF_REPORT_SERVER_RECORDS) expect(selfReportHttpAllowed(a as IntegrationType)).toBe(false); + const r = await syncSelfReportMcp(enabledOpts({}, true)); + for (const x of r) expect(x.transport).toBe(selfReportHttpAllowed(x.agent) ? "http" : "stdio"); + // Every agent's HTTP shape is still one we recognise (a stale one is moved). + for (const a of INTEGRATION_TYPES) { + const t = SELF_REPORT_MCP_TARGETS[a]; + expect(isOurMcpEntry(t.entry({ kind: "http", url: `http://127.0.0.1:4319/mcp?agent=${a}` }, t.container({})))).toBe(true); + } + }); + + it("never asks for the live check when only server-recorded agents want an entry", async () => { + const daemonLive = vi.fn(async () => true); + await syncSelfReportMcp(enabledOpts({ agents: ["copilot", "pi", "hermes"], deps: { daemonLive } })); + expect(daemonLive).not.toHaveBeenCalled(); + }); + + it("moves a server-recorded agent's older HTTP entry to stdio", async () => { + put(pathOf("copilot"), JSON.stringify({ mcpServers: { failproofai: { type: "http", url: "http://127.0.0.1:4319/mcp?agent=copilot", tools: ["*"] } } })); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["copilot"] }, true)); + expect(r[0]).toMatchObject({ action: "updated", transport: "stdio" }); + expect(entryIn("copilot")).toEqual({ type: "local", command: CLI, args: ["mcp", "--agent", "copilot"], tools: ["*"] }); + }); + it("uses stdio with the CLI path and --agent when no daemon is live", async () => { await syncSelfReportMcp(enabledOpts({ agents: ["claude", "codex", "opencode", "goose"] }, false)); expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"] }); @@ -150,11 +183,12 @@ describe("transport choice", () => { it("exposes Pi's entry directly, on both transports, and moves an old entry to it", async () => { await syncSelfReportMcp(enabledOpts({ agents: ["pi"] }, false)); expect(entryIn("pi")).toEqual({ command: CLI, args: ["mcp", "--agent", "pi"], exposure: "direct" }); - // An entry written before `exposure` was set is ours and gets updated. + // An older HTTP entry, written before `exposure` was set, is ours: it is + // moved to stdio (Pi is server-recorded) with exposure set. put(pathOf("pi"), JSON.stringify({ mcpServers: { failproofai: { url: "http://127.0.0.1:4319/mcp?agent=pi" } } })); const r = await syncSelfReportMcp(enabledOpts({ agents: ["pi"] }, true)); - expect(r[0]).toMatchObject({ action: "updated", transport: "http" }); - expect(entryIn("pi")).toEqual({ url: "http://127.0.0.1:4319/mcp?agent=pi", exposure: "direct" }); + expect(r[0]).toMatchObject({ action: "updated", transport: "stdio" }); + expect(entryIn("pi")).toEqual({ command: CLI, args: ["mcp", "--agent", "pi"], exposure: "direct" }); }); it("tells the user how cursor-agent approves the server when Cursor's entry is written", async () => { @@ -179,8 +213,8 @@ describe("transport choice", () => { const p = resolve(home, ".failproofai", "self-report.json"); put(p, JSON.stringify({ version: 1, enabled: true, mcp: { port: 5555, url: "http://127.0.0.1:5555/mcp" } })); expect(readSelfReportMcpSettings()).toEqual({ enabled: true, port: 5555 }); - await syncSelfReportMcp({ quiet: true, agents: ["cursor"], deps: { daemonLive: async () => true, hooksInstalled: () => true } }); - expect(entryIn("cursor")).toEqual({ url: "http://127.0.0.1:5555/mcp?agent=cursor" }); + await syncSelfReportMcp({ quiet: true, agents: ["claude"], deps: { daemonLive: async () => true, hooksInstalled: () => true } }); + expect(entryIn("claude")).toEqual({ type: "http", url: "http://127.0.0.1:5555/mcp?agent=claude" }); }); it("reads a missing or broken settings file as disabled", async () => { @@ -256,6 +290,28 @@ describe("which agents", () => { expect(r[0].action).toBe("added"); }); + it("keeps and repairs an existing registration whose hooks are only at project scope", async () => { + // Installed with project-scope hooks (alsoHooked) while the daemon was up. + await syncSelfReportMcp(enabledOpts({ agents: ["claude"], alsoHooked: ["claude"], deps: { hooksInstalled: () => false } }, true)); + expect(entryIn("claude")).toEqual({ type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude" }); + // A later sync sees no user-scope hooks; the daemon is gone. The entry is + // moved to stdio, not stranded on a dead endpoint. + const r = await syncSelfReportMcp(enabledOpts({ agents: ["claude", "factory"], deps: { hooksInstalled: () => false } }, false)); + expect(r.find((x) => x.agent === "claude")).toMatchObject({ action: "updated", transport: "stdio", status: "ok" }); + expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"] }); + // An agent never registered and without hooks is still left alone. + expect(r.find((x) => x.agent === "factory")).toMatchObject({ action: "skipped", status: "not-hooked" }); + expect(existsSync(pathOf("factory"))).toBe(false); + }); + + it("the live check is asked for an unhooked agent that already has our entry", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["codex"], alsoHooked: ["codex"], deps: { hooksInstalled: () => false } }, false)); + const daemonLive = vi.fn(async () => true); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["codex"], deps: { daemonLive, hooksInstalled: () => false } })); + expect(daemonLive).toHaveBeenCalledTimes(1); + expect(r[0]).toMatchObject({ action: "updated", transport: "http" }); + }); + it("disabled: removes ours from every agent, hooked or not", async () => { await syncSelfReportMcp(enabledOpts({ agents: ["claude", "factory"] })); const r = await syncSelfReportMcp({ quiet: true, deps: { settings: { enabled: false, port: 4319 }, hooksInstalled: () => false, daemonLive: async () => true } }); @@ -269,8 +325,8 @@ describe("which agents", () => { const r = await syncSelfReportMcp(enabledOpts({ agents: ["hermes"] })); expect(r.map((x) => x.action)).toEqual(["added", "added"]); for (const p of [resolve(home, ".hermes", "config.yaml"), resolve(home, ".hermes", "profiles", "work", "config.yaml")]) { - const doc = parseYaml(read(p)) as { mcp_servers: { failproofai: { url: string } } }; - expect(doc.mcp_servers.failproofai.url).toBe("http://127.0.0.1:4319/mcp?agent=hermes"); + const doc = parseYaml(read(p)) as { mcp_servers: { failproofai: unknown } }; + expect(doc.mcp_servers.failproofai).toEqual({ command: CLI, args: ["mcp", "--agent", "hermes"] }); expect(read(p)).toContain("failproofai self-report MCP server"); } }); @@ -288,7 +344,7 @@ describe("which agents", () => { put(pathOf("opencode"), JSON.stringify({ mcp: { servers: { mine: { type: "local", command: ["node"] } } } })); await syncSelfReportMcp(enabledOpts({ agents: ["opencode"] })); const doc = JSON.parse(read(pathOf("opencode"))); - expect(doc.mcp.servers.failproofai).toEqual({ type: "remote", url: "http://127.0.0.1:4319/mcp?agent=opencode" }); + expect(doc.mcp.servers.failproofai).toEqual({ type: "local", command: [CLI, "mcp", "--agent", "opencode"] }); expect(doc.mcp.failproofai).toBeUndefined(); }); @@ -301,8 +357,11 @@ describe("which agents", () => { // ── Live transport check ──────────────────────────────────────────────────── -/** A fake daemon socket: answers every framed request with a framed pong. */ -function fakeDaemon(path: string, answer = true): Promise { +/** + * A fake daemon socket: answers every framed request with a framed pong. With + * `selfReport`, the pong names the MCP server it serves (instance id + port). + */ +function fakeDaemon(path: string, answer = true, selfReport?: { instanceId: string; port: number }): Promise { const server = createNetServer((sock) => { let buf = Buffer.alloc(0); sock.on("data", (chunk) => { @@ -310,7 +369,7 @@ function fakeDaemon(path: string, answer = true): Promise { if (buf.length < 4 || buf.length < 4 + buf.readUInt32BE(0)) return; if (!answer) return; // accepted, never answered const req = JSON.parse(buf.subarray(4, 4 + buf.readUInt32BE(0)).toString("utf8")); - const body = Buffer.from(JSON.stringify({ type: "pong", protocolVersion: req.protocolVersion })); + const body = Buffer.from(JSON.stringify({ type: "pong", protocolVersion: req.protocolVersion, ...(selfReport ? { selfReport } : {}) })); const head = Buffer.alloc(4); head.writeUInt32BE(body.length, 0); sock.end(Buffer.concat([head, body])); @@ -320,14 +379,14 @@ function fakeDaemon(path: string, answer = true): Promise { } /** A fake MCP endpoint on an ephemeral loopback port. */ -function fakeMcp(serverName = "failproofai"): Promise<{ server: HttpServer; port: number }> { +function fakeMcp(serverName = "failproofai", instanceId: string | null = "inst-1"): Promise<{ server: HttpServer; port: number }> { const server = createHttpServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { const msg = JSON.parse(body || "{}"); res.setHeader("content-type", "application/json"); - res.end(JSON.stringify({ jsonrpc: "2.0", id: msg.id, result: { protocolVersion: "2025-06-18", capabilities: {}, serverInfo: { name: serverName, version: "1" } } })); + res.end(JSON.stringify({ jsonrpc: "2.0", id: msg.id, result: { protocolVersion: "2025-06-18", capabilities: {}, serverInfo: { name: serverName, version: "1", ...(instanceId === null ? {} : { instanceId }) } } })); }); }); return new Promise((ok) => server.listen(0, "127.0.0.1", () => ok({ server, port: (server.address() as { port: number }).port }))); @@ -368,8 +427,8 @@ describe("live transport check", () => { it("a daemon answering ping AND an MCP initialize gives http; a later sync moves it back once it is gone", async () => { vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); - const daemon = await fakeDaemon(socket()); const { server, port } = await fakeMcp(); + const daemon = await fakeDaemon(socket(), true, { instanceId: "inst-1", port }); expect(await selfReportDaemonLive(port)).toBe(true); const opts = { quiet: true, agents: ["claude"] as IntegrationType[], binaryPath: CLI, deps: { hooksInstalled: () => true, settings: { enabled: true, port } } }; expect((await syncSelfReportMcp(opts))[0]).toMatchObject({ action: "added", transport: "http" }); @@ -382,8 +441,9 @@ describe("live transport check", () => { it("needs both halves: a ping without the endpoint, or the endpoint without a ping, is stdio", async () => { vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); - const daemon = track(await fakeDaemon(socket())); - expect(await selfReportDaemonLive(await deadPort())).toBe(false); + const dead = await deadPort(); + const daemon = track(await fakeDaemon(socket(), true, { instanceId: "inst-1", port: dead })); + expect(await selfReportDaemonLive(dead)).toBe(false); await new Promise((ok) => daemon.close(ok)); closeAll.pop(); const { server, port } = await fakeMcp(); @@ -399,6 +459,43 @@ describe("live transport check", () => { expect(await selfReportDaemonLive(port)).toBe(false); }, 10_000); + it("the endpoint must be served by the daemon behind this socket", async () => { + vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); + // Another daemon (another home) holds the port; this one's bind failed, so + // its pong names no MCP server: stdio, even though the port answers. + const { server, port } = await fakeMcp("failproofai", "other-daemon"); + track(server); + const daemon = track(await fakeDaemon(socket())); + expect(await probeSelfReportHttpInstance(port)).toBe("other-daemon"); + expect(await selfReportDaemonLive(port)).toBe(false); + const r = await syncSelfReportMcp({ + quiet: true, agents: ["claude"], binaryPath: CLI, + deps: { hooksInstalled: () => true, settings: { enabled: true, port } }, + }); + expect(r[0]).toMatchObject({ transport: "stdio" }); + await new Promise((ok) => daemon.close(ok)); + closeAll.pop(); + // This daemon serves MCP too, under its own id, but the port answers with + // another id: still stdio. + track(await fakeDaemon(socket(), true, { instanceId: "this-daemon", port })); + expect(await selfReportDaemonLive(port)).toBe(false); + }); + + it("a pong naming another port, or an endpoint with no instance id, is stdio", async () => { + vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); + const { server, port } = await fakeMcp("failproofai", "inst-1"); + track(server); + const daemon = track(await fakeDaemon(socket(), true, { instanceId: "inst-1", port: port + 1 })); + expect(await selfReportDaemonLive(port)).toBe(false); + await new Promise((ok) => daemon.close(ok)); + closeAll.pop(); + const old = await fakeMcp("failproofai", null); + track(old.server); + expect(await probeSelfReportHttpInstance(old.port)).toBe(""); + track(await fakeDaemon(socket(), true, { instanceId: "inst-1", port: old.port })); + expect(await selfReportDaemonLive(old.port)).toBe(false); + }); + it("another server on the port is not ours", async () => { const { server, port } = await fakeMcp("someone-else"); track(server); diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index 38a5391c4..bc6a9bf78 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -293,6 +293,31 @@ function runMcp(agentArgs: string[], messages: unknown[], cwd: string): Promise< }); } +describe("self-report sync on a stale home", () => { + it("refuses, like a scheduled audit, instead of migrating (and resetting) the home unattended", async () => { + // What failproofaid runs at startup and after each settings change. + writeFileSync(join(home, "VERSION"), JSON.stringify({ layout: 1, cli: "0.0.1" })); + const toml = "[telemetry]\nenabled = false\n"; + writeFileSync(join(home, "config.toml"), toml); + const { code, stderr } = await new Promise<{ code: number | null; stderr: string }>((ok, fail) => { + const child = spawn("bun", [BINARY, "self-report", "sync", "--quiet"], { + cwd: home, + env: { ...process.env, HOME: home, FAILPROOFAI_HOME: home, FAILPROOFAI_TELEMETRY_DISABLED: "1" }, + stdio: ["ignore", "pipe", "pipe"], + }); + let err = ""; + child.stderr.on("data", (b: Buffer) => (err += b.toString())); + child.on("error", fail); + child.on("close", (c) => ok({ code: c, stderr: err })); + }); + expect(code).toBe(1); + expect(stderr).toContain("refusing to run unattended"); + expect(stderr).toContain("failproofai config"); + expect(readFileSync(join(home, "config.toml"), "utf8")).toBe(toml); + expect(JSON.parse(readFileSync(join(home, "VERSION"), "utf8")).layout).toBe(1); + }, 30_000); +}); + const INIT = { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "t", version: "1" } } }; const INITIALIZED = { jsonrpc: "2.0", method: "notifications/initialized" }; const LIST = { jsonrpc: "2.0", id: 2, method: "tools/list" }; @@ -548,6 +573,23 @@ describe("failproofai self-report enable | disable | status", () => { expect(synced).toBe(0); }); + it("status moves a server-recorded agent off HTTP even while the endpoint answers", async () => { + writeEffectiveSelfReport({ enabled: true }); + let synced = 0; + let rows = [row({ agent: "copilot", transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=copilot" })]; + const r = await runSelfReportCommand(["status"], { + probeEndpoint: async () => true, + registrations: () => rows, + sync: async () => { + synced++; + rows = [row({ agent: "copilot", transport: "stdio", endpoint: "/usr/bin/failproofai" })]; + return [{ agent: "copilot", path: "/x", action: "updated", transport: "stdio", status: "ok" }]; + }, + }); + expect(synced).toBe(1); + expect(r.lines.join("\n")).toContain("Repaired:"); + }); + it("enable says \"Agents updated.\" only when a sync changed something", async () => { const quiet = await runSelfReportCommand(["enable"], { probeEndpoint: async () => false, sync: async () => [{ agent: "claude", path: "/x", action: "unchanged", transport: "http", status: "ok" }] }); expect(quiet.lines.join("\n")).not.toContain("Agents updated."); diff --git a/__tests__/hooks/uninstall-cli.test.ts b/__tests__/hooks/uninstall-cli.test.ts index 4d7f8277f..993f90d24 100644 --- a/__tests__/hooks/uninstall-cli.test.ts +++ b/__tests__/hooks/uninstall-cli.test.ts @@ -42,6 +42,7 @@ vi.mock("../../src/hooks/manager", () => ({ // its own behaviour is covered in self-report-install.test.ts. vi.mock("../../src/hooks/self-report-install", () => ({ removeSelfReportMcp: vi.fn(() => []), + selfReportRegistrationStatus: vi.fn(() => []), })); vi.mock("../../src/hooks/agent-skill", () => ({ installedAgentSkillDirs: () => skillDirs, @@ -573,6 +574,34 @@ describe("hooks/uninstall-cli — the agent selection is not uninstall's to chan }); describe("hooks/uninstall-cli — Self Reports MCP server", () => { + it("an orphan MCP registration alone is something to uninstall, named in the plan", async () => { + installedClis = []; + configured = false; + rmSync(servicePath, { force: true }); + const mod = await import("../../src/hooks/self-report-install"); + const orphan = { agent: "copilot", path: "/x/.copilot/mcp-config.json", hooked: false, registered: true, transport: "stdio", endpoint: "/x/failproofai", conflict: false } as const; + vi.mocked(mod.selfReportRegistrationStatus).mockReturnValue([ + orphan, + { ...orphan, agent: "claude", path: "/x/.claude.json", registered: false, transport: null, endpoint: null }, + ]); + const { runUninstallCommand } = await import("../../src/hooks/uninstall-cli"); + try { + const dry = await runUninstallCommand({ dryRun: true }); + expect(dry.lines.join("\n")).not.toContain("Nothing to uninstall"); + expect(dry.lines.join("\n")).toContain("the Self Reports MCP server from 1 agent config"); + expect(vi.mocked(mod.removeSelfReportMcp)).not.toHaveBeenCalled(); + + vi.mocked(mod.removeSelfReportMcp).mockReturnValueOnce([ + { agent: "copilot", path: orphan.path, action: "removed", transport: "stdio", status: "ok" }, + ]); + const res = await runUninstallCommand({ yes: true }); + expect(res.exitCode).toBe(0); + expect(res.lines.join("\n")).toContain("Removed the Self Reports MCP server from 1 agent config."); + } finally { + vi.mocked(mod.selfReportRegistrationStatus).mockReturnValue([]); + } + }); + it("removes failproofai's MCP server from every agent and says so", async () => { const mod = await import("../../src/hooks/self-report-install"); vi.mocked(mod.removeSelfReportMcp).mockReturnValueOnce([ diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index bfc55a259..c882f0260 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -688,7 +688,14 @@ async function runCli() { { const isHelpOrVersion = args.includes("--help") || args.includes("-h") || args.includes("--version") || args.includes("-v"); - if (args[0] === "audit" && args.includes("--scheduled")) { + // `self-report sync` takes it too: failproofaid runs it (`--quiet`) at + // startup and after every settings change, unattended, exactly like a + // scheduled audit. A person running it by hand on a stale home is told to + // run `failproofai config`, which migrates visibly. + const unattended = + (args[0] === "audit" && args.includes("--scheduled")) || + (args[0] === "self-report" && args[1] === "sync" && !isHelpOrVersion); + if (unattended) { // NOT `layoutWarningForHook` — that one answers the hook's question // ("are policies unenforced?") and deliberately stays quiet when the // global config is readable. This gate is about the LAYOUT, and must diff --git a/crates/PROTOCOL.md b/crates/PROTOCOL.md index c07b936cc..f0ad7c964 100644 --- a/crates/PROTOCOL.md +++ b/crates/PROTOCOL.md @@ -85,6 +85,11 @@ an unnamed agent would escape: there it fails closed. ```jsonc { "type": "pong", "protocolVersion": 2 } +// While the Self Reports MCP listener is bound, a pong also carries +// "selfReport": { "instanceId": "", "port": 4319 } +// (optional and additive: older clients ignore it). The endpoint's MCP +// initialize returns the same id as serverInfo.instanceId, so a client can +// prove the HTTP port belongs to the daemon behind this socket. { "type": "hookResult", diff --git a/crates/failproofaid/src/server.rs b/crates/failproofaid/src/server.rs index 97e93cf5e..436ee3a1d 100644 --- a/crates/failproofaid/src/server.rs +++ b/crates/failproofaid/src/server.rs @@ -470,6 +470,12 @@ fn evaluate(request: ClientMessage, worker: &Worker) -> ServerMessage { match request { ClientMessage::Ping { .. } => ServerMessage::Pong { protocol_version: PROTOCOL_VERSION, + self_report: fpai_collect::self_report::listening().map(|port| { + fpai_ipc::SelfReportServer { + instance_id: fpai_collect::self_report::instance_id().to_string(), + port, + } + }), }, ClientMessage::Hook { hook_event, @@ -691,7 +697,8 @@ mod tests { assert_eq!( response, ServerMessage::Pong { - protocol_version: PROTOCOL_VERSION + protocol_version: PROTOCOL_VERSION, + self_report: None } ); } @@ -1042,7 +1049,8 @@ mod tests { assert_eq!( response, ServerMessage::Pong { - protocol_version: 1 + protocol_version: 1, + self_report: None } ); @@ -1223,7 +1231,8 @@ mod tests { assert_eq!( response, ServerMessage::Pong { - protocol_version: PROTOCOL_VERSION + protocol_version: PROTOCOL_VERSION, + self_report: None } ); }) @@ -1264,7 +1273,8 @@ mod tests { assert_eq!( response, ServerMessage::Pong { - protocol_version: PROTOCOL_VERSION + protocol_version: PROTOCOL_VERSION, + self_report: None } ); } diff --git a/crates/failproofaid/tests/daemon_e2e.rs b/crates/failproofaid/tests/daemon_e2e.rs index 67eba1017..9054361c9 100644 --- a/crates/failproofaid/tests/daemon_e2e.rs +++ b/crates/failproofaid/tests/daemon_e2e.rs @@ -176,11 +176,15 @@ fn real_binary_answers_ping_over_a_real_socket() { ) .unwrap(); let response: ServerMessage = read_message(&mut stream).unwrap(); - assert_eq!( - response, - ServerMessage::Pong { - protocol_version: PROTOCOL_VERSION - } + assert!( + matches!( + response, + ServerMessage::Pong { + protocol_version: PROTOCOL_VERSION, + .. + } + ), + "{response:?}" ); let status = daemon.terminate(); @@ -226,11 +230,15 @@ fn a_second_daemon_on_the_same_socket_refuses_to_start() { ) .unwrap(); let response: ServerMessage = read_message(&mut stream).unwrap(); - assert_eq!( - response, - ServerMessage::Pong { - protocol_version: PROTOCOL_VERSION - } + assert!( + matches!( + response, + ServerMessage::Pong { + protocol_version: PROTOCOL_VERSION, + .. + } + ), + "{response:?}" ); first.terminate(); @@ -256,11 +264,15 @@ fn a_fresh_daemon_can_bind_again_after_the_previous_one_shut_down_cleanly() { ) .unwrap(); let response: ServerMessage = read_message(&mut stream).unwrap(); - assert_eq!( - response, - ServerMessage::Pong { - protocol_version: PROTOCOL_VERSION - } + assert!( + matches!( + response, + ServerMessage::Pong { + protocol_version: PROTOCOL_VERSION, + .. + } + ), + "{response:?}" ); second.terminate(); @@ -442,11 +454,15 @@ fn a_fifo_log_after_an_unclean_exit_does_not_stall_startup() { ) .unwrap(); let response: ServerMessage = read_message(&mut stream).unwrap(); - assert_eq!( - response, - ServerMessage::Pong { - protocol_version: PROTOCOL_VERSION - } + assert!( + matches!( + response, + ServerMessage::Pong { + protocol_version: PROTOCOL_VERSION, + .. + } + ), + "{response:?}" ); assert!(daemon.terminate().success()); } diff --git a/crates/failproofaid/tests/self_report_e2e.rs b/crates/failproofaid/tests/self_report_e2e.rs index 1973a68b1..8fc7a49f5 100644 --- a/crates/failproofaid/tests/self_report_e2e.rs +++ b/crates/failproofaid/tests/self_report_e2e.rs @@ -73,7 +73,7 @@ fn wait(what: &str, predicate: impl Fn() -> bool) { } } -fn ping(daemon: &Daemon) { +fn ping(daemon: &Daemon) -> ServerMessage { let mut stream = UnixStream::connect(daemon.home.join("run/failproofaid.sock")).unwrap(); stream .set_read_timeout(Some(Duration::from_secs(2))) @@ -87,6 +87,24 @@ fn ping(daemon: &Daemon) { .unwrap(); let response: ServerMessage = read_message(&mut stream).unwrap(); assert!(matches!(response, ServerMessage::Pong { .. })); + response +} + +fn pong_self_report(daemon: &Daemon) -> Option { + match ping(daemon) { + ServerMessage::Pong { self_report, .. } => self_report, + other => panic!("{other:?}"), + } +} + +fn initialize(port: u16) -> Option { + reqwest::blocking::Client::new() + .post(format!("http://127.0.0.1:{port}/mcp")) + .header("Content-Type", "application/json") + .body(r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#) + .send() + .ok() + .and_then(|r| r.json::().ok()) } fn free_port() -> u16 { @@ -173,3 +191,45 @@ fn a_busy_self_report_port_never_costs_the_enforcement_socket() { ); drop(holder); } + +/// Two daemons with separate homes and one port: the second's bind fails. Its +/// pong must say it serves no MCP endpoint, and the first's pong must name the +/// instance that answers the port, so a client of the second never takes the +/// first's endpoint for its own. +#[test] +fn the_pong_names_the_daemon_that_holds_the_mcp_port() { + let port = free_port(); + let first = spawn(port); + wait("the first daemon's MCP endpoint", || { + initialize(port).is_some() + }); + wait("the first daemon's socket", || { + first.home.join("run/failproofaid.sock").exists() + }); + let served = initialize(port).unwrap(); + let id = served["result"]["serverInfo"]["instanceId"] + .as_str() + .expect("an instanceId") + .to_string(); + let mine = pong_self_report(&first).expect("the first daemon serves MCP"); + assert_eq!(mine.instance_id, id); + assert_eq!(mine.port, port); + + let second = spawn(port); + wait("the second daemon's busy-port warning", || { + second + .log + .lock() + .unwrap() + .contains("Self Reports MCP server off") + }); + wait("the second daemon's socket", || { + second.home.join("run/failproofaid.sock").exists() + }); + assert_eq!(pong_self_report(&second), None); + // The port still answers, as the first daemon. + assert_eq!( + initialize(port).unwrap()["result"]["serverInfo"]["instanceId"], + id.as_str() + ); +} diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index 93c320fcc..c2fa78ca1 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -23,8 +23,8 @@ use std::fs; use std::io::{self, Write}; use std::net::{Ipv4Addr, SocketAddr}; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use axum::Router; @@ -402,6 +402,31 @@ impl SettingsCache { } } +// ── This daemon's identity ─────────────────────────────────────────────────── + +/// Random per process, sent as `serverInfo.instanceId` in the MCP +/// `initialize` result and in the daemon's IPC `Pong`. The CLI points agents at +/// the HTTP endpoint only when the two agree: a socket ping and a port probe +/// can otherwise reach two different daemons (another user's, or another +/// FAILPROOFAI_HOME's whose bind won the port), and the report would then be +/// recorded and uploaded under that daemon's home and credentials. +pub fn instance_id() -> &'static str { + static ID: OnceLock = OnceLock::new(); + ID.get_or_init(crate::uploader::new_request_id) +} + +/// The port this process's MCP listener is bound to, 0 while none is. +static LISTENING_PORT: AtomicU32 = AtomicU32::new(0); + +/// The port [`spawn`]'s listener holds right now, or `None` when it never +/// bound (a busy port) or has stopped. The daemon's `Pong` carries it. +pub fn listening() -> Option { + match LISTENING_PORT.load(Ordering::SeqCst) { + 0 => None, + port => u16::try_from(port).ok(), + } +} + // ── The HTTP server ────────────────────────────────────────────────────────── struct Server { @@ -456,10 +481,12 @@ pub fn spawn( } }; tracing::info!(port, "Self Reports MCP server listening on 127.0.0.1"); + LISTENING_PORT.store(u32::from(port), Ordering::SeqCst); let _ = listening.send(true); if let Err(err) = serve(listener, home, Shutdown::from_daemon(shutdown)).await { tracing::warn!(%err, "Self Reports MCP server stopped"); } + LISTENING_PORT.store(0, Ordering::SeqCst); }); }) .inspect_err(|err| tracing::warn!(%err, "could not start the Self Reports MCP server")) @@ -653,7 +680,11 @@ impl Server { // stream to push the notification on. A client sees a // changed list on its next tools/list. "capabilities": {"tools": {"listChanged": false}}, - "serverInfo": {"name": SERVER_NAME, "version": env!("CARGO_PKG_VERSION")}, + "serverInfo": { + "name": SERVER_NAME, + "version": env!("CARGO_PKG_VERSION"), + "instanceId": instance_id(), + }, }); if let Some(text) = server_instructions(self.settings.current().as_ref()) { result["instructions"] = Value::String(text); @@ -685,6 +716,11 @@ impl Server { /// The fallback recording. A failure is logged and never reaches the agent: /// the call's answer is `Recorded.` whatever happens here. + /// + /// Nothing is recorded unless the settings file says enabled right now: a + /// client that listed the tool before it was turned off (or that never + /// listed it) can still send a call. Read from disk, not the cache, so a + /// disable is honoured on the very next call (as the stdio server does). fn record(&self, args: &Value, caller: &Caller) { let Some(agent) = caller .agent @@ -693,6 +729,9 @@ impl Server { else { return; }; + if !read_settings(&settings_path(&self.home)).is_some_and(|s| s.enabled) { + return; + } let report = Report::from_args(args); let event = fallback_event(&self.home, agent, caller.cwd.as_deref(), &report, now_ms()); if let Err(err) = write_event_file(&self.home, &[event]) { @@ -772,9 +811,15 @@ pub fn cwd_affinity(want: &str, have: Option<&str>) -> u8 { /// The session a report from `integration` belongs to, in hook activity /// within [`SESSION_LOOKBACK`] of `now_ms`, with the cwd its row had. Most /// specific first when `cwd` is known: the newest session in exactly that -/// directory, else in one above or below it, else the newest of that -/// integration anywhere. The CLI's stdio server (`selfReportFindSessionMatch`) -/// does the same. +/// directory, else in one above or below it. +/// +/// Never a cross-project guess. When `cwd` is unknown (an HTTP call carries +/// only `?agent=`) or no row is related to it, the newest row is taken only if +/// every row of that integration in the window has the same cwd, i.e. there is +/// one project to choose from; otherwise `None`, and the report is +/// `unattributed`. The installer registers every agent recorded here over +/// stdio, where the CLI knows the server's real cwd; this guards a +/// hand-written or older HTTP registration. pub fn find_session( home: &Path, integration: &str, @@ -800,6 +845,8 @@ pub fn find_session( } let oldest = now_ms - SESSION_LOOKBACK.as_millis() as i64; let mut best: Option<(u8, i64, String, Option)> = None; + // The distinct cwds seen, to tell one project from several. + let mut cwds: Vec> = Vec::new(); for file in files { let Ok(text) = read_tail(&file, 1024 * 1024) else { continue; @@ -814,6 +861,13 @@ pub fn find_session( if row.integration.as_deref() != Some(integration) || row.timestamp < oldest { continue; } + let row_cwd = row + .cwd + .as_deref() + .map(|c| c.trim_end_matches('/').to_string()); + if !cwds.contains(&row_cwd) { + cwds.push(row_cwd); + } let rank = cwd.map_or(0, |want| cwd_affinity(want, row.cwd.as_deref())); if best .as_ref() @@ -824,7 +878,11 @@ pub fn find_session( best = Some((rank, row.timestamp, session.to_string(), row.cwd.clone())); } } - best.map(|(_, _, session, cwd)| (session, cwd)) + match best { + Some((0, ..)) if cwds.len() > 1 => None, + Some((_, _, session, cwd)) => Some((session, cwd)), + None => None, + } } /// The last `max` bytes of a file, from the first whole line in them. @@ -1217,23 +1275,21 @@ mod tests { + "\n", ) .unwrap(); - assert_eq!( - find_session(&home, "openclaw", None, now), - Some(("s-page".to_string(), Some("/w/a".to_string()))) - ); + // No cwd and openclaw rows in /w/a and /w/b: two projects, no guess. + assert_eq!(find_session(&home, "openclaw", None, now), None); assert_eq!( find_session(&home, "openclaw", Some("/w/b"), now).map(|s| s.0), Some("s-older".to_string()) ); - // A descendant beats a newer unrelated row; no relation at all falls - // back to the newest session anywhere. + // A descendant beats a newer unrelated row; no relation at all, with + // rows from two projects, is not a guess at either. assert_eq!( find_session(&home, "openclaw", Some("/w/b/sub"), now), Some(("s-older".to_string(), Some("/w/b".to_string()))) ); assert_eq!( find_session(&home, "openclaw", Some("/elsewhere"), now), - Some(("s-page".to_string(), Some("/w/a".to_string()))) + None ); assert_eq!(find_session(&home, "goose", Some("/w/a"), now), None); assert_eq!(find_session(&home, "goose", None, now), None); @@ -1245,7 +1301,7 @@ mod tests { let event = fallback_event( &home, "openclaw", - None, + Some("/w/a"), &Report { category: "looping".into(), detail: "stuck".into(), @@ -1275,6 +1331,148 @@ mod tests { let _ = fs::remove_dir_all(home); } + fn server_for(home: &Path) -> Server { + Server { + home: home.to_path_buf(), + port: DEFAULT_PORT, + settings: SettingsCache::new(settings_path(home)), + } + } + + fn event_files(home: &Path) -> usize { + fs::read_dir(home.join("custom-agents/events")) + .map(|d| { + d.filter_map(Result::ok) + .filter(|e| e.path().extension().is_some_and(|x| x == "jsonl")) + .count() + }) + .unwrap_or(0) + } + + fn call_report(server: &Server, agent: &str) -> Value { + let caller = Caller { + agent: Some(agent.to_string()), + cwd: None, + }; + server + .dispatch( + json!({"jsonrpc": "2.0", "id": 7, "method": "tools/call", + "params": {"name": "report", "arguments": {"category": "looping", "detail": "d"}}}), + &caller, + ) + .unwrap() + } + + #[test] + fn an_http_report_is_recorded_only_while_the_settings_say_enabled() { + let home = temp_home("http-enabled"); + let server = server_for(&home); + let path = settings_path(&home); + // Missing settings: answered, not recorded. + let reply = call_report(&server, "copilot"); + assert_eq!(reply["result"]["content"][0]["text"], RESULT_TEXT); + assert_eq!(event_files(&home), 0, "missing settings"); + // Malformed settings. + fs::write(&path, "{not json").unwrap(); + call_report(&server, "copilot"); + assert_eq!(event_files(&home), 0, "malformed settings"); + // Disabled. + let mut off = enabled(default_categories(), None); + off.enabled = false; + write_settings(&path, &off).unwrap(); + let reply = call_report(&server, "copilot"); + assert_eq!(reply["result"]["isError"], false); + assert_eq!(event_files(&home), 0, "disabled settings"); + // Enabled: one event. + write_settings(&path, &enabled(default_categories(), None)).unwrap(); + call_report(&server, "copilot"); + assert_eq!(event_files(&home), 1, "enabled settings"); + // Disabled again, with the cache primed by the enabled read: honoured + // on the next call. + assert!(server.settings.current().unwrap().enabled); + write_settings(&path, &off).unwrap(); + call_report(&server, "copilot"); + assert_eq!(event_files(&home), 1, "disabled after enabled"); + // A hook-recorded agent is never recorded here. + write_settings(&path, &enabled(default_categories(), None)).unwrap(); + call_report(&server, "claude"); + assert_eq!(event_files(&home), 1, "claude is recorded by its hook"); + let _ = fs::remove_dir_all(home); + } + + #[test] + fn initialize_names_this_process() { + let home = temp_home("instance"); + let server = server_for(&home); + let reply = server + .dispatch( + json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}), + &Caller::default(), + ) + .unwrap(); + let info = &reply["result"]["serverInfo"]; + assert_eq!(info["name"], SERVER_NAME); + assert_eq!(info["instanceId"], instance_id()); + assert_eq!(instance_id().len(), 32); + assert_eq!(instance_id(), instance_id(), "stable for the process"); + let _ = fs::remove_dir_all(home); + } + + #[test] + fn no_cwd_is_attributed_only_within_one_project() { + let home = temp_home("one-project"); + let dir = home.join("hook-activity"); + fs::create_dir_all(&dir).unwrap(); + let now = 1_800_000_000_000_i64; + let row = |at: i64, session: &str, cwd: &str| { + json!({"timestamp": at, "eventType": "PreToolUse", "integration": "copilot", + "sessionId": session, "cwd": cwd, "toolName": "x", "decision": "allow"}) + .to_string() + }; + // One project (two sessions in it): the newest owns the report. + fs::write( + dir.join("current.jsonl"), + [ + row(now - 3000, "a-1", "/repo/a"), + row(now - 2000, "a-2", "/repo/a/"), + ] + .join("\n") + + "\n", + ) + .unwrap(); + assert_eq!( + find_session(&home, "copilot", None, now), + Some(("a-2".to_string(), Some("/repo/a/".to_string()))) + ); + // Then project B is active too: a report with no cwd is not given to + // B's (newer) session, nor to A's. + fs::write( + dir.join("current.jsonl"), + [ + row(now - 3000, "a-1", "/repo/a"), + row(now - 1000, "b-1", "/repo/b"), + ] + .join("\n") + + "\n", + ) + .unwrap(); + assert_eq!(find_session(&home, "copilot", None, now), None); + let report = Report { + category: "looping".into(), + detail: "d".into(), + }; + let event = fallback_event(&home, "copilot", None, &report, now); + assert_eq!(event["session_id"], UNATTRIBUTED_SESSION); + // A known cwd still picks its own project. + assert_eq!( + find_session(&home, "copilot", Some("/repo/a"), now).map(|s| s.0), + Some("a-1".to_string()) + ); + let event = fallback_event(&home, "copilot", Some("/repo/a"), &report, now); + assert_eq!(event["session_id"], "a-1"); + let _ = fs::remove_dir_all(home); + } + #[test] fn cwd_affinity_ranks_exact_then_related() { assert_eq!(cwd_affinity("/a/b", Some("/a/b/")), 2); diff --git a/crates/fpai-ipc/src/envelope.rs b/crates/fpai-ipc/src/envelope.rs index ae7808144..dfc759465 100644 --- a/crates/fpai-ipc/src/envelope.rs +++ b/crates/fpai-ipc/src/envelope.rs @@ -78,7 +78,18 @@ pub enum ClientMessage { #[serde(tag = "type", rename_all = "camelCase")] pub enum ServerMessage { #[serde(rename_all = "camelCase")] - Pong { protocol_version: u32 }, + Pong { + protocol_version: u32, + /// The Self Reports MCP server this daemon is serving, present only + /// while its loopback listener is bound. An optional, additive field + /// that older clients ignore. A client about to point agents at + /// `http://127.0.0.1:/mcp` compares this with the `instanceId` + /// the endpoint's `initialize` returns, which proves the port is held + /// by the daemon behind THIS socket and not by another daemon (another + /// user or another FAILPROOFAI_HOME) whose own bind won. + #[serde(default, skip_serializing_if = "Option::is_none")] + self_report: Option, + }, #[serde(rename_all = "camelCase")] HookResult { protocol_version: u32, @@ -109,6 +120,17 @@ pub enum ServerMessage { }, } +/// See [`ServerMessage::Pong`]. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct SelfReportServer { + /// Random per daemon process; the MCP `initialize` result carries the + /// same value as `serverInfo.instanceId`. + pub instance_id: String, + /// The loopback port the MCP listener bound. + pub port: u16, +} + impl ClientMessage { pub fn protocol_version(&self) -> u32 { match self { @@ -170,7 +192,9 @@ impl ServerMessage { /// checks for its own version accepts an answer from a newer daemon. pub fn with_protocol_version(mut self, version: u32) -> Self { match &mut self { - ServerMessage::Pong { protocol_version } + ServerMessage::Pong { + protocol_version, .. + } | ServerMessage::HookResult { protocol_version, .. } @@ -186,7 +210,9 @@ impl ServerMessage { pub fn protocol_version(&self) -> u32 { match self { - ServerMessage::Pong { protocol_version } => *protocol_version, + ServerMessage::Pong { + protocol_version, .. + } => *protocol_version, ServerMessage::HookResult { protocol_version, .. } => *protocol_version, @@ -300,6 +326,32 @@ mod tests { assert_eq!(decoded, msg); } + #[test] + fn a_pong_carries_the_self_report_server_only_when_there_is_one() { + let bare = ServerMessage::Pong { + protocol_version: PROTOCOL_VERSION, + self_report: None, + }; + let json = serde_json::to_value(&bare).unwrap(); + assert!(json.get("selfReport").is_none(), "{json}"); + // A pong from a daemon that predates the field still parses. + let old: ServerMessage = + serde_json::from_value(serde_json::json!({"type": "pong", "protocolVersion": 2})) + .unwrap(); + assert_eq!(old, bare); + let full = ServerMessage::Pong { + protocol_version: PROTOCOL_VERSION, + self_report: Some(SelfReportServer { + instance_id: "abc".into(), + port: 4319, + }), + }; + let json = serde_json::to_value(&full).unwrap(); + assert_eq!(json["selfReport"]["instanceId"], "abc"); + assert_eq!(json["selfReport"]["port"], 4319); + assert_eq!(serde_json::from_value::(json).unwrap(), full); + } + #[test] fn protocol_version_accessor_matches_every_variant() { assert_eq!( diff --git a/crates/fpai-ipc/src/lib.rs b/crates/fpai-ipc/src/lib.rs index af3d2e0f3..c0adea790 100644 --- a/crates/fpai-ipc/src/lib.rs +++ b/crates/fpai-ipc/src/lib.rs @@ -7,7 +7,7 @@ pub mod framing; pub mod peer; pub use envelope::{ - ClientMessage, MIN_PROTOCOL_VERSION, PROTOCOL_VERSION, ServerMessage, + ClientMessage, MIN_PROTOCOL_VERSION, PROTOCOL_VERSION, SelfReportServer, ServerMessage, is_supported_protocol_version, }; pub use framing::{FramingError, MAX_FRAME_LEN, read_message, write_message}; diff --git a/docs/reference/mcp.mdx b/docs/reference/mcp.mdx index 731de5d0d..65213e16c 100644 --- a/docs/reference/mcp.mdx +++ b/docs/reference/mcp.mdx @@ -126,7 +126,7 @@ Results go to the AI tool you connected, and that tool's provider handles them u | | Cloud MCP gateway | Local Self Reports server | | --- | --- | --- | -| Address | `https://gateway.befailproof.ai/mcp` | `http://127.0.0.1:4319/mcp` (served by `failproofaid`), or `failproofai mcp` over stdio | +| Address | `https://gateway.befailproof.ai/mcp` | `http://127.0.0.1:4319/mcp` (served by `failproofaid`, for Claude Code and Codex), or `failproofai mcp` over stdio | | Who adds it | You, in each client | failproofai, in every agent with failproofai hooks, while Self Reports is on | | What it offers | Your organization's data, with your permissions | One `report` tool an agent calls when it is stuck | | Sign-in | OAuth, one organization per connection | None. It answers only on `127.0.0.1` and refuses requests from web pages | diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index 119912e4e..34f7fb3c6 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -51,9 +51,9 @@ A report with a category that is not on the list is still recorded under the nam ## Agent support -failproofai registers one MCP server, named `failproofai`, in each agent's user-level MCP settings. When `failproofaid` is answering on the machine, the entry points at the daemon's local server, `http://127.0.0.1:4319/mcp` (set `FAILPROOFAI_SELF_REPORT_PORT` to move it). Otherwise it runs `failproofai mcp` over stdio. Every entry is marked as failproofai's, so removing it never touches a server you added. +failproofai registers one MCP server, named `failproofai`, in each agent's user-level MCP settings. For Claude Code and Codex, whose hooks record the report, the entry points at the daemon's local server, `http://127.0.0.1:4319/mcp` (set `FAILPROOFAI_SELF_REPORT_PORT` to move it), when `failproofaid` is serving it, and runs `failproofai mcp` over stdio otherwise. Every other agent always gets `failproofai mcp` over stdio, because its report is recorded by the server, which needs the agent's working directory to find the session (see below). Every entry is marked as failproofai's, so removing it never touches a server you added. -The transport is chosen when the entries are written, from a live check: the daemon must answer on its socket and its MCP endpoint must answer. When the daemon starts, it re-runs `failproofai self-report sync`, so agents move to HTTP. If the daemon stops, `failproofai self-report status` finds agents pointing at an endpoint that does not answer and moves them back to stdio. A running agent keeps the server it loaded at startup. +The transport is chosen when the entries are written, from a live check: the daemon behind this account's socket must answer, and the endpoint must answer as that same daemon (both carry the daemon's instance id). A port held by another daemon, for example another user's, or one whose own server could not bind the port, gives stdio. When the daemon starts, it re-runs `failproofai self-report sync`, so Claude Code and Codex move to HTTP. If the daemon stops, `failproofai self-report status` finds agents pointing at an endpoint that does not answer, or an agent the server records left on HTTP by an earlier version, and moves them to stdio. A running agent keeps the server it loaded at startup. Both transports send the model short server instructions in the MCP handshake: when to report, the category names, and your guidance. Some agents, Claude Code among them, load MCP tools only on demand. They add a server's instructions to the system prompt, though, so the model knows the tool exists. Copilot CLI passes a server's instructions to the model only for servers on its allowlist (or with `--allow-all-mcp-server-instructions`), so on Copilot the model may see only the tool's own description. @@ -61,7 +61,7 @@ Pi shows the model only a server's name by default. failproofai's Pi entry sets Where an agent's hooks see MCP tool calls and the server they belong to, the hook records the report. Where they do not, failproofai's MCP server records it. It attributes the report to that agent's newest session seen by the hooks in the last 6 hours: in the server's working directory if there is one, else in a directory above or below it, else anywhere on the machine. The agent the report is filed under comes from that session's own hook events. -Over HTTP, the server does not know the agent's working directory: the MCP entry is per user, not per project, so its URL carries only `?agent=`. So the report goes to that agent's newest session on the machine. If two sessions of one such agent run at the same time, in different projects, a report can land on the other session. Over stdio, the working directory narrows the match first. +These agents are registered over stdio for that reason: the MCP entry is per user, not per project, so an HTTP URL could carry only `?agent=`, and the server could not tell which project called. The daemon's HTTP server still answers an entry like that (one written by hand, or by an earlier version until the next sync), but it never guesses across projects: with no working directory, it files the report under that agent's newest session only when all of the agent's recent sessions are in one directory, and as `unattributed` otherwise. It records nothing while Self Reports is off. | Agent | Where the server is registered | Recorded by | | --- | --- | --- | diff --git a/sdk/python/CHANGELOG.md b/sdk/python/CHANGELOG.md index 4ee998511..763361666 100644 --- a/sdk/python/CHANGELOG.md +++ b/sdk/python/CHANGELOG.md @@ -23,8 +23,11 @@ see `scripts/changelog-section.py`. `integrations..self_report_tool()`, and the Pydantic AI capability adds it with `FailproofAI(self_report=True)` / `instrument("pydantic_ai", self_report=True)`. Categories and guidance come from - `$FAILPROOFAI_HOME/self-report.json`, else six defaults. Still no runtime - dependencies. + `$FAILPROOFAI_HOME/self-report.json`, else six defaults. A report with no + session bound matches an open tool call only within one session (never the + newest of several), and open calls are tracked per session. The CrewAI tool is + never cached and runs in the caller's context on CrewAI's async path. Still no + runtime dependencies. ### Dependencies diff --git a/sdk/python/failproofai_sdk/_events.py b/sdk/python/failproofai_sdk/_events.py index 4ef59d90e..4235ab07e 100644 --- a/sdk/python/failproofai_sdk/_events.py +++ b/sdk/python/failproofai_sdk/_events.py @@ -298,11 +298,14 @@ class EventNamespace: def __init__(self, writer) -> None: self._writer = writer self._pending: dict[str, datetime] = {} - # tool_call_id -> (session_id, agent_id, tool_name) for every tool_use - # not yet closed by its tool_result. Read only by `self_report`, so a - # report made from inside a tool the caller already brackets lands on - # that tool's session and agent. Same cap and eviction as `_pending`. - self._open_tools: dict[str, tuple[str, str, str]] = {} + # _tool_key(session_id, tool_call_id) -> (session_id, agent_id, + # tool_name, tool_call_id) for every tool_use not yet closed by its + # tool_result. Keyed by session like `_pending`: two sessions may reuse + # one call id, and a bare key let the second replace (and its result + # remove) the first's entry. Read only by `self_report`, so a report + # made from inside a tool the caller already brackets lands on that + # tool's session and agent. Same cap and eviction as `_pending`. + self._open_tools: dict[str, tuple[str, str, str, str]] = {} def _track_pending(self, key: str, ts: datetime) -> None: # Evicting has to tolerate another thread doing the same thing, because @@ -337,7 +340,7 @@ def _track_pending(self, key: str, ts: datetime) -> None: self._pending.pop(oldest, None) # may already be gone self._pending[key] = ts - def _track_open_tool(self, tool_call_id: str, entry: "tuple[str, str, str]") -> None: + def _track_open_tool(self, key: str, entry: "tuple[str, str, str, str]") -> None: # Tolerant for the reasons spelled out in `_track_pending`. if len(self._open_tools) >= _PENDING_CAP: try: @@ -346,8 +349,8 @@ def _track_open_tool(self, tool_call_id: str, entry: "tuple[str, str, str]") -> pass else: self._open_tools.pop(oldest, None) - self._open_tools.pop(tool_call_id, None) # re-insert at the end: newest last - self._open_tools[tool_call_id] = entry + self._open_tools.pop(key, None) # re-insert at the end: newest last + self._open_tools[key] = entry def _report_identity( self, tool_call_id: "str | None", agent_id: "str | None" @@ -357,7 +360,9 @@ def _report_identity( Most specific first, within the ambient session when one is bound: the open `tool_use` with this `tool_call_id`; then the newest open `tool_use` of the report tool itself; then the enclosing scope; then - `"unattributed"` with one warning. Never raises: a report is evidence, + `"unattributed"` with one warning. With no ambient session, an open + `tool_use` is used only when every candidate is in one session: the + newest of several sessions would be a guess. Never raises: a report is evidence, and losing it to a missing scope is the worse outcome. The third item is the `tool_call_id` to record: the caller's, else the @@ -369,20 +374,24 @@ def _report_identity( ambient = _context.session_id() try: - open_tools = list(self._open_tools.items()) + open_tools = list(self._open_tools.values()) except RuntimeError: # resized under us by another thread open_tools = [] - candidates = [ - (call_id, entry) for call_id, entry in open_tools - if ambient is None or entry[0] == ambient - ] + candidates = [e for e in open_tools if ambient is None or e[0] == ambient] + + def unambiguous(found: "list[tuple[str, str, str, str]]") -> "tuple[str, str, str, str] | None": + if not found or (ambient is None and len({e[0] for e in found}) > 1): + return None + return found[-1] + match = None if tool_call_id is not None: - match = next(((c, e) for c, e in candidates if c == tool_call_id), None) + match = unambiguous([e for e in candidates if e[3] == tool_call_id]) if match is None: - match = next(((c, e) for c, e in reversed(candidates) if is_self_report_tool(e[2])), None) + match = unambiguous([e for e in candidates if is_self_report_tool(e[2])]) if match is not None: - call_id, entry = match + entry = match + call_id = entry[3] return ( entry[0], agent_id if agent_id is not None else entry[1], @@ -407,11 +416,11 @@ def _open_report_call_id(self, session_id: str) -> "str | None": from failproofai_sdk._self_report import is_self_report_tool try: - open_tools = list(self._open_tools.items()) + open_tools = list(self._open_tools.values()) except RuntimeError: # resized under us by another thread return None return next( - (c for c, e in reversed(open_tools) if e[0] == session_id and is_self_report_tool(e[2])), + (e[3] for e in reversed(open_tools) if e[0] == session_id and is_self_report_tool(e[2])), None, ) @@ -461,7 +470,7 @@ def tool_use( session_id, agent_id = _resolve_identity(session_id, agent_id) ts = self._now() self._track_pending(_tool_key(session_id, tool_call_id), ts) - self._track_open_tool(tool_call_id, (session_id, agent_id, tool_name)) + self._track_open_tool(_tool_key(session_id, tool_call_id), (session_id, agent_id, tool_name, tool_call_id)) self._writer.submit( ToolUseEvent( timestamp=self._fmt_ts(ts), @@ -491,7 +500,7 @@ def tool_result( session_id, agent_id = _resolve_identity(session_id, agent_id) ts = self._now() start_ts = self._pending.pop(_tool_key(session_id, tool_call_id), None) - self._open_tools.pop(tool_call_id, None) + self._open_tools.pop(_tool_key(session_id, tool_call_id), None) duration_ms = _measured_duration_ms(start_ts, ts) self._writer.submit( ToolResultEvent( diff --git a/sdk/python/failproofai_sdk/integrations/crewai.py b/sdk/python/failproofai_sdk/integrations/crewai.py index a08dbad92..2fdc28e6f 100644 --- a/sdk/python/failproofai_sdk/integrations/crewai.py +++ b/sdk/python/failproofai_sdk/integrations/crewai.py @@ -1727,6 +1727,41 @@ def _report_call_id() -> "str | None": return None +def _never_cache(_args=None, _result=None) -> bool: + """The report tool's `cache_function`: every call must run and record.""" + return False + + +_context_tool_classes: dict = {} + + +def _context_preserving(structured): + """`structured` with an `ainvoke` that runs the tool in the caller's context. + + CrewAI before 1.15 runs a sync tool's function through `run_in_executor` + without copying the context, so the report tool's `_run` saw an empty + CrewAI event stack in a fresh worker thread and could take another, + newer crew's identity. `asyncio.to_thread` copies the context (what 1.15+ + does itself). Same validation and usage counting: it calls the tool's own + sync `invoke`. Left unchanged if the instance cannot take the subclass. + """ + import asyncio + + base = type(structured) + cls = _context_tool_classes.get(base) + if cls is None: + async def ainvoke(self, input, config=None, **kwargs): # noqa: A002 - CrewAI's name + return await asyncio.to_thread(self.invoke, input, config, **kwargs) + + cls = type(base.__name__, (base,), {"__module__": __name__, "ainvoke": ainvoke}) + _context_tool_classes[base] = cls + try: + object.__setattr__(structured, "__class__", cls) + except TypeError: + logger.debug("failproofai_sdk: could not wrap CrewAI's structured tool", exc_info=True) + return structured + + def self_report_tool( *, session_id: "str | None" = None, @@ -1743,6 +1778,7 @@ def self_report_tool( read when the tool is built. Identity: the factory's `session_id` / `agent_id`, else the crew run this adapter is recording (when instrumented), else the ambient scope, else "unattributed". Always returns `"Recorded."`. + Never cached, and run in the caller's context on CrewAI's async path. """ from crewai.tools import BaseTool @@ -1767,6 +1803,9 @@ def _run(self, category, detail) -> str: _run.__annotations__ = _self_report.framework_signature(names) + def to_structured_tool(self): + return _context_preserving(BaseTool.to_structured_tool(self)) + tool_cls = type( "FailproofAIReportTool", (BaseTool,), @@ -1777,6 +1816,9 @@ def _run(self, category, detail) -> str: "name": spec["name"], "description": spec["description"], "_run": _run, + "to_structured_tool": to_structured_tool, }, ) - return tool_cls() + # Never cached: CrewAI's cache would answer a repeated report (same + # arguments) with the stored "Recorded." and the report would not be made. + return tool_cls(cache_function=_never_cache) diff --git a/sdk/python/skill/SKILL.md b/sdk/python/skill/SKILL.md index ac5488f0a..2b47b39f8 100644 --- a/sdk/python/skill/SKILL.md +++ b/sdk/python/skill/SKILL.md @@ -166,6 +166,9 @@ recipe — `references/typescript.md` → *The contract, in TypeScript* and *Shu Nothing bound and nothing passed raises `TypeError` naming the fix — never a silent emit, because ingest skips an event with no session and answers `200`. + The one exception is `self_report()`: a report is evidence, so with no + session it is recorded under `session_id="unattributed"` (one warning per + process) instead of raising. The other 15 methods raise. Two more shapes raise, for the same reason: diff --git a/sdk/python/skill/references/integration.md b/sdk/python/skill/references/integration.md index 6c707ab32..2fa650ff1 100644 --- a/sdk/python/skill/references/integration.md +++ b/sdk/python/skill/references/integration.md @@ -94,6 +94,11 @@ fixes. That is deliberate: the alternative is dropping the event silently, and this SDK already asks you to debug enough invisible failures. `agent_id` never raises — it is a label, and it falls back to `"main"`. +`self_report()` is the exception: with no session bound and none passed it +records the report under `session_id="unattributed"` and logs one warning per +process, because losing a report to a missing scope is worse than filing it +unattributed. Every other event method raises as above. + ## Don't use a module global The shortcut the scopes exist to replace, because it breaks silently: diff --git a/sdk/python/tests/integrations/test_crewai.py b/sdk/python/tests/integrations/test_crewai.py index d7bd1cfa1..7b4fd8980 100644 --- a/sdk/python/tests/integrations/test_crewai.py +++ b/sdk/python/tests/integrations/test_crewai.py @@ -1341,6 +1341,50 @@ def test_records_on_the_instrumented_crew_agent(self, instrumented, emitted): (use,) = [e for e in events if e["type"] == "tool_use" and e["tool_name"] == "failproofai_report"] assert use["tool_call_id"] and report["tool_call_id"] == use["tool_call_id"] + def test_is_never_cached(self, emitted): + from failproofai_sdk.integrations.crewai import self_report_tool + + tool = self_report_tool() + args = {"category": "looping", "detail": "same"} + assert tool.cache_function(args, "Recorded.") is False + assert tool.to_structured_tool().cache_function(args, "Recorded.") is False + + def test_async_invoke_runs_in_the_callers_context(self, emitted): + import asyncio + import contextvars + import threading + + from failproofai_sdk.integrations.crewai import self_report_tool + + seen = [] + probe = contextvars.ContextVar("probe", default=None) + tool = self_report_tool() + structured = tool.to_structured_tool() + # Its own ainvoke, not CrewAI's: CrewAI < 1.15 hands a sync tool to + # run_in_executor without the caller's context. + from crewai.tools.structured_tool import CrewStructuredTool + + assert isinstance(structured, CrewStructuredTool) + assert type(structured).ainvoke is not CrewStructuredTool.ainvoke + original = structured.func + + def spy(**kw): + seen.append((probe.get(), threading.current_thread() is threading.main_thread())) + return original(**kw) + + structured.func = spy + + async def call(): + probe.set("caller") + with failproofai_sdk.session("crew-async"): + return await structured.ainvoke({"category": "looping", "detail": "d"}) + + assert asyncio.run(call()) == "Recorded." + # Off the loop's thread, with the caller's context (and its session). + assert seen == [("caller", False)] + (report,) = [e for e in emitted() if e["type"] == "self_report"] + assert report["session_id"] == "crew-async" + def test_ambient_and_explicit_identity(self, emitted): from failproofai_sdk.integrations.crewai import self_report_tool diff --git a/sdk/python/tests/test_self_report.py b/sdk/python/tests/test_self_report.py index a9b89dcf4..0406f970d 100644 --- a/sdk/python/tests/test_self_report.py +++ b/sdk/python/tests/test_self_report.py @@ -154,6 +154,42 @@ def test_a_closed_or_foreign_session_tool_use_is_not_used(recorded): assert [r["session_id"] for r in reports] == ["s-mine", "s-mine"] +def test_two_sessions_reusing_one_call_id_keep_their_own_open_calls(recorded): + ev = _runtime.event + ev.tool_use(session_id="s-1", agent_id="a-1", tool_name="failproofai_report", tool_call_id="call_0") + ev.tool_use(session_id="s-2", agent_id="a-2", tool_name="failproofai_report", tool_call_id="call_0") + # Each session's report finds its own call, not the other's. + with fp.session("s-1"): + fp.self_report("looping", "one", tool_call_id="call_0") + with fp.session("s-2"): + fp.self_report("looping", "two", tool_call_id="call_0") + # Closing s-1's call leaves s-2's open. + ev.tool_result(session_id="s-1", agent_id="a-1", tool_name="failproofai_report", tool_call_id="call_0") + with fp.session("s-2"): + fp.self_report("looping", "after", tool_call_id="call_0") + with fp.session("s-1"): + fp.self_report("looping", "closed", tool_call_id="call_0") + reports = [e for e in recorded if e["type"] == "self_report"] + assert [(r["detail"], r["session_id"], r["agent_id"]) for r in reports] == [ + ("one", "s-1", "a-1"), ("two", "s-2", "a-2"), ("after", "s-2", "a-2"), ("closed", "s-1", "main"), + ] + + +def test_with_nothing_bound_open_calls_in_two_sessions_are_not_guessed(recorded): + ev = _runtime.event + ev.tool_use(session_id="s-x", agent_id="a-x", tool_name="failproofai_report", tool_call_id="cx") + ev.tool_use(session_id="s-y", agent_id="a-y", tool_name="failproofai_report", tool_call_id="cy") + ev.tool_use(session_id="s-y", agent_id="a-y", tool_name="failproofai_report", tool_call_id="shared") + ev.tool_use(session_id="s-x", agent_id="a-x", tool_name="failproofai_report", tool_call_id="shared") + fp.self_report("looping", "no id") # newest of two sessions: no guess + fp.self_report("looping", "shared id", tool_call_id="shared") # id open in two sessions + fp.self_report("looping", "unique id", tool_call_id="cy") # one candidate: used + reports = [e for e in recorded if e["type"] == "self_report"] + assert [(r["detail"], r["session_id"]) for r in reports] == [ + ("no id", "unattributed"), ("shared id", "unattributed"), ("unique id", "s-y"), + ] + + def test_written_to_the_spool_by_the_real_writer(tmp_path): with fp.session("disk"): fp.self_report("looping", "on disk") diff --git a/sdk/typescript/CHANGELOG.md b/sdk/typescript/CHANGELOG.md index 6f937b242..b3f83c37c 100644 --- a/sdk/typescript/CHANGELOG.md +++ b/sdk/typescript/CHANGELOG.md @@ -20,7 +20,11 @@ section is missing or empty is refused before anything is built. Edge build. Categories and guidance come from `$FAILPROOFAI_HOME/self-report.json` (`selfReportSettings()`), with the six defaults when it is missing or disabled. A report made inside a framework's tool loop joins the agent whose loop called - it, and never throws for want of a session. + it, and never throws for want of a session; with no scope it joins an open + call only when all candidates are in one session. The `/ai` tool carries both + schema keys for a `module` passed in, and the Edge `/langchain` tool builds a + real LangChain tool with a `module` passed in (the tool needs + `@langchain/core` 0.3.44 or later). ### Fixes diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index 5ddb3993e..09cb6b555 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -457,7 +457,7 @@ With a framework, add the ready-made tool from its subpath: import { selfReportTool } from "@failproofai/sdk/ai"; // Vercel AI SDK 4–7 await generateText({ model, prompt, tools: { failproofai_report: selfReportTool(), ...tools } }); -import { selfReportTool } from "@failproofai/sdk/langchain"; // @langchain/core >=0.3 +import { selfReportTool } from "@failproofai/sdk/langchain"; // @langchain/core >=0.3.44 createReactAgent({ llm, tools: [selfReportTool(), ...tools] }); import { selfReportTool } from "@failproofai/sdk/mastra"; // createTool + your zod @@ -503,8 +503,12 @@ other tool format. tool needs no zod and works on v7, which cannot be `require`d, by building the `jsonSchema()` object itself. The LangChain, Mastra and LlamaIndex tools return `unknown` unless you name the type, as above. +- **LangChain needs `@langchain/core` 0.3.44 or later for this tool**: older + 0.3 releases read a tool's schema only as zod and send the model an empty one. - **Edge builds** offer the same spec and tools, which answer `Recorded.` and - record nothing. + record nothing. The Edge LangChain tool is a real LangChain tool when you pass + `{ module: await import("@langchain/core/tools") }`; without it, it is a plain + named-tool object that `@langchain/core` 0.3.52 and later recognise. --- diff --git a/sdk/typescript/src/edge/langchain.ts b/sdk/typescript/src/edge/langchain.ts index 6f1b4ca2d..49b1c314d 100644 --- a/sdk/typescript/src/edge/langchain.ts +++ b/sdk/typescript/src/edge/langchain.ts @@ -2,7 +2,7 @@ import { noopAdapter } from "./adapter.js"; import { notice } from "./notice.js"; -import { inertNamedTool } from "./self-report-tool.js"; +import { inertLangChainTool, type EdgeLangChainToolsModule } from "./self-report-tool.js"; export const SESSION_METADATA_KEY = "failproofai_sdk_session_id"; @@ -18,8 +18,12 @@ export function langchainHandler(): Record { export const adapter = noopAdapter("langchain"); -/** The Self Reports tool, answering `Recorded.` and recording nothing. */ -export function selfReportTool(...options: unknown[]): T { - void options; - return inertNamedTool(); +/** + * The Self Reports tool, answering `Recorded.` and recording nothing. Pass the + * application's `@langchain/core/tools` as `module` to get a real LangChain + * structured tool (recognised by every `@langchain/core` from 0.3.44); without + * it, a plain named-tool object that 0.3.52 and later recognise. + */ +export function selfReportTool(options?: { module?: EdgeLangChainToolsModule } & Record): T { + return inertLangChainTool(options?.module); } diff --git a/sdk/typescript/src/edge/self-report-tool.ts b/sdk/typescript/src/edge/self-report-tool.ts index a6885628c..6c5acef9d 100644 --- a/sdk/typescript/src/edge/self-report-tool.ts +++ b/sdk/typescript/src/edge/self-report-tool.ts @@ -53,3 +53,29 @@ export function inertNamedTool(): T { execute: inertAnswer, } as T; } + +/** The `@langchain/core/tools` exports the Edge LangChain tool can build with. */ +export interface EdgeLangChainToolsModule { + tool?: (func: never, fields: never) => unknown; + DynamicStructuredTool?: new (fields: never) => unknown; +} + +/** + * The LangChain report tool for runtimes with no filesystem. Handed the + * application's `@langchain/core/tools` (`{ module: await import(...) }`), it is + * a real structured tool built by that module, which every `@langchain/core` + * from 0.3.44 converts for the model and runs like any other. Without one it is + * the plain named-tool object: `@langchain/core` 0.3.52 and later recognise it + * as a tool (name + JSON Schema); older ones would pass it to the model as it + * is, so pass the module there. No framework is ever imported here. + */ +export function inertLangChainTool(module?: EdgeLangChainToolsModule): T { + const spec = inertSpec(); + const fields = { name: SELF_REPORT_TOOL_NAME, description: spec.description, schema: spec.inputSchema }; + const func = () => inertAnswer(); + if (typeof module?.tool === "function") return module.tool(func as never, fields as never) as T; + if (typeof module?.DynamicStructuredTool === "function") { + return new module.DynamicStructuredTool({ ...fields, func } as never) as T; + } + return inertNamedTool(); +} diff --git a/sdk/typescript/src/events.ts b/sdk/typescript/src/events.ts index becb6d96a..c5f87c411 100644 --- a/sdk/typescript/src/events.ts +++ b/sdk/typescript/src/events.ts @@ -906,13 +906,17 @@ export class EventNamespace { * The newest open tool call a report belongs to: the one with this id, else * one named like the report tool (LlamaIndex gives a tool no id, and an * adapter may have recorded its own id rather than the model's). Inside a - * scope only that scope's session is searched. + * scope only that scope's session is searched. With no scope, a match is + * used only when every candidate is in one session: picking the newest of + * several sessions (two concurrent LlamaIndex runs, each with a report call + * open) would be a guess, and the report goes the unattributed way instead. */ private openToolFor(toolCallId: string | undefined, preferSession: string | null): OpenLeaf | undefined { const leaves = [...this.openLeaves.values()].filter((leaf) => leaf.kind === "tool").reverse(); const pick = (matches: (leaf: OpenLeaf) => boolean): OpenLeaf | undefined => { const found = leaves.filter(matches); - return preferSession === null ? found[0] : found.find((leaf) => leaf.sessionId === preferSession); + if (preferSession !== null) return found.find((leaf) => leaf.sessionId === preferSession); + return new Set(found.map((leaf) => leaf.sessionId)).size === 1 ? found[0] : undefined; }; return ( (toolCallId !== undefined ? pick((leaf) => leaf.id === toolCallId) : undefined) ?? diff --git a/sdk/typescript/src/integrations/self-report-tools.ts b/sdk/typescript/src/integrations/self-report-tools.ts index 00d56c444..5ea9827e4 100644 --- a/sdk/typescript/src/integrations/self-report-tools.ts +++ b/sdk/typescript/src/integrations/self-report-tools.ts @@ -83,16 +83,21 @@ function handMadeJsonSchema(schema: Record): Record(options: AiSelfReportToolOptions = {}): T { const spec = selfReportSpec(); - const major = versionTuple("ai")?.[0]; + const resolved = versionTuple("ai")?.[0]; // v4–v6 ship CommonJS; v7 does not, and a `require` of it would print // Node's require(esm) warning in the customer's process for nothing. - const ai = options.module ?? (major !== undefined && major <= 6 ? tryRequire("ai") : null); + const ai = options.module ?? (resolved !== undefined && resolved <= 6 ? tryRequire("ai") : null); + // The resolved `ai` says nothing about a module the caller passed in (an + // application can resolve v6 and hand over a v4 copy), so its version is + // unknown and the definition carries both schema keys. + const major = options.module ? undefined : resolved; const schema = typeof ai?.jsonSchema === "function" ? ai.jsonSchema(spec.inputSchema as never) diff --git a/sdk/typescript/test/self-report-ai-module.test.ts b/sdk/typescript/test/self-report-ai-module.test.ts new file mode 100644 index 000000000..33d1c6eba --- /dev/null +++ b/sdk/typescript/test/self-report-ai-module.test.ts @@ -0,0 +1,44 @@ +/** + * The AI SDK report tool picks its schema key from the `ai` version this + * package resolves only when it builds with that copy. A module passed in may + * be another major (an application resolving v6 can hand over a v4 copy), so + * its definition carries both keys. + */ +import { describe, expect, it, vi } from "vitest"; + +const resolved = vi.hoisted(() => ({ major: 6 })); +vi.mock("../src/integrations/compat.js", async (orig) => { + const real = await orig(); + return { + ...real, + versionTuple: (pkg: string) => (pkg === "ai" ? [resolved.major, 0, 0] : real.versionTuple(pkg)), + }; +}); + +import { selfReportTool as aiTool } from "../src/integrations/ai.js"; + +type Def = { inputSchema?: unknown; parameters?: unknown }; + +describe("the AI SDK report tool's schema key", () => { + it("follows the resolved major when it builds with the resolved copy", () => { + resolved.major = 6; + const v6 = aiTool(); + expect(v6.inputSchema).toBeDefined(); + expect(v6.parameters).toBeUndefined(); + resolved.major = 4; + const v4 = aiTool(); + expect(v4.parameters).toBeDefined(); + expect(v4.inputSchema).toBeUndefined(); + }); + + it("carries both keys for a module passed in, whatever major resolves here", () => { + for (const major of [4, 6]) { + resolved.major = major; + // An AI SDK 4 `tool()` returns the definition unchanged. + const v4Module = { tool: (d: unknown) => d, jsonSchema: (s: unknown) => ({ schemaOf: s }) }; + const built = aiTool({ module: v4Module }); + expect(built.parameters, `resolved v${major}`).toBeDefined(); + expect(built.inputSchema).toBe(built.parameters); + } + }); +}); diff --git a/sdk/typescript/test/self-report.test.ts b/sdk/typescript/test/self-report.test.ts index aec6da1b0..ef6e7ab8b 100644 --- a/sdk/typescript/test/self-report.test.ts +++ b/sdk/typescript/test/self-report.test.ts @@ -171,29 +171,32 @@ describe("event.selfReport and selfReport()", () => { }); it("joins the open tool call it was made from, by id, even outside any scope", async () => { + const ns = new EventNamespace(runtime.writer); await session({ sessionId: "framework-run" }, () => agent("weather-agent", () => { - failproofai.event.toolUse({ toolName: "failproofai_report", toolCallId: "call-7" }); + ns.toolUse({ toolName: "failproofai_report", toolCallId: "call-7" }); }), ); - failproofai.selfReport("looping", "d", { toolCallId: "call-7" }); + ns.selfReport("looping", "d", { toolCallId: "call-7" }); const [report] = await reports(); expect(report).toMatchObject({ session_id: "framework-run", agent_id: "weather-agent", tool_call_id: "call-7" }); }); it("joins an open report-tool call by name when there is no id", async () => { + const ns = new EventNamespace(runtime.writer); await session({ sessionId: "s2" }, () => - agent("reporter", () => failproofai.event.toolUse({ toolName: "failproofai_report", toolCallId: "own-id" })), + agent("reporter", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "own-id" })), ); - failproofai.selfReport("looping", "d"); + ns.selfReport("looping", "d"); expect((await reports())[0]).toMatchObject({ session_id: "s2", agent_id: "reporter", tool_call_id: "own-id" }); }); it("keeps the caller's call id over the matched tool call's", async () => { + const ns = new EventNamespace(runtime.writer); await session({ sessionId: "s3" }, () => - agent("reporter", () => failproofai.event.toolUse({ toolName: "failproofai_report", toolCallId: "adapter-id" })), + agent("reporter", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "adapter-id" })), ); - failproofai.selfReport("looping", "d", { toolCallId: "model-id" }); + ns.selfReport("looping", "d", { toolCallId: "model-id" }); expect((await reports())[0]).toMatchObject({ session_id: "s3", tool_call_id: "model-id" }); }); @@ -213,6 +216,31 @@ describe("event.selfReport and selfReport()", () => { expect(report).toMatchObject({ session_id: "mine" }); }); + it("with no scope, never picks among open report calls of different sessions by recency", async () => { + const ns = new EventNamespace(runtime.writer); + quietLogger(); + // Two concurrent runs (LlamaIndex gives its tool no id and binds no scope), + // each with a report-tool call open. + await session({ sessionId: "run-a" }, () => + agent("a", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "a-1" })), + ); + await session({ sessionId: "run-b" }, () => + agent("b", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "b-1" })), + ); + ns.selfReport("looping", "no id"); + // An id open in both sessions is ambiguous too; one open in only one is not. + await session({ sessionId: "run-a" }, () => ns.toolUse({ toolName: "x", toolCallId: "dup" })); + await session({ sessionId: "run-b" }, () => ns.toolUse({ toolName: "x", toolCallId: "dup" })); + ns.selfReport("looping", "dup id", { toolCallId: "dup" }); + ns.selfReport("looping", "unique id", { toolCallId: "a-1" }); + const recorded = await reports(); + expect(recorded.map((e) => [e.detail, e.session_id])).toEqual([ + ["no id", UNATTRIBUTED_SESSION], + ["dup id", UNATTRIBUTED_SESSION], + ["unique id", "run-a"], + ]); + }); + it("files a report with no session under unattributed and warns once, never throwing", async () => { const warn = quietLogger(); const namespace = new EventNamespace(runtime.writer); @@ -537,4 +565,22 @@ describe("the edge build", () => { } expect(await reports()).toEqual([]); }); + + it("builds a real LangChain tool with the module it is handed, still recording nothing", async () => { + const tool = vi.fn((func: (input: unknown) => Promise, fields: Record) => ({ func, fields })); + const built = edgeLangchain.selfReportTool<{ func: (i: unknown) => Promise; fields: Record }>({ + module: { tool: tool }, + }); + expect(tool).toHaveBeenCalledTimes(1); + expect(built.fields).toEqual({ name: "failproofai_report", description: DEFAULT_DESCRIPTION, schema: DEFAULT_SCHEMA }); + expect(await built.func({ category: "looping", detail: "d" })).toBe("Recorded."); + class DynamicStructuredTool { + constructor(readonly fields: Record) {} + } + const viaClass = edgeLangchain.selfReportTool({ module: { DynamicStructuredTool: DynamicStructuredTool } }); + expect(viaClass).toBeInstanceOf(DynamicStructuredTool); + expect(viaClass.fields).toMatchObject({ name: "failproofai_report", schema: DEFAULT_SCHEMA }); + expect(await (viaClass.fields.func as () => Promise)()).toBe("Recorded."); + expect(await reports()).toEqual([]); + }); }); diff --git a/src/hooks/daemon-client.ts b/src/hooks/daemon-client.ts index b61690342..1d5ea7b69 100644 --- a/src/hooks/daemon-client.ts +++ b/src/hooks/daemon-client.ts @@ -173,20 +173,33 @@ export async function daemonAcceptsConnections( }); } +/** The Self Reports MCP server a daemon's pong names (see crates/PROTOCOL.md). */ +export interface DaemonSelfReportServer { + instanceId: string; + port: number; +} + /** - * Whether a daemon answers a `ping` with a `pong` within `responseTimeoutMs`. - * - * Unlike `daemonSocketPresent()` this proves a live daemon: a socket file left - * behind by a daemon that was killed hard refuses the connection. Used where a - * stale answer writes something lasting (the Self Reports transport choice), - * never on the hook path. + * The Self Reports MCP server the daemon behind this home's socket is serving, + * from its pong (a live daemon: a socket file left by a hard-killed one + * refuses the connection). Used where a stale answer writes something lasting + * (the Self Reports transport choice), never on the hook path. `null` when no + * daemon answers, when its MCP listener is not bound (a busy port), or when the + * daemon predates the field. The endpoint's + * MCP `initialize` carries the same `instanceId`, which is how a caller proves + * the HTTP port belongs to this daemon and not to another one. */ -export async function daemonAnswersPing(responseTimeoutMs = 1000): Promise { +export async function daemonSelfReportServer(responseTimeoutMs = 1000): Promise { const attempt = await attemptDaemonRequest( (protocolVersion) => ({ type: "ping", protocolVersion }), { responseTimeoutMs }, ); - return attempt.ok && attempt.message.type === "pong"; + if (!attempt.ok || attempt.message.type !== "pong") return null; + const sr = attempt.message.selfReport as Record | undefined; + if (!sr || typeof sr !== "object") return null; + const { instanceId, port } = sr; + if (typeof instanceId !== "string" || instanceId === "" || typeof port !== "number" || !Number.isInteger(port)) return null; + return { instanceId, port }; } function socketPath(): string { diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index b77d816ce..6c61299cd 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -803,7 +803,14 @@ export async function evaluateHookEvent( // file it under the one name before anything else reads the tool name. // Cursor's preToolUse names one `MCP:report` with no server; only a payload // that also names the server (`mcp_server_name: "failproofai"`) is ours. - if (cli === "cursor" && isSelfReportCursorCall(parsed)) { + // + // For Cursor that server check is the ONLY way a call becomes ours: a + // payload naming another server (or none) keeps its own tool name even + // when that name is one of our qualified spellings, and never reaches the + // short-circuit below. Otherwise another server's tool could be named + // `mcp__failproofai__report` and skip every policy. + const cursorSelfReport = cli === "cursor" && isSelfReportCursorCall(parsed); + if (cursorSelfReport) { parsed.tool_name = SELF_REPORT_MCP_TOOL_NAME; } // Antigravity's lazy MCP path wraps the call in `call_mcp_tool`; unwrap it @@ -816,7 +823,10 @@ export async function evaluateHookEvent( } } const rawToolName = parsed.tool_name as string | undefined; - const canonicalToolName = canonicalizeToolName(rawToolName, cli); + const canonicalToolName = + cli === "cursor" && !cursorSelfReport && isSelfReportToolName(rawToolName) + ? rawToolName + : canonicalizeToolName(rawToolName, cli); if (canonicalToolName !== rawToolName) { parsed.tool_name = canonicalToolName; } @@ -859,7 +869,7 @@ export async function evaluateHookEvent( // when no policy decides. PostToolUse for the tool is recorded, never // evaluated; any other event for it takes the ordinary path. if ( - isSelfReportToolName(parsed.tool_name) && + (cli === "cursor" ? cursorSelfReport : isSelfReportToolName(parsed.tool_name)) && (canonicalEventType === "PreToolUse" || (cli === "cursor" && eventType === "beforeMCPExecution") || canonicalEventType === "PermissionRequest" || diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts index 7c3d3b96c..8b72791ba 100644 --- a/src/hooks/self-report-cli.ts +++ b/src/hooks/self-report-cli.ts @@ -32,6 +32,7 @@ import { daemonSocketPresent, isDaemonConfigured } from "./daemon-client"; import { SELF_REPORT_CURSOR_APPROVAL_HINT, probeSelfReportHttp, + selfReportHttpAllowed, selfReportCommandRunnable, selfReportRegistrationStatus, selfReportSyncChanged, @@ -148,9 +149,15 @@ function selfReportRegistrationLines(rows: readonly SelfReportRegistration[], he ]; } -/** Whether a row is registered over HTTP at an endpoint that is not answering. */ +/** + * Whether a row is registered over HTTP where it should not be: an endpoint + * that is not answering, or an agent whose reports the server records (those + * belong on stdio, where the server knows the caller's cwd; an older version + * registered them over HTTP). + */ function selfReportStranded(r: SelfReportRegistration, health: ReadonlyMap): boolean { if (!r.registered || r.transport !== "http") return false; + if (!selfReportHttpAllowed(r.agent)) return true; const port = selfReportUrlPort(r.endpoint); return port === null || health.get(port) !== true; } @@ -180,7 +187,7 @@ async function selfReportStatus(deps: SelfReportCliDeps): Promise syncSelfReportMcp({ quiet: true })))(); if (selfReportSyncChanged(results)) { - lines.push("Repaired: agents pointed at an HTTP endpoint that is not answering were re-synced:"); + lines.push("Repaired: agents on an HTTP endpoint that is not answering, or that belong on stdio, were re-synced:"); lines.push(...selfReportSyncLines(results).map((l) => ` ${l}`)); rows = readRows(); health = await selfReportHttpHealth(rows, deps); diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index 208b9dfd5..2569541c8 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -2,14 +2,23 @@ * Self Reports: register failproofai's `report` MCP server in every agent that * has failproofai hooks, and take it out again. * - * The server is named `failproofai` everywhere (CONTRACT §1). It is served by - * the daemon over Streamable HTTP at `http://127.0.0.1:/mcp` when a - * daemon is live here (it answers a ping on its socket AND the endpoint - * answers an MCP initialize), and otherwise by `failproofai mcp` over stdio - * (CONTRACT §7). The daemon runs `self-report sync` once it is listening, so - * agents move to HTTP when it comes up. Both carry the agent, `?agent=` / `--agent `, so the - * server can record a report itself for agents whose hooks do not see MCP - * calls (CONTRACT §8). + * The server is named `failproofai` everywhere (CONTRACT §1). Which transport + * an agent gets depends on who records its reports (CONTRACT §7, §8): + * + * - Hook-recorded agents (claude, codex: not in `SELF_REPORT_SERVER_RECORDS`) + * are served by the daemon over Streamable HTTP at + * `http://127.0.0.1:/mcp?agent=` when the daemon behind this home's + * socket is serving that port (`selfReportDaemonLive`), else stdio. Their + * hook records the report against the exact session, so the server records + * nothing and needs no caller identity. + * - Server-recorded agents (everything in `SELF_REPORT_SERVER_RECORDS`) always + * get `failproofai mcp --agent ` over stdio. The server records their + * report itself and must pick the session; one user-scope HTTP entry serves + * every project and carries only `?agent=`, so over HTTP it could not tell + * which project called, while a stdio server knows its real cwd. + * + * The daemon runs `self-report sync` once it is listening, so hook-recorded + * agents move to HTTP when it comes up. * * ## Where each agent keeps user-scope MCP servers (checked 2026-11-25) * @@ -47,8 +56,8 @@ * OpenClaw (`tools.toolSearch`) defer MCP tools with a global switch only; * neither has a per-server "always load" option, so their entries set none. * - * Every agent supports Streamable HTTP, so the transport choice is purely - * "is a daemon live here". Every path is the user-scope one: MCP servers are a per + * Every agent supports Streamable HTTP; HTTP is still used only for the + * hook-recorded ones (see above). Every path is the user-scope one: MCP servers are a per * user (per profile) setting even where failproofai's hooks are per project. * Codex: user scope only. Its system config (`/etc/codex/config.toml`, where * root installs put the hooks) is not documented to honour `[mcp_servers]`, so @@ -75,8 +84,8 @@ import { isMap, type Document } from "yaml"; import { writeConfigFileAtomic } from "./safe-config-write"; import { codexHome } from "./codex-system-hooks"; import { claudeConfigDir, getIntegration, readYamlDoc, writeYamlDoc, UnreadableAgentConfigError } from "./integrations"; -import { daemonAnswersPing } from "./daemon-client"; -import { readEffectiveSelfReport, selfReportPort, selfReportSettingsFile, SELF_REPORT_SERVER_NAME } from "./self-report"; +import { daemonSelfReportServer } from "./daemon-client"; +import { readEffectiveSelfReport, selfReportPort, selfReportSettingsFile, SELF_REPORT_SERVER_NAME, SELF_REPORT_SERVER_RECORDS } from "./self-report"; import { listHermesProfiles } from "../../lib/hermes-profiles"; import { listOpenClawProfiles } from "../../lib/openclaw-profiles"; import { INTEGRATION_TYPES, type IntegrationType } from "./types"; @@ -110,6 +119,14 @@ export function readSelfReportMcpSettings(path = selfReportSettingsPath()): Self // ── Transports ────────────────────────────────────────────────────────────── +/** + * Whether an agent may be registered over HTTP at all: only when its hook, + * not the server, records the report (see the header). + */ +export function selfReportHttpAllowed(agent: IntegrationType): boolean { + return SELF_REPORT_MCP_TARGETS[agent]?.http === true && !SELF_REPORT_SERVER_RECORDS.includes(agent); +} + export type SelfReportTransport = | { kind: "http"; url: string } | { kind: "stdio"; command: string; args: string[] }; @@ -166,11 +183,12 @@ function endpointOf(entry: unknown): string | null { const SELF_REPORT_PROBE_TIMEOUT_MS = 1500; /** - * Whether `http://127.0.0.1:/mcp` answers an MCP `initialize` as - * failproofai's server, within the timeout. Anything else (refused, timed out, - * a different server on the port) is false. + * The `serverInfo.instanceId` that `http://127.0.0.1:/mcp` returns when + * it answers an MCP `initialize` as failproofai's server within the timeout, + * `""` when it answers as failproofai's server with no id (an older daemon), + * or null for anything else (refused, timed out, another server on the port). */ -export async function probeSelfReportHttp(port: number, timeoutMs = SELF_REPORT_PROBE_TIMEOUT_MS): Promise { +export async function probeSelfReportHttpInstance(port: number, timeoutMs = SELF_REPORT_PROBE_TIMEOUT_MS): Promise { try { const res = await fetch(`http://127.0.0.1:${port}/mcp`, { method: "POST", @@ -183,23 +201,36 @@ export async function probeSelfReportHttp(port: number, timeoutMs = SELF_REPORT_ }), signal: AbortSignal.timeout(timeoutMs), }); - if (!res.ok) return false; - const body = (await res.json()) as { result?: { serverInfo?: { name?: unknown } } }; - return body?.result?.serverInfo?.name === SELF_REPORT_SERVER_NAME; + if (!res.ok) return null; + const body = (await res.json()) as { result?: { serverInfo?: { name?: unknown; instanceId?: unknown } } }; + const info = body?.result?.serverInfo; + if (info?.name !== SELF_REPORT_SERVER_NAME) return null; + return typeof info.instanceId === "string" ? info.instanceId : ""; } catch { - return false; + return null; } } +/** Whether the endpoint answers an MCP `initialize` as failproofai's server. */ +export async function probeSelfReportHttp(port: number, timeoutMs = SELF_REPORT_PROBE_TIMEOUT_MS): Promise { + return (await probeSelfReportHttpInstance(port, timeoutMs)) !== null; +} + /** * Whether agents should be pointed at the daemon's HTTP server: the daemon - * answers a ping on its socket AND its MCP endpoint answers an initialize. A - * socket file alone is not enough (a hard-killed daemon leaves one behind), - * and neither is the port alone (something else may hold it). + * behind THIS home's socket answers a ping naming the MCP server it is + * serving (its pong's `selfReport`: present only while its listener is bound, + * on this port), AND the endpoint answers an initialize with that same + * `instanceId`. A socket file alone is not enough (a hard-killed daemon leaves + * one behind), and neither is a ping plus an answering port: the port may be + * held by a different daemon (another user's, or another FAILPROOFAI_HOME's) + * whose bind won while this one's failed, and a report sent there would be + * recorded under that daemon's home and credentials. Anything short of a match + * is stdio. */ export async function selfReportDaemonLive(port: number): Promise { - const [ping, http] = await Promise.all([daemonAnswersPing(), probeSelfReportHttp(port)]); - return ping && http; + const [mine, served] = await Promise.all([daemonSelfReportServer(), probeSelfReportHttpInstance(port)]); + return !!mine && mine.port === port && !!served && served === mine.instanceId; } /** Whether a stdio command can be run (exists and is executable). */ @@ -627,8 +658,9 @@ function defaultHooksInstalled(agent: IntegrationType): boolean { /** * Add (enabled) or remove (disabled) our `failproofai` MCP server in every * agent. Enabled: only agents with failproofai hooks get it, and agents without - * hooks are left as they are; HTTP when the daemon is live right now (see - * `selfReportDaemonLive`), stdio otherwise. Disabled: ours is removed from + * hooks are left as they are; HTTP for a hook-recorded agent when this home's + * daemon is serving the port right now (see `selfReportDaemonLive`), stdio + * otherwise and always for a server-recorded agent. Disabled: ours is removed from * every agent's file, hooked or not. Idempotent; never touches an entry that * is not ours; one agent's failure never stops the others. */ @@ -646,11 +678,33 @@ export async function syncSelfReportMcp(opts: SyncSelfReportMcpOptions = {}): Pr // it runs only when some agent will get an HTTP-capable entry. const also = opts.alsoHooked ?? []; const wanted = - enabled && agents.some((a) => SELF_REPORT_MCP_TARGETS[a]?.http && (also.includes(a) || hooked(a))); + enabled && agents.some((a) => selfReportHttpAllowed(a) && (also.includes(a) || hooked(a) || ownedRegistrationIn(a))); const daemonHere = wanted ? await (opts.deps?.daemonLive ?? selfReportDaemonLive)(settings.port) : false; return applySelfReportMcp({ ...opts, deps: { ...opts.deps, settings, hooksInstalled: hooked } }, enabled, daemonHere); } +/** + * Whether any of an agent's files already holds our entry. An agent whose + * hooks are installed only at project/local scope is registered by the + * install itself (`alsoHooked`), and later syncs do not see those hooks; its + * existing entry is still kept and its transport repaired. + */ +function ownedRegistrationIn(agent: IntegrationType): boolean { + const target = SELF_REPORT_MCP_TARGETS[agent]; + if (!target) return false; + try { + return target.paths().some((path) => { + try { + return existsSync(path) && opsFor(target, path).current().state === "ours"; + } catch { + return false; + } + }); + } catch { + return false; + } +} + function applySelfReportMcp(opts: SyncSelfReportMcpOptions, enabled: boolean, daemonHere: boolean): SelfReportMcpResult[] { const settings = opts.deps?.settings ?? readSelfReportMcpSettings(); const agents = opts.agents ?? INTEGRATION_TYPES; @@ -672,23 +726,39 @@ function applySelfReportMcp(opts: SyncSelfReportMcpOptions, enabled: boolean, da results.push({ agent, path: "", action: "skipped", transport: null, status: "error", detail: errText(err) }); continue; } - const wantIt = enabled && (also.has(agent) || hooked(agent)); - - let transport: SelfReportTransport | null = null; - if (wantIt) { - if (daemonHere && target.http) { - transport = { kind: "http", url: selfReportHttpUrl(settings.port, agent) }; + const agentHooked = enabled && (also.has(agent) || hooked(agent)); + + let chosen: SelfReportTransport | null | undefined; + const transportFor = (): SelfReportTransport | null => { + if (chosen !== undefined) return chosen; + chosen = null; + if (daemonHere && selfReportHttpAllowed(agent)) { + chosen = { kind: "http", url: selfReportHttpUrl(settings.port, agent) }; } else { if (cliPath === undefined) cliPath = (opts.deps?.resolveCliPath ?? resolveSelfReportCliPath)(); - if (cliPath) transport = { kind: "stdio", command: cliPath, args: selfReportStdioArgs(agent) }; + if (cliPath) chosen = { kind: "stdio", command: cliPath, args: selfReportStdioArgs(agent) }; } - } + return chosen; + }; for (const path of paths) { + // No hooks detected (user scope), but our entry is already in this file: + // keep it and repair its transport. A file without ours is left alone. + let wantIt = agentHooked; if (enabled && !wantIt) { - results.push({ agent, path, action: "skipped", transport: null, status: "not-hooked" }); - continue; + let owned = false; + try { + owned = existsSync(path) && opsFor(target, path).current().state === "ours"; + } catch { + owned = false; + } + if (!owned) { + results.push({ agent, path, action: "skipped", transport: null, status: "not-hooked" }); + continue; + } + wantIt = true; } + const transport = wantIt ? transportFor() : null; if (wantIt && !transport) { results.push({ agent, path, action: "skipped", transport: null, status: "error", diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts index 879b8bfac..df2f7cf51 100644 --- a/src/hooks/self-report-mcp.ts +++ b/src/hooks/self-report-mcp.ts @@ -110,8 +110,11 @@ export interface SelfReportSessionMatch { * ancestor or descendant of it; else the newest session of that integration * anywhere. The stdio server's cwd is wherever the agent started it, which is * often not the project (Hermes runs it from its own directory), so an exact - * match alone left those reports unattributed. The daemon's HTTP fallback - * (crates/fpai-collect/src/self_report.rs `find_session`) does the same. + * match alone left those reports unattributed. Every server-recorded agent is + * registered over stdio, so this server always has a cwd. The daemon's HTTP + * fallback (crates/fpai-collect/src/self_report.rs `find_session`) ranks the + * same way but, having no cwd from an HTTP entry, refuses a guess across + * projects and records such a report as unattributed. * * Reads `current.jsonl` and, because it holds at most one page (25 rows) and * may have just rotated, the newest archived page too. diff --git a/src/hooks/uninstall-cli.ts b/src/hooks/uninstall-cli.ts index 70362639c..2b44c9bae 100644 --- a/src/hooks/uninstall-cli.ts +++ b/src/hooks/uninstall-cli.ts @@ -48,7 +48,7 @@ import { import { listInstallableIds, getIntegration } from "./integrations"; import type { IntegrationType } from "./types"; import { removeHooks } from "./manager"; -import { removeSelfReportMcp } from "./self-report-install"; +import { removeSelfReportMcp, selfReportRegistrationStatus } from "./self-report-install"; import { shellQuote } from "./shell-quote"; import { NO_PRINTED_COMMAND_REASON, sudoCommandLine } from "./system-command"; import { installedAgentSkillDirs, removeAgentSkill } from "./agent-skill"; @@ -129,6 +129,12 @@ interface Leftovers { stagedBinaryDir: string | null; daemonConfigured: boolean; homeExists: boolean; + /** + * Agent config files holding failproofai's own Self Reports MCP entry, hooked + * or not: an entry left after its hooks were removed by hand is exactly the + * kind of orphan this command clears. + */ + selfReportMcpPaths: string[]; } function survey(cwd?: string): Leftovers { @@ -170,9 +176,21 @@ function survey(cwd?: string): Leftovers { stagedBinaryDir: stagedBinaryDir && existsSync(stagedBinaryDir) ? stagedBinaryDir : null, daemonConfigured, homeExists: existsSync(failproofaiHome()), + selfReportMcpPaths: ownedSelfReportMcpPaths(), }; } +function ownedSelfReportMcpPaths(): string[] { + try { + return selfReportRegistrationStatus({ hooksInstalled: () => false }) + .filter((r) => r.registered) + .map((r) => r.path); + } catch { + // Unreadable files are reported by the removal step itself. + return []; + } +} + export async function runUninstallCommand(opts: UninstallOptions = {}): Promise { const found = survey(opts.cwd); const kit = screenKit(opts.render ?? optsFor(process.stdout)); @@ -182,7 +200,8 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< const lines: string[] = []; const nothingToDo = - found.clis.length === 0 && found.skillDirs.length === 0 && !found.serviceInstalled && !found.stagedBinaryDir && !found.daemonConfigured && + found.clis.length === 0 && found.skillDirs.length === 0 && found.selfReportMcpPaths.length === 0 && + !found.serviceInstalled && !found.stagedBinaryDir && !found.daemonConfigured && !(opts.purge && found.homeExists); if (nothingToDo) { return { @@ -208,6 +227,9 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< const removals: string[] = []; if (found.clis.length > 0) removals.push(`failproofai's hooks from ${many(found.clis.length, "agent")}`); if (found.skillDirs.length > 0) removals.push(`the failproofai skill from ${many(found.skillDirs.length, "agent folder")}`); + if (found.selfReportMcpPaths.length > 0) { + removals.push(`the Self Reports MCP server from ${many(found.selfReportMcpPaths.length, "agent config")}`); + } if (found.serviceInstalled) removals.push("the failproofaid service (needs sudo)"); else if (found.stagedBinaryDir) removals.push(`the failproofaid binary in ${found.stagedBinaryDir} (needs sudo)`); if (purging) removals.push(home); From f6efba8c05b7ac9f5ae33278ca16a1116c28dc68 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Fri, 27 Nov 2026 14:25:02 +0530 Subject: [PATCH 14/54] [self-reports] Address second review round - Claude/Codex hooks record a report only while self-report.json says enabled, read on every call; the call is still allowed (disable takes effect in a running agent) - Detail cut to 2000 code points with no lone surrogate in the CLI, the activity store, the stdio server and both SDKs; shared cases in test-fixtures/self-report/truncation.golden.json, tested by every implementation including Rust - Session lookup (stdio server and daemon HTTP fallback) reads every activity page in the 6 h window; with no related cwd it takes the newest session only when all of the agent's sessions share one directory - SDKs: an explicit tool_call_id open in several sessions never falls back to the tool name; with an explicit session the call id is inferred only from the one open report call of that session and agent - TS SDK: Responses tool has strict: true (Python too); LangChain tool reads configurable.tool_call_id - Pydantic AI: uninstrument() closes only installed runs and leaves the shared tracker for in-flight manual runs - status repairs an HTTP registration answered by another home's daemon - uninstall reports agent configs it cannot inspect instead of "Nothing to uninstall" - Docs, skill, changelogs Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/self-report-golden.test.ts | 31 ++++ __tests__/hooks/self-report-handler.test.ts | 47 ++++++- __tests__/hooks/self-report.test.ts | 71 +++++++++- __tests__/hooks/uninstall-cli.test.ts | 47 +++++++ crates/fpai-collect/src/self_report.rs | 133 +++++++++++++++--- docs/self-reports.mdx | 10 +- sdk/python/CHANGELOG.md | 11 +- sdk/python/failproofai_sdk/_events.py | 68 ++++++--- sdk/python/failproofai_sdk/_self_report.py | 13 +- .../integrations/pydantic_ai.py | 32 +++-- sdk/python/skill/SKILL.md | 10 +- sdk/python/skill/references/integration.md | 12 +- .../tests/integrations/test_pydantic_ai.py | 45 ++++++ sdk/python/tests/test_self_report.py | 54 +++++++ sdk/python/tests/test_self_report_golden.py | 14 ++ sdk/typescript/CHANGELOG.md | 8 +- sdk/typescript/src/events.ts | 54 ++++--- .../src/integrations/self-report-tools.ts | 17 ++- sdk/typescript/src/self-report-spec.ts | 40 ++++-- sdk/typescript/test/self-report.test.ts | 98 ++++++++++++- src/hooks/handler.ts | 11 +- src/hooks/hook-activity-store.ts | 7 +- src/hooks/self-report-cli.ts | 53 +++++-- src/hooks/self-report-mcp.ts | 98 +++++-------- src/hooks/self-report-names.ts | 21 +++ src/hooks/self-report.ts | 9 +- src/hooks/uninstall-cli.ts | 35 +++-- .../self-report/truncation.golden.json | 13 ++ 29 files changed, 869 insertions(+), 195 deletions(-) create mode 100644 test-fixtures/self-report/truncation.golden.json diff --git a/CHANGELOG.md b/CHANGELOG.md index ceb962327..92efd3a1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Features -- Self Reports: every hooked agent gets a `report` tool (MCP server `failproofai`, served by `failproofaid` at `http://127.0.0.1:4319/mcp` or by `failproofai mcp` over stdio) to say it is stuck, under six default categories or the organization's own; the hook allows the call before any policy, pause or Jev review and records it as a `self_report` event, the MCP server records it for agents whose hooks do not see MCP calls, the setting comes from Cloud (`selfReport` in desired-state) or `failproofai self-report enable|disable|status|test|sync` and lives in `~/.failproofai/self-report.json`, and both SDKs add `self_report()` / `selfReport()` with ready-made framework tools; the server's initialize result carries short instructions (agents that defer MCP tools, like Claude Code, still see them), and HTTP vs stdio is chosen from a live daemon check that the daemon re-runs at startup; the instructions name the `category` and `detail` arguments, and a call that sends the detail under another name (`summary`, `sentence`, `message`, ...) still records it; Cursor reports are recorded by the MCP server (its tool hook does not name the server), Antigravity's `call_mcp_tool` wrapper for `failproofai`/`report` is allowed ahead of the policies, Copilot's likely `failproofai-report` spelling is exempt, Pi's entry is exposed directly, server-recorded reports find their session by an exact, then related, then any working directory and take the session's own agent, and a hand-started daemon finds `failproofai` on PATH for its startup sync; HTTP is used only for Claude Code and Codex (hook-recorded) and only when the endpoint answers with the instance id of the daemon behind this home's socket, every server-recorded agent stays on stdio, the HTTP server records nothing while Self Reports is off and never attributes a report across projects, a Cursor call that fails the server check always goes through the policies, `self-report sync` refuses a stale home instead of migrating it unattended, and `uninstall` also finds an orphan MCP registration +- Self Reports: every hooked agent gets a `report` tool (MCP server `failproofai`, served by `failproofaid` at `http://127.0.0.1:4319/mcp` or by `failproofai mcp` over stdio) to say it is stuck, under six default categories or the organization's own; the hook allows the call before any policy, pause or Jev review and records it as a `self_report` event, the MCP server records it for agents whose hooks do not see MCP calls, the setting comes from Cloud (`selfReport` in desired-state) or `failproofai self-report enable|disable|status|test|sync` and lives in `~/.failproofai/self-report.json`, and both SDKs add `self_report()` / `selfReport()` with ready-made framework tools; the server's initialize result carries short instructions (agents that defer MCP tools, like Claude Code, still see them), and HTTP vs stdio is chosen from a live daemon check that the daemon re-runs at startup; the instructions name the `category` and `detail` arguments, and a call that sends the detail under another name (`summary`, `sentence`, `message`, ...) still records it; Cursor reports are recorded by the MCP server (its tool hook does not name the server), Antigravity's `call_mcp_tool` wrapper for `failproofai`/`report` is allowed ahead of the policies, Copilot's likely `failproofai-report` spelling is exempt, Pi's entry is exposed directly, server-recorded reports find their session by an exact, then related working directory, else the agent's newest session only when all its sessions in the 6-hour window share one directory, reading every activity page in that window, and take the session's own agent, and a hand-started daemon finds `failproofai` on PATH for its startup sync; HTTP is used only for Claude Code and Codex (hook-recorded) and only when the endpoint answers with the instance id of the daemon behind this home's socket, every server-recorded agent stays on stdio, the HTTP server records nothing while Self Reports is off and never attributes a report across projects, a Cursor call that fails the server check always goes through the policies, `self-report sync` refuses a stale home instead of migrating it unattended, and `uninstall` also finds an orphan MCP registration and reports an agent config it cannot read; the Claude Code and Codex hooks record a report only while `self-report.json` says enabled (read on every call, so `disable` takes effect in a running agent), the detail is cut to 2000 code points everywhere so a cut never splits a surrogate pair (one did, and the collector dropped the whole row), and `status` re-syncs an agent whose HTTP endpoint answers as another home's daemon ### Fixes diff --git a/__tests__/hooks/self-report-golden.test.ts b/__tests__/hooks/self-report-golden.test.ts index af8787751..745e9519d 100644 --- a/__tests__/hooks/self-report-golden.test.ts +++ b/__tests__/hooks/self-report-golden.test.ts @@ -17,6 +17,7 @@ import { SELF_REPORT_DEFAULT_CATEGORIES, SELF_REPORT_SERVER_RECORDS, selfReportArgs, + selfReportClip, describeSelfReportTool, isSelfReportCursorCall, isSelfReportToolName, @@ -46,6 +47,24 @@ describe("Self Reports golden files (CLI)", () => { expect(golden("instructions.golden.txt").length).toBeLessThan(600); }); + it("cuts detail in code points, as the shared truncation cases say", () => { + const fixture = JSON.parse(golden("truncation.golden.json")) as { + max: number; + cases: { pad_char: string; pad: number; tail: string; expected_tail: string }[]; + }; + for (const c of fixture.cases) { + const input = c.pad_char.repeat(c.pad) + c.tail; + const want = c.pad_char.repeat(c.pad) + c.expected_tail; + const label = `${c.pad} x ${JSON.stringify(c.pad_char)} + ${JSON.stringify(c.tail)}`; + expect(selfReportClip(input, fixture.max), label).toBe(want); + expect(selfReportArgs({ category: "looping", detail: input }).detail, label).toBe(want); + } + // A lone surrogate (which no golden JSON can carry) becomes U+FFFD, never an unpaired escape. + expect(selfReportClip("a\ud83d")).toBe("a\ufffd"); + expect(selfReportClip("\ude00b")).toBe("\ufffdb"); + expect(JSON.stringify(selfReportArgs({ detail: "x\ud83d" }))).not.toMatch(/\\ud83d/); + }); + it("reads argument aliases from the shared list, for raw and hook-wrapped arguments", () => { const fixture = JSON.parse(golden("arg-aliases.json")) as { aliases: { category: string[]; detail: string[] }; @@ -131,5 +150,17 @@ describe("Self Reports golden files (CLI)", () => { expect(Object.keys(event)).toEqual([...spec.order, ...spec.fallbackExtras]); expect(Object.keys(JSON.parse(readFileSync(path, "utf8").trim()))).toEqual([...spec.order, ...spec.fallbackExtras]); }); + + it("writes a detail cut at a surrogate boundary as valid UTF-8, with no lone surrogate", async () => { + const { path, event } = await writeSelfReportEvent({ + integration: "hermes", + category: "looping", + detail: `${"a".repeat(1999)}\u{1F600} tail \ud83d`, + cwd: home, + now: Date.parse("2026-11-25T10:00:00Z"), + }); + expect(event.detail).toBe(`${"a".repeat(1999)}\u{1F600}`); + expect(readFileSync(path, "utf8")).not.toMatch(/\\ud[89a-f][0-9a-f]{2}/i); + }); }); }); diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index 229f9303b..256bb89f4 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -6,7 +6,7 @@ * call) shows the same setup really does deny, so an allow is not vacuous. */ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -38,6 +38,7 @@ import { jevChecksInstalled } from "../../src/hooks/effective-reviewers"; import { writePause } from "../../src/hooks/session-pause"; import { _resetForTest } from "../../src/hooks/hook-activity-store"; import { HEALTH_PROBE_SOURCE } from "../../src/hooks/health-probe"; +import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; const SESSION = "sr-session"; let home: string; @@ -66,6 +67,8 @@ beforeEach(() => { process.env.FAILPROOFAI_HOME = home; process.env.FAILPROOFAI_STATE_DIR = join(home, "state"); _resetForTest(join(home, "hook-activity")); + // Self Reports on: the hook records a report only while the setting says so. + writeEffectiveSelfReport({ enabled: true }); // A custom policy that denies everything, on every event. vi.mocked(loadAllCustomHooks).mockImplementation((async () => ({ hooks: [ @@ -115,6 +118,48 @@ describe("Self Reports short-circuit", () => { }); }); + describe("the current Self Reports setting", () => { + const settings = () => join(home, "self-report.json"); + + it.each([ + ["missing", () => rmSync(settings(), { force: true })], + ["disabled", () => writeEffectiveSelfReport({ enabled: false })], + ["malformed", () => writeFileSync(settings(), "{ not json")], + ["of another version", () => writeFileSync(settings(), JSON.stringify({ version: 2, enabled: true }))], + ])("%s: still allows the call (Claude and Codex) but records no report", async (_name, setUp) => { + setUp(); + for (const [event, cli] of [["PreToolUse", "claude"], ["pre_tool_use", "codex"]] as const) { + const out = await evaluateHookEvent(event, cli, report()); + expect(out.evaluation?.decision).toBe("allow"); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + } + const all = rows(); + expect(all).toHaveLength(2); + expect(all.every((r) => r.selfReport === undefined)).toBe(true); + }); + + it("disabling during a session stops the next call's report, and enabling brings it back", async () => { + await evaluateHookEvent("PreToolUse", "claude", report()); + writeEffectiveSelfReport({ enabled: false }); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("allow"); + writeEffectiveSelfReport({ enabled: true }); + await evaluateHookEvent("PreToolUse", "claude", report()); + expect(rows().map((r) => r.selfReport !== undefined)).toEqual([true, false, true]); + }); + }); + + it("cuts detail at 2000 code points, never through a surrogate pair", async () => { + const detail = `${"a".repeat(1999)}\u{1F600} and more text`; + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai__report", { category: "looping", detail })); + const line = readFileSync(join(home, "hook-activity", "current.jsonl"), "utf8").trim().split("\n").pop()!; + // The row is valid UTF-8 JSON with no lone surrogate escape, which the + // Rust collector would reject along with every hook event on the row. + expect(line).not.toMatch(/\\ud[89a-f][0-9a-f]{2}/i); + const kept = (JSON.parse(line).selfReport as { detail: string }).detail; + expect(kept).toBe(`${"a".repeat(1999)}\u{1F600}`); + expect([...kept]).toHaveLength(2000); + }); + it("allows it with fail-closed forced (daemon unreachable), while the control call is denied", async () => { const force = { forceDecision: { decision: "deny" as const, reason: "daemon down" } }; expect((await evaluateHookEvent("PreToolUse", "claude", bash(), force)).evaluation?.decision).toBe("deny"); diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index bc6a9bf78..efba4f2de 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -209,8 +209,10 @@ describe("MCP fallback recording helpers", () => { ].join("\n") + "\n", ); expect(selfReportFindSession("pi", "/p", now)).toBe("s2"); - // No row in or around this cwd: the agent's newest session anywhere. - expect(selfReportFindSession("pi", "/nowhere", now)).toBe("wrong-cwd"); + // No row in or around this cwd, and pi's rows are in two projects: a guess + // across projects is refused. + expect(selfReportFindSession("pi", "/nowhere", now)).toBeNull(); + // ...but goose has one project in the window, so its newest session is it. expect(selfReportFindSession("goose", "/nowhere", now)).toBe("wrong-agent"); expect(selfReportFindSession("hermes", "/p", now)).toBeNull(); expect(selfReportFindSession("pi", "/p", now + 10 * 3600_000)).toBeNull(); @@ -241,6 +243,40 @@ describe("MCP fallback recording helpers", () => { expect(selfReportCwdAffinity("/a/b", undefined)).toBe(0); }); + it("finds a project's session behind many pages of another project's hook activity", () => { + // Project A's session started, then 80 events in project B rotated A's row + // several pages back. The report from A's cwd still lands on A. + const now = 1_800_000_000_000; + const dir = join(home, "hook-activity"); + mkdirSync(dir, { recursive: true }); + const row = (o: Record) => + JSON.stringify({ eventType: "PreToolUse", decision: "allow", integration: "copilot", ...o }); + let t = now - 3600_000; + writeFileSync(join(dir, `page-${t + 1}-0.jsonl`), row({ cwd: "/work/a", sessionId: "sess-A", timestamp: t }) + "\n"); + for (let page = 1; page <= 4; page++) { + const lines: string[] = []; + for (let i = 0; i < 20; i++) lines.push(row({ cwd: "/work/b", sessionId: "sess-B", timestamp: (t += 1000) })); + writeFileSync(join(dir, `page-${t + 1}-${page}.jsonl`), lines.join("\n") + "\n"); + } + writeFileSync(join(dir, "current.jsonl"), row({ cwd: "/work/b", sessionId: "sess-B", timestamp: (t += 1000) }) + "\n"); + expect(selfReportFindSessionMatch("copilot", "/work/a", now)).toEqual({ sessionId: "sess-A", cwd: "/work/a" }); + expect(selfReportFindSessionMatch("copilot", "/work/b", now)?.sessionId).toBe("sess-B"); + // A third, unrelated cwd: two projects to choose from, so unattributed rather than B. + expect(selfReportFindSessionMatch("copilot", "/work/c", now)).toBeNull(); + }); + + it("does not read pages rotated before the window opened", () => { + const now = 1_800_000_000_000; + const dir = join(home, "hook-activity"); + mkdirSync(dir, { recursive: true }); + const old = now - 8 * 3600_000; + writeFileSync( + join(dir, `page-${old}-0.jsonl`), + JSON.stringify({ eventType: "PreToolUse", integration: "pi", cwd: "/p", sessionId: "stale", timestamp: old - 1 }) + "\n", + ); + expect(selfReportFindSessionMatch("pi", "/p", now)).toBeNull(); + }); + it("files a fallback report under the matched row's agent, not the server's cwd", async () => { writeEffectiveSelfReport({ enabled: true }); const now = Date.now(); @@ -487,6 +523,7 @@ describe("failproofai self-report enable | disable | status", () => { const r = await runSelfReportCommand(["status"], { skipSync: true, probeEndpoint: async (_url, port) => port === 4319, + daemonLive: async (port) => port === 4319, registrations: () => [ row({ agent: "claude", transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" }), row({ agent: "codex", transport: "http", endpoint: "http://127.0.0.1:4999/mcp?agent=codex" }), @@ -568,11 +605,39 @@ describe("failproofai self-report enable | disable | status", () => { // Healthy, or skipSync: no write. synced = 0; rows = [row({ transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" })]; - await runSelfReportCommand(["status"], { probeEndpoint: async () => true, registrations: () => rows, sync: async () => (synced++, []) }); + await runSelfReportCommand(["status"], { + probeEndpoint: async () => true, daemonLive: async () => true, registrations: () => rows, sync: async () => (synced++, []), + }); await runSelfReportCommand(["status"], { skipSync: true, probeEndpoint: async () => false, registrations: () => rows, sync: async () => (synced++, []) }); expect(synced).toBe(0); }); + it("status re-syncs an agent whose HTTP endpoint answers as another home's daemon", async () => { + writeEffectiveSelfReport({ enabled: true }); + let synced = 0; + const http = [row({ transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" })]; + const seen = await runSelfReportCommand(["status"], { + skipSync: true, + probeEndpoint: async () => true, + daemonLive: async () => false, + registrations: () => http, + }); + expect(seen.lines.join("\n")).toMatch(/claude +http +\S+ \(answering, but NOT this home's daemon\)/); + let rows = http; + const r = await runSelfReportCommand(["status"], { + probeEndpoint: async () => true, + daemonLive: async () => false, + registrations: () => rows, + sync: async () => { + synced++; + rows = [row({ transport: "stdio", endpoint: "/usr/bin/failproofai" })]; + return [{ agent: "claude", path: "/x", action: "updated", transport: "stdio", status: "ok" }]; + }, + }); + expect(synced).toBe(1); + expect(r.lines.join("\n")).toContain("Repaired:"); + }); + it("status moves a server-recorded agent off HTTP even while the endpoint answers", async () => { writeEffectiveSelfReport({ enabled: true }); let synced = 0; diff --git a/__tests__/hooks/uninstall-cli.test.ts b/__tests__/hooks/uninstall-cli.test.ts index 993f90d24..01c1d845c 100644 --- a/__tests__/hooks/uninstall-cli.test.ts +++ b/__tests__/hooks/uninstall-cli.test.ts @@ -602,6 +602,53 @@ describe("hooks/uninstall-cli — Self Reports MCP server", () => { } }); + it("an agent config that cannot be inspected is not \"nothing to uninstall\": the cleanup is tried and reported incomplete", async () => { + installedClis = []; + configured = false; + rmSync(servicePath, { force: true }); + const mod = await import("../../src/hooks/self-report-install"); + const broken = { + agent: "copilot", path: "/x/.copilot/mcp-config.json", hooked: false, registered: false, + transport: null, endpoint: null, conflict: false, error: "Unexpected token } in JSON", + } as const; + vi.mocked(mod.selfReportRegistrationStatus).mockReturnValue([broken]); + const { runUninstallCommand } = await import("../../src/hooks/uninstall-cli"); + try { + const dry = await runUninstallCommand({ dryRun: true }); + const plan = dry.lines.join("\n"); + expect(plan).not.toContain("Nothing to uninstall"); + expect(plan).toContain("could not be read"); + expect(plan).toContain(broken.path); + + vi.mocked(mod.removeSelfReportMcp).mockReturnValueOnce([ + { agent: "copilot", path: broken.path, action: "skipped", transport: null, status: "error", detail: broken.error }, + ]); + const res = await runUninstallCommand({ yes: true }); + expect(res.exitCode).toBe(1); + expect(res.lines.join("\n")).toContain(`Could not remove the Self Reports MCP server from ${broken.path}`); + } finally { + vi.mocked(mod.selfReportRegistrationStatus).mockReturnValue([]); + } + }); + + it("with every agent config genuinely absent, there is still nothing to uninstall", async () => { + installedClis = []; + configured = false; + rmSync(servicePath, { force: true }); + const mod = await import("../../src/hooks/self-report-install"); + vi.mocked(mod.selfReportRegistrationStatus).mockReturnValue([ + { agent: "copilot", path: "/x/.copilot/mcp-config.json", hooked: false, registered: false, transport: null, endpoint: null, conflict: false }, + ]); + const { runUninstallCommand } = await import("../../src/hooks/uninstall-cli"); + try { + const res = await runUninstallCommand({ yes: true }); + expect(res.exitCode).toBe(0); + expect(res.lines.join("\n")).toContain("Nothing to uninstall"); + } finally { + vi.mocked(mod.selfReportRegistrationStatus).mockReturnValue([]); + } + }); + it("removes failproofai's MCP server from every agent and says so", async () => { const mod = await import("../../src/hooks/self-report-install"); vi.mocked(mod.removeSelfReportMcp).mockReturnValueOnce([ diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index c2fa78ca1..57dc80b09 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -827,23 +827,9 @@ pub fn find_session( now_ms: i64, ) -> Option<(String, Option)> { let dir = home.join("hook-activity"); - // `current.jsonl` rotates to a page every 25 rows, so the newest session - // may be in the newest page when current was just rotated. - let mut files = vec![dir.join("current.jsonl")]; - if let Ok(entries) = fs::read_dir(&dir) { - let mut pages: Vec = entries - .filter_map(Result::ok) - .map(|e| e.path()) - .filter(|p| { - p.file_name() - .and_then(|n| n.to_str()) - .is_some_and(|n| n.starts_with("page-") && n.ends_with(".jsonl")) - }) - .collect(); - pages.sort(); - files.extend(pages.into_iter().rev().take(2)); - } let oldest = now_ms - SESSION_LOOKBACK.as_millis() as i64; + let mut files = vec![dir.join("current.jsonl")]; + files.extend(pages_since(&dir, oldest)); let mut best: Option<(u8, i64, String, Option)> = None; // The distinct cwds seen, to tell one project from several. let mut cwds: Vec> = Vec::new(); @@ -885,6 +871,45 @@ pub fn find_session( } } +/// Slack on a page's rotation stamp, as `ROTATION_CLOCK_SLACK_MS` in the CLI's +/// hook-activity store: a clock stepped back a little costs one more page read +/// rather than a row missed. +const ROTATION_CLOCK_SLACK_MS: i64 = 10 * 60 * 1000; + +/// Every archived activity page that can hold a row stamped at or after +/// `oldest_ms`, newest first. `current.jsonl` rotates to +/// `page--.jsonl` every 25 rows, so another busy project's +/// hooks can push a session's rows many pages back within the window; reading +/// only the newest pages lost them (and could see one project where there +/// were two). Every row in a page is at or before its rotation stamp, so the +/// listing stops at the first page rotated before the window opened, as the +/// CLI's `getHookActivityEntriesSince` does. +fn pages_since(dir: &Path, oldest_ms: i64) -> Vec { + let Ok(entries) = fs::read_dir(dir) else { + return Vec::new(); + }; + let mut pages: Vec<((i64, i64), PathBuf)> = entries + .filter_map(Result::ok) + .filter_map(|e| { + let name = e.file_name().into_string().ok()?; + let stem = name.strip_prefix("page-")?.strip_suffix(".jsonl")?; + let mut parts = stem.split('-'); + let at = parts.next()?.parse::().ok()?; + let seq = parts + .next() + .and_then(|p| p.parse::().ok()) + .unwrap_or(0); + Some(((at, seq), e.path())) + }) + .collect(); + pages.sort_by_key(|p| std::cmp::Reverse(p.0)); + pages + .into_iter() + .take_while(|((at, _), _)| *at >= oldest_ms - ROTATION_CLOCK_SLACK_MS) + .map(|(_, path)| path) + .collect() +} + /// The last `max` bytes of a file, from the first whole line in them. fn read_tail(path: &Path, max: u64) -> io::Result { use std::io::{Read, Seek, SeekFrom}; @@ -1258,8 +1283,9 @@ mod tests { "sessionId": session, "cwd": cwd, "toolName": "x", "decision": "allow"}) .to_string() }; + // A page is named for when it rotated, after its last row was written. fs::write( - dir.join("page-1-0.jsonl"), + dir.join(format!("page-{}-0.jsonl", now - 900)), format!("{}\n", row(now - 1000, "openclaw", "s-page", "/w/a")), ) .unwrap(); @@ -1418,6 +1444,58 @@ mod tests { let _ = fs::remove_dir_all(home); } + #[test] + fn reads_every_page_in_the_window_not_just_the_newest() { + let home = temp_home("busy-pages"); + let dir = home.join("hook-activity"); + fs::create_dir_all(&dir).unwrap(); + let now = 1_800_000_000_000_i64; + let row = |at: i64, session: &str, cwd: &str| { + json!({"timestamp": at, "eventType": "PreToolUse", "integration": "copilot", + "sessionId": session, "cwd": cwd, "toolName": "x", "decision": "allow"}) + .to_string() + }; + // Project A's one row, then four pages of project B (80 rows). + let mut t = now - 3_600_000; + fs::write( + dir.join(format!("page-{}-0.jsonl", t + 1)), + row(t, "sess-A", "/work/a") + "\n", + ) + .unwrap(); + for page in 1..=4 { + let mut lines = Vec::new(); + for _ in 0..20 { + t += 1000; + lines.push(row(t, "sess-B", "/work/b")); + } + fs::write( + dir.join(format!("page-{}-{page}.jsonl", t + 1)), + lines.join("\n") + "\n", + ) + .unwrap(); + } + fs::write( + dir.join("current.jsonl"), + row(t + 1000, "sess-B", "/work/b") + "\n", + ) + .unwrap(); + assert_eq!( + find_session(&home, "copilot", Some("/work/a"), now), + Some(("sess-A".to_string(), Some("/work/a".to_string()))) + ); + // No cwd: A is still in the window, so there are two projects; never B. + assert_eq!(find_session(&home, "copilot", None, now), None); + // A page rotated before the window opened is not read at all. + let stale = now - 8 * 3_600_000; + fs::write( + dir.join(format!("page-{stale}-0.jsonl")), + row(now - 60_000, "misfiled", "/work/z") + "\n", + ) + .unwrap(); + // (Its row would be an exact match for /work/z if it were read.) + assert_eq!(find_session(&home, "copilot", Some("/work/z"), now), None); + } + #[test] fn no_cwd_is_attributed_only_within_one_project() { let home = temp_home("one-project"); @@ -1560,6 +1638,27 @@ mod tests { .collect() } + #[test] + fn golden_truncation_counts_code_points() { + let fixture: Value = serde_json::from_str(&golden("truncation.golden.json")).unwrap(); + let max = fixture["max"].as_u64().unwrap() as usize; + assert_eq!(max, MAX_DETAIL_CHARS); + for case in fixture["cases"].as_array().unwrap() { + let pad = case["pad_char"] + .as_str() + .unwrap() + .repeat(case["pad"].as_u64().unwrap() as usize); + let input = format!("{pad}{}", case["tail"].as_str().unwrap()); + let want = format!("{pad}{}", case["expected_tail"].as_str().unwrap()); + assert_eq!(truncate_chars(&input, max), want, "{case}"); + assert_eq!( + Report::from_args(&json!({"category": "looping", "detail": input})).detail, + want, + "{case}" + ); + } + } + #[test] fn golden_description_and_schema() { let cats = default_categories(); diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index 34f7fb3c6..7733aa2f3 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -28,7 +28,7 @@ A report never unblocks the agent and never changes a decision. Afterwards the a failproofai self-report test --agent claude ``` - `enable` writes the `selfReport` block of `~/.failproofai/config.json` and `~/.failproofai/self-report.json`, then registers the MCP server in every agent with failproofai hooks. To replace the default categories, pass `--categories-file `, a JSON list of `{name, description}`. To append instructions to the tool's description, pass `--guidance ""`. `failproofai self-report disable` turns it off and removes the MCP entries, keeping your categories for next time. + `enable` writes the `selfReport` block of `~/.failproofai/config.json` and `~/.failproofai/self-report.json`, then registers the MCP server in every agent with failproofai hooks. To replace the default categories, pass `--categories-file `, a JSON list of `{name, description}`. To append instructions to the tool's description, pass `--guidance ""`. `failproofai self-report disable` turns it off and removes the MCP entries, keeping your categories for next time. An agent that is already running keeps the tool it loaded, but from then on its calls are allowed without being recorded. `test` sends one report end to end as the agent you name and shows where it landed. @@ -47,7 +47,7 @@ An organization's own list replaces these entirely. Names are lowercase letters, | `repeated_tool_failure` | A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. | | `task_failure` | You genuinely tried and could not complete the task. Not for refusals or policy blocks. | -A report with a category that is not on the list is still recorded under the name the agent gave. The detail is cut to 2,000 characters. An agent that calls the tool without loading its schema sometimes guesses the argument names, so when `detail` is missing or empty the first non-empty of `summary`, `sentence`, `message`, `description`, `reason`, `text` and `details` is recorded instead, and when `category` is, `type` or `kind`. Other unknown arguments are ignored; a call is never rejected. +A report with a category that is not on the list is still recorded under the name the agent gave. The detail is cut to 2,000 characters (Unicode code points, so an emoji or other character outside the Basic Multilingual Plane counts once and is never split). An agent that calls the tool without loading its schema sometimes guesses the argument names, so when `detail` is missing or empty the first non-empty of `summary`, `sentence`, `message`, `description`, `reason`, `text` and `details` is recorded instead, and when `category` is, `type` or `kind`. Other unknown arguments are ignored; a call is never rejected. ## Agent support @@ -59,7 +59,7 @@ Both transports send the model short server instructions in the MCP handshake: w Pi shows the model only a server's name by default. failproofai's Pi entry sets `"exposure": "direct"`, so `report` and its description reach the model like a built-in tool. Hermes and OpenClaw defer MCP tools behind their tool search (`tools.tool_search` / `tools.toolSearch`). Neither has a per-server setting to load one server directly, so failproofai leaves that setting alone, and the model sees `report` in the deferred tool listing. -Where an agent's hooks see MCP tool calls and the server they belong to, the hook records the report. Where they do not, failproofai's MCP server records it. It attributes the report to that agent's newest session seen by the hooks in the last 6 hours: in the server's working directory if there is one, else in a directory above or below it, else anywhere on the machine. The agent the report is filed under comes from that session's own hook events. +Where an agent's hooks see MCP tool calls and the server they belong to, the hook records the report. Where they do not, failproofai's MCP server records it. It attributes the report to that agent's newest session seen by the hooks in the last 6 hours: in the server's working directory if there is one, else in a directory above or below it. With neither, it takes the agent's newest session only when all of the agent's sessions in those 6 hours are in one directory, and files the report as `unattributed` otherwise, rather than guess between projects. The lookup reads every page of hook activity written in the 6 hours, however busy other agents or projects kept the hooks, so a session that is still in the window is found. The agent the report is filed under comes from that session's own hook events. These agents are registered over stdio for that reason: the MCP entry is per user, not per project, so an HTTP URL could carry only `?agent=`, and the server could not tell which project called. The daemon's HTTP server still answers an entry like that (one written by hand, or by an earlier version until the next sync), but it never guesses across projects: with no working directory, it files the report under that agent's newest session only when all of the agent's recent sessions are in one directory, and as `unattributed` otherwise. It records nothing while Self Reports is off. @@ -67,7 +67,7 @@ These agents are registered over stdio for that reason: the MCP entry is per use | --- | --- | --- | | Claude Code | `~/.claude.json` | Hook | | Codex | `~/.codex/config.toml` | Hook | -| Cursor | `~/.cursor/mcp.json` | MCP server. Cursor's tool hook names the call `MCP:report`, without the server, so it cannot tell our `report` from another server's | +| Cursor | `~/.cursor/mcp.json` | MCP server. Cursor's tool hook names the call `MCP:report`, without the server, so it cannot tell our `report` from another server's, and the call goes through the policies like any other. When the daemon cannot be reached, it is denied with every other call | | Copilot CLI | `~/.copilot/mcp-config.json` | MCP server | | OpenCode | `~/.config/opencode/opencode.json` | MCP server | | Pi | `~/.pi/agent/mcp.json` | MCP server | @@ -91,7 +91,7 @@ In a container, run `failproofaid` in the foreground as the container's main pro A daemon you start by hand has no service unit, so it has none of the commands the unit would give it: - **The startup sync** runs the CLI named by `FAILPROOFAI_CLI_CMD`. Without it, the daemon looks for `failproofai` on `PATH`, then in npm's global bin (`$NPM_CONFIG_PREFIX/bin`, `~/.npm-global/bin`, `/usr/local/bin`) and `~/.bun/bin`. After an `npm install -g failproofai`, agents therefore move to HTTP when the daemon starts. If the CLI is somewhere else, set `FAILPROOFAI_CLI_CMD` to the command that runs it, or run `failproofai self-report sync` once the daemon is up. -- **Hermes and OpenClaw** need the daemon's policy worker. Without `FAILPROOFAI_WORKER_CMD`, the daemon looks for `dist/worker.mjs` relative to its working directory, and `policies --install --cli hermes` (or `openclaw`) refuses. Set it to the worker in the installed package: +- **The policy worker** evaluates every hook the daemon receives, from every agent, Claude Code included. Without `FAILPROOFAI_WORKER_CMD`, the daemon looks for `dist/worker.mjs` relative to its working directory. If it is not there, every hook routed through the daemon fails closed: Claude Code's tool calls, for example, are denied. `policies --install --cli hermes` (or `openclaw`) refuses outright. Set it to the worker in the installed package: ```bash export FAILPROOFAI_WORKER_CMD="node $(npm root -g)/failproofai/dist/worker.mjs" diff --git a/sdk/python/CHANGELOG.md b/sdk/python/CHANGELOG.md index 763361666..28e5753b1 100644 --- a/sdk/python/CHANGELOG.md +++ b/sdk/python/CHANGELOG.md @@ -25,9 +25,14 @@ see `scripts/changelog-section.py`. `instrument("pydantic_ai", self_report=True)`. Categories and guidance come from `$FAILPROOFAI_HOME/self-report.json`, else six defaults. A report with no session bound matches an open tool call only within one session (never the - newest of several), and open calls are tracked per session. The CrewAI tool is - never cached and runs in the caller's context on CrewAI's async path. Still no - runtime dependencies. + newest of several), and open calls are tracked per session; a `tool_call_id` + open in several sessions is never resolved by the tool name instead, and with + an explicit session the call id is taken only from the one open report call of + that session and agent. `detail` is cut to 2000 code points with no lone + surrogate, as the daemon cuts it. `openai_responses_tool()` sets + `strict: True`. `uninstrument("pydantic_ai")` leaves runs of a hand-attached + `FailproofAI()` to finish. The CrewAI tool is never cached and runs in the + caller's context on CrewAI's async path. Still no runtime dependencies. ### Dependencies diff --git a/sdk/python/failproofai_sdk/_events.py b/sdk/python/failproofai_sdk/_events.py index 4235ab07e..b947e1935 100644 --- a/sdk/python/failproofai_sdk/_events.py +++ b/sdk/python/failproofai_sdk/_events.py @@ -69,6 +69,22 @@ #: whichever path wrote it. SELF_REPORT_DETAIL_LIMIT = 2000 + +def clip_report_text(text: str, limit: "int | None" = SELF_REPORT_DETAIL_LIMIT) -> str: + """`text` with no lone surrogate, cut to `limit` code points (`None`: not cut). + + Code points are what the daemon (`truncate_chars`) and the CLI count, so + every recorder keeps the same prefix of a long detail. A surrogate pair + spelled as two code points is joined; a lone one becomes U+FFFD. Either + would otherwise reach the event file as an unpaired `\\ud8xx` escape, which + the Rust collector rejects, losing the report. The shared cases are in + test-fixtures/self-report/truncation.golden.json. + """ + if any("\ud800" <= ch <= "\udfff" for ch in text): + text = text.encode("utf-16", "surrogatepass").decode("utf-16", "replace") + return text if limit is None else text[:limit] + + #: The session a `self_report` is filed under when nothing else identifies one — #: the same value the MCP server fallback uses. UNATTRIBUTED_SESSION = "unattributed" @@ -358,12 +374,16 @@ def _report_identity( """Where a `self_report` with no explicit `session_id` belongs, and its call id. Most specific first, within the ambient session when one is bound: - the open `tool_use` with this `tool_call_id`; then the newest open - `tool_use` of the report tool itself; then the enclosing scope; then + the open `tool_use` with this `tool_call_id`; then, only when no open + call has that id (or none was given), the newest open `tool_use` of + the report tool itself, since an adapter may have recorded its own id + rather than the model's; then the enclosing scope; then `"unattributed"` with one warning. With no ambient session, an open `tool_use` is used only when every candidate is in one session: the - newest of several sessions would be a guess. Never raises: a report is evidence, - and losing it to a missing scope is the worse outcome. + newest of several sessions would be a guess. An id open in several + sessions is such a guess too, and never falls back to the tool name. + Never raises: a report is evidence, and losing it to a missing scope is + the worse outcome. The third item is the `tool_call_id` to record: the caller's, else the matched `tool_use`'s own id, so a tool that cannot see the model's call @@ -384,10 +404,11 @@ def unambiguous(found: "list[tuple[str, str, str, str]]") -> "tuple[str, str, st return None return found[-1] - match = None - if tool_call_id is not None: - match = unambiguous([e for e in candidates if e[3] == tool_call_id]) - if match is None: + by_id = [e for e in candidates if e[3] == tool_call_id] if tool_call_id is not None else [] + if by_id: + # The id is known here: its call, or no guess at all. + match = unambiguous(by_id) + else: match = unambiguous([e for e in candidates if is_self_report_tool(e[2])]) if match is not None: entry = match @@ -411,18 +432,23 @@ def unambiguous(found: "list[tuple[str, str, str, str]]") -> "tuple[str, str, st ) return UNATTRIBUTED_SESSION, agent_id, tool_call_id - def _open_report_call_id(self, session_id: str) -> "str | None": - """The id of the newest open report-tool `tool_use` in this session, or None.""" + def _open_report_call_id(self, session_id: str, agent_id: str) -> "str | None": + """The id of the one open report-tool `tool_use` of this session and agent. + + None when there is none, or several: two report calls open at once + (parallel tool calls) would make the id a guess between them. + """ from failproofai_sdk._self_report import is_self_report_tool try: open_tools = list(self._open_tools.values()) except RuntimeError: # resized under us by another thread return None - return next( - (e[3] for e in reversed(open_tools) if e[0] == session_id and is_self_report_tool(e[2])), - None, - ) + found = [ + e[3] for e in open_tools + if e[0] == session_id and e[1] == agent_id and is_self_report_tool(e[2]) + ] + return found[0] if len(found) == 1 else None def _validate_fields(self, fields: dict) -> None: bad = _RESERVED & fields.keys() @@ -904,8 +930,8 @@ def self_report( raises here, unlike the other event methods — the TypeError/ValueError checks on the arguments themselves still apply. With no `tool_call_id` given, the report takes the id of the open report-tool `tool_use` it - was matched to (or, with an explicit `session_id`, the newest one open - in that session). + was matched to (or, with an explicit `session_id`, of the one such call + open for that session and agent; none when several are open). """ if "source" in fields: raise ValueError("source is set by the SDK (always \"sdk\") and cannot be passed by the caller") @@ -924,8 +950,10 @@ def self_report( session_id, agent_id, tool_call_id = self._report_identity(tool_call_id, agent_id) elif tool_call_id is None: # A framework tool that resolved its session from the adapter's run - # (LlamaIndex, CrewAI) but cannot see the model's call id. - tool_call_id = self._open_report_call_id(session_id) + # (LlamaIndex, CrewAI) but cannot see the model's call id. The agent + # is resolved first, so only that agent's open call is a candidate. + session_id, agent_id = _resolve_identity(session_id, agent_id) + tool_call_id = self._open_report_call_id(session_id, agent_id) session_id, agent_id = _resolve_identity(session_id, agent_id) ts = self._now() self._writer.submit( @@ -933,8 +961,8 @@ def self_report( timestamp=self._fmt_ts(ts), session_id=session_id, agent_id=agent_id, - category=category, - detail=detail[:SELF_REPORT_DETAIL_LIMIT], + category=clip_report_text(category, None), + detail=clip_report_text(detail), tool_call_id=tool_call_id, extra_fields=fields, ).to_dict() diff --git a/sdk/python/failproofai_sdk/_self_report.py b/sdk/python/failproofai_sdk/_self_report.py index 954680491..b7688313f 100644 --- a/sdk/python/failproofai_sdk/_self_report.py +++ b/sdk/python/failproofai_sdk/_self_report.py @@ -33,7 +33,7 @@ from typing import Any from failproofai_sdk import _runtime -from failproofai_sdk._events import SELF_REPORT_DETAIL_LIMIT +from failproofai_sdk._events import clip_report_text from failproofai_sdk._resolver import failproofai_home logger = logging.getLogger(__name__) @@ -254,13 +254,18 @@ def openai_tool(**overrides: Any) -> dict[str, Any]: def openai_responses_tool(**overrides: Any) -> dict[str, Any]: - """The tool for the OpenAI Responses API `tools=[...]` (flat function shape).""" + """The tool for the OpenAI Responses API `tools=[...]` (flat function shape). + + `strict: True`, as the TypeScript SDK's `openaiResponsesTool()`: the schema + already meets strict mode (every property required, no extra properties). + """ spec = self_report_spec(**overrides) return { "type": "function", "name": spec["name"], "description": spec["description"], "parameters": spec["input_schema"], + "strict": True, } @@ -348,11 +353,11 @@ def parse_arguments(arguments: Any) -> tuple[str, str]: try: arguments = json.loads(text) except ValueError: - return "", text[:SELF_REPORT_DETAIL_LIMIT] + return "", clip_report_text(text) if arguments is None: arguments = {} if not isinstance(arguments, dict): - return "", _coerce_text(arguments)[:SELF_REPORT_DETAIL_LIMIT] + return "", clip_report_text(_coerce_text(arguments)) return _first_text(arguments, "category"), _first_text(arguments, "detail") diff --git a/sdk/python/failproofai_sdk/integrations/pydantic_ai.py b/sdk/python/failproofai_sdk/integrations/pydantic_ai.py index 625f2580a..9c025bcac 100644 --- a/sdk/python/failproofai_sdk/integrations/pydantic_ai.py +++ b/sdk/python/failproofai_sdk/integrations/pydantic_ai.py @@ -384,10 +384,15 @@ def _is_base_model(value: Any) -> bool: # --------------------------------------------------------------------------- class _RunState: - __slots__ = ("key", "scope", "spans", "closed", "reported_error") + __slots__ = ("key", "scope", "spans", "closed", "reported_error", "installed") - def __init__(self, key: Any) -> None: + def __init__(self, key: Any, installed: bool = False) -> None: self.key = key + # Whether the capability running it was injected by `instrument()`. + # `uninstrument()` tears down only those: a `FailproofAI()` the + # developer attached by hand records whether or not instrument() ran, + # and its runs finish on their own. + self.installed = installed self.scope: Any = None # Leaf spans this run has opened and not yet closed, newest last. This # exists because a leaf can outlive its own run — see `_close_spans`. @@ -553,17 +558,22 @@ def _close_spans(state: _RunState, exc: "BaseException | None") -> None: ) -def _close_open_runs() -> None: - """Close every run this adapter still has open, newest first. +def _close_open_runs() -> bool: + """Close every run the installed capability still has open, newest first. Teardown, not a hot path: `uninstall()` is the only caller. Each run's leaves close before its `agent_end`, and `_claim_run` makes the run's own - `wrap_run` frame a no-op when it eventually unwinds. + `wrap_run` frame a no-op when it eventually unwinds. A run of a manually + attached capability is left open to finish normally. + + Returns whether any such manual run is still open. """ with _runs_lock: states = list(_open_runs.values()) for state in reversed(states): - _core.call_safely(_close_run, (state,), {}, f"{__name__}.uninstall") + if state.installed: + _core.call_safely(_close_run, (state,), {}, f"{__name__}.uninstall") + return any(not state.installed for state in states) def _close_run(state: _RunState) -> None: @@ -686,7 +696,7 @@ def _begin_run(self, ctx) -> _RunState: metadata=getattr(ctx, "metadata", None), ), ) - state = _RunState(key) + state = _RunState(key, installed=bool(getattr(self, "_installed", False))) _register_run(state) try: scope = failproofai_sdk.session(identity.session_id, agent_id=identity.agent_id) @@ -995,7 +1005,13 @@ def uninstall(self) -> None: # `wrap_run` frame does not emit a second `agent_end` when it finally # unwinds. `close_open_agents()` stays as the backstop for a key that # reached the tracker without reaching `_open_runs`. - _close_open_runs() + # + # A manually attached `FailproofAI()` keeps recording after + # `uninstrument()`, and its runs share this tracker: while one is in + # flight the tracker is left as it is, so it can still emit its leaves + # and its own `agent_end`. + if _close_open_runs(): + return _tracker.close_open_agents() _tracker.reset() diff --git a/sdk/python/skill/SKILL.md b/sdk/python/skill/SKILL.md index 2b47b39f8..1175928a5 100644 --- a/sdk/python/skill/SKILL.md +++ b/sdk/python/skill/SKILL.md @@ -166,9 +166,13 @@ recipe — `references/typescript.md` → *The contract, in TypeScript* and *Shu Nothing bound and nothing passed raises `TypeError` naming the fix — never a silent emit, because ingest skips an event with no session and answers `200`. - The one exception is `self_report()`: a report is evidence, so with no - session it is recorded under `session_id="unattributed"` (one warning per - process) instead of raising. The other 15 methods raise. + The one exception is `self_report()`: a report is evidence, so it never + raises for a missing session. With none passed or bound, an unambiguous open + `tool_use` for the call (by its `tool_call_id`, else the one open report-tool + call) gives it its session, with no warning. Only when no explicit session, + no such open call and no enclosing scope identifies one is it recorded under + `session_id="unattributed"` (one warning per process). The other 15 methods + raise. Two more shapes raise, for the same reason: diff --git a/sdk/python/skill/references/integration.md b/sdk/python/skill/references/integration.md index 2fa650ff1..8769b5d55 100644 --- a/sdk/python/skill/references/integration.md +++ b/sdk/python/skill/references/integration.md @@ -94,10 +94,14 @@ fixes. That is deliberate: the alternative is dropping the event silently, and this SDK already asks you to debug enough invisible failures. `agent_id` never raises — it is a label, and it falls back to `"main"`. -`self_report()` is the exception: with no session bound and none passed it -records the report under `session_id="unattributed"` and logs one warning per -process, because losing a report to a missing scope is worse than filing it -unattributed. Every other event method raises as above. +`self_report()` is the exception: it never raises for a missing session, +because losing a report to a missing scope is worse than filing it +unattributed. With no session bound and none passed, an unambiguous open +`tool_use` for the call (matched by `tool_call_id`, else the one open +report-tool call) supplies the session and agent, with no warning. Only when no +explicit session, no such open call and no enclosing scope resolves the identity +is the report recorded under `session_id="unattributed"`, with one warning per +process. Every other event method raises as above. ## Don't use a module global diff --git a/sdk/python/tests/integrations/test_pydantic_ai.py b/sdk/python/tests/integrations/test_pydantic_ai.py index ff66a628e..190e92388 100644 --- a/sdk/python/tests/integrations/test_pydantic_ai.py +++ b/sdk/python/tests/integrations/test_pydantic_ai.py @@ -689,6 +689,51 @@ async def wait() -> str: assert kinds.index("tool_result") < kinds.index("agent_end") +def test_uninstrumenting_leaves_a_manually_attached_capabilitys_run_to_finish(instrumented, emitted): + """`uninstrument()` closes only the runs it instrumented. + + A `FailproofAI()` the developer attached by hand keeps recording after + `uninstrument()`; its in-flight run must end on its own, once, with its + real outcome, and its tool call must still be recorded. + """ + + async def main(): + waiting = [] + release = asyncio.Event() + manual = Agent( + one_shot_tool_model("wait", {}, tool_call_id="call-manual"), + name="manual_agent", + capabilities=[FailproofAI()], + ) + injected = Agent( + one_shot_tool_model("wait", {}, tool_call_id="call-injected"), + name="injected_agent", + ) + + async def wait() -> str: + waiting.append(1) + await release.wait() + return "finished" + + manual.tool_plain(wait) + injected.tool_plain(wait) + tasks = [asyncio.create_task(manual.run("go")), asyncio.create_task(injected.run("go"))] + while len(waiting) < 2: + await asyncio.sleep(0.01) + failproofai_sdk.uninstrument("pydantic_ai") + release.set() + await asyncio.gather(*tasks) + + asyncio.run(main()) + rows = emitted() + ends = {r["agent_id"]: r["outcome"] for r in of_type(rows, "agent_end")} + assert len(of_type(rows, "agent_end")) == 2, types_of(rows) + assert ends == {"manual_agent": "success", "injected_agent": "cancelled"} + manual_rows = [r for r in rows if r.get("agent_id") == "manual_agent"] + assert types_of(manual_rows).count("tool_result") == 1 + assert types_of(manual_rows)[-1] == "agent_end" + + # --------------------------------------------------------------------------- # What `tool_result.output` actually says # --------------------------------------------------------------------------- diff --git a/sdk/python/tests/test_self_report.py b/sdk/python/tests/test_self_report.py index 0406f970d..efae2746f 100644 --- a/sdk/python/tests/test_self_report.py +++ b/sdk/python/tests/test_self_report.py @@ -190,6 +190,55 @@ def test_with_nothing_bound_open_calls_in_two_sessions_are_not_guessed(recorded) ] +def test_an_id_open_in_two_sessions_never_falls_back_to_the_tool_name(recorded): + ev = _runtime.event + # The id is open in two sessions (on another tool); a report call is open in a third. + ev.tool_use(session_id="s-1", agent_id="a-1", tool_name="search", tool_call_id="dup") + ev.tool_use(session_id="s-2", agent_id="a-2", tool_name="search", tool_call_id="dup") + ev.tool_use(session_id="s-3", agent_id="a-3", tool_name="failproofai_report", tool_call_id="r3") + fp.self_report("looping", "ambiguous id", tool_call_id="dup") + fp.self_report("looping", "unknown id", tool_call_id="model-id") # no call has it: name fallback + fp.self_report("looping", "no id") + reports = [e for e in recorded if e["type"] == "self_report"] + assert [(r["detail"], r["session_id"], r.get("tool_call_id")) for r in reports] == [ + ("ambiguous id", "unattributed", "dup"), + ("unknown id", "s-3", "model-id"), + ("no id", "s-3", "r3"), + ] + + +def test_an_explicit_session_infers_the_call_id_only_from_one_call_of_its_agent(recorded): + ev = _runtime.event + ev.tool_use(session_id="s", agent_id="planner", tool_name="failproofai_report", tool_call_id="p-1") + ev.tool_use(session_id="s", agent_id="worker", tool_name="failproofai_report", tool_call_id="w-1") + fp.self_report("looping", "planner", session_id="s", agent_id="planner") + fp.self_report("looping", "worker", session_id="s", agent_id="worker") + fp.self_report("looping", "nobody", session_id="s", agent_id="other") + # A second open report call for the worker: two candidates, no guess. + ev.tool_use(session_id="s", agent_id="worker", tool_name="failproofai_report", tool_call_id="w-2") + fp.self_report("looping", "worker twice", session_id="s", agent_id="worker") + with fp.agent("planner"): + fp.self_report("looping", "ambient agent", session_id="s") + reports = [e for e in recorded if e["type"] == "self_report"] + assert [(r["detail"], r["agent_id"], r.get("tool_call_id")) for r in reports] == [ + ("planner", "planner", "p-1"), + ("worker", "worker", "w-1"), + ("nobody", "other", None), + ("worker twice", "worker", None), + ("ambient agent", "planner", "p-1"), + ] + + +def test_detail_cut_at_a_surrogate_boundary_has_no_lone_surrogate(recorded): + fp.self_report("looping", "a" * 1999 + "\U0001F600 and more", session_id="s") + fp.self_report("lo\ud83dping", "x\ud83d", session_id="s") + first, second = recorded + assert first["detail"] == "a" * 1999 + "\U0001F600" + assert (second["category"], second["detail"]) == ("lo\ufffdping", "x\ufffd") + # Encodable as strict UTF-8, which is what the collector reads. + json.dumps(second, ensure_ascii=False).encode("utf-8") + + def test_written_to_the_spool_by_the_real_writer(tmp_path): with fp.session("disk"): fp.self_report("looping", "on disk") @@ -369,7 +418,12 @@ def test_openai_responses_tool_shape(home): "name": spec["name"], "description": spec["description"], "parameters": spec["input_schema"], + "strict": True, } + # Strict mode holds: every property required, nothing else allowed. + params = tool["parameters"] + assert set(params["required"]) == set(params["properties"]) + assert params["additionalProperties"] is False def test_anthropic_tool_shape(home): diff --git a/sdk/python/tests/test_self_report_golden.py b/sdk/python/tests/test_self_report_golden.py index ab959caf3..8ab64d3e5 100644 --- a/sdk/python/tests/test_self_report_golden.py +++ b/sdk/python/tests/test_self_report_golden.py @@ -91,3 +91,17 @@ def test_argument_aliases_match_the_shared_list(): want = (case["category"], case["detail"]) assert _self_report.parse_arguments(case["args"]) == want, case["args"] assert _self_report.parse_arguments(json.dumps(case["args"])) == want, case["args"] + + +def test_truncation_counts_code_points_like_every_recorder(): + from failproofai_sdk._events import SELF_REPORT_DETAIL_LIMIT, clip_report_text + + fixture = json.loads(golden("truncation.golden.json")) + assert fixture["max"] == SELF_REPORT_DETAIL_LIMIT + assert fixture["cases"] + for case in fixture["cases"]: + pad = case["pad_char"] * case["pad"] + text, want = pad + case["tail"], pad + case["expected_tail"] + assert clip_report_text(text) == want, case + # Arguments that are not JSON are kept whole as the detail, cut the same way. + assert _self_report.parse_arguments(text) == ("", want), case diff --git a/sdk/typescript/CHANGELOG.md b/sdk/typescript/CHANGELOG.md index b3f83c37c..aa5ea724b 100644 --- a/sdk/typescript/CHANGELOG.md +++ b/sdk/typescript/CHANGELOG.md @@ -21,7 +21,13 @@ section is missing or empty is refused before anything is built. (`selfReportSettings()`), with the six defaults when it is missing or disabled. A report made inside a framework's tool loop joins the agent whose loop called it, and never throws for want of a session; with no scope it joins an open - call only when all candidates are in one session. The `/ai` tool carries both + call only when all candidates are in one session, and a `toolCallId` open in + several sessions is never resolved by the tool name instead; with an explicit + `sessionId` the call id is taken only from the one open report call of that + session and agent. `detail` is cut to 2000 code points (as the daemon and the + Python SDK count) with no lone surrogate. `openaiResponsesTool()` sets + `strict: true`, as openai's `FunctionTool` type requires. The `/langchain` tool + also reads the call id from `configurable.tool_call_id`. The `/ai` tool carries both schema keys for a `module` passed in, and the Edge `/langchain` tool builds a real LangChain tool with a `module` passed in (the tool needs `@langchain/core` 0.3.44 or later). diff --git a/sdk/typescript/src/events.ts b/sdk/typescript/src/events.ts index c5f87c411..8ec02f47e 100644 --- a/sdk/typescript/src/events.ts +++ b/sdk/typescript/src/events.ts @@ -21,7 +21,7 @@ import { import type { EventWriter } from "./writer.js"; import { formatMicros, nowMicros } from "./clock.js"; import { fatalSuffix, onProcessExit, type OpenItem } from "./exit.js"; -import { SELF_REPORT_DETAIL_LIMIT, clipDetail, isSelfReportTool } from "./self-report-spec.js"; +import { SELF_REPORT_DETAIL_LIMIT, clipDetail, clipReportText, isSelfReportTool } from "./self-report-spec.js"; /** * `sessionId` and `agentId` are named options on every method, so a caller @@ -839,7 +839,8 @@ export class EventNamespace { * enclosing scope; and last `"unattributed"`, with one warning. Unlike every * other event method a missing session never throws. With no `toolCallId` * given, the report takes the id of the open report-tool `tool_use` it was - * matched to (with an explicit `sessionId`, the newest one open there). + * matched to (with an explicit `sessionId`, of the one such call open for + * that session and agent; none when several are). */ selfReport(category: string, detail?: string | null, options: SelfReportOptions = {}): void { const { sessionId, agentId, toolCallId, ...fields } = options; @@ -857,7 +858,10 @@ export class EventNamespace { timestamp: this.fmtTs(this.now()), sessionId: sid, agentId: aid, - category: typeof category === "string" ? category : category === undefined || category === null ? "" : String(category), + category: clipReportText( + typeof category === "string" ? category : category === undefined || category === null ? "" : String(category), + Infinity, + ), detail: clipDetail(typeof detail === "string" ? detail : detail === undefined || detail === null ? "" : String(detail)), source: "sdk", toolCallId: callId ?? matchedCallId, @@ -875,9 +879,15 @@ export class EventNamespace { ): [string, string, string | undefined] { if (sessionId !== undefined && sessionId !== null) { // An explicit session (a tool that resolved it itself) still takes the - // id of the report-tool call open in that session, when it has none. - const open = toolCallId === undefined ? this.openToolFor(undefined, sessionId) : undefined; - return [...resolveIdentity(sessionId, agentId), open?.id]; + // id of the report-tool call open in that session for that agent, when + // it has none — but only of the one such call: with two open (parallel + // calls) the id would be a guess. The agent is resolved first. + const [sid, aid] = resolveIdentity(sessionId, agentId); + if (toolCallId !== undefined) return [sid, aid, undefined]; + const open = [...this.openLeaves.values()].filter( + (leaf) => leaf.kind === "tool" && leaf.sessionId === sid && leaf.agentId === aid && isSelfReportTool(leaf.name), + ); + return [sid, aid, open.length === 1 ? open[0]!.id : undefined]; } const ambient = context.sessionId(); const leaf = this.openToolFor(toolCallId, ambient); @@ -904,24 +914,24 @@ export class EventNamespace { /** * The newest open tool call a report belongs to: the one with this id, else - * one named like the report tool (LlamaIndex gives a tool no id, and an - * adapter may have recorded its own id rather than the model's). Inside a - * scope only that scope's session is searched. With no scope, a match is - * used only when every candidate is in one session: picking the newest of - * several sessions (two concurrent LlamaIndex runs, each with a report call - * open) would be a guess, and the report goes the unattributed way instead. + * — only when no open call has that id, or none was given — one named like + * the report tool (LlamaIndex gives a tool no id, and an adapter may have + * recorded its own id rather than the model's). Inside a scope only that + * scope's session is searched. With no scope, a match is used only when + * every candidate is in one session: picking the newest of several sessions + * (two concurrent LlamaIndex runs, each with a report call open) would be a + * guess, and the report goes the unattributed way instead. An id open in + * several sessions is the same guess, and does not fall back to the name. */ private openToolFor(toolCallId: string | undefined, preferSession: string | null): OpenLeaf | undefined { - const leaves = [...this.openLeaves.values()].filter((leaf) => leaf.kind === "tool").reverse(); - const pick = (matches: (leaf: OpenLeaf) => boolean): OpenLeaf | undefined => { - const found = leaves.filter(matches); - if (preferSession !== null) return found.find((leaf) => leaf.sessionId === preferSession); - return new Set(found.map((leaf) => leaf.sessionId)).size === 1 ? found[0] : undefined; - }; - return ( - (toolCallId !== undefined ? pick((leaf) => leaf.id === toolCallId) : undefined) ?? - pick((leaf) => isSelfReportTool(leaf.name)) - ); + const leaves = [...this.openLeaves.values()] + .filter((leaf) => leaf.kind === "tool" && (preferSession === null || leaf.sessionId === preferSession)) + .reverse(); + const pick = (found: OpenLeaf[]): OpenLeaf | undefined => + new Set(found.map((leaf) => leaf.sessionId)).size === 1 ? found[0] : undefined; + const byId = toolCallId !== undefined ? leaves.filter((leaf) => leaf.id === toolCallId) : []; + if (byId.length > 0) return pick(byId); + return pick(leaves.filter((leaf) => isSelfReportTool(leaf.name))); } humanWait(opts: HumanWaitOptions): void { diff --git a/sdk/typescript/src/integrations/self-report-tools.ts b/sdk/typescript/src/integrations/self-report-tools.ts index 5ea9827e4..1481b2e43 100644 --- a/sdk/typescript/src/integrations/self-report-tools.ts +++ b/sdk/typescript/src/integrations/self-report-tools.ts @@ -138,12 +138,21 @@ export function langchainSelfReportTool(options: LangChainSelfRepor const identity = identityOf(options); // `tool()` calls `func(input, config)`, with the model's call at // `config.toolCall`; a `DynamicStructuredTool` calls `func(input, runManager, - // config)`. Read the id from whichever argument carries it. A run id is not - // the model's call id, so it is never used. - type WithToolCall = { toolCall?: { id?: unknown } } | undefined; + // config)`. Read the id from whichever argument carries it, at + // `toolCall.id` or, as a graph runner may pass it, `configurable.tool_call_id`. + // A run id is not the model's call id, so it is never used. + type WithToolCall = { toolCall?: { id?: unknown }; configurable?: { tool_call_id?: unknown } } | undefined; const func = (input: unknown, second?: WithToolCall, third?: WithToolCall) => Promise.resolve( - recordToolCall(input, { ...identity, toolCallId: pickId(second?.toolCall?.id, third?.toolCall?.id) }), + recordToolCall(input, { + ...identity, + toolCallId: pickId( + second?.toolCall?.id, + third?.toolCall?.id, + second?.configurable?.tool_call_id, + third?.configurable?.tool_call_id, + ), + }), ); const fields = { name: SELF_REPORT_TOOL_NAME, description: spec.description, schema: spec.inputSchema }; if (typeof tools?.tool === "function") return tools.tool(func as never, fields as never) as T; diff --git a/sdk/typescript/src/self-report-spec.ts b/sdk/typescript/src/self-report-spec.ts index a7f124909..cd7cc165d 100644 --- a/sdk/typescript/src/self-report-spec.ts +++ b/sdk/typescript/src/self-report-spec.ts @@ -130,16 +130,22 @@ export function toOpenAITool(spec: SelfReportSpec): OpenAITool { }; } -/** The OpenAI Responses API `tools[]` entry: the flat function shape. */ +/** + * The OpenAI Responses API `tools[]` entry: the flat function shape. `strict` + * is required by openai's own `FunctionTool` type, and the schema already + * meets strict mode (every property required, no additional properties), so + * the model's arguments are held to it. + */ export interface OpenAIResponsesTool { type: "function"; name: string; description: string; parameters: JsonSchemaObject; + strict: boolean; } export function toOpenAIResponsesTool(spec: SelfReportSpec): OpenAIResponsesTool { - return { type: "function", name: spec.name, description: spec.description, parameters: spec.inputSchema }; + return { type: "function", name: spec.name, description: spec.description, parameters: spec.inputSchema, strict: true }; } /** The Anthropic Messages `tools[]` entry. */ @@ -217,7 +223,7 @@ export function normalizeSelfReportArgs(args: unknown): { category: string; deta } const record = typeof value === "object" && value !== null ? (value as Record) : {}; return { - category: firstText(record, "category", SELF_REPORT_ARG_ALIASES.category), + category: clipReportText(firstText(record, "category", SELF_REPORT_ARG_ALIASES.category), Infinity), detail: clipDetail(firstText(record, "detail", SELF_REPORT_ARG_ALIASES.detail)), }; } @@ -253,13 +259,29 @@ function asText(value: unknown): string { } } -/** `detail` cut to `SELF_REPORT_DETAIL_LIMIT`, never through a surrogate pair. */ +/** + * `text` with no lone surrogate (each becomes U+FFFD), cut to `max` Unicode + * code points (`Infinity`: not cut). Code points are what the daemon and the + * Python SDK count, so all of them keep the same prefix of a long detail; a + * lone surrogate would be written as an unpaired `\ud8xx` escape, which the + * collector rejects along with the report. The shared cases are in + * `test-fixtures/self-report/truncation.golden.json` in the repo. + */ +export function clipReportText(text: string, max: number = SELF_REPORT_DETAIL_LIMIT): string { + let out = ""; + let n = 0; + for (const ch of text) { + if (n === max) break; + const code = ch.charCodeAt(0); + out += ch.length === 1 && code >= 0xd800 && code <= 0xdfff ? "\uFFFD" : ch; + n++; + } + return out; +} + +/** `detail` cut to `SELF_REPORT_DETAIL_LIMIT` code points, never through a surrogate pair. */ export function clipDetail(detail: string): string { - if (detail.length <= SELF_REPORT_DETAIL_LIMIT) return detail; - let cut = detail.slice(0, SELF_REPORT_DETAIL_LIMIT); - const last = cut.charCodeAt(cut.length - 1); - if (last >= 0xd800 && last <= 0xdbff) cut = cut.slice(0, -1); - return cut; + return clipReportText(detail); } /** diff --git a/sdk/typescript/test/self-report.test.ts b/sdk/typescript/test/self-report.test.ts index ef6e7ab8b..5540b7474 100644 --- a/sdk/typescript/test/self-report.test.ts +++ b/sdk/typescript/test/self-report.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -20,7 +20,7 @@ import { setLogger } from "../src/logger.js"; import { runtime } from "../src/runtime.js"; import * as schema from "../src/schema.js"; import { agent, session, toolCall } from "../src/scopes.js"; -import { DEFAULT_SELF_REPORT_CATEGORIES } from "../src/self-report-spec.js"; +import { DEFAULT_SELF_REPORT_CATEGORIES, clipDetail } from "../src/self-report-spec.js"; import { flushed, useSpool } from "./helpers.js"; import type { Spool } from "./helpers.js"; @@ -52,6 +52,15 @@ afterEach(async () => { vi.restoreAllMocks(); }); +/** openai's Responses `FunctionTool` (openai 7.x), copied: this package does not depend on openai. */ +interface OpenAIFunctionTool { + name: string; + parameters: { [key: string]: unknown } | null; + strict: boolean | null; + type: "function"; + description?: string | null; +} + const reports = async () => (await flushed(spool)).filter((e) => e.type === "self_report"); const writeSettings = (value: unknown) => writeFileSync(join(home, "self-report.json"), typeof value === "string" ? value : JSON.stringify(value)); @@ -151,7 +160,25 @@ describe("event.selfReport and selfReport()", () => { const [unknown, long, surrogate] = await reports(); expect(unknown).toMatchObject({ category: "not_a_category", detail: "" }); expect((long!.detail as string).length).toBe(2000); - expect(surrogate!.detail).toBe("y".repeat(1999)); + // 2000 code points, as the daemon and the Python SDK count: the emoji is the 2000th. + expect(surrogate!.detail).toBe(`${"y".repeat(1999)}😀`); + }); + + it("cuts detail as the shared truncation cases say, and replaces a lone surrogate", async () => { + const fixture = JSON.parse(readFileSync(join(__dirname, "..", "..", "..", "test-fixtures", "self-report", "truncation.golden.json"), "utf8")) as { + max: number; + cases: { pad_char: string; pad: number; tail: string; expected_tail: string }[]; + }; + await session({ sessionId: "trunc" }, () => { + for (const c of fixture.cases) failproofai.selfReport("looping", c.pad_char.repeat(c.pad) + c.tail); + failproofai.selfReport("lo\ud83dping", "x\ud83d"); + }); + const recorded = await reports(); + fixture.cases.forEach((c, i) => { + expect(recorded[i]!.detail, JSON.stringify(c.tail)).toBe(c.pad_char.repeat(c.pad) + c.expected_tail); + expect(clipDetail(c.pad_char.repeat(c.pad) + c.tail)).toBe(c.pad_char.repeat(c.pad) + c.expected_tail); + }); + expect(recorded.at(-1)).toMatchObject({ category: "lo\ufffdping", detail: "x\ufffd" }); }); it("takes an explicit session, agent, tool call id and custom fields", async () => { @@ -241,6 +268,47 @@ describe("event.selfReport and selfReport()", () => { ]); }); + it("an id open in several sessions never falls back to the tool name; an id open nowhere does", async () => { + const ns = new EventNamespace(runtime.writer); + quietLogger(); + await session({ sessionId: "s-1" }, () => ns.toolUse({ toolName: "search", toolCallId: "dup" })); + await session({ sessionId: "s-2" }, () => ns.toolUse({ toolName: "search", toolCallId: "dup" })); + await session({ sessionId: "s-3" }, () => + agent("reporter", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "r-3" })), + ); + ns.selfReport("looping", "ambiguous id", { toolCallId: "dup" }); + ns.selfReport("looping", "unknown id", { toolCallId: "model-id" }); + const recorded = await reports(); + expect(recorded.map((e) => [e.detail, e.session_id, e.tool_call_id])).toEqual([ + ["ambiguous id", UNATTRIBUTED_SESSION, "dup"], + ["unknown id", "s-3", "model-id"], + ]); + }); + + it("with an explicit session, infers the call id only from the one open report call of that agent", async () => { + const ns = new EventNamespace(runtime.writer); + await session({ sessionId: "s" }, async () => { + await agent("planner", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "p-1" })); + await agent("worker", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "w-1" })); + }); + ns.selfReport("looping", "planner", { sessionId: "s", agentId: "planner" }); + ns.selfReport("looping", "worker", { sessionId: "s", agentId: "worker" }); + ns.selfReport("looping", "nobody", { sessionId: "s", agentId: "other" }); + await session({ sessionId: "s" }, () => + agent("worker", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "w-2" })), + ); + ns.selfReport("looping", "worker twice", { sessionId: "s", agentId: "worker" }); + await agent("planner", () => ns.selfReport("looping", "ambient agent", { sessionId: "s" })); + const recorded = await reports(); + expect(recorded.map((e) => [e.detail, e.agent_id, e.tool_call_id])).toEqual([ + ["planner", "planner", "p-1"], + ["worker", "worker", "w-1"], + ["nobody", "other", undefined], + ["worker twice", "worker", undefined], + ["ambient agent", "planner", "p-1"], + ]); + }); + it("files a report with no session under unattributed and warns once, never throwing", async () => { const warn = quietLogger(); const namespace = new EventNamespace(runtime.writer); @@ -353,8 +421,17 @@ describe("the raw tool helpers", () => { name: "failproofai_report", description: DEFAULT_DESCRIPTION, parameters: DEFAULT_SCHEMA, + strict: true, }); expect(edge.openaiResponsesTool()).toEqual(failproofai.openaiResponsesTool()); + // Strict mode holds for the schema: every property required, nothing else allowed. + const { parameters } = failproofai.openaiResponsesTool(); + expect([...(parameters.required as string[])].sort()).toEqual(Object.keys(parameters.properties as object).sort()); + expect(parameters.additionalProperties).toBe(false); + // Assignable to openai's own `FunctionTool` (openai/resources/responses), whose + // `strict` is required: checked by `npm run typecheck`, which covers test/. + const asOpenAI: OpenAIFunctionTool = failproofai.openaiResponsesTool(); + expect(asOpenAI.strict).toBe(true); }); it.each([ @@ -468,6 +545,21 @@ describe("the framework tools", () => { expect(recorded[1]!.tool_call_id).toBeUndefined(); }); + it("reads the call id from configurable.tool_call_id in either argument, toolCall.id first", async () => { + class DynamicStructuredTool { + constructor(readonly fields: { func: (...args: unknown[]) => Promise }) {} + } + const tool = vi.fn((func: unknown) => ({ func })); + const viaTool = langchainTool<{ func: (...args: unknown[]) => Promise }>({ module: { tool }, sessionId: "fixed" }); + const viaDst = langchainTool({ module: { DynamicStructuredTool }, sessionId: "fixed" }); + const input = { category: "looping", detail: "d" }; + await viaTool.func(input, { configurable: { tool_call_id: "cfg-2nd" } }); + await viaDst.fields.func(input, { runId: "run-1" }, { configurable: { tool_call_id: "cfg-3rd" } }); + await viaTool.func(input, { toolCall: { id: "tc" }, configurable: { tool_call_id: "cfg" } }); + await viaDst.fields.func(input, { runId: "run-2", configurable: {} }); + expect((await reports()).map((e) => e.tool_call_id)).toEqual(["cfg-2nd", "cfg-3rd", "tc", undefined]); + }); + it("falls back to DynamicStructuredTool", () => { class DynamicStructuredTool { constructor(readonly fields: Record) {} diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 6c61299cd..aab80588d 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -58,6 +58,7 @@ import { persistHookActivity } from "./hook-activity-store"; import { isSelfReportCursorCall, isSelfReportToolName, + readEnabledSelfReport, selfReportAntigravityWrappedArgs, selfReportArgs, SELF_REPORT_MCP_TOOL_NAME, @@ -672,6 +673,12 @@ async function captureJevIntent( * `SELF_REPORT_SERVER_RECORDS` has its report written by the MCP server * instead, so a hook that turns out to see the call there must not file it a * second time. A PostToolUse row is the call's completion, not a second report. + * + * Only while Self Reports is on, read from `self-report.json` on every call: a + * running agent keeps the MCP tools it loaded at startup, so taking our entry + * out of its config cannot stop it calling `report`, and this check is what + * makes `self-report disable` take effect at once. A missing, unreadable or + * disabled file records no report; the call is still allowed either way. */ function recordSelfReportCall( canonicalEventType: string, @@ -688,7 +695,7 @@ function recordSelfReportCall( // `self_report` event per row that has it, and a call that also raises a // PermissionRequest (or completes with a PostToolUse) is still one report. const isReportRow = canonicalEventType === "PreToolUse"; - const hookRecords = !SELF_REPORT_SERVER_RECORDS.includes(cli); + const hookRecords = isReportRow && !SELF_REPORT_SERVER_RECORDS.includes(cli) && readEnabledSelfReport() !== null; try { persistHookActivity({ timestamp: writtenAt, @@ -707,7 +714,7 @@ function recordSelfReportCall( cwd: session.cwd, permissionMode: session.permissionMode, hookEventName: session.hookEventName, - ...(isReportRow && hookRecords ? { selfReport: { ...selfReportArgs(parsed.tool_input), source: "mcp" as const } } : {}), + ...(hookRecords ? { selfReport: { ...selfReportArgs(parsed.tool_input), source: "mcp" as const } } : {}), }); } catch { hookLogWarn("activity persistence failed"); diff --git a/src/hooks/hook-activity-store.ts b/src/hooks/hook-activity-store.ts index ed6dc8dc0..a5f34b60c 100644 --- a/src/hooks/hook-activity-store.ts +++ b/src/hooks/hook-activity-store.ts @@ -25,6 +25,7 @@ import { join } from "node:path"; import type { IntegrationType } from "./types"; import { hookActivityDir } from "./fp-home"; import { sanitizeJevActivity, type JevCheckRecord } from "./jev-activity"; +import { selfReportClip } from "./self-report-names"; export const PAGE_SIZE = 25; @@ -285,7 +286,7 @@ export function persistHookActivity(input: HookActivityEntry): void { /** * Keep `selfReport` only in its declared shape: two strings of at most 2000 - * characters and `source: "mcp"`. Like the Jev fields it is shipped off the + * code points (no lone surrogate) and `source: "mcp"`. Like the Jev fields it is shipped off the * machine by the collector, so it is checked at this one door. */ function sanitizeSelfReportActivity(entry: HookActivityEntry): HookActivityEntry { @@ -298,8 +299,8 @@ function sanitizeSelfReportActivity(entry: HookActivityEntry): HookActivityEntry } const rec = sr as Record; out.selfReport = { - category: typeof rec.category === "string" ? rec.category.slice(0, 2000) : "", - detail: typeof rec.detail === "string" ? rec.detail.slice(0, 2000) : "", + category: typeof rec.category === "string" ? selfReportClip(rec.category) : "", + detail: typeof rec.detail === "string" ? selfReportClip(rec.detail) : "", source: "mcp", }; return out; diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts index 8b72791ba..72cf3bdc1 100644 --- a/src/hooks/self-report-cli.ts +++ b/src/hooks/self-report-cli.ts @@ -32,6 +32,7 @@ import { daemonSocketPresent, isDaemonConfigured } from "./daemon-client"; import { SELF_REPORT_CURSOR_APPROVAL_HINT, probeSelfReportHttp, + selfReportDaemonLive, selfReportHttpAllowed, selfReportCommandRunnable, selfReportRegistrationStatus, @@ -51,6 +52,8 @@ export interface SelfReportCliDeps { cliCommand?: string[]; /** Health probe override (tests): does the HTTP endpoint on this port answer? */ probeEndpoint?: (url: string, port: number) => Promise; + /** Ownership override (tests): is the endpoint on this port this home's daemon? (`selfReportDaemonLive`) */ + daemonLive?: (port: number) => Promise; /** Registration rows override (tests). */ registrations?: () => SelfReportRegistration[]; /** Sync override (tests). */ @@ -124,8 +127,27 @@ async function selfReportHttpHealth(rows: readonly SelfReportRegistration[], dep return health; } +/** + * For each answering port, whether it is THIS home's daemon that answers + * (`selfReportDaemonLive`): a name-only answer may be another user's or + * another FAILPROOFAI_HOME's daemon, which would record reports under its + * own home and credentials. + */ +async function selfReportHttpOwnership(health: ReadonlyMap, deps: SelfReportCliDeps): Promise> { + const live = deps.daemonLive ?? selfReportDaemonLive; + const owned = new Map(); + await Promise.all( + [...health].filter(([, answering]) => answering).map(async ([port]) => owned.set(port, await live(port))), + ); + return owned; +} + /** Per-agent registration state: transport, endpoint and whether it answers. */ -function selfReportRegistrationLines(rows: readonly SelfReportRegistration[], health: ReadonlyMap): string[] { +function selfReportRegistrationLines( + rows: readonly SelfReportRegistration[], + health: ReadonlyMap, + owned: ReadonlyMap, +): string[] { const hooked = rows.filter((r) => r.hooked || r.registered || r.conflict || r.error); if (hooked.length === 0) return ["Agents: none with failproofai hooks"]; return [ @@ -137,7 +159,8 @@ function selfReportRegistrationLines(rows: readonly SelfReportRegistration[], he else if (r.registered && r.transport === "http") { const port = selfReportUrlPort(r.endpoint); const ok = port !== null && health.get(port) === true; - state = `http ${r.endpoint ?? "?"} ${ok ? "(answering)" : "(NOT answering)"}`; + const mine = ok && owned.get(port!) === true; + state = `http ${r.endpoint ?? "?"} ${mine ? "(answering)" : ok ? "(answering, but NOT this home's daemon)" : "(NOT answering)"}`; } else if (r.registered) { const ok = !!r.endpoint && selfReportCommandRunnable(r.endpoint); state = `stdio ${r.endpoint ?? "?"} ${ok ? "(runnable)" : "(NOT runnable)"}`; @@ -151,15 +174,19 @@ function selfReportRegistrationLines(rows: readonly SelfReportRegistration[], he /** * Whether a row is registered over HTTP where it should not be: an endpoint - * that is not answering, or an agent whose reports the server records (those - * belong on stdio, where the server knows the caller's cwd; an older version - * registered them over HTTP). + * that is not answering, or that answers as some other home's daemon, or an + * agent whose reports the server records (those belong on stdio, where the + * server knows the caller's cwd; an older version registered them over HTTP). */ -function selfReportStranded(r: SelfReportRegistration, health: ReadonlyMap): boolean { +function selfReportStranded( + r: SelfReportRegistration, + health: ReadonlyMap, + owned: ReadonlyMap, +): boolean { if (!r.registered || r.transport !== "http") return false; if (!selfReportHttpAllowed(r.agent)) return true; const port = selfReportUrlPort(r.endpoint); - return port === null || health.get(port) !== true; + return port === null || health.get(port) !== true || owned.get(port) !== true; } async function selfReportStatus(deps: SelfReportCliDeps): Promise { @@ -181,16 +208,20 @@ async function selfReportStatus(deps: SelfReportCliDeps): Promise selfReportRegistrationStatus()); let rows = readRows(); let health = await selfReportHttpHealth(rows, deps); + let owned = await selfReportHttpOwnership(health, deps); // An agent left on the daemon's HTTP endpoint after the daemon died would - // have no report tool. Move it (live check: stdio unless a daemon answers). - if (settings.enabled && !deps.skipSync && rows.some((r) => selfReportStranded(r, health))) { + // have no report tool, and one on a port another home's daemon holds would + // report into that home. Move it (live check: stdio unless this home's + // daemon serves the endpoint). + if (settings.enabled && !deps.skipSync && rows.some((r) => selfReportStranded(r, health, owned))) { try { const results = await (deps.sync ?? (() => syncSelfReportMcp({ quiet: true })))(); if (selfReportSyncChanged(results)) { - lines.push("Repaired: agents on an HTTP endpoint that is not answering, or that belong on stdio, were re-synced:"); + lines.push("Repaired: agents on an HTTP endpoint that is not this home's answering daemon, or that belong on stdio, were re-synced:"); lines.push(...selfReportSyncLines(results).map((l) => ` ${l}`)); rows = readRows(); health = await selfReportHttpHealth(rows, deps); + owned = await selfReportHttpOwnership(health, deps); } } catch { lines.push("▲ Could not re-sync agents whose HTTP endpoint is not answering. Run `failproofai self-report sync`."); @@ -201,7 +232,7 @@ async function selfReportStatus(deps: SelfReportCliDeps): Promise; try { - const pages = readdirSync(dir) - .filter((f) => f.startsWith("page-") && f.endsWith(".jsonl")) - .map((f) => ({ f, m: selfReportMtime(join(dir, f)) })) - .sort((a, b) => b.m - a.m); - if (pages[0]) files.push(join(dir, pages[0].f)); + entries = getHookActivityEntriesSince(now - SELF_REPORT_SESSION_WINDOW_MS); } catch { - // No activity directory: nothing to attribute to. + return null; // No readable activity: nothing to attribute to. } let best: { rank: number; ts: number; id: string; cwd: string | undefined } | null = null; - for (const file of files) { - let text: string; - try { - text = readFileSync(file, "utf8"); - } catch { + // The distinct cwds of this integration's rows, to tell one project from several. + const cwds = new Set(); + for (const row of entries as unknown as Array>) { + const ts = typeof row.timestamp === "number" ? row.timestamp : NaN; + if ( + row.integration !== integration || + typeof row.sessionId !== "string" || + !row.sessionId || + !Number.isFinite(ts) || + now - ts > SELF_REPORT_SESSION_WINDOW_MS || + ts - now > 60_000 + ) { continue; } - for (const line of text.split("\n")) { - if (!line.trim()) continue; - let row: Record; - try { - row = JSON.parse(line) as Record; - } catch { - continue; - } - const ts = typeof row.timestamp === "number" ? row.timestamp : NaN; - if ( - row.integration !== integration || - typeof row.sessionId !== "string" || - !row.sessionId || - !Number.isFinite(ts) || - now - ts > SELF_REPORT_SESSION_WINDOW_MS || - ts - now > 60_000 - ) { - continue; - } - const rank = cwd ? selfReportCwdAffinity(cwd, row.cwd) : 0; - if (!best || rank > best.rank || (rank === best.rank && ts > best.ts)) { - best = { rank, ts, id: row.sessionId, cwd: typeof row.cwd === "string" && row.cwd ? row.cwd : undefined }; - } + const rowCwd = typeof row.cwd === "string" && row.cwd ? row.cwd : undefined; + cwds.add(rowCwd === undefined ? "" : rowCwd.replace(/\/+$/, "") || "/"); + const rank = cwd ? selfReportCwdAffinity(cwd, row.cwd) : 0; + if (!best || rank > best.rank || (rank === best.rank && ts > best.ts)) { + best = { rank, ts, id: row.sessionId, cwd: rowCwd }; } } - return best ? { sessionId: best.id, cwd: best.cwd } : null; + if (!best || (best.rank === 0 && cwds.size > 1)) return null; + return { sessionId: best.id, cwd: best.cwd }; } /** The session id of `selfReportFindSessionMatch`, or null. */ @@ -176,14 +164,6 @@ export function selfReportFindSession(integration: string, cwd: string, now: num return selfReportFindSessionMatch(integration, cwd, now)?.sessionId ?? null; } -function selfReportMtime(path: string): number { - try { - return statSync(path).mtimeMs; - } catch { - return 0; - } -} - /** * The agent id the collector files a hook event under (`agent_id` in * crates/fpai-collect/src/sources/hooks/transform.rs): `-= 0xd800 && code <= 0xdfff ? "\uFFFD" : ch; + n++; + } + return out; +} + /** * Every spelling of the report tool an agent's hook can deliver. Exact matches * only: a prefix or substring match would let any tool whose name merely diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts index e326cb9e3..5cadfc8b5 100644 --- a/src/hooks/self-report.ts +++ b/src/hooks/self-report.ts @@ -35,8 +35,9 @@ export { isSelfReportToolName, isSelfReportCursorCall, selfReportAntigravityWrappedArgs, + selfReportClip, } from "./self-report-names"; -import { SELF_REPORT_DETAIL_MAX, SELF_REPORT_DEFAULT_PORT } from "./self-report-names"; +import { SELF_REPORT_DEFAULT_PORT, selfReportClip } from "./self-report-names"; // ── Categories (contract §2) ──────────────────────────────────────────────── @@ -190,7 +191,7 @@ export const SELF_REPORT_RESULT_TEXT = "Recorded."; * A call's arguments as they are recorded: an unknown category is kept as-is * (never rejected), a missing or empty argument falls back to its first * non-empty alias (`SELF_REPORT_ARG_ALIASES`), else `""`; unknown keys are ignored; detail is cut to 2000 - * characters. A category is cut to the same bound so a hostile argument cannot + * code points (`selfReportClip`). A category is cut to the same bound so a hostile argument cannot * grow every activity row without limit. * * Accepts the arguments object itself, or a hook's `tool_input` that wraps it @@ -217,8 +218,8 @@ export function selfReportArgs(input: unknown): { category: string; detail: stri const category = selfReportArg(rec, "category", SELF_REPORT_ARG_ALIASES.category); const detail = selfReportArg(rec, "detail", SELF_REPORT_ARG_ALIASES.detail); return { - category: category.slice(0, SELF_REPORT_DETAIL_MAX), - detail: detail.slice(0, SELF_REPORT_DETAIL_MAX), + category: selfReportClip(category), + detail: selfReportClip(detail), }; } diff --git a/src/hooks/uninstall-cli.ts b/src/hooks/uninstall-cli.ts index 2b44c9bae..fbf8e897a 100644 --- a/src/hooks/uninstall-cli.ts +++ b/src/hooks/uninstall-cli.ts @@ -135,6 +135,12 @@ interface Leftovers { * kind of orphan this command clears. */ selfReportMcpPaths: string[]; + /** + * Agent config files that could not be inspected for that entry (unreadable + * or malformed). Not proof the entry is absent, so they are not "nothing to + * uninstall": the removal step tries them and reports any it cannot clean. + */ + selfReportMcpErrors: Array<{ path: string; error: string }>; } function survey(cwd?: string): Leftovers { @@ -176,18 +182,24 @@ function survey(cwd?: string): Leftovers { stagedBinaryDir: stagedBinaryDir && existsSync(stagedBinaryDir) ? stagedBinaryDir : null, daemonConfigured, homeExists: existsSync(failproofaiHome()), - selfReportMcpPaths: ownedSelfReportMcpPaths(), + ...selfReportMcpSurvey(), }; } -function ownedSelfReportMcpPaths(): string[] { +function selfReportMcpSurvey(): Pick { try { - return selfReportRegistrationStatus({ hooksInstalled: () => false }) - .filter((r) => r.registered) - .map((r) => r.path); - } catch { - // Unreadable files are reported by the removal step itself. - return []; + const rows = selfReportRegistrationStatus({ hooksInstalled: () => false }); + return { + selfReportMcpPaths: rows.filter((r) => r.registered).map((r) => r.path), + selfReportMcpErrors: rows + .filter((r) => r.error !== undefined) + .map((r) => ({ path: r.path || `${r.agent}'s MCP settings`, error: r.error! })), + }; + } catch (err) { + return { + selfReportMcpPaths: [], + selfReportMcpErrors: [{ path: "agent MCP settings", error: err instanceof Error ? err.message : String(err) }], + }; } } @@ -201,6 +213,7 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< const nothingToDo = found.clis.length === 0 && found.skillDirs.length === 0 && found.selfReportMcpPaths.length === 0 && + found.selfReportMcpErrors.length === 0 && !found.serviceInstalled && !found.stagedBinaryDir && !found.daemonConfigured && !(opts.purge && found.homeExists); if (nothingToDo) { @@ -230,6 +243,9 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< if (found.selfReportMcpPaths.length > 0) { removals.push(`the Self Reports MCP server from ${many(found.selfReportMcpPaths.length, "agent config")}`); } + if (found.selfReportMcpErrors.length > 0 && found.selfReportMcpPaths.length === 0) { + removals.push(`any Self Reports MCP server from ${many(found.selfReportMcpErrors.length, "agent config")} that could not be read`); + } if (found.serviceInstalled) removals.push("the failproofaid service (needs sudo)"); else if (found.stagedBinaryDir) removals.push(`the failproofaid binary in ${found.stagedBinaryDir} (needs sudo)`); if (purging) removals.push(home); @@ -248,6 +264,9 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< "Also resets enabled policies, custom policy paths and policy parameters in policies-config.json.", ); } + for (const { path, error } of found.selfReportMcpErrors) { + details.push(`Could not read ${path} (${error}); failproofai's MCP entry may still be in it.`); + } if (purging) details.push(`${home} holds your settings, credentials, audit history and the daemon binary.`); else if (found.homeExists) { details.push(`${found.clis.length > 0 ? "The rest of " : ""}${home} is kept unless you add --purge.`); diff --git a/test-fixtures/self-report/truncation.golden.json b/test-fixtures/self-report/truncation.golden.json new file mode 100644 index 000000000..25d0bec66 --- /dev/null +++ b/test-fixtures/self-report/truncation.golden.json @@ -0,0 +1,13 @@ +{ + "comment": "How detail is cut to 2000 characters, counted in Unicode code points (never UTF-16 units, never through a surrogate pair). input = pad_char repeated pad times + tail; the recorded value = the same pad + expected_tail. Every implementation (CLI, daemon, both SDKs) is tested against these cases.", + "max": 2000, + "cases": [ + {"pad_char": "a", "pad": 1999, "tail": "😀 and more text", "expected_tail": "😀"}, + {"pad_char": "a", "pad": 1998, "tail": "😀😀😀", "expected_tail": "😀😀"}, + {"pad_char": "a", "pad": 2000, "tail": "😀", "expected_tail": ""}, + {"pad_char": "a", "pad": 1999, "tail": "éè", "expected_tail": "é"}, + {"pad_char": "😀", "pad": 2000, "tail": "x", "expected_tail": ""}, + {"pad_char": "😀", "pad": 1999, "tail": "中文", "expected_tail": "中"}, + {"pad_char": "a", "pad": 0, "tail": "short 😀", "expected_tail": "short 😀"} + ] +} From bfbbbe364379664164eaee38ff32bf36f9895dc5 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Fri, 27 Nov 2026 14:33:59 +0530 Subject: [PATCH 15/54] [release] 1.0.18-beta.1 for the Self Reports beta Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- Cargo.lock | 6 +++--- Cargo.toml | 2 +- hermes-plugin/plugin.yaml | 2 +- package.json | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 92efd3a1b..42702697f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## 1.0.18-beta.0 — 2026-11-24 +## 1.0.18-beta.1 — 2026-11-27 ### Features diff --git a/Cargo.lock b/Cargo.lock index ffe0db5af..f04dc5f4e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -298,7 +298,7 @@ dependencies = [ [[package]] name = "failproofaid" -version = "1.0.17" +version = "1.0.18-beta.1" dependencies = [ "fpai-collect", "fpai-ipc", @@ -361,7 +361,7 @@ dependencies = [ [[package]] name = "fpai-collect" -version = "1.0.17" +version = "1.0.18-beta.1" dependencies = [ "axum", "getrandom 0.4.3", @@ -382,7 +382,7 @@ dependencies = [ [[package]] name = "fpai-ipc" -version = "1.0.17" +version = "1.0.18-beta.1" dependencies = [ "libc", "proptest", diff --git a/Cargo.toml b/Cargo.toml index fd6017f4a..634beb3d2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "1.0.17" +version = "1.0.18-beta.1" edition = "2024" license-file = "LICENSE" repository = "https://github.com/FailproofAI/failproofai" diff --git a/hermes-plugin/plugin.yaml b/hermes-plugin/plugin.yaml index 5525d5425..5f234c8e2 100644 --- a/hermes-plugin/plugin.yaml +++ b/hermes-plugin/plugin.yaml @@ -1,5 +1,5 @@ name: failproofai -version: 1.0.17 +version: 1.0.18-beta.1 description: Real-time FailproofAI policy enforcement for Hermes manifest_version: 2 api_version: 1 diff --git a/package.json b/package.json index 798b2d4a9..810ec5ae3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "failproofai", - "version": "1.0.17", + "version": "1.0.18-beta.1", "description": "The reliability layer for AI agents: see every failure, stop it in realtime. Policies hooked into 12 agent harnesses — Claude Code, Codex, Cursor, Hermes, OpenClaw and more — block the tool call before it runs. Local dashboard included, no account needed.", "bin": { "failproofai": "./dist/cli.mjs", From cf8fdf0fddc7894d3be5e5c883a08aa6a557e6e8 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Fri, 27 Nov 2026 15:54:57 +0530 Subject: [PATCH 16/54] [self-reports] On by default; apply selfReport only from an accepted desired-state Self Reports is now on unless turned off: - With no self-report.json, every reader (hook recorder, stdio server, the daemon's HTTP server, status, the daemon's startup sync) treats it as on with the default categories, unless the machine is Cloud enrolled (off until the daemon writes the org's setting) or config.json says selfReport.enabled false. A malformed file stays off. TS resolveSelfReport and Rust effective_settings implement the same rule; the daemon installs its own Enrolment::resolve as the enrolment check. - policies --install and config write self-report.json (source local, on) when it is missing off Cloud, then register the MCP entries. - Leaving Cloud re-syncs agents, since the open-source default now applies. - Docs, help, README and CHANGELOG say on by default and how to turn it off. Review fixes: - The daemon noted a desired-state's selfReport before the reconcile checked for a rollback, so a refused out-of-order deployment still flipped the feature. It is now noted only after the reconcile accepts the response (not on InvalidDesiredState or Withdrawn), with regression tests. - The Python SDK skill docs say a report with no tool_call_id takes the newest open report call, and to pass tool_call_id when calls overlap. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + README.md | 3 +- __tests__/hooks/self-report-handler.test.ts | 25 +- __tests__/hooks/self-report-install.test.ts | 99 +++++++- __tests__/hooks/self-report.test.ts | 86 ++++++- bin/failproofai.mjs | 33 ++- crates/failproofaid/src/cloud_client.rs | 163 ++++++++++++- crates/failproofaid/src/main.rs | 11 +- crates/failproofaid/src/self_report.rs | 73 ++++-- crates/failproofaid/tests/audit_lane_e2e.rs | 6 +- crates/fpai-collect/src/self_report.rs | 226 +++++++++++++++++-- crates/fpai-collect/tests/self_report_mcp.rs | 32 ++- docs/reference/events-and-configuration.mdx | 4 +- docs/self-reports.mdx | 21 +- sdk/python/README.md | 8 +- sdk/python/skill/SKILL.md | 7 +- sdk/python/skill/references/integration.md | 7 +- sdk/typescript/README.md | 6 +- src/hooks/manager.ts | 50 ++-- src/hooks/self-report-cli.ts | 46 +++- src/hooks/self-report-install.ts | 10 +- src/hooks/self-report.ts | 143 +++++++++++- 22 files changed, 940 insertions(+), 121 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 42702697f..89056b983 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,11 @@ ### Features - Self Reports: every hooked agent gets a `report` tool (MCP server `failproofai`, served by `failproofaid` at `http://127.0.0.1:4319/mcp` or by `failproofai mcp` over stdio) to say it is stuck, under six default categories or the organization's own; the hook allows the call before any policy, pause or Jev review and records it as a `self_report` event, the MCP server records it for agents whose hooks do not see MCP calls, the setting comes from Cloud (`selfReport` in desired-state) or `failproofai self-report enable|disable|status|test|sync` and lives in `~/.failproofai/self-report.json`, and both SDKs add `self_report()` / `selfReport()` with ready-made framework tools; the server's initialize result carries short instructions (agents that defer MCP tools, like Claude Code, still see them), and HTTP vs stdio is chosen from a live daemon check that the daemon re-runs at startup; the instructions name the `category` and `detail` arguments, and a call that sends the detail under another name (`summary`, `sentence`, `message`, ...) still records it; Cursor reports are recorded by the MCP server (its tool hook does not name the server), Antigravity's `call_mcp_tool` wrapper for `failproofai`/`report` is allowed ahead of the policies, Copilot's likely `failproofai-report` spelling is exempt, Pi's entry is exposed directly, server-recorded reports find their session by an exact, then related working directory, else the agent's newest session only when all its sessions in the 6-hour window share one directory, reading every activity page in that window, and take the session's own agent, and a hand-started daemon finds `failproofai` on PATH for its startup sync; HTTP is used only for Claude Code and Codex (hook-recorded) and only when the endpoint answers with the instance id of the daemon behind this home's socket, every server-recorded agent stays on stdio, the HTTP server records nothing while Self Reports is off and never attributes a report across projects, a Cursor call that fails the server check always goes through the policies, `self-report sync` refuses a stale home instead of migrating it unattended, and `uninstall` also finds an orphan MCP registration and reports an agent config it cannot read; the Claude Code and Codex hooks record a report only while `self-report.json` says enabled (read on every call, so `disable` takes effect in a running agent), the detail is cut to 2000 code points everywhere so a cut never splits a surrogate pair (one did, and the collector dropped the whole row), and `status` re-syncs an agent whose HTTP endpoint answers as another home's daemon +- Self Reports is on by default: `policies --install` and `config` register the `failproofai` MCP server in every hooked agent and write `~/.failproofai/self-report.json` on with the six default categories, and with no settings file every reader (the hook, `failproofai mcp`, the daemon's HTTP server, `status`) treats it as on, except on a Cloud-connected machine, which stays off until the daemon writes the organization's setting (on unless the organization turned it off); turn it off with `failproofai self-report disable`, or the Cloud switch on a connected machine, which removes the MCP entries and stops recording, and an explicit `enabled: false` always wins; an unparsable settings file still reads as off (#1062) ### Fixes +- A desired-state response the daemon refuses (a deployment rollback, or a disconnect during the poll) no longer changes Self Reports: its `selfReport` setting is applied only after the reconcile accepts the response, so an out-of-order older deployment can no longer turn reporting back on (#1062) - Retire the hook-sync agent and stop publishing its image: `docker-hook-sync/`, its prompt and `build-image.yml` (which pushed `ghcr.io/failproofai/hook-sync` publicly every day) are removed. The agent ran Claude Code with permission checks skipped, a GitHub write token and a Claude token in its environment and no failproofai hooks, after reading a third-party npm README. Nothing had run it since July (FailproofAI/agenteye#1797, #1055) - `fp`, the dashboard's api-server client, and the collector's uploader and OTLP relay refuse a plain `http://` URL for any host but `localhost` and loopback addresses, so `FP_DASHBOARD_URL`, `FAILPROOF_API_URL` or `FAILPROOFAI_INGEST_URL` can no longer put a session, a token, a sign-in code or the ingest key on the network in clear, and the api-server client no longer follows redirects; `fp logout` still clears a session saved against such a URL, without sending it (#1057) - A dashboard bound off loopback (`FAILPROOFAI_DASHBOARD_HOST`) requires a per-launch access token on every request: the launch screen and `failproofai audit` print the address with `?token=` (audit no longer hands it to a browser opener, whose command line other local users can read), and the browser trades it for an HttpOnly cookie. Before, any machine on the network could set `Host` and `Origin` itself and read transcripts, change policies, or install a policy pack, which runs its code (#1057) diff --git a/README.md b/README.md index ea1a8f266..9cc01c2dc 100644 --- a/README.md +++ b/README.md @@ -287,7 +287,8 @@ hand an agent more autonomy, not less: - **Agents that say when they're stuck.** [Self Reports](https://docs.befailproof.ai/self-reports) gives every agent a `report` tool for looping, a broken credential, missing context or a request it cannot do. No policy can block the call, and each report lands on its - session, so you see where agents get stuck without reading every transcript. + session, so you see where agents get stuck without reading every transcript. It is on + by default; `failproofai self-report disable` (or the Cloud switch) turns it off. --- diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index 256bb89f4..4b0270c9b 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -122,7 +122,20 @@ describe("Self Reports short-circuit", () => { const settings = () => join(home, "self-report.json"); it.each([ - ["missing", () => rmSync(settings(), { force: true })], + [ + "missing on a Cloud-enrolled machine", + () => { + rmSync(settings(), { force: true }); + writeFileSync(join(home, "credentials.json"), JSON.stringify({ cloud: { url: "https://x", machine_id: "m", token: "t" } })); + }, + ], + [ + "missing with config.json selfReport.enabled false", + () => { + rmSync(settings(), { force: true }); + writeFileSync(join(home, "config.json"), JSON.stringify({ selfReport: { enabled: false } })); + }, + ], ["disabled", () => writeEffectiveSelfReport({ enabled: false })], ["malformed", () => writeFileSync(settings(), "{ not json")], ["of another version", () => writeFileSync(settings(), JSON.stringify({ version: 2, enabled: true }))], @@ -138,6 +151,16 @@ describe("Self Reports short-circuit", () => { expect(all.every((r) => r.selfReport === undefined)).toBe(true); }); + it("missing off Cloud: on by default, the report is recorded with no settings file", async () => { + rmSync(settings(), { force: true }); + for (const [event, cli] of [["PreToolUse", "claude"], ["pre_tool_use", "codex"]] as const) { + expect((await evaluateHookEvent(event, cli, report())).evaluation?.decision).toBe("allow"); + } + const all = rows(); + expect(all).toHaveLength(2); + expect(all.every((r) => (r.selfReport as { source?: string } | undefined)?.source === "mcp")).toBe(true); + }); + it("disabling during a session stops the next call's report, and enabling brings it back", async () => { await evaluateHookEvent("PreToolUse", "claude", report()); writeEffectiveSelfReport({ enabled: false }); diff --git a/__tests__/hooks/self-report-install.test.ts b/__tests__/hooks/self-report-install.test.ts index 9a45e047e..fe46e897c 100644 --- a/__tests__/hooks/self-report-install.test.ts +++ b/__tests__/hooks/self-report-install.test.ts @@ -24,7 +24,13 @@ import { } from "../../src/hooks/self-report-install"; import { mergeTomlManagedBlock } from "../../src/hooks/toml-managed-block"; import { INTEGRATION_TYPES, type IntegrationType } from "../../src/hooks/types"; -import { SELF_REPORT_SERVER_RECORDS } from "../../src/hooks/self-report"; +import { + SELF_REPORT_SERVER_RECORDS, + ensureSelfReportSettingsFile, + readEffectiveSelfReport, + readEnabledSelfReport, +} from "../../src/hooks/self-report"; +import { runSelfReportCommand } from "../../src/hooks/self-report-cli"; const CLI = "/usr/local/bin/failproofai"; let home: string; @@ -217,8 +223,19 @@ describe("transport choice", () => { expect(entryIn("claude")).toEqual({ type: "http", url: "http://127.0.0.1:5555/mcp?agent=claude" }); }); - it("reads a missing or broken settings file as disabled", async () => { + it("reads a missing file as on off Cloud, off on Cloud, and a broken file as off", async () => { + // On by default: no file and no local config on an open-source machine. + expect(readSelfReportMcpSettings()).toEqual({ enabled: true, port: 4319 }); + // Cloud enrolled, the daemon has not written the file yet: off. + vi.stubEnv("FAILPROOFAI_CLOUD_URL", "https://cloud.example.com"); + expect(readSelfReportMcpSettings()).toEqual({ enabled: false, port: 4319 }); + vi.stubEnv("FAILPROOFAI_CLOUD_URL", ""); + put(resolve(home, ".failproofai", "credentials.json"), JSON.stringify({ cloud: { url: "https://x", machine_id: "m", token: "t" } })); expect(readSelfReportMcpSettings().enabled).toBe(false); + // Switched back to open source: the default applies again. + put(resolve(home, ".failproofai", "config.json"), JSON.stringify({ mode: { kind: "oss" } })); + expect(readSelfReportMcpSettings().enabled).toBe(true); + // A malformed file is off whatever else is true (fail safe). put(resolve(home, ".failproofai", "self-report.json"), "{nope"); expect(readSelfReportMcpSettings()).toEqual({ enabled: false, port: 4319 }); }); @@ -545,3 +562,81 @@ describe("mergeTomlManagedBlock", () => { expect(() => mergeTomlManagedBlock("# >>> b >>>\nx=1\n", null, M)).toThrow(); }); }); + +describe("on by default: install, disable, enable", () => { + const settingsFile = () => resolve(home, ".failproofai", "self-report.json"); + /** The sync the CLI runs, against this test's agents and with no daemon. */ + const sync = () => + syncSelfReportMcp({ + quiet: true, + binaryPath: CLI, + agents: ["claude", "cursor"], + deps: { daemonLive: async () => false, hooksInstalled: () => true }, + }); + + it("a fresh install with no file writes it on, registers the server and records", async () => { + expect(existsSync(settingsFile())).toBe(false); + const written = await ensureSelfReportSettingsFile(); + expect(written).toMatchObject({ enabled: true, source: "local" }); + expect(readEffectiveSelfReport()?.categories.map((c) => c.name)).toEqual([ + "looping", "cannot_do_request", "invalid_tool_or_credential", "missing_context", "repeated_tool_failure", "task_failure", + ]); + const results = await sync(); + expect(results.map((r) => r.status)).toEqual(["ok", "ok"]); + expect(entryIn("claude")).toMatchObject({ type: "stdio" }); + expect(entryIn("cursor")).toBeDefined(); + expect(readEnabledSelfReport()).not.toBeNull(); + // A second install leaves the file as it is. + expect(await ensureSelfReportSettingsFile()).toBeNull(); + }); + + it("disable removes the entries and stops recording; enable brings both back", async () => { + await ensureSelfReportSettingsFile(); + await sync(); + expect(entryIn("claude")).toBeDefined(); + + const off = await runSelfReportCommand(["disable"], { sync }); + expect(off.exitCode).toBe(0); + expect(readEffectiveSelfReport()?.enabled).toBe(false); + expect(readEnabledSelfReport()).toBeNull(); + expect(entryIn("claude")).toBeUndefined(); + expect(entryIn("cursor")).toBeUndefined(); + const config = JSON.parse(read(resolve(home, ".failproofai", "config.json"))); + expect(config.selfReport.enabled).toBe(false); + + // An explicit off wins over a later install, with or without the file. + expect(await ensureSelfReportSettingsFile()).toBeNull(); + rmSync(settingsFile()); + expect(readEnabledSelfReport()).toBeNull(); + expect(await ensureSelfReportSettingsFile()).toMatchObject({ enabled: false }); + expect((await sync()).every((r) => r.status === "ok")).toBe(true); + expect(entryIn("claude")).toBeUndefined(); + + const on = await runSelfReportCommand(["enable"], { sync }); + expect(on.exitCode).toBe(0); + expect(readEnabledSelfReport()).not.toBeNull(); + expect(entryIn("claude")).toBeDefined(); + expect(entryIn("cursor")).toBeDefined(); + }); + + it("a Cloud-enrolled machine writes no file on install and stays off until the daemon writes it", async () => { + vi.stubEnv("FAILPROOFAI_CLOUD_URL", "https://cloud.example.com"); + expect(await ensureSelfReportSettingsFile()).toBeNull(); + expect(existsSync(settingsFile())).toBe(false); + expect(readEnabledSelfReport()).toBeNull(); + await sync(); + expect(entryIn("claude")).toBeUndefined(); + const refused = await runSelfReportCommand(["disable"], { sync }); + expect(refused.exitCode).toBe(1); + expect(refused.lines.join("\n")).toContain("Settings > Self Reports"); + }); + + it("a malformed file is off and an install leaves it alone", async () => { + put(settingsFile(), "{ not json"); + expect(await ensureSelfReportSettingsFile()).toBeNull(); + expect(read(settingsFile())).toBe("{ not json"); + expect(readEnabledSelfReport()).toBeNull(); + await sync(); + expect(entryIn("claude")).toBeUndefined(); + }); +}); diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index efba4f2de..781943ae2 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -16,7 +16,9 @@ import { inputSchema, isSelfReportToolName, readEffectiveSelfReport, + resolveSelfReport, selfReportArgs, + selfReportCloudEnrolled, selfReportCloudManaged, validateSelfReportCategories, validateSelfReportGuidance, @@ -171,6 +173,49 @@ describe("self-report.json (contract §4)", () => { }); }); +describe("resolveSelfReport: on by default (contract §4)", () => { + const enrolled = () => true; + const oss = () => false; + it("a missing file is on with the defaults off Cloud, and off on Cloud", () => { + expect(resolveSelfReport(undefined, oss)).toMatchObject({ enabled: true, source: "local", categories: DEFAULT_CATEGORIES, guidance: null }); + expect(resolveSelfReport(undefined, enrolled)).toBeNull(); + }); + it("an explicit local off in config.json wins over the default", () => { + writeFileSync(join(home, "config.json"), JSON.stringify({ selfReport: { enabled: false } })); + expect(resolveSelfReport(undefined, oss)).toBeNull(); + writeFileSync(join(home, "config.json"), JSON.stringify({ selfReport: { categories: [] } })); + expect(resolveSelfReport(undefined, oss)?.enabled).toBe(true); + }); + it("a present file decides, and a malformed one is off", () => { + writeEffectiveSelfReport({ enabled: false }); + expect(resolveSelfReport(undefined, oss)?.enabled).toBe(false); + writeFileSync(join(home, "self-report.json"), "{not json"); + expect(resolveSelfReport(undefined, oss)).toBeNull(); + expect(resolveSelfReport(undefined, enrolled)).toBeNull(); + }); +}); + +describe("selfReportCloudEnrolled (sync, the daemon's Enrolment::resolve)", () => { + it("follows the env, the credential files and the oss veto", () => { + expect(selfReportCloudEnrolled()).toBe(false); + writeFileSync(join(home, "credentials.json"), JSON.stringify({ ingest: { key: "k" } })); + expect(selfReportCloudEnrolled()).toBe(false); + writeFileSync(join(home, "credentials.json"), JSON.stringify({ cloud: { url: "https://x", machine_id: "m", token: "t" } })); + expect(selfReportCloudEnrolled()).toBe(true); + writeFileSync(join(home, "credentials.json"), "{broken"); + expect(selfReportCloudEnrolled()).toBe(true); + writeFileSync(join(home, "config.json"), JSON.stringify({ mode: { kind: "oss" } })); + expect(selfReportCloudEnrolled()).toBe(false); + process.env.FAILPROOFAI_CLOUD_URL = "https://example.invalid"; + expect(selfReportCloudEnrolled()).toBe(true); + delete process.env.FAILPROOFAI_CLOUD_URL; + rmSync(join(home, "config.json")); + rmSync(join(home, "credentials.json")); + writeFileSync(join(home, "cloud.json"), JSON.stringify({ schemaVersion: 1 })); + expect(selfReportCloudEnrolled()).toBe(true); + }); +}); + describe("Cloud enrolment", () => { it("is off with no credential, on with FAILPROOFAI_CLOUD_URL", async () => { expect(await selfReportCloudManaged()).toBe(false); @@ -362,6 +407,7 @@ const PING = { jsonrpc: "2.0", id: 4, method: "ping" }; describe("failproofai mcp (stdio, spawned)", () => { it("answers initialize, ping, and an empty tools/list while disabled — with no daemon", async () => { + writeEffectiveSelfReport({ enabled: false }); const { replies, code } = await runMcp([], [INIT, INITIALIZED, LIST, PING], home); expect(code).toBe(0); expect(replies.map((r) => r.id)).toEqual([1, 2, 4]); @@ -385,6 +431,22 @@ describe("failproofai mcp (stdio, spawned)", () => { expect(replies[2]).toEqual({ jsonrpc: "2.0", id: 3, result: { content: [{ type: "text", text: "Recorded." }] } }); }, 30_000); + it("with no settings file (not Cloud enrolled) lists the tool and records: on by default", async () => { + const { replies } = await runMcp(["--agent", "pi"], [INIT, LIST, CALL], home); + expect((replies[0].result as Record).instructions).toBe(selfReportInstructions(DEFAULT_CATEGORIES)); + const tools = (replies[1].result as { tools: Array> }).tools; + expect(tools.map((t) => t.name)).toEqual(["report"]); + expect(readdirSync(join(home, "custom-agents", "events"))).toHaveLength(1); + }, 30_000); + + it("with no settings file on a Cloud-enrolled machine lists nothing and records nothing", async () => { + writeFileSync(join(home, "credentials.json"), JSON.stringify({ cloud: { url: "https://x", machine_id: "m", token: "t" } })); + const { replies } = await runMcp(["--agent", "pi"], [INIT, LIST, CALL], home); + expect((replies[0].result as Record)).not.toHaveProperty("instructions"); + expect(replies[1]).toEqual({ jsonrpc: "2.0", id: 2, result: { tools: [] } }); + expect(() => readdirSync(join(home, "custom-agents", "events"))).toThrow(); + }, 30_000); + it("writes no event for a hook-recorded agent (claude)", async () => { writeEffectiveSelfReport({ enabled: true }); await runMcp(["--agent", "claude"], [INIT, CALL], home); @@ -661,16 +723,34 @@ describe("failproofai self-report enable | disable | status", () => { const changed = await runSelfReportCommand(["enable"], { probeEndpoint: async () => false, sync: async () => [{ agent: "claude", path: "/x", action: "added", transport: "http", status: "ok" }] }); expect(changed.lines.join("\n")).toContain("Agents updated."); const off = await runSelfReportCommand(["disable"], { sync: async () => [] }); - expect(off.lines).toEqual(["✓ Self Reports is off."]); + expect(off.lines).toEqual([ + "✓ Self Reports is off. Agents lose the report tool and nothing is recorded.", + " Turn it back on with `failproofai self-report enable`.", + ]); }); - it("status with no settings file says it is off", async () => { + it("status with no settings file says it is on by default, and how to turn it off", async () => { const r = await runSelfReportCommand(["status"], deps); expect(r.exitCode).toBe(0); - expect(r.lines[0]).toContain("off"); + expect(r.lines[0]).toBe("Self Reports: on"); + expect(r.lines.join("\n")).toContain("the default (no settings file yet)"); + expect(r.lines.join("\n")).toContain("`failproofai self-report disable`"); + }); + + it("status with no settings file on a Cloud-enrolled machine says it is off until Cloud sends it", async () => { + process.env.FAILPROOFAI_CLOUD_URL = "https://example.invalid"; + const r = await runSelfReportCommand(["status"], deps); + expect(r.lines[0]).toContain("off (waiting for FailproofAI Cloud"); + }); + + it("status with a malformed settings file says it is off", async () => { + writeFileSync(join(home, "self-report.json"), "{not json"); + const r = await runSelfReportCommand(["status"], deps); + expect(r.lines[0]).toBe("Self Reports: off (the settings file cannot be read)"); }); it("test refuses while disabled and rejects an unknown agent", async () => { + writeEffectiveSelfReport({ enabled: false }); expect((await runSelfReportCommand(["test", "--agent", "claude"], deps)).exitCode).toBe(1); writeEffectiveSelfReport({ enabled: true }); const r = await runSelfReportCommand(["test", "--agent", "nope"], deps); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index c882f0260..4a65b5923 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -611,7 +611,7 @@ async function runCli() { ["(no args)", "Open the policy dashboard on localhost:8020"], ["audit", "Scan your agents' history for risky and wasteful patterns"], ["otel", "Opt in to OpenTelemetry from agents and apps"], - ["self-report", "Let agents report to you when they are stuck"], + ["self-report", "Let agents report to you when they are stuck (on by default)"], ]), ...section("Less often", [ ["harness", "Collect sessions from extra locations per agent"], @@ -1070,19 +1070,20 @@ async function runCli() { // self-report status | enable | disable | test // - // Self Reports: the `report` tool agents call when they are stuck. On a - // machine managed by FailproofAI Cloud the setting comes from Cloud and - // enable/disable refuse; otherwise they write config.json's `selfReport` and - // ~/.failproofai/self-report.json, then update the agents' MCP entries. + // Self Reports: the `report` tool agents call when they are stuck. On by + // default. On a machine managed by FailproofAI Cloud the setting comes from + // Cloud and enable/disable refuse; otherwise they write config.json's + // `selfReport` and ~/.failproofai/self-report.json, then update the agents' + // MCP entries (disable removes them and stops recording). if (args[0] === "self-report") { const subArgs = args.slice(1); if (subArgs.length === 0 || subArgs.includes("--help") || subArgs.includes("-h")) { await printHelp({ name: "self-report", usage: [ - ["failproofai self-report status", "Show whether it is on, and where that came from"], - ["failproofai self-report enable [options]", "Turn it on for this machine"], - ["failproofai self-report disable", "Turn it off for this machine"], + ["failproofai self-report status", "Show whether it is on (it is by default), and where that came from"], + ["failproofai self-report enable [options]", "Turn it back on for this machine, or change its categories"], + ["failproofai self-report disable", "Turn it off: removes the MCP entries and stops recording"], ["failproofai self-report test --agent ", "Send one test report end to end"], ["failproofai self-report sync [--quiet]", "Update each hooked agent's MCP entry (the daemon runs this)"], ], @@ -1092,7 +1093,8 @@ async function runCli() { ["--agent ", "With test: the agent to send it as"], ], examples: [ - "failproofai self-report enable", + "failproofai self-report status", + "failproofai self-report disable", "failproofai self-report test --agent claude", ], }); @@ -2202,10 +2204,17 @@ async function runCli() { else updateExit = 1; } } - // Self Reports: bring every hooked agent's MCP registration in line with - // self-report.json, also when setup found the machine already configured - // and wrote no hooks. Best-effort; prints only what changed. + // Self Reports (on by default): write self-report.json when it is missing + // off Cloud, then bring every hooked agent's MCP registration in line with + // it, also when setup found the machine already configured and wrote no + // hooks. Best-effort; prints only what changed. if (result.applied) { + try { + const { ensureSelfReportSettingsFile } = await import("../src/hooks/self-report"); + await ensureSelfReportSettingsFile(); + } catch { + // the readers apply the same default without the file + } try { const { syncSelfReportMcp, selfReportSyncLines } = await import("../src/hooks/self-report-install"); const lines = selfReportSyncLines(await syncSelfReportMcp({ quiet: true })); diff --git a/crates/failproofaid/src/cloud_client.rs b/crates/failproofaid/src/cloud_client.rs index bd93b3d12..86a69f0eb 100644 --- a/crates/failproofaid/src/cloud_client.rs +++ b/crates/failproofaid/src/cloud_client.rs @@ -600,6 +600,14 @@ fn enrolment_withdrawn() -> bool { matches!(Enrolment::resolve(), Ok(None)) } +/// Is this machine Cloud enrolled, for Self Reports' missing-file rule +/// (`fpai_collect::self_report::effective_settings`)? The same resolution as +/// the policy poll; an unreadable credential counts as enrolled, so a missing +/// `self-report.json` stays off rather than guessing on. +pub fn self_report_enrolled() -> bool { + !enrolment_withdrawn() +} + impl Enrolment { fn resolve() -> Result, String> { if let Some(enrolment) = Self::from_env()? { @@ -839,7 +847,7 @@ impl CloudClient { &self, applied: Option, policy_errors: Option<&str>, - ) -> Result { + ) -> Result<(DesiredState, Option), PollFailure> { let mut url = self .base_url .join("enforcement/v1/desired-state") @@ -883,9 +891,11 @@ impl CloudClient { // does not decode) must not turn troubleshooting back on or start // an upload, so the last valid answer keeps standing. let (desired, consent, self_report) = decode_desired_state(raw)?; - // Applied by the maintenance lane after this tick (see - // `self_report::tick`), so a refused response changes nothing. - crate::self_report::note_desired(self_report); + // `selfReport` is NOT noted here: the reconcile can still refuse + // this response (a deployment rollback, a withdrawn enrolment), + // and a refused response must not flip the feature. The caller + // notes it once the reconcile accepted the deployment + // (`reconcile_and_note_self_report`). // The org's troubleshooting switch: `machineLogs: false` means // send no daemon log (logship.rs). Absent, from a Cloud with it // on or one that predates the key, means send. @@ -894,7 +904,7 @@ impl CloudClient { if let Some(id) = consent.log_request { crate::logship::note_request(&id); } - Ok(desired) + Ok((desired, self_report)) }) } @@ -1441,7 +1451,7 @@ fn poll_once_guarded( ) .map(|errors| encode_policy_errors(&errors)); match cloud.poll_desired_state(applied, report.as_deref()) { - Ok(desired) => { + Ok((desired, self_report)) => { // The GET created/checked-in the machine row the PUT requires. // Do not let a roster network outage interrupt local enforcement. if let Ok(path) = agent_roster::roster_path() @@ -1450,8 +1460,10 @@ fn poll_once_guarded( { report_and_reclaim(cloud, &path, Path::new(&home), &roster); } - match store.reconcile_unless( + match reconcile_and_note_self_report( + store, &desired, + self_report, &|policy: &DesiredPolicy| cloud.artifact(policy), withdrawn, ) { @@ -1505,6 +1517,37 @@ fn poll_once_guarded( } } +/// Reconcile `desired`, then hand its `selfReport` block to the maintenance +/// lane only when the reconcile accepted the response. +/// +/// Refused means: the response itself failed validation (an unknown shape, a +/// deployment below the rollback floor — both `InvalidDesiredState`), or the +/// machine was disconnected while the poll was in flight (`Withdrawn`). Such a +/// response is not the server's current answer for this machine, so its +/// `selfReport` must not change anything: an out-of-order deployment 99 that +/// says "on" after deployment 100 said "off" leaves the feature off. +/// +/// An artifact failure (fetch, hash, I/O) is not a refusal: the response passed +/// the rollback guard and is the server's newest answer, and an org toggle must +/// not wait on an unrelated policy download that may keep failing. +fn reconcile_and_note_self_report( + store: &PolicyStore, + desired: &DesiredState, + self_report: Option, + fetcher: &impl crate::cloud_policies::ArtifactFetcher, + withdrawn: &dyn Fn() -> bool, +) -> Result { + let result = store.reconcile_unless(desired, fetcher, withdrawn); + let refused = matches!( + result, + Err(ReconcileError::InvalidDesiredState(_) | ReconcileError::Withdrawn) + ); + if !refused && !withdrawn() { + crate::self_report::note_desired(self_report); + } + result +} + pub fn poll_interval_from_env() -> Duration { let milliseconds = env_value("FAILPROOFAI_CLOUD_POLICY_POLL_MS") .and_then(|value| value.parse::().ok()) @@ -1568,6 +1611,7 @@ mod tests { /// The poll without an error report, for the tests that predate it. fn desired_state(&self, applied: Option) -> Result { self.poll_desired_state(applied, None) + .map(|(desired, _)| desired) .map_err(|failure| failure.message) } } @@ -2302,6 +2346,111 @@ mod tests { store } + fn self_report_on(enabled: bool) -> Option { + Some(crate::self_report::Desired { + enabled, + categories: None, + guidance: None, + }) + } + + /// The review's replay: deployment 100 switched Self Reports off, then an + /// out-of-order deployment 99 said on. The rollback is refused, and its + /// `selfReport` must be refused with it: nothing is queued for the lane, so + /// the feature stays off and `active.json` stays at 100. + #[test] + fn a_rolled_back_response_does_not_change_self_reports() { + let _env = lock_env(); + let _ = crate::self_report::take_pending(); + let store = temp_store("self-report-rollback"); + + reconcile_and_note_self_report( + &store, + &jev_state(100), + self_report_on(false), + &serve, + &|| false, + ) + .unwrap(); + assert_eq!( + crate::self_report::take_pending(), + Some(self_report_on(false)), + "an accepted response queues its setting" + ); + + let refused = reconcile_and_note_self_report( + &store, + &jev_state(99), + self_report_on(true), + &serve, + &|| false, + ); + assert!( + matches!(&refused, Err(ReconcileError::InvalidDesiredState(m)) if m.contains("rollback")), + "{refused:?}" + ); + assert_eq!( + crate::self_report::take_pending(), + None, + "a rolled-back response must not queue its selfReport" + ); + assert_eq!(store.read_active().unwrap().unwrap().deployment, 100); + + // Absent `selfReport` on a rolled-back response is refused the same way: + // it must not switch an enabled machine off either. + let _ = reconcile_and_note_self_report(&store, &jev_state(98), None, &serve, &|| false); + assert_eq!(crate::self_report::take_pending(), None); + fs::remove_dir_all(store.root()).ok(); + } + + /// A response whose reconcile runs into `config --disconnect` is discarded, + /// its `selfReport` included. + #[test] + fn a_withdrawn_response_does_not_change_self_reports() { + let _env = lock_env(); + let _ = crate::self_report::take_pending(); + let store = temp_store("self-report-withdrawn"); + let result = reconcile_and_note_self_report( + &store, + &jev_state(5), + self_report_on(true), + &serve, + &|| true, + ); + assert!( + matches!(result, Err(ReconcileError::Withdrawn)), + "{result:?}" + ); + assert_eq!(crate::self_report::take_pending(), None); + fs::remove_dir_all(store.root()).ok(); + } + + /// A response that passed validation and the rollback guard is the server's + /// newest answer even when one of its artifacts fails to download: the org's + /// toggle still applies rather than waiting on an unrelated policy. + #[test] + fn an_accepted_response_with_a_failed_artifact_still_applies_self_reports() { + let _env = lock_env(); + let _ = crate::self_report::take_pending(); + let store = temp_store("self-report-fetch-fail"); + let result = reconcile_and_note_self_report( + &store, + &jev_state(5), + self_report_on(true), + &|_: &DesiredPolicy| Err::, String>("offline".into()), + &|| false, + ); + assert!( + matches!(result, Err(ReconcileError::Fetch { .. })), + "{result:?}" + ); + assert_eq!( + crate::self_report::take_pending(), + Some(self_report_on(true)) + ); + fs::remove_dir_all(store.root()).ok(); + } + /// Exactly what `config --disconnect` removes /// (`clearActiveCloudManagedPolicies` in `cloud-managed-policies.ts`). fn disconnect_like_the_cli(store: &PolicyStore) { diff --git a/crates/failproofaid/src/main.rs b/crates/failproofaid/src/main.rs index fcc3c65ec..b910d4c76 100644 --- a/crates/failproofaid/src/main.rs +++ b/crates/failproofaid/src/main.rs @@ -276,8 +276,13 @@ fn run() -> Result<(), Box> { // Self Reports: the `report` tool's MCP server on 127.0.0.1. Its own // thread and runtime rather than a collector task, because the collector // runs only with an ingest credential and an OSS machine needs this too. - // Always listening; `tools/list` is empty while `self-report.json` says - // off. A busy port logs a warning and the daemon carries on. + // Always listening; `tools/list` is empty while Self Reports is off. On by + // default: a missing `self-report.json` reads as on unless this machine is + // Cloud enrolled, and the server asks the same enrolment check the policy + // poll uses. A busy port logs a warning and the daemon carries on. + fpai_collect::self_report::set_enrolment_check(std::sync::Arc::new( + cloud_client::self_report_enrolled, + )); let (self_report_listening, self_report_ready) = std::sync::mpsc::channel(); let mut self_report_mcp = paths::failproofai_home().ok().and_then(|home| { fpai_collect::self_report::spawn( @@ -312,7 +317,7 @@ fn run() -> Result<(), Box> { // Self Reports: once the MCP server is listening and this socket is bound, // re-run the agent sync so agents registered over stdio while the daemon // was down move to its HTTP server (the sync's live check pings this - // socket and the MCP port). Only when self-report.json says enabled. + // socket and the MCP port). Only when Self Reports is on. self_report::spawn_startup_sync(self_report_ready, shutdown.clone()); let run_result = srv.run_until(shutdown); diff --git a/crates/failproofaid/src/self_report.rs b/crates/failproofaid/src/self_report.rs index b942d7676..7c2f20363 100644 --- a/crates/failproofaid/src/self_report.rs +++ b/crates/failproofaid/src/self_report.rs @@ -6,7 +6,9 @@ //! enrolled. Off Cloud the TypeScript CLI writes it from the local config, so //! nothing here touches it then — except a file this daemon itself wrote for an //! org the machine has since left, which is removed (a departed org's toggle -//! must not keep the tool registered in every agent). +//! must not decide this machine any more). With the file gone the machine is an +//! open-source one, where Self Reports is on by default unless `config.json` +//! turned it off, so agents are re-synced to match. use std::io; use std::path::{Path, PathBuf}; @@ -70,7 +72,7 @@ pub fn note_desired(desired: Option) { *PENDING.lock().unwrap_or_else(|p| p.into_inner()) = Some(desired); } -fn take_pending() -> Option> { +pub(crate) fn take_pending() -> Option> { PENDING.lock().unwrap_or_else(|p| p.into_inner()).take() } @@ -117,7 +119,9 @@ pub fn apply(path: &Path, desired: Option<&Desired>, port: u16) -> io::Result io::Result { let Some(previous) = sr::read_settings(path) else { return Ok(false); @@ -126,7 +130,13 @@ pub fn release(path: &Path) -> io::Result { return Ok(false); } match std::fs::remove_file(path) { - Ok(()) => Ok(previous.enabled), + Ok(()) => { + let now_on = path + .parent() + .and_then(|home| sr::effective_settings(home, &|| false)) + .is_some_and(|s| s.enabled); + Ok(previous.enabled || now_on) + } Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(false), Err(err) => Err(err), } @@ -178,7 +188,10 @@ pub fn tick(enrolled: Option, withdrawn: &dyn Fn() -> bool) { let _ = take_pending(); match release(&path) { Ok(true) => { - tracing::info!("Self Reports settings from FailproofAI Cloud removed"); + tracing::info!( + "Self Reports settings from FailproofAI Cloud removed; \ + this machine's own setting applies" + ); spawn_sync(); } Ok(false) => {} @@ -206,9 +219,10 @@ fn now_rfc3339() -> String { /// How long the startup sync waits for the MCP server to report its bind. const STARTUP_LISTEN_WAIT: Duration = Duration::from_secs(10); -/// Whether the startup sync should run: `self-report.json` says enabled. -fn enabled_on_disk(home: &Path) -> bool { - sr::read_settings(&sr::settings_path(home)).is_some_and(|s| s.enabled) +/// Whether the startup sync should run: Self Reports is on (a missing file is +/// on off Cloud; `sr::effective_settings`). +fn enabled_on_disk(home: &Path, enrolled: &dyn Fn() -> bool) -> bool { + sr::effective_settings(home, enrolled).is_some_and(|s| s.enabled) } /// Run `failproofai self-report sync --quiet` once at startup, after the MCP @@ -230,7 +244,7 @@ pub fn spawn_startup_sync( let Ok(home) = crate::paths::failproofai_home() else { return; }; - if !enabled_on_disk(&home) { + if !enabled_on_disk(&home, &*sr::enrolment_check()) { return; } if bound != Ok(true) { @@ -623,9 +637,29 @@ mod tests { ); assert!(!path.exists()); + // A disabled cloud file: the machine is open source now, where Self + // Reports is on by default, so agents need the sync too... apply(&path, None, 4319).unwrap(); - assert!(!release(&path).unwrap(), "a disabled one does not"); + assert!( + release(&path).unwrap(), + "off -> the open-source default (on)" + ); assert!(!path.exists()); + + // ...unless config.json turned it off here: off stays off. + let home = path.parent().unwrap(); + std::fs::write( + home.join("config.json"), + r#"{"selfReport":{"enabled":false}}"#, + ) + .unwrap(); + apply(&path, None, 4319).unwrap(); + assert!( + !release(&path).unwrap(), + "a disabled one with a local off does not" + ); + assert!(!path.exists()); + let _ = std::fs::remove_dir_all(home); } #[test] @@ -652,17 +686,26 @@ mod tests { } #[test] - fn the_startup_sync_runs_only_when_the_file_says_enabled() { + fn the_startup_sync_runs_only_when_self_reports_is_on() { let home = temp_path("startup").parent().unwrap().to_path_buf(); - assert!(!enabled_on_disk(&home), "no file: off"); + let oss = || false; + let cloud = || true; + assert!( + enabled_on_disk(&home, &oss), + "no file, open source: on by default" + ); + assert!( + !enabled_on_disk(&home, &cloud), + "no file, enrolled: off until written" + ); let mut s = effective(None, 4319, "2026-11-26T00:00:00Z".into()); sr::write_settings(&sr::settings_path(&home), &s).unwrap(); - assert!(!enabled_on_disk(&home), "disabled"); + assert!(!enabled_on_disk(&home, &oss), "disabled"); s.enabled = true; sr::write_settings(&sr::settings_path(&home), &s).unwrap(); - assert!(enabled_on_disk(&home), "enabled"); + assert!(enabled_on_disk(&home, &cloud), "enabled"); std::fs::write(sr::settings_path(&home), "garbage").unwrap(); - assert!(!enabled_on_disk(&home), "unparsable: off"); + assert!(!enabled_on_disk(&home, &oss), "unparsable: off"); let _ = std::fs::remove_dir_all(&home); } diff --git a/crates/failproofaid/tests/audit_lane_e2e.rs b/crates/failproofaid/tests/audit_lane_e2e.rs index 43913dd56..7ee03b3ca 100644 --- a/crates/failproofaid/tests/audit_lane_e2e.rs +++ b/crates/failproofaid/tests/audit_lane_e2e.rs @@ -144,9 +144,13 @@ fn read_schedule(home: &Path) -> serde_json::Value { /// A stand-in for the CLI: records that it ran (with the arguments the lane /// appended) and exits with `exit_code`. +/// The CLI the daemon runs, standing in for `failproofai audit`. It ignores the +/// `self-report sync` the daemon also runs at startup (Self Reports is on by +/// default, so a home with no `self-report.json` gets that sync too): only an +/// audit leaves the marker. fn stub_cli(marker: &Path, exit_code: i32) -> String { format!( - "sh -c 'printf \"%s\" \"$*\" > {} ; exit {exit_code}' fp", + "sh -c 'case \"$1\" in self-report) exit 0;; esac; printf \"%s\" \"$*\" > {} ; exit {exit_code}' fp", marker.display() ) } diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index 57dc80b09..61745354b 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -11,8 +11,11 @@ //! spool format, so it reaches Cloud through the existing upload. //! //! The settings file is written by the daemon when the machine is Cloud -//! managed and by the TypeScript CLI otherwise. A missing or unparsable file -//! means the feature is off. +//! managed and by the TypeScript CLI otherwise. Self Reports is on by default: +//! a MISSING file means on with the default categories on a machine that is +//! not Cloud enrolled (unless `config.json`'s `selfReport.enabled` is `false`), +//! and off on an enrolled one until the daemon writes it. An unparsable file +//! always means off (see [`effective_settings`]). //! //! The server binds loopback only and refuses any request whose `Host` or //! `Origin` is not this port on `127.0.0.1` / `localhost`, so a web page in a @@ -232,12 +235,88 @@ pub fn settings_path(home: &Path) -> PathBuf { home.join(SETTINGS_FILE) } -/// The file, or `None` when it is missing or does not parse (both: disabled). +/// The file, or `None` when it is missing or does not parse. Readers that +/// decide whether the feature is on use [`effective_settings`], which tells +/// the two apart. pub fn read_settings(path: &Path) -> Option { let text = fs::read_to_string(path).ok()?; serde_json::from_str(&text).ok() } +/// Is this machine Cloud enrolled? Asked only when `self-report.json` is +/// missing. The daemon installs its own check (the same `Enrolment::resolve` +/// its policy poll uses) with [`set_enrolment_check`]. +pub type EnrolmentCheck = Arc bool + Send + Sync>; + +static ENROLMENT_CHECK: OnceLock = OnceLock::new(); + +/// Install the enrolment check every reader in this process uses. First call wins. +pub fn set_enrolment_check(check: EnrolmentCheck) { + let _ = ENROLMENT_CHECK.set(check); +} + +/// The installed check; without one (no daemon in this process), not enrolled. +pub fn enrolment_check() -> EnrolmentCheck { + ENROLMENT_CHECK + .get() + .cloned() + .unwrap_or_else(|| Arc::new(|| false)) +} + +/// The settings a reader acts on (CONTRACT §4), identical to the TypeScript +/// `resolveSelfReport` in src/hooks/self-report.ts: +/// +/// - the file, when it is there and parses; +/// - an unparsable or unreadable file: `None`, off (fail safe: a half-written +/// or hand-broken file must not turn recording on); +/// - a missing file on a Cloud-enrolled machine: `None`, off until the daemon +/// writes it from the org's setting; +/// - a missing file otherwise: on with the default categories, unless +/// `config.json`'s `selfReport.enabled` is `false` (an explicit off wins). +pub fn effective_settings(home: &Path, enrolled: &dyn Fn() -> bool) -> Option { + match fs::read_to_string(settings_path(home)) { + Ok(text) => serde_json::from_str(&text).ok(), + Err(err) if err.kind() == io::ErrorKind::NotFound => missing_file_settings(home, enrolled), + Err(_) => None, + } +} + +/// What a missing `self-report.json` means (see [`effective_settings`]). +fn missing_file_settings(home: &Path, enrolled: &dyn Fn() -> bool) -> Option { + if enrolled() || local_config_disabled(home) { + return None; + } + Some(default_settings(port_from_env())) +} + +/// On, local, the default categories, no guidance: what a machine with no +/// settings file and no explicit off runs. +pub fn default_settings(port: u16) -> Settings { + Settings { + version: SETTINGS_VERSION, + enabled: true, + source: "local".to_string(), + categories: default_categories(), + guidance: None, + mcp: McpEndpoint::on_port(port), + updated_at: String::new(), + } +} + +/// `config.json`'s `selfReport.enabled` is exactly `false`. +fn local_config_disabled(home: &Path) -> bool { + let Ok(text) = fs::read_to_string(home.join("config.json")) else { + return false; + }; + let Ok(root) = serde_json::from_str::(&text) else { + return false; + }; + root.get("selfReport") + .and_then(|b| b.get("enabled")) + .and_then(Value::as_bool) + == Some(false) +} + /// Write the settings atomically (tmp + rename), mode 0644. pub fn write_settings(path: &Path, settings: &Settings) -> io::Result<()> { use std::os::unix::fs::OpenOptionsExt; @@ -368,22 +447,35 @@ pub fn tool_definition(settings: Option<&Settings>) -> Option { // ── Settings cache ─────────────────────────────────────────────────────────── -/// `self-report.json`, re-read only when its mtime or size changes. +/// `self-report.json`, re-read only when its mtime or size changes. A missing +/// file is resolved on every call ([`effective_settings`]): it is cheap, and an +/// enrolment or a `config.json` off must take effect on the next request. struct SettingsCache { + home: PathBuf, path: PathBuf, + enrolled: EnrolmentCheck, state: Mutex)>>, } impl SettingsCache { - fn new(path: PathBuf) -> Self { + fn new(home: &Path, enrolled: EnrolmentCheck) -> Self { SettingsCache { - path, + home: home.to_path_buf(), + path: settings_path(home), + enrolled, state: Mutex::new(None), } } fn current(&self) -> Option { - let meta = fs::metadata(&self.path).ok(); + let meta = match fs::metadata(&self.path) { + Ok(meta) => Some(meta), + Err(err) if err.kind() == io::ErrorKind::NotFound => { + *self.state.lock().unwrap_or_else(|p| p.into_inner()) = None; + return missing_file_settings(&self.home, &*self.enrolled); + } + Err(_) => None, + }; let stamp = meta.and_then(|m| Some((m.modified().ok()?, m.len()))); let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner()); let Some((mtime, len)) = stamp else { @@ -499,13 +591,24 @@ pub async fn serve( listener: tokio::net::TcpListener, home: PathBuf, sd: Shutdown, +) -> Result<(), TaskError> { + serve_with_enrolment(listener, home, sd, enrolment_check()).await +} + +/// [`serve`] with an explicit enrolment check (tests; the daemon installs its +/// own with [`set_enrolment_check`]). +pub async fn serve_with_enrolment( + listener: tokio::net::TcpListener, + home: PathBuf, + sd: Shutdown, + enrolled: EnrolmentCheck, ) -> Result<(), TaskError> { let port = listener .local_addr() .map_err(|e| TaskError(e.to_string()))? .port(); let server = Arc::new(Server { - settings: SettingsCache::new(settings_path(&home)), + settings: SettingsCache::new(&home, enrolled), home, port, }); @@ -717,10 +820,11 @@ impl Server { /// The fallback recording. A failure is logged and never reaches the agent: /// the call's answer is `Recorded.` whatever happens here. /// - /// Nothing is recorded unless the settings file says enabled right now: a - /// client that listed the tool before it was turned off (or that never - /// listed it) can still send a call. Read from disk, not the cache, so a - /// disable is honoured on the very next call (as the stdio server does). + /// Nothing is recorded unless the settings say enabled right now + /// ([`effective_settings`]: a missing file is on off Cloud): a client that + /// listed the tool before it was turned off (or that never listed it) can + /// still send a call. Read from disk, not the cache, so a disable is + /// honoured on the very next call (as the stdio server does). fn record(&self, args: &Value, caller: &Caller) { let Some(agent) = caller .agent @@ -729,7 +833,7 @@ impl Server { else { return; }; - if !read_settings(&settings_path(&self.home)).is_some_and(|s| s.enabled) { + if !effective_settings(&self.home, &*self.settings.enrolled).is_some_and(|s| s.enabled) { return; } let report = Report::from_args(args); @@ -1197,7 +1301,8 @@ mod tests { fn the_cache_rereads_a_changed_file() { let home = temp_home("cache"); let path = settings_path(&home); - let cache = SettingsCache::new(path.clone()); + // Enrolled: a missing file is off until the daemon writes it. + let cache = SettingsCache::new(&home, Arc::new(|| true)); assert!(cache.current().is_none()); write_settings(&path, &enabled(default_categories(), None)).unwrap(); assert!(cache.current().unwrap().enabled); @@ -1211,6 +1316,93 @@ mod tests { let _ = fs::remove_dir_all(home); } + /// On by default (CONTRACT §4): what a reader makes of each state of the file. + #[test] + fn a_missing_file_is_on_off_cloud_and_off_on_cloud() { + let home = temp_home("effective"); + let path = settings_path(&home); + // Fresh machine, not enrolled: on, defaults. + let s = effective_settings(&home, &|| false).expect("on by default"); + assert!(s.enabled); + assert_eq!(s.source, "local"); + assert_eq!(s.categories, default_categories()); + // Enrolled, file not written yet: off. + assert_eq!(effective_settings(&home, &|| true), None); + // An explicit local off in config.json wins over the default. + fs::write( + home.join("config.json"), + r#"{"selfReport":{"enabled":false}}"#, + ) + .unwrap(); + assert_eq!(effective_settings(&home, &|| false), None); + fs::write( + home.join("config.json"), + r#"{"selfReport":{"enabled":true}}"#, + ) + .unwrap(); + assert!(effective_settings(&home, &|| false).unwrap().enabled); + // A malformed file is off, enrolled or not (fail safe). + fs::write(&path, "{not json").unwrap(); + assert_eq!(effective_settings(&home, &|| false), None); + assert_eq!(effective_settings(&home, &|| true), None); + // An explicit enabled:false file is off. + let mut off = enabled(default_categories(), None); + off.enabled = false; + write_settings(&path, &off).unwrap(); + assert!(!effective_settings(&home, &|| false).unwrap().enabled); + // The cache agrees with the reader. + fs::remove_file(&path).unwrap(); + fs::remove_file(home.join("config.json")).unwrap(); + assert!( + SettingsCache::new(&home, Arc::new(|| false)) + .current() + .unwrap() + .enabled + ); + assert!( + SettingsCache::new(&home, Arc::new(|| true)) + .current() + .is_none() + ); + let _ = fs::remove_dir_all(home); + } + + /// A fresh OSS machine: no file, the HTTP server lists the tool and records. + #[test] + fn an_unenrolled_machine_with_no_file_lists_and_records() { + let home = temp_home("http-default-on"); + let server = server_enrolled(&home, false); + let caller = Caller { + agent: Some("copilot".to_string()), + cwd: None, + }; + let listed = server + .dispatch( + json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}), + &caller, + ) + .unwrap(); + assert_eq!(listed["result"]["tools"][0]["name"], TOOL_NAME); + call_report(&server, "copilot"); + assert_eq!(event_files(&home), 1, "recorded with no settings file"); + // Enrolled with no file yet: nothing listed, nothing recorded. + let enrolled = server_enrolled(&home, true); + let listed = enrolled + .dispatch( + json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}), + &caller, + ) + .unwrap(); + assert_eq!(listed["result"]["tools"], json!([])); + call_report(&enrolled, "copilot"); + assert_eq!( + event_files(&home), + 1, + "not recorded while enrolled with no file" + ); + let _ = fs::remove_dir_all(home); + } + #[test] fn host_and_origin_must_be_this_loopback_port() { let headers = |host: Option<&str>, origin: Option<&str>| { @@ -1358,10 +1550,14 @@ mod tests { } fn server_for(home: &Path) -> Server { + server_enrolled(home, true) + } + + fn server_enrolled(home: &Path, enrolled: bool) -> Server { Server { home: home.to_path_buf(), port: DEFAULT_PORT, - settings: SettingsCache::new(settings_path(home)), + settings: SettingsCache::new(home, Arc::new(move || enrolled)), } } diff --git a/crates/fpai-collect/tests/self_report_mcp.rs b/crates/fpai-collect/tests/self_report_mcp.rs index 2cfdf1373..ba669002f 100644 --- a/crates/fpai-collect/tests/self_report_mcp.rs +++ b/crates/fpai-collect/tests/self_report_mcp.rs @@ -51,13 +51,19 @@ struct Running { impl Running { async fn start(home: &Path) -> Self { + Self::start_enrolled(home, false).await + } + + async fn start_enrolled(home: &Path, enrolled: bool) -> Self { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = listener.local_addr().unwrap().port(); let stop = Arc::new(AtomicBool::new(false)); let sd = Shutdown::for_test(stop.clone()); let home = home.to_path_buf(); let task = tokio::spawn(async move { - self_report::serve(listener, home, sd).await.unwrap(); + self_report::serve_with_enrolment(listener, home, sd, Arc::new(move || enrolled)) + .await + .unwrap(); }); Running { port, @@ -247,14 +253,30 @@ async fn initialize_list_and_call_the_report_tool() { #[tokio::test(flavor = "multi_thread")] async fn the_tool_list_follows_the_settings_file() { let home = tmpdir("follow"); - let server = Running::start(&home).await; - assert_eq!(list(&server).await, json!([]), "no file: off"); let init = json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}); let instructions = |reply: Option| reply.unwrap()["result"].get("instructions").cloned(); + + // Cloud enrolled and the daemon has not written the file yet: off. + let enrolled = Running::start_enrolled(&home, true).await; + assert_eq!(list(&enrolled).await, json!([]), "enrolled, no file: off"); assert_eq!( - instructions(server.rpc("", init.clone()).await.1), + instructions(enrolled.rpc("", init.clone()).await.1), None, - "no file: no instructions field" + "enrolled, no file: no instructions field" + ); + enrolled.stop().await; + + // Not enrolled: on by default, with the default categories. + let server = Running::start(&home).await; + let tools = list(&server).await; + assert_eq!(tools[0]["name"], "report", "no file: on by default"); + assert_eq!( + tools[0]["inputSchema"]["properties"]["category"]["enum"][0], + "looping" + ); + assert!( + instructions(server.rpc("", init.clone()).await.1).is_some(), + "no file: instructions sent" ); write_settings( diff --git a/docs/reference/events-and-configuration.mdx b/docs/reference/events-and-configuration.mdx index bafcedf26..54d2d68ea 100644 --- a/docs/reference/events-and-configuration.mdx +++ b/docs/reference/events-and-configuration.mdx @@ -76,7 +76,7 @@ Do not use `timestamp`, `session_id`, `agent_id`, `type`, or `environment` as cu - `failproofai-sdk` always spools under `~/.failproofai/custom-agents`. `FAILPROOFAI_HOME` relocates that home; the `custom-agents` segment is always appended, so the spool cannot be placed outside it. Only the SDK's own `configure(base_dir=...)` writes elsewhere. `AGENTEYE_HOME` is read by the older `agenteye-collector` to choose what to watch, and no longer affects where the SDK writes. - Environment labels can be set through SDK configuration or `AGENTEYE_ENVIRONMENT`. - Daemon credentials are stored separately from non-secret settings. -- `~/.failproofai/self-report.json` holds the effective [Self Reports](/self-reports) setting every reader uses: the daemon's MCP server, `failproofai mcp`, both SDKs, and `failproofai self-report status`. A missing or unreadable file means off. +- `~/.failproofai/self-report.json` holds the effective [Self Reports](/self-reports) setting every reader uses: the daemon's MCP server, `failproofai mcp`, both SDKs, and `failproofai self-report status`. Self Reports is on by default: a missing file means on with the default categories, except on a machine connected to Failproof AI Cloud, where it means off until `failproofaid` writes the file from your organization's setting. A file that cannot be parsed means off. Use stable, low-cardinality environment names. Commas are not supported in daemon environment labels. @@ -94,7 +94,7 @@ Use stable, low-cardinality environment names. Commas are not supported in daemo } ``` -`source` is `cloud` when `failproofaid` wrote it from your organization's setting, or `local` when `failproofai self-report enable` or `disable` did. The file is written atomically with mode 0644, so agent processes running as another account can read it. `FAILPROOFAI_HOME` moves it with the rest of `~/.failproofai`, and `FAILPROOFAI_SELF_REPORT_PORT`, read when the daemon starts, sets the port. +`source` is `cloud` when `failproofaid` wrote it from your organization's setting, or `local` when failproofai wrote it on this machine: `policies --install` and `config` write it on when it is missing, and `failproofai self-report enable` or `disable` rewrite it. The file is written atomically with mode 0644, so agent processes running as another account can read it. `FAILPROOFAI_HOME` moves it with the rest of `~/.failproofai`, and `FAILPROOFAI_SELF_REPORT_PORT`, read when the daemon starts, sets the port. ## Change an environment label diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index 7733aa2f3..f19ef9250 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -8,32 +8,41 @@ Self Reports gives every agent one extra tool, `report`. An agent that is blocke A report never unblocks the agent and never changes a decision. Afterwards the agent works around the problem or tells the user what is blocking it. No policy can block or rewrite a report: failproofai's hook allows the call before any policy, session pause, or Jev review runs. -## Turn it on +## On by default + +Self Reports is on as soon as failproofai is installed. `failproofai policies --install` and `failproofai config` register the `failproofai` MCP server in every agent they install hooks for, and write `~/.failproofai/self-report.json` with the default categories so every reader sees the same settings. - On a machine connected to Failproof AI Cloud, the setting comes from your organization. + On a machine connected to Failproof AI Cloud, the setting comes from your organization, and it is on unless someone turned it off. 1. Go to **settings → self reports**. - 2. Switch it on. Keep the default categories or write your own, and optionally add guidance for the agents. + 2. Keep it on, or switch it off. Keep the default categories or write your own, and optionally add guidance for the agents. - Every connected machine picks the change up on its next policy poll. `failproofaid` writes `~/.failproofai/self-report.json` and adds the `failproofai` MCP server to every agent that has failproofai hooks, or removes it when you switch the feature off. + Every connected machine picks the change up on its next policy poll. `failproofaid` writes `~/.failproofai/self-report.json` from it and adds the `failproofai` MCP server to every agent that has failproofai hooks, or removes it when the switch is off. Until the first poll after connecting writes that file, the machine treats Self Reports as off. On a Cloud-managed machine, `failproofai self-report enable` and `disable` refuse and point you to the dashboard. ```bash - failproofai self-report enable failproofai self-report status + failproofai self-report disable + failproofai self-report enable failproofai self-report test --agent claude ``` - `enable` writes the `selfReport` block of `~/.failproofai/config.json` and `~/.failproofai/self-report.json`, then registers the MCP server in every agent with failproofai hooks. To replace the default categories, pass `--categories-file `, a JSON list of `{name, description}`. To append instructions to the tool's description, pass `--guidance ""`. `failproofai self-report disable` turns it off and removes the MCP entries, keeping your categories for next time. An agent that is already running keeps the tool it loaded, but from then on its calls are allowed without being recorded. + With no settings file and no `selfReport` block in `~/.failproofai/config.json`, Self Reports is on with the default categories. + + `failproofai self-report disable` turns it off. It writes `enabled: false` to the `selfReport` block of `~/.failproofai/config.json` and to `~/.failproofai/self-report.json`, and removes the MCP entries from every agent. Your categories are kept for next time. An agent that is already running keeps the tool it loaded, but from then on its calls are allowed and not recorded. An explicit `enabled: false` always wins: a later install leaves it off. + + `failproofai self-report enable` turns it back on and registers the MCP server again. To replace the default categories, pass `--categories-file `, a JSON list of `{name, description}`. To append instructions to the tool's description, pass `--guidance ""`. `test` sends one report end to end as the agent you name and shows where it landed. +A settings file that cannot be parsed counts as off, so a broken file never starts recording. Run `failproofai self-report enable` or `disable` to write it again. + ## Categories An organization's own list replaces these entirely. Names are lowercase letters, digits, and underscores; a list holds 1 to 32 categories. diff --git a/sdk/python/README.md b/sdk/python/README.md index 63b922d70..6003c714c 100644 --- a/sdk/python/README.md +++ b/sdk/python/README.md @@ -116,12 +116,12 @@ failproofai_sdk.self_report("invalid_tool_or_credential", "The search API reject - **Spec.** `failproofai_sdk.self_report_spec()` returns `{name: "failproofai_report", description, input_schema}`. The categories (the `category` enum) and any extra guidance come from `$FAILPROOFAI_HOME/self-report.json` — written by the daemon - from your org's Cloud setting, or by `failproofai self-report enable` — read each + from your org's Cloud setting, or by the failproofai CLI — read each time a spec is built. When that file is missing, unreadable or disabled, six defaults are used (`looping`, `cannot_do_request`, `invalid_tool_or_credential`, - `missing_context`, `repeated_tool_failure`, `task_failure`): adding the tool is - itself the opt-in. Pass `categories=[...]` (and `guidance=`) to any helper to - override. + `missing_context`, `repeated_tool_failure`, `task_failure`): the tool works by + default, and adding it is itself the opt-in. Pass `categories=[...]` (and + `guidance=`) to any helper to override. - **Event.** `{type: "self_report", category, detail, source: "sdk", tool_call_id?}` plus the usual `session_id` / `agent_id` / `timestamp` / `environment`. An unknown category is recorded as given; `detail` is cut to 2,000 characters. diff --git a/sdk/python/skill/SKILL.md b/sdk/python/skill/SKILL.md index 1175928a5..eb496b19d 100644 --- a/sdk/python/skill/SKILL.md +++ b/sdk/python/skill/SKILL.md @@ -168,8 +168,11 @@ recipe — `references/typescript.md` → *The contract, in TypeScript* and *Shu silent emit, because ingest skips an event with no session and answers `200`. The one exception is `self_report()`: a report is evidence, so it never raises for a missing session. With none passed or bound, an unambiguous open - `tool_use` for the call (by its `tool_call_id`, else the one open report-tool - call) gives it its session, with no warning. Only when no explicit session, + `tool_use` for the call gives it its session, with no warning: the one with its + `tool_call_id`, else the NEWEST open report-tool call. Newest, not only: two + report calls open in one session (parallel tool calls) resolve to the later + one, so pass `tool_call_id` whenever report calls can overlap. Open calls in + several sessions resolve to none. Only when no explicit session, no such open call and no enclosing scope identifies one is it recorded under `session_id="unattributed"` (one warning per process). The other 15 methods raise. diff --git a/sdk/python/skill/references/integration.md b/sdk/python/skill/references/integration.md index 8769b5d55..5a3f04d80 100644 --- a/sdk/python/skill/references/integration.md +++ b/sdk/python/skill/references/integration.md @@ -97,8 +97,11 @@ raises — it is a label, and it falls back to `"main"`. `self_report()` is the exception: it never raises for a missing session, because losing a report to a missing scope is worse than filing it unattributed. With no session bound and none passed, an unambiguous open -`tool_use` for the call (matched by `tool_call_id`, else the one open -report-tool call) supplies the session and agent, with no warning. Only when no +`tool_use` for the call supplies the session and agent, with no warning: the +one matched by `tool_call_id`, else the newest open report-tool call. Two report +calls open in one session at once (parallel tool calls) resolve to the newer one, +so pass `tool_call_id` when report calls can overlap; open calls in several +sessions resolve to none. Only when no explicit session, no such open call and no enclosing scope resolves the identity is the report recorded under `session_id="unattributed"`, with one warning per process. Every other event method raises as above. diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index 09cb6b555..c81edb184 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -482,10 +482,12 @@ report from your own code, `failproofai.selfReport(category, detail)`. `failproofai.selfReportSpec()` gives `{ name, description, inputSchema }` for any other tool format. +- **On by default.** The tool works as soon as you add it: no setting has to be + turned on first, and adding it is the opt-in. - **Categories.** The tool's categories, and an optional paragraph of guidance, come from `~/.failproofai/self-report.json` (`$FAILPROOFAI_HOME` moves it), which - the daemon writes for a Cloud-managed machine and `failproofai self-report - enable` writes otherwise. A missing or disabled file means the six default + the daemon writes for a Cloud-managed machine and the failproofai CLI writes + otherwise. A missing or disabled file means the six default categories (`failproofai.DEFAULT_SELF_REPORT_CATEGORIES`). `failproofai.selfReportSettings()` returns what the file says. - **Where a report lands.** An explicit `sessionId`, else the open `tool_use` of diff --git a/src/hooks/manager.ts b/src/hooks/manager.ts index 0df127d3b..45da53264 100644 --- a/src/hooks/manager.ts +++ b/src/hooks/manager.ts @@ -44,6 +44,7 @@ import { probeDaemonPolicyEvaluation } from "./daemon-service"; import { NO_PRINTED_COMMAND_REASON, sudoPath } from "./system-command"; import { keepAgentSelectionTrue } from "./agent-selection"; import { removeSelfReportMcp, selfReportSyncLines, syncSelfReportMcp } from "./self-report-install"; +import { ensureSelfReportSettingsFile } from "./self-report"; import { INDENT, colorsEnabled, optsFor, printBlock, screenKit, type ScreenKitOpts } from "./tui"; const VALID_POLICY_NAMES = new Set(BUILTIN_POLICIES.map((p) => p.name)); @@ -1009,17 +1010,16 @@ async function installHooksImpl( } catch {} } - // Last, after everything above: the agents whose hooks were actually written. - // A call that returned early (only a third-party pack's policies were named) - // or threw wrote none and changes nothing. - if (syncAgentSelection) { - const note = keepAgentSelectionTrue("installed", writtenSettingsPaths.map((written) => written.cli)); - if (note) console.log(note); + // Self Reports: on by default, so the agents that now have hooks get + // failproofai's MCP server unless it was turned off (and lose a stale one + // when it is). The settings file is written first when it is missing (off + // Cloud), so every reader agrees. Best-effort: a config it cannot change is + // reported, never a failed install. + try { + await ensureSelfReportSettingsFile(); + } catch { + // the readers apply the same default without the file } - - // Self Reports: the agents that now have hooks get failproofai's MCP server - // when the feature is on (and lose a stale one when it is off). Best-effort: - // a config it cannot change is reported, never a failed install. try { const results = await syncSelfReportMcp({ quiet: true, @@ -1030,6 +1030,14 @@ async function installHooksImpl( } catch { // never block the install } + + // Last, after everything above: the agents whose hooks were actually written. + // A call that returned early (only a third-party pack's policies were named) + // or threw wrote none and changes nothing. + if (syncAgentSelection) { + const note = keepAgentSelectionTrue("installed", writtenSettingsPaths.map((written) => written.cli)); + if (note) console.log(note); + } } /** @@ -1140,17 +1148,6 @@ export async function removeHooks(policyNames?: string[], scope: HookScope | "al if (note) say(note); }; - // Self Reports: an agent whose user-scope hooks go also loses failproofai's - // MCP server, whatever the setting says. Project/local removals leave it: - // the user-scope hooks that use it are still there. - if (scope === "user" || scope === "all") { - try { - for (const line of selfReportSyncLines(removeSelfReportMcp({ agents: selectedClis, quiet: true }))) say(line); - } catch { - // never block the removal - } - } - // Remove failproofai hooks from each selected CLI's settings file(s) let totalRemoved = 0; let nothingToReport = false; @@ -1238,6 +1235,17 @@ export async function removeHooks(policyNames?: string[], scope: HookScope | "al } } + // Self Reports, after the hooks: an agent whose user-scope hooks go also loses failproofai's + // MCP server, whatever the setting says. Project/local removals leave it: + // the user-scope hooks that use it are still there. + if (scope === "user" || scope === "all") { + try { + for (const line of selfReportSyncLines(removeSelfReportMcp({ agents: selectedClis, quiet: true }))) say(line); + } catch { + // never block the removal + } + } + if (nothingToReport && totalRemoved === 0) { untraceRemoved(); return; diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts index 72cf3bdc1..23d1ad31b 100644 --- a/src/hooks/self-report-cli.ts +++ b/src/hooks/self-report-cli.ts @@ -19,6 +19,8 @@ import { SELF_REPORT_SERVER_RECORDS, readEffectiveSelfReport, readLocalSelfReportConfig, + resolveSelfReport, + selfReportCloudEnrolled, selfReportCloudManaged, selfReportSettingsFile, validateSelfReportCategories, @@ -190,18 +192,37 @@ function selfReportStranded( } async function selfReportStatus(deps: SelfReportCliDeps): Promise { - const settings = readEffectiveSelfReport(); + const file = readEffectiveSelfReport(); + const settings = resolveSelfReport(); const cloud = await selfReportCloudManaged(); const lines: string[] = []; if (!settings) { - lines.push("Self Reports: off (no settings file)"); + const missing = !file && !selfReportFileExists(); + lines.push( + missing + ? selfReportCloudEnrolled() + ? "Self Reports: off (waiting for FailproofAI Cloud to send this machine's setting)" + : "Self Reports: off (turned off in config.json)" + : "Self Reports: off (the settings file cannot be read)", + ); lines.push(`Settings: ${selfReportSettingsFile()}`); - lines.push(cloud ? "Managed by: FailproofAI Cloud" : "Turn on: `failproofai self-report enable`"); + lines.push(cloud ? "Managed by: FailproofAI Cloud (Settings > Self Reports)" : "Turn on: `failproofai self-report enable`"); return { exitCode: 0, lines }; } lines.push(`Self Reports: ${settings.enabled ? "on" : "off"}`); - lines.push(`Source: ${settings.source === "cloud" ? "FailproofAI Cloud" : "this machine (config.json)"}`); + lines.push( + `Source: ${ + settings.source === "cloud" ? "FailproofAI Cloud" : file ? "this machine (config.json)" : "the default (no settings file yet)" + }`, + ); lines.push(`Settings: ${selfReportSettingsFile()}`); + lines.push( + settings.source === "cloud" + ? "Turn off: in the dashboard, Settings > Self Reports" + : settings.enabled + ? "Turn off: `failproofai self-report disable`" + : "Turn on: `failproofai self-report enable`", + ); if (settings.updatedAt) lines.push(`Updated: ${settings.updatedAt}`); lines.push(`Categories: ${settings.categories.map((c) => c.name).join(", ")}`); if (settings.guidance) lines.push(`Guidance: ${settings.guidance.length > 60 ? `${settings.guidance.slice(0, 57)}...` : settings.guidance}`); @@ -326,7 +347,11 @@ async function selfReportDisable(args: string[], deps: SelfReportCliDeps): Promi writeEffectiveSelfReport({ enabled: false, categories: previous?.categories, guidance: previous?.guidance }); return { exitCode: 0, - lines: ["✓ Self Reports is off.", ...(await selfReportSync(deps)).map((l) => (l.startsWith("▲") ? l : ` ${l}`))], + lines: [ + "✓ Self Reports is off. Agents lose the report tool and nothing is recorded.", + ...(await selfReportSync(deps)).map((l) => (l.startsWith("▲") ? l : ` ${l}`)), + " Turn it back on with `failproofai self-report enable`.", + ], }; } @@ -341,7 +366,7 @@ async function selfReportTest(args: string[], deps: SelfReportCliDeps): Promise< if (!(INTEGRATION_TYPES as readonly string[]).includes(agent)) { return { exitCode: 1, lines: [`Not an agent: ${agent}.`, `Agents: ${INTEGRATION_TYPES.join(", ")}`] }; } - const settings = readEffectiveSelfReport(); + const settings = resolveSelfReport(); if (!settings?.enabled) { return { exitCode: 1, lines: ["Self Reports is off, so there is nothing to test.", "Turn it on with `failproofai self-report enable`."] }; } @@ -434,6 +459,15 @@ async function selfReportTest(args: string[], deps: SelfReportCliDeps): Promise< }; } +function selfReportFileExists(): boolean { + try { + readFileSync(selfReportSettingsFile()); + return true; + } catch (err) { + return (err as NodeJS.ErrnoException)?.code !== "ENOENT"; + } +} + function selfReportListDir(dir: string): string[] { try { return readdirSync(dir); diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index 2569541c8..7a92953cd 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -85,7 +85,7 @@ import { writeConfigFileAtomic } from "./safe-config-write"; import { codexHome } from "./codex-system-hooks"; import { claudeConfigDir, getIntegration, readYamlDoc, writeYamlDoc, UnreadableAgentConfigError } from "./integrations"; import { daemonSelfReportServer } from "./daemon-client"; -import { readEffectiveSelfReport, selfReportPort, selfReportSettingsFile, SELF_REPORT_SERVER_NAME, SELF_REPORT_SERVER_RECORDS } from "./self-report"; +import { resolveSelfReport, selfReportPort, selfReportSettingsFile, SELF_REPORT_SERVER_NAME, SELF_REPORT_SERVER_RECORDS } from "./self-report"; import { listHermesProfiles } from "../../lib/hermes-profiles"; import { listOpenClawProfiles } from "../../lib/openclaw-profiles"; import { INTEGRATION_TYPES, type IntegrationType } from "./types"; @@ -108,11 +108,13 @@ export interface SelfReportMcpSettings { /** * The bits of self-report.json this module needs, through the one settings - * reader in ./self-report. Missing or unparsable file ⇒ disabled, on the port - * a local writer would record. + * reader in ./self-report (`resolveSelfReport`). On by default: a missing file + * is enabled off Cloud and disabled on a Cloud-enrolled machine until the + * daemon writes it; an unparsable file is disabled. Disabled is reported on the + * port a local writer would record. */ export function readSelfReportMcpSettings(path = selfReportSettingsPath()): SelfReportMcpSettings { - const s = readEffectiveSelfReport(path); + const s = resolveSelfReport(path); if (!s) return { enabled: false, port: selfReportPort() }; return { enabled: s.enabled, port: s.mcp.port }; } diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts index 5cadfc8b5..33c4c2659 100644 --- a/src/hooks/self-report.ts +++ b/src/hooks/self-report.ts @@ -22,7 +22,7 @@ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeSync } from "node:fs"; import { dirname, join } from "node:path"; import { randomBytes } from "node:crypto"; -import { failproofaiHome } from "./fp-home"; +import { configFile, credentialsFile, failproofaiHome } from "./fp-home"; export { SELF_REPORT_SERVER_NAME, @@ -291,10 +291,13 @@ export function selfReportMcpUrl(port: number): string { } /** - * Read `self-report.json`. Missing, unparsable or not version 1 reads as - * `null`, which every caller treats as disabled. A file that says enabled but - * whose category list is unusable falls back to the defaults (contract §4: - * "never empty when enabled; defaults if none given"). + * Read `self-report.json` exactly as it is on disk. Missing, unparsable or not + * version 1 reads as `null`. A file that says enabled but whose category list + * is unusable falls back to the defaults (contract §4: "never empty when + * enabled; defaults if none given"). + * + * This is the raw file. Whether Self Reports is ON is `resolveSelfReport()`, + * which tells a missing file (on by default off Cloud) from a broken one (off). */ export function readEffectiveSelfReport(path: string = selfReportSettingsFile()): SelfReportEffective | null { let raw: unknown; @@ -324,9 +327,108 @@ export function readEffectiveSelfReport(path: string = selfReportSettingsFile()) }; } -/** The settings only when the feature is on; `null` otherwise. */ +/** + * The settings every reader acts on (contract §4). Self Reports is ON by + * default. Identical to the daemon's `effective_settings` + * (crates/fpai-collect/src/self_report.rs): + * + * - the file, when it is there and parses; + * - an unparsable file: `null`, off (fail safe: a half-written or hand-broken + * file must not turn recording on); + * - a missing file on a Cloud-enrolled machine: `null`, off until the daemon + * writes it from the org's setting; + * - a missing file otherwise: on with the default categories, unless + * `config.json`'s `selfReport.enabled` is `false` (an explicit off wins). + */ +export function resolveSelfReport( + path: string = selfReportSettingsFile(), + enrolled: () => boolean = selfReportCloudEnrolled, +): SelfReportEffective | null { + const presence = selfReportFilePresence(path); + // Present: the file decides. Unreadable is a broken file: off. + if (presence === "present") return readEffectiveSelfReport(path); + if (presence === "unreadable") return null; + if (enrolled() || selfReportLocalConfigOff()) return null; + return selfReportDefaultSettings(); +} + +/** On, local, the default categories: what a machine with no settings file runs. */ +export function selfReportDefaultSettings(): SelfReportEffective { + const port = selfReportPort(); + return { + version: 1, + enabled: true, + source: "local", + categories: SELF_REPORT_DEFAULT_CATEGORIES.map((c) => ({ ...c })), + guidance: null, + mcp: { port, url: selfReportMcpUrl(port) }, + updatedAt: "", + }; +} + +/** `config.json`'s `selfReport.enabled` is exactly `false` (sync; the hook path). */ +function selfReportLocalConfigOff(): boolean { + try { + const raw: unknown = JSON.parse(readFileSync(configFile(), "utf8")); + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false; + const block = (raw as Record).selfReport; + return !!block && typeof block === "object" && (block as Record).enabled === false; + } catch { + return false; + } +} + +/** + * Is this machine Cloud enrolled, for the missing-file rule? Synchronous (the + * hook path), and the same answer as the daemon's `Enrolment::resolve` + * (cloud_client.rs) so TS and Rust readers agree: `FAILPROOFAI_CLOUD_URL` set; + * else, unless `config.json` says `mode.kind == "oss"`, a credential file: + * `FAILPROOFAI_CLOUD_CREDENTIALS` when named, else `credentials.json` with a + * `cloud` entry, else the layout-1 `cloud.json`. A credential file that cannot + * be read or parsed counts as enrolled, as the daemon's does: a missing + * `self-report.json` then stays off rather than guessing on. + */ +export function selfReportCloudEnrolled(): boolean { + if (process.env.FAILPROOFAI_CLOUD_URL?.trim()) return true; + if (selfReportOssMode()) return false; + const override = process.env.FAILPROOFAI_CLOUD_CREDENTIALS; + if (override) return selfReportFilePresence(override) !== "missing"; + const creds = credentialsFile(); + const presence = selfReportFilePresence(creds); + if (presence === "missing") return selfReportFilePresence(join(failproofaiHome(), "cloud.json")) !== "missing"; + if (presence === "unreadable") return true; + try { + const raw: unknown = JSON.parse(readFileSync(creds, "utf8")); + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return true; + const cloud = (raw as Record).cloud; + return cloud !== undefined && cloud !== null; + } catch { + return true; + } +} + +function selfReportFilePresence(path: string): "present" | "missing" | "unreadable" { + try { + readFileSync(path); + return "present"; + } catch (err) { + return (err as NodeJS.ErrnoException)?.code === "ENOENT" ? "missing" : "unreadable"; + } +} + +function selfReportOssMode(): boolean { + try { + const raw: unknown = JSON.parse(readFileSync(configFile(), "utf8")); + const mode = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as { mode?: unknown }).mode : undefined; + return !!mode && typeof mode === "object" && !Array.isArray(mode) && (mode as { kind?: unknown }).kind === "oss"; + } catch { + return false; + } +} + +/** The settings only when the feature is on (`resolveSelfReport`); `null` otherwise. */ export function readEnabledSelfReport(path?: string): SelfReportEffective | null { - const s = readEffectiveSelfReport(path); + const s = resolveSelfReport(path); return s && s.enabled ? s : null; } @@ -415,6 +517,33 @@ export async function writeLocalSelfReportConfig(block: SelfReportLocalConfig): writeConfigFileAtomic(configFile(), `${JSON.stringify(raw, null, 2)}\n`, { backup: false }); } +/** + * On install (`policies --install`, `config`): make the effective settings file + * exist, so every reader (the hooks, the stdio server, the daemon's HTTP + * server, the SDKs, `status`) reads the same thing from disk rather than each + * applying the missing-file default on its own. + * + * Writes only when the file is missing and the machine is not Cloud enrolled + * (on Cloud the daemon owns the file). It carries config.json's `selfReport` + * block when there is one — so an explicit `enabled: false` there is written + * as off — and is on with the defaults otherwise. An existing file, even a + * broken one, is left alone: it is the user's or the daemon's, and a broken + * file reads as off until `self-report enable` / `disable` rewrites it. + * Returns what it wrote, or `null` when it wrote nothing. + */ +export async function ensureSelfReportSettingsFile( + path: string = selfReportSettingsFile(), + enrolled: () => boolean = selfReportCloudEnrolled, +): Promise { + if (selfReportFilePresence(path) !== "missing" || enrolled()) return null; + const local = await readLocalSelfReportConfig().catch(() => null); + const enabled = !selfReportLocalConfigOff(); + return writeEffectiveSelfReport( + { enabled, categories: local?.categories ?? null, guidance: local?.guidance ?? null }, + path, + ); +} + // ── Cloud enrolment ───────────────────────────────────────────────────────── /** From cfa875bdab1b545de553b885b72ee5a5355839ed Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Fri, 27 Nov 2026 16:13:03 +0530 Subject: [PATCH 17/54] [self-reports] Project-scope installs leave user-wide MCP configs alone; tests can't write the real home A test that set FAILPROOFAI_HOME but not HOME ran the install-time sync against the developer's real ~/.claude.json, ~/.codex/config.toml, ~/.cursor/mcp.json and ~/.copilot/mcp-config.json, registering a server at a deleted temp binary. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/manager.test.ts | 12 +++++++ __tests__/hooks/self-report-install.test.ts | 23 +++++++++++++ src/hooks/manager.ts | 4 +++ src/hooks/self-report-install.ts | 36 ++++++++++++++++++--- 5 files changed, 72 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 89056b983..0bf5d31da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ### Fixes +- Self Reports: a project- or local-scope `policies --install` no longer writes failproofai's MCP server into the agents' user-wide configs, and under the test runner the installer refuses to write any agent config inside the real home directory (a test that did not isolate `HOME` had registered a server pointing at a deleted temp binary) (#1062) - A desired-state response the daemon refuses (a deployment rollback, or a disconnect during the poll) no longer changes Self Reports: its `selfReport` setting is applied only after the reconcile accepts the response, so an out-of-order older deployment can no longer turn reporting back on (#1062) - Retire the hook-sync agent and stop publishing its image: `docker-hook-sync/`, its prompt and `build-image.yml` (which pushed `ghcr.io/failproofai/hook-sync` publicly every day) are removed. The agent ran Claude Code with permission checks skipped, a GitHub write token and a Claude token in its environment and no failproofai hooks, after reading a third-party npm README. Nothing had run it since July (FailproofAI/agenteye#1797, #1055) - `fp`, the dashboard's api-server client, and the collector's uploader and OTLP relay refuse a plain `http://` URL for any host but `localhost` and loopback addresses, so `FP_DASHBOARD_URL`, `FAILPROOF_API_URL` or `FAILPROOFAI_INGEST_URL` can no longer put a session, a token, a sign-in code or the ingest key on the network in clear, and the api-server client no longer follows redirects; `fp logout` still clears a session saved against such a URL, without sending it (#1057) diff --git a/__tests__/hooks/manager.test.ts b/__tests__/hooks/manager.test.ts index 0635c89ce..52f74e131 100644 --- a/__tests__/hooks/manager.test.ts +++ b/__tests__/hooks/manager.test.ts @@ -196,6 +196,18 @@ describe("hooks/manager", () => { }); }); + it("a project-scope install never touches the agents' user-wide MCP configs", async () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue("{}"); + const sr = await import("../../src/hooks/self-report-install"); + vi.mocked(sr.syncSelfReportMcp).mockClear(); + + const { installHooks } = await import("../../src/hooks/manager"); + await installHooks(undefined, "project", "/tmp/some-project"); + + expect(sr.syncSelfReportMcp).not.toHaveBeenCalled(); + }); + // `--install` with no names WIRES HOOKS. It does not choose policies, and // it used to: a second picker opened here over BUILTIN_POLICIES — the // compiled catalog, which is not how policies arrive any more — and wrote diff --git a/__tests__/hooks/self-report-install.test.ts b/__tests__/hooks/self-report-install.test.ts index fe46e897c..9fd17d302 100644 --- a/__tests__/hooks/self-report-install.test.ts +++ b/__tests__/hooks/self-report-install.test.ts @@ -640,3 +640,26 @@ describe("on by default: install, disable, enable", () => { expect(entryIn("claude")).toBeUndefined(); }); }); + +describe("the test-only real-home guard", () => { + it("refuses to write an agent config under the developer's real home", async () => { + const { userInfo } = await import("node:os"); + const { join } = await import("node:path"); + const realHome = userInfo().homedir; + const prev = process.env.HOME; + // Simulate a test that forgot to move HOME: the writer resolves the real home. + process.env.HOME = realHome; + try { + const mod = await import("../../src/hooks/self-report-install"); + const results = await mod.syncSelfReportMcp({ enabled: true, quiet: true, agents: ["cursor"], alsoHooked: ["cursor"] } as never); + const target = join(realHome, ".cursor", "mcp.json"); + const written = results.find((r: { agent: string; path?: string; action?: string }) => r.agent === "cursor"); + expect(written?.action).not.toBe("added"); + expect(written?.action).not.toBe("updated"); + expect(String(written?.path ?? target).startsWith(realHome)).toBe(true); + } finally { + if (prev === undefined) delete process.env.HOME; + else process.env.HOME = prev; + } + }); +}); diff --git a/src/hooks/manager.ts b/src/hooks/manager.ts index 45da53264..3f6fc36e9 100644 --- a/src/hooks/manager.ts +++ b/src/hooks/manager.ts @@ -1015,6 +1015,9 @@ async function installHooksImpl( // when it is). The settings file is written first when it is missing (off // Cloud), so every reader agrees. Best-effort: a config it cannot change is // reported, never a failed install. + // Only a user-scope install touches the agents' user-wide MCP configs: a + // project or local install must not register anything outside that project. + if (scope === "user") { try { await ensureSelfReportSettingsFile(); } catch { @@ -1030,6 +1033,7 @@ async function installHooksImpl( } catch { // never block the install } + } // Last, after everything above: the agents whose hooks were actually written. // A call that returned early (only a third-party pack's policies were named) diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index 7a92953cd..de58c749b 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -76,14 +76,15 @@ */ import { accessSync, constants as fsConstants, existsSync, readFileSync, realpathSync } from "node:fs"; import { execSync } from "node:child_process"; -import { homedir } from "node:os"; -import { basename, resolve } from "node:path"; +import { homedir, userInfo } from "node:os"; +import { basename, resolve, sep } from "node:path"; import { parse as parseToml } from "smol-toml"; import { applyEdits, modify, parse as parseJsonc, type ParseError } from "jsonc-parser/lib/esm/main.js"; import { isMap, type Document } from "yaml"; import { writeConfigFileAtomic } from "./safe-config-write"; import { codexHome } from "./codex-system-hooks"; import { claudeConfigDir, getIntegration, readYamlDoc, writeYamlDoc, UnreadableAgentConfigError } from "./integrations"; + import { daemonSelfReportServer } from "./daemon-client"; import { resolveSelfReport, selfReportPort, selfReportSettingsFile, SELF_REPORT_SERVER_NAME, SELF_REPORT_SERVER_RECORDS } from "./self-report"; import { listHermesProfiles } from "../../lib/hermes-profiles"; @@ -91,6 +92,32 @@ import { listOpenClawProfiles } from "../../lib/openclaw-profiles"; import { INTEGRATION_TYPES, type IntegrationType } from "./types"; import { mergeTomlManagedBlock, readTomlManagedBlock, tomlString, type TomlBlockMarkers } from "./toml-managed-block"; +/** + * Test-only guard: a test that forgot to isolate HOME must never write the + * developer's real agent configs. `os.userInfo().homedir` ignores `$HOME`, so it + * names the real home even when a test moved `$HOME`; under Vitest a write into + * it throws. Production (no `VITEST` in the environment) is unaffected. + */ +function assertNotRealHomeUnderTest(path: string): void { + if (!process.env.VITEST) return; + let real = ""; + try { + real = userInfo().homedir; + } catch { + return; + } + if (!real) return; + const target = resolve(path); + if (target === real || target.startsWith(real.endsWith(sep) ? real : real + sep)) { + throw new Error(`refusing to write ${target} under test: set HOME to a temp dir`); + } +} + +function guardedWriteConfig(path: string, text: string): void { + assertNotRealHomeUnderTest(path); + writeConfigFileAtomic(path, text); +} + // ── Settings (CONTRACT §4) ────────────────────────────────────────────────── /** The MCP server's name in every agent. */ @@ -472,7 +499,7 @@ function jsonOps(target: McpTarget, path: string): FileOps { }); let next = applyEdits(base, edits); if (!next.endsWith("\n")) next += "\n"; - writeConfigFileAtomic(path, next); + guardedWriteConfig(path, next); }, }; } @@ -530,7 +557,7 @@ function tomlOps(path: string): FileOps { throw new Error(`the result would not be valid TOML (${err instanceof Error ? err.message.split("\n")[0] : String(err)})`); } if (entry && getIn(check, keyPath) === undefined) throw new Error("the written entry did not read back"); - writeConfigFileAtomic(path, next); + guardedWriteConfig(path, next); }, }; } @@ -563,6 +590,7 @@ function yamlOps(target: McpTarget, path: string): FileOps { } else { doc.deleteIn(keyPath); } + assertNotRealHomeUnderTest(path); writeYamlDoc(path, doc); }, }; From 32ca69cbb60252d465345b1422e7c71aec535f9e Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Fri, 27 Nov 2026 16:51:07 +0530 Subject: [PATCH 18/54] [self-reports] Apply machineLogs/logRequest only from an accepted desired-state; LangChain tool refuses core <0.3.44 Daemon: - poll_desired_state no longer applies machineLogs or logRequest; it returns them with selfReport, and reconcile_and_apply_settings applies them after the reconcile. A rollback, InvalidDesiredState or Withdrawn response changes neither the troubleshooting switch nor Self Reports; an accepted response whose artifact fetch failed still applies. machineLogs keeps its rules (absent = on, false = off). - logRequest exception: a current response refused only because the daemon cannot validate it (a newer server's policy shape) still delivers its request, since that refusal repeats every poll and support needs that machine's logs. Stale (below the rollback floor) and withdrawn responses do not; the upload stays bound by the switch as last accepted. - Tests: rolled back, withdrawn, failed artifact for troubleshooting, plus the unvalidatable-current case; logship's test lock is shared with them. TS SDK: - /langchain selfReportTool() throws FailproofAICompatError on an application @langchain/core older than 0.3.44 (empty schema to the model). The peer range stays >=0.3.0 <2: the tracer gives the same trace on 0.3.0, 0.3.43 and 0.3.44. A module passed in is not version-checked. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + crates/failproofaid/src/cloud_client.rs | 361 +++++++++++++++--- crates/failproofaid/src/cloud_policies.rs | 6 + crates/failproofaid/src/logship.rs | 15 +- sdk/typescript/CHANGELOG.md | 7 +- sdk/typescript/README.md | 4 +- .../src/integrations/self-report-tools.ts | 35 +- .../test/self-report-langchain-core.test.ts | 60 +++ 8 files changed, 439 insertions(+), 50 deletions(-) create mode 100644 sdk/typescript/test/self-report-langchain-core.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bf5d31da..c603cce3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - Self Reports: a project- or local-scope `policies --install` no longer writes failproofai's MCP server into the agents' user-wide configs, and under the test runner the installer refuses to write any agent config inside the real home directory (a test that did not isolate `HOME` had registered a server pointing at a deleted temp binary) (#1062) - A desired-state response the daemon refuses (a deployment rollback, or a disconnect during the poll) no longer changes Self Reports: its `selfReport` setting is applied only after the reconcile accepts the response, so an out-of-order older deployment can no longer turn reporting back on (#1062) +- The troubleshooting switch (`machineLogs`) and a `logRequest` follow the same rule: a desired-state response the daemon refuses no longer turns daemon-log uploads on or off, and a rolled-back or disconnected response no longer requests an upload. A response refused only because this daemon cannot validate it (a newer server's policy shape) still delivers its `logRequest`, since that refusal repeats every poll and support needs that machine's logs; the upload stays bound by the switch as last accepted (#1062) - Retire the hook-sync agent and stop publishing its image: `docker-hook-sync/`, its prompt and `build-image.yml` (which pushed `ghcr.io/failproofai/hook-sync` publicly every day) are removed. The agent ran Claude Code with permission checks skipped, a GitHub write token and a Claude token in its environment and no failproofai hooks, after reading a third-party npm README. Nothing had run it since July (FailproofAI/agenteye#1797, #1055) - `fp`, the dashboard's api-server client, and the collector's uploader and OTLP relay refuse a plain `http://` URL for any host but `localhost` and loopback addresses, so `FP_DASHBOARD_URL`, `FAILPROOF_API_URL` or `FAILPROOFAI_INGEST_URL` can no longer put a session, a token, a sign-in code or the ingest key on the network in clear, and the api-server client no longer follows redirects; `fp logout` still clears a session saved against such a URL, without sending it (#1057) - A dashboard bound off loopback (`FAILPROOFAI_DASHBOARD_HOST`) requires a per-launch access token on every request: the launch screen and `failproofai audit` print the address with `?token=` (audit no longer hands it to a browser opener, whose command line other local users can read), and the browser trades it for an HttpOnly cookie. Before, any machine on the network could set `Host` and `Origin` itself and read transcripts, change policies, or install a policy pack, which runs its code (#1057) diff --git a/crates/failproofaid/src/cloud_client.rs b/crates/failproofaid/src/cloud_client.rs index 86a69f0eb..a01ec96fe 100644 --- a/crates/failproofaid/src/cloud_client.rs +++ b/crates/failproofaid/src/cloud_client.rs @@ -847,7 +847,7 @@ impl CloudClient { &self, applied: Option, policy_errors: Option<&str>, - ) -> Result<(DesiredState, Option), PollFailure> { + ) -> Result<(DesiredState, CloudSettings), PollFailure> { let mut url = self .base_url .join("enforcement/v1/desired-state") @@ -886,25 +886,21 @@ impl CloudClient { .json::() .map_err(|err| PollFailure::payload(format!("invalid desired-state response: {err}"))) .and_then(|raw| { - // Applied only once the whole response is known good: a response - // this daemon refuses (an unknown schemaVersion, a payload that - // does not decode) must not turn troubleshooting back on or start - // an upload, so the last valid answer keeps standing. + // Nothing is applied here. A response this daemon refuses to + // decode (an unknown schemaVersion, a payload that does not + // decode) carries no settings at all, and one that decodes can + // still be refused by the reconcile (a deployment rollback, a + // withdrawn enrolment). The caller applies `selfReport`, + // `machineLogs` and `logRequest` once it knows which + // (`reconcile_and_apply_settings`). let (desired, consent, self_report) = decode_desired_state(raw)?; - // `selfReport` is NOT noted here: the reconcile can still refuse - // this response (a deployment rollback, a withdrawn enrolment), - // and a refused response must not flip the feature. The caller - // notes it once the reconcile accepted the deployment - // (`reconcile_and_note_self_report`). - // The org's troubleshooting switch: `machineLogs: false` means - // send no daemon log (logship.rs). Absent, from a Cloud with it - // on or one that predates the key, means send. - crate::logship::set_cloud_allows(consent.machine_logs != Some(false)); - // An operator asked for this machine's logs (logship.rs). - if let Some(id) = consent.log_request { - crate::logship::note_request(&id); - } - Ok((desired, self_report)) + Ok(( + desired, + CloudSettings { + consent, + self_report, + }, + )) }) } @@ -1346,12 +1342,22 @@ fn report_and_reclaim(cloud: &CloudClient, path: &Path, home: &Path, roster: &Ag } /// The log-shipping fields of a desired-state response (logship.rs). -#[derive(Debug, Default, PartialEq, Eq)] +#[derive(Debug, Default, Clone, PartialEq, Eq)] struct LogConsent { machine_logs: Option, log_request: Option, } +/// The machine settings a desired-state response carries beside its policies, +/// applied by `reconcile_and_apply_settings` only from a response the reconcile +/// accepted. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +struct CloudSettings { + consent: LogConsent, + /// `None`: absent, which means Self Reports are off. + self_report: Option, +} + /// Validates a desired-state response and decodes it. The log-shipping fields /// come back only with a response that was accepted, so a refused one has /// nothing to apply. @@ -1451,7 +1457,7 @@ fn poll_once_guarded( ) .map(|errors| encode_policy_errors(&errors)); match cloud.poll_desired_state(applied, report.as_deref()) { - Ok((desired, self_report)) => { + Ok((desired, settings)) => { // The GET created/checked-in the machine row the PUT requires. // Do not let a roster network outage interrupt local enforcement. if let Ok(path) = agent_roster::roster_path() @@ -1460,10 +1466,10 @@ fn poll_once_guarded( { report_and_reclaim(cloud, &path, Path::new(&home), &roster); } - match reconcile_and_note_self_report( + match reconcile_and_apply_settings( store, &desired, - self_report, + settings, &|policy: &DesiredPolicy| cloud.artifact(policy), withdrawn, ) { @@ -1517,33 +1523,56 @@ fn poll_once_guarded( } } -/// Reconcile `desired`, then hand its `selfReport` block to the maintenance -/// lane only when the reconcile accepted the response. +/// Reconcile `desired`, then apply the settings beside it: `selfReport` (to +/// the maintenance lane), `machineLogs` and `logRequest` (to logship.rs), only +/// when the reconcile accepted the response. /// /// Refused means: the response itself failed validation (an unknown shape, a /// deployment below the rollback floor — both `InvalidDesiredState`), or the /// machine was disconnected while the poll was in flight (`Withdrawn`). Such a -/// response is not the server's current answer for this machine, so its -/// `selfReport` must not change anything: an out-of-order deployment 99 that -/// says "on" after deployment 100 said "off" leaves the feature off. +/// response is not an answer this machine acts on, so its settings must not +/// change anything: an out-of-order deployment 99 that says "on" after +/// deployment 100 said "off" leaves the feature off, and troubleshooting off. /// /// An artifact failure (fetch, hash, I/O) is not a refusal: the response passed /// the rollback guard and is the server's newest answer, and an org toggle must /// not wait on an unrelated policy download that may keep failing. -fn reconcile_and_note_self_report( +/// +/// `machineLogs` keeps its rules: `false` means send no daemon log, absent +/// (a Cloud with it on, or one that predates the key) means send. A refused +/// response leaves the last accepted answer standing either way. +fn reconcile_and_apply_settings( store: &PolicyStore, desired: &DesiredState, - self_report: Option, + settings: CloudSettings, fetcher: &impl crate::cloud_policies::ArtifactFetcher, withdrawn: &dyn Fn() -> bool, ) -> Result { let result = store.reconcile_unless(desired, fetcher, withdrawn); - let refused = matches!( - result, - Err(ReconcileError::InvalidDesiredState(_) | ReconcileError::Withdrawn) - ); - if !refused && !withdrawn() { - crate::self_report::note_desired(self_report); + if matches!(result, Err(ReconcileError::Withdrawn)) || withdrawn() { + // Disconnected: this response is not Cloud's to act on any more, and + // a log request would only queue an upload for a machine that left. + return result; + } + let accepted = !matches!(result, Err(ReconcileError::InvalidDesiredState(_))); + if accepted { + crate::self_report::note_desired(settings.self_report); + // Before the request: turning troubleshooting off drops an open one. + crate::logship::set_cloud_allows(settings.consent.machine_logs != Some(false)); + } + // `logRequest` is the one exception, and only for a response that is not + // stale. A deployment this daemon cannot validate (a newer server's policy + // shape, a jevMode or authority this version does not know) is refused on + // every poll until the daemon is upgraded, and that machine is the one + // support needs logs from: a request is how they pull them. Out-of-order + // responses (below the rollback floor) are still ignored, and the upload + // stays bound by the org's switch as last accepted, since `note_request` + // queues nothing while troubleshooting is off. For an accepted response + // the floor is its own deployment, so this is every accepted response too. + if let Some(id) = &settings.consent.log_request + && desired.deployment >= store.server_high_water() + { + crate::logship::note_request(id); } result } @@ -2354,6 +2383,39 @@ mod tests { }) } + /// The settings beside the policies, as a desired-state response carries + /// them. + fn settings( + self_report: Option, + machine_logs: Option, + log_request: Option<&str>, + ) -> CloudSettings { + CloudSettings { + consent: LogConsent { + machine_logs, + log_request: log_request.map(str::to_owned), + }, + self_report, + } + } + + /// Every test below drives logship.rs's process-wide state; this holds its + /// lock and starts from troubleshooting on with nothing requested. + fn lock_logship() -> std::sync::MutexGuard<'static, ()> { + let guard = crate::logship::TEST_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + crate::logship::reset_for_test(true); + guard + } + + /// A response this daemon cannot validate: a `jevMode` it does not know. + fn unvalidatable_state(deployment: u64) -> DesiredState { + let mut desired = jev_state(deployment); + desired.jev_mode = Some("from-a-newer-server".into()); + desired + } + /// The review's replay: deployment 100 switched Self Reports off, then an /// out-of-order deployment 99 said on. The rollback is refused, and its /// `selfReport` must be refused with it: nothing is queued for the lane, so @@ -2361,13 +2423,14 @@ mod tests { #[test] fn a_rolled_back_response_does_not_change_self_reports() { let _env = lock_env(); + let _logs = lock_logship(); let _ = crate::self_report::take_pending(); let store = temp_store("self-report-rollback"); - reconcile_and_note_self_report( + reconcile_and_apply_settings( &store, &jev_state(100), - self_report_on(false), + settings(self_report_on(false), None, None), &serve, &|| false, ) @@ -2378,10 +2441,10 @@ mod tests { "an accepted response queues its setting" ); - let refused = reconcile_and_note_self_report( + let refused = reconcile_and_apply_settings( &store, &jev_state(99), - self_report_on(true), + settings(self_report_on(true), None, None), &serve, &|| false, ); @@ -2398,7 +2461,13 @@ mod tests { // Absent `selfReport` on a rolled-back response is refused the same way: // it must not switch an enabled machine off either. - let _ = reconcile_and_note_self_report(&store, &jev_state(98), None, &serve, &|| false); + let _ = reconcile_and_apply_settings( + &store, + &jev_state(98), + CloudSettings::default(), + &serve, + &|| false, + ); assert_eq!(crate::self_report::take_pending(), None); fs::remove_dir_all(store.root()).ok(); } @@ -2408,12 +2477,13 @@ mod tests { #[test] fn a_withdrawn_response_does_not_change_self_reports() { let _env = lock_env(); + let _logs = lock_logship(); let _ = crate::self_report::take_pending(); let store = temp_store("self-report-withdrawn"); - let result = reconcile_and_note_self_report( + let result = reconcile_and_apply_settings( &store, &jev_state(5), - self_report_on(true), + settings(self_report_on(true), None, None), &serve, &|| true, ); @@ -2431,12 +2501,13 @@ mod tests { #[test] fn an_accepted_response_with_a_failed_artifact_still_applies_self_reports() { let _env = lock_env(); + let _logs = lock_logship(); let _ = crate::self_report::take_pending(); let store = temp_store("self-report-fetch-fail"); - let result = reconcile_and_note_self_report( + let result = reconcile_and_apply_settings( &store, &jev_state(5), - self_report_on(true), + settings(self_report_on(true), None, None), &|_: &DesiredPolicy| Err::, String>("offline".into()), &|| false, ); @@ -2451,6 +2522,206 @@ mod tests { fs::remove_dir_all(store.root()).ok(); } + /// The same replay for troubleshooting: an out-of-order deployment 99 must + /// neither turn it back on (absent `machineLogs` means on) nor off, and its + /// `logRequest` must not start an upload. + #[test] + fn a_rolled_back_response_does_not_change_troubleshooting() { + let _env = lock_env(); + let _logs = lock_logship(); + let store = temp_store("logs-rollback"); + + // 100 turned troubleshooting off; 99 has no key (on) and a request. + reconcile_and_apply_settings( + &store, + &jev_state(100), + settings(None, Some(false), None), + &serve, + &|| false, + ) + .unwrap(); + assert_eq!(crate::logship::consent_for_test(), (false, None)); + let refused = reconcile_and_apply_settings( + &store, + &jev_state(99), + settings(None, None, Some("req-99")), + &serve, + &|| false, + ); + assert!( + matches!(&refused, Err(ReconcileError::InvalidDesiredState(m)) if m.contains("rollback")), + "{refused:?}" + ); + assert_eq!( + crate::logship::consent_for_test(), + (false, None), + "a rolled-back response must not turn troubleshooting back on" + ); + + // 101 turned it on; 98 says off and asks for logs. + reconcile_and_apply_settings( + &store, + &jev_state(101), + settings(None, Some(true), None), + &serve, + &|| false, + ) + .unwrap(); + assert_eq!(crate::logship::consent_for_test(), (true, None)); + let _ = reconcile_and_apply_settings( + &store, + &jev_state(98), + settings(None, Some(false), Some("req-98")), + &serve, + &|| false, + ); + assert_eq!( + crate::logship::consent_for_test(), + (true, None), + "a rolled-back response must neither turn troubleshooting off nor request logs" + ); + assert_eq!(store.read_active().unwrap().unwrap().deployment, 101); + fs::remove_dir_all(store.root()).ok(); + } + + /// A response discarded by `config --disconnect` changes neither the switch + /// nor queues its request. + #[test] + fn a_withdrawn_response_does_not_change_troubleshooting() { + let _env = lock_env(); + let _logs = lock_logship(); + let store = temp_store("logs-withdrawn"); + let result = reconcile_and_apply_settings( + &store, + &jev_state(5), + settings(None, Some(false), Some("req-5")), + &serve, + &|| true, + ); + assert!( + matches!(result, Err(ReconcileError::Withdrawn)), + "{result:?}" + ); + assert_eq!(crate::logship::consent_for_test(), (true, None)); + fs::remove_dir_all(store.root()).ok(); + } + + /// An accepted response whose artifact failed still applies both: `false` + /// turns troubleshooting off, and a request on a later one is queued. + #[test] + fn an_accepted_response_with_a_failed_artifact_still_applies_troubleshooting() { + let _env = lock_env(); + let _logs = lock_logship(); + let store = temp_store("logs-fetch-fail"); + let offline = |_: &DesiredPolicy| Err::, String>("offline".into()); + + let result = reconcile_and_apply_settings( + &store, + &jev_state(5), + settings(None, Some(false), Some("req-5")), + &offline, + &|| false, + ); + assert!( + matches!(result, Err(ReconcileError::Fetch { .. })), + "{result:?}" + ); + assert_eq!( + crate::logship::consent_for_test(), + (false, None), + "off applies, and drops the request that came with it" + ); + + let result = reconcile_and_apply_settings( + &store, + &jev_state(6), + settings(None, None, Some("req-6")), + &offline, + &|| false, + ); + assert!( + matches!(result, Err(ReconcileError::Fetch { .. })), + "{result:?}" + ); + assert_eq!( + crate::logship::consent_for_test(), + (true, Some("req-6".to_string())), + "absent means on, and the request is queued" + ); + fs::remove_dir_all(store.root()).ok(); + } + + /// The one exception: a current response this daemon refuses only because it + /// cannot validate it (a newer server's policy shape) still delivers its + /// `logRequest`, since that refusal repeats every poll and support needs + /// that machine's logs. Its `machineLogs` and `selfReport` are not applied, + /// and a request is still bound by the switch as last accepted. + #[test] + fn an_unvalidatable_current_response_still_delivers_its_log_request() { + let _env = lock_env(); + let _logs = lock_logship(); + let _ = crate::self_report::take_pending(); + let store = temp_store("logs-unvalidatable"); + reconcile_and_apply_settings( + &store, + &jev_state(100), + settings(None, Some(true), None), + &serve, + &|| false, + ) + .unwrap(); + let _ = crate::self_report::take_pending(); + + let refused = reconcile_and_apply_settings( + &store, + &unvalidatable_state(101), + settings(self_report_on(true), Some(false), Some("req-101")), + &serve, + &|| false, + ); + assert!( + matches!(&refused, Err(ReconcileError::InvalidDesiredState(m)) if m.contains("jevMode")), + "{refused:?}" + ); + assert_eq!( + crate::logship::consent_for_test(), + (true, Some("req-101".to_string())), + "the request is queued; the refused response's `false` is not applied" + ); + assert_eq!(crate::self_report::take_pending(), None); + assert_eq!(store.read_active().unwrap().unwrap().deployment, 100); + + // An unvalidatable response that is also stale is ignored entirely. + crate::logship::reset_for_test(true); + let _ = reconcile_and_apply_settings( + &store, + &unvalidatable_state(99), + settings(None, None, Some("req-99")), + &serve, + &|| false, + ); + assert_eq!(crate::logship::consent_for_test(), (true, None)); + + // With troubleshooting off (as last accepted), the request queues nothing. + reconcile_and_apply_settings( + &store, + &jev_state(102), + settings(None, Some(false), None), + &serve, + &|| false, + ) + .unwrap(); + let _ = reconcile_and_apply_settings( + &store, + &unvalidatable_state(103), + settings(None, Some(true), Some("req-103")), + &serve, + &|| false, + ); + assert_eq!(crate::logship::consent_for_test(), (false, None)); + fs::remove_dir_all(store.root()).ok(); + } + /// Exactly what `config --disconnect` removes /// (`clearActiveCloudManagedPolicies` in `cloud-managed-policies.ts`). fn disconnect_like_the_cli(store: &PolicyStore) { diff --git a/crates/failproofaid/src/cloud_policies.rs b/crates/failproofaid/src/cloud_policies.rs index ff42b5bc8..0aeac291c 100644 --- a/crates/failproofaid/src/cloud_policies.rs +++ b/crates/failproofaid/src/cloud_policies.rs @@ -535,6 +535,12 @@ impl PolicyStore { &self.root } + /// The highest deployment the server has offered this process (the + /// rollback floor). A response below it is an out-of-order older answer. + pub fn server_high_water(&self) -> u64 { + self.server_high_water.load(Ordering::Relaxed) + } + /// Forgets the highest deployment the server has offered this process. /// /// The deployment counter is the server's per (org, machine) — a different diff --git a/crates/failproofaid/src/logship.rs b/crates/failproofaid/src/logship.rs index ca21d8f71..f4372961a 100644 --- a/crates/failproofaid/src/logship.rs +++ b/crates/failproofaid/src/logship.rs @@ -917,6 +917,19 @@ fn ship_at(machine_id: &str, scrub: &Scrub, post: &dyn Fn(&Value) -> PostOutcome } } +/// Serialises every test that touches the process-wide state, in this module +/// and in `cloud_client`'s desired-state tests. +#[cfg(test)] +pub(crate) static TEST_LOCK: Mutex<()> = Mutex::new(()); + +/// What the org's switch and the open request are: (`uploads allowed`, +/// `requested id`). +#[cfg(test)] +pub(crate) fn consent_for_test() -> (bool, Option) { + let st = state(); + (!st.cloud_off, st.requested.clone()) +} + #[cfg(test)] pub(crate) fn reset_for_test(enabled: bool) { let mut st = state(); @@ -930,7 +943,7 @@ mod tests { use std::cell::RefCell; // The module keeps one process-wide state; serialise the tests that use it. - static LOCK: Mutex<()> = Mutex::new(()); + use super::TEST_LOCK as LOCK; fn line(level: &str, target: &str, msg: &str) -> String { format!("2026-11-18T13:18:37.676211Z {level:>5} {target}: {msg}\n") diff --git a/sdk/typescript/CHANGELOG.md b/sdk/typescript/CHANGELOG.md index aa5ea724b..3f4400516 100644 --- a/sdk/typescript/CHANGELOG.md +++ b/sdk/typescript/CHANGELOG.md @@ -34,7 +34,12 @@ section is missing or empty is refused before anything is built. ### Fixes -- _Nothing yet._ +- **The `/langchain` report tool refuses an `@langchain/core` older than 0.3.44.** + Before 0.3.44 a tool's schema is read only as zod, so the model was offered + `failproofai_report` with an empty schema. `selfReportTool()` now throws a + `FailproofAICompatError` naming the version found and the upgrade. The peer + range stays `>=0.3.0 <2`: the tracer records the same trace on 0.3.0, 0.3.43 + and 0.3.44. A `module` passed in is not version-checked. ## 0.0.1-beta.2 — 2026-10-16 diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index c81edb184..891c2f34e 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -506,7 +506,9 @@ other tool format. `jsonSchema()` object itself. The LangChain, Mastra and LlamaIndex tools return `unknown` unless you name the type, as above. - **LangChain needs `@langchain/core` 0.3.44 or later for this tool**: older - 0.3 releases read a tool's schema only as zod and send the model an empty one. + 0.3 releases read a tool's schema only as zod and send the model an empty one, + so on them `selfReportTool()` throws a `FailproofAICompatError` that says so + (the tracer still works from 0.3.0). A `module` you pass in is not checked. - **Edge builds** offer the same spec and tools, which answer `Recorded.` and record nothing. The Edge LangChain tool is a real LangChain tool when you pass `{ module: await import("@langchain/core/tools") }`; without it, it is a plain diff --git a/sdk/typescript/src/integrations/self-report-tools.ts b/sdk/typescript/src/integrations/self-report-tools.ts index 1481b2e43..09dd6bb64 100644 --- a/sdk/typescript/src/integrations/self-report-tools.ts +++ b/sdk/typescript/src/integrations/self-report-tools.ts @@ -16,7 +16,7 @@ import { tryRequire } from "../node-require.js"; import { recordToolCall, selfReportSpec } from "../self-report.js"; import { SELF_REPORT_TOOL_NAME } from "../self-report-spec.js"; -import { versionTuple } from "./compat.js"; +import { FailproofAICompatError, parseVersion, versionString, versionTuple } from "./compat.js"; /** Identity to record reports under, when the tool runs outside any scope. */ export interface SelfReportToolOptions { @@ -126,13 +126,44 @@ export interface LangChainSelfReportToolOptions extends SelfReportToolOptions { } /** - * The report tool for LangChain / LangGraph (`@langchain/core` ≥0.3), a + * The first `@langchain/core` whose tools take a JSON Schema. Before it, a + * tool's schema was read only as zod, so a JSON Schema reached the model as an + * empty one: the model saw a tool with no arguments. The `/langchain` tracer + * needs no such thing and keeps the peer range's 0.3.0 floor. + */ +const LANGCHAIN_SELF_REPORT_MIN_CORE = "0.3.44"; + +/** Refuse an `@langchain/core` older than the tool needs, by name and version. */ +function requireJsonSchemaTools(found: string | null): void { + if (found === null) return; + const [major = 0, minor = 0, patch = 0] = parseVersion(found); + const [needMajor = 0, needMinor = 0, needPatch = 0] = parseVersion(LANGCHAIN_SELF_REPORT_MIN_CORE); + const older = + major !== needMajor ? major < needMajor : minor !== needMinor ? minor < needMinor : patch < needPatch; + if (!older) return; + throw new FailproofAICompatError( + `selfReportTool() needs @langchain/core ${LANGCHAIN_SELF_REPORT_MIN_CORE} or later, and this ` + + `application has ${found}: older releases read a tool's schema only as zod, so the model ` + + `would be offered failproofai_report with no arguments. Upgrade it ` + + `(\`npm install @langchain/core@^${LANGCHAIN_SELF_REPORT_MIN_CORE}\`). The LangChain tracer ` + + `(instrument("langchain"), langchainHandler()) works on ${found} as it is.`, + ); +} + +/** + * The report tool for LangChain / LangGraph (`@langchain/core` ≥0.3.44), a * structured tool with a JSON Schema — bind it with the rest: * * const model = chat.bindTools([selfReportTool(), ...tools]); * createReactAgent({ llm, tools: [selfReportTool(), ...tools] }); + * + * Throws `FailproofAICompatError` when the application's `@langchain/core` is + * older than 0.3.44, rather than hand the model a tool with an empty schema. A + * `module` passed in is another copy whose version cannot be read, so it is + * taken as it is. */ export function langchainSelfReportTool(options: LangChainSelfReportToolOptions = {}): T { + if (options.module === undefined) requireJsonSchemaTools(versionString("@langchain/core")); const tools = options.module ?? tryRequire("@langchain/core/tools"); const spec = selfReportSpec(); const identity = identityOf(options); diff --git a/sdk/typescript/test/self-report-langchain-core.test.ts b/sdk/typescript/test/self-report-langchain-core.test.ts new file mode 100644 index 000000000..d61953dad --- /dev/null +++ b/sdk/typescript/test/self-report-langchain-core.test.ts @@ -0,0 +1,60 @@ +/** + * The LangChain report tool needs `@langchain/core` 0.3.44 or later: older 0.3 + * releases read a tool's schema only as zod and would offer the model the tool + * with no arguments. The peer range keeps its 0.3.0 floor for the tracer, so the + * tool refuses an older core itself, with a message that says so. + */ +import { describe, expect, it, vi } from "vitest"; + +const installed = vi.hoisted(() => ({ core: null as string | null })); +vi.mock("../src/integrations/compat.js", async (orig) => { + const real = await orig(); + return { + ...real, + versionString: (pkg: string) => (pkg === "@langchain/core" ? installed.core : real.versionString(pkg)), + }; +}); + +import { FailproofAICompatError } from "../src/integrations/compat.js"; +import { selfReportTool as langchainTool } from "../src/integrations/langchain.js"; + +describe("the LangChain report tool's @langchain/core floor", () => { + it("refuses a core older than 0.3.44 by name, version and fix", () => { + for (const core of ["0.3.0", "0.3.43", "0.2.36"]) { + installed.core = core; + let thrown: unknown; + try { + langchainTool(); + } catch (error) { + thrown = error; + } + expect(thrown, core).toBeInstanceOf(FailproofAICompatError); + const message = (thrown as Error).message; + expect(message).toContain(`needs @langchain/core 0.3.44 or later, and this application has ${core}`); + expect(message).toContain("npm install @langchain/core@^0.3.44"); + expect(message).toContain("LangChain tracer"); + } + }); + + it("passes 0.3.44 and later on to the usual resolution", () => { + // `@langchain/core` is not installed in this package, so a supported + // version gets past the floor and then reports the missing module. + for (const core of ["0.3.44", "0.3.80", "1.3.0", "0.4.0-rc.1"]) { + installed.core = core; + expect(() => langchainTool(), core).toThrow(/npm install @langchain\/core`/); + expect(() => langchainTool(), core).not.toThrow(FailproofAICompatError); + } + }); + + it("takes a module passed in as it is, whatever version resolves here", () => { + installed.core = "0.3.0"; + const tool = vi.fn((func: unknown, fields: unknown) => ({ func, fields })); + const built = langchainTool<{ fields: { name: string } }>({ module: { tool } }); + expect(built.fields.name).toBe("failproofai_report"); + }); + + it("does not guess when the version cannot be read", () => { + installed.core = null; + expect(() => langchainTool()).not.toThrow(FailproofAICompatError); + }); +}); From 10e709d14035e35b232e33a418f7cec98e659b52 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Fri, 27 Nov 2026 16:51:59 +0530 Subject: [PATCH 19/54] [release] 1.0.18-beta.2 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +++++++-- Cargo.lock | 6 +++--- Cargo.toml | 2 +- hermes-plugin/plugin.yaml | 2 +- package.json | 2 +- 5 files changed, 13 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c603cce3f..36e116398 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 1.0.18-beta.2 — 2026-11-27 + +### Fixes + +- Self Reports: a project- or local-scope `policies --install` no longer writes failproofai's MCP server into the agents' user-wide configs, and under the test runner the installer refuses to write any agent config inside the real home directory (a test that did not isolate `HOME` had registered a server pointing at a deleted temp binary) (#1062) +- The troubleshooting switch (`machineLogs`) and a `logRequest` follow the same rule: a desired-state response the daemon refuses no longer turns daemon-log uploads on or off, and a rolled-back or disconnected response no longer requests an upload. A response refused only because this daemon cannot validate it (a newer server's policy shape) still delivers its `logRequest`, since that refusal repeats every poll and support needs that machine's logs; the upload stays bound by the switch as last accepted (#1062) + ## 1.0.18-beta.1 — 2026-11-27 ### Features @@ -9,9 +16,7 @@ ### Fixes -- Self Reports: a project- or local-scope `policies --install` no longer writes failproofai's MCP server into the agents' user-wide configs, and under the test runner the installer refuses to write any agent config inside the real home directory (a test that did not isolate `HOME` had registered a server pointing at a deleted temp binary) (#1062) - A desired-state response the daemon refuses (a deployment rollback, or a disconnect during the poll) no longer changes Self Reports: its `selfReport` setting is applied only after the reconcile accepts the response, so an out-of-order older deployment can no longer turn reporting back on (#1062) -- The troubleshooting switch (`machineLogs`) and a `logRequest` follow the same rule: a desired-state response the daemon refuses no longer turns daemon-log uploads on or off, and a rolled-back or disconnected response no longer requests an upload. A response refused only because this daemon cannot validate it (a newer server's policy shape) still delivers its `logRequest`, since that refusal repeats every poll and support needs that machine's logs; the upload stays bound by the switch as last accepted (#1062) - Retire the hook-sync agent and stop publishing its image: `docker-hook-sync/`, its prompt and `build-image.yml` (which pushed `ghcr.io/failproofai/hook-sync` publicly every day) are removed. The agent ran Claude Code with permission checks skipped, a GitHub write token and a Claude token in its environment and no failproofai hooks, after reading a third-party npm README. Nothing had run it since July (FailproofAI/agenteye#1797, #1055) - `fp`, the dashboard's api-server client, and the collector's uploader and OTLP relay refuse a plain `http://` URL for any host but `localhost` and loopback addresses, so `FP_DASHBOARD_URL`, `FAILPROOF_API_URL` or `FAILPROOFAI_INGEST_URL` can no longer put a session, a token, a sign-in code or the ingest key on the network in clear, and the api-server client no longer follows redirects; `fp logout` still clears a session saved against such a URL, without sending it (#1057) - A dashboard bound off loopback (`FAILPROOFAI_DASHBOARD_HOST`) requires a per-launch access token on every request: the launch screen and `failproofai audit` print the address with `?token=` (audit no longer hands it to a browser opener, whose command line other local users can read), and the browser trades it for an HttpOnly cookie. Before, any machine on the network could set `Host` and `Origin` itself and read transcripts, change policies, or install a policy pack, which runs its code (#1057) diff --git a/Cargo.lock b/Cargo.lock index f04dc5f4e..e7ff233bc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -298,7 +298,7 @@ dependencies = [ [[package]] name = "failproofaid" -version = "1.0.18-beta.1" +version = "1.0.18-beta.2" dependencies = [ "fpai-collect", "fpai-ipc", @@ -361,7 +361,7 @@ dependencies = [ [[package]] name = "fpai-collect" -version = "1.0.18-beta.1" +version = "1.0.18-beta.2" dependencies = [ "axum", "getrandom 0.4.3", @@ -382,7 +382,7 @@ dependencies = [ [[package]] name = "fpai-ipc" -version = "1.0.18-beta.1" +version = "1.0.18-beta.2" dependencies = [ "libc", "proptest", diff --git a/Cargo.toml b/Cargo.toml index 634beb3d2..9a3557303 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "1.0.18-beta.1" +version = "1.0.18-beta.2" edition = "2024" license-file = "LICENSE" repository = "https://github.com/FailproofAI/failproofai" diff --git a/hermes-plugin/plugin.yaml b/hermes-plugin/plugin.yaml index 5f234c8e2..48517f045 100644 --- a/hermes-plugin/plugin.yaml +++ b/hermes-plugin/plugin.yaml @@ -1,5 +1,5 @@ name: failproofai -version: 1.0.18-beta.1 +version: 1.0.18-beta.2 description: Real-time FailproofAI policy enforcement for Hermes manifest_version: 2 api_version: 1 diff --git a/package.json b/package.json index 810ec5ae3..70af9e288 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "failproofai", - "version": "1.0.18-beta.1", + "version": "1.0.18-beta.2", "description": "The reliability layer for AI agents: see every failure, stop it in realtime. Policies hooked into 12 agent harnesses — Claude Code, Codex, Cursor, Hermes, OpenClaw and more — block the tool call before it runs. Local dashboard included, no account needed.", "bin": { "failproofai": "./dist/cli.mjs", From 1046646d31b0a46e5841ca4ae8338da9381707a7 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Fri, 27 Nov 2026 17:31:57 +0530 Subject: [PATCH 20/54] [self-reports] Name the local MCP server failproofai_local; enrolment, receipt and version fixes The local Self Reports server is registered as `failproofai_local` in every agent, so it no longer clashes with the FailproofAI Cloud gateway, which users add as `failproofai`. The installer never reads, changes, removes or reports an entry named `failproofai`, and the gateway's tools (and any other server's `report`) go through the policies. Tool-name spellings, Cursor's mcp_server_name and Antigravity's ServerName checks, the golden list, the daemon's serverInfo name, both SDKs, docs, status and help follow. Review fixes on #1062: - A local-source self-report.json no longer decides on a Cloud-enrolled machine: CLI readers, the daemon's reader and its HTTP settings cache all read off until the daemon writes the org's setting. - `self-report test` checks a receipt from the stdio server instead of the spool file, which a running collector may already have uploaded and deleted. - The daemon refuses settings files in an unsupported version, as the CLI does; test-fixtures/self-report/settings-cases.golden.json holds the shared cases. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + __tests__/hooks/self-report-golden.test.ts | 13 +- __tests__/hooks/self-report-handler.test.ts | 96 +++++--- __tests__/hooks/self-report-install.test.ts | 83 +++++-- __tests__/hooks/self-report.test.ts | 65 +++++- bin/failproofai.mjs | 4 +- crates/fpai-collect/src/self_report.rs | 153 ++++++++++-- crates/fpai-collect/tests/hooks_source.rs | 2 +- crates/fpai-collect/tests/self_report_mcp.rs | 42 +++- docs/reference/mcp.mdx | 6 +- docs/self-reports.mdx | 12 +- sdk/python/README.md | 2 +- sdk/python/failproofai_sdk/_self_report.py | 49 ++-- sdk/python/tests/test_self_report.py | 12 +- sdk/python/tests/test_self_report_golden.py | 8 +- sdk/typescript/src/self-report-spec.ts | 39 ++-- .../test/self-report-golden.test.ts | 9 +- sdk/typescript/test/self-report.test.ts | 10 +- src/hooks/handler.ts | 6 +- src/hooks/hook-activity-store.ts | 2 +- src/hooks/self-report-cli.ts | 53 +++-- src/hooks/self-report-install.ts | 47 ++-- src/hooks/self-report-mcp.ts | 12 +- src/hooks/self-report-names.ts | 52 +++-- src/hooks/self-report.ts | 17 +- .../self-report/settings-cases.golden.json | 221 ++++++++++++++++++ .../self-report/tool-names.golden.txt | 23 +- 27 files changed, 806 insertions(+), 236 deletions(-) create mode 100644 test-fixtures/self-report/settings-cases.golden.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 36e116398..10bf18067 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ ### Fixes +- Self Reports' local MCP server is now named `failproofai_local`, so it no longer clashes with the FailproofAI Cloud gateway, which users add as `failproofai`: the two coexist in one agent, the installer never reads, changes, removes or reports an entry named `failproofai`, and the gateway's tools go through the policies like any other server's. Agents see the tool as `mcp__failproofai_local__report` (Claude Code, Codex, Pi, Factory, Devin), `failproofai_local_report` (OpenCode), `mcp_failproofai_local_report` (Hermes, Antigravity) or `failproofai_local__report` (OpenClaw, Goose); Cursor's `mcp_server_name` and Antigravity's `call_mcp_tool` `ServerName` must be `failproofai_local`. The SDK tool stays `failproofai_report` (#1062) +- Self Reports on a machine that enrolls in Cloud with its own settings file in place: that local file no longer decides. Until the daemon writes the organization's setting, the hook, `failproofai mcp`, the daemon's HTTP server and `status` all read Self Reports as off, as they already did with no file (#1062) +- `failproofai self-report test` no longer reports a recorded test as a failure when the collector uploads and deletes the batch first: the stdio server hands the test a receipt naming the batch it published, and the test checks that instead of the file (#1062) +- The daemon refuses a `self-report.json` in a settings version it does not support, as the CLI already did, so its HTTP server no longer offers or records the tool for a file `status` and the stdio server read as off; a shared fixture holds the cases both readers are tested against (#1062) - Self Reports: a project- or local-scope `policies --install` no longer writes failproofai's MCP server into the agents' user-wide configs, and under the test runner the installer refuses to write any agent config inside the real home directory (a test that did not isolate `HOME` had registered a server pointing at a deleted temp binary) (#1062) - The troubleshooting switch (`machineLogs`) and a `logRequest` follow the same rule: a desired-state response the daemon refuses no longer turns daemon-log uploads on or off, and a rolled-back or disconnected response no longer requests an upload. A response refused only because this daemon cannot validate it (a newer server's policy shape) still delivers its `logRequest`, since that refusal repeats every poll and support needs that machine's logs; the upload stays bound by the switch as last accepted (#1062) diff --git a/__tests__/hooks/self-report-golden.test.ts b/__tests__/hooks/self-report-golden.test.ts index 745e9519d..7ee275866 100644 --- a/__tests__/hooks/self-report-golden.test.ts +++ b/__tests__/hooks/self-report-golden.test.ts @@ -93,18 +93,21 @@ describe("Self Reports golden files (CLI)", () => { expect(isSelfReportToolName(name), name).toBe(true); expect(isSelfReportToolName(name.toUpperCase()), name).toBe(true); } - for (const name of ["report", "MCP:report", "mcp__other__report", "failproofai_report_x", "xfailproofai__report", "failproofai"]) { + // The Cloud gateway's server is `failproofai`; its tools are never ours. + const gateway = ["mcp__failproofai__report", "failproofai__report", "failproofai___report", "mcp_failproofai_report", "failproofai-report", "failproofai/report"]; + for (const name of ["report", "MCP:report", "mcp__other__report", "failproofai_report_x", "xfailproofai_local__report", "failproofai", "failproofai_local", ...gateway]) { expect(isSelfReportToolName(name), name).toBe(false); } }); - it("recognises Cursor's MCP hook only with the failproofai server name", () => { - expect(isSelfReportCursorCall({ tool_name: "report", mcp_server_name: "failproofai" })).toBe(true); - expect(isSelfReportCursorCall({ tool_name: "MCP:report", mcp_server_name: "failproofai" })).toBe(true); + it("recognises Cursor's MCP hook only with the failproofai_local server name", () => { + expect(isSelfReportCursorCall({ tool_name: "report", mcp_server_name: "failproofai" })).toBe(false); + expect(isSelfReportCursorCall({ tool_name: "report", mcp_server_name: "failproofai_local" })).toBe(true); + expect(isSelfReportCursorCall({ tool_name: "MCP:report", mcp_server_name: "failproofai_local" })).toBe(true); expect(isSelfReportCursorCall({ tool_name: "report", mcp_server_name: "linear" })).toBe(false); expect(isSelfReportCursorCall({ tool_name: "report" })).toBe(false); expect(isSelfReportCursorCall({ tool_name: "MCP:report" })).toBe(false); - expect(isSelfReportCursorCall({ tool_name: "search", mcp_server_name: "failproofai" })).toBe(false); + expect(isSelfReportCursorCall({ tool_name: "search", mcp_server_name: "failproofai_local" })).toBe(false); }); it("keeps the TypeScript SDK's tool-name list equal to the golden list", () => { diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index 4b0270c9b..c366c79f5 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -47,7 +47,7 @@ function payload(toolName: string, toolInput: unknown, extra: Record = {}) => - payload("mcp__failproofai__report", { category: "invalid_tool_or_credential", detail: "tracker rejected its API key" }, extra); + payload("mcp__failproofai_local__report", { category: "invalid_tool_or_credential", detail: "tracker rejected its API key" }, extra); const bash = () => payload("Bash", { command: "echo hi" }); function rows(): Array> { @@ -109,7 +109,7 @@ describe("Self Reports short-circuit", () => { expect(row).toMatchObject({ eventType: "PreToolUse", integration: "claude", - toolName: "mcp__failproofai__report", + toolName: "mcp__failproofai_local__report", decision: "allow", policyName: null, sessionId: SESSION, @@ -173,7 +173,7 @@ describe("Self Reports short-circuit", () => { it("cuts detail at 2000 code points, never through a surrogate pair", async () => { const detail = `${"a".repeat(1999)}\u{1F600} and more text`; - await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai__report", { category: "looping", detail })); + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "looping", detail })); const line = readFileSync(join(home, "hook-activity", "current.jsonl"), "utf8").trim().split("\n").pop()!; // The row is valid UTF-8 JSON with no lone surrogate escape, which the // Rust collector would reject along with every hook event on the row. @@ -242,9 +242,9 @@ describe("Self Reports short-circuit", () => { }); it("files another agent's spelling under the canonical name", async () => { - const out = await evaluateHookEvent("PreToolUse", "claude", payload("failproofai__report", { category: "looping", detail: "x" })); + const out = await evaluateHookEvent("PreToolUse", "claude", payload("failproofai_local__report", { category: "looping", detail: "x" })); expect(out.evaluation?.decision).toBe("allow"); - expect(rows().pop()!.toolName).toBe("mcp__failproofai__report"); + expect(rows().pop()!.toolName).toBe("mcp__failproofai_local__report"); }); it("for an agent whose MCP server records, allows but leaves the report to the server", async () => { @@ -256,9 +256,9 @@ describe("Self Reports short-circuit", () => { }); it("records an unknown category as-is, a missing detail as empty, and cuts detail at 2000", async () => { - await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai__report", { category: "made_up" })); + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "made_up" })); expect(rows().pop()!.selfReport).toEqual({ category: "made_up", detail: "", source: "mcp" }); - await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai__report", { category: "looping", detail: "y".repeat(5000) })); + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "looping", detail: "y".repeat(5000) })); expect((rows().pop()!.selfReport as { detail: string }).detail).toHaveLength(2000); }); @@ -268,16 +268,16 @@ describe("Self Reports short-circuit", () => { }); it.each([ - ["factory", "failproofai___report"], - ["hermes", "mcp_failproofai_report"], - ["antigravity", "mcp_failproofai_report"], - ["opencode", "failproofai_report"], - ["openclaw", "failproofai__report"], - ["goose", "failproofai__report"], - ["pi", "mcp__failproofai__report"], - ["devin", "mcp__failproofai__report"], - ["copilot", "failproofai-report"], - ["copilot", "failproofai/report"], + ["factory", "failproofai_local___report"], + ["hermes", "mcp_failproofai_local_report"], + ["antigravity", "mcp_failproofai_local_report"], + ["opencode", "failproofai_local_report"], + ["openclaw", "failproofai_local__report"], + ["goose", "failproofai_local__report"], + ["pi", "mcp__failproofai_local__report"], + ["devin", "mcp__failproofai_local__report"], + ["copilot", "failproofai_local-report"], + ["copilot", "failproofai_local/report"], ] as const)("allows %s's spelling %s past a deny-everything policy", async (cli, name) => { const out = await evaluateHookEvent( "PreToolUse", @@ -288,12 +288,48 @@ describe("Self Reports short-circuit", () => { expect(loadAllCustomHooks).not.toHaveBeenCalled(); }); - it("allows Cursor's beforeMCPExecution for the failproofai server, with a schema-valid answer, leaving the report to the server", async () => { + it.each([ + ["claude", "mcp__failproofai__report"], + ["codex", "mcp__failproofai__report"], + ["factory", "failproofai___report"], + ["hermes", "mcp_failproofai_report"], + ["openclaw", "failproofai__report"], + ["goose", "failproofai__report"], + ["copilot", "failproofai-report"], + ["claude", "mcp__linear__report"], + ["opencode", "linear_report"], + ] as const)("keeps another server's report tool on the policy path: %s %s", async (cli, name) => { + // `failproofai` is the Cloud gateway's server name, not ours: its tools, + // and any other server's `report`, go through the policies like any call. + const out = await evaluateHookEvent("PreToolUse", cli, payload(name, { category: "looping", detail: "x" })); + expect(out.evaluation?.decision).toBe("deny"); + expect(loadAllCustomHooks).toHaveBeenCalled(); + expect(rows().some((r) => r.selfReport !== undefined)).toBe(false); + }); + + it("does not early-allow Cursor or Antigravity calls naming the Cloud gateway's server failproofai", async () => { + for (const event of ["preToolUse", "beforeMCPExecution"]) { + const out = await evaluateHookEvent(event, "cursor", payload("report", { category: "looping", detail: "x" }, { mcp_server_name: "failproofai" })); + expect(out.evaluation?.decision, event).toBe("deny"); + } + const agy = await evaluateHookEvent( + "PreToolUse", + "antigravity", + JSON.stringify({ + conversationId: SESSION, + workspacePaths: ["/tmp/project"], + toolCall: { name: "call_mcp_tool", args: { ServerName: "failproofai", ToolName: "report", Arguments: {} } }, + }), + ); + expect(agy.evaluation?.decision).toBe("deny"); + }); + + it("allows Cursor's beforeMCPExecution for the failproofai_local server, with a schema-valid answer, leaving the report to the server", async () => { const out = await evaluateHookEvent( "beforeMCPExecution", "cursor", payload("report", JSON.stringify({ category: "missing_context", detail: "no repo access" }), { - mcp_server_name: "failproofai", + mcp_server_name: "failproofai_local", url: "http://127.0.0.1:4319/mcp?agent=cursor", }), ); @@ -303,7 +339,7 @@ describe("Self Reports short-circuit", () => { const [row] = rows(); // Cursor is server-recorded: the MCP server writes the report, so the // hook row must not carry a second one. - expect(row).toMatchObject({ eventType: "PreToolUse", integration: "cursor", toolName: "mcp__failproofai__report" }); + expect(row).toMatchObject({ eventType: "PreToolUse", integration: "cursor", toolName: "mcp__failproofai_local__report" }); expect(row.selfReport).toBeUndefined(); }); @@ -312,11 +348,11 @@ describe("Self Reports short-circuit", () => { expect(out.evaluation?.decision).toBe("deny"); }); - it("early-allows Cursor's preToolUse MCP:report only when the payload names server failproofai", async () => { + it("early-allows Cursor's preToolUse MCP:report only when the payload names server failproofai_local", async () => { const ours = await evaluateHookEvent( "preToolUse", "cursor", - payload("MCP:report", { category: "looping", detail: "x" }, { mcp_server_name: "failproofai" }), + payload("MCP:report", { category: "looping", detail: "x" }, { mcp_server_name: "failproofai_local" }), ); expect(ours.evaluation?.decision).toBe("allow"); expect(rows().pop()!.selfReport).toBeUndefined(); @@ -331,7 +367,7 @@ describe("Self Reports short-circuit", () => { it("never lets a Cursor call that fails the server check through by its name alone", async () => { // Another server's tool, or one with no server named, spelled like ours: // it keeps its own name, is not recorded as a report, and the policies run. - for (const name of ["mcp__failproofai__report", "failproofai__report", "failproofai-report", "mcp_failproofai_report"]) { + for (const name of ["mcp__failproofai_local__report", "failproofai_local__report", "failproofai_local-report", "mcp_failproofai_local_report"]) { for (const extra of [{ mcp_server_name: "linear" }, {}]) { vi.mocked(loadAllCustomHooks).mockClear(); for (const event of ["preToolUse", "beforeMCPExecution"]) { @@ -346,7 +382,7 @@ describe("Self Reports short-circuit", () => { // The same spelling WITH our server is still ours. const ours = await evaluateHookEvent( "preToolUse", "cursor", - payload("mcp__failproofai__report", { category: "looping", detail: "x" }, { mcp_server_name: "failproofai" }), + payload("mcp__failproofai_local__report", { category: "looping", detail: "x" }, { mcp_server_name: "failproofai_local" }), ); expect(ours.evaluation?.decision).toBe("allow"); }); @@ -355,16 +391,16 @@ describe("Self Reports short-circuit", () => { const agy = (args: Record) => JSON.stringify({ conversationId: SESSION, workspacePaths: ["/tmp/project"], toolCall: { name: "call_mcp_tool", args } }); - it("early-allows the wrapper when it names server failproofai and tool report", async () => { + it("early-allows the wrapper when it names server failproofai_local and tool report", async () => { const out = await evaluateHookEvent( "PreToolUse", "antigravity", - agy({ ServerName: "failproofai", ToolName: "report", Arguments: { category: "looping", detail: "again" } }), + agy({ ServerName: "failproofai_local", ToolName: "report", Arguments: { category: "looping", detail: "again" } }), ); expect(out.evaluation?.decision).toBe("allow"); expect(loadAllCustomHooks).not.toHaveBeenCalled(); const row = rows().pop()!; - expect(row).toMatchObject({ integration: "antigravity", toolName: "mcp__failproofai__report", sessionId: SESSION }); + expect(row).toMatchObject({ integration: "antigravity", toolName: "mcp__failproofai_local__report", sessionId: SESSION }); // Antigravity is server-recorded: the MCP server writes the report. expect(row.selfReport).toBeUndefined(); }); @@ -373,14 +409,14 @@ describe("Self Reports short-circuit", () => { const out = await evaluateHookEvent( "PreToolUse", "antigravity", - agy({ ServerName: "failproofai", ToolName: "report", Arguments: JSON.stringify({ category: "looping", detail: "x" }) }), + agy({ ServerName: "failproofai_local", ToolName: "report", Arguments: JSON.stringify({ category: "looping", detail: "x" }) }), ); expect(out.evaluation?.decision).toBe("allow"); }); it.each([ [{ ServerName: "linear", ToolName: "report", Arguments: {} }], - [{ ServerName: "failproofai", ToolName: "search", Arguments: {} }], + [{ ServerName: "failproofai_local", ToolName: "search", Arguments: {} }], [{ ToolName: "report", Arguments: {} }], [{ ServerName: "failproofai-evil", ToolName: "report" }], ])("keeps any other wrapped call on the policy path: %j", async (args) => { @@ -392,7 +428,7 @@ describe("Self Reports short-circuit", () => { const out = await evaluateHookEvent( "PreToolUse", "claude", - payload("call_mcp_tool", { ServerName: "failproofai", ToolName: "report", Arguments: {} }), + payload("call_mcp_tool", { ServerName: "failproofai_local", ToolName: "report", Arguments: {} }), ); expect(out.evaluation?.decision).toBe("deny"); }); diff --git a/__tests__/hooks/self-report-install.test.ts b/__tests__/hooks/self-report-install.test.ts index 9fd17d302..f05e58f39 100644 --- a/__tests__/hooks/self-report-install.test.ts +++ b/__tests__/hooks/self-report-install.test.ts @@ -62,7 +62,7 @@ function read(path: string): string { return readFileSync(path, "utf8"); } -/** The parsed `failproofai` entry, whatever the agent's format. */ +/** The parsed `failproofai_local` entry, whatever the agent's format. */ function entryIn(agent: IntegrationType): Record | undefined { const path = pathOf(agent); if (!existsSync(path)) return undefined; @@ -71,7 +71,7 @@ function entryIn(agent: IntegrationType): Record | undefined { const doc = (t.format === "toml" ? parseToml(text) : t.format === "yaml" ? parseYaml(text) ?? {} : parseJsonc(text)) as Record; const container = t.container(doc); let v: unknown = doc; - for (const k of [...container, "failproofai"]) v = (v as Record | undefined)?.[k]; + for (const k of [...container, "failproofai_local"]) v = (v as Record | undefined)?.[k]; return v as Record | undefined; } @@ -172,7 +172,7 @@ describe("transport choice", () => { }); it("moves a server-recorded agent's older HTTP entry to stdio", async () => { - put(pathOf("copilot"), JSON.stringify({ mcpServers: { failproofai: { type: "http", url: "http://127.0.0.1:4319/mcp?agent=copilot", tools: ["*"] } } })); + put(pathOf("copilot"), JSON.stringify({ mcpServers: { failproofai_local: { type: "http", url: "http://127.0.0.1:4319/mcp?agent=copilot", tools: ["*"] } } })); const r = await syncSelfReportMcp(enabledOpts({ agents: ["copilot"] }, true)); expect(r[0]).toMatchObject({ action: "updated", transport: "stdio" }); expect(entryIn("copilot")).toEqual({ type: "local", command: CLI, args: ["mcp", "--agent", "copilot"], tools: ["*"] }); @@ -191,7 +191,7 @@ describe("transport choice", () => { expect(entryIn("pi")).toEqual({ command: CLI, args: ["mcp", "--agent", "pi"], exposure: "direct" }); // An older HTTP entry, written before `exposure` was set, is ours: it is // moved to stdio (Pi is server-recorded) with exposure set. - put(pathOf("pi"), JSON.stringify({ mcpServers: { failproofai: { url: "http://127.0.0.1:4319/mcp?agent=pi" } } })); + put(pathOf("pi"), JSON.stringify({ mcpServers: { failproofai_local: { url: "http://127.0.0.1:4319/mcp?agent=pi" } } })); const r = await syncSelfReportMcp(enabledOpts({ agents: ["pi"] }, true)); expect(r[0]).toMatchObject({ action: "updated", transport: "stdio" }); expect(entryIn("pi")).toEqual({ command: CLI, args: ["mcp", "--agent", "pi"], exposure: "direct" }); @@ -200,7 +200,7 @@ describe("transport choice", () => { it("tells the user how cursor-agent approves the server when Cursor's entry is written", async () => { const { selfReportSyncLines } = await import("../../src/hooks/self-report-install"); const lines = selfReportSyncLines(await syncSelfReportMcp(enabledOpts({ agents: ["cursor", "claude"] }))); - expect(lines.filter((l) => l.includes("cursor-agent mcp enable failproofai"))).toHaveLength(1); + expect(lines.filter((l) => l.includes("cursor-agent mcp enable failproofai_local"))).toHaveLength(1); expect(lines.findIndex((l) => l.includes("cursor-agent mcp enable"))).toBe( lines.findIndex((l) => l.includes("Cursor")) + 1, ); @@ -211,7 +211,7 @@ describe("transport choice", () => { const r = await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, true)); expect(r[0]).toMatchObject({ action: "updated", transport: "http" }); const text = read(pathOf("codex")); - expect(text.match(/\[mcp_servers\.failproofai\]/g)).toHaveLength(1); + expect(text.match(/\[mcp_servers\.failproofai_local\]/g)).toHaveLength(1); expect(entryIn("codex")).toEqual({ url: "http://127.0.0.1:4319/mcp?agent=codex" }); }); @@ -249,9 +249,9 @@ describe("transport choice", () => { }); describe("ownership", () => { - it("never touches a failproofai entry it did not write (e.g. the Cloud MCP gateway)", async () => { + it("never touches a failproofai_local entry it did not write, and reports it as a conflict", async () => { const path = pathOf("claude"); - const foreign = { mcpServers: { failproofai: { type: "http", url: "https://gateway.example.com/mcp" } } }; + const foreign = { mcpServers: { failproofai_local: { type: "http", url: "https://elsewhere.example.com/mcp" } } }; put(path, JSON.stringify(foreign, null, 2) + "\n"); const before = read(path); expect((await syncSelfReportMcp(enabledOpts({ agents: ["claude"] })))[0]).toMatchObject({ status: "conflict", action: "skipped" }); @@ -259,14 +259,59 @@ describe("ownership", () => { expect(read(path)).toBe(before); }); - it("treats a hand-written codex [mcp_servers.failproofai] outside our markers as foreign", async () => { + it("treats a hand-written codex [mcp_servers.failproofai_local] outside our markers as foreign", async () => { const path = pathOf("codex"); - put(path, '[mcp_servers.failproofai]\nurl = "http://127.0.0.1:4319/mcp?agent=codex"\n'); + put(path, '[mcp_servers.failproofai_local]\nurl = "http://127.0.0.1:4319/mcp?agent=codex"\n'); const before = read(path); expect((await syncSelfReportMcp(enabledOpts({ agents: ["codex"] })))[0].status).toBe("conflict"); expect(read(path)).toBe(before); }); + // The Cloud MCP gateway is registered as `failproofai`. Ours is + // `failproofai_local`, so the gateway's entry is never read, changed, + // removed or reported, in any format, even one shaped exactly like ours. + const GATEWAY_URL = "https://gateway.befailproof.ai/mcp"; + const gatewayFixtures: Array<[IntegrationType, string, (text: string) => unknown]> = [ + ["claude", JSON.stringify({ mcpServers: { failproofai: { type: "http", url: GATEWAY_URL } } }, null, 2) + "\n", + (t) => (JSON.parse(t) as { mcpServers: Record }).mcpServers.failproofai], + ["cursor", JSON.stringify({ mcpServers: { failproofai: { url: GATEWAY_URL } } }, null, 2) + "\n", + (t) => (JSON.parse(t) as { mcpServers: Record }).mcpServers.failproofai], + ["opencode", JSON.stringify({ mcp: { failproofai: { type: "remote", url: GATEWAY_URL, enabled: true } } }, null, 2) + "\n", + (t) => (JSON.parse(t) as { mcp: Record }).mcp.failproofai], + ["codex", `[mcp_servers.failproofai]\nurl = "${GATEWAY_URL}"\n`, + (t) => (parseToml(t) as { mcp_servers: Record }).mcp_servers.failproofai], + ["hermes", `mcp_servers:\n failproofai:\n url: ${GATEWAY_URL}\n`, + (t) => (parseYaml(t) as { mcp_servers: Record }).mcp_servers.failproofai], + ["goose", `extensions:\n failproofai:\n name: failproofai\n type: streamable_http\n enabled: true\n uri: ${GATEWAY_URL}\n`, + (t) => (parseYaml(t) as { extensions: Record }).extensions.failproofai], + ]; + for (const [agent, text, gatewayOf] of gatewayFixtures) { + it(`${agent}: leaves a Cloud gateway entry named failproofai untouched next to ours`, async () => { + if (agent === "hermes") put(resolve(home, ".hermes", "config.yaml"), text); + else put(pathOf(agent), text); + const path = pathOf(agent); + const gateway = gatewayOf(read(path)); + const added = await syncSelfReportMcp(enabledOpts({ agents: [agent] })); + expect(added.map((r) => [r.action, r.status])).toEqual([["added", "ok"]]); + expect(isOurMcpEntry(entryIn(agent))).toBe(true); + expect(gatewayOf(read(path))).toEqual(gateway); + const status = selfReportRegistrationStatus({ agents: [agent], hooksInstalled: () => true }); + expect(status.map((r) => [r.registered, r.conflict])).toEqual([[true, false]]); + // Disable and uninstall take out ours only. + expect(removeSelfReportMcp({ agents: [agent], quiet: true }).map((r) => r.action)).toEqual(["removed"]); + expect(entryIn(agent)).toBeUndefined(); + expect(gatewayOf(read(path))).toEqual(gateway); + }); + } + + it("leaves a failproofai entry alone even when it is shaped like ours", async () => { + const path = pathOf("claude"); + put(path, JSON.stringify({ mcpServers: { failproofai: { type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude" } } }, null, 2) + "\n"); + await syncSelfReportMcp(enabledOpts({ agents: ["claude"] })); + removeSelfReportMcp({ agents: ["claude"], quiet: true }); + expect(JSON.parse(read(path)).mcpServers.failproofai).toEqual({ type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude" }); + }); + it("refuses a codex config whose inline mcp_servers table would collide, leaving it as is", async () => { const path = pathOf("codex"); put(path, 'mcp_servers = { mine = { command = "node" } }\n'); @@ -342,8 +387,8 @@ describe("which agents", () => { const r = await syncSelfReportMcp(enabledOpts({ agents: ["hermes"] })); expect(r.map((x) => x.action)).toEqual(["added", "added"]); for (const p of [resolve(home, ".hermes", "config.yaml"), resolve(home, ".hermes", "profiles", "work", "config.yaml")]) { - const doc = parseYaml(read(p)) as { mcp_servers: { failproofai: unknown } }; - expect(doc.mcp_servers.failproofai).toEqual({ command: CLI, args: ["mcp", "--agent", "hermes"] }); + const doc = parseYaml(read(p)) as { mcp_servers: { failproofai_local: unknown } }; + expect(doc.mcp_servers.failproofai_local).toEqual({ command: CLI, args: ["mcp", "--agent", "hermes"] }); expect(read(p)).toContain("failproofai self-report MCP server"); } }); @@ -361,8 +406,8 @@ describe("which agents", () => { put(pathOf("opencode"), JSON.stringify({ mcp: { servers: { mine: { type: "local", command: ["node"] } } } })); await syncSelfReportMcp(enabledOpts({ agents: ["opencode"] })); const doc = JSON.parse(read(pathOf("opencode"))); - expect(doc.mcp.servers.failproofai).toEqual({ type: "local", command: [CLI, "mcp", "--agent", "opencode"] }); - expect(doc.mcp.failproofai).toBeUndefined(); + expect(doc.mcp.servers.failproofai_local).toEqual({ type: "local", command: [CLI, "mcp", "--agent", "opencode"] }); + expect(doc.mcp.failproofai_local).toBeUndefined(); }); it("keeps a backup of the file it changed", async () => { @@ -396,7 +441,7 @@ function fakeDaemon(path: string, answer = true, selfReport?: { instanceId: stri } /** A fake MCP endpoint on an ephemeral loopback port. */ -function fakeMcp(serverName = "failproofai", instanceId: string | null = "inst-1"): Promise<{ server: HttpServer; port: number }> { +function fakeMcp(serverName = "failproofai_local", instanceId: string | null = "inst-1"): Promise<{ server: HttpServer; port: number }> { const server = createHttpServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); @@ -480,7 +525,7 @@ describe("live transport check", () => { vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); // Another daemon (another home) holds the port; this one's bind failed, so // its pong names no MCP server: stdio, even though the port answers. - const { server, port } = await fakeMcp("failproofai", "other-daemon"); + const { server, port } = await fakeMcp("failproofai_local", "other-daemon"); track(server); const daemon = track(await fakeDaemon(socket())); expect(await probeSelfReportHttpInstance(port)).toBe("other-daemon"); @@ -500,13 +545,13 @@ describe("live transport check", () => { it("a pong naming another port, or an endpoint with no instance id, is stdio", async () => { vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); - const { server, port } = await fakeMcp("failproofai", "inst-1"); + const { server, port } = await fakeMcp("failproofai_local", "inst-1"); track(server); const daemon = track(await fakeDaemon(socket(), true, { instanceId: "inst-1", port: port + 1 })); expect(await selfReportDaemonLive(port)).toBe(false); await new Promise((ok) => daemon.close(ok)); closeAll.pop(); - const old = await fakeMcp("failproofai", null); + const old = await fakeMcp("failproofai_local", null); track(old.server); expect(await probeSelfReportHttpInstance(old.port)).toBe(""); track(await fakeDaemon(socket(), true, { instanceId: "inst-1", port: old.port })); @@ -536,7 +581,7 @@ describe("live transport check", () => { describe("selfReportRegistrationStatus", () => { it("reports registered, transport, conflict and hooked per file without writing", async () => { await syncSelfReportMcp(enabledOpts({ agents: ["claude"] }, false)); - put(pathOf("cursor"), JSON.stringify({ mcpServers: { failproofai: { url: "https://elsewhere" } } })); + put(pathOf("cursor"), JSON.stringify({ mcpServers: { failproofai_local: { url: "https://elsewhere" } } })); const s = selfReportRegistrationStatus({ agents: ["claude", "cursor", "factory"], hooksInstalled: (a) => a === "claude" }); expect(s).toEqual([ expect.objectContaining({ agent: "claude", hooked: true, registered: true, transport: "stdio", endpoint: CLI, conflict: false }), diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index 781943ae2..99d8a1e03 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -100,11 +100,11 @@ describe("tool text and schema (contract §3)", () => { }); describe("tool-name matching (contract §1)", () => { - it.each(["mcp__failproofai__report", "failproofai__report", "failproofai_report", "failproofai.report", "failproofai/report", "MCP__FAILPROOFAI__REPORT"])( + it.each(["mcp__failproofai_local__report", "failproofai_local__report", "failproofai_report", "failproofai_local.report", "failproofai_local/report", "MCP__FAILPROOFAI_LOCAL__REPORT"])( "matches %s", (name) => expect(isSelfReportToolName(name)).toBe(true), ); - it.each(["report", "mcp__other__report", "mcp__failproofai__report2", "xfailproofai_report", "Bash", "", undefined, 7])( + it.each(["report", "mcp__other__report", "mcp__failproofai__report", "failproofai__report", "mcp__failproofai_local__report2", "xfailproofai_report", "Bash", "", undefined, 7])( "does not match %s", (name) => expect(isSelfReportToolName(name)).toBe(false), ); @@ -195,6 +195,41 @@ describe("resolveSelfReport: on by default (contract §4)", () => { }); }); +describe("settings-cases.golden.json: the same on/off as the daemon's readers", () => { + const fixture = JSON.parse( + readFileSync(resolve(__dirname, "..", "..", "test-fixtures", "self-report", "settings-cases.golden.json"), "utf8"), + ) as { cases: { name: string; file?: unknown; text?: string; enrolled: boolean; on: boolean }[] }; + for (const c of fixture.cases) { + it(c.name, () => { + const path = join(home, "self-report.json"); + if (c.text !== undefined) writeFileSync(path, c.text); + else if (c.file !== null && c.file !== undefined) writeFileSync(path, JSON.stringify(c.file, null, 2)); + expect(resolveSelfReport(path, () => c.enrolled)?.enabled === true).toBe(c.on); + }); + } +}); + +describe("enrolling with a local settings file in place", () => { + it("sets this machine's own file aside until the daemon writes the org's setting", async () => { + writeEffectiveSelfReport({ enabled: true }); + expect(resolveSelfReport()?.enabled).toBe(true); + // Enrolled now; the daemon's first poll has not been applied yet. + process.env.FAILPROOFAI_CLOUD_URL = "https://cloud.example.invalid"; + expect(resolveSelfReport()).toBeNull(); + // Every reader agrees: the stdio server hides the tool, the hook records nothing. + const listed = await handleSelfReportRpc({ jsonrpc: "2.0", id: 1, method: "tools/list" }); + expect((listed as { result: { tools: unknown[] } }).result.tools).toEqual([]); + const status = await runSelfReportCommand(["status"], { registrations: () => [], probeEndpoint: async () => false, daemonExpected: () => false }); + expect(status.lines[0]).toContain("off (waiting for FailproofAI Cloud"); + // The org's setting arrives (the daemon writes a cloud file): it decides. + const cloud = { ...JSON.parse(readFileSync(join(home, "self-report.json"), "utf8")), source: "cloud", enabled: true }; + writeFileSync(join(home, "self-report.json"), JSON.stringify(cloud)); + expect(resolveSelfReport()?.enabled).toBe(true); + writeFileSync(join(home, "self-report.json"), JSON.stringify({ ...cloud, enabled: false })); + expect(resolveSelfReport()?.enabled).toBe(false); + }); +}); + describe("selfReportCloudEnrolled (sync, the daemon's Enrolment::resolve)", () => { it("follows the env, the credential files and the oss veto", () => { expect(selfReportCloudEnrolled()).toBe(false); @@ -411,7 +446,7 @@ describe("failproofai mcp (stdio, spawned)", () => { const { replies, code } = await runMcp([], [INIT, INITIALIZED, LIST, PING], home); expect(code).toBe(0); expect(replies.map((r) => r.id)).toEqual([1, 2, 4]); - expect(replies[0]).toMatchObject({ result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "failproofai" } } }); + expect(replies[0]).toMatchObject({ result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "failproofai_local" } } }); expect((replies[0].result as Record)).not.toHaveProperty("instructions"); expect(replies[1]).toEqual({ jsonrpc: "2.0", id: 2, result: { tools: [] } }); expect(replies[2]).toEqual({ jsonrpc: "2.0", id: 4, result: {} }); @@ -766,11 +801,33 @@ describe("failproofai self-report enable | disable | status", () => { expect(r.lines.join("\n")).toContain(join(dir, readdirSync(dir)[0])); }, 30_000); + it("test --agent pi passes when a collector consumes the batch before the check", async () => { + // The wrapper runs the real CLI, then deletes every published batch the way + // a running collector does after uploading it, before the command looks. + writeEffectiveSelfReport({ enabled: true }); + const consume = `bun "${BINARY}" "$@"; code=$?; rm -f "$FAILPROOFAI_HOME"/custom-agents/events/*.jsonl; exit $code`; + const r = await runSelfReportCommand(["test", "--agent", "pi"], { ...deps, cliCommand: ["sh", "-c", consume, "sh"], cwd: home }); + expect(r.lines.join("\n")).toContain("recorded by the MCP server"); + expect(r.lines.join("\n")).toContain("already picked up by the collector"); + expect(r.exitCode).toBe(0); + expect(readdirSync(join(home, "custom-agents", "events")).filter((f) => f.endsWith(".jsonl"))).toEqual([]); + }, 30_000); + + it("test --agent pi still fails when the server recorded nothing", async () => { + writeEffectiveSelfReport({ enabled: true }); + // The server answers Recorded. but cannot write (the spool is a file). + mkdirSync(join(home, "custom-agents"), { recursive: true }); + writeFileSync(join(home, "custom-agents", "events"), "not a directory"); + const r = await runSelfReportCommand(["test", "--agent", "pi"], { ...deps, cliCommand: ["bun", BINARY], cwd: home }); + expect(r.exitCode).toBe(1); + expect(r.lines[0]).toContain("did not land"); + }, 30_000); + it("test --agent claude goes through --hook and lands in hook activity", async () => { writeEffectiveSelfReport({ enabled: true }); const r = await runSelfReportCommand(["test", "--agent", "claude"], { ...deps, cliCommand: ["bun", BINARY], cwd: home }); expect(r.exitCode).toBe(0); const rows = readFileSync(join(home, "hook-activity", "current.jsonl"), "utf8").trim().split("\n").map((l) => JSON.parse(l)); - expect(rows.pop()).toMatchObject({ toolName: "mcp__failproofai__report", decision: "allow", selfReport: { source: "mcp" } }); + expect(rows.pop()).toMatchObject({ toolName: "mcp__failproofai_local__report", decision: "allow", selfReport: { source: "mcp" } }); }, 30_000); }); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index 4a65b5923..e2627890b 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -805,7 +805,7 @@ async function runCli() { if (subArgs.includes("--help") || subArgs.includes("-h")) { await printHelp({ name: "self-report sync", - usage: [["failproofai self-report sync [--quiet]", "Register or remove the Self Reports MCP server in each hooked agent"]], + usage: [["failproofai self-report sync [--quiet]", "Register or remove the Self Reports MCP server (failproofai_local) in each hooked agent"]], options: [["--quiet", "Print nothing; the exit code says whether every agent succeeded"]], optionsCol: 12, }); @@ -1085,7 +1085,7 @@ async function runCli() { ["failproofai self-report enable [options]", "Turn it back on for this machine, or change its categories"], ["failproofai self-report disable", "Turn it off: removes the MCP entries and stops recording"], ["failproofai self-report test --agent ", "Send one test report end to end"], - ["failproofai self-report sync [--quiet]", "Update each hooked agent's MCP entry (the daemon runs this)"], + ["failproofai self-report sync [--quiet]", "Update each hooked agent's failproofai_local MCP entry (the daemon runs this)"], ], options: [ ["--categories-file ", "JSON list of {name, description}; replaces the defaults"], diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index 61745354b..a79bfa16a 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -49,7 +49,7 @@ pub const DEFAULT_PORT: u16 = 4319; /// Overrides [`DEFAULT_PORT`]; read by the daemon at start. pub const PORT_ENV: &str = "FAILPROOFAI_SELF_REPORT_PORT"; /// MCP server name, as registered in each agent. -pub const SERVER_NAME: &str = "failproofai"; +pub const SERVER_NAME: &str = "failproofai_local"; /// The tool's name inside the MCP server. pub const TOOL_NAME: &str = "report"; /// The one thing a call ever returns. @@ -235,12 +235,29 @@ pub fn settings_path(home: &Path) -> PathBuf { home.join(SETTINGS_FILE) } -/// The file, or `None` when it is missing or does not parse. Readers that -/// decide whether the feature is on use [`effective_settings`], which tells -/// the two apart. +/// The file, or `None` when it is missing, does not parse, or is not +/// [`SETTINGS_VERSION`] (the CLI's `readEffectiveSelfReport` refuses any other +/// version too, so every transport agrees on such a file). Readers that decide +/// whether the feature is on use [`effective_settings`], which tells a missing +/// file from a broken one. pub fn read_settings(path: &Path) -> Option { let text = fs::read_to_string(path).ok()?; - serde_json::from_str(&text).ok() + parse_settings(&text) +} + +/// `self-report.json`'s text as [`Settings`], only in the supported version. +pub fn parse_settings(text: &str) -> Option { + serde_json::from_str::(text) + .ok() + .filter(|s| s.version == SETTINGS_VERSION) +} + +/// Whether a file that parsed may decide anything. A file this machine wrote +/// itself (`source` anything but `cloud`) does not while it is Cloud enrolled: +/// there the organization decides, so until the daemon writes the org's +/// setting the feature is off, exactly as with no file at all. +fn authoritative(settings: Settings, enrolled: &dyn Fn() -> bool) -> Option { + (settings.source == "cloud" || !enrolled()).then_some(settings) } /// Is this machine Cloud enrolled? Asked only when `self-report.json` is @@ -266,16 +283,18 @@ pub fn enrolment_check() -> EnrolmentCheck { /// The settings a reader acts on (CONTRACT §4), identical to the TypeScript /// `resolveSelfReport` in src/hooks/self-report.ts: /// -/// - the file, when it is there and parses; -/// - an unparsable or unreadable file: `None`, off (fail safe: a half-written -/// or hand-broken file must not turn recording on); +/// - the file, when it is there and parses as version [`SETTINGS_VERSION`], +/// except a local-source file on a Cloud-enrolled machine: `None`, off until +/// the daemon writes the organization's setting; +/// - an unparsable, unreadable or other-version file: `None`, off (fail safe: +/// a half-written or hand-broken file must not turn recording on); /// - a missing file on a Cloud-enrolled machine: `None`, off until the daemon /// writes it from the org's setting; /// - a missing file otherwise: on with the default categories, unless /// `config.json`'s `selfReport.enabled` is `false` (an explicit off wins). pub fn effective_settings(home: &Path, enrolled: &dyn Fn() -> bool) -> Option { match fs::read_to_string(settings_path(home)) { - Ok(text) => serde_json::from_str(&text).ok(), + Ok(text) => authoritative(parse_settings(&text)?, enrolled), Err(err) if err.kind() == io::ErrorKind::NotFound => missing_file_settings(home, enrolled), Err(_) => None, } @@ -482,15 +501,22 @@ impl SettingsCache { *state = None; return None; }; - if let Some((cached_mtime, cached_len, settings)) = state.as_ref() - && *cached_mtime == mtime - && *cached_len == len - { - return settings.clone(); - } - let settings = read_settings(&self.path); - *state = Some((mtime, len, settings.clone())); - settings + let settings = match state.as_ref() { + Some((cached_mtime, cached_len, settings)) + if *cached_mtime == mtime && *cached_len == len => + { + settings.clone() + } + _ => { + let settings = read_settings(&self.path); + *state = Some((mtime, len, settings.clone())); + settings + } + }; + drop(state); + // Asked on every call, not cached: an enrolment must take effect on + // the next request, even with the file unchanged. + authoritative(settings?, &*self.enrolled) } } @@ -1304,9 +1330,11 @@ mod tests { // Enrolled: a missing file is off until the daemon writes it. let cache = SettingsCache::new(&home, Arc::new(|| true)); assert!(cache.current().is_none()); - write_settings(&path, &enabled(default_categories(), None)).unwrap(); + let mut on = enabled(default_categories(), None); + on.source = "cloud".into(); + write_settings(&path, &on).unwrap(); assert!(cache.current().unwrap().enabled); - let mut off = enabled(default_categories(), None); + let mut off = on.clone(); off.enabled = false; off.guidance = Some("a longer file so the size changes too".into()); write_settings(&path, &off).unwrap(); @@ -1590,6 +1618,12 @@ mod tests { let home = temp_home("http-enabled"); let server = server_for(&home); let path = settings_path(&home); + // This server is enrolled, so the file that decides is the one the + // daemon writes from the org's setting. + let org = |mut s: Settings| { + s.source = "cloud".into(); + s + }; // Missing settings: answered, not recorded. let reply = call_report(&server, "copilot"); assert_eq!(reply["result"]["content"][0]["text"], RESULT_TEXT); @@ -1599,15 +1633,19 @@ mod tests { call_report(&server, "copilot"); assert_eq!(event_files(&home), 0, "malformed settings"); // Disabled. - let mut off = enabled(default_categories(), None); + let mut off = org(enabled(default_categories(), None)); off.enabled = false; write_settings(&path, &off).unwrap(); let reply = call_report(&server, "copilot"); assert_eq!(reply["result"]["isError"], false); assert_eq!(event_files(&home), 0, "disabled settings"); - // Enabled: one event. + // This machine's own file, on, while enrolled: not the org's, so off. write_settings(&path, &enabled(default_categories(), None)).unwrap(); call_report(&server, "copilot"); + assert_eq!(event_files(&home), 0, "local file while enrolled"); + // Enabled: one event. + write_settings(&path, &org(enabled(default_categories(), None))).unwrap(); + call_report(&server, "copilot"); assert_eq!(event_files(&home), 1, "enabled settings"); // Disabled again, with the cache primed by the enabled read: honoured // on the next call. @@ -1616,7 +1654,7 @@ mod tests { call_report(&server, "copilot"); assert_eq!(event_files(&home), 1, "disabled after enabled"); // A hook-recorded agent is never recorded here. - write_settings(&path, &enabled(default_categories(), None)).unwrap(); + write_settings(&path, &org(enabled(default_categories(), None))).unwrap(); call_report(&server, "claude"); assert_eq!(event_files(&home), 1, "claude is recorded by its hook"); let _ = fs::remove_dir_all(home); @@ -1834,6 +1872,73 @@ mod tests { .collect() } + /// The same on/off as the CLI's `resolveSelfReport` for every case in + /// settings-cases.golden.json, through the reader the record path uses + /// and through the cache behind `initialize` and `tools/list`. + #[test] + fn golden_settings_cases_agree_with_the_cli() { + let fixture: Value = serde_json::from_str(&golden("settings-cases.golden.json")).unwrap(); + for (i, case) in fixture["cases"].as_array().unwrap().iter().enumerate() { + let name = case["name"].as_str().unwrap(); + let home = temp_home(&format!("settings-case-{i}")); + let path = settings_path(&home); + if let Some(text) = case["text"].as_str() { + fs::write(&path, text).unwrap(); + } else if !case["file"].is_null() { + fs::write(&path, serde_json::to_string_pretty(&case["file"]).unwrap()).unwrap(); + } + let enrolled = case["enrolled"].as_bool().unwrap(); + let want = case["on"].as_bool().unwrap(); + let read = effective_settings(&home, &|| enrolled).is_some_and(|s| s.enabled); + assert_eq!(read, want, "effective_settings: {name}"); + let cache = SettingsCache::new(&home, Arc::new(move || enrolled)); + assert_eq!( + cache.current().is_some_and(|s| s.enabled), + want, + "cache: {name}" + ); + assert_eq!( + tool_definition(cache.current().as_ref()).is_some(), + want, + "tools/list: {name}" + ); + let _ = fs::remove_dir_all(home); + } + } + + /// Enrolling with a local file in place: the cache stops serving it on + /// the next call, with the file unchanged, and serves the org's file once + /// the daemon writes it. + #[test] + fn enrolling_ignores_a_local_file_until_the_org_setting_is_written() { + let home = temp_home("enrol-transition"); + let path = settings_path(&home); + write_settings(&path, &enabled(default_categories(), None)).unwrap(); + let flag = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let check = { + let flag = flag.clone(); + Arc::new(move || flag.load(std::sync::atomic::Ordering::SeqCst)) + }; + let cache = SettingsCache::new(&home, check); + assert!(cache.current().unwrap().enabled); + flag.store(true, std::sync::atomic::Ordering::SeqCst); + assert!( + cache.current().is_none(), + "enrolled: the local file no longer decides" + ); + assert!(effective_settings(&home, &|| true).is_none()); + let mut org = enabled(default_categories(), None); + org.source = "cloud".into(); + org.enabled = false; + org.guidance = Some("the org's own file, so the size changes".into()); + write_settings(&path, &org).unwrap(); + assert!(!cache.current().unwrap().enabled); + org.enabled = true; + write_settings(&path, &org).unwrap(); + assert!(cache.current().unwrap().enabled); + let _ = fs::remove_dir_all(home); + } + #[test] fn golden_truncation_counts_code_points() { let fixture: Value = serde_json::from_str(&golden("truncation.golden.json")).unwrap(); @@ -1959,7 +2064,7 @@ mod tests { "sessionId": "s1", "integration": "claude", "eventType": "PreToolUse", - "toolName": "mcp__failproofai__report", + "toolName": "mcp__failproofai_local__report", "decision": "allow", "toolCallId": "toolu_1", "selfReport": {"category": "looping", "detail": "again", "source": "mcp"} diff --git a/crates/fpai-collect/tests/hooks_source.rs b/crates/fpai-collect/tests/hooks_source.rs index c02d04383..87b54358e 100644 --- a/crates/fpai-collect/tests/hooks_source.rs +++ b/crates/fpai-collect/tests/hooks_source.rs @@ -858,7 +858,7 @@ fn self_report_row(ts: i64) -> String { "timestamp": ts, "eventType": "PreToolUse", "integration": "claude", - "toolName": "mcp__failproofai__report", + "toolName": "mcp__failproofai_local__report", "toolCallId": "toolu_01", "decision": "allow", "durationMs": 1, diff --git a/crates/fpai-collect/tests/self_report_mcp.rs b/crates/fpai-collect/tests/self_report_mcp.rs index ba669002f..b7460f874 100644 --- a/crates/fpai-collect/tests/self_report_mcp.rs +++ b/crates/fpai-collect/tests/self_report_mcp.rs @@ -145,7 +145,7 @@ async fn initialize_list_and_call_the_report_tool() { let reply = reply.unwrap(); assert_eq!(reply["id"], 1); assert_eq!(reply["result"]["protocolVersion"], "2025-06-18"); - assert_eq!(reply["result"]["serverInfo"]["name"], "failproofai"); + assert_eq!(reply["result"]["serverInfo"]["name"], "failproofai_local"); assert!(reply["result"]["capabilities"]["tools"].is_object()); // The instructions Claude Code puts in the system prompt (its tools are // deferred behind tool search, so the description alone is never seen). @@ -480,3 +480,43 @@ fn spawn_reports_whether_it_is_listening() { handle.join().unwrap(); fs::remove_dir_all(&home).ok(); } + +#[tokio::test(flavor = "multi_thread")] +async fn http_hides_the_tool_for_a_local_file_while_enrolled_and_for_another_version() { + let home = tmpdir("gate"); + // Enrolled, with this machine's own file on: the org decides, and it has + // not been written yet, so the HTTP server agrees with the CLI: off. + write_settings(&home, true, self_report::default_categories()); + let enrolled = Running::start_enrolled(&home, true).await; + assert_eq!( + list(&enrolled).await, + json!([]), + "enrolled, local file: off" + ); + enrolled.stop().await; + let open = Running::start(&home).await; + assert_eq!( + list(&open).await[0]["name"], + "report", + "not enrolled, local file: on" + ); + open.stop().await; + + // A complete enabled file in a version this build does not know: off, as + // the CLI's reader and the stdio server read it. + let path = self_report::settings_path(&home); + let mut raw: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap(); + raw["version"] = json!(2); + raw["source"] = json!("cloud"); + fs::write(&path, serde_json::to_string(&raw).unwrap()).unwrap(); + for enrolled in [false, true] { + let server = Running::start_enrolled(&home, enrolled).await; + assert_eq!( + list(&server).await, + json!([]), + "version 2, enrolled={enrolled}: off" + ); + server.stop().await; + } + fs::remove_dir_all(&home).ok(); +} diff --git a/docs/reference/mcp.mdx b/docs/reference/mcp.mdx index 65213e16c..72b49ed1a 100644 --- a/docs/reference/mcp.mdx +++ b/docs/reference/mcp.mdx @@ -15,7 +15,7 @@ https://gateway.befailproof.ai/mcp ``` - This page is about the **Cloud MCP gateway**, which lets you query Failproof AI Cloud from an AI tool. It is not the local `failproofai` MCP server that [Self Reports](#the-local-self-reports-server) adds to your agents. + This page is about the **Cloud MCP gateway**, which lets you query Failproof AI Cloud from an AI tool. It is not the local `failproofai_local` MCP server that [Self Reports](#the-local-self-reports-server) adds to your agents. ## Connect a client @@ -122,7 +122,7 @@ Results go to the AI tool you connected, and that tool's provider handles them u ## The local Self Reports server -[Self Reports](/self-reports) registers a different MCP server in your agents, also named `failproofai`. It runs on your machine, serves one tool, `report`, and needs no sign-in: +[Self Reports](/self-reports) registers a different MCP server in your agents, named `failproofai_local`. It runs on your machine, serves one tool, `report`, and needs no sign-in: | | Cloud MCP gateway | Local Self Reports server | | --- | --- | --- | @@ -131,7 +131,7 @@ Results go to the AI tool you connected, and that tool's provider handles them u | What it offers | Your organization's data, with your permissions | One `report` tool an agent calls when it is stuck | | Sign-in | OAuth, one organization per connection | None. It answers only on `127.0.0.1` and refuses requests from web pages | -Both use the name `failproofai`. If you added the gateway under that name in an agent failproofai hooks, failproofai leaves your entry alone and `failproofai self-report status` reports a conflict. To use both, rename the gateway entry, for example to `failproofai-cloud`, and run `failproofai self-report sync`. +The two have different names, so they coexist in the same agent: add the gateway as `failproofai` and failproofai adds `failproofai_local` beside it. failproofai never changes, removes or reports an entry named `failproofai`, and a call to one of the gateway's tools goes through your policies like any other tool call. ## Troubleshooting diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index f19ef9250..049627eeb 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -10,7 +10,7 @@ A report never unblocks the agent and never changes a decision. Afterwards the a ## On by default -Self Reports is on as soon as failproofai is installed. `failproofai policies --install` and `failproofai config` register the `failproofai` MCP server in every agent they install hooks for, and write `~/.failproofai/self-report.json` with the default categories so every reader sees the same settings. +Self Reports is on as soon as failproofai is installed. `failproofai policies --install` and `failproofai config` register the `failproofai_local` MCP server in every agent they install hooks for, and write `~/.failproofai/self-report.json` with the default categories so every reader sees the same settings. @@ -19,7 +19,7 @@ Self Reports is on as soon as failproofai is installed. `failproofai policies -- 1. Go to **settings → self reports**. 2. Keep it on, or switch it off. Keep the default categories or write your own, and optionally add guidance for the agents. - Every connected machine picks the change up on its next policy poll. `failproofaid` writes `~/.failproofai/self-report.json` from it and adds the `failproofai` MCP server to every agent that has failproofai hooks, or removes it when the switch is off. Until the first poll after connecting writes that file, the machine treats Self Reports as off. + Every connected machine picks the change up on its next policy poll. `failproofaid` writes `~/.failproofai/self-report.json` from it and adds the `failproofai_local` MCP server to every agent that has failproofai hooks, or removes it when the switch is off. Until the first poll after connecting writes that file, the machine treats Self Reports as off. On a Cloud-managed machine, `failproofai self-report enable` and `disable` refuse and point you to the dashboard. @@ -60,7 +60,7 @@ A report with a category that is not on the list is still recorded under the nam ## Agent support -failproofai registers one MCP server, named `failproofai`, in each agent's user-level MCP settings. For Claude Code and Codex, whose hooks record the report, the entry points at the daemon's local server, `http://127.0.0.1:4319/mcp` (set `FAILPROOFAI_SELF_REPORT_PORT` to move it), when `failproofaid` is serving it, and runs `failproofai mcp` over stdio otherwise. Every other agent always gets `failproofai mcp` over stdio, because its report is recorded by the server, which needs the agent's working directory to find the session (see below). Every entry is marked as failproofai's, so removing it never touches a server you added. +failproofai registers one MCP server, named `failproofai_local`, in each agent's user-level MCP settings. Agents see its tool as `mcp__failproofai_local__report` (Claude Code, Codex, Pi, Factory, Devin), `failproofai_local_report` (OpenCode), `mcp_failproofai_local_report` (Hermes, Antigravity) or `failproofai_local__report` (OpenClaw, Goose). The name is not `failproofai`, which is the name the [Cloud MCP gateway](/reference/mcp) is usually added under, so the two coexist. For Claude Code and Codex, whose hooks record the report, the entry points at the daemon's local server, `http://127.0.0.1:4319/mcp` (set `FAILPROOFAI_SELF_REPORT_PORT` to move it), when `failproofaid` is serving it, and runs `failproofai mcp` over stdio otherwise. Every other agent always gets `failproofai mcp` over stdio, because its report is recorded by the server, which needs the agent's working directory to find the session (see below). Every entry is marked as failproofai's, so removing it never touches a server you added. The transport is chosen when the entries are written, from a live check: the daemon behind this account's socket must answer, and the endpoint must answer as that same daemon (both carry the daemon's instance id). A port held by another daemon, for example another user's, or one whose own server could not bind the port, gives stdio. When the daemon starts, it re-runs `failproofai self-report sync`, so Claude Code and Codex move to HTTP. If the daemon stops, `failproofai self-report status` finds agents pointing at an endpoint that does not answer, or an agent the server records left on HTTP by an earlier version, and moves them to stdio. A running agent keeps the server it loaded at startup. @@ -87,11 +87,11 @@ These agents are registered over stdio for that reason: the MCP entry is per use | Antigravity | `~/.gemini/config/mcp_config.json` | MCP server | | Goose | `~/.config/goose/config.yaml` | MCP server | -If `cursor-agent mcp list` shows `failproofai` as "not loaded (needs approval)", run `cursor-agent mcp enable failproofai`. cursor-agent asks for approval of servers in a project's `.cursor/mcp.json`, so this happens, for example, when it runs with your home directory as the project. The approval is per project and per entry, so failproofai does not write it for you. The sync and `status` output say so for Cursor. +If `cursor-agent mcp list` shows `failproofai_local` as "not loaded (needs approval)", run `cursor-agent mcp enable failproofai_local`. cursor-agent asks for approval of servers in a project's `.cursor/mcp.json`, so this happens, for example, when it runs with your home directory as the project. The approval is per project and per entry, so failproofai does not write it for you. The sync and `status` output say so for Cursor. -On Antigravity, an MCP call can come through its `call_mcp_tool` wrapper. The hook lets that call through ahead of the policies only when the wrapper names server `failproofai` and tool `report`. A wrapped call to any other server goes through the policies as usual. +On Antigravity, an MCP call can come through its `call_mcp_tool` wrapper. The hook lets that call through ahead of the policies only when the wrapper names server `failproofai_local` and tool `report`. A wrapped call to any other server goes through the policies as usual. -`failproofai self-report status` shows whether the daemon's endpoint answers (`not running (agents use stdio)` when no daemon is set up here) and, per agent, whether the server is registered, over which transport, and whether that endpoint answers (HTTP) or the command can run (stdio). If an MCP server named `failproofai` that failproofai did not write is already there, such as the [Cloud MCP gateway](/reference/mcp) added under that name, it is left alone and reported as a conflict. +`failproofai self-report status` shows whether the daemon's endpoint answers (`not running (agents use stdio)` when no daemon is set up here) and, per agent, whether the server is registered, over which transport, and whether that endpoint answers (HTTP) or the command can run (stdio). If an MCP server named `failproofai_local` that failproofai did not write is already there, it is left alone and reported as a conflict. A server named `failproofai`, such as the [Cloud MCP gateway](/reference/mcp), is never touched or reported: it sits next to `failproofai_local`, and its tools go through your policies like any other server's. ## Containers diff --git a/sdk/python/README.md b/sdk/python/README.md index 6003c714c..6a3485ddb 100644 --- a/sdk/python/README.md +++ b/sdk/python/README.md @@ -135,7 +135,7 @@ failproofai_sdk.self_report("invalid_tool_or_credential", "The search API reject agent loop at all. - **Hiding it.** `failproofai_sdk.is_self_report_tool(name)` is true for `failproofai_report` and the coding-agent MCP spellings - (`mcp__failproofai__report`, `failproofai__report`, ...). + (`mcp__failproofai_local__report`, `failproofai_local__report`, ...). ## OpenTelemetry (opt in) diff --git a/sdk/python/failproofai_sdk/_self_report.py b/sdk/python/failproofai_sdk/_self_report.py index b7688313f..dab64a000 100644 --- a/sdk/python/failproofai_sdk/_self_report.py +++ b/sdk/python/failproofai_sdk/_self_report.py @@ -88,27 +88,29 @@ _MAX_GUIDANCE = 2000 #: Every spelling the report tool reaches a host under (case-insensitive, -#: exact): the SDK name (also OpenCode's), and the MCP tool `report` on server -#: `failproofai` as each agent prefixes it: Claude Code, Codex, Pi, Factory and -#: Devin `mcp__failproofai__report`, Factory's matcher form -#: `failproofai___report`, Hermes and Antigravity `mcp_failproofai_report`, -#: OpenClaw and Goose `failproofai__report`, Copilot CLI (likely, unverified) -#: `failproofai-report` / `failproofai/report`, plus other server-qualified forms. -#: The CLI and the TypeScript SDK test the same list against the repository's -#: test-fixtures/self-report/tool-names.golden.txt. +#: exact): the SDK name, and the MCP tool `report` on server +#: `failproofai_local` as each agent prefixes it: Claude Code, Codex, Pi, +#: Factory and Devin `mcp__failproofai_local__report`, Factory's matcher form +#: `failproofai_local___report`, OpenCode `failproofai_local_report`, Hermes +#: and Antigravity `mcp_failproofai_local_report`, OpenClaw and Goose +#: `failproofai_local__report`, Copilot CLI (likely, unverified) +#: `failproofai_local-report` / `failproofai_local/report`, plus other +#: server-qualified forms. The CLI and the TypeScript SDK test the same list +#: against the repository's test-fixtures/self-report/tool-names.golden.txt. TOOL_SPELLINGS: tuple[str, ...] = ( - "mcp__failproofai__report", - "failproofai___report", - "failproofai__report", + "mcp__failproofai_local__report", + "failproofai_local___report", + "failproofai_local__report", "failproofai_report", - "failproofai.report", - "failproofai/report", - "failproofai:report", - "mcp_failproofai_report", - "mcp__failproofai_report", - "mcp:failproofai:report", - "mcp:failproofai/report", - "failproofai-report", + "failproofai_local_report", + "failproofai_local.report", + "failproofai_local/report", + "failproofai_local:report", + "mcp_failproofai_local_report", + "mcp__failproofai_local_report", + "mcp:failproofai_local:report", + "mcp:failproofai_local/report", + "failproofai_local-report", ) _TOOL_NAMES = frozenset(TOOL_SPELLINGS) @@ -294,11 +296,12 @@ def is_self_report_tool(name: Any, server: Any = None) -> bool: """True for the report tool under any of its names. Use it to hide the call from your UI or transcript: `failproofai_report` - (this SDK), and the MCP tool as agents spell it (`mcp__failproofai__report`, - `mcp_failproofai_report`, `failproofai__report`, ...). `server` is for + (this SDK), and the MCP tool as agents spell it + (`mcp__failproofai_local__report`, `mcp_failproofai_local_report`, + `failproofai_local__report`, ...). `server` is for hosts that name an MCP tool and its server separately (Cursor's `tool_name` + `mcp_server_name`): a bare `report` matches only when the - server is `failproofai`. + server is `failproofai_local`. """ if not isinstance(name, str): return False @@ -307,7 +310,7 @@ def is_self_report_tool(name: Any, server: Any = None) -> bool: return True return ( isinstance(server, str) - and server.strip().lower() == "failproofai" + and server.strip().lower() == "failproofai_local" and lower in ("report", "mcp:report") ) diff --git a/sdk/python/tests/test_self_report.py b/sdk/python/tests/test_self_report.py index efae2746f..beb133e4c 100644 --- a/sdk/python/tests/test_self_report.py +++ b/sdk/python/tests/test_self_report.py @@ -435,11 +435,11 @@ def test_anthropic_tool_shape(home): "name", [ "failproofai_report", - "mcp__failproofai__report", - "failproofai__report", - "failproofai.report", - "failproofai/report", - "failproofai-report", + "mcp__failproofai_local__report", + "failproofai_local__report", + "failproofai_local.report", + "failproofai_local/report", + "failproofai_local-report", ], ) def test_is_self_report_tool_accepts_every_spelling(name): @@ -466,7 +466,7 @@ def test_handle_tool_call_with_a_json_string(recorded): def test_handle_tool_call_with_a_dict_and_explicit_identity(recorded): out = fp.handle_tool_call( - "mcp__failproofai__report", {"category": "x", "detail": "y"}, session_id="s", agent_id="a" + "mcp__failproofai_local__report", {"category": "x", "detail": "y"}, session_id="s", agent_id="a" ) assert out == "Recorded." assert (recorded[0]["session_id"], recorded[0]["agent_id"]) == ("s", "a") diff --git a/sdk/python/tests/test_self_report_golden.py b/sdk/python/tests/test_self_report_golden.py index 8ab64d3e5..38d11c6a2 100644 --- a/sdk/python/tests/test_self_report_golden.py +++ b/sdk/python/tests/test_self_report_golden.py @@ -64,10 +64,14 @@ def test_tool_names(): for name in lines("tool-names.golden.txt"): assert fp.is_self_report_tool(name), name assert fp.is_self_report_tool(name.upper()), name - assert fp.is_self_report_tool("report", "failproofai") - assert fp.is_self_report_tool("MCP:report", "failproofai") + assert fp.is_self_report_tool("report", "failproofai_local") + assert fp.is_self_report_tool("MCP:report", "failproofai_local") assert not fp.is_self_report_tool("report", "linear") assert not fp.is_self_report_tool("MCP:report") + # The Cloud gateway's server is `failproofai`: its tools are never ours. + assert not fp.is_self_report_tool("report", "failproofai") + for name in ("mcp__failproofai__report", "failproofai__report", "mcp_failproofai_report", "failproofai-report"): + assert not fp.is_self_report_tool(name), name def test_event_field_order(): diff --git a/sdk/typescript/src/self-report-spec.ts b/sdk/typescript/src/self-report-spec.ts index cd7cc165d..f4f5983f6 100644 --- a/sdk/typescript/src/self-report-spec.ts +++ b/sdk/typescript/src/self-report-spec.ts @@ -161,29 +161,32 @@ export function toAnthropicTool(spec: SelfReportSpec): AnthropicTool { /** * Every spelling an agent gives the report tool (case-insensitive, exact): - * `failproofai_report` (the SDKs, OpenCode), `mcp__failproofai__report` - * (Claude Code, Codex, Pi, Factory, Devin), `failproofai___report` (Factory's - * matcher form), `mcp_failproofai_report` (Hermes, Antigravity), - * `failproofai__report` (OpenClaw, Goose), `failproofai-report` (Copilot CLI, - * likely), and other server-qualified forms. + * `failproofai_report` (the SDKs), and the MCP tool `report` on server + * `failproofai_local`: `mcp__failproofai_local__report` (Claude Code, Codex, + * Pi, Factory, Devin), `failproofai_local___report` (Factory's matcher form), + * `failproofai_local_report` (OpenCode), `mcp_failproofai_local_report` + * (Hermes, Antigravity), `failproofai_local__report` (OpenClaw, Goose), + * `failproofai_local-report` (Copilot CLI, likely), and other + * server-qualified forms. * * Mirrors `isSelfReportToolName` in the CLI's `src/hooks/self-report-names.ts`; * this package cannot import that, so both are tested against the same golden * list (`test-fixtures/self-report/tool-names.golden.txt` in the repo). */ export const SELF_REPORT_TOOL_SPELLINGS: ReadonlyArray = Object.freeze([ - "mcp__failproofai__report", - "failproofai___report", - "failproofai__report", + "mcp__failproofai_local__report", + "failproofai_local___report", + "failproofai_local__report", "failproofai_report", - "failproofai.report", - "failproofai/report", - "failproofai:report", - "mcp_failproofai_report", - "mcp__failproofai_report", - "mcp:failproofai:report", - "mcp:failproofai/report", - "failproofai-report", + "failproofai_local_report", + "failproofai_local.report", + "failproofai_local/report", + "failproofai_local:report", + "mcp_failproofai_local_report", + "mcp__failproofai_local_report", + "mcp:failproofai_local:report", + "mcp:failproofai_local/report", + "failproofai_local-report", ]); const SPELLINGS = new Set(SELF_REPORT_TOOL_SPELLINGS); @@ -191,14 +194,14 @@ const SPELLINGS = new Set(SELF_REPORT_TOOL_SPELLINGS); /** * Whether a tool is the report tool. `server` is for hosts that name an MCP * tool and its server separately (Cursor's `tool_name` + `mcp_server_name`): - * a bare `report` matches only when the server is `failproofai`. + * a bare `report` matches only when the server is `failproofai_local`. */ export function isSelfReportTool(name: unknown, server?: unknown): boolean { if (typeof name !== "string") return false; const lower = name.toLowerCase(); if (SPELLINGS.has(lower)) return true; return ( - typeof server === "string" && server.toLowerCase() === "failproofai" && (lower === "report" || lower === "mcp:report") + typeof server === "string" && server.toLowerCase() === "failproofai_local" && (lower === "report" || lower === "mcp:report") ); } diff --git a/sdk/typescript/test/self-report-golden.test.ts b/sdk/typescript/test/self-report-golden.test.ts index e5798c17e..d77f20980 100644 --- a/sdk/typescript/test/self-report-golden.test.ts +++ b/sdk/typescript/test/self-report-golden.test.ts @@ -60,9 +60,14 @@ describe("Self Reports golden files (TypeScript SDK)", () => { for (const name of lines("tool-names.golden.txt")) expect(isSelfReportTool(name), name).toBe(true); expect(isSelfReportTool("report")).toBe(false); expect(isSelfReportTool("MCP:report")).toBe(false); - expect(isSelfReportTool("report", "failproofai")).toBe(true); - expect(isSelfReportTool("MCP:report", "failproofai")).toBe(true); + expect(isSelfReportTool("report", "failproofai_local")).toBe(true); + expect(isSelfReportTool("MCP:report", "failproofai_local")).toBe(true); expect(isSelfReportTool("report", "linear")).toBe(false); + // The Cloud gateway's server is `failproofai`: its tools are never ours. + expect(isSelfReportTool("report", "failproofai")).toBe(false); + for (const name of ["mcp__failproofai__report", "failproofai__report", "mcp_failproofai_report", "failproofai-report"]) { + expect(isSelfReportTool(name), name).toBe(false); + } }); it("writes the golden event fields in wire order", () => { diff --git a/sdk/typescript/test/self-report.test.ts b/sdk/typescript/test/self-report.test.ts index 5540b7474..0306bb7a8 100644 --- a/sdk/typescript/test/self-report.test.ts +++ b/sdk/typescript/test/self-report.test.ts @@ -436,10 +436,10 @@ describe("the raw tool helpers", () => { it.each([ ["failproofai_report", true], - ["mcp__failproofai__report", true], - ["failproofai__report", true], - ["failproofai.report", true], - ["failproofai/report", true], + ["mcp__failproofai_local__report", true], + ["failproofai_local__report", true], + ["failproofai_local.report", true], + ["failproofai_local/report", true], ["report", false], ["failproofai_report_x", false], ["mcp__other__report", false], @@ -477,7 +477,7 @@ describe("the raw tool helpers", () => { it("never throws: unreadable arguments are recorded empty, a bad field is logged", async () => { const warn = quietLogger(); await session({ sessionId: "s1" }, () => { - expect(failproofai.handleToolCall("mcp__failproofai__report", "{oops")).toBe("Recorded."); + expect(failproofai.handleToolCall("mcp__failproofai_local__report", "{oops")).toBe("Recorded."); expect(failproofai.handleToolCall("failproofai_report", { category: "looping" }, { timestamp: "x" })).toBe( "Recorded.", ); diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index aab80588d..668afd2c3 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -809,19 +809,19 @@ export async function evaluateHookEvent( // Cursor's MCP hook names our tool `report` and the server separately; // file it under the one name before anything else reads the tool name. // Cursor's preToolUse names one `MCP:report` with no server; only a payload - // that also names the server (`mcp_server_name: "failproofai"`) is ours. + // that also names the server (`mcp_server_name: "failproofai_local"`) is ours. // // For Cursor that server check is the ONLY way a call becomes ours: a // payload naming another server (or none) keeps its own tool name even // when that name is one of our qualified spellings, and never reaches the // short-circuit below. Otherwise another server's tool could be named - // `mcp__failproofai__report` and skip every policy. + // `mcp__failproofai_local__report` and skip every policy. const cursorSelfReport = cli === "cursor" && isSelfReportCursorCall(parsed); if (cursorSelfReport) { parsed.tool_name = SELF_REPORT_MCP_TOOL_NAME; } // Antigravity's lazy MCP path wraps the call in `call_mcp_tool`; unwrap it - // only when the wrapper names server `failproofai` and tool `report`. + // only when the wrapper names server `failproofai_local` and tool `report`. if (cli === "antigravity") { const wrapped = selfReportAntigravityWrappedArgs(parsed.tool_name, parsed.tool_input); if (wrapped) { diff --git a/src/hooks/hook-activity-store.ts b/src/hooks/hook-activity-store.ts index a5f34b60c..b640a495c 100644 --- a/src/hooks/hook-activity-store.ts +++ b/src/hooks/hook-activity-store.ts @@ -183,7 +183,7 @@ export interface HookActivityEntry { reason: string | null; }>; /** - * Set only on a call to the Self Reports tool (`mcp__failproofai__report` and + * Set only on a call to the Self Reports tool (`mcp__failproofai_local__report` and * its per-agent spellings): what the agent reported. Such a row was allowed * before any policy ran and was never evaluated, so its decision is always * `allow` and it names no policy. The collector turns it into a diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts index 23d1ad31b..4cd1cf469 100644 --- a/src/hooks/self-report-cli.ts +++ b/src/hooks/self-report-cli.ts @@ -10,13 +10,15 @@ */ import { spawn } from "node:child_process"; import { readdirSync, readFileSync } from "node:fs"; -import { join } from "node:path"; +import { basename, dirname, join } from "node:path"; import { customAgentsEventsDir, hookActivityDir } from "./fp-home"; import { SELF_REPORT_DEFAULT_CATEGORIES, SELF_REPORT_MCP_TOOL_NAME, SELF_REPORT_RESULT_TEXT, + SELF_REPORT_SERVER_NAME, SELF_REPORT_SERVER_RECORDS, + SELF_REPORT_TOOL_NAME, readEffectiveSelfReport, readLocalSelfReportConfig, resolveSelfReport, @@ -31,6 +33,7 @@ import { } from "./self-report"; import { INTEGRATION_TYPES } from "./types"; import { daemonSocketPresent, isDaemonConfigured } from "./daemon-client"; +import { SELF_REPORT_RECEIPT_ENV, SELF_REPORT_RECEIPT_PREFIX } from "./self-report-mcp"; import { SELF_REPORT_CURSOR_APPROVAL_HINT, probeSelfReportHttp, @@ -82,10 +85,11 @@ function selfReportRunChild( stdin: string, timeoutMs: number, cwd?: string, + extraEnv: Record = {}, ): Promise<{ code: number | null; stdout: string; stderr: string }> { return new Promise((resolveRun) => { const [cmd, ...rest] = argv; - const child = spawn(cmd, rest, { cwd, stdio: ["pipe", "pipe", "pipe"], env: process.env }); + const child = spawn(cmd, rest, { cwd, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...extraEnv } }); let stdout = ""; let stderr = ""; const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs); @@ -157,7 +161,7 @@ function selfReportRegistrationLines( ...hooked.map((r) => { let state: string; if (r.error) state = `unreadable (${r.error})`; - else if (r.conflict) state = "another failproofai MCP server is configured; left alone"; + else if (r.conflict) state = `another "${SELF_REPORT_SERVER_NAME}" MCP server is configured; left alone`; else if (r.registered && r.transport === "http") { const port = selfReportUrlPort(r.endpoint); const ok = port !== null && health.get(port) === true; @@ -198,8 +202,12 @@ async function selfReportStatus(deps: SelfReportCliDeps): Promise c.name).join(", ")}`); + lines.push(`MCP server: ${SELF_REPORT_SERVER_NAME} (tool \`${SELF_REPORT_TOOL_NAME}\`)`); if (settings.guidance) lines.push(`Guidance: ${settings.guidance.length > 60 ? `${settings.guidance.slice(0, 57)}...` : settings.guidance}`); const readRows = deps.registrations ?? (() => selfReportRegistrationStatus()); let rows = readRows(); @@ -378,7 +387,6 @@ async function selfReportTest(args: string[], deps: SelfReportCliDeps): Promise< // This agent's hooks do not see MCP calls: the MCP server records. Drive // the stdio server exactly as the agent would. const dir = customAgentsEventsDir(); - const before = new Set(selfReportListDir(dir)); const stdin = [ { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "failproofai-self-report-test", version: "1" } } }, { jsonrpc: "2.0", method: "notifications/initialized" }, @@ -386,32 +394,39 @@ async function selfReportTest(args: string[], deps: SelfReportCliDeps): Promise< ] .map((m) => JSON.stringify(m)) .join("\n"); - const run = await selfReportRunChild([...cli, "mcp", "--agent", agent], `${stdin}\n`, 20_000, cwd); - const answered = run.stdout.includes(SELF_REPORT_RESULT_TEXT); - const landed = selfReportListDir(dir).filter((f) => !before.has(f) && f.endsWith(".jsonl")); - const hit = landed.find((f) => { - try { - return readFileSync(join(dir, f), "utf8").includes(SELF_REPORT_TEST_DETAIL); - } catch { - return false; - } + const run = await selfReportRunChild([...cli, "mcp", "--agent", agent], `${stdin}\n`, 20_000, cwd, { + [SELF_REPORT_RECEIPT_ENV]: "1", }); - if (!answered || !hit) { + const answered = run.stdout.includes(SELF_REPORT_RESULT_TEXT); + // The server's receipt names the batch it published. The batch itself may + // already be gone: a running collector uploads and deletes it, often + // before this child has exited, so its absence proves nothing. + const receipt = run.stderr + .split("\n") + .filter((l) => l.startsWith(SELF_REPORT_RECEIPT_PREFIX)) + .map((l) => l.slice(SELF_REPORT_RECEIPT_PREFIX.length).trim()) + .find((p) => dirname(p) === dir && p.endsWith(".jsonl")); + if (!answered || !receipt) { + const diagnostic = run.stderr + .split("\n") + .filter((l) => l.trim() && !l.startsWith(SELF_REPORT_RECEIPT_PREFIX)) + .pop(); return { exitCode: 1, lines: [ `✕ The test report for ${agent} did not land.`, - ` MCP server ${answered ? "answered Recorded." : "did not answer"}${run.stderr.trim() ? `: ${run.stderr.trim().split("\n").pop()}` : ""}`, + ` MCP server ${answered ? "answered Recorded., but recorded nothing" : "did not answer"}${diagnostic ? `: ${diagnostic.trim()}` : ""}`, ], }; } - // Possibly consumed by a running collector between write and read; the - // name is what we report. + const stillThere = selfReportListDir(dir).includes(basename(receipt)); return { exitCode: 0, lines: [ `✓ Test report from ${agent} recorded by the MCP server.`, - ` Event file: ${join(dir, hit)}`, + stillThere + ? ` Event file: ${receipt}` + : ` Event file: ${receipt} (already picked up by the collector)`, " The collector uploads it to FailproofAI Cloud when this machine is connected.", ], }; diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index de58c749b..e54c7c42e 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -2,7 +2,9 @@ * Self Reports: register failproofai's `report` MCP server in every agent that * has failproofai hooks, and take it out again. * - * The server is named `failproofai` everywhere (CONTRACT §1). Which transport + * The server is named `failproofai_local` everywhere (CONTRACT §1), so it + * never clashes with the FailproofAI Cloud gateway MCP server, which users + * register as `failproofai`; the two coexist. Which transport * an agent gets depends on who records its reports (CONTRACT §7, §8): * * - Hook-recorded agents (claude, codex: not in `SELF_REPORT_SERVER_RECORDS`) @@ -24,23 +26,23 @@ * * Sources are each agent's current official docs (and source where the docs * are silent). "Hook sees MCP" is whether the hook failproofai installs fires - * for an MCP tool call, and the name it carries for server `failproofai`, + * for an MCP tool call, and the name it carries for server `failproofai_local`, * tool `report`. * * | Agent | File (profile/env) | Key | HTTP entry | stdio entry | Hook sees MCP / name | * |-------------|------------------------------------------------------|----------------------------|----------------------------------------------|-------------------------------------|----------------------| - * | claude | `$CLAUDE_CONFIG_DIR/.claude.json`, else `~/.claude.json` | `mcpServers` | `{type:"http", url}` | `{type:"stdio", command, args}` | yes, PreToolUse `mcp__failproofai__report` | - * | codex | `$CODEX_HOME/config.toml` (TOML) | `[mcp_servers.failproofai]`| `url = "…"` | `command`, `args` | yes, PreToolUse `mcp__failproofai__report` | - * | copilot | `$COPILOT_HOME/mcp-config.json`, else `~/.copilot/` | `mcpServers` | `{type:"http", url, tools:["*"]}` | `{type:"local", command, args, tools:["*"]}` | not documented; likely `failproofai-report` (exempt, with `failproofai/report`) | + * | claude | `$CLAUDE_CONFIG_DIR/.claude.json`, else `~/.claude.json` | `mcpServers` | `{type:"http", url}` | `{type:"stdio", command, args}` | yes, PreToolUse `mcp__failproofai_local__report` | + * | codex | `$CODEX_HOME/config.toml` (TOML) | `[mcp_servers.failproofai_local]`| `url = "…"` | `command`, `args` | yes, PreToolUse `mcp__failproofai_local__report` | + * | copilot | `$COPILOT_HOME/mcp-config.json`, else `~/.copilot/` | `mcpServers` | `{type:"http", url, tools:["*"]}` | `{type:"local", command, args, tools:["*"]}` | not documented; likely `failproofai_local-report` (exempt, with `failproofai_local/report`) | * | cursor | `~/.cursor/mcp.json` (editor and cursor-agent) | `mcpServers` | `{url}` | `{type:"stdio", command, args}` | `beforeMCPExecution` (tool_name `report` + mcp_server_name; not installed) and preToolUse `MCP:report` with no server, so the server records | - * | opencode | `~/.config/opencode/opencode.json` (as the hooks) | v1 `mcp.`; v2 `mcp.servers.` | `{type:"remote", url, enabled:true}` (v2: no `enabled`) | `{type:"local", command:[…]}` | yes, plugin `tool.execute.before` `failproofai_report` | - * | pi | `$PI_CODING_AGENT_DIR/mcp.json`, else `~/.pi/agent/` | `mcpServers` | `{url, exposure:"direct"}` | `{command, args, exposure:"direct"}` | yes per docs, `tool_call` `mcp__failproofai__report` | - * | hermes | every profile's `config.yaml` (YAML, HERMES_HOME) | `mcp_servers` | `{url}` | `{command, args}` | yes per source, `pre_tool_call` `mcp_failproofai_report` | - * | openclaw | every profile's `openclaw.json` | `mcp.servers` | `{url, transport:"streamable-http"}` | `{command, args}` | likely (source only), `before_tool_call` `failproofai__report` | - * | factory | `~/.factory/mcp.json` | `mcpServers` | `{type:"http", url}` | `{type:"stdio", command, args}` | yes, `mcp__failproofai__report` (regex sees `failproofai___report`) | - * | devin | `~/.config/devin/mcp_config.json` | `mcpServers` | `{url, transport:"http"}` | `{command, args}` | yes, `mcp__failproofai__report` | - * | antigravity | `~/.gemini/config/mcp_config.json` | `mcpServers` | `{serverUrl}` | `{command, args}` | not documented; eager tools `mcp_failproofai_report`, lazy (default) via `call_mcp_tool` | - * | goose | `$GOOSE_PATH_ROOT/config/config.yaml`, else `~/.config/goose/config.yaml` (YAML) | `extensions` | `{type:"streamable_http", name, enabled, uri, …}` | `{type:"stdio", name, enabled, cmd, args, …}` | not documented; would be `failproofai__report` | + * | opencode | `~/.config/opencode/opencode.json` (as the hooks) | v1 `mcp.`; v2 `mcp.servers.` | `{type:"remote", url, enabled:true}` (v2: no `enabled`) | `{type:"local", command:[…]}` | yes, plugin `tool.execute.before` `failproofai_local_report` | + * | pi | `$PI_CODING_AGENT_DIR/mcp.json`, else `~/.pi/agent/` | `mcpServers` | `{url, exposure:"direct"}` | `{command, args, exposure:"direct"}` | yes per docs, `tool_call` `mcp__failproofai_local__report` | + * | hermes | every profile's `config.yaml` (YAML, HERMES_HOME) | `mcp_servers` | `{url}` | `{command, args}` | yes per source, `pre_tool_call` `mcp_failproofai_local_report` | + * | openclaw | every profile's `openclaw.json` | `mcp.servers` | `{url, transport:"streamable-http"}` | `{command, args}` | likely (source only), `before_tool_call` `failproofai_local__report` | + * | factory | `~/.factory/mcp.json` | `mcpServers` | `{type:"http", url}` | `{type:"stdio", command, args}` | yes, `mcp__failproofai_local__report` (regex sees `failproofai_local___report`) | + * | devin | `~/.config/devin/mcp_config.json` | `mcpServers` | `{url, transport:"http"}` | `{command, args}` | yes, `mcp__failproofai_local__report` | + * | antigravity | `~/.gemini/config/mcp_config.json` | `mcpServers` | `{serverUrl}` | `{command, args}` | not documented; eager tools `mcp_failproofai_local_report`, lazy (default) via `call_mcp_tool` | + * | goose | `$GOOSE_PATH_ROOT/config/config.yaml`, else `~/.config/goose/config.yaml` (YAML) | `extensions` | `{type:"streamable_http", name, enabled, uri, …}` | `{type:"stdio", name, enabled, cmd, args, …}` | not documented; would be `failproofai_local__report` | * * Cursor approval (cursor-agent 2026.11): servers from a *project* * `.cursor/mcp.json` load only once approved; approvals live per project root @@ -49,7 +51,7 @@ * when cursor-agent runs with the home directory as its project, where it is * also the project file. That key changes with every project and transport, so * failproofai writes no approval; sync and status point at - * `cursor-agent mcp enable failproofai` instead. + * `cursor-agent mcp enable failproofai_local` instead. * * Deferred tools: Pi's entry sets `exposure: "direct"` (its default `codemode` * shows the model only the server's name). Hermes (`tools.tool_search`) and @@ -65,14 +67,15 @@ * * ## Ownership * - * An entry is ours when it is named `failproofai` AND has our shape: a URL + * An entry is ours when it is named `failproofai_local` AND has our shape: a URL * `http://127.0.0.1:/mcp?agent=`, or a command whose file name * contains `failproofai` run with `mcp --agent `. That shape is the marker: * the JSON agents validate their server schema and an extra marker key could * make one reject the whole file. Codex's entry also sits between two marker - * comments; Hermes' and Goose's carry a marker comment. A `failproofai` entry of - * any other shape (for example the Cloud MCP gateway) is the user's: it is never - * changed and is reported as a conflict. + * comments; Hermes' and Goose's carry a marker comment. A `failproofai_local` + * entry of any other shape is the user's: it is never changed and is reported + * as a conflict. An entry named `failproofai` (the Cloud MCP gateway, or + * anything else) is not ours by name and is never read, changed or reported. */ import { accessSync, constants as fsConstants, existsSync, readFileSync, realpathSync } from "node:fs"; import { execSync } from "node:child_process"; @@ -614,7 +617,7 @@ export type SelfReportMcpStatus = | "ok" /** Enabled, but this agent has no failproofai hooks; nothing written. */ | "not-hooked" - /** A `failproofai` server that is not ours is there; left alone. */ + /** A `failproofai_local` server that is not ours is there; left alone. */ | "conflict" /** The file could not be read or written; left as it was. */ | "error" @@ -686,7 +689,7 @@ function defaultHooksInstalled(agent: IntegrationType): boolean { } /** - * Add (enabled) or remove (disabled) our `failproofai` MCP server in every + * Add (enabled) or remove (disabled) our `failproofai_local` MCP server in every * agent. Enabled: only agents with failproofai hooks get it, and agents without * hooks are left as they are; HTTP for a hook-recorded agent when this home's * daemon is serving the port right now (see `selfReportDaemonLive`), stdio @@ -852,7 +855,7 @@ function errText(err: unknown): string { /** What to do when cursor-agent has not loaded the server yet. */ export const SELF_REPORT_CURSOR_APPROVAL_HINT = - "cursor-agent: if `cursor-agent mcp list` shows failproofai as needing approval, run `cursor-agent mcp enable failproofai`"; + "cursor-agent: if `cursor-agent mcp list` shows failproofai_local as needing approval, run `cursor-agent mcp enable failproofai_local`"; /** One line per change, conflict or error; nothing for an agent left as it was. */ export function selfReportSyncLines(results: readonly SelfReportMcpResult[]): string[] { @@ -891,7 +894,7 @@ export interface SelfReportRegistration { transport: "http" | "stdio" | null; /** The URL (http) or command (stdio) our entry points at. */ endpoint: string | null; - /** A `failproofai` server that is not ours is there. */ + /** A `failproofai_local` server that is not ours is there. */ conflict: boolean; /** The file could not be read. */ error?: string; diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts index 5f39cae3b..c3e64afc7 100644 --- a/src/hooks/self-report-mcp.ts +++ b/src/hooks/self-report-mcp.ts @@ -42,6 +42,15 @@ import { selfReportInstructions, } from "./self-report"; +/** + * Set to `1` in the server's environment (by `self-report test`), it writes one + * receipt line to stderr for each report it published, naming the batch file: + * `[failproofai mcp] recorded: `. The file itself is no proof: a running + * collector can upload and delete it before anyone looks. + */ +export const SELF_REPORT_RECEIPT_ENV = "FAILPROOFAI_SELF_REPORT_RECEIPT"; +export const SELF_REPORT_RECEIPT_PREFIX = "[failproofai mcp] recorded: "; + /** How far back a hook-activity session may be and still own a report. */ export const SELF_REPORT_SESSION_WINDOW_MS = 6 * 60 * 60 * 1000; const SELF_REPORT_DEFAULT_PROTOCOL = "2025-06-18"; @@ -300,13 +309,14 @@ export async function handleSelfReportRpc( if (agent && SELF_REPORT_SERVER_RECORDS.includes(agent) && readEnabledSelfReport()) { const { category, detail } = selfReportArgs(params.arguments ?? {}); try { - await writeSelfReportEvent({ + const { path } = await writeSelfReportEvent({ integration: agent, category, detail, cwd: opts.cwd ?? process.cwd(), now: opts.now?.(), }); + if (process.env[SELF_REPORT_RECEIPT_ENV] === "1") process.stderr.write(`${SELF_REPORT_RECEIPT_PREFIX}${path}\n`); } catch (err) { // The agent still hears "Recorded.": a report changes no decision, // and an error here would only make it retry. diff --git a/src/hooks/self-report-names.ts b/src/hooks/self-report-names.ts index 9df4db3f9..a770086a2 100644 --- a/src/hooks/self-report-names.ts +++ b/src/hooks/self-report-names.ts @@ -11,12 +11,16 @@ * Re-exported from self-report.ts; import from there everywhere else. */ -/** MCP server name every installer registers. */ -export const SELF_REPORT_SERVER_NAME = "failproofai"; +/** + * MCP server name every installer registers. Not `failproofai`: that is the name + * users give the FailproofAI Cloud gateway MCP server, and the two coexist. An + * underscore, not a hyphen, because some agents rewrite hyphens in tool names. + */ +export const SELF_REPORT_SERVER_NAME = "failproofai_local"; /** The MCP tool's own name. */ export const SELF_REPORT_TOOL_NAME = "report"; /** How Claude Code and Codex spell it: `mcp____`. */ -export const SELF_REPORT_MCP_TOOL_NAME = "mcp__failproofai__report"; +export const SELF_REPORT_MCP_TOOL_NAME = "mcp__failproofai_local__report"; /** The SDK tool's name. */ export const SELF_REPORT_SDK_TOOL_NAME = "failproofai_report"; /** Detail is truncated to this many characters (contract §3). */ @@ -52,36 +56,38 @@ export function selfReportClip(text: string, max: number = SELF_REPORT_DETAIL_MA * one thing that skips them all. * * Per agent (installer research, 2026-11-25; see self-report-install.ts): - * - `mcp__failproofai__report`: Claude Code, Codex, Pi, Factory, Devin. - * - `failproofai___report`: Factory's matcher-regex form of the same name. - * - `mcp_failproofai_report`: Hermes, and Antigravity's eager tools. - * - `failproofai_report`: OpenCode (and the SDK tool). - * - `failproofai__report`: OpenClaw and Goose (`__`). + * - `mcp__failproofai_local__report`: Claude Code, Codex, Pi, Factory, Devin. + * - `failproofai_local___report`: Factory's matcher-regex form of the same name. + * - `mcp_failproofai_local_report`: Hermes, and Antigravity's eager tools. + * - `failproofai_local_report`: OpenCode (`_`). + * - `failproofai_report`: the SDK tool. + * - `failproofai_local__report`: OpenClaw and Goose (`__`). * - Cursor: see `isSelfReportCursorCall`; its preToolUse name `MCP:report` * carries no server, so it is never matched by name alone. * - Antigravity's lazy path, `call_mcp_tool`: see * `selfReportAntigravityWrappedArgs`; matched only on its server and tool. - * - `failproofai-report` (`-`) and `failproofai/report`: Copilot + * - `failproofai_local-report` (`-`) and `failproofai_local/report`: Copilot * CLI's likely forms. Its hook spelling of an MCP tool is not documented and * could not be observed without a signed-in run, so both are exempt. - * - `failproofai.report`, `failproofai/report`, `failproofai:report`, - * `mcp__failproofai_report`, `mcp:failproofai:report`, - * `mcp:failproofai/report`: other server-qualified forms, kept so a + * - `failproofai_local.report`, `failproofai_local/report`, `failproofai_local:report`, + * `mcp__failproofai_local_report`, `mcp:failproofai_local:report`, + * `mcp:failproofai_local/report`: other server-qualified forms, kept so a * spelling change in an agent cannot route a report through the policies. */ const SELF_REPORT_TOOL_SPELLINGS: ReadonlySet = new Set([ SELF_REPORT_MCP_TOOL_NAME, - "failproofai___report", - "failproofai__report", + "failproofai_local___report", + "failproofai_local__report", SELF_REPORT_SDK_TOOL_NAME, - "failproofai.report", - "failproofai/report", - "failproofai:report", - "mcp_failproofai_report", - "mcp__failproofai_report", - "mcp:failproofai:report", - "mcp:failproofai/report", - "failproofai-report", + "failproofai_local_report", + "failproofai_local.report", + "failproofai_local/report", + "failproofai_local:report", + "mcp_failproofai_local_report", + "mcp__failproofai_local_report", + "mcp:failproofai_local:report", + "mcp:failproofai_local/report", + "failproofai_local-report", ]); /** True for the report tool under any agent's spelling of it (contract §1). */ @@ -109,7 +115,7 @@ export function isSelfReportCursorCall(payload: unknown): boolean { * `call_mcp_tool` wrapper with `{ServerName, ToolName, Arguments}` (agy 1.5's * own description says to judge it by ServerName + ToolName). Returns the * wrapped call's arguments when, and only when, the wrapper names server - * `failproofai` and tool `report`; `undefined` for any other server or tool, + * `failproofai_local` and tool `report`; `undefined` for any other server or tool, * whose calls keep going through the policies. */ export function selfReportAntigravityWrappedArgs(toolName: unknown, toolInput: unknown): { args: unknown } | undefined { diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts index 33c4c2659..7c7fd0101 100644 --- a/src/hooks/self-report.ts +++ b/src/hooks/self-report.ts @@ -332,8 +332,10 @@ export function readEffectiveSelfReport(path: string = selfReportSettingsFile()) * default. Identical to the daemon's `effective_settings` * (crates/fpai-collect/src/self_report.rs): * - * - the file, when it is there and parses; - * - an unparsable file: `null`, off (fail safe: a half-written or hand-broken + * - the file, when it is there and parses, except a local-source file on a + * Cloud-enrolled machine: `null`, off until the daemon writes the org's + * setting (enrolling must not leave this machine's own switch in charge); + * - an unparsable file, or one in another version: `null`, off (fail safe: a half-written or hand-broken * file must not turn recording on); * - a missing file on a Cloud-enrolled machine: `null`, off until the daemon * writes it from the org's setting; @@ -345,8 +347,15 @@ export function resolveSelfReport( enrolled: () => boolean = selfReportCloudEnrolled, ): SelfReportEffective | null { const presence = selfReportFilePresence(path); - // Present: the file decides. Unreadable is a broken file: off. - if (presence === "present") return readEffectiveSelfReport(path); + // Present: the file decides, except that this machine's own (local) file + // does not on a Cloud-enrolled machine, where the organization decides: off + // until the daemon writes the org's setting, as with no file. Unreadable is + // a broken file: off. + if (presence === "present") { + const file = readEffectiveSelfReport(path); + if (file && file.source !== "cloud" && enrolled()) return null; + return file; + } if (presence === "unreadable") return null; if (enrolled() || selfReportLocalConfigOff()) return null; return selfReportDefaultSettings(); diff --git a/test-fixtures/self-report/settings-cases.golden.json b/test-fixtures/self-report/settings-cases.golden.json new file mode 100644 index 000000000..00f219864 --- /dev/null +++ b/test-fixtures/self-report/settings-cases.golden.json @@ -0,0 +1,221 @@ +{ + "_comment": "Every Self Reports settings reader (the CLI's resolveSelfReport, the daemon's effective_settings and its HTTP settings cache) must reach the same on/off for each case. `file` null means no self-report.json; `text` is a raw file body.", + "cases": [ + { + "name": "no file, not enrolled: on by default", + "file": null, + "enrolled": false, + "on": true + }, + { + "name": "no file, enrolled: off until the daemon writes the org setting", + "file": null, + "enrolled": true, + "on": false + }, + { + "name": "local file on, not enrolled", + "file": { + "version": 1, + "enabled": true, + "source": "local", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": false, + "on": true + }, + { + "name": "local file on, enrolled: ignored until the org setting arrives", + "file": { + "version": 1, + "enabled": true, + "source": "local", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": true, + "on": false + }, + { + "name": "local file off, not enrolled", + "file": { + "version": 1, + "enabled": false, + "source": "local", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": false, + "on": false + }, + { + "name": "cloud file on, enrolled", + "file": { + "version": 1, + "enabled": true, + "source": "cloud", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": true, + "on": true + }, + { + "name": "cloud file off, enrolled", + "file": { + "version": 1, + "enabled": false, + "source": "cloud", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": true, + "on": false + }, + { + "name": "cloud file on, not enrolled (left from an org; the daemon removes it)", + "file": { + "version": 1, + "enabled": true, + "source": "cloud", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": false, + "on": true + }, + { + "name": "version 2, local, on, not enrolled: unsupported, off", + "file": { + "version": 2, + "enabled": true, + "source": "local", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": false, + "on": false + }, + { + "name": "version 2, cloud, on, enrolled: unsupported, off", + "file": { + "version": 2, + "enabled": true, + "source": "cloud", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": true, + "on": false + }, + { + "name": "version 0: unsupported, off", + "file": { + "version": 0, + "enabled": true, + "source": "local", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": false, + "on": false + }, + { + "name": "unparsable file: off", + "text": "{not json", + "enrolled": false, + "on": false + } + ] +} diff --git a/test-fixtures/self-report/tool-names.golden.txt b/test-fixtures/self-report/tool-names.golden.txt index 5243c6ac1..20a7f567e 100644 --- a/test-fixtures/self-report/tool-names.golden.txt +++ b/test-fixtures/self-report/tool-names.golden.txt @@ -1,12 +1,13 @@ -mcp__failproofai__report -failproofai___report -failproofai__report +mcp__failproofai_local__report +failproofai_local___report +failproofai_local__report failproofai_report -failproofai.report -failproofai/report -failproofai:report -mcp_failproofai_report -mcp__failproofai_report -mcp:failproofai:report -mcp:failproofai/report -failproofai-report +failproofai_local_report +failproofai_local.report +failproofai_local/report +failproofai_local:report +mcp_failproofai_local_report +mcp__failproofai_local_report +mcp:failproofai_local:report +mcp:failproofai_local/report +failproofai_local-report From 93cc7f4ddd64b8e0090732542d431957edb0b6b9 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Fri, 27 Nov 2026 22:13:47 +0530 Subject: [PATCH 21/54] [self-reports] Fix the end-to-end run's findings; 1.0.18-beta.3 - Daemon sync: sync on the first Cloud write, a source change, or any change an entry is built from. The startup sync failed (exit 1) because under the service's PATH no `failproofai` was found and the CLI runs as `cli.mjs`; the stdio command is now the npm link beside the daemon's node. `sync --quiet` names failed agents on stderr and the daemon logs them. - Claude Code / Codex: the stdio server records a report unless the hook already did (an untrusted Codex runs no hook), attributed to the agent's own rollout/transcript session; HTTP only while the hook will record; status shows who records and how to trust the Codex hooks. - Pi: Pi before 0.99 has no MCP, so the mcp.json entry never reached the model. The Pi extension now registers the report tool itself from `failproofai mcp --agent pi`; sync removes the old entry. - block-failproofai-commands: allow jq/grep/rg quoted arguments, heredocs that only write text, and vetted read-only `python -c`; still deny CLI runs, pause, uninstall and every write into the state (now also yq -i). - Report text: call it before the final answer when blocked, with concrete triggers (CLI, daemon, both SDKs, goldens). - Docs: hooks that do not run, Pi's extension tool, Devin's imported servers. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 15 + Cargo.lock | 6 +- Cargo.toml | 2 +- .../hooks/self-report-hook-trust.test.ts | 286 +++++++++++++++ __tests__/hooks/self-report-install.test.ts | 40 +- __tests__/hooks/self-report.test.ts | 32 +- __tests__/hooks/state-guard.test.ts | 109 +++++- bin/failproofai.mjs | 6 + crates/failproofaid/src/self_report.rs | 115 +++++- crates/fpai-collect/src/self_report.rs | 14 +- crates/fpai-collect/tests/self_report_mcp.rs | 5 +- docs/self-reports.mdx | 29 +- hermes-plugin/plugin.yaml | 2 +- package.json | 2 +- pi-extension/index.ts | 141 ++++++- sdk/python/failproofai_sdk/_self_report.py | 9 +- sdk/python/tests/test_self_report.py | 2 +- sdk/typescript/src/self-report-spec.ts | 6 +- sdk/typescript/test/self-report.test.ts | 2 +- src/hooks/builtin-policies.ts | 344 +++++++++++++++++- src/hooks/self-report-cli.ts | 61 +++- src/hooks/self-report-hook-trust.ts | 218 +++++++++++ src/hooks/self-report-install.ts | 82 ++++- src/hooks/self-report-mcp.ts | 125 ++++++- src/hooks/self-report.ts | 15 +- .../description-guidance.golden.txt | 2 +- .../self-report/description.golden.txt | 2 +- .../instructions-guidance.golden.txt | 2 +- .../self-report/instructions.golden.txt | 2 +- 29 files changed, 1593 insertions(+), 83 deletions(-) create mode 100644 __tests__/hooks/self-report-hook-trust.test.ts create mode 100644 src/hooks/self-report-hook-trust.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 10bf18067..10904ee2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.0.18-beta.3 — 2026-11-27 + +### Fixes + +- Self Reports: the daemon's sync after a Cloud setting failed with exit 1 for every agent the MCP server records (Copilot, Cursor, OpenCode, Hermes, OpenClaw, Factory, Devin, Antigravity, Goose): under the service's `PATH` no `failproofai` was found and the CLI it runs is named `cli.mjs`, so there was no stdio command to write. The sync now takes the `failproofai` npm installed beside the daemon's Node (then npm's and bun's global bins), `self-report sync --quiet` names each agent it could not update on stderr, and the daemon logs those lines as warnings ahead of its verdict (#1062) +- Self Reports: the daemon also syncs the agents when it first writes the Cloud settings file and when the file's source changes, not only when `enabled` or the port does. A machine that enrolled with its own settings file (which reads as off until Cloud answers) got the org's "on" with no sync, so no agent was registered until a manual `self-report sync` (#1062) +- Self Reports: a Codex report is no longer lost when Codex does not run failproofai's hooks (Codex 0.129+ runs an untrusted `~/.codex/hooks.json` hook never), nor a Claude Code one with `disableAllHooks`. The stdio server records a Claude Code or Codex report unless the agent's hook already recorded that report (the hook runs before the MCP call), filed on the session the agent's own rollout or transcript names; such an agent is registered over stdio rather than on the daemon's endpoint, `status` says who records each one's reports and how to trust the Codex hooks, and `self-report test` follows the same path (#1062) +- Self Reports on Pi: Pi before 0.99 has no MCP at all, so the `failproofai_local` entry in `~/.pi/agent/mcp.json` never reached the model, `exposure: "direct"` or not. failproofai's Pi extension now registers `mcp__failproofai_local__report` itself, with the server's description, categories and instructions (as a system-prompt guideline), and hands each call to `failproofai mcp --agent pi`, which records it; sync no longer writes a Pi MCP entry and removes the old one. Verified with Pi 0.85.1 on gpt-5-nano, which reported an expired token unprompted (#1062) +- Self Reports: the tool description and the server's instructions now say to call it before the final answer whenever something the agent cannot fix stopped it, with concrete triggers (a missing or expired token or key, a 401 or 403, a command or tool that keeps failing, information it cannot get, a request it cannot do); weaker models mostly ignored the old wording. Same text in the CLI, the daemon and both SDKs (#1062) +- `block-failproofai-commands` no longer blocks reads and mentions it mistook for tampering: a `jq` filter with a `|` in it, a `grep`/`rg` pattern with a `(`, a heredoc that only writes text mentioning the CLI (to a file outside failproofai's state, with nothing in the same command that could run it), and a `python -c` program that can only read. It still denies running the CLI however it is spelled, pausing, uninstalling, and every write, move, delete, `chmod` or redirect into failproofai's state, including `yq -i`, which it had read as a reader (#1062) + +### Docs + +- Self Reports: when Claude Code's or Codex's hooks do not run, Pi's tool coming from failproofai's Pi extension, and where the extra servers in `devin mcp list` come from (Devin also lists other agents' servers, such as a Claude Code project's) (#1062) + ## 1.0.18-beta.2 — 2026-11-27 ### Fixes diff --git a/Cargo.lock b/Cargo.lock index e7ff233bc..769ed755c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -298,7 +298,7 @@ dependencies = [ [[package]] name = "failproofaid" -version = "1.0.18-beta.2" +version = "1.0.18-beta.3" dependencies = [ "fpai-collect", "fpai-ipc", @@ -361,7 +361,7 @@ dependencies = [ [[package]] name = "fpai-collect" -version = "1.0.18-beta.2" +version = "1.0.18-beta.3" dependencies = [ "axum", "getrandom 0.4.3", @@ -382,7 +382,7 @@ dependencies = [ [[package]] name = "fpai-ipc" -version = "1.0.18-beta.2" +version = "1.0.18-beta.3" dependencies = [ "libc", "proptest", diff --git a/Cargo.toml b/Cargo.toml index 9a3557303..9b2f8aee8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "1.0.18-beta.2" +version = "1.0.18-beta.3" edition = "2024" license-file = "LICENSE" repository = "https://github.com/FailproofAI/failproofai" diff --git a/__tests__/hooks/self-report-hook-trust.test.ts b/__tests__/hooks/self-report-hook-trust.test.ts new file mode 100644 index 000000000..92eb25590 --- /dev/null +++ b/__tests__/hooks/self-report-hook-trust.test.ts @@ -0,0 +1,286 @@ +// @vitest-environment node +// +// Self Reports for Claude Code and Codex, whose hook is the recorder: when that +// hook will not run (an untrusted Codex, Claude Code with hooks off) the stdio +// server records the report instead, and never a second time when it did. +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { getIntegration } from "../../src/hooks/integrations"; +import { failproofaiCodexHookIdentities } from "../../src/hooks/codex-system-hooks"; +import { + claudeHooksBlockedReason, + codexReportHookRuns, + selfReportHookRecordedRecently, + selfReportHookState, +} from "../../src/hooks/self-report-hook-trust"; +import { + handleSelfReportRpc, + selfReportClaudeTranscriptSession, + selfReportCodexRolloutSession, +} from "../../src/hooks/self-report-mcp"; +import { selfReportCliDirs, resolveSelfReportCliPath, syncSelfReportMcp } from "../../src/hooks/self-report-install"; +import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; +import { runSelfReportCommand } from "../../src/hooks/self-report-cli"; + +const BIN = "/usr/local/bin/failproofai"; +const CURRENT = () => "0.172.0"; +let home: string; + +beforeEach(() => { + home = mkdtempSync(resolve(tmpdir(), "fp-sr-trust-")); + vi.stubEnv("HOME", home); + vi.stubEnv("CODEX_HOME", join(home, ".codex")); + vi.stubEnv("CLAUDE_CONFIG_DIR", ""); + vi.stubEnv("FAILPROOFAI_HOME", join(home, ".failproofai")); + vi.stubEnv("FAILPROOFAI_CLAUDE_MANAGED_SETTINGS", join(home, "managed-settings.json")); + mkdirSync(join(home, ".codex"), { recursive: true }); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(home, { recursive: true, force: true }); +}); + +function writeCodexHooks(file = join(home, ".codex", "hooks.json")): void { + const settings: Record = {}; + getIntegration("codex").writeHookEntries(settings, BIN, "user"); + mkdirSync(join(file, ".."), { recursive: true }); + writeFileSync(file, JSON.stringify(settings, null, 2)); +} + +function trust(file: string, only?: (key: string) => boolean): void { + const lines = failproofaiCodexHookIdentities(file) + .filter((h) => !only || only(h.key)) + .flatMap((h) => [`[hooks.state.${JSON.stringify(h.key)}]`, `trusted_hash = ${JSON.stringify(h.hash)}`, ""]); + writeFileSync(join(home, ".codex", "config.toml"), `model = "o3"\n${lines.join("\n")}\n`); +} + +const noSystem = { codexSystemPresent: () => false, codexVersion: CURRENT }; + +describe("will Codex run failproofai's PreToolUse hook?", () => { + it("no hooks.json of ours: no", () => { + expect(codexReportHookRuns(undefined, noSystem)).toBe(false); + }); + + it("hooks.json, untrusted (the laptop run): no; trusted at its current hash: yes", () => { + writeCodexHooks(); + writeFileSync(join(home, ".codex", "config.toml"), 'model = "o3"\n'); + expect(codexReportHookRuns(undefined, noSystem)).toBe(false); + trust(join(home, ".codex", "hooks.json")); + expect(codexReportHookRuns(undefined, noSystem)).toBe(true); + }); + + it("only the PreToolUse hook matters, since it is the one that records", () => { + writeCodexHooks(); + trust(join(home, ".codex", "hooks.json"), (k) => !k.includes(":pre_tool_use:")); + expect(codexReportHookRuns(undefined, noSystem)).toBe(false); + trust(join(home, ".codex", "hooks.json"), (k) => k.includes(":pre_tool_use:")); + expect(codexReportHookRuns(undefined, noSystem)).toBe(true); + }); + + it("a project's .codex/hooks.json above the working directory counts, trusted like the user's", () => { + const project = join(home, "proj"); + writeCodexHooks(join(project, ".codex", "hooks.json")); + trust(join(project, ".codex", "hooks.json")); + expect(codexReportHookRuns(undefined, noSystem)).toBe(false); + mkdirSync(join(project, "src"), { recursive: true }); + expect(codexReportHookRuns(join(project, "src"), noSystem)).toBe(true); + }); + + it("system hooks (run without trust) and a Codex older than the trust gate: yes", () => { + expect(codexReportHookRuns(undefined, { codexSystemPresent: () => true })).toBe(true); + writeCodexHooks(); + expect(codexReportHookRuns(undefined, { codexSystemPresent: () => false, codexVersion: () => "0.120.0" })).toBe(true); + }); +}); + +describe("will Claude Code run failproofai's hooks?", () => { + it("disableAllHooks, with Claude Code's precedence, and a managed allowManagedHooksOnly", () => { + const project = join(home, "proj"); + mkdirSync(join(project, ".claude"), { recursive: true }); + mkdirSync(join(home, ".claude"), { recursive: true }); + expect(claudeHooksBlockedReason(project)).toBeNull(); + writeFileSync(join(home, ".claude", "settings.json"), JSON.stringify({ disableAllHooks: true })); + expect(claudeHooksBlockedReason(project)).toMatch(/disableAllHooks/); + // A closer layer that sets it false wins. + writeFileSync(join(project, ".claude", "settings.json"), JSON.stringify({ disableAllHooks: false })); + expect(claudeHooksBlockedReason(project)).toBeNull(); + writeFileSync(join(project, ".claude", "settings.local.json"), JSON.stringify({ disableAllHooks: true })); + expect(claudeHooksBlockedReason(project)).toMatch(/settings\.local\.json/); + rmSync(join(project, ".claude", "settings.local.json")); + writeFileSync(join(home, "managed-settings.json"), JSON.stringify({ allowManagedHooksOnly: true })); + expect(claudeHooksBlockedReason(project)).toMatch(/allowManagedHooksOnly/); + }); +}); + +describe("selfReportHookState (status, sync)", () => { + it("names the recorder and, for an untrusted Codex, how to trust the hooks", () => { + writeCodexHooks(); + writeFileSync(join(home, ".codex", "config.toml"), ""); + const untrusted = selfReportHookState("codex", { ...noSystem, userHooksInstalled: () => true }); + expect(untrusted).toMatchObject({ recorder: "server", reason: expect.stringMatching(/not trusted/) }); + expect(untrusted.recorder === "server" && untrusted.fix).toMatch(/failproofai config.*sudo.*codex.*approve/); + trust(join(home, ".codex", "hooks.json")); + expect(selfReportHookState("codex", { ...noSystem, userHooksInstalled: () => true })).toEqual({ recorder: "hook" }); + expect(selfReportHookState("claude", { userHooksInstalled: () => true })).toEqual({ recorder: "hook" }); + expect(selfReportHookState("claude", { userHooksInstalled: () => false })).toMatchObject({ recorder: "server" }); + expect(selfReportHookState("pi")).toEqual({ recorder: "hook" }); + }); + + it("sync puts an agent whose hook will not record on stdio even with a live daemon", async () => { + const r = await syncSelfReportMcp({ + quiet: true, binaryPath: BIN, agents: ["claude", "codex"], + deps: { + daemonLive: async () => true, hooksInstalled: () => true, settings: { enabled: true, port: 4319 }, + hookRecords: (a) => a === "claude", + }, + }); + expect(r.map((x) => [x.agent, x.transport])).toEqual([["claude", "http"], ["codex", "stdio"]]); + expect(readFileSync(join(home, ".codex", "config.toml"), "utf8")).toContain('args = ["mcp", "--agent", "codex"]'); + }); + + it("status shows who records, repairs an untrusted Codex left on HTTP, and says how to trust the hooks", async () => { + writeEffectiveSelfReport({ enabled: true }); + let synced = 0; + const row = (transport: "http" | "stdio", endpoint: string) => ({ + agent: "codex" as const, path: "/x/config.toml", hooked: true, registered: true, transport, endpoint, conflict: false, + }); + let rows = [row("http", "http://127.0.0.1:4319/mcp?agent=codex")]; + const r = await runSelfReportCommand(["status"], { + probeEndpoint: async () => true, + daemonLive: async () => true, + registrations: () => rows, + hookState: () => ({ recorder: "server", reason: "Codex has not trusted failproofai's hooks, so it does not run them", fix: "Trust them." }), + sync: async () => { + synced++; + rows = [row("stdio", BIN)]; + return [{ agent: "codex", path: "/x/config.toml", action: "updated", transport: "stdio", status: "ok" }]; + }, + }); + expect(synced).toBe(1); + const text = r.lines.join("\n"); + expect(text).toContain("Repaired:"); + expect(text).toMatch(/codex +stdio/); + expect(text).toContain("reports recorded by the MCP server: Codex has not trusted failproofai's hooks"); + expect(text).toContain("Trust them."); + + const ok = await runSelfReportCommand(["status"], { + probeEndpoint: async () => true, daemonLive: async () => true, + registrations: () => [row("http", "http://127.0.0.1:4319/mcp?agent=codex")], + hookState: () => ({ recorder: "hook" }), + sync: async () => (synced++, []), + }); + expect(synced).toBe(1); + expect(ok.lines.join("\n")).toContain("reports recorded by its hook"); + }); +}); + +describe("the server records what the hook did not, once", () => { + const call = (args: Record) => ({ jsonrpc: "2.0", id: 9, method: "tools/call", params: { name: "report", arguments: args } }); + const events = () => { + try { + return readdirSync(join(home, ".failproofai", "custom-agents", "events")).map((f) => + JSON.parse(readFileSync(join(home, ".failproofai", "custom-agents", "events", f), "utf8")), + ); + } catch { + return []; + } + }; + const hookRow = (over: Record) => { + mkdirSync(join(home, ".failproofai", "hook-activity"), { recursive: true }); + writeFileSync( + join(home, ".failproofai", "hook-activity", "current.jsonl"), + JSON.stringify({ timestamp: Date.now() - 1000, eventType: "PreToolUse", integration: "codex", sessionId: "s", decision: "allow", ...over }) + "\n", + ); + }; + + it("a hook row with the same report suppresses it; a different one, an old one or another agent's does not", () => { + const args = { category: "invalid_tool_or_credential", detail: "token expired" }; + hookRow({ selfReport: { ...args, source: "mcp" } }); + expect(selfReportHookRecordedRecently("codex", args)).toBe(true); + expect(selfReportHookRecordedRecently("codex", { ...args, detail: "other" })).toBe(false); + expect(selfReportHookRecordedRecently("claude", args)).toBe(false); + hookRow({ selfReport: { ...args, source: "mcp" }, timestamp: Date.now() - 10 * 60 * 1000 }); + expect(selfReportHookRecordedRecently("codex", args)).toBe(false); + hookRow({ eventType: "PostToolUse", selfReport: { ...args, source: "mcp" } }); + expect(selfReportHookRecordedRecently("codex", args)).toBe(false); + // Aliased arguments are compared as the hook recorded them. + hookRow({ selfReport: { ...args, source: "mcp" } }); + expect(selfReportHookRecordedRecently("codex", { type: args.category, summary: args.detail })).toBe(true); + }); + + it("an untrusted Codex's report lands once, on the session Codex's own rollout names", async () => { + writeEffectiveSelfReport({ enabled: true }); + const project = join(home, "proj"); + const day = new Date(); + const pad = (n: number) => String(n).padStart(2, "0"); + const dir = join(home, ".codex", "sessions", String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate())); + mkdirSync(dir, { recursive: true }); + mkdirSync(project, { recursive: true }); + const meta = (id: string, cwd: string) => JSON.stringify({ type: "session_meta", payload: { id, cwd } }) + "\n"; + writeFileSync(join(dir, "rollout-a-elsewhere.jsonl"), meta("other-id", join(home, "elsewhere"))); + writeFileSync(join(dir, "rollout-b.jsonl"), meta("codex-session-1", project)); + expect(selfReportCodexRolloutSession(project)).toEqual({ sessionId: "codex-session-1", cwd: project }); + // Too old: outside the 6 h window. + const old = new Date(Date.now() - 7 * 60 * 60 * 1000); + utimesSync(join(dir, "rollout-b.jsonl"), old, old); + expect(selfReportCodexRolloutSession(project)).toBeNull(); + utimesSync(join(dir, "rollout-b.jsonl"), new Date(), new Date()); + + const args = { category: "invalid_tool_or_credential", detail: "tickets: 401, token expired" }; + const reply = await handleSelfReportRpc(call(args), { agent: "codex", cwd: project }); + expect(reply).toMatchObject({ result: { content: [{ type: "text", text: "Recorded." }] } }); + expect(events()).toEqual([expect.objectContaining({ integration: "codex", session_id: "codex-session-1", agent_id: "codex-proj", ...args })]); + + // The same call after the hook recorded it: nothing more. + hookRow({ selfReport: { ...args, source: "mcp" } }); + await handleSelfReportRpc(call(args), { agent: "codex", cwd: project }); + expect(events()).toHaveLength(1); + }); + + it("Claude Code with hooks off: attributed to its newest transcript in that directory", () => { + const project = join(home, "my.proj"); + const dir = join(home, ".claude", "projects", project.replace(/[^A-Za-z0-9]/g, "-")); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "11111111-1111-4111-8111-111111111111.jsonl"), "{}\n"); + const older = new Date(Date.now() - 60_000); + utimesSync(join(dir, "11111111-1111-4111-8111-111111111111.jsonl"), older, older); + writeFileSync(join(dir, "22222222-2222-4222-8222-222222222222.jsonl"), "{}\n"); + expect(selfReportClaudeTranscriptSession(project)).toEqual({ sessionId: "22222222-2222-4222-8222-222222222222", cwd: project }); + expect(selfReportClaudeTranscriptSession(join(home, "other"))).toBeNull(); + }); +}); + +describe("the CLI a daemon's sync registers for stdio", () => { + it("looks beside the node that runs it, then npm's and bun's global bins", () => { + const dirs = selfReportCliDirs({ NPM_CONFIG_PREFIX: "/opt/npm" }, "/home/u/.nvm/versions/node/v26/bin/node", "/home/u"); + expect(dirs).toEqual([ + "/home/u/.nvm/versions/node/v26/bin", + "/opt/npm/bin", + "/home/u/.npm-global/bin", + "/usr/local/bin", + "/home/u/.bun/bin", + ]); + }); + + it("finds the npm link next to node when PATH has no failproofai (a systemd unit's PATH)", () => { + const bin = join(home, "nodebin"); + mkdirSync(bin); + writeFileSync(join(bin, "failproofai"), "#!/bin/sh\n"); + chmodSync(join(bin, "failproofai"), 0o755); + vi.stubEnv("PATH", "/nonexistent"); + vi.stubEnv("FAILPROOFAI_BINARY_OVERRIDE", ""); + const execPath = process.execPath; + Object.defineProperty(process, "execPath", { value: join(bin, "node"), configurable: true }); + const argv1 = process.argv[1]; + process.argv[1] = "/x/lib/node_modules/failproofai/dist/cli.mjs"; + try { + expect(resolveSelfReportCliPath()).toBe(join(bin, "failproofai")); + } finally { + Object.defineProperty(process, "execPath", { value: execPath, configurable: true }); + process.argv[1] = argv1; + } + }); +}); diff --git a/__tests__/hooks/self-report-install.test.ts b/__tests__/hooks/self-report-install.test.ts index f05e58f39..a20b2ed10 100644 --- a/__tests__/hooks/self-report-install.test.ts +++ b/__tests__/hooks/self-report-install.test.ts @@ -43,6 +43,7 @@ function enabledOpts(extra: Partial = {}, daemon = tru deps: { daemonLive: async () => daemon, hooksInstalled: () => true, + hookRecords: () => true, settings: { enabled: true, port: 4319 }, ...extra.deps, }, @@ -101,7 +102,7 @@ const USER_JSON = (container: string[]) => { }; describe("syncSelfReportMcp: every agent round-trips", () => { - for (const agent of INTEGRATION_TYPES) { + for (const agent of INTEGRATION_TYPES.filter((a) => !SELF_REPORT_MCP_TARGETS[a].extension)) { const target = SELF_REPORT_MCP_TARGETS[agent]; it(`${agent}: adds, is idempotent, keeps the user's entries, removes only ours`, async () => { const path = pathOf(agent); @@ -157,7 +158,7 @@ describe("transport choice", () => { expect(INTEGRATION_TYPES.filter((a) => selfReportHttpAllowed(a))).toEqual(["claude", "codex"]); for (const a of SELF_REPORT_SERVER_RECORDS) expect(selfReportHttpAllowed(a as IntegrationType)).toBe(false); const r = await syncSelfReportMcp(enabledOpts({}, true)); - for (const x of r) expect(x.transport).toBe(selfReportHttpAllowed(x.agent) ? "http" : "stdio"); + for (const x of r) expect(x.transport).toBe(x.agent === "pi" ? "extension" : selfReportHttpAllowed(x.agent) ? "http" : "stdio"); // Every agent's HTTP shape is still one we recognise (a stale one is moved). for (const a of INTEGRATION_TYPES) { const t = SELF_REPORT_MCP_TARGETS[a]; @@ -186,15 +187,32 @@ describe("transport choice", () => { expect(entryIn("goose")).toMatchObject({ type: "stdio", cmd: CLI, args: ["mcp", "--agent", "goose"], enabled: true }); }); - it("exposes Pi's entry directly, on both transports, and moves an old entry to it", async () => { - await syncSelfReportMcp(enabledOpts({ agents: ["pi"] }, false)); - expect(entryIn("pi")).toEqual({ command: CLI, args: ["mcp", "--agent", "pi"], exposure: "direct" }); - // An older HTTP entry, written before `exposure` was set, is ours: it is - // moved to stdio (Pi is server-recorded) with exposure set. - put(pathOf("pi"), JSON.stringify({ mcpServers: { failproofai_local: { url: "http://127.0.0.1:4319/mcp?agent=pi" } } })); - const r = await syncSelfReportMcp(enabledOpts({ agents: ["pi"] }, true)); - expect(r[0]).toMatchObject({ action: "updated", transport: "stdio" }); - expect(entryIn("pi")).toEqual({ command: CLI, args: ["mcp", "--agent", "pi"], exposure: "direct" }); + // Pi before 0.99 has no MCP, so an mcp.json entry never reached its model: + // failproofai's Pi extension offers the tool instead (pi-extension/index.ts). + it("writes no Pi MCP entry, takes out one an earlier version wrote, and keeps the user's", async () => { + const r0 = await syncSelfReportMcp(enabledOpts({ agents: ["pi"] }, false)); + expect(r0).toEqual([{ agent: "pi", path: "", action: "unchanged", transport: "extension", status: "ok" }]); + expect(existsSync(pathOf("pi"))).toBe(false); + for (const old of [ + { command: CLI, args: ["mcp", "--agent", "pi"], exposure: "direct" }, + { url: "http://127.0.0.1:4319/mcp?agent=pi" }, + ]) { + put(pathOf("pi"), JSON.stringify({ mcpServers: { failproofai_local: old, mine: { command: "node", args: ["x.js"] } } })); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["pi"] }, true)); + expect(r[0]).toMatchObject({ action: "removed", status: "ok" }); + expect(r[1]).toMatchObject({ action: "unchanged", transport: "extension" }); + expect(entryIn("pi")).toBeUndefined(); + expect(read(pathOf("pi"))).toContain("mine"); + } + // A failproofai_local of the user's own is not ours: left alone. + put(pathOf("pi"), JSON.stringify({ mcpServers: { failproofai_local: { command: "node", args: ["mine.js"] } } })); + await syncSelfReportMcp(enabledOpts({ agents: ["pi"] }, true)); + expect(entryIn("pi")).toEqual({ command: "node", args: ["mine.js"] }); + // Off, or not hooked: no tool from the extension either. + const off = await syncSelfReportMcp(enabledOpts({ agents: ["pi"], enabled: false }, true)); + expect(off.at(-1)).toMatchObject({ transport: null, status: "ok" }); + const unhooked = await syncSelfReportMcp(enabledOpts({ agents: ["pi"], deps: { hooksInstalled: () => false } }, true)); + expect(unhooked.at(-1)).toMatchObject({ transport: null, status: "not-hooked" }); }); it("tells the user how cursor-agent approves the server when Cursor's entry is written", async () => { diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index 99d8a1e03..333ac08b2 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -36,7 +36,7 @@ import { runSelfReportCommand } from "../../src/hooks/self-report-cli"; const BINARY = resolve(__dirname, "..", "..", "bin", "failproofai.mjs"); -const EXPECTED_DESCRIPTION = `Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; do not call it for normal work, clarifying questions or a single error. One call per distinct problem. +const EXPECTED_DESCRIPTION = `Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. Categories: @@ -437,7 +437,8 @@ describe("self-report sync on a stale home", () => { const INIT = { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "t", version: "1" } } }; const INITIALIZED = { jsonrpc: "2.0", method: "notifications/initialized" }; const LIST = { jsonrpc: "2.0", id: 2, method: "tools/list" }; -const CALL = { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "report", arguments: { category: "looping", detail: "stuck in a retry loop" } } }; +const CALL_ARGS = { category: "looping", detail: "stuck in a retry loop" }; +const CALL = { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "report", arguments: CALL_ARGS } }; const PING = { jsonrpc: "2.0", id: 4, method: "ping" }; describe("failproofai mcp (stdio, spawned)", () => { @@ -482,12 +483,37 @@ describe("failproofai mcp (stdio, spawned)", () => { expect(() => readdirSync(join(home, "custom-agents", "events"))).toThrow(); }, 30_000); - it("writes no event for a hook-recorded agent (claude)", async () => { + // Claude Code and Codex: the hook records, so the server writes nothing for + // a call the hook already recorded. The hook runs before the MCP call is + // sent, so its row is there first. + it("writes no event for a hook-recorded agent (claude) whose hook recorded the call", async () => { writeEffectiveSelfReport({ enabled: true }); + mkdirSync(join(home, "hook-activity"), { recursive: true }); + writeFileSync( + join(home, "hook-activity", "current.jsonl"), + JSON.stringify({ + timestamp: Date.now() - 500, eventType: "PreToolUse", integration: "claude", sessionId: "c1", decision: "allow", + toolName: "mcp__failproofai_local__report", selfReport: { ...CALL_ARGS, source: "mcp" }, + }) + "\n", + ); await runMcp(["--agent", "claude"], [INIT, CALL], home); expect(() => readdirSync(join(home, "custom-agents", "events"))).toThrow(); }, 30_000); + // ...and records it when the hook did not (an untrusted Codex runs no hook): + // otherwise the report would be lost. + it("records a hook-recorded agent's report when its hook did not", async () => { + writeEffectiveSelfReport({ enabled: true }); + for (const agent of ["codex", "claude"]) { + await runMcp(["--agent", agent], [INIT, CALL], home); + } + const files = readdirSync(join(home, "custom-agents", "events")); + expect(files).toHaveLength(2); + const events = files.map((f) => JSON.parse(readFileSync(join(home, "custom-agents", "events", f), "utf8"))); + expect(events.map((e) => e.integration).sort()).toEqual(["claude", "codex"]); + for (const e of events) expect(e).toMatchObject({ type: "self_report", ...CALL_ARGS, source: "mcp" }); + }, 30_000); + it("writes one self_report event in the SDK spool format for a server-recorded agent, attributed to its session", async () => { writeEffectiveSelfReport({ enabled: true }); const project = join(home, "proj"); diff --git a/__tests__/hooks/state-guard.test.ts b/__tests__/hooks/state-guard.test.ts index 11a84cbfd..3fc219e2f 100644 --- a/__tests__/hooks/state-guard.test.ts +++ b/__tests__/hooks/state-guard.test.ts @@ -673,10 +673,14 @@ describe("block-failproofai-commands — the state guard", () => { // enforcement silently; an allowlist miss denies a command the operator can // see and report. These two are misses of the second kind — a backup and a // read — and they are pinned so the next person knows they are a decision - // rather than an accident. - it("over-denies a tar backup and an interpreter read, which is the chosen failure", async () => { + // rather than an accident. A `python -c` read used to be the second one; + // it is allowed now only when `pythonCodeOnlyReads` can vet the program + // (see "reads and mentions are not tampering" below), and an interpreter + // program it cannot vet is still over-denied. + it("over-denies a tar backup and an interpreter read it cannot vet, which is the chosen failure", async () => { expect(await decide("tar -cf /tmp/backup.tar ~/.failproofai")).toBe("deny"); - expect(await decide("python3 -c \"print(open('/home/u/.failproofai/policies-config.json').read())\"")).toBe("deny"); + expect(await decide("python3 -c \"import os; print(open('/home/u/.failproofai/policies-config.json').read())\"")).toBe("deny"); + expect(await decide("node -e \"console.log(require('fs').readFileSync('/home/u/.failproofai/policies-config.json','utf8'))\"")).toBe("deny"); }); }); @@ -805,4 +809,103 @@ describe("block-failproofai-commands — the state guard", () => { expect(await reason("failproofai config --pause")).toMatch(/human action/); }); }); + + // Found by a full end-to-end run: an agent diagnosing Self Reports was denied + // a read-only jq and python read of self-report.json, a grep for the MCP + // server's name, and a heredoc that only wrote notes mentioning the CLI. + describe("reads and mentions are not tampering", () => { + const F = "fail" + "proofai"; + it("allows a jq whose filter has a pipe, and a vetted python -c read", async () => { + for (const c of [ + `jq '.categories | length' ~/.${F}/self-report.json`, + `jq -r '.enabled, .source' ~/.${F}/self-report.json`, + `python3 -c "import json; print(json.load(open('/home/u/.${F}/self-report.json'))['enabled'])"`, + `python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(d["source"])' ~/.${F}/self-report.json`, + `python3 -c "import json; print(open('/home/u/.${F}/self-report.json', 'r', encoding='utf-8').read())"`, + ]) expect(await decide(c), c).toBe("allow"); + }); + + it("allows a grep whose pattern names the CLI or the MCP server", async () => { + for (const c of [ + `grep '${F}_local' ~/.codex/config.toml`, + `grep -E '(${F}_local|kiln)' ~/.codex/config.toml`, + `grep -rn '${F} config --pause' docs/`, + `rg '(${F}_local)' ~/.config`, + `grep -r 'npm uninstall -g ${F}' docs`, + ]) expect(await decide(c), c).toBe("allow"); + }); + + it("allows a heredoc that only writes text mentioning the CLI", async () => { + for (const c of [ + `cat > ~/Desktop/notes.md <<'EOF'\nRun ${F} self-report sync to fix it.\n${F} config --pause is for people.\nEOF`, + `cat > ~/Desktop/n.md <<'EOF'\nnpm uninstall -g ${F}\nrm -rf ~/.${F}\nEOF`, + `cat <<-EOF > ~/Desktop/n.md\n\t${F} policies --install\n\tEOF`, + `tee ~/Desktop/n.md <<'EOF'\n${F} self-report status\nEOF`, + ]) expect(await decide(c), c).toBe("allow"); + }); + + it("still denies running the CLI, pausing and uninstalling, however the command is dressed", async () => { + for (const c of [ + `${F} self-report sync`, + `npx ${F} config --pause`, + `npx -y ${F}@latest policies --uninstall`, + `npm uninstall -g ${F}`, + `fail"proof"ai config --pause`, + `grep x f; fail\\proofai self-report sync`, + `grep -e '(x' f ; ${F} policies`, + `grep "$(${F} config --pause)" f`, + `jq -n "$(${F} config --pause)"`, + `python3 -c "print(1)" ; ${F} config --pause`, + ]) expect(await decide(c), c).toBe("deny"); + }); + + it("still runs a heredoc's body when it can execute", async () => { + for (const c of [ + `sh <<'EOF'\n${F} config --pause\nEOF`, + `bash -s <<'EOF'\n${F} self-report disable\nEOF`, + `cat <<'EOF' | sh\n${F} config --pause\nEOF`, + `cat > /tmp/p.sh <<'EOF'\n${F} config --pause\nEOF\nsh /tmp/p.sh`, + `cat <<'EOF' > /tmp/x\n${F} config --pause\nEOF\nchmod +x /tmp/x && /tmp/x`, + // An unquoted delimiter expands $(...) and backticks while writing. + `cat > n < n < n <<'EOF'\nx\nEOF\n${F} config --pause`, + `cat > f <<'EOF' ; ${F} config --pause\nbody\nEOF`, + ]) expect(await decide(c), c).toBe("deny"); + }); + + it("still denies every write, move, delete, chmod and redirect into the state", async () => { + for (const c of [ + `rm ~/.${F}/self-report.json`, + `echo '{}' > ~/.${F}/self-report.json`, + `echo x >> ~/.${F}/policies-config.json`, + `chmod 000 ~/.${F}/policies-config.json`, + `mv ~/.${F} /tmp/x`, + `jq '.enabled=false' ~/.${F}/self-report.json > /tmp/t && mv /tmp/t ~/.${F}/self-report.json`, + `jq '.' ~/.${F}/a | tee ~/.${F}/b`, + `grep x ~/.${F}/f > ~/.${F}/g`, + `yq -i '.a=1' ~/.${F}/x.yaml`, + `tee ~/.${F}/self-report.json <<'EOF'\n{}\nEOF`, + `cat > ~/.${F}/self-report.json <<'EOF'\n{}\nEOF`, + `python3 -c "import json; json.load(open('/x/.${F}/a'))" > ~/.${F}/b`, + ]) expect(await denialIsAboutState(c), c).toBe(true); + }); + + it("denies a python -c it cannot vet as a read", async () => { + for (const c of [ + `python3 -c "import os; os.remove('/home/u/.${F}/self-report.json')"`, + `python3 -c "open('/home/u/.${F}/self-report.json','w').write('{}')"`, + `python3 -c "import json;o=open;o('/x/.${F}/a','w')"`, + `python3 -c "open('/x/.${F}/a', mode='w')"`, + `python3 -c "open('/x/.${F}/a', 'r+')"`, + `python3 -c "import os; print(open('/x/.${F}/a').read())"`, + `python3 -c "import json; getattr(json, 'load')(open('/x/.${F}/a'))"`, + `python3 -c "__import__('os').remove('/x/.${F}/a')"`, + `python3 -c "import json; print(open('/x/.${F}/a').read())" -c "x"; rm ~/.${F}/a`, + `python3 -c "import shutil; shutil.rmtree('/x/.${F}')"`, + `python3 -c "import json; exec('\\x6f')" ~/.${F}/a`, + ]) expect(await decide(c), c).toBe("deny"); + }); + }); }); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index e2627890b..adbb2559e 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -822,6 +822,12 @@ async function runCli() { if (!subArgs.includes("--quiet")) { const lines = selfReportSyncLines(results); await printLines(lines.length > 0 ? lines : ["Self Reports MCP registration is already up to date."], !failed); + } else if (failed) { + // The daemon runs this with --quiet and logs our stderr: without the + // failing agents' lines, "exit 1" was all its journal ever said. + for (const r of results.filter((x) => x.status === "error")) { + process.stderr.write(`${r.agent}: not updated in ${r.path || "its config"}: ${r.detail ?? "error"}\n`); + } } lastSubcommand = null; await exitAfterFlush(failed ? 1 : 0); diff --git a/crates/failproofaid/src/self_report.rs b/crates/failproofaid/src/self_report.rs index 7c2f20363..9eefac36a 100644 --- a/crates/failproofaid/src/self_report.rs +++ b/crates/failproofaid/src/self_report.rs @@ -94,10 +94,32 @@ pub fn effective(desired: Option<&Desired>, port: u16, updated_at: String) -> Se #[derive(Debug, PartialEq, Eq)] pub struct Applied { pub written: bool, - /// `enabled` or the port changed: agent configs need `self-report sync`. + /// What an agent's entry would be may have changed: agent configs need + /// `self-report sync`. pub needs_sync: bool, } +/// Whether going from `previous` to `next` can change what `self-report sync` +/// writes into an agent's config. Categories and guidance never do (the server +/// reads them on every request); everything an entry is built from does: +/// +/// - no file before: this is the first Cloud write. Before it the machine was +/// either on by default (it just enrolled) or off while it waited for this +/// answer (`failproofai config` syncs then and removes every entry), so no +/// file says nothing about what the agents hold; +/// - `source`: a local file is set aside while the org's setting is awaited, +/// which reads as off, so an org "on" that matches the old local "on" still +/// has agents to register; +/// - `enabled`, and the endpoint while on (its port is in the HTTP entries). +fn entries_may_change(previous: Option<&Settings>, next: &Settings) -> bool { + let Some(previous) = previous else { + return true; + }; + previous.source != next.source + || previous.enabled != next.enabled + || (next.enabled && previous.mcp != next.mcp) +} + /// Write `path` for this response, only when its content (not `updatedAt`) /// changed. pub fn apply(path: &Path, desired: Option<&Desired>, port: u16) -> io::Result { @@ -110,11 +132,9 @@ pub fn apply(path: &Path, desired: Option<&Desired>, port: u16) -> io::Result io::Result .stderr(Stdio::piped()) .process_group(0) .spawn()?; + let (done_tx, done_rx) = std::sync::mpsc::channel::<()>(); + let mut readers = 0; for (label, pipe) in [ ( "stdout", @@ -435,26 +457,47 @@ fn run_with_timeout(command: &str, home: &Path, timeout: Duration) -> io::Result .map(|p| Box::new(p) as Box), ), ] { + // `sync --quiet` prints nothing on success and one line per agent it + // could not update on stderr, so a failure in the journal says which + // agent and why. stderr is a warning; anything on stdout is info. if let Some(pipe) = pipe { + let done = done_tx.clone(); std::thread::spawn(move || { use std::io::BufRead; for line in io::BufReader::new(pipe).lines().map_while(Result::ok) { - tracing::info!("self-report sync {label}: {line}"); + if label == "stderr" { + tracing::warn!("self-report sync: {line}"); + } else { + tracing::info!("self-report sync: {line}"); + } } + let _ = done.send(()); }); + readers += 1; } } + drop(done_tx); let started = Instant::now(); - loop { + let code = loop { if let Some(status) = child.try_wait()? { - return Ok(status.code()); + break status.code(); } if started.elapsed() > timeout { kill_group(&mut child); - return Ok(None); + break None; } std::thread::sleep(Duration::from_millis(100)); + }; + // Let the output reach the log ahead of the caller's verdict line, but + // never wait on a pipe some leftover grandchild still holds. + let deadline = Instant::now() + Duration::from_secs(1); + for _ in 0..readers { + let left = deadline.saturating_duration_since(Instant::now()); + if done_rx.recv_timeout(left).is_err() { + break; + } } + Ok(code) } fn kill_group(child: &mut Child) { @@ -543,12 +586,13 @@ mod tests { guidance: None, }; - // First write while off: nothing was registered, nothing to sync. + // First write, even while off: before it the machine was on by default + // (or off while it waited), so the agents' entries are unknown. assert_eq!( apply(&path, None, 4319).unwrap(), Applied { written: true, - needs_sync: false + needs_sync: true } ); let first = std::fs::read_to_string(&path).unwrap(); @@ -610,6 +654,57 @@ mod tests { ); } + #[test] + fn the_first_cloud_write_syncs_even_when_it_matches_the_local_file() { + // The laptop run: `config` wrote a local, enabled file, then synced + // while enrolled (a local file then reads as off) and removed every + // entry. The org's first answer, "on", matched the old `enabled`. + let on = Desired { + enabled: true, + ..Default::default() + }; + let path = temp_path("first-cloud"); + assert_eq!( + apply(&path, Some(&on), 4319).unwrap(), + Applied { + written: true, + needs_sync: true + }, + "no file before" + ); + + let path = temp_path("local-to-cloud"); + let mut local = effective(Some(&on), 4319, "t".into()); + local.source = "local".into(); + sr::write_settings(&path, &local).unwrap(); + assert_eq!( + apply(&path, Some(&on), 4319).unwrap(), + Applied { + written: true, + needs_sync: true + }, + "a local file replaced by the org's" + ); + // From then on, only a change an entry is built from syncs. + assert_eq!( + apply( + &path, + Some(&Desired { + enabled: true, + guidance: Some("Be brief.".into()), + ..Default::default() + }), + 4319 + ) + .unwrap(), + Applied { + written: true, + needs_sync: false + } + ); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + #[test] fn leaving_cloud_removes_only_a_cloud_file() { let path = temp_path("release"); diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index a79bfa16a..7bd0a60f8 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -93,7 +93,7 @@ pub const SERVER_RECORDS: &[&str] = &[ /// a client asking for one it does not know. const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05", "2025-11-25"]; -const DESCRIPTION_HEAD: &str = "Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; do not call it for normal work, clarifying questions or a single error. One call per distinct problem.\nReporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user."; +const DESCRIPTION_HEAD: &str = "Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem.\nReporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user."; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Category { @@ -423,10 +423,12 @@ pub fn input_schema(categories: &[Category]) -> Value { pub fn instructions(categories: &[Category], guidance: Option<&str>) -> String { let names: Vec<&str> = categories.iter().map(|c| c.name.as_str()).collect(); let mut text = format!( - "FailproofAI records when an agent is stuck. If you get stuck ({}), call this server's \ - `report` tool once with two arguments: `category` (one of those names) and `detail` \ - (one factual sentence). It does not unblock you: continue, or tell the user what is \ - blocking you. There is no need to mention the report to the user.", + "FailproofAI records when an agent is blocked. Before your final answer, if something \ + failed that you cannot fix yourself (a missing or expired token or key, a 401 or 403, a \ + command or tool that keeps failing, information you cannot get, a request you cannot \ + do), call this server's `report` tool once with `category` (one of: {}) and `detail` \ + (one factual sentence). Not when the task succeeded. It does not unblock you, and there \ + is no need to mention it to the user.", names.join(", ") ); if let Some(g) = guidance.filter(|g| !g.is_empty()) { @@ -1206,7 +1208,7 @@ mod tests { describe(&cats, Some("Be brief.")), format!("{want}\n\nBe brief.") ); - assert!(DESCRIPTION_HEAD.starts_with("Report to FailproofAI that you are stuck.")); + assert!(DESCRIPTION_HEAD.starts_with("Report to FailproofAI that you are blocked.")); assert!(DESCRIPTION_HEAD.ends_with("There is no need to mention this report to the user.")); } diff --git a/crates/fpai-collect/tests/self_report_mcp.rs b/crates/fpai-collect/tests/self_report_mcp.rs index b7460f874..d75faf5c6 100644 --- a/crates/fpai-collect/tests/self_report_mcp.rs +++ b/crates/fpai-collect/tests/self_report_mcp.rs @@ -293,7 +293,10 @@ async fn the_tool_list_follows_the_settings_file() { json!(["org_custom"]) ); let text = instructions(server.rpc("", init.clone()).await.1).unwrap(); - assert!(text.as_str().unwrap().contains("(org_custom)"), "{text}"); + assert!( + text.as_str().unwrap().contains("(one of: org_custom)"), + "{text}" + ); assert!( text.as_str().unwrap().ends_with("\n\nPrefer one report."), "{text}" diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index 049627eeb..7058931b1 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -19,7 +19,7 @@ Self Reports is on as soon as failproofai is installed. `failproofai policies -- 1. Go to **settings → self reports**. 2. Keep it on, or switch it off. Keep the default categories or write your own, and optionally add guidance for the agents. - Every connected machine picks the change up on its next policy poll. `failproofaid` writes `~/.failproofai/self-report.json` from it and adds the `failproofai_local` MCP server to every agent that has failproofai hooks, or removes it when the switch is off. Until the first poll after connecting writes that file, the machine treats Self Reports as off. + Every connected machine picks the change up on its next policy poll. `failproofaid` writes `~/.failproofai/self-report.json` from it and adds the `failproofai_local` MCP server to every agent that has failproofai hooks, or removes it when the switch is off. Until the first poll after connecting writes that file, the machine treats Self Reports as off. The daemon updates the agents whenever what their entries depend on changes: the first time it writes the file, when the file's source changes (a machine's own file replaced by the organization's), when the switch flips, and when the port changes. On a Cloud-managed machine, `failproofai self-report enable` and `disable` refuse and point you to the dashboard. @@ -60,13 +60,13 @@ A report with a category that is not on the list is still recorded under the nam ## Agent support -failproofai registers one MCP server, named `failproofai_local`, in each agent's user-level MCP settings. Agents see its tool as `mcp__failproofai_local__report` (Claude Code, Codex, Pi, Factory, Devin), `failproofai_local_report` (OpenCode), `mcp_failproofai_local_report` (Hermes, Antigravity) or `failproofai_local__report` (OpenClaw, Goose). The name is not `failproofai`, which is the name the [Cloud MCP gateway](/reference/mcp) is usually added under, so the two coexist. For Claude Code and Codex, whose hooks record the report, the entry points at the daemon's local server, `http://127.0.0.1:4319/mcp` (set `FAILPROOFAI_SELF_REPORT_PORT` to move it), when `failproofaid` is serving it, and runs `failproofai mcp` over stdio otherwise. Every other agent always gets `failproofai mcp` over stdio, because its report is recorded by the server, which needs the agent's working directory to find the session (see below). Every entry is marked as failproofai's, so removing it never touches a server you added. +failproofai registers one MCP server, named `failproofai_local`, in each agent's user-level MCP settings. Agents see its tool as `mcp__failproofai_local__report` (Claude Code, Codex, Factory, Devin, and Pi, whose tool comes from failproofai's Pi extension, see below), `failproofai_local_report` (OpenCode), `mcp_failproofai_local_report` (Hermes, Antigravity) or `failproofai_local__report` (OpenClaw, Goose). The name is not `failproofai`, which is the name the [Cloud MCP gateway](/reference/mcp) is usually added under, so the two coexist. For Claude Code and Codex, whose hooks record the report, the entry points at the daemon's local server, `http://127.0.0.1:4319/mcp` (set `FAILPROOFAI_SELF_REPORT_PORT` to move it), when `failproofaid` is serving it and the agent's hooks will run, and runs `failproofai mcp` over stdio otherwise (see [When the hooks do not run](#when-the-hooks-do-not-run)). Every other agent always gets `failproofai mcp` over stdio, because its report is recorded by the server, which needs the agent's working directory to find the session (see below). Every entry is marked as failproofai's, so removing it never touches a server you added. -The transport is chosen when the entries are written, from a live check: the daemon behind this account's socket must answer, and the endpoint must answer as that same daemon (both carry the daemon's instance id). A port held by another daemon, for example another user's, or one whose own server could not bind the port, gives stdio. When the daemon starts, it re-runs `failproofai self-report sync`, so Claude Code and Codex move to HTTP. If the daemon stops, `failproofai self-report status` finds agents pointing at an endpoint that does not answer, or an agent the server records left on HTTP by an earlier version, and moves them to stdio. A running agent keeps the server it loaded at startup. +The transport is chosen when the entries are written, from a live check: the daemon behind this account's socket must answer, and the endpoint must answer as that same daemon (both carry the daemon's instance id). A port held by another daemon, for example another user's, or one whose own server could not bind the port, gives stdio. When the daemon starts, it re-runs `failproofai self-report sync`, so Claude Code and Codex move to HTTP. The sync writes the stdio command as the `failproofai` that npm installed beside the daemon's Node, so it finds it even under the service's own `PATH`, and when it cannot update an agent the daemon's log names the agent and the reason. If the daemon stops, `failproofai self-report status` finds agents pointing at an endpoint that does not answer, or an agent the server records left on HTTP by an earlier version, and moves them to stdio. A running agent keeps the server it loaded at startup. Both transports send the model short server instructions in the MCP handshake: when to report, the category names, and your guidance. Some agents, Claude Code among them, load MCP tools only on demand. They add a server's instructions to the system prompt, though, so the model knows the tool exists. Copilot CLI passes a server's instructions to the model only for servers on its allowlist (or with `--allow-all-mcp-server-instructions`), so on Copilot the model may see only the tool's own description. -Pi shows the model only a server's name by default. failproofai's Pi entry sets `"exposure": "direct"`, so `report` and its description reach the model like a built-in tool. Hermes and OpenClaw defer MCP tools behind their tool search (`tools.tool_search` / `tools.toolSearch`). Neither has a per-server setting to load one server directly, so failproofai leaves that setting alone, and the model sees `report` in the deferred tool listing. +Pi has no MCP support before 0.99, so an MCP entry for it reaches no model. failproofai's Pi extension, which every Pi with failproofai hooks already loads, registers the tool itself as `mcp__failproofai_local__report` on every Pi version, with the server's instructions in Pi's system prompt. It asks `failproofai mcp --agent pi` for the tool when Pi starts (no tool while Self Reports is off) and hands each call to it, so the text, the categories and the recording are the same as every other agent's. `self-report sync` writes no Pi MCP entry and takes out one an earlier version wrote. Hermes and OpenClaw defer MCP tools behind their tool search (`tools.tool_search` / `tools.toolSearch`). Neither has a per-server setting to load one server directly, so failproofai leaves that setting alone, and the model sees `report` in the deferred tool listing. Where an agent's hooks see MCP tool calls and the server they belong to, the hook records the report. Where they do not, failproofai's MCP server records it. It attributes the report to that agent's newest session seen by the hooks in the last 6 hours: in the server's working directory if there is one, else in a directory above or below it. With neither, it takes the agent's newest session only when all of the agent's sessions in those 6 hours are in one directory, and files the report as `unattributed` otherwise, rather than guess between projects. The lookup reads every page of hook activity written in the 6 hours, however busy other agents or projects kept the hooks, so a session that is still in the window is found. The agent the report is filed under comes from that session's own hook events. @@ -74,12 +74,12 @@ These agents are registered over stdio for that reason: the MCP entry is per use | Agent | Where the server is registered | Recorded by | | --- | --- | --- | -| Claude Code | `~/.claude.json` | Hook | -| Codex | `~/.codex/config.toml` | Hook | +| Claude Code | `~/.claude.json` | Hook, or the MCP server while hooks are off | +| Codex | `~/.codex/config.toml` | Hook, or the MCP server while Codex has not trusted the hooks | | Cursor | `~/.cursor/mcp.json` | MCP server. Cursor's tool hook names the call `MCP:report`, without the server, so it cannot tell our `report` from another server's, and the call goes through the policies like any other. When the daemon cannot be reached, it is denied with every other call | | Copilot CLI | `~/.copilot/mcp-config.json` | MCP server | | OpenCode | `~/.config/opencode/opencode.json` | MCP server | -| Pi | `~/.pi/agent/mcp.json` | MCP server | +| Pi | failproofai's Pi extension | MCP server | | Hermes | Each profile's `config.yaml` | MCP server | | OpenClaw | Each profile's `openclaw.json` | MCP server | | Factory | `~/.factory/mcp.json` | MCP server | @@ -87,6 +87,21 @@ These agents are registered over stdio for that reason: the MCP entry is per use | Antigravity | `~/.gemini/config/mcp_config.json` | MCP server | | Goose | `~/.config/goose/config.yaml` | MCP server | +### When the hooks do not run + +Claude Code and Codex can load the MCP server while skipping failproofai's hooks, and then no hook records a report: + +- Codex 0.129 and later runs a hook from `~/.codex/hooks.json` only once a person trusted it, at its current hash. Hooks in Codex's system config (`/etc/codex/config.toml`, where `failproofai config` puts them when it has sudo) run without trust. +- Claude Code runs no hooks with `disableAllHooks: true`, and only managed ones with a managed `allowManagedHooksOnly: true`. + +So the stdio server records a Claude Code or Codex report itself unless that agent's hook already recorded it: the agent runs its hook before it sends the MCP call, so the server looks for the hook's record of the same report from the last two minutes. A report is recorded once either way, and a person who trusts the hooks while the agent runs changes nothing. A report the server records goes on the session the agent's own files name (Codex's rollout, Claude Code's transcript for that directory). `self-report sync` registers such an agent over stdio, never on the daemon's endpoint, which records nothing for it. `self-report status` says who records each one's reports and, for an untrusted Codex, how to trust the hooks: re-run `failproofai config` and allow sudo, or open `codex` once and approve them. + +### Other agents' servers + +Devin also lists the MCP servers of other agents' configs: `~/.claude.json` (user and per-project servers), a project's `.mcp.json`, and `.cursor/mcp.json` in the directory it runs in. It keeps one server per name, and its own `~/.config/devin/mcp_config.json` wins over the imported ones, except that a `.cursor/mcp.json` in the working directory (so `~/.cursor/mcp.json` when Devin runs in your home directory) wins over Devin's own. Servers under other names are listed beside ours: a `failproofai` or `failproofai-local` that `devin mcp list` shows comes from one of those files (for example a Claude Code project's `mcpServers`), not from failproofai, which only ever writes `failproofai_local`. + +### Cursor approval + If `cursor-agent mcp list` shows `failproofai_local` as "not loaded (needs approval)", run `cursor-agent mcp enable failproofai_local`. cursor-agent asks for approval of servers in a project's `.cursor/mcp.json`, so this happens, for example, when it runs with your home directory as the project. The approval is per project and per entry, so failproofai does not write it for you. The sync and `status` output say so for Cursor. On Antigravity, an MCP call can come through its `call_mcp_tool` wrapper. The hook lets that call through ahead of the policies only when the wrapper names server `failproofai_local` and tool `report`. A wrapped call to any other server goes through the policies as usual. diff --git a/hermes-plugin/plugin.yaml b/hermes-plugin/plugin.yaml index 48517f045..e0a12eb90 100644 --- a/hermes-plugin/plugin.yaml +++ b/hermes-plugin/plugin.yaml @@ -1,5 +1,5 @@ name: failproofai -version: 1.0.18-beta.2 +version: 1.0.18-beta.3 description: Real-time FailproofAI policy enforcement for Hermes manifest_version: 2 api_version: 1 diff --git a/package.json b/package.json index 70af9e288..e6f73afde 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "failproofai", - "version": "1.0.18-beta.2", + "version": "1.0.18-beta.3", "description": "The reliability layer for AI agents: see every failure, stop it in realtime. Policies hooked into 12 agent harnesses — Claude Code, Codex, Cursor, Hermes, OpenClaw and more — block the tool call before it runs. Local dashboard included, no account needed.", "bin": { "failproofai": "./dist/cli.mjs", diff --git a/pi-extension/index.ts b/pi-extension/index.ts index 21b2022e0..08a49b4a9 100644 --- a/pi-extension/index.ts +++ b/pi-extension/index.ts @@ -25,7 +25,7 @@ * spawns extensions with an undefined cwd contract, so paths are resolved * relative to this file via `import.meta.url`, NOT process.cwd(). */ -import { spawnSync } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; import { resolve, dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { existsSync, readdirSync, statSync } from "node:fs"; @@ -333,9 +333,138 @@ interface PiBeforeAgentStartEvent { interface PiExtensionApi { on(event: string, handler: (event: unknown) => unknown): void; + /** Pi's custom tools (every Pi failproofai supports has it; checked anyway). */ + registerTool?(tool: Record): void; } -export default function failproofaiBridge(pi: PiExtensionApi) { +// ── Self Reports ──────────────────────────────────────────────────────────── +// +// Pi has no MCP of its own before 0.99 (its README: "No MCP."), so the +// `failproofai_local` entry in ~/.pi/agent/mcp.json reached no model there, +// with or without `exposure: "direct"`. This extension, which every hooked Pi +// already loads, offers the report tool itself instead, on every Pi version. +// The tool's text and the recording both come from failproofai's own stdio MCP +// server (`failproofai mcp --agent pi`), so this file holds no copy of either: +// at load it asks the server for the tool (none while Self Reports is off), +// and a call is handed to the server, which records it against Pi's session. + +/** Pi spells it like Claude Code: one of the names the hook lets past every policy. */ +const SELF_REPORT_PI_TOOL = "mcp__failproofai_local__report"; + +interface SelfReportTool { + description: string; + inputSchema: Record; + instructions?: string; +} + +/** Send JSON-RPC lines to `failproofai mcp --agent pi`; resolves with the replies by id. */ +function selfReportServer(lines: unknown[], cwd: string, timeoutMs: number): Promise>> { + const { cmd, args } = resolveSpawn(); + return new Promise((resolveRun) => { + const replies = new Map>(); + let out = ""; + let settled = false; + let child: ReturnType; + try { + child = spawn(cmd, [...args, "mcp", "--agent", "pi"], { cwd, stdio: ["pipe", "pipe", "ignore"] }); + } catch { + resolveRun(replies); + return; + } + const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs); + child.stdout?.on("data", (b: Buffer) => (out += b.toString("utf8"))); + const done = () => { + if (settled) return; + settled = true; + clearTimeout(timer); + for (const line of out.split("\n")) { + try { + const msg = JSON.parse(line) as { id?: unknown; result?: Record }; + if (typeof msg.id === "number" && msg.result) replies.set(msg.id, msg.result); + } catch { + // not a reply + } + } + resolveRun(replies); + }; + child.on("error", done); + child.on("close", done); + child.stdin?.on("error", () => {}); + child.stdin?.end(lines.map((l) => JSON.stringify(l)).join("\n") + "\n"); + }); +} + +const SELF_REPORT_INIT = { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "failproofai-pi-extension", version: "1" } }, +}; + +/** The report tool as the server offers it right now, or null (off, or no server). */ +async function selfReportToolFromServer(): Promise { + const replies = await selfReportServer( + [SELF_REPORT_INIT, { jsonrpc: "2.0", method: "notifications/initialized" }, { jsonrpc: "2.0", id: 2, method: "tools/list" }], + process.cwd(), + 10_000, + ); + const tools = replies.get(2)?.tools; + const tool = Array.isArray(tools) ? (tools[0] as Record | undefined) : undefined; + if (!tool || typeof tool.description !== "string" || !tool.inputSchema || typeof tool.inputSchema !== "object") return null; + const instructions = replies.get(1)?.instructions; + return { + description: tool.description, + inputSchema: tool.inputSchema as Record, + ...(typeof instructions === "string" ? { instructions } : {}), + }; +} + +/** The first non-empty string among `keys` (the server accepts the same aliases). */ +function selfReportPick(args: Record, keys: string[]): string { + for (const k of keys) { + const v = args[k]; + if (typeof v === "string" && v.trim() !== "") return v; + } + return ""; +} + +function registerSelfReportTool(pi: PiExtensionApi, tool: SelfReportTool): void { + if (typeof pi.registerTool !== "function") return; + pi.registerTool({ + name: SELF_REPORT_PI_TOOL, + label: "Report (FailproofAI)", + description: tool.description, + // The server's instructions go into Pi's system prompt, as an MCP client + // that honours them would put them. + ...(tool.instructions ? { promptSnippet: "Report to FailproofAI when you are blocked", promptGuidelines: [tool.instructions] } : {}), + parameters: tool.inputSchema, + // A model that guessed the argument names still reports (contract §3). + prepareArguments: (raw: unknown) => { + const a = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record) : {}; + return { + category: selfReportPick(a, ["category", "type", "kind"]), + detail: selfReportPick(a, ["detail", "summary", "sentence", "message", "description", "reason", "text", "details"]), + }; + }, + async execute(_id: string, params: Record, _signal: unknown, _update: unknown, ctx?: { cwd?: string }) { + const replies = await selfReportServer( + [ + SELF_REPORT_INIT, + { jsonrpc: "2.0", method: "notifications/initialized" }, + { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "report", arguments: params } }, + ], + ctx?.cwd ?? process.cwd(), + 20_000, + ); + const content = replies.get(2)?.content; + const first = Array.isArray(content) ? (content[0] as { text?: unknown } | undefined) : undefined; + const text = typeof first?.text === "string" ? first.text : "Recorded."; + return { content: [{ type: "text", text }], details: {} }; + }, + }); +} + +export default async function failproofaiBridge(pi: PiExtensionApi) { // tool_call → PreToolUse. Block tool execution when failproofai denies. pi.on("tool_call", (event: unknown): unknown => { const e = event as PiToolCallEvent; @@ -534,4 +663,12 @@ export default function failproofaiBridge(pi: PiExtensionApi) { if (sessionId) pendingStopBlockBySession.delete(sessionId); return undefined; }); + + // Last, so the policy hooks above are in place whatever this does. + try { + const tool = await selfReportToolFromServer(); + if (tool) registerSelfReportTool(pi, tool); + } catch (err) { + debug(`self-report tool not registered: ${err instanceof Error ? err.message : String(err)}`); + } } diff --git a/sdk/python/failproofai_sdk/_self_report.py b/sdk/python/failproofai_sdk/_self_report.py index dab64a000..a7ed5ac98 100644 --- a/sdk/python/failproofai_sdk/_self_report.py +++ b/sdk/python/failproofai_sdk/_self_report.py @@ -72,9 +72,12 @@ ) _PREAMBLE = ( - "Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot " - "make progress on your own; do not call it for normal work, clarifying questions or a " - "single error. One call per distinct problem.\n" + "Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever " + "something stops you that you cannot fix yourself, for example a missing, invalid or " + "expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, " + "information or access you cannot get, or a request you cannot do here. Do not call it for " + "normal work, clarifying questions or an error you then fixed. One call per distinct " + "problem.\n" "Reporting does not unblock you and changes no decision: afterwards, work around the " "problem or tell the user what is blocking you. There is no need to mention this report " "to the user." diff --git a/sdk/python/tests/test_self_report.py b/sdk/python/tests/test_self_report.py index beb133e4c..8c543bdde 100644 --- a/sdk/python/tests/test_self_report.py +++ b/sdk/python/tests/test_self_report.py @@ -12,7 +12,7 @@ from failproofai_sdk import _runtime, _self_report from failproofai_sdk._events import EventNamespace -EXPECTED_DEFAULT_DESCRIPTION = """Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; do not call it for normal work, clarifying questions or a single error. One call per distinct problem. +EXPECTED_DEFAULT_DESCRIPTION = """Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. Categories: diff --git a/sdk/typescript/src/self-report-spec.ts b/sdk/typescript/src/self-report-spec.ts index f4f5983f6..7994c4475 100644 --- a/sdk/typescript/src/self-report-spec.ts +++ b/sdk/typescript/src/self-report-spec.ts @@ -68,8 +68,10 @@ export const MAX_CATEGORY_DESCRIPTION = 500; export const MAX_GUIDANCE = 2000; const PREAMBLE = - "Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; " + - "do not call it for normal work, clarifying questions or a single error. One call per distinct problem.\n" + + "Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you " + + "cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP " + + "server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for " + + "normal work, clarifying questions or an error you then fixed. One call per distinct problem.\n" + "Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what " + "is blocking you. There is no need to mention this report to the user."; diff --git a/sdk/typescript/test/self-report.test.ts b/sdk/typescript/test/self-report.test.ts index 0306bb7a8..512377d20 100644 --- a/sdk/typescript/test/self-report.test.ts +++ b/sdk/typescript/test/self-report.test.ts @@ -71,7 +71,7 @@ const quietLogger = () => { }; const DEFAULT_DESCRIPTION = [ - "Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; do not call it for normal work, clarifying questions or a single error. One call per distinct problem.", + "Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem.", "Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user.", "", "Categories:", diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 717bd18c7..64e139cda 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1413,6 +1413,12 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo return operands.length > 1 && namesState(operands[operands.length - 1]); } + // `yq -i` edits in place. + if (head === "yq" && args.some((a) => a === "-i" || a.startsWith("--inplace") || /^-[A-Za-z]*i[A-Za-z]*$/.test(a))) return true; + + // A `python -c` whose program `pythonCodeOnlyReads` vetted, now the marker. + if (PYTHON_HEAD_RE.test(head) && readOnlyPythonMarker !== null && args.includes(readOnlyPythonMarker)) return false; + // `git` normally carries the path as prose in a message or a body. if (head === "git") { const subcommand = gitSubcommand(args); @@ -2637,6 +2643,328 @@ function blockWorkOnMain(ctx: PolicyContext): PolicyResult { * deny is what actually happened on every machine and the allow never ran. The * merge keeps the behaviour users have. */ +// -- block-failproofai-commands: arguments that never run -- +// +// Both halves of this guard read the command without knowing where quoting +// ends, which is what makes them hard to fool with `fail"proof"ai`. The price +// was paid by reads and by text: `jq '.categories | length' ` split at +// the `|` inside the filter and judged `length'` an unknown, destructive +// command; `grep -E '(failproofai_local|x)' f` split at the `(` and saw the +// binary in command position; a heredoc writing notes that mention the CLI +// was judged line by line as if it were a script. Before either half looks, +// the command is rewritten so only those inert pieces disappear: +// +// - a quoted argument of a command that never executes its arguments (the +// grep family, jq, yq), unless it names the state or holds a substitution; +// - the body of a heredoc fed to a command that only writes it out (`cat`, +// `tee`, `:`), when nothing in the same command could run what it wrote; +// - the program of a `python -c` that can only read (`pythonCodeOnlyReads`), +// replaced by a per-call marker that `simpleCommandDestroys` reads as a +// reader. +// +// Anything the scan does not fully understand (an unbalanced quote, a heredoc +// with no end) leaves the command exactly as it was, so a confusing command is +// judged as strictly as before. + +/** Commands that never execute an argument: their quoted operands are data. */ +const INERT_ARGUMENT_HEADS = new Set(["grep", "egrep", "fgrep", "rg", "jq"]); + +/** Commands a heredoc body can be fed to without the body running. */ +const HEREDOC_DATA_HEADS = new Set(["cat", "tee", ":"]); + +/** + * Command words that run code they are handed, so a heredoc written by another + * part of the same command could be executed by them, and a body piped to them + * runs. Also any command word that is a path (`/tmp/p.sh`, `./p.sh`). + */ +const CODE_RUNNING_HEADS = new Set([ + "sh", "bash", "zsh", "dash", "ksh", "fish", "ash", "csh", "tcsh", "source", ".", "eval", "exec", + "xargs", "env", "sudo", "doas", "su", "ssh", "script", "watch", "nohup", "setsid", "timeout", "nice", + "node", "bun", "deno", "perl", "ruby", "php", "lua", "npx", "bunx", "pnpx", "npm", "pnpm", "yarn", + "make", "chmod", "crontab", "at", "batch", "systemd-run", "launchctl", +]); + +const PYTHON_HEAD_RE = /^python(?:\d+(?:\.\d+)?)?$/; + +/** A word of a command, with where it sits in the raw text. */ +interface ShellWord { + /** The word with its quotes removed (`fail"proof"ai` → `failproofai`). */ + value: string; + start: number; + end: number; + /** Any part of it was quoted. */ + quoted: boolean; + /** Its raw text contains `$(`, `${` or a backtick, quoted or not. */ + substitutes: boolean; +} + +/** A simple command: its words, and whether a `|` follows it. */ +interface ShellSimple { + words: ShellWord[]; + pipedOut: boolean; + pipedIn: boolean; + /** Heredocs opened in this command: delimiter, and the raw span of the body (with its end line). */ + /** Raw span of each body; `expands` when an unquoted delimiter lets `$(…)` or a backtick in it run. */ + heredocs: Array<{ bodyStart: number; bodyEnd: number; expands: boolean }>; +} + +/** + * Split `cmd` into simple commands the way a shell would, honouring quotes, + * or null when it cannot be done with confidence (unbalanced quotes, a + * heredoc without its end line, nested `$(` inside quotes it would have to + * follow). Separators: `;`, `&`, `|`, newline and the brackets of a subshell, + * brace group or substitution. + */ +function scanShellCommands(cmd: string): ShellSimple[] | null { + const out: ShellSimple[] = []; + let words: ShellWord[] = []; + let heredocs: ShellSimple["heredocs"] = []; + let pendingHeredocs: Array<{ delim: string; strip: boolean; quoted: boolean; owner: number }> = []; + let pipedIn = false; + let cur: ShellWord | null = null; + const flushWord = (end: number) => { + if (cur) { + cur.end = end; + words.push(cur); + cur = null; + } + }; + const flushCommand = (pipedOut: boolean) => { + if (words.length > 0 || heredocs.length > 0) out.push({ words, pipedOut, pipedIn, heredocs }); + pipedIn = pipedOut; + words = []; + heredocs = []; + }; + let i = 0; + while (i < cmd.length) { + const c = cmd[i]; + if (c === "\n") { + flushWord(i); + // Heredoc bodies start on the line after their operator. + let pos = i + 1; + for (const h of pendingHeredocs) { + const bodyStart = pos; + let found = false; + while (pos <= cmd.length) { + const nl = cmd.indexOf("\n", pos); + const lineEnd = nl === -1 ? cmd.length : nl; + const line = cmd.slice(pos, lineEnd); + const next = nl === -1 ? cmd.length : nl + 1; + if ((h.strip ? line.replace(/^\t+/, "") : line) === h.delim) { + const body = cmd.slice(bodyStart, pos); + const span = { bodyStart, bodyEnd: lineEnd, expands: !h.quoted && /\$\(|`/.test(body) }; + // The command that opened it, which a `;` may already have ended. + if (h.owner < out.length) out[h.owner].heredocs.push(span); + else heredocs.push(span); + pos = next; + found = true; + break; + } + if (nl === -1) break; + pos = next; + } + if (!found) return null; + } + const hadHeredocs = pendingHeredocs.length > 0; + pendingHeredocs = []; + flushCommand(false); + i = hadHeredocs ? pos : i + 1; + continue; + } + if (c === "\\") { + if (!cur) cur = { value: "", start: i, end: i, quoted: true, substitutes: false }; + if (cmd[i + 1] === "\n") { + i += 2; + continue; + } + cur.value += cmd[i + 1] ?? ""; + i += 2; + continue; + } + if (c === "'" || c === '"' || (c === "$" && cmd[i + 1] === "'")) { + if (!cur) cur = { value: "", start: i, end: i, quoted: true, substitutes: false }; + cur.quoted = true; + if (c === "$") { + const close = cmd.indexOf("'", i + 2); + if (close === -1) return null; + cur.value += decodeAnsiC(cmd.slice(i + 2, close)); + i = close + 1; + continue; + } + if (c === "'") { + const close = cmd.indexOf("'", i + 1); + if (close === -1) return null; + cur.value += cmd.slice(i + 1, close); + i = close + 1; + continue; + } + let j = i + 1; + while (j < cmd.length && cmd[j] !== '"') { + if (cmd[j] === "\\") j++; + else if (cmd[j] === "`" || (cmd[j] === "$" && (cmd[j + 1] === "(" || cmd[j + 1] === "{"))) cur.substitutes = true; + j++; + } + if (j >= cmd.length) return null; + cur.value += cmd.slice(i + 1, j).replace(/\\(["\\$`])/g, "$1"); + i = j + 1; + continue; + } + if (c === "<" && cmd[i + 1] === "<" && cmd[i + 2] !== "<") { + flushWord(i); + let j = i + 2; + const strip = cmd[j] === "-"; + if (strip) j++; + while (cmd[j] === " " || cmd[j] === "\t") j++; + const m = /^(?:'([^'\n]*)'|"([^"\n]*)"|([^\s;&|<>()]+))/.exec(cmd.slice(j)); + if (!m) return null; + const raw = m[1] ?? m[2] ?? m[3]; + pendingHeredocs.push({ delim: raw.replace(/\\/g, ""), strip, quoted: m[3] === undefined || raw.includes("\\"), owner: out.length }); + words.push({ value: "<<", start: i, end: j, quoted: false, substitutes: false }); + i = j + m[0].length; + continue; + } + if (/[;&|(){}`]/.test(c) || (c === "$" && cmd[i + 1] === "(")) { + flushWord(i); + flushCommand(c === "|" && cmd[i + 1] !== "|"); + i += c === "$" ? 2 : c === "|" || c === "&" ? (cmd[i + 1] === c ? 2 : 1) : 1; + continue; + } + if (c === " " || c === "\t" || c === "\r") { + flushWord(i); + i++; + continue; + } + if (c === "<" || c === ">") { + flushWord(i); + let j = i; + while (cmd[j] === "<" || cmd[j] === ">" || cmd[j] === "|" || cmd[j] === "&") j++; + words.push({ value: cmd.slice(i, j), start: i, end: j, quoted: false, substitutes: false }); + i = j; + continue; + } + if (!cur) cur = { value: "", start: i, end: i, quoted: false, substitutes: false }; + if (c === "$" && cmd[i + 1] === "{") cur.substitutes = true; + cur.value += c; + i++; + } + if (pendingHeredocs.length > 0) return null; + flushWord(cmd.length); + flushCommand(false); + return out; +} + +/** The command word of a simple command (after assignments and runners), or undefined. */ +function scannedHead(words: ShellWord[]): { word: ShellWord; at: number } | undefined { + for (let i = 0; i < words.length; i++) { + const v = words[i].value; + if (/^[<>]/.test(v)) { + i++; // and its target + continue; + } + if (ENV_ASSIGNMENT_RE.test(v) || SHELL_KEYWORD_PREFIXES.has(v)) continue; + return { word: words[i], at: i }; + } + return undefined; +} + +/** + * True when a `python -c` program can only read files: it imports nothing + * beyond json/sys/pprint/tomllib, names no dunder, no escape sequence that + * could spell another name, no call that writes, deletes, renames, runs or + * looks a name up dynamically, and every `open(` is a read. + */ +function pythonCodeOnlyReads(code: string): boolean { + if (code.length > 2000 || code.includes("__")) return false; + if (/\\(?![nt])/.test(code)) return false; + const imported = [ + ...[...code.matchAll(/\bfrom\s+([\w.]+)\s+import\b/g)].map((m) => m[1]), + ...[...code.matchAll(/\bimport\s+([\w.]+(?:\s*,\s*[\w.]+)*)/g)].flatMap((m) => m[1].split(/\s*,\s*/)), + ]; + if (/\bimport\b/.test(code) && imported.length === 0) return false; + if (imported.some((m) => !["json", "sys", "pprint", "tomllib"].includes(m))) return false; + const FORBIDDEN = + /\b(?:exec|eval|compile|getattr|setattr|delattr|globals|locals|vars|breakpoint|memoryview|input|help|write|writelines|truncate|unlink|remove|rmdir|rmtree|rename|renames|replace|chmod|chown|symlink|link|mkdir|makedirs|system|popen|spawn\w*|fork|kill|modules|stdin|path_hooks|meta_path|settrace|setprofile|exit)\b/; + if (FORBIDDEN.test(code)) return false; + // Every `open` is a call, and every call reads. + const opens = [...code.matchAll(/\bopen\b/g)]; + for (const m of opens) { + const after = code.slice(m.index! + 4); + if (!/^\s*\(/.test(after)) return false; + let depth = 0; + let end = -1; + let topComma = -1; + for (let k = after.indexOf("("); k < after.length; k++) { + const ch = after[k]; + if (ch === "(" || ch === "[" || ch === "{") depth++; + else if (ch === ")" || ch === "]" || ch === "}") { + depth--; + if (depth === 0) { + end = k; + break; + } + } else if (ch === "," && depth === 1 && topComma === -1) topComma = k; + } + if (end === -1) return false; + if (topComma !== -1) { + const rest = after.slice(topComma + 1, end); + const READ_ARG = String.raw`\s*(?:(?:mode\s*=\s*)?['"](?:r|rb|rt|br|tr)['"]|encoding\s*=\s*['"][A-Za-z0-9_-]+['"])\s*`; + if (!new RegExp(`^${READ_ARG}(?:,${READ_ARG})*$`).test(rest)) return false; + } + } + return true; +} + +/** + * `cmd` with its inert pieces taken out (see above), and the marker that now + * stands for a read-only `python -c` program, or `cmd` unchanged. + */ +function withoutInertArguments(cmd: string, marker: string): string { + const scanned = scanShellCommands(cmd); + if (!scanned) return cmd; + const cuts: Array<{ start: number; end: number; text: string }> = []; + const heads = scanned.map((s) => scannedHead(s.words)); + const anyCodeRunner = heads.some((h) => { + if (!h) return false; + const base = h.word.value.slice(h.word.value.lastIndexOf("/") + 1); + return CODE_RUNNING_HEADS.has(base) || h.word.value.includes("/") || PYTHON_HEAD_RE.test(base); + }); + scanned.forEach((simple, n) => { + const head = heads[n]; + if (!head) return; + const base = head.word.value.slice(head.word.value.lastIndexOf("/") + 1); + const args = simple.words.slice(head.at + 1); + // rg runs a preprocessor named by `--pre`. + if (INERT_ARGUMENT_HEADS.has(base) && !(base === "rg" && args.some((w) => w.value.startsWith("--pre")))) { + args.forEach((w, k) => { + const prev = k === 0 ? simple.words[head.at] : args[k - 1]; + if (!w.quoted || w.substitutes || /^[<>]/.test(prev.value)) return; + if (FAILPROOFAI_STATE_PATH_RE.test(w.value) || globCouldNameState(w.value)) return; + cuts.push({ start: w.start, end: w.end, text: "''" }); + }); + } + if (PYTHON_HEAD_RE.test(base)) { + const c = args.findIndex((w) => w.value === "-c"); + const code = c === -1 ? undefined : args[c + 1]; + if (code && !code.substitutes && pythonCodeOnlyReads(code.value)) { + cuts.push({ start: code.start, end: code.end, text: marker }); + } + } + if (simple.heredocs.length > 0 && HEREDOC_DATA_HEADS.has(base) && !simple.pipedOut && !anyCodeRunner) { + for (const h of simple.heredocs) if (!h.expands) cuts.push({ start: h.bodyStart, end: h.bodyEnd, text: "" }); + } + }); + if (cuts.length === 0) return cmd; + cuts.sort((a, b) => b.start - a.start); + let result = cmd; + let floor = Infinity; + for (const cut of cuts) { + if (cut.end > floor) return cmd; // overlapping pieces: not understood + result = result.slice(0, cut.start) + cut.text + result.slice(cut.end); + floor = cut.start; + } + return result; +} + function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // A file tool reaches the state without a shell at all. Writing // `{"enabledPolicies":[]}` over `~/.failproofai/policies-config.json`, or an @@ -2665,7 +2993,21 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { return allow(); } if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx); + // Per call, so no command can spell it. + const marker = `fpReadOnlyPython${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`; + const cmd = withoutInertArguments(getCommand(ctx), marker); + readOnlyPythonMarker = marker; + try { + return judgeFailproofaiCommand(cmd); + } finally { + readOnlyPythonMarker = null; + } +} + +/** The marker standing for a read-only `python -c` program in the command being judged. */ +let readOnlyPythonMarker: string | null = null; + +function judgeFailproofaiCommand(cmd: string): PolicyResult { // The raw command AND its shell-unescaped form: a shell strips quotes and // backslashes before running the binary, so `fail\proofai config --pause` // reaches the pause CLI even though the literal name is broken. diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts index 4cd1cf469..b650e2de8 100644 --- a/src/hooks/self-report-cli.ts +++ b/src/hooks/self-report-cli.ts @@ -34,6 +34,13 @@ import { import { INTEGRATION_TYPES } from "./types"; import { daemonSocketPresent, isDaemonConfigured } from "./daemon-client"; import { SELF_REPORT_RECEIPT_ENV, SELF_REPORT_RECEIPT_PREFIX } from "./self-report-mcp"; +import { + SELF_REPORT_HOOK_RECORDED_AGENTS, + claudeHooksBlockedReason, + codexReportHookRuns, + selfReportHookState, + type SelfReportHookState, +} from "./self-report-hook-trust"; import { SELF_REPORT_CURSOR_APPROVAL_HINT, probeSelfReportHttp, @@ -65,6 +72,8 @@ export interface SelfReportCliDeps { sync?: () => Promise; /** Override (tests): is a daemon configured here, or its socket file present? */ daemonExpected?: () => boolean; + /** Who records a hook-recorded agent's reports (tests; default `selfReportHookState`). */ + hookState?: (agent: string) => SelfReportHookState; /** Skip the agent sync after enable/disable (tests). */ skipSync?: boolean; cwd?: string; @@ -153,6 +162,7 @@ function selfReportRegistrationLines( rows: readonly SelfReportRegistration[], health: ReadonlyMap, owned: ReadonlyMap, + recorders: ReadonlyMap = new Map(), ): string[] { const hooked = rows.filter((r) => r.hooked || r.registered || r.conflict || r.error); if (hooked.length === 0) return ["Agents: none with failproofai hooks"]; @@ -167,13 +177,23 @@ function selfReportRegistrationLines( const ok = port !== null && health.get(port) === true; const mine = ok && owned.get(port!) === true; state = `http ${r.endpoint ?? "?"} ${mine ? "(answering)" : ok ? "(answering, but NOT this home's daemon)" : "(NOT answering)"}`; + } else if (r.registered && r.transport === "extension") { + state = "tool offered by failproofai's Pi extension (loaded with its hooks)"; } else if (r.registered) { const ok = !!r.endpoint && selfReportCommandRunnable(r.endpoint); state = `stdio ${r.endpoint ?? "?"} ${ok ? "(runnable)" : "(NOT runnable)"}`; } else state = r.hooked ? "not registered" : "registered, no hooks"; if (r.registered && !r.hooked) state += ", no hooks"; const line = ` ${r.agent.padEnd(12)} ${state}`; - return r.agent === "cursor" && r.registered ? [line, ` ${"".padEnd(12)} ${SELF_REPORT_CURSOR_APPROVAL_HINT}`] : [line]; + const pad = ` ${"".padEnd(12)} `; + if (r.agent === "cursor" && r.registered) return [line, `${pad}${SELF_REPORT_CURSOR_APPROVAL_HINT}`]; + const recorder = recorders.get(r.agent); + if (recorder && r.registered) { + return recorder.recorder === "hook" + ? [line, `${pad}reports recorded by its hook`] + : [line, `${pad}reports recorded by the MCP server: ${recorder.reason}.`, `${pad}${recorder.fix}`]; + } + return [line]; }).flat(), ]; } @@ -188,9 +208,13 @@ function selfReportStranded( r: SelfReportRegistration, health: ReadonlyMap, owned: ReadonlyMap, + recorders: ReadonlyMap = new Map(), ): boolean { if (!r.registered || r.transport !== "http") return false; if (!selfReportHttpAllowed(r.agent)) return true; + // The daemon's endpoint records nothing for Claude Code or Codex, so one + // whose hook will not run (an untrusted Codex) would lose every report there. + if (recorders.get(r.agent)?.recorder === "server") return true; const port = selfReportUrlPort(r.endpoint); return port === null || health.get(port) !== true || owned.get(port) !== true; } @@ -239,11 +263,21 @@ async function selfReportStatus(deps: SelfReportCliDeps): Promise(); + for (const agent of SELF_REPORT_HOOK_RECORDED_AGENTS) { + if (!rows.some((r) => r.agent === agent && (r.registered || r.hooked))) continue; + try { + const hooked = (a: string) => rows.some((r) => r.agent === a && r.hooked); + recorders.set(agent, deps.hookState ? deps.hookState(agent) : selfReportHookState(agent, { userHooksInstalled: hooked })); + } catch { + // unknown: show nothing for it + } + } // An agent left on the daemon's HTTP endpoint after the daemon died would // have no report tool, and one on a port another home's daemon holds would // report into that home. Move it (live check: stdio unless this home's // daemon serves the endpoint). - if (settings.enabled && !deps.skipSync && rows.some((r) => selfReportStranded(r, health, owned))) { + if (settings.enabled && !deps.skipSync && rows.some((r) => selfReportStranded(r, health, owned, recorders))) { try { const results = await (deps.sync ?? (() => syncSelfReportMcp({ quiet: true })))(); if (selfReportSyncChanged(results)) { @@ -262,7 +296,7 @@ async function selfReportStatus(deps: SelfReportCliDeps): Promise { const agentFlag = selfReportFlag(args, "--agent"); if (agentFlag.error || !agentFlag.value) { @@ -383,9 +429,12 @@ async function selfReportTest(args: string[], deps: SelfReportCliDeps): Promise< const cwd = deps.cwd ?? process.cwd(); const cli = selfReportCliCommand(deps); - if (SELF_REPORT_SERVER_RECORDS.includes(agent)) { - // This agent's hooks do not see MCP calls: the MCP server records. Drive - // the stdio server exactly as the agent would. + if ( + SELF_REPORT_SERVER_RECORDS.includes(agent) || + (SELF_REPORT_HOOK_RECORDED_AGENTS.includes(agent) && selfReportTestHookSkipped(agent, cwd, deps)) + ) { + // This agent's hooks do not see MCP calls, or will not run (an untrusted + // Codex): the MCP server records. Drive the stdio server as the agent would. const dir = customAgentsEventsDir(); const stdin = [ { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "failproofai-self-report-test", version: "1" } } }, diff --git a/src/hooks/self-report-hook-trust.ts b/src/hooks/self-report-hook-trust.ts new file mode 100644 index 000000000..e4b2bed01 --- /dev/null +++ b/src/hooks/self-report-hook-trust.ts @@ -0,0 +1,218 @@ +/** + * Self Reports for the agents whose HOOK records the report (Claude Code and + * Codex, contract §8): will that hook actually run? + * + * Both can skip failproofai's hooks while still loading its MCP server: + * + * - Codex ≥0.129 runs a `hooks.json` hook only once a person trusted it at its + * current hash (`codexHookTrust`). An untrusted hook never runs, so a report + * would be lost. Hooks in Codex's system config run without trust. + * - Claude Code runs no hooks with `disableAllHooks: true`, and only managed + * ones with a managed `allowManagedHooksOnly: true`. + * + * Two uses, and only the second decides whether a report is recorded: + * + * - `self-report sync` registers such an agent on the daemon's HTTP endpoint + * (which records nothing for it) only when its user-scope hook will run, and + * over stdio otherwise. `status` shows the state and how to fix it. + * - The stdio server records a Claude Code or Codex report itself unless the + * hook already did (`selfReportHookRecordedRecently`). The agent runs its + * PreToolUse hook before it sends the MCP call, so the hook's row is on disk + * first. Asking what happened, rather than predicting it from trust state, + * is what keeps a report from being lost or counted twice when the + * prediction is wrong (a Codex whose hash scheme changed, say) or the state + * changes while the agent runs (a person trusts the hooks mid-session). + */ +import { existsSync, readFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { + CODEX_UNTRUSTED_NOTICE, + codexGatesHookTrust, + codexHome, + codexSystemHooksPresent, + detectCodexVersion, + failproofaiCodexHookIdentities, + parseCodexTrustedHashes, +} from "./codex-system-hooks"; +import { claudeConfigDir, getIntegration } from "./integrations"; +import { getHookActivityEntriesSince } from "./hook-activity-store"; +import { selfReportArgs } from "./self-report"; +import { selfReportClip } from "./self-report-names"; + +/** The agents whose hook, when it runs, is the recorder. */ +export const SELF_REPORT_HOOK_RECORDED_AGENTS: readonly string[] = ["claude", "codex"]; + +export type SelfReportHookState = + | { recorder: "hook" } + | { recorder: "server"; reason: string; fix: string }; + +export interface SelfReportHookTrustDeps { + /** Codex: the trust check (default `codexHookTrust`'s pieces, at user scope). */ + codexVersion?: () => string | null; + codexSystemPresent?: () => boolean; + /** Claude Code: managed settings file (default per platform). */ + claudeManagedSettingsPath?: string | null; + /** Hooks installed at user scope (default: the integration's own check). */ + userHooksInstalled?: (agent: string) => boolean; +} + +// ── Codex ─────────────────────────────────────────────────────────────────── + +/** `.codex/hooks.json` files a Codex started in `cwd` reads: the user's, then the project's up the tree. */ +function codexHooksFiles(cwd: string | undefined): string[] { + const files = [resolve(codexHome(), "hooks.json")]; + if (cwd) { + let dir = resolve(cwd); + for (;;) { + const candidate = resolve(dir, ".codex", "hooks.json"); + if (!files.includes(candidate)) files.push(candidate); + const up = dirname(dir); + if (up === dir) break; + dir = up; + } + } + return files; +} + +/** + * Whether Codex will run failproofai's PreToolUse hook (the one that records a + * report): it is in Codex's system config, or in a hooks.json Codex reads and + * either trusted at its current hash or on a Codex too old to ask. + */ +export function codexReportHookRuns(cwd?: string, deps: SelfReportHookTrustDeps = {}): boolean { + try { + if ((deps.codexSystemPresent ?? codexSystemHooksPresent)()) return true; + } catch { + // unreadable system config: fall through to hooks.json + } + let trusted: Map | undefined; + let version: string | null | undefined; + for (const file of codexHooksFiles(cwd)) { + const pre = failproofaiCodexHookIdentities(file).filter((h) => h.key.includes(":pre_tool_use:")); + if (pre.length === 0) continue; + if (version === undefined) version = (deps.codexVersion ?? detectCodexVersion)(); + if (!codexGatesHookTrust(version)) return true; + if (!trusted) { + try { + trusted = parseCodexTrustedHashes(readFileSync(resolve(codexHome(), "config.toml"), "utf8")); + } catch { + trusted = new Map(); + } + } + if (pre.some((h) => trusted!.get(h.key) === h.hash)) return true; + } + return false; +} + +// ── Claude Code ───────────────────────────────────────────────────────────── + +function claudeManagedSettingsPath(): string | null { + const override = process.env.FAILPROOFAI_CLAUDE_MANAGED_SETTINGS; + if (override !== undefined) return override.trim() === "" || override === "off" ? null : override; + if (process.platform === "darwin") return "/Library/Application Support/ClaudeCode/managed-settings.json"; + if (process.platform === "linux") return "/etc/claude-code/managed-settings.json"; + return null; +} + +function readJsonObject(path: string | null): Record | null { + if (!path || !existsSync(path)) return null; + try { + const v: unknown = JSON.parse(readFileSync(path, "utf8")); + return v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : null; + } catch { + return null; + } +} + +/** + * Why Claude Code will not run failproofai's user or project hooks, or null + * when nothing stops them. `disableAllHooks` is read with Claude Code's + * precedence (managed, then local, then project, then user: the first layer + * that sets it wins); a managed `allowManagedHooksOnly` stops every hook that + * is not managed, which failproofai's never are. + */ +export function claudeHooksBlockedReason(cwd?: string, deps: SelfReportHookTrustDeps = {}): string | null { + const managed = readJsonObject(deps.claudeManagedSettingsPath !== undefined ? deps.claudeManagedSettingsPath : claudeManagedSettingsPath()); + if (managed?.allowManagedHooksOnly === true) return "managed settings allow only managed hooks (allowManagedHooksOnly)"; + const layers: Array<[string, Record | null]> = [ + ["managed settings", managed], + ...(cwd + ? ([ + [".claude/settings.local.json", readJsonObject(resolve(cwd, ".claude", "settings.local.json"))], + [".claude/settings.json", readJsonObject(resolve(cwd, ".claude", "settings.json"))], + ] as Array<[string, Record | null]>) + : []), + [`${claudeConfigDir()}/settings.json`, readJsonObject(resolve(claudeConfigDir(), "settings.json"))], + ]; + for (const [label, layer] of layers) { + const v = layer?.disableAllHooks; + if (typeof v === "boolean") return v ? `disableAllHooks is set in ${label}` : null; + } + return null; +} + +// ── Both ──────────────────────────────────────────────────────────────────── + +function defaultUserHooksInstalled(agent: string): boolean { + try { + return getIntegration(agent as Parameters[0]).hooksInstalledInSettings("user"); + } catch { + return false; + } +} + +/** + * Who records a report from `agent` registered at user scope: its hook, or (for + * Claude Code and Codex when their user-scope hook will not run) the MCP + * server. Every other agent is recorded by the server and is not asked here. + */ +export function selfReportHookState(agent: string, deps: SelfReportHookTrustDeps = {}): SelfReportHookState { + if (!SELF_REPORT_HOOK_RECORDED_AGENTS.includes(agent)) return { recorder: "hook" }; + const installed = (deps.userHooksInstalled ?? defaultUserHooksInstalled)(agent); + if (agent === "codex") { + if (codexReportHookRuns(undefined, deps)) return { recorder: "hook" }; + return installed + ? { recorder: "server", reason: "Codex has not trusted failproofai's hooks, so it does not run them", fix: CODEX_UNTRUSTED_NOTICE.replace(/\n/g, " ") } + : { recorder: "server", reason: "failproofai's Codex hooks are not installed at user scope", fix: "Run `failproofai policies --install --cli codex`." }; + } + const blocked = claudeHooksBlockedReason(undefined, deps); + if (blocked) { + return { recorder: "server", reason: `Claude Code runs no failproofai hooks: ${blocked}`, fix: "Remove that setting to let failproofai's hooks run." }; + } + if (!installed) { + return { recorder: "server", reason: "failproofai's Claude Code hooks are not installed at user scope", fix: "Run `failproofai policies --install --cli claude`." }; + } + return { recorder: "hook" }; +} + +/** How long after its hook row a report can still be the same call. */ +export const SELF_REPORT_HOOK_DEDUPE_MS = 2 * 60 * 1000; + +/** + * Whether `agent`'s hook already recorded this report: a PreToolUse row from + * that integration, written in the last two minutes, carrying a `selfReport` + * with the same category and detail (as the hook would have clipped them). + * An unreadable activity store reads as "no", so a report is recorded rather + * than lost. + */ +export function selfReportHookRecordedRecently( + agent: string, + args: unknown, + now: number = Date.now(), +): boolean { + const { category, detail } = selfReportArgs(args ?? {}); + const want = { category: selfReportClip(category), detail: selfReportClip(detail) }; + let rows: Array>; + try { + rows = getHookActivityEntriesSince(now - SELF_REPORT_HOOK_DEDUPE_MS) as unknown as Array>; + } catch { + return false; + } + return rows.some((row) => { + if (row.integration !== agent || row.eventType !== "PreToolUse") return false; + const ts = typeof row.timestamp === "number" ? row.timestamp : NaN; + if (!Number.isFinite(ts) || now - ts > SELF_REPORT_HOOK_DEDUPE_MS || ts - now > 60_000) return false; + const sr = row.selfReport as { category?: unknown; detail?: unknown } | undefined; + return !!sr && sr.category === want.category && sr.detail === want.detail; + }); +} diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index e54c7c42e..01414d5d3 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -80,7 +80,7 @@ import { accessSync, constants as fsConstants, existsSync, readFileSync, realpathSync } from "node:fs"; import { execSync } from "node:child_process"; import { homedir, userInfo } from "node:os"; -import { basename, resolve, sep } from "node:path"; +import { basename, dirname, resolve, sep } from "node:path"; import { parse as parseToml } from "smol-toml"; import { applyEdits, modify, parse as parseJsonc, type ParseError } from "jsonc-parser/lib/esm/main.js"; import { isMap, type Document } from "yaml"; @@ -89,6 +89,7 @@ import { codexHome } from "./codex-system-hooks"; import { claudeConfigDir, getIntegration, readYamlDoc, writeYamlDoc, UnreadableAgentConfigError } from "./integrations"; import { daemonSelfReportServer } from "./daemon-client"; +import { selfReportHookState } from "./self-report-hook-trust"; import { resolveSelfReport, selfReportPort, selfReportSettingsFile, SELF_REPORT_SERVER_NAME, SELF_REPORT_SERVER_RECORDS } from "./self-report"; import { listHermesProfiles } from "../../lib/hermes-profiles"; import { listOpenClawProfiles } from "../../lib/openclaw-profiles"; @@ -290,6 +291,12 @@ interface McpTarget { container(parsed: Record): string[]; /** The entry to write, given the container path chosen above. */ entry(t: SelfReportTransport, container: string[]): Record; + /** + * The tool comes from failproofai's own extension for this agent, not from + * an MCP entry (Pi): sync writes none, and takes out one an earlier version + * wrote. + */ + extension?: true; } const plainEntry = (t: SelfReportTransport, urlKey = "url"): Record => @@ -374,9 +381,13 @@ export const SELF_REPORT_MCP_TARGETS: Record = { agent: "pi", format: "json", http: true, paths: () => [resolve(process.env.PI_CODING_AGENT_DIR?.trim() || resolve(homedir(), ".pi", "agent"), "mcp.json")], container: () => ["mcpServers"], - // Pi's default exposure, `codemode`, puts only the server's name in the - // prompt; `direct` declares `report` and its description like a built-in. + // Pi before 0.99 has no MCP at all, so an entry here reached no model on + // the Pi this was verified against (0.85.1). failproofai's Pi extension, + // which a hooked Pi already loads, registers the tool itself + // (pi-extension/index.ts); this file only loses an entry an earlier + // version wrote. The entry shape is kept so that one is recognised. entry: (t) => ({ ...plainEntry(t), exposure: "direct" }), + extension: true, }, hermes: { agent: "hermes", format: "yaml", http: true, @@ -628,7 +639,8 @@ export interface SelfReportMcpResult { agent: IntegrationType; path: string; action: SelfReportMcpAction; - transport: "http" | "stdio" | null; + /** `extension`: the agent's tool comes from failproofai's own extension (Pi). */ + transport: "http" | "stdio" | "extension" | null; status: SelfReportMcpStatus; detail?: string; } @@ -652,6 +664,12 @@ export interface SyncSelfReportMcpOptions { /** The live check (default `selfReportDaemonLive`); asked only when an agent wants the server. */ daemonLive?: (port: number) => Promise; hooksInstalled?: (agent: IntegrationType) => boolean; + /** + * Whether a hook-recorded agent's user-scope hook will run (default + * `selfReportHookState`): only then may it be on the daemon's HTTP endpoint, + * which records nothing for it. + */ + hookRecords?: (agent: IntegrationType) => boolean; settings?: SelfReportMcpSettings; resolveCliPath?: () => string | null; }; @@ -668,6 +686,17 @@ export function resolveSelfReportCliPath(): string | null { } catch { // not on PATH (a daemon's service environment, say) } + // A daemon's service has no login PATH (an nvm node is on no system PATH), + // and it runs the CLI as ` …/failproofai/dist/cli.mjs`, whose name is + // not one an entry can be recognised by. npm puts the `failproofai` link in + // the same bin directory as the node that installed it, so look there, then + // where the daemon looks for the CLI (`global_bin_dirs` in + // crates/failproofaid/src/self_report.rs). Without this the daemon's sync + // had no stdio command and failed every server-recorded agent. + for (const dir of selfReportCliDirs()) { + const candidate = resolve(dir, process.platform === "win32" ? "failproofai.cmd" : "failproofai"); + if (selfReportCommandRunnable(candidate)) return candidate; + } const self = process.argv[1]; if (self && basename(self).toLowerCase().includes("failproofai")) { try { @@ -679,6 +708,15 @@ export function resolveSelfReportCliPath(): string | null { return null; } +/** Bin directories that hold an npm/bun global `failproofai` when PATH does not. */ +export function selfReportCliDirs(env: Record = process.env, execPath = process.execPath, home = homedir()): string[] { + const dirs = [dirname(execPath)]; + const prefix = (env.NPM_CONFIG_PREFIX ?? env.npm_config_prefix)?.trim(); + if (prefix) dirs.push(resolve(prefix, "bin")); + dirs.push(resolve(home, ".npm-global", "bin"), "/usr/local/bin", resolve(home, ".bun", "bin")); + return [...new Set(dirs)]; +} + function defaultHooksInstalled(agent: IntegrationType): boolean { try { const integration = getIntegration(agent); @@ -743,6 +781,9 @@ function applySelfReportMcp(opts: SyncSelfReportMcpOptions, enabled: boolean, da const agents = opts.agents ?? INTEGRATION_TYPES; const hooked = opts.deps?.hooksInstalled ?? defaultHooksInstalled; const also = new Set(opts.alsoHooked ?? []); + const hookRecords = + opts.deps?.hookRecords ?? + ((a: IntegrationType) => selfReportHookState(a, { userHooksInstalled: (x) => hooked(x as IntegrationType) }).recorder === "hook"); let cliPath: string | null | undefined = opts.binaryPath; const results: SelfReportMcpResult[] = []; @@ -761,11 +802,34 @@ function applySelfReportMcp(opts: SyncSelfReportMcpOptions, enabled: boolean, da } const agentHooked = enabled && (also.has(agent) || hooked(agent)); + if (target.extension) { + for (const path of paths) { + try { + const ops = existsSync(path) ? opsFor(target, path) : null; + const cur = ops?.current(); + if (ops && cur?.state === "ours") { + ops.write(null); + results.push({ agent, path, action: "removed", transport: transportOf(cur.entry), status: "ok" }); + } + } catch (err) { + results.push({ agent, path, action: "skipped", transport: null, status: "error", detail: errText(err) }); + } + } + results.push({ + agent, path: "", action: "unchanged", transport: agentHooked ? "extension" : null, + status: enabled && !agentHooked ? "not-hooked" : "ok", + }); + continue; + } + let chosen: SelfReportTransport | null | undefined; const transportFor = (): SelfReportTransport | null => { if (chosen !== undefined) return chosen; chosen = null; - if (daemonHere && selfReportHttpAllowed(agent)) { + // HTTP only while the hook will record: an untrusted Codex, or a Claude + // Code with hooks off, gets stdio, whose server records what the hook + // did not. + if (daemonHere && selfReportHttpAllowed(agent) && hookRecords(agent)) { chosen = { kind: "http", url: selfReportHttpUrl(settings.port, agent) }; } else { if (cliPath === undefined) cliPath = (opts.deps?.resolveCliPath ?? resolveSelfReportCliPath)(); @@ -889,9 +953,9 @@ export interface SelfReportRegistration { path: string; /** failproofai hooks are installed for this agent (user scope). */ hooked: boolean; - /** Our entry is in this file. */ + /** Our entry is in this file (or, for Pi, its extension offers the tool). */ registered: boolean; - transport: "http" | "stdio" | null; + transport: "http" | "stdio" | "extension" | null; /** The URL (http) or command (stdio) our entry points at. */ endpoint: string | null; /** A `failproofai_local` server that is not ours is there. */ @@ -910,6 +974,10 @@ export function selfReportRegistrationStatus( const target = SELF_REPORT_MCP_TARGETS[agent]; if (!target) continue; const isHooked = hooked(agent); + if (target.extension) { + out.push({ agent, path: "", hooked: isHooked, registered: isHooked, transport: isHooked ? "extension" : null, endpoint: null, conflict: false }); + continue; + } let paths: string[] = []; try { paths = target.paths(); diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts index c3e64afc7..cb0b05c0b 100644 --- a/src/hooks/self-report-mcp.ts +++ b/src/hooks/self-report-mcp.ts @@ -22,7 +22,8 @@ * * Top-level names are prefixed for the same bundle reason as self-report.ts. */ -import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeSync, constants as fsConstants } from "node:fs"; +import { closeSync, fsyncSync, mkdirSync, openSync, readdirSync, readSync, renameSync, rmSync, statSync, writeSync, constants as fsConstants } from "node:fs"; +import { homedir } from "node:os"; import { join } from "node:path"; import { createInterface } from "node:readline"; import type { Readable, Writable } from "node:stream"; @@ -224,7 +225,15 @@ export interface SelfReportEventInput { */ export async function writeSelfReportEvent(input: SelfReportEventInput): Promise<{ path: string; event: Record }> { const now = input.now ?? Date.now(); - const match = input.sessionId === undefined ? selfReportFindSessionMatch(input.integration, input.cwd, now) : null; + const match = + input.sessionId === undefined + ? selfReportFindSessionMatch(input.integration, input.cwd, now) ?? + (input.integration === "codex" + ? selfReportCodexRolloutSession(input.cwd, now) + : input.integration === "claude" + ? selfReportClaudeTranscriptSession(input.cwd, now) + : null) + : null; const sessionId = input.sessionId ?? match?.sessionId ?? "unattributed"; const event: Record = { timestamp: new Date(now).toISOString(), @@ -263,6 +272,116 @@ export async function writeSelfReportEvent(input: SelfReportEventInput): Promise return { path: finalPath, event }; } +/** + * Whether this server records a report from `agent`: always for an agent in + * `SELF_REPORT_SERVER_RECORDS`; for Claude Code and Codex, whose hook is the + * recorder, only when that hook did not already record this call — it was + * not trusted (Codex), hooks are off (Claude Code), or none is installed where + * the agent runs. The hook runs before the agent sends the MCP call, so its + * row is already on disk (self-report-hook-trust.ts). + */ +export async function selfReportServerShouldRecord(agent: string, args: unknown, now?: number): Promise { + if (SELF_REPORT_SERVER_RECORDS.includes(agent)) return true; + const { SELF_REPORT_HOOK_RECORDED_AGENTS, selfReportHookRecordedRecently } = await import("./self-report-hook-trust"); + if (!SELF_REPORT_HOOK_RECORDED_AGENTS.includes(agent)) return false; + return !selfReportHookRecordedRecently(agent, args ?? {}, now ?? Date.now()); +} + +/** + * Codex's own record of its newest session in (or around) `cwd`, from its + * rollout files (`$CODEX_HOME/sessions/YYYY/MM/DD/rollout-*.jsonl`, whose first + * line is `session_meta` with the session `id` and `cwd`), for a report its + * hooks never saw: an untrusted Codex runs no hook, so there is no hook row to + * attribute to. The session id is the one Codex's hooks would have carried. + */ +export function selfReportCodexRolloutSession( + cwd: string, + now: number = Date.now(), + home: string = process.env.CODEX_HOME?.trim() || join(homedirForCodex(), ".codex"), +): SelfReportSessionMatch | null { + const dayDirs = new Set(); + for (const t of [now, now - SELF_REPORT_SESSION_WINDOW_MS]) { + const d = new Date(t); + const pad = (n: number) => String(n).padStart(2, "0"); + dayDirs.add(join(home, "sessions", String(d.getFullYear()), pad(d.getMonth() + 1), pad(d.getDate()))); + } + let best: { rank: number; mtime: number; id: string; cwd: string } | null = null; + for (const dir of dayDirs) { + let names: string[]; + try { + names = readdirSync(dir).filter((n) => n.startsWith("rollout-") && n.endsWith(".jsonl")); + } catch { + continue; + } + for (const name of names) { + const file = join(dir, name); + try { + const mtime = statSync(file).mtimeMs; + if (now - mtime > SELF_REPORT_SESSION_WINDOW_MS) continue; + const head = readFirstLine(file); + const meta = JSON.parse(head) as { type?: unknown; payload?: { id?: unknown; cwd?: unknown } }; + if (meta.type !== "session_meta" || typeof meta.payload?.id !== "string" || typeof meta.payload.cwd !== "string") continue; + const rank = selfReportCwdAffinity(cwd, meta.payload.cwd); + if (rank === 0) continue; + if (!best || rank > best.rank || (rank === best.rank && mtime > best.mtime)) { + best = { rank, mtime, id: meta.payload.id, cwd: meta.payload.cwd }; + } + } catch { + // unreadable or not a rollout: skip it + } + } + } + return best ? { sessionId: best.id, cwd: best.cwd } : null; +} + +/** + * Claude Code's newest session in exactly `cwd`, from its transcripts + * (`/projects//.jsonl`), + * for a report its hooks never saw (`disableAllHooks`). + */ +export function selfReportClaudeTranscriptSession( + cwd: string, + now: number = Date.now(), + configDir: string = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedirForCodex(), ".claude"), +): SelfReportSessionMatch | null { + const dir = join(configDir, "projects", cwd.replace(/\/+$/, "").replace(/[^A-Za-z0-9]/g, "-")); + let best: { mtime: number; id: string } | null = null; + let names: string[]; + try { + names = readdirSync(dir).filter((n) => /^[0-9a-f-]{36}\.jsonl$/i.test(n)); + } catch { + return null; + } + for (const name of names) { + try { + const mtime = statSync(join(dir, name)).mtimeMs; + if (now - mtime > SELF_REPORT_SESSION_WINDOW_MS) continue; + if (!best || mtime > best.mtime) best = { mtime, id: name.slice(0, -".jsonl".length) }; + } catch { + // gone since the listing + } + } + return best ? { sessionId: best.id, cwd } : null; +} + +function homedirForCodex(): string { + return process.env.HOME?.trim() || homedir(); +} + +/** The first line of a file, reading at most 1 MiB (session_meta carries the base instructions). */ +function readFirstLine(file: string): string { + const fd = openSync(file, "r"); + try { + const buf = Buffer.alloc(1 << 20); + const n = readSync(fd, buf, 0, buf.length, 0); + const text = buf.subarray(0, n).toString("utf8"); + const nl = text.indexOf("\n"); + return nl < 0 ? text : text.slice(0, nl); + } finally { + closeSync(fd); + } +} + // ── JSON-RPC ──────────────────────────────────────────────────────────────── type SelfReportRpcResponse = Record | null; @@ -306,7 +425,7 @@ export async function handleSelfReportRpc( return ok({ content: [{ type: "text", text: `Unknown tool: ${String(params.name)}` }], isError: true }); } const agent = opts.agent; - if (agent && SELF_REPORT_SERVER_RECORDS.includes(agent) && readEnabledSelfReport()) { + if (agent && readEnabledSelfReport() && (await selfReportServerShouldRecord(agent, params.arguments, opts.now?.()))) { const { category, detail } = selfReportArgs(params.arguments ?? {}); try { const { path } = await writeSelfReportEvent({ diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts index 7c7fd0101..f5429a606 100644 --- a/src/hooks/self-report.ts +++ b/src/hooks/self-report.ts @@ -130,8 +130,10 @@ export function validateSelfReportGuidance(input: unknown): SelfReportValidation // ── The tool (contract §3) ────────────────────────────────────────────────── const SELF_REPORT_DESCRIPTION_HEAD = - "Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; " + - "do not call it for normal work, clarifying questions or a single error. One call per distinct problem.\n" + + "Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you " + + "cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP " + + "server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for " + + "normal work, clarifying questions or an error you then fixed. One call per distinct problem.\n" + "Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is " + "blocking you. There is no need to mention this report to the user."; @@ -175,10 +177,11 @@ function selfReportInstructions( ): string { const names = categories.map((c) => c.name).join(", "); const body = - `FailproofAI records when an agent is stuck. If you get stuck (${names}), call this server's ` + - "`report` tool once with two arguments: `category` (one of those names) and `detail` (one factual " + - "sentence). It does not unblock you: continue, or tell the user what is blocking you. There is no " + - "need to mention the report to the user."; + "FailproofAI records when an agent is blocked. Before your final answer, if something failed that you cannot fix " + + "yourself (a missing or expired token or key, a 401 or 403, a command or tool that keeps failing, information you " + + "cannot get, a request you cannot do), call this server's `report` tool once with `category` (one of: " + + `${names}) and \`detail\` (one factual sentence). Not when the task succeeded. It does not unblock you, and ` + + "there is no need to mention it to the user."; return guidance ? `${body}\n\n${guidance}` : body; } diff --git a/test-fixtures/self-report/description-guidance.golden.txt b/test-fixtures/self-report/description-guidance.golden.txt index a6b185a2a..9cd2c646e 100644 --- a/test-fixtures/self-report/description-guidance.golden.txt +++ b/test-fixtures/self-report/description-guidance.golden.txt @@ -1,4 +1,4 @@ -Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; do not call it for normal work, clarifying questions or a single error. One call per distinct problem. +Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. Categories: diff --git a/test-fixtures/self-report/description.golden.txt b/test-fixtures/self-report/description.golden.txt index 922c27eb9..24a3bf298 100644 --- a/test-fixtures/self-report/description.golden.txt +++ b/test-fixtures/self-report/description.golden.txt @@ -1,4 +1,4 @@ -Report to FailproofAI that you are stuck. Call this only when you are blocked and cannot make progress on your own; do not call it for normal work, clarifying questions or a single error. One call per distinct problem. +Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. Categories: diff --git a/test-fixtures/self-report/instructions-guidance.golden.txt b/test-fixtures/self-report/instructions-guidance.golden.txt index cc0b0dfad..c175a9bc9 100644 --- a/test-fixtures/self-report/instructions-guidance.golden.txt +++ b/test-fixtures/self-report/instructions-guidance.golden.txt @@ -1,3 +1,3 @@ -FailproofAI records when an agent is stuck. If you get stuck (looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure), call this server's `report` tool once with two arguments: `category` (one of those names) and `detail` (one factual sentence). It does not unblock you: continue, or tell the user what is blocking you. There is no need to mention the report to the user. +FailproofAI records when an agent is blocked. Before your final answer, if something failed that you cannot fix yourself (a missing or expired token or key, a 401 or 403, a command or tool that keeps failing, information you cannot get, a request you cannot do), call this server's `report` tool once with `category` (one of: looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure) and `detail` (one factual sentence). Not when the task succeeded. It does not unblock you, and there is no need to mention it to the user. Report a missing repository as missing_context. \ No newline at end of file diff --git a/test-fixtures/self-report/instructions.golden.txt b/test-fixtures/self-report/instructions.golden.txt index 69d973551..2863734e8 100644 --- a/test-fixtures/self-report/instructions.golden.txt +++ b/test-fixtures/self-report/instructions.golden.txt @@ -1 +1 @@ -FailproofAI records when an agent is stuck. If you get stuck (looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure), call this server's `report` tool once with two arguments: `category` (one of those names) and `detail` (one factual sentence). It does not unblock you: continue, or tell the user what is blocking you. There is no need to mention the report to the user. \ No newline at end of file +FailproofAI records when an agent is blocked. Before your final answer, if something failed that you cannot fix yourself (a missing or expired token or key, a 401 or 403, a command or tool that keeps failing, information you cannot get, a request you cannot do), call this server's `report` tool once with `category` (one of: looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure) and `detail` (one factual sentence). Not when the task succeeded. It does not unblock you, and there is no need to mention it to the user. \ No newline at end of file From 0ea26f6b7765252623d6bd5e38ef8ec110be6d72 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Sat, 28 Nov 2026 01:01:04 +0530 Subject: [PATCH 22/54] [self-reports] Lean output, MCP events in the daemon log, sync fix proven end to end - Setup, install, uninstall, enable and disable print one Self Reports line ("on for 12 agents", "off", or the agents not updated); `config` finishes gateway restarts and the sync behind one spinner line and drops the Codex trust notice (`config --status` keeps it, now one line). - `self-report status`: header, working agents, one line per problem with its fix; --verbose has the old detail, --json everything. - Every Self Reports MCP event goes to the daemon log: the HTTP server logs its own; the stdio server and CLI syncs send a one-way `selfReportLog` frame over the daemon socket (250 ms budget, dropped by older daemons). Previews are scrubbed of secrets, then cut to 40 chars. - Tests: the enrolled-config-then-first-Cloud-write sequence and the service-PATH sync, both running the real CLI under a bare PATH. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + __tests__/hooks/config-status.test.ts | 5 +- __tests__/hooks/configure-wizard.test.ts | 11 +- __tests__/hooks/manager.test.ts | 1 + .../hooks/self-report-hook-trust.test.ts | 4 +- __tests__/hooks/self-report-log.test.ts | 272 +++++++++++++++++ __tests__/hooks/self-report.test.ts | 102 +++++-- bin/failproofai.mjs | 65 ++-- crates/PROTOCOL.md | 30 ++ crates/failproofaid/src/self_report.rs | 288 +++++++++++++++++- crates/failproofaid/src/server.rs | 13 + crates/failproofaid/tests/self_report_e2e.rs | 112 +++++++ crates/fpai-collect/src/self_report.rs | 255 +++++++++++++++- crates/fpai-ipc/src/envelope.rs | 81 ++++- crates/fpai-ipc/src/lib.rs | 4 +- docs/self-reports.mdx | 14 +- src/hooks/config-status.ts | 5 +- src/hooks/configure-wizard.ts | 5 +- src/hooks/manager.ts | 12 +- src/hooks/self-report-cli.ts | 231 +++++++++++--- src/hooks/self-report-install.ts | 105 ++++++- src/hooks/self-report-log.ts | 119 ++++++++ src/hooks/self-report-mcp.ts | 40 ++- src/hooks/self-report.ts | 23 ++ src/hooks/setup-finish.ts | 76 +++++ src/hooks/tui.ts | 46 +++ 26 files changed, 1754 insertions(+), 169 deletions(-) create mode 100644 __tests__/hooks/self-report-log.test.ts create mode 100644 src/hooks/self-report-log.ts create mode 100644 src/hooks/setup-finish.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 10904ee2a..21893ace4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ - Self Reports: the tool description and the server's instructions now say to call it before the final answer whenever something the agent cannot fix stopped it, with concrete triggers (a missing or expired token or key, a 401 or 403, a command or tool that keeps failing, information it cannot get, a request it cannot do); weaker models mostly ignored the old wording. Same text in the CLI, the daemon and both SDKs (#1062) - `block-failproofai-commands` no longer blocks reads and mentions it mistook for tampering: a `jq` filter with a `|` in it, a `grep`/`rg` pattern with a `(`, a heredoc that only writes text mentioning the CLI (to a file outside failproofai's state, with nothing in the same command that could run it), and a `python -c` program that can only read. It still denies running the CLI however it is spelled, pausing, uninstalling, and every write, move, delete, `chmod` or redirect into failproofai's state, including `yq -i`, which it had read as a reader (#1062) +- Self Reports output is one line: `config`, `policies --install`/`--uninstall`, `self-report enable` and `disable` print `Self Reports: on for 12 agents` (or `off`, naming any agent that could not be updated) instead of a line per agent and file. `config` finishes its gateway restarts and the Self Reports sync behind one spinner line and keeps only what needs you (a gateway to restart by hand, an agent not updated); it no longer prints the Codex trust notice, which `config --status` now gives in one line, since the MCP server records an untrusted Codex's reports (#1062) +- `failproofai self-report status` is a header, one line of working agents, and one line per agent with a problem and its fix; `--verbose` has the paths, URLs, categories, update time and per-agent transport (and the Cursor approval hint), and `--json` has everything (#1062) +- Self Reports in the daemon's log, so machine logs carry it: every MCP `initialize`, `tools/list` and `tools/call` (agent, category, session, recorded or skipped and why), write failures, unknown categories, unreadable settings and sync results. The stdio server and CLI syncs send theirs over the daemon socket as a new one-way `selfReportLog` message (older daemons drop it; it never waits more than 250 ms); a line carries at most 40 characters of the detail, scrubbed of secrets (#1062) + ### Docs - Self Reports: when Claude Code's or Codex's hooks do not run, Pi's tool coming from failproofai's Pi extension, and where the extra servers in `devin mcp list` come from (Devin also lists other agents' servers, such as a Claude Code project's) (#1062) diff --git a/__tests__/hooks/config-status.test.ts b/__tests__/hooks/config-status.test.ts index ad03ef6dc..4745c9d53 100644 --- a/__tests__/hooks/config-status.test.ts +++ b/__tests__/hooks/config-status.test.ts @@ -778,10 +778,9 @@ describe("config --status — Codex trust", () => { const f = facts({ codex: { kind: "untrusted", path: "/h/.codex/hooks.json", untrusted: 10, total: 10 } }); const lines = renderStatusScreen(f, PLAIN); expect(rowValue(lines, "codex")).toBe("○ Not enforcing: hooks not trusted"); - expect(enforcement(lines).slice(-3)).toEqual([ + expect(enforcement(lines).slice(-2)).toEqual([ "", - "▲ Codex won't run failproofai's hooks until they're trusted.", - " Re-run failproofai config and allow sudo, or open codex once and approve the hooks.", + "▲ Codex won't run failproofai's hooks until they're trusted. · failproofai config", ]); }); diff --git a/__tests__/hooks/configure-wizard.test.ts b/__tests__/hooks/configure-wizard.test.ts index 0b5bbfb20..c3ec81b99 100644 --- a/__tests__/hooks/configure-wizard.test.ts +++ b/__tests__/hooks/configure-wizard.test.ts @@ -579,18 +579,14 @@ describe("doneLines", () => { describe("doneLines — Codex trust", () => { const untrusted = { kind: "untrusted", path: "/h/.codex/hooks.json", untrusted: 10, total: 10 } as const; - const WARNING = [ - "▲ Codex won't run failproofai's hooks until they're trusted.", - " Re-run failproofai config and allow sudo, or open codex once and approve the hooks.", - ]; - it("does not count Codex as enforcing while its hooks are untrusted, and says how to fix it", () => { + it("does not count Codex as enforcing while its hooks are untrusted, and prints no trust notice", () => { vi.mocked(notEnforcingReason).mockReturnValue(null); vi.mocked(enforcingPolicyCount).mockReturnValue({ count: 1, custom: false }); const lines = doneLines(kit, { elapsedMs: 1, done: [], cwd: "/x", agents: 2, connected: true, codexTrust: untrusted }); expect(lines).toContain("✓ 1 policy is enforcing on 1 agent."); - const at = lines.indexOf(WARNING[0]); - expect(lines.slice(at, at + 2)).toEqual(WARNING); + // `config --status` says how to trust them; setup stays lean. + expect(lines.join("\n")).not.toContain("trusted"); }); it("claims nothing enforces when Codex was the only agent", () => { @@ -598,7 +594,6 @@ describe("doneLines — Codex trust", () => { vi.mocked(enforcingPolicyCount).mockReturnValue({ count: 1, custom: false }); const lines = doneLines(kit, { elapsedMs: 1, done: [], cwd: "/x", agents: 1, connected: true, codexTrust: untrusted }); expect(lines.join("\n")).not.toMatch(/enforcing on/); - expect(lines).toContain(WARNING[0]); }); it("counts Codex when its hooks are in the system config", () => { diff --git a/__tests__/hooks/manager.test.ts b/__tests__/hooks/manager.test.ts index 52f74e131..6aa2c4442 100644 --- a/__tests__/hooks/manager.test.ts +++ b/__tests__/hooks/manager.test.ts @@ -96,6 +96,7 @@ vi.mock("../../src/hooks/self-report-install", () => ({ syncSelfReportMcp: vi.fn(() => []), removeSelfReportMcp: vi.fn(() => []), selfReportSyncLines: vi.fn(() => []), + selfReportSummary: vi.fn(() => null), })); describe("hooks/manager", () => { diff --git a/__tests__/hooks/self-report-hook-trust.test.ts b/__tests__/hooks/self-report-hook-trust.test.ts index 92eb25590..0921f5867 100644 --- a/__tests__/hooks/self-report-hook-trust.test.ts +++ b/__tests__/hooks/self-report-hook-trust.test.ts @@ -148,7 +148,7 @@ describe("selfReportHookState (status, sync)", () => { agent: "codex" as const, path: "/x/config.toml", hooked: true, registered: true, transport, endpoint, conflict: false, }); let rows = [row("http", "http://127.0.0.1:4319/mcp?agent=codex")]; - const r = await runSelfReportCommand(["status"], { + const r = await runSelfReportCommand(["status", "--verbose"], { probeEndpoint: async () => true, daemonLive: async () => true, registrations: () => rows, @@ -166,7 +166,7 @@ describe("selfReportHookState (status, sync)", () => { expect(text).toContain("reports recorded by the MCP server: Codex has not trusted failproofai's hooks"); expect(text).toContain("Trust them."); - const ok = await runSelfReportCommand(["status"], { + const ok = await runSelfReportCommand(["status", "--verbose"], { probeEndpoint: async () => true, daemonLive: async () => true, registrations: () => [row("http", "http://127.0.0.1:4319/mcp?agent=codex")], hookState: () => ({ recorder: "hook" }), diff --git a/__tests__/hooks/self-report-log.test.ts b/__tests__/hooks/self-report-log.test.ts new file mode 100644 index 000000000..f07e57068 --- /dev/null +++ b/__tests__/hooks/self-report-log.test.ts @@ -0,0 +1,272 @@ +// @vitest-environment node +/** + * Lean Self Reports output and the daemon-log events: + * - the one summary line install, config, uninstall, enable and disable print; + * - the sync result line the daemon logs; + * - `selfReportLog` frames from the stdio server and syncs, over the daemon + * socket, fire-and-forget (no daemon, a dead socket, an old daemon: dropped); + * - setup's finish step: one spinner, then only what needs the user. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createServer, type Server } from "node:net"; +import { + selfReportSummaryLine, + selfReportSyncLogLine, + type SelfReportMcpResult, +} from "../../src/hooks/self-report-install"; +import { SELF_REPORT_LOG_BUDGET_MS, flushSelfReportLogs, sendSelfReportLog } from "../../src/hooks/self-report-log"; +import { handleSelfReportRpc, runSelfReportMcpServer } from "../../src/hooks/self-report-mcp"; +import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; +import { progressLine } from "../../src/hooks/tui"; +import { PassThrough } from "node:stream"; + +let home: string; +const saved: Record = {}; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "fpai-srlog-")); + for (const k of ["FAILPROOFAI_HOME", "FAILPROOFAI_DAEMON_SOCKET", "FAILPROOFAI_CLOUD_URL", "FAILPROOFAI_SELF_REPORT_SYNC_LOG"]) { + saved[k] = process.env[k]; + delete process.env[k]; + } + process.env.FAILPROOFAI_HOME = home; + process.env.FAILPROOFAI_DAEMON_SOCKET = join(home, "d.sock"); +}); + +afterEach(() => { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + rmSync(home, { recursive: true, force: true }); +}); + +const r = (agent: string, action: string, extra: Partial = {}): SelfReportMcpResult => + ({ agent, path: `/h/${agent}.json`, action, transport: action === "removed" ? "stdio" : "stdio", status: "ok", ...extra }) as SelfReportMcpResult; + +describe("the one Self Reports line", () => { + it("counts the agents left registered, once each", () => { + const results = [r("claude", "added"), r("codex", "unchanged"), r("hermes", "added"), r("hermes", "updated"), r("pi", "unchanged", { transport: "extension" })]; + expect(selfReportSummaryLine(results, "on")).toBe("✓ Self Reports: on for 4 agents"); + expect(selfReportSummaryLine([r("claude", "unchanged")], "on")).toBe("✓ Self Reports: on for 1 agent"); + // On with nothing hooked: nothing to say. + expect(selfReportSummaryLine([r("goose", "skipped", { transport: null, status: "not-hooked" })], "on")).toBeNull(); + }); + + it("off is one line whatever was removed, and names Cloud while it waits for it", () => { + const removed = Array.from({ length: 12 }, (_, i) => r(`a${i}`, "removed")); + expect(selfReportSummaryLine(removed, "off")).toBe("✓ Self Reports: off"); + expect(selfReportSummaryLine(removed, "waiting")).toBe("✓ Self Reports: off until Cloud sends this machine's setting"); + expect(selfReportSummaryLine([r("claude", "removed"), r("codex", "removed")], "removed")).toBe("✓ Self Reports: removed from 2 agents"); + expect(selfReportSummaryLine([r("claude", "unchanged", { transport: null })], "removed")).toBeNull(); + }); + + it("names the agents that failed in the same line, with the fix", () => { + const results = [ + r("claude", "added"), + r("codex", "skipped", { transport: null, status: "error", detail: "EACCES" }), + r("cursor", "skipped", { transport: null, status: "conflict" }), + ]; + expect(selfReportSummaryLine(results, "on")).toBe( + "▲ Self Reports: on for 1 agent; not updated for OpenAI Codex, Cursor Agent · failproofai self-report sync", + ); + expect(selfReportSummaryLine([results[1]], "removed")).toBe( + "▲ Self Reports: not updated for OpenAI Codex · failproofai self-report sync", + ); + }); +}); + +describe("the sync line the daemon logs", () => { + it("names agents and transports, never a path, and nothing when nothing changed", () => { + const line = selfReportSyncLogLine([ + r("claude", "added", { transport: "http" }), + r("cursor", "updated"), + r("pi", "removed"), + r("codex", "unchanged"), + r("factory", "skipped", { transport: null, status: "error", detail: "no daemon is answering here" }), + ]); + expect(line).toBe("added claude (http); updated cursor (stdio); removed pi; failed factory (no daemon is answering here)"); + expect(line).not.toContain("/h/"); + expect(selfReportSyncLogLine([r("codex", "unchanged")])).toBeNull(); + }); +}); + +/** A fake daemon socket that records every frame it is sent. */ +function fakeDaemon(path: string): Promise<{ server: Server; frames: Array> }> { + const frames: Array> = []; + const server = createServer((socket) => { + let buf = Buffer.alloc(0); + socket.on("data", (chunk: Buffer) => { + buf = Buffer.concat([buf, chunk]); + while (buf.length >= 4 && buf.length >= 4 + buf.readUInt32BE(0)) { + const len = buf.readUInt32BE(0); + frames.push(JSON.parse(buf.subarray(4, 4 + len).toString("utf8"))); + buf = buf.subarray(4 + len); + } + }); + socket.on("error", () => {}); + }); + return new Promise((ok) => server.listen(path, () => ok({ server, frames }))); +} + +describe("selfReportLog over the daemon socket", () => { + it("sends one framed selfReportLog and cuts the preview", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + await sendSelfReportLog({ event: "tools/call", agent: "hermes", transport: "stdio", outcome: "recorded", preview: "x".repeat(500) }); + await vi.waitFor(() => expect(frames).toHaveLength(1)); + expect(frames[0]).toMatchObject({ type: "selfReportLog", protocolVersion: 2, event: { event: "tools/call", agent: "hermes", outcome: "recorded" } }); + expect(((frames[0].event as Record).preview).length).toBe(200); + } finally { + server.close(); + } + }); + + it("never waits on a daemon: none, a dead socket, or one that never reads", async () => { + // None. + let t = Date.now(); + await sendSelfReportLog({ event: "initialize" }); + expect(Date.now() - t).toBeLessThan(50); + // A socket file nobody listens on. + writeFileSync(process.env.FAILPROOFAI_DAEMON_SOCKET!, ""); + t = Date.now(); + await sendSelfReportLog({ event: "initialize" }); + expect(Date.now() - t).toBeLessThan(SELF_REPORT_LOG_BUDGET_MS + 100); + rmSync(process.env.FAILPROOFAI_DAEMON_SOCKET!); + // A listener that accepts and never answers (an old daemon reads, fails to + // parse, and closes; this one does not even close). + const held = createServer(() => {}); + await new Promise((ok) => held.listen(process.env.FAILPROOFAI_DAEMON_SOCKET!, () => ok())); + try { + t = Date.now(); + await sendSelfReportLog({ event: "initialize" }); + await flushSelfReportLogs(); + expect(Date.now() - t).toBeLessThan(SELF_REPORT_LOG_BUDGET_MS + 100); + } finally { + held.close(); + } + }); + + it("the stdio server logs initialize, tools/list and each call: recorded, with its session, or skipped and why", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + writeEffectiveSelfReport({ enabled: true }); + const opts = { agent: "copilot", cwd: home }; + await handleSelfReportRpc({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }, opts); + await handleSelfReportRpc({ jsonrpc: "2.0", id: 2, method: "tools/list" }, opts); + const call = (args: Record) => + handleSelfReportRpc({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "report", arguments: args } }, opts); + await call({ category: "looping", detail: "stuck" }); + await call({ category: "made_up", detail: "odd" }); + writeEffectiveSelfReport({ enabled: false }); + await call({ category: "looping", detail: "off now" }); + writeFileSync(join(home, "self-report.json"), "{broken"); + await call({ category: "looping", detail: "broken" }); + await handleSelfReportRpc({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "report", arguments: {} } }, { cwd: home }); + await flushSelfReportLogs(1000); + await vi.waitFor(() => expect(frames).toHaveLength(7)); + const events = frames.map((f) => f.event as Record); + expect(events[0]).toMatchObject({ event: "initialize", agent: "copilot", transport: "stdio", outcome: "on" }); + expect(events[1]).toMatchObject({ event: "tools/list", outcome: "report" }); + expect(events[2]).toMatchObject({ event: "tools/call", outcome: "recorded", category: "looping", knownCategory: true, session: "unattributed", preview: "stuck" }); + expect(events[3]).toMatchObject({ outcome: "recorded", category: "made_up", knownCategory: false }); + expect(events[4]).toMatchObject({ outcome: "skipped", reason: "Self Reports is off" }); + expect(events[5]).toMatchObject({ outcome: "skipped", reason: "settings unreadable" }); + expect(events[6]).toMatchObject({ outcome: "skipped", reason: "no --agent" }); + // Two reports were written, as before. + expect(readdirSync(join(home, "custom-agents", "events")).filter((f) => f.endsWith(".jsonl"))).toHaveLength(2); + } finally { + server.close(); + } + }); + + it("the stdio server's run waits for its events, at most the budget, before it ends", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + writeEffectiveSelfReport({ enabled: true }); + const input = new PassThrough(); + const output = new PassThrough(); + const run = runSelfReportMcpServer({ agent: "goose", cwd: home, input, output }); + input.end(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} })}\n`); + await run; + await vi.waitFor(() => expect(frames.map((f) => (f.event as { event: string }).event)).toEqual(["initialize"])); + } finally { + server.close(); + } + }); +}); + +describe("progressLine", () => { + it("piped: draws nothing while it runs, then prints only the lines to keep", () => { + let out = ""; + const stream = { isTTY: false, write: (s: string) => ((out += s), true) } as unknown as NodeJS.WritableStream; + const p = progressLine(stream, "Working…"); + p.set("Still working…"); + p.done(["✓ Self Reports: on for 3 agents"]); + expect(out).toBe("✓ Self Reports: on for 3 agents\n"); + out = ""; + const q = progressLine(stream, "Working…"); + q.done([]); + expect(out).toBe(""); + }); + + it("on a terminal: one spinner line, erased when there is nothing to keep", () => { + const noColor = process.env.NO_COLOR; + delete process.env.NO_COLOR; + let out = ""; + const stream = { isTTY: true, columns: 80, write: (s: string) => ((out += s), true) } as unknown as NodeJS.WritableStream; + const p = progressLine(stream, "Restarting agent gateways…"); + expect(out).toContain("Restarting agent gateways…"); + out = ""; + p.done([]); + // Up one line, clear to the end, cursor back; nothing printed. + expect(out).toBe("\x1b[1A\x1b[J\x1b[?25h"); + if (noColor !== undefined) process.env.NO_COLOR = noColor; + }); +}); + +describe("setup's finish step", () => { + it("leaves the Self Reports line and only what needs the user", async () => { + vi.resetModules(); + const realUpdateRun = await vi.importActual("../../src/hooks/update-run"); + vi.doMock("../../src/hooks/update-run", () => ({ + setupNeedsUpdateSteps: () => true, + runUpdateSteps: async () => ({ + ok: true, + lines: [" hermes/default already current, gateway restarting", "✕ Hermes: plugin could not be updated"], + restarts: [ + { host: "openclaw", profile: "default", status: "restarting" }, + { host: "hermes", profile: "work", status: "not-supervised" }, + ], + }), + setupGatewayLine: realUpdateRun.setupGatewayLine, + restartNewlyPlugged: async () => [], + markUpdated: vi.fn(), + })); + vi.doMock("../../src/hooks/self-report-install", async () => ({ + ...(await vi.importActual("../../src/hooks/self-report-install")), + syncSelfReportMcp: async () => Array.from({ length: 12 }, (_, i) => r(`a${i}`, "added")), + })); + try { + writeEffectiveSelfReport({ enabled: true }); + const { finishSetup } = await import("../../src/hooks/setup-finish"); + let out = ""; + const stream = { isTTY: false, write: (s: string) => ((out += s), true) } as unknown as NodeJS.WritableStream; + expect(await finishSetup({ version: "9.9.9", pluggedBefore: [], out: stream })).toBe(0); + expect(out.trimEnd().split("\n")).toEqual([ + "✕ Hermes: plugin could not be updated", + "▲ hermes/work: restart the gateway", + "✓ Self Reports: on for 12 agents", + ]); + expect(out).not.toContain("gateway restarting"); + expect(out).not.toContain("MCP server"); + } finally { + vi.doUnmock("../../src/hooks/update-run"); + vi.doUnmock("../../src/hooks/self-report-install"); + vi.resetModules(); + } + }); +}); diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index 333ac08b2..de646a076 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -219,7 +219,7 @@ describe("enrolling with a local settings file in place", () => { // Every reader agrees: the stdio server hides the tool, the hook records nothing. const listed = await handleSelfReportRpc({ jsonrpc: "2.0", id: 1, method: "tools/list" }); expect((listed as { result: { tools: unknown[] } }).result.tools).toEqual([]); - const status = await runSelfReportCommand(["status"], { registrations: () => [], probeEndpoint: async () => false, daemonExpected: () => false }); + const status = await runSelfReportCommand(["status", "--verbose"], { registrations: () => [], probeEndpoint: async () => false, daemonExpected: () => false }); expect(status.lines[0]).toContain("off (waiting for FailproofAI Cloud"); // The org's setting arrives (the daemon writes a cloud file): it decides. const cloud = { ...JSON.parse(readFileSync(join(home, "self-report.json"), "utf8")), source: "cloud", enabled: true }; @@ -585,7 +585,7 @@ describe("failproofai self-report enable | disable | status", () => { expect(config.unrelated).toEqual({ keep: true }); expect(readEffectiveSelfReport()).toMatchObject({ enabled: true, source: "local", guidance: "say what tool", categories: DEFAULT_CATEGORIES }); - const status = await runSelfReportCommand(["status"], deps); + const status = await runSelfReportCommand(["status", "--verbose"], deps); expect(status.exitCode).toBe(0); const text = status.lines.join("\n"); expect(text).toContain("Self Reports: on"); @@ -643,7 +643,7 @@ describe("failproofai self-report enable | disable | status", () => { writeEffectiveSelfReport({ enabled: true }); const runnable = join(home, "failproofai"); writeFileSync(runnable, "#!/bin/sh\n", { mode: 0o755 }); - const r = await runSelfReportCommand(["status"], { + const r = await runSelfReportCommand(["status", "--verbose"], { skipSync: true, probeEndpoint: async (_url, port) => port === 4319, daemonLive: async (port) => port === 4319, @@ -671,7 +671,7 @@ describe("failproofai self-report enable | disable | status", () => { it("status says the daemon is not running, not \"not answering\", when there is no daemon", async () => { writeEffectiveSelfReport({ enabled: true }); const status = (expected: boolean) => - runSelfReportCommand(["status"], { + runSelfReportCommand(["status", "--verbose"], { skipSync: true, probeEndpoint: async () => false, daemonExpected: () => expected, @@ -688,7 +688,7 @@ describe("failproofai self-report enable | disable | status", () => { it("status expects a daemon when setup configured one or its socket file is there", async () => { writeEffectiveSelfReport({ enabled: true }); const status = async () => - (await runSelfReportCommand(["status"], { + (await runSelfReportCommand(["status", "--verbose"], { skipSync: true, probeEndpoint: async () => false, registrations: () => [], @@ -710,7 +710,7 @@ describe("failproofai self-report enable | disable | status", () => { writeEffectiveSelfReport({ enabled: true }); let synced = 0; let rows = [row({ transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" })]; - const r = await runSelfReportCommand(["status"], { + const r = await runSelfReportCommand(["status", "--verbose"], { probeEndpoint: async () => false, registrations: () => rows, sync: async () => { @@ -728,10 +728,10 @@ describe("failproofai self-report enable | disable | status", () => { // Healthy, or skipSync: no write. synced = 0; rows = [row({ transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" })]; - await runSelfReportCommand(["status"], { + await runSelfReportCommand(["status", "--verbose"], { probeEndpoint: async () => true, daemonLive: async () => true, registrations: () => rows, sync: async () => (synced++, []), }); - await runSelfReportCommand(["status"], { skipSync: true, probeEndpoint: async () => false, registrations: () => rows, sync: async () => (synced++, []) }); + await runSelfReportCommand(["status", "--verbose"], { skipSync: true, probeEndpoint: async () => false, registrations: () => rows, sync: async () => (synced++, []) }); expect(synced).toBe(0); }); @@ -739,7 +739,7 @@ describe("failproofai self-report enable | disable | status", () => { writeEffectiveSelfReport({ enabled: true }); let synced = 0; const http = [row({ transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" })]; - const seen = await runSelfReportCommand(["status"], { + const seen = await runSelfReportCommand(["status", "--verbose"], { skipSync: true, probeEndpoint: async () => true, daemonLive: async () => false, @@ -747,7 +747,7 @@ describe("failproofai self-report enable | disable | status", () => { }); expect(seen.lines.join("\n")).toMatch(/claude +http +\S+ \(answering, but NOT this home's daemon\)/); let rows = http; - const r = await runSelfReportCommand(["status"], { + const r = await runSelfReportCommand(["status", "--verbose"], { probeEndpoint: async () => true, daemonLive: async () => false, registrations: () => rows, @@ -765,7 +765,7 @@ describe("failproofai self-report enable | disable | status", () => { writeEffectiveSelfReport({ enabled: true }); let synced = 0; let rows = [row({ agent: "copilot", transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=copilot" })]; - const r = await runSelfReportCommand(["status"], { + const r = await runSelfReportCommand(["status", "--verbose"], { probeEndpoint: async () => true, registrations: () => rows, sync: async () => { @@ -778,20 +778,76 @@ describe("failproofai self-report enable | disable | status", () => { expect(r.lines.join("\n")).toContain("Repaired:"); }); - it("enable says \"Agents updated.\" only when a sync changed something", async () => { - const quiet = await runSelfReportCommand(["enable"], { probeEndpoint: async () => false, sync: async () => [{ agent: "claude", path: "/x", action: "unchanged", transport: "http", status: "ok" }] }); - expect(quiet.lines.join("\n")).not.toContain("Agents updated."); - const changed = await runSelfReportCommand(["enable"], { probeEndpoint: async () => false, sync: async () => [{ agent: "claude", path: "/x", action: "added", transport: "http", status: "ok" }] }); - expect(changed.lines.join("\n")).toContain("Agents updated."); - const off = await runSelfReportCommand(["disable"], { sync: async () => [] }); - expect(off.lines).toEqual([ - "✓ Self Reports is off. Agents lose the report tool and nothing is recorded.", - " Turn it back on with `failproofai self-report enable`.", + it("enable and disable print one line, naming only agents that could not be updated", async () => { + const ok = (agent: string, action: string) => ({ agent, path: `/${agent}`, action, transport: "stdio", status: "ok" }) as never; + const on = await runSelfReportCommand(["enable"], { probeEndpoint: async () => false, sync: async () => [ok("claude", "unchanged"), ok("cursor", "added")] }); + expect(on.lines).toEqual(["✓ Self Reports: on for 2 agents"]); + const partly = await runSelfReportCommand(["enable"], { + probeEndpoint: async () => false, + sync: async () => [ok("claude", "added"), { agent: "codex", path: "/c", action: "skipped", transport: null, status: "error", detail: "EACCES" }], + }); + expect(partly.lines).toEqual(["▲ Self Reports: on for 1 agent; not updated for OpenAI Codex · `failproofai self-report sync`"]); + const off = await runSelfReportCommand(["disable"], { sync: async () => [ok("claude", "removed")] }); + expect(off.lines).toEqual(["✓ Self Reports: off"]); + expect((await runSelfReportCommand(["enable"], { skipSync: true })).lines).toEqual(["✓ Self Reports: on"]); + }); + + it("status is one header, the healthy agents in one line, and a line per agent with a problem", async () => { + writeEffectiveSelfReport({ enabled: true }); + const runnable = join(home, "failproofai"); + writeFileSync(runnable, "#!/bin/sh\n", { mode: 0o755 }); + const r = await runSelfReportCommand(["status"], { + skipSync: true, + probeEndpoint: async (_url, port) => port === 4319, + daemonLive: async (port) => port === 4319, + registrations: () => [ + row({ agent: "claude", transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" }), + row({ agent: "cursor", transport: "stdio", endpoint: runnable }), + row({ agent: "copilot", transport: "stdio", endpoint: runnable }), + row({ agent: "factory", transport: "stdio", endpoint: join(home, "missing", "failproofai") }), + row({ agent: "goose", registered: false, transport: null }), + row({ agent: "devin", hooked: false, registered: false, transport: null }), + ], + }); + expect(r.lines).toEqual([ + "Self Reports: on · this machine", + "Agents: claude, cursor, copilot", + "▲ factory: command not runnable · `failproofai self-report sync`", + "▲ goose: not registered · `failproofai self-report sync`", + ]); + // No paths, URLs, categories or Cursor hint by default. + expect(r.lines.join("\n")).not.toMatch(/http:|cursor-agent|looping|self-report\.json/); + }); + + it("status says off in one line, and --json carries what --verbose shows", async () => { + writeEffectiveSelfReport({ enabled: false }); + expect((await runSelfReportCommand(["status"], deps)).lines).toEqual(["Self Reports: off · this machine"]); + rmSync(join(home, "self-report.json")); + expect((await runSelfReportCommand(["status"], deps)).lines).toEqual(["Self Reports: on · default", "Agents: none with failproofai hooks"]); + writeFileSync(join(home, "self-report.json"), "{not json"); + expect((await runSelfReportCommand(["status"], deps)).lines).toEqual([ + "Self Reports: off · settings file unreadable · `failproofai self-report enable`", ]); + + writeEffectiveSelfReport({ enabled: true }); + const j = await runSelfReportCommand(["status", "--json"], { + skipSync: true, + probeEndpoint: async () => false, + registrations: () => [row({ agent: "copilot", transport: "stdio", endpoint: join(home, "nope") })], + }); + expect(j.exitCode).toBe(0); + expect(j.json).toMatchObject({ + enabled: true, + source: "local", + categories: DEFAULT_CATEGORIES.map((c) => c.name), + daemon: { url: "http://127.0.0.1:4319/mcp", answering: false }, + agents: [{ agent: "copilot", transport: "stdio", healthy: false, problem: "command not runnable", fix: "failproofai self-report sync" }], + }); + expect((await runSelfReportCommand(["status", "--bogus"], deps)).exitCode).toBe(1); }); it("status with no settings file says it is on by default, and how to turn it off", async () => { - const r = await runSelfReportCommand(["status"], deps); + const r = await runSelfReportCommand(["status", "--verbose"], deps); expect(r.exitCode).toBe(0); expect(r.lines[0]).toBe("Self Reports: on"); expect(r.lines.join("\n")).toContain("the default (no settings file yet)"); @@ -800,13 +856,13 @@ describe("failproofai self-report enable | disable | status", () => { it("status with no settings file on a Cloud-enrolled machine says it is off until Cloud sends it", async () => { process.env.FAILPROOFAI_CLOUD_URL = "https://example.invalid"; - const r = await runSelfReportCommand(["status"], deps); + const r = await runSelfReportCommand(["status", "--verbose"], deps); expect(r.lines[0]).toContain("off (waiting for FailproofAI Cloud"); }); it("status with a malformed settings file says it is off", async () => { writeFileSync(join(home, "self-report.json"), "{not json"); - const r = await runSelfReportCommand(["status"], deps); + const r = await runSelfReportCommand(["status", "--verbose"], deps); expect(r.lines[0]).toBe("Self Reports: off (the settings file cannot be read)"); }); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index adbb2559e..fd6f5aebf 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -822,9 +822,15 @@ async function runCli() { if (!subArgs.includes("--quiet")) { const lines = selfReportSyncLines(results); await printLines(lines.length > 0 ? lines : ["Self Reports MCP registration is already up to date."], !failed); - } else if (failed) { - // The daemon runs this with --quiet and logs our stderr: without the - // failing agents' lines, "exit 1" was all its journal ever said. + } else { + // The daemon runs this with --quiet and logs our stdout and stderr: what + // changed (one line), and each agent that failed, so "exit 1" is never + // all its journal says. + if (process.env.FAILPROOFAI_SELF_REPORT_SYNC_LOG === "stdout") { + const { selfReportSyncLogLine } = await import("../src/hooks/self-report-install"); + const changed = selfReportSyncLogLine(results.filter((x) => x.status !== "error" && x.status !== "conflict")); + if (changed) process.stdout.write(`${changed}\n`); + } for (const r of results.filter((x) => x.status === "error")) { process.stderr.write(`${r.agent}: not updated in ${r.path || "its config"}: ${r.detail ?? "error"}\n`); } @@ -1087,7 +1093,7 @@ async function runCli() { await printHelp({ name: "self-report", usage: [ - ["failproofai self-report status", "Show whether it is on (it is by default), and where that came from"], + ["failproofai self-report status [--verbose] [--json]", "Whether it is on, the agents it serves, and any that need a fix"], ["failproofai self-report enable [options]", "Turn it back on for this machine, or change its categories"], ["failproofai self-report disable", "Turn it off: removes the MCP entries and stops recording"], ["failproofai self-report test --agent ", "Send one test report end to end"], @@ -1097,6 +1103,8 @@ async function runCli() { ["--categories-file ", "JSON list of {name, description}; replaces the defaults"], ["--guidance ", "Extra instructions appended to the tool description"], ["--agent ", "With test: the agent to send it as"], + ["--verbose", "With status: paths, endpoints, categories and each agent's transport"], + ["--json", "With status: everything, as JSON"], ], examples: [ "failproofai self-report status", @@ -1109,7 +1117,8 @@ async function runCli() { lastSubcommand = "self-report"; const { runSelfReportCommand } = await import("../src/hooks/self-report-cli"); const result = await runSelfReportCommand(subArgs); - await printReport(`self-report ${subArgs[0]}`, result.lines, { ok: result.exitCode === 0 }); + if (result.json !== undefined) process.stdout.write(`${JSON.stringify(result.json, null, 2)}\n`); + else await printReport(`self-report ${subArgs[0]}`, result.lines, { ok: result.exitCode === 0 }); await track("cli_self_report", { ok: result.exitCode === 0, // The subcommand only — never a category, guidance text or a path. @@ -2185,49 +2194,13 @@ async function runCli() { // running Hermes or OpenClaw gateway kept the plugin it loaded before (or // none) until someone thought to run `update`. Setup has already brought // the daemon to this version and the entry check migrated the home. + // Then Self Reports: every hooked agent's MCP entry brought in line with + // self-report.json. Both behind one spinner line, which leaves the Self + // Reports line and only what needs the user (src/hooks/setup-finish.ts). let updateExit = 0; if (result.applied) { - const { runUpdateSteps, markUpdated, setupNeedsUpdateSteps, setupGatewayLine, restartNewlyPlugged } = - await import("../src/hooks/update-run"); - const { screenKit, colorsEnabled } = await import("../src/hooks/tui"); - const kit = screenKit({ color: colorsEnabled(process.stdout) }); - if (!setupNeedsUpdateSteps(version)) { - // Already updated on this version: only a profile this run plugged in - // (one created since) has a gateway still running without the plugin. - const gateway = setupGatewayLine(await restartNewlyPlugged(pluggedBefore).catch(() => [])); - if (gateway) process.stdout.write(`${gateway.ok ? kit.ok(gateway.text) : kit.caution(gateway.text)}\n`); - } else { - const run = await runUpdateSteps({ layout: false, daemon: false, restart: true }); - // One line at most, in update's own words; a Hermes failure keeps its - // existing ✕ line so it is not lost. - const gateway = setupGatewayLine(run.restarts); - const out = [ - ...run.lines.filter((l) => l.startsWith("✕")), - ...(gateway ? [gateway.ok ? kit.ok(gateway.text) : kit.caution(gateway.text)] : []), - ]; - if (out.length > 0) process.stdout.write(`${out.join("\n")}\n`); - if (run.ok) markUpdated(version); - else updateExit = 1; - } - } - // Self Reports (on by default): write self-report.json when it is missing - // off Cloud, then bring every hooked agent's MCP registration in line with - // it, also when setup found the machine already configured and wrote no - // hooks. Best-effort; prints only what changed. - if (result.applied) { - try { - const { ensureSelfReportSettingsFile } = await import("../src/hooks/self-report"); - await ensureSelfReportSettingsFile(); - } catch { - // the readers apply the same default without the file - } - try { - const { syncSelfReportMcp, selfReportSyncLines } = await import("../src/hooks/self-report-install"); - const lines = selfReportSyncLines(await syncSelfReportMcp({ quiet: true })); - if (lines.length > 0) process.stdout.write(`${lines.join("\n")}\n`); - } catch { - // never fail setup over it - } + const { finishSetup } = await import("../src/hooks/setup-finish"); + updateExit = await finishSetup({ version, pluggedBefore }); } await warnTokenOnArgv(); await track("cli_configure_invoked", { diff --git a/crates/PROTOCOL.md b/crates/PROTOCOL.md index f0ad7c964..e8e763bab 100644 --- a/crates/PROTOCOL.md +++ b/crates/PROTOCOL.md @@ -66,6 +66,36 @@ Tagged JSON, `"type"` as the discriminant, camelCase field names. } ``` +```jsonc +// One Self Reports MCP event from outside the daemon — the stdio server +// `failproofai mcp` (a child of each agent) or a CLI `self-report sync` — +// for the daemon's log, which machine logs ship. ONE-WAY: the daemon writes +// no reply and closes the connection; the sender never reads one. +{ + "type": "selfReportLog", + "protocolVersion": 2, + "event": { + "event": "tools/call", // initialize | tools/list | tools/call | sync | error + "agent": "hermes", // every field below is optional + "transport": "stdio", // stdio | cli + "outcome": "recorded", // recorded | skipped | failed (calls); on | off (initialize) + "reason": "Self Reports is off", + "category": "looping", + "knownCategory": true, + "session": "…", + "preview": "≤ 200 chars of the detail; the daemon scrubs secrets and logs ≤ 40", + "summary": "added claude (stdio); failed codex (…)" // sync only + } +} +``` + +`selfReportLog` needs no version bump: a daemon that predates it fails to parse +the unknown `type` and closes the connection (see "Malformed input handling"), +which drops the event — exactly what a one-way message wants. Unknown fields in +`event` are ignored, so either side can add one. The client sends it only when +the socket file exists, gives the whole send 250 ms, and drops it on any error, +so an agent is never held up. + `cwd` must be the *originating* CLI process's cwd, captured by the thin client before dispatch — never the daemon's own cwd. The daemon is a single long-lived process; its own `cwd` does not vary per request and must never be diff --git a/crates/failproofaid/src/self_report.rs b/crates/failproofaid/src/self_report.rs index 9eefac36a..33ea5e330 100644 --- a/crates/failproofaid/src/self_report.rs +++ b/crates/failproofaid/src/self_report.rs @@ -222,6 +222,33 @@ pub fn tick(enrolled: Option, withdrawn: &dyn Fn() -> bool) { } } +/// Log one Self Reports event that arrived over the socket (`selfReportLog`): +/// the stdio server's MCP traffic, or a CLI sync's result. Written exactly as +/// the HTTP server's own events, so the machine logs hold both the same way. +/// The preview is scrubbed and cut again here: the sender is not trusted to. +pub fn log_remote(ev: &fpai_ipc::SelfReportLogEvent) { + let transport = match ev.transport.as_deref() { + Some("cli") => "cli", + _ => "stdio", + }; + sr::log_event(&sr::McpLog { + event: &ev.event, + transport, + agent: ev.agent.as_deref(), + outcome: ev.outcome.as_deref(), + reason: ev.reason.as_deref(), + category: ev.category.as_deref(), + known_category: ev.known_category, + session: ev.session.as_deref(), + detail: ev.preview.as_deref(), + summary: ev.summary.as_deref(), + }); +} + +/// Set on the sync child: print the sync's result on stdout (which this +/// daemon logs) rather than send it back over the socket. +pub const SYNC_LOG_ENV: &str = "FAILPROOFAI_SELF_REPORT_SYNC_LOG"; + /// The MCP port, from `FAILPROOFAI_SELF_REPORT_PORT` once per process. pub fn port() -> u16 { static PORT: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -393,11 +420,16 @@ fn run_sync_once() { tracing::warn!("Self Reports sync skipped: {problem}"); return; } - match run_with_timeout( + report_sync(run_with_timeout( &format!("{cli} self-report sync --quiet"), &home, SYNC_TIMEOUT, - ) { + )); +} + +/// The daemon's log line for one sync child's exit. +fn report_sync(result: io::Result>) { + match result { Ok(Some(0)) => tracing::info!("Self Reports agent configs synced"), Ok(Some(code)) => tracing::warn!("`failproofai self-report sync` failed (exit {code})"), Ok(None) => tracing::warn!("`failproofai self-report sync` was killed (timeout or signal)"), @@ -428,12 +460,33 @@ fn sync_identity_problem(home: &Path, euid: u32) -> Option { } fn run_with_timeout(command: &str, home: &Path, timeout: Duration) -> io::Result> { + run_with_timeout_in(command, home, timeout, None) +} + +/// [`run_with_timeout`] with the child's whole environment given (tests: a +/// service's bare `PATH` and a scratch `HOME`, nothing inherited). +fn run_with_timeout_in( + command: &str, + home: &Path, + timeout: Duration, + only_env: Option<&[(&str, &std::ffi::OsStr)]>, +) -> io::Result> { use std::os::unix::process::CommandExt; - let mut child = Command::new("sh") - .arg("-c") - .arg(command) + let mut command = { + let mut c = Command::new("sh"); + c.arg("-c").arg(command); + if let Some(env) = only_env { + c.env_clear(); + for (k, v) in env { + c.env(k, v); + } + } + c + }; + let mut child = command // The CLI resolves the same home the daemon read self-report.json from. .env("FAILPROOFAI_HOME", home) + .env(SYNC_LOG_ENV, "stdout") .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -879,4 +932,229 @@ mod tests { ); let _ = std::fs::remove_dir_all(&home); } + + /// A machine laid out like an nvm install run by a service: `node` and + /// npm's `failproofai` link side by side in `/nvm/bin`, the package's + /// `dist/cli.mjs` (here a shim that runs this checkout's CLI with bun) in + /// `lib/node_modules`, and a scratch `HOME`. Nothing is inherited from the + /// test's environment, so no real agent config is ever read or written. + struct ServiceMachine { + root: PathBuf, + home: PathBuf, + bin: PathBuf, + /// How the service runs the CLI: ` …/dist/cli.mjs`. + cli: String, + } + + impl ServiceMachine { + fn new(name: &str) -> Self { + let root = temp_path(name).parent().unwrap().to_path_buf(); + let home = root.join("home"); + let bin = root.join("nvm").join("bin"); + let pkg = root.join("nvm/lib/node_modules/failproofai/dist"); + std::fs::create_dir_all(home.join(".failproofai")).unwrap(); + std::fs::create_dir_all(&bin).unwrap(); + std::fs::create_dir_all(&pkg).unwrap(); + let bun = std::env::var_os("PATH") + .and_then(|p| find_named(&p, "bun")) + .expect("bun on PATH (cargo test runs the TypeScript CLI with it)"); + // A real file, not a symlink: bun reports a symlink's target as its + // execPath, and the point is the `node` the service was given. + let node = bin.join("node"); + if std::fs::hard_link(&bun, &node).is_err() { + std::fs::copy(&bun, &node).unwrap(); + } + let repo_cli = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../bin/failproofai.mjs"); + let cli_mjs = pkg.join("cli.mjs"); + std::fs::write( + &cli_mjs, + format!( + "#!/usr/bin/env node\nawait import({:?});\n", + repo_cli.canonicalize().unwrap().display().to_string() + ), + ) + .unwrap(); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&cli_mjs, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + std::os::unix::fs::symlink(&cli_mjs, bin.join("failproofai")).unwrap(); + let cli = format!("{} {}", shell_quote(&node), shell_quote(&cli_mjs)); + ServiceMachine { + root, + home, + bin, + cli, + } + } + + fn fp_home(&self) -> PathBuf { + self.home.join(".failproofai") + } + + /// Run ` ` with `PATH`, the scratch `HOME`, and nothing else. + fn run(&self, args: &str, path: &str) -> Option { + let env: [(&str, &std::ffi::OsStr); 3] = [ + ("PATH", std::ffi::OsStr::new(path)), + ("HOME", self.home.as_os_str()), + ("FAILPROOFAI_TELEMETRY_DISABLED", std::ffi::OsStr::new("1")), + ]; + run_with_timeout_in( + &format!("{} {args}", self.cli), + &self.fp_home(), + SYNC_TIMEOUT, + Some(&env), + ) + .unwrap() + } + + /// The agent configs that hold a `failproofai_local` entry. + fn registered(&self) -> Vec<&'static str> { + [ + ("claude", ".claude.json"), + ("codex", ".codex/config.toml"), + ("cursor", ".cursor/mcp.json"), + ("copilot", ".copilot/mcp-config.json"), + ("factory", ".factory/mcp.json"), + ("devin", ".config/devin/mcp_config.json"), + ] + .into_iter() + .filter(|(_, file)| { + std::fs::read_to_string(self.home.join(file)) + .is_ok_and(|text| text.contains("failproofai_local")) + }) + .map(|(agent, _)| agent) + .collect() + } + + fn config(&self, file: &str) -> String { + std::fs::read_to_string(self.home.join(file)).unwrap_or_default() + } + } + + impl Drop for ServiceMachine { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.root); + } + } + + fn find_named(path: &std::ffi::OsStr, name: &str) -> Option { + std::env::split_paths(path) + .map(|dir| dir.join(name)) + .find(|p| p.is_file()) + .and_then(|p| p.canonicalize().ok()) + } + + const HOOKED: &str = "claude codex cursor copilot factory devin"; + + /// The laptop run, end to end: no settings file; `config` (here its hook + /// install) runs while the machine is enrolled with no org setting yet, + /// which is off, so its sync registers nothing; then the daemon writes the + /// org's "on". That first Cloud write must sync, and the sync, run the way + /// the service runs it (bare PATH, ` dist/cli.mjs`), must register + /// every hooked agent with no manual `self-report sync`. + #[test] + fn the_first_cloud_write_after_an_enrolled_config_registers_every_hooked_agent() { + let m = ServiceMachine::new("cloud-first-sync"); + std::fs::write(m.fp_home().join("credentials.json"), r#"{"cloud":{}}"#).unwrap(); + let settings = sr::settings_path(&m.fp_home()); + assert!(!settings.exists()); + + // `config` runs in the user's shell, where nvm's bin is on PATH. + let shell_path = format!("{}:/usr/bin:/bin", m.bin.display()); + assert_eq!( + m.run( + &format!("policies --install --cli {HOOKED} --scope user"), + &shell_path + ), + Some(0) + ); + assert!( + !settings.exists(), + "an enrolled machine waits for the org's setting" + ); + assert_eq!( + m.registered(), + Vec::<&str>::new(), + "enrolled with no setting is off" + ); + + // The daemon's maintenance lane, with the org's first answer. + let on = Desired { + enabled: true, + ..Default::default() + }; + let applied = apply(&settings, Some(&on), 4319).unwrap(); + assert_eq!( + applied, + Applied { + written: true, + needs_sync: true + } + ); + // The sync the lane spawns, under the service's environment. + assert_eq!(m.run("self-report sync --quiet", "/usr/bin:/bin"), Some(0)); + assert_eq!( + m.registered(), + vec!["claude", "codex", "cursor", "copilot", "factory", "devin"] + ); + // No daemon answers here, so every entry is stdio, on npm's link + // beside the service's node (on no PATH the service has). + let link = m.bin.join("failproofai").display().to_string(); + assert!( + m.config(".cursor/mcp.json").contains(&link), + "{}", + m.config(".cursor/mcp.json") + ); + assert!(m.config(".codex/config.toml").contains(&link)); + // And the same answer again changes nothing. + assert_eq!( + apply(&settings, Some(&on), 4319).unwrap(), + Applied { + written: false, + needs_sync: false + } + ); + } + + /// The startup sync under a service's PATH: `failproofai` is on no PATH + /// the service has and the CLI runs as `dist/cli.mjs`, so the only way to + /// a stdio command is npm's link beside the service's node. Without that + /// link every server-recorded agent fails and the sync exits 1. + #[test] + fn the_startup_sync_finds_the_cli_beside_the_services_node() { + let m = ServiceMachine::new("service-path"); + let shell_path = format!("{}:/usr/bin:/bin", m.bin.display()); + assert_eq!( + m.run( + &format!("policies --install --cli {HOOKED} --scope user"), + &shell_path + ), + Some(0) + ); + // Not enrolled and no file: on by default, so the install registered them. + assert_eq!(m.registered().len(), 6); + // Start over from no entries, then the daemon's startup sync. + for file in [ + ".claude.json", + ".codex/config.toml", + ".cursor/mcp.json", + ".copilot/mcp-config.json", + ".factory/mcp.json", + ".config/devin/mcp_config.json", + ] { + let _ = std::fs::remove_file(m.home.join(file)); + } + assert_eq!(m.run("self-report sync --quiet", "/usr/bin:/bin"), Some(0)); + assert_eq!(m.registered().len(), 6); + let link = m.bin.join("failproofai").display().to_string(); + assert!(m.config(".copilot/mcp-config.json").contains(&link)); + + // The control: without the link the same sync fails, as it did. + std::fs::remove_file(m.bin.join("failproofai")).unwrap(); + for file in [".cursor/mcp.json", ".copilot/mcp-config.json"] { + let _ = std::fs::remove_file(m.home.join(file)); + } + assert_eq!(m.run("self-report sync --quiet", "/usr/bin:/bin"), Some(1)); + } } diff --git a/crates/failproofaid/src/server.rs b/crates/failproofaid/src/server.rs index 436ee3a1d..bf9af8348 100644 --- a/crates/failproofaid/src/server.rs +++ b/crates/failproofaid/src/server.rs @@ -321,6 +321,11 @@ pub fn handle_connection(stream: UnixStream, worker: &Worker) -> io::Result<()> Ok(msg) => msg, Err(_) => return Ok(()), // malformed frame: nothing to respond to, nothing to act on }; + // One-way: logged, and the connection closes with no reply. + if let ClientMessage::SelfReportLog { event, .. } = &request { + crate::self_report::log_remote(event); + return Ok(()); + } // The worker call is deliberately OUTSIDE the connection budget: it is our // own evaluation taking time, not the peer withholding bytes, and it has @@ -574,6 +579,14 @@ fn evaluate(request: ClientMessage, worker: &Worker) -> ServerMessage { }, } } + // `handle_connection` logs these and replies nothing; never reached. + ClientMessage::SelfReportLog { event, .. } => { + crate::self_report::log_remote(&event); + ServerMessage::Error { + protocol_version: PROTOCOL_VERSION, + message: "selfReportLog takes no reply".to_string(), + } + } } } diff --git a/crates/failproofaid/tests/self_report_e2e.rs b/crates/failproofaid/tests/self_report_e2e.rs index 8fc7a49f5..52159c280 100644 --- a/crates/failproofaid/tests/self_report_e2e.rs +++ b/crates/failproofaid/tests/self_report_e2e.rs @@ -233,3 +233,115 @@ fn the_pong_names_the_daemon_that_holds_the_mcp_port() { id.as_str() ); } + +/// Every Self Reports MCP event lands in the daemon's log: the HTTP server's +/// own, and a stdio server's sent over the socket (`selfReportLog`, one-way: +/// no reply). The preview is scrubbed of secrets and cut short; nothing else +/// of the detail is logged. +#[test] +fn self_report_mcp_events_reach_the_daemon_log() { + let port = free_port(); + let daemon = spawn(port); + fpai_collect::self_report::write_settings( + &daemon.home.join("self-report.json"), + &fpai_collect::self_report::Settings { + version: 1, + enabled: true, + source: "local".into(), + categories: fpai_collect::self_report::default_categories(), + guidance: None, + mcp: fpai_collect::self_report::McpEndpoint::on_port(port), + updated_at: "2026-11-25T10:00:00Z".into(), + }, + ) + .unwrap(); + wait("the MCP endpoint", || initialize(port).is_some()); + wait("the socket", || { + daemon.home.join("run/failproofaid.sock").exists() + }); + let secret = "sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGH"; + let detail = + format!("the key {secret} was rejected with a 401 and everything after this point is long"); + let call = serde_json::json!({ + "jsonrpc": "2.0", "id": 3, "method": "tools/call", + "params": {"name": "report", "arguments": {"category": "not_a_category", "detail": detail}} + }); + let client = reqwest::blocking::Client::new(); + let url = format!("http://127.0.0.1:{port}/mcp?agent=copilot"); + for body in [ + serde_json::json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}), + call, + ] { + let reply = client + .post(&url) + .header("Content-Type", "application/json") + .body(body.to_string()) + .send() + .unwrap(); + assert!(reply.status().is_success()); + } + wait("the HTTP tools/call line", || { + daemon + .log + .lock() + .unwrap() + .contains("Self Reports MCP tools/call over http agent=copilot outcome=recorded") + }); + + // A stdio server's event, over the socket. + let mut stream = UnixStream::connect(daemon.home.join("run/failproofaid.sock")).unwrap(); + write_message( + &mut stream, + &ClientMessage::SelfReportLog { + protocol_version: PROTOCOL_VERSION, + event: fpai_ipc::SelfReportLogEvent { + event: "tools/call".into(), + agent: Some("hermes".into()), + transport: Some("stdio".into()), + outcome: Some("recorded".into()), + category: Some("looping".into()), + known_category: Some(true), + session: Some("sess-42".into()), + preview: Some(detail.clone()), + ..Default::default() + }, + }, + ) + .unwrap(); + // No reply: the daemon closes the connection. + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut buf = [0u8; 1]; + assert_eq!(std::io::Read::read(&mut stream, &mut buf).unwrap(), 0); + wait("the stdio tools/call line", || { + daemon + .log + .lock() + .unwrap() + .contains("Self Reports MCP tools/call over stdio agent=hermes outcome=recorded") + }); + // The socket still answers after it. + ping(&daemon); + + let log = daemon.log.lock().unwrap().clone(); + assert!( + log.contains("Self Reports MCP tools/list over http agent=copilot"), + "{log}" + ); + assert!(log.contains("session=sess-42"), "{log}"); + // An unknown category is a warning; a known one is not. + let http_line = log + .lines() + .find(|l| l.contains("over http agent=copilot outcome=recorded")) + .unwrap(); + assert!(http_line.contains("WARN"), "{http_line}"); + assert!(http_line.contains("unknown_category=true"), "{http_line}"); + let stdio_line = log + .lines() + .find(|l| l.contains("over stdio agent=hermes")) + .unwrap(); + assert!(stdio_line.contains("INFO"), "{stdio_line}"); + assert!(!log.contains(secret), "the key reached the log:\n{log}"); + assert!(!log.contains("everything after this point"), "{log}"); +} diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index 7bd0a60f8..034267f8c 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -817,7 +817,19 @@ impl Server { "instanceId": instance_id(), }, }); - if let Some(text) = server_instructions(self.settings.current().as_ref()) { + let current = self.settings.current(); + log_event(&McpLog { + event: "initialize", + transport: "http", + agent: caller.agent.as_deref(), + outcome: Some(if current.as_ref().is_some_and(|s| s.enabled) { + "on" + } else { + "off" + }), + ..Default::default() + }); + if let Some(text) = server_instructions(current.as_ref()) { result["instructions"] = Value::String(text); } rpc_result(id, result) @@ -827,11 +839,30 @@ impl Server { let tools: Vec = tool_definition(self.settings.current().as_ref()) .into_iter() .collect(); + log_event(&McpLog { + event: "tools/list", + transport: "http", + agent: caller.agent.as_deref(), + outcome: Some(if tools.is_empty() { + "no tool (off)" + } else { + "report" + }), + ..Default::default() + }); rpc_result(id, json!({"tools": tools})) } "tools/call" => { let name = params.get("name").and_then(Value::as_str); if name != Some(TOOL_NAME) { + log_event(&McpLog { + event: "tools/call", + transport: "http", + agent: caller.agent.as_deref(), + outcome: Some("skipped"), + reason: Some("unknown tool"), + ..Default::default() + }); return Some(rpc_error(id, -32602, "Unknown tool")); } let args = params.get("arguments").cloned().unwrap_or(Value::Null); @@ -854,21 +885,177 @@ impl Server { /// still send a call. Read from disk, not the cache, so a disable is /// honoured on the very next call (as the stdio server does). fn record(&self, args: &Value, caller: &Caller) { + let report = Report::from_args(args); + let mut log = McpLog { + event: "tools/call", + transport: "http", + agent: caller.agent.as_deref(), + outcome: Some("skipped"), + category: Some(&report.category), + detail: Some(&report.detail), + ..Default::default() + }; let Some(agent) = caller .agent .as_deref() .filter(|a| SERVER_RECORDS.contains(a)) else { + log.reason = Some(if caller.agent.is_none() { + "no agent in the URL" + } else { + "its hook records it" + }); + log_event(&log); return; }; - if !effective_settings(&self.home, &*self.settings.enrolled).is_some_and(|s| s.enabled) { - return; - } - let report = Report::from_args(args); + let settings = match effective_settings(&self.home, &*self.settings.enrolled) { + Some(s) if s.enabled => s, + _ => { + log.reason = Some(if settings_unreadable(&self.home) { + "settings unreadable" + } else { + "Self Reports is off" + }); + log_event(&log); + return; + } + }; + log.known_category = Some( + effective_categories(&settings) + .iter() + .any(|c| c.name == report.category), + ); let event = fallback_event(&self.home, agent, caller.cwd.as_deref(), &report, now_ms()); - if let Err(err) = write_event_file(&self.home, &[event]) { - tracing::warn!(%err, agent, "could not record a self report"); + let session = event + .get("session_id") + .and_then(Value::as_str) + .map(str::to_string); + log.session = session.as_deref(); + let failure; + match write_event_file(&self.home, &[event]) { + Ok(_) => log.outcome = Some("recorded"), + Err(err) => { + failure = format!("write failed: {err}"); + log.outcome = Some("failed"); + log.reason = Some(&failure); + } } + log_event(&log); + } +} + +// ── Logging ────────────────────────────────────────────────────────────────── + +/// How much of a report's detail a log line carries, after secrets are +/// scrubbed from the whole detail. +pub const LOG_PREVIEW_CHARS: usize = 40; + +/// One Self Reports MCP event, as the daemon logs it: the HTTP server's own, +/// and the stdio server's and CLI syncs' that arrive over the socket +/// (`selfReportLog`, crates/PROTOCOL.md). +#[derive(Debug, Default, Clone)] +pub struct McpLog<'a> { + /// `initialize`, `tools/list`, `tools/call`, `sync` or `error`. + pub event: &'a str, + /// `http`, `stdio` or `cli`. + pub transport: &'a str, + pub agent: Option<&'a str>, + pub outcome: Option<&'a str>, + pub reason: Option<&'a str>, + pub category: Option<&'a str>, + pub known_category: Option, + pub session: Option<&'a str>, + /// The report's detail; only [`log_preview`] of it is logged. + pub detail: Option<&'a str>, + pub summary: Option<&'a str>, +} + +/// The detail as a log line may show it: secrets scrubbed from the whole +/// text first (a cut token would no longer match), then one line, then the +/// first [`LOG_PREVIEW_CHARS`] characters. Machine logs can leave the machine +/// and scrub only the home directory and the machine key, so this is the +/// whole of what protects the detail. +pub fn log_preview(detail: &str) -> String { + let scrubbed = crate::redact::scrub_str(detail).map_or_else(|| detail.to_string(), |(s, _)| s); + let flat: String = scrubbed + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .collect(); + let flat = flat.trim(); + let cut = truncate_chars(flat, LOG_PREVIEW_CHARS); + if cut.chars().count() < flat.chars().count() { + format!("{cut}…") + } else { + cut + } +} + +/// The line [`log_event`] writes (without its level). +pub fn log_line(ev: &McpLog) -> String { + fn word(v: &str, max: usize) -> String { + let clean: String = v + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .collect(); + truncate_chars(clean.trim(), max) + } + let mut line = format!( + "Self Reports MCP {} over {}", + word(ev.event, 32), + word(ev.transport, 16) + ); + let mut field = |key: &str, value: String| line.push_str(&format!(" {key}={value}")); + if let Some(v) = ev.agent { + field("agent", word(v, 64)); + } + if let Some(v) = ev.outcome { + field("outcome", word(v, 32)); + } + if let Some(v) = ev.category { + field("category", format!("{:?}", word(v, 64))); + } + if ev.known_category == Some(false) { + field("unknown_category", "true".to_string()); + } + if let Some(v) = ev.session { + field("session", word(v, 128)); + } + if let Some(v) = ev.reason { + let v = crate::redact::scrub_str(v).map_or_else(|| v.to_string(), |(s, _)| s); + field("reason", format!("{:?}", word(&v, 300))); + } + if let Some(v) = ev.summary { + let v = crate::redact::scrub_str(v).map_or_else(|| v.to_string(), |(s, _)| s); + field("result", format!("{:?}", word(&v, 1000))); + } + if let Some(v) = ev.detail.filter(|d| !d.trim().is_empty()) { + field("preview", format!("{:?}", log_preview(v))); + } + line +} + +/// Log one event: WARN for a failure, an `error` event, a report filed under +/// a category the settings do not list, or settings that cannot be read; +/// INFO otherwise. +pub fn log_event(ev: &McpLog) { + let line = log_line(ev); + let warn = ev.event == "error" + || ev.outcome == Some("failed") + || ev.known_category == Some(false) + || ev.reason == Some("settings unreadable"); + if warn { + tracing::warn!("{line}"); + } else { + tracing::info!("{line}"); + } +} + +/// Whether `self-report.json` is there but cannot be read or parsed. +fn settings_unreadable(home: &Path) -> bool { + let path = settings_path(home); + match fs::read_to_string(&path) { + Ok(text) => parse_settings(&text).is_none(), + Err(err) => err.kind() != io::ErrorKind::NotFound, } } @@ -1166,6 +1353,60 @@ pub fn write_event_file(home: &Path, events: &[Value]) -> io::Result { mod tests { use super::*; + #[test] + fn a_log_preview_is_scrubbed_before_it_is_cut() { + // The key starts inside the first 40 characters and ends after them: + // cut first, the half left would no longer look like a key. + let detail = + "auth failed: sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789 then more\nlines"; + let preview = log_preview(detail); + assert!(!preview.contains("abcdefghij"), "{preview}"); + assert!(preview.starts_with("auth failed: "), "{preview}"); + assert!( + preview.chars().count() <= LOG_PREVIEW_CHARS + 1, + "{preview}" + ); + assert!(!preview.contains('\n')); + assert_eq!(log_preview("short"), "short"); + assert_eq!(log_preview(&"é".repeat(50)), format!("{}…", "é".repeat(40))); + } + + #[test] + fn a_log_line_names_the_event_and_only_the_fields_it_has() { + let line = log_line(&McpLog { + event: "tools/call", + transport: "stdio", + agent: Some("hermes"), + outcome: Some("skipped"), + reason: Some("Self Reports is off"), + category: Some("looping"), + known_category: Some(false), + session: Some("s-1"), + detail: Some("stuck\nin a loop"), + summary: None, + }); + assert_eq!( + line, + "Self Reports MCP tools/call over stdio agent=hermes outcome=skipped \ + category=\"looping\" unknown_category=true session=s-1 \ + reason=\"Self Reports is off\" preview=\"stuck in a loop\"" + ); + let bare = log_line(&McpLog { + event: "initialize", + transport: "http", + ..Default::default() + }); + assert_eq!(bare, "Self Reports MCP initialize over http"); + // A sync result is scrubbed too. + let sync = log_line(&McpLog { + event: "sync", + transport: "cli", + summary: Some("failed codex (token=sk-proj-abcdefghijklmnopqrstuvwxyz012345)"), + ..Default::default() + }); + assert!(!sync.contains("abcdefghij"), "{sync}"); + } + fn temp_home(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!( "fpai-self-report-{name}-{}-{}", diff --git a/crates/fpai-ipc/src/envelope.rs b/crates/fpai-ipc/src/envelope.rs index dfc759465..d73f871c2 100644 --- a/crates/fpai-ipc/src/envelope.rs +++ b/crates/fpai-ipc/src/envelope.rs @@ -8,7 +8,10 @@ use serde::{Deserialize, Serialize}; -/// Bumped whenever a change is made to either message enum below. +/// Bumped whenever a request or reply gains a field that changes how a request +/// is answered. A new one-way message ([`ClientMessage::SelfReportLog`]) needs +/// no bump: an older daemon fails to parse its unknown `type` and closes the +/// connection, which is exactly "ignored" for a message that expects no reply. pub const PROTOCOL_VERSION: u32 = 2; /// The oldest version the daemon still answers, and the oldest a client will @@ -72,6 +75,49 @@ pub enum ClientMessage { #[serde(default, skip_serializing_if = "Option::is_none")] agent_settings_path: Option, }, + /// One Self Reports MCP event from a process outside the daemon (the + /// stdio server `failproofai mcp`, or a CLI `self-report sync`), for the + /// daemon's log. One-way: the daemon writes no reply and the sender does + /// not wait for one. An older daemon cannot parse it and closes the + /// connection, which drops it. + #[serde(rename_all = "camelCase")] + SelfReportLog { + protocol_version: u32, + event: SelfReportLogEvent, + }, +} + +/// See [`ClientMessage::SelfReportLog`]. Every field but `event` is optional +/// and unknown fields are ignored, so either side can add one. +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", default)] +pub struct SelfReportLogEvent { + /// `initialize`, `tools/list`, `tools/call`, `sync` or `error`. + pub event: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub agent: Option, + /// `stdio` (the stdio server) or `cli` (a sync). + #[serde(skip_serializing_if = "Option::is_none")] + pub transport: Option, + /// For a call: `recorded`, `skipped` or `failed`. + #[serde(skip_serializing_if = "Option::is_none")] + pub outcome: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub category: Option, + /// Whether `category` is on the settings' list. + #[serde(skip_serializing_if = "Option::is_none")] + pub known_category: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub session: Option, + /// The start of the report's detail. The daemon scrubs secrets from it + /// and cuts it again before it logs anything. + #[serde(skip_serializing_if = "Option::is_none")] + pub preview: Option, + /// A sync's result: `added claude (http); removed pi; failed …`. + #[serde(skip_serializing_if = "Option::is_none")] + pub summary: Option, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -141,6 +187,9 @@ impl ClientMessage { ClientMessage::PolicyEvaluation { protocol_version, .. } => *protocol_version, + ClientMessage::SelfReportLog { + protocol_version, .. + } => *protocol_version, } } } @@ -182,7 +231,7 @@ impl ClientMessage { cwd, agent_settings_path: agent_settings_path.filter(|_| keep_settings), }, - ping @ ClientMessage::Ping { .. } => ping, + other @ (ClientMessage::Ping { .. } | ClientMessage::SelfReportLog { .. }) => other, } } } @@ -352,6 +401,34 @@ mod tests { assert_eq!(serde_json::from_value::(json).unwrap(), full); } + #[test] + fn a_self_report_log_reads_with_only_its_event_and_ignores_unknown_fields() { + let msg: ClientMessage = serde_json::from_value(serde_json::json!({ + "type": "selfReportLog", + "protocolVersion": PROTOCOL_VERSION, + "event": {"event": "tools/call", "agent": "copilot", "knownCategory": false, "later": 1} + })) + .unwrap(); + let ClientMessage::SelfReportLog { event, .. } = msg else { + panic!("expected SelfReportLog"); + }; + assert_eq!(event.event, "tools/call"); + assert_eq!(event.agent.as_deref(), Some("copilot")); + assert_eq!(event.known_category, Some(false)); + assert_eq!(event.session, None); + // Absent fields stay off the wire. + let json = serde_json::to_value(ClientMessage::SelfReportLog { + protocol_version: PROTOCOL_VERSION, + event: SelfReportLogEvent { + event: "initialize".into(), + ..Default::default() + }, + }) + .unwrap(); + assert_eq!(json["type"], "selfReportLog"); + assert_eq!(json["event"], serde_json::json!({"event": "initialize"})); + } + #[test] fn protocol_version_accessor_matches_every_variant() { assert_eq!( diff --git a/crates/fpai-ipc/src/lib.rs b/crates/fpai-ipc/src/lib.rs index c0adea790..261a69462 100644 --- a/crates/fpai-ipc/src/lib.rs +++ b/crates/fpai-ipc/src/lib.rs @@ -7,7 +7,7 @@ pub mod framing; pub mod peer; pub use envelope::{ - ClientMessage, MIN_PROTOCOL_VERSION, PROTOCOL_VERSION, SelfReportServer, ServerMessage, - is_supported_protocol_version, + ClientMessage, MIN_PROTOCOL_VERSION, PROTOCOL_VERSION, SelfReportLogEvent, SelfReportServer, + ServerMessage, is_supported_protocol_version, }; pub use framing::{FramingError, MAX_FRAME_LEN, read_message, write_message}; diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index 7058931b1..75824e47b 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -94,7 +94,7 @@ Claude Code and Codex can load the MCP server while skipping failproofai's hooks - Codex 0.129 and later runs a hook from `~/.codex/hooks.json` only once a person trusted it, at its current hash. Hooks in Codex's system config (`/etc/codex/config.toml`, where `failproofai config` puts them when it has sudo) run without trust. - Claude Code runs no hooks with `disableAllHooks: true`, and only managed ones with a managed `allowManagedHooksOnly: true`. -So the stdio server records a Claude Code or Codex report itself unless that agent's hook already recorded it: the agent runs its hook before it sends the MCP call, so the server looks for the hook's record of the same report from the last two minutes. A report is recorded once either way, and a person who trusts the hooks while the agent runs changes nothing. A report the server records goes on the session the agent's own files name (Codex's rollout, Claude Code's transcript for that directory). `self-report sync` registers such an agent over stdio, never on the daemon's endpoint, which records nothing for it. `self-report status` says who records each one's reports and, for an untrusted Codex, how to trust the hooks: re-run `failproofai config` and allow sudo, or open `codex` once and approve them. +So the stdio server records a Claude Code or Codex report itself unless that agent's hook already recorded it: the agent runs its hook before it sends the MCP call, so the server looks for the hook's record of the same report from the last two minutes. A report is recorded once either way, and a person who trusts the hooks while the agent runs changes nothing. A report the server records goes on the session the agent's own files name (Codex's rollout, Claude Code's transcript for that directory). `self-report sync` registers such an agent over stdio, never on the daemon's endpoint, which records nothing for it. `self-report status --verbose` says who records each one's reports and, for an untrusted Codex, how to trust the hooks: re-run `failproofai config` and allow sudo, or open `codex` once and approve them. ### Other agents' servers @@ -102,11 +102,19 @@ Devin also lists the MCP servers of other agents' configs: `~/.claude.json` (use ### Cursor approval -If `cursor-agent mcp list` shows `failproofai_local` as "not loaded (needs approval)", run `cursor-agent mcp enable failproofai_local`. cursor-agent asks for approval of servers in a project's `.cursor/mcp.json`, so this happens, for example, when it runs with your home directory as the project. The approval is per project and per entry, so failproofai does not write it for you. The sync and `status` output say so for Cursor. +If `cursor-agent mcp list` shows `failproofai_local` as "not loaded (needs approval)", run `cursor-agent mcp enable failproofai_local`. cursor-agent asks for approval of servers in a project's `.cursor/mcp.json`, so this happens, for example, when it runs with your home directory as the project. The approval is per project and per entry, so failproofai does not write it for you. `self-report sync` and `self-report status --verbose` say so for Cursor. On Antigravity, an MCP call can come through its `call_mcp_tool` wrapper. The hook lets that call through ahead of the policies only when the wrapper names server `failproofai_local` and tool `report`. A wrapped call to any other server goes through the policies as usual. -`failproofai self-report status` shows whether the daemon's endpoint answers (`not running (agents use stdio)` when no daemon is set up here) and, per agent, whether the server is registered, over which transport, and whether that endpoint answers (HTTP) or the command can run (stdio). If an MCP server named `failproofai_local` that failproofai did not write is already there, it is left alone and reported as a conflict. A server named `failproofai`, such as the [Cloud MCP gateway](/reference/mcp), is never touched or reported: it sits next to `failproofai_local`, and its tools go through your policies like any other server's. +`failproofai self-report status` prints one header line (on or off, and where the setting comes from), one line with the agents whose server is registered and working, and a line with the fix for each agent that has a problem: not registered, an endpoint that does not answer, a command that cannot run, a config it cannot read. `--verbose` adds the settings file, the categories, the daemon's endpoint (`not running (agents use stdio)` when no daemon is set up here) and, per agent, the transport, the URL or command, and who records its reports. `--json` prints all of it as JSON. + +`policies --install`, `config`, `policies --uninstall`, `enable` and `disable` each print one Self Reports line, such as `Self Reports: on for 12 agents`, which also names any agent they could not update. `self-report sync` lists every change. + +If an MCP server named `failproofai_local` that failproofai did not write is already there, it is left alone and reported as a conflict. A server named `failproofai`, such as the [Cloud MCP gateway](/reference/mcp), is never touched or reported: it sits next to `failproofai_local`, and its tools go through your policies like any other server's. + +## The daemon's log + +The daemon's log (`~/.failproofai/logs/daemon.log`, which machine logs upload) has a line for every Self Reports MCP event: each `initialize` and `tools/list`, each `tools/call` with the agent, the category, the session it was filed under, and whether it was recorded or skipped and why, and each sync's result. A write failure, a category the settings do not list, and an unreadable settings file are warnings. A line carries at most the first 40 characters of the report's detail, after secrets are scrubbed from it. The stdio server, which runs as a child of each agent, sends its events to the daemon over its socket and never waits for it: with no daemon, or a version that predates this, they are dropped. ## Containers diff --git a/src/hooks/config-status.ts b/src/hooks/config-status.ts index c5f4621b6..43d83379e 100644 --- a/src/hooks/config-status.ts +++ b/src/hooks/config-status.ts @@ -441,8 +441,9 @@ export function pickStatusAttention(facts: StatusFacts): StatusAttention | null return { severity: "caution", text: "Policies are not enforcing yet.", fix }; } if (facts.codex?.kind === "untrusted") { - const [text, fixLine] = CODEX_UNTRUSTED_NOTICE.split("\n"); - return { severity: "caution", text, detail: fixLine }; + // One line: the fix that needs no one at the Codex prompt (sudo puts the + // hooks in Codex's system config, which runs them without trust). + return { severity: "caution", text: CODEX_UNTRUSTED_NOTICE.split("\n")[0], fix: "failproofai config" }; } if (cloud.kind !== "none" && !daemon.answering && daemon.service !== "running") { const idle = diff --git a/src/hooks/configure-wizard.ts b/src/hooks/configure-wizard.ts index 2bdcd6578..5a768c3ae 100644 --- a/src/hooks/configure-wizard.ts +++ b/src/hooks/configure-wizard.ts @@ -64,7 +64,6 @@ import { INTEGRATION_TYPES, type IntegrationType, type HookScope } from "./types import { cloudDashboardUrl, enforcingPolicyCount, installHooks, notEnforcingReason } from "./manager"; import { installAgentSkill } from "./agent-skill"; import { - CODEX_UNTRUSTED_NOTICE, codexHookTrust, removeCodexSystemHooks, type CodexHookTrust, @@ -1898,7 +1897,9 @@ export function doneLines( lines.push(kit.ok(`Policies are enforcing on ${on}.`)); } } - if (codexSkips) lines.push(...kit.notice("caution", CODEX_UNTRUSTED_NOTICE)); + // No trust notice here: an untrusted Codex is left out of the count above, + // its reports are still recorded (by the MCP server), and `config --status` + // says how to trust the hooks. if (!state.connected) lines.push(` Connect to cloud any time: ${kit.cmd("failproofai config")}`); for (const warning of describeCustomPolicies(state.cwd).warnings) { lines.push(kit.caution(warning.replace(/^! /, ""))); diff --git a/src/hooks/manager.ts b/src/hooks/manager.ts index 3f6fc36e9..38ed396bf 100644 --- a/src/hooks/manager.ts +++ b/src/hooks/manager.ts @@ -43,8 +43,8 @@ import { packPolicyParamKey } from "./policy-evaluator"; import { probeDaemonPolicyEvaluation } from "./daemon-service"; import { NO_PRINTED_COMMAND_REASON, sudoPath } from "./system-command"; import { keepAgentSelectionTrue } from "./agent-selection"; -import { removeSelfReportMcp, selfReportSyncLines, syncSelfReportMcp } from "./self-report-install"; -import { ensureSelfReportSettingsFile } from "./self-report"; +import { removeSelfReportMcp, selfReportSummary, syncSelfReportMcp } from "./self-report-install"; +import { ensureSelfReportSettingsFile, selfReportSettingsState } from "./self-report"; import { INDENT, colorsEnabled, optsFor, printBlock, screenKit, type ScreenKitOpts } from "./tui"; const VALID_POLICY_NAMES = new Set(BUILTIN_POLICIES.map((p) => p.name)); @@ -1029,7 +1029,9 @@ async function installHooksImpl( alsoHooked: writtenSettingsPaths.map((written) => written.cli), binaryPath, }); - for (const line of selfReportSyncLines(results)) console.log(line); + // One line; the per-agent changes are `self-report sync`'s and `status`'s. + const summary = selfReportSummary(results, selfReportSettingsState()); + if (summary) console.log(summary.ok ? kit.ok(summary.text) : kit.caution(summary.text, summary.fix)); } catch { // never block the install } @@ -1244,7 +1246,9 @@ export async function removeHooks(policyNames?: string[], scope: HookScope | "al // the user-scope hooks that use it are still there. if (scope === "user" || scope === "all") { try { - for (const line of selfReportSyncLines(removeSelfReportMcp({ agents: selectedClis, quiet: true }))) say(line); + const summary = selfReportSummary(removeSelfReportMcp({ agents: selectedClis, quiet: true }), "removed"); + const kit = screenKit(optsFor(process.stdout)); + if (summary) say(summary.ok ? kit.ok(summary.text) : kit.caution(summary.text, summary.fix)); } catch { // never block the removal } diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts index b650e2de8..200a6d167 100644 --- a/src/hooks/self-report-cli.ts +++ b/src/hooks/self-report-cli.ts @@ -49,6 +49,7 @@ import { selfReportCommandRunnable, selfReportRegistrationStatus, selfReportSyncChanged, + selfReportSummaryLine, selfReportSyncLines, syncSelfReportMcp, type SelfReportRegistration, @@ -57,6 +58,8 @@ import { export interface SelfReportCliResult { exitCode: number; lines: string[]; + /** `status --json`: printed as JSON instead of the lines. */ + json?: unknown; } export interface SelfReportCliDeps { @@ -219,7 +222,72 @@ function selfReportStranded( return port === null || health.get(port) !== true || owned.get(port) !== true; } -async function selfReportStatus(deps: SelfReportCliDeps): Promise { +/** One agent's state, for every view of `status`. */ +interface SelfReportAgentView { + agent: string; + path: string; + hooked: boolean; + registered: boolean; + transport: SelfReportRegistration["transport"]; + endpoint: string | null; + /** Registered and working: its endpoint answers as this home's daemon, or its command runs. */ + healthy: boolean; + /** What is wrong, when something is, and the command that fixes it. */ + problem?: string; + fix?: string; + /** Claude Code / Codex: who records its reports, and why when it is the server. */ + recorder?: SelfReportHookState; +} + +const SELF_REPORT_SYNC_FIX = "failproofai self-report sync"; + +function selfReportAgentViews( + rows: readonly SelfReportRegistration[], + health: ReadonlyMap, + owned: ReadonlyMap, + recorders: ReadonlyMap, +): SelfReportAgentView[] { + const out: SelfReportAgentView[] = []; + for (const r of rows.filter((x) => x.hooked || x.registered || x.conflict || x.error)) { + const recorder = r.registered ? recorders.get(r.agent) : undefined; + const view: SelfReportAgentView = { + agent: r.agent, path: r.path, hooked: r.hooked, registered: r.registered, + transport: r.transport, endpoint: r.endpoint, healthy: false, + ...(recorder ? { recorder } : {}), + }; + if (r.error) view.problem = `config unreadable (${r.error})`; + else if (r.conflict) view.problem = `another "${SELF_REPORT_SERVER_NAME}" MCP server is configured; left alone`; + else if (!r.registered) Object.assign(view, { problem: "not registered", fix: SELF_REPORT_SYNC_FIX }); + else if (r.transport === "http") { + const port = selfReportUrlPort(r.endpoint); + const ok = port !== null && health.get(port) === true; + if (ok && owned.get(port!) === true) view.healthy = true; + else Object.assign(view, { problem: ok ? "endpoint is another home's daemon" : "endpoint not answering", fix: SELF_REPORT_SYNC_FIX }); + } else if (r.transport === "extension") view.healthy = true; + else if (r.endpoint && selfReportCommandRunnable(r.endpoint)) view.healthy = true; + else Object.assign(view, { problem: "command not runnable", fix: SELF_REPORT_SYNC_FIX }); + out.push(view); + } + return out; +} + +/** The lean view: a header, the healthy agents in one line, a line per problem. */ +function selfReportLeanLines(header: string, views: readonly SelfReportAgentView[], repaired: string | null): string[] { + const lines = [header]; + if (repaired) lines.push(repaired); + const healthy = views.filter((v) => v.healthy).map((v) => v.agent).filter((a, i, all) => all.indexOf(a) === i); + const problems = views.filter((v) => !v.healthy && v.problem); + if (healthy.length > 0) lines.push(`Agents: ${healthy.join(", ")}`); + else if (problems.length === 0) lines.push("Agents: none with failproofai hooks"); + for (const v of problems) lines.push(`▲ ${v.agent}: ${v.problem}${v.fix ? ` · \`${v.fix}\`` : ""}`); + return lines; +} + +async function selfReportStatus(args: string[], deps: SelfReportCliDeps): Promise { + const unknown = args.find((a) => a !== "--verbose" && a !== "-v" && a !== "--json"); + if (unknown) return { exitCode: 1, lines: [`Unexpected argument: ${unknown}.`] }; + const verbose = args.includes("--verbose") || args.includes("-v"); + const asJson = args.includes("--json"); const file = readEffectiveSelfReport(); const settings = resolveSelfReport(); const cloud = await selfReportCloudManaged(); @@ -228,6 +296,29 @@ async function selfReportStatus(deps: SelfReportCliDeps): Promise Self Reports)" : "Turn on: `failproofai self-report enable`"); return { exitCode: 0, lines }; } - lines.push(`Self Reports: ${settings.enabled ? "on" : "off"}`); - lines.push( - `Source: ${ - settings.source === "cloud" ? "FailproofAI Cloud" : file ? "this machine (config.json)" : "the default (no settings file yet)" - }`, - ); - lines.push(`Settings: ${selfReportSettingsFile()}`); - lines.push( - settings.source === "cloud" - ? "Turn off: in the dashboard, Settings > Self Reports" - : settings.enabled - ? "Turn off: `failproofai self-report disable`" - : "Turn on: `failproofai self-report enable`", - ); - if (settings.updatedAt) lines.push(`Updated: ${settings.updatedAt}`); - lines.push(`Categories: ${settings.categories.map((c) => c.name).join(", ")}`); - lines.push(`MCP server: ${SELF_REPORT_SERVER_NAME} (tool \`${SELF_REPORT_TOOL_NAME}\`)`); - if (settings.guidance) lines.push(`Guidance: ${settings.guidance.length > 60 ? `${settings.guidance.slice(0, 57)}...` : settings.guidance}`); + const source = settings.source === "cloud" ? "cloud" : file ? "local" : "default"; const readRows = deps.registrations ?? (() => selfReportRegistrationStatus()); let rows = readRows(); let health = await selfReportHttpHealth(rows, deps); @@ -277,25 +351,96 @@ async function selfReportStatus(deps: SelfReportCliDeps): Promise selfReportStranded(r, health, owned, recorders))) { try { const results = await (deps.sync ?? (() => syncSelfReportMcp({ quiet: true })))(); if (selfReportSyncChanged(results)) { - lines.push("Repaired: agents on an HTTP endpoint that is not this home's answering daemon, or that belong on stdio, were re-synced:"); - lines.push(...selfReportSyncLines(results).map((l) => ` ${l}`)); + repairedAgents = results + .filter((r) => r.action === "added" || r.action === "updated" || r.action === "removed") + .map((r) => r.agent) + .filter((a, i, all) => all.indexOf(a) === i); + repaired = `✓ Re-synced ${repairedAgents.join(", ")}`; + repairedLines = [ + "Repaired: agents on an HTTP endpoint that is not this home's answering daemon, or that belong on stdio, were re-synced:", + ...selfReportSyncLines(results).map((l) => ` ${l}`), + ]; rows = readRows(); health = await selfReportHttpHealth(rows, deps); owned = await selfReportHttpOwnership(health, deps); } } catch { - lines.push("▲ Could not re-sync agents whose HTTP endpoint is not answering. Run `failproofai self-report sync`."); + repaired = `▲ Could not re-sync agents whose HTTP endpoint is not answering · \`${SELF_REPORT_SYNC_FIX}\``; + repairedLines = [`▲ Could not re-sync agents whose HTTP endpoint is not answering. Run \`${SELF_REPORT_SYNC_FIX}\`.`]; } } if (!health.has(settings.mcp.port)) { const probe = deps.probeEndpoint ?? ((_url: string, port: number) => probeSelfReportHttp(port)); health.set(settings.mcp.port, await probe(settings.mcp.url, settings.mcp.port)); } - lines.push(selfReportDaemonLine(settings.mcp.url, health.get(settings.mcp.port) === true, deps)); + const daemonAnswering = health.get(settings.mcp.port) === true; + const views = selfReportAgentViews(rows, health, owned, recorders); + + if (asJson) { + return { + exitCode: 0, + lines: [], + json: { + enabled: settings.enabled, + source, + settingsPath: selfReportSettingsFile(), + updatedAt: settings.updatedAt || null, + categories: settings.categories.map((c) => c.name), + guidance: settings.guidance, + server: SELF_REPORT_SERVER_NAME, + tool: SELF_REPORT_TOOL_NAME, + daemon: { url: settings.mcp.url, answering: daemonAnswering }, + repaired: repairedAgents, + agents: views.map((v) => ({ + agent: v.agent, + path: v.path, + hooked: v.hooked, + registered: v.registered, + transport: v.transport, + endpoint: v.endpoint, + healthy: v.healthy, + problem: v.problem ?? null, + fix: v.fix ?? null, + recordedBy: v.recorder ? v.recorder.recorder : null, + })), + }, + }; + } + + if (!verbose) { + const from = source === "cloud" ? "from Cloud" : source === "local" ? "this machine" : "default"; + const header = `Self Reports: ${settings.enabled ? "on" : "off"} · ${from}`; + if (!settings.enabled) return { exitCode: 0, lines: [header] }; + return { exitCode: 0, lines: selfReportLeanLines(header, views, repaired) }; + } + + lines.push(`Self Reports: ${settings.enabled ? "on" : "off"}`); + lines.push( + `Source: ${ + source === "cloud" ? "FailproofAI Cloud" : source === "local" ? "this machine (config.json)" : "the default (no settings file yet)" + }`, + ); + lines.push(`Settings: ${selfReportSettingsFile()}`); + lines.push( + settings.source === "cloud" + ? "Turn off: in the dashboard, Settings > Self Reports" + : settings.enabled + ? "Turn off: `failproofai self-report disable`" + : "Turn on: `failproofai self-report enable`", + ); + if (settings.updatedAt) lines.push(`Updated: ${settings.updatedAt}`); + lines.push(`Categories: ${settings.categories.map((c) => c.name).join(", ")}`); + lines.push(`MCP server: ${SELF_REPORT_SERVER_NAME} (tool \`${SELF_REPORT_TOOL_NAME}\`)`); + if (settings.guidance) lines.push(`Guidance: ${settings.guidance.length > 60 ? `${settings.guidance.slice(0, 57)}...` : settings.guidance}`); + lines.push(...repairedLines); + lines.push(selfReportDaemonLine(settings.mcp.url, daemonAnswering, deps)); lines.push(...selfReportRegistrationLines(rows, health, owned, recorders)); return { exitCode: 0, lines }; } @@ -313,17 +458,19 @@ function selfReportDaemonLine(url: string, answering: boolean, deps: SelfReportC return "Daemon MCP: not running (agents use stdio)"; } -/** Update every hooked agent's MCP entry to match the settings just written. */ -async function selfReportSync(deps: SelfReportCliDeps): Promise { - if (deps.skipSync) return []; +/** + * Update every hooked agent's MCP entry to match the settings just written, + * and say it in the one line enable and disable print. + */ +async function selfReportSyncLine(deps: SelfReportCliDeps, enabled: boolean): Promise { + const plain = enabled ? "✓ Self Reports: on" : "✓ Self Reports: off"; + if (deps.skipSync) return plain; try { const results = await (deps.sync ?? (() => syncSelfReportMcp({ quiet: true })))(); - if (results.some((r) => r.status === "error")) { - return ["▲ Could not update every agent's MCP settings. Run `failproofai self-report sync` to see why."]; - } - return selfReportSyncChanged(results) ? ["Agents updated."] : []; + const line = selfReportSummaryLine(results, enabled ? "on" : "off"); + return (line ?? plain).replace(/ · (failproofai .+)$/, " · `$1`"); } catch { - return ["▲ Could not update your agents' MCP settings. Run `failproofai self-report sync` to see why."]; + return `▲ Self Reports: ${enabled ? "on" : "off"}; agents not updated · \`${SELF_REPORT_SYNC_FIX}\``; } } @@ -371,14 +518,8 @@ async function selfReportEnable(args: string[], deps: SelfReportCliDeps): Promis } await writeLocalSelfReportConfig({ enabled: true, categories, guidance }); - const written = writeEffectiveSelfReport({ enabled: true, categories, guidance }); - const lines = [ - "✓ Self Reports is on.", - ` Categories: ${written.categories.map((c) => c.name).join(", ")}${categories ? "" : " (defaults)"}`, - ` Settings: ${selfReportSettingsFile()}`, - ...(await selfReportSync(deps)).map((l) => (l.startsWith("▲") ? l : ` ${l}`)), - ]; - return { exitCode: 0, lines }; + writeEffectiveSelfReport({ enabled: true, categories, guidance }); + return { exitCode: 0, lines: [await selfReportSyncLine(deps, true)] }; } async function selfReportDisable(args: string[], deps: SelfReportCliDeps): Promise { @@ -388,14 +529,7 @@ async function selfReportDisable(args: string[], deps: SelfReportCliDeps): Promi // The category list and guidance are kept, so turning it back on restores them. await writeLocalSelfReportConfig({ enabled: false, categories: previous?.categories, guidance: previous?.guidance }); writeEffectiveSelfReport({ enabled: false, categories: previous?.categories, guidance: previous?.guidance }); - return { - exitCode: 0, - lines: [ - "✓ Self Reports is off. Agents lose the report tool and nothing is recorded.", - ...(await selfReportSync(deps)).map((l) => (l.startsWith("▲") ? l : ` ${l}`)), - " Turn it back on with `failproofai self-report enable`.", - ], - }; + return { exitCode: 0, lines: [await selfReportSyncLine(deps, false)] }; } const SELF_REPORT_TEST_DETAIL = "failproofai self-report test: this is a test report, not a real problem."; @@ -545,8 +679,7 @@ export async function runSelfReportCommand(args: string[], deps: SelfReportCliDe try { switch (verb) { case "status": - if (rest.length > 0) return { exitCode: 1, lines: [`Unexpected argument: ${rest[0]}.`] }; - return await selfReportStatus(deps); + return await selfReportStatus(rest, deps); case "enable": return await selfReportEnable(rest, deps); case "disable": diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index 01414d5d3..f559b0a15 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -89,6 +89,7 @@ import { codexHome } from "./codex-system-hooks"; import { claudeConfigDir, getIntegration, readYamlDoc, writeYamlDoc, UnreadableAgentConfigError } from "./integrations"; import { daemonSelfReportServer } from "./daemon-client"; +import { flushSelfReportLogs, sendSelfReportLog } from "./self-report-log"; import { selfReportHookState } from "./self-report-hook-trust"; import { resolveSelfReport, selfReportPort, selfReportSettingsFile, SELF_REPORT_SERVER_NAME, SELF_REPORT_SERVER_RECORDS } from "./self-report"; import { listHermesProfiles } from "../../lib/hermes-profiles"; @@ -751,7 +752,27 @@ export async function syncSelfReportMcp(opts: SyncSelfReportMcpOptions = {}): Pr const wanted = enabled && agents.some((a) => selfReportHttpAllowed(a) && (also.includes(a) || hooked(a) || ownedRegistrationIn(a))); const daemonHere = wanted ? await (opts.deps?.daemonLive ?? selfReportDaemonLive)(settings.port) : false; - return applySelfReportMcp({ ...opts, deps: { ...opts.deps, settings, hooksInstalled: hooked } }, enabled, daemonHere); + const results = applySelfReportMcp({ ...opts, deps: { ...opts.deps, settings, hooksInstalled: hooked } }, enabled, daemonHere); + logSelfReportSync(results); + await flushSelfReportLogs(); + return results; +} + +/** + * The environment variable the daemon sets on the sync it runs itself: it + * logs that sync's stdout, so the result is printed there (by bin's `sync`) + * rather than sent back over its socket. Same name as `SYNC_LOG_ENV` in + * crates/failproofaid/src/self_report.rs. + */ +export const SELF_REPORT_SYNC_LOG_ENV = "FAILPROOFAI_SELF_REPORT_SYNC_LOG"; + +/** A sync's result for the daemon's log, when it changed or failed anything. */ +function logSelfReportSync(results: readonly SelfReportMcpResult[]): void { + if (process.env[SELF_REPORT_SYNC_LOG_ENV] === "stdout") return; + const summary = selfReportSyncLogLine(results); + if (!summary) return; + const failed = selfReportFailedAgents(results).length > 0; + void sendSelfReportLog({ event: "sync", transport: "cli", outcome: failed ? "failed" : "ok", summary }); } /** @@ -905,7 +926,9 @@ function applySelfReportMcp(opts: SyncSelfReportMcpOptions, enabled: boolean, da /** Remove our entries from every agent (or `agents`), whatever the settings say. Needs no live check. */ export function removeSelfReportMcp(opts: Omit = {}): SelfReportMcpResult[] { - return applySelfReportMcp({ ...opts, enabled: false }, false, false); + const results = applySelfReportMcp({ ...opts, enabled: false }, false, false); + logSelfReportSync(results); + return results; } /** Whether a sync changed any agent's file. */ @@ -938,6 +961,84 @@ export function selfReportSyncLines(results: readonly SelfReportMcpResult[]): st return out; } +/** The distinct agents among `results` that match `pick`, in order. */ +function agentsWhere(results: readonly SelfReportMcpResult[], pick: (r: SelfReportMcpResult) => boolean): IntegrationType[] { + const out: IntegrationType[] = []; + for (const r of results) if (pick(r) && !out.includes(r.agent)) out.push(r.agent); + return out; +} + +/** Agents a sync left registered (any transport, Pi's extension included). */ +export function selfReportRegisteredAgents(results: readonly SelfReportMcpResult[]): IntegrationType[] { + return agentsWhere(results, (r) => r.status === "ok" && r.action !== "removed" && r.transport !== null); +} + +/** Agents a sync could not update (an error, or a `failproofai_local` that is not ours). */ +export function selfReportFailedAgents(results: readonly SelfReportMcpResult[]): IntegrationType[] { + return agentsWhere(results, (r) => r.status === "error" || r.status === "conflict"); +} + +/** + * The one line every command but `sync` and `status` prints about Self + * Reports, or null for nothing to say. `state` is the setting + * (`selfReportSettingsState`), or `removed` for a command that took the + * entries out of the agents it unhooked. A failure is named in the same line. + */ +export function selfReportSummaryLine( + results: readonly SelfReportMcpResult[], + state: "on" | "off" | "waiting" | "unreadable" | "removed", +): string | null { + const s = selfReportSummary(results, state); + if (!s) return null; + return s.ok ? `✓ ${s.text}` : `▲ ${s.text} · ${s.fix}`; +} + +/** `selfReportSummaryLine` before it is drawn: for a caller with its own screen kit. */ +export function selfReportSummary( + results: readonly SelfReportMcpResult[], + state: "on" | "off" | "waiting" | "unreadable" | "removed", +): { ok: boolean; text: string; fix?: string } | null { + const failed = selfReportFailedAgents(results).map(displayName); + const n = (k: number) => `${k} ${k === 1 ? "agent" : "agents"}`; + let text: string | null; + if (state === "on") { + const on = selfReportRegisteredAgents(results).length; + text = on > 0 ? `Self Reports: on for ${n(on)}` : null; + } else if (state === "removed") { + const removed = agentsWhere(results, (r) => r.action === "removed").length; + text = removed > 0 ? `Self Reports: removed from ${n(removed)}` : null; + } else { + text = state === "waiting" ? "Self Reports: off until Cloud sends this machine's setting" : "Self Reports: off"; + } + if (failed.length === 0) return text ? { ok: true, text } : null; + const problem = `not updated for ${failed.join(", ")}`; + return { ok: false, text: text ? `${text}; ${problem}` : `Self Reports: ${problem}`, fix: "failproofai self-report sync" }; +} + +/** + * The daemon-log summary of one sync: `added claude (http), cursor (stdio); + * removed pi; failed codex (reason)`, or null when nothing changed or failed. + * Agents and transports only, never a path: the line can leave the machine as + * part of its machine logs. + */ +export function selfReportSyncLogLine(results: readonly SelfReportMcpResult[]): string | null { + const parts: string[] = []; + const list = (action: SelfReportMcpAction) => + results + .filter((r) => r.action === action) + .map((r) => (r.transport && action !== "removed" ? `${r.agent} (${r.transport})` : r.agent)) + .filter((v, i, all) => all.indexOf(v) === i); + for (const action of ["added", "updated", "removed"] as const) { + const items = list(action); + if (items.length > 0) parts.push(`${action} ${items.join(", ")}`); + } + const failed = results + .filter((r) => r.status === "error" || r.status === "conflict") + .map((r) => `${r.agent} (${r.status === "conflict" ? "another failproofai_local server is configured" : (r.detail ?? "error").slice(0, 120)})`); + if (failed.length > 0) parts.push(`failed ${failed.join(", ")}`); + return parts.length > 0 ? parts.join("; ") : null; +} + function displayName(agent: IntegrationType): string { try { return getIntegration(agent).displayName; diff --git a/src/hooks/self-report-log.ts b/src/hooks/self-report-log.ts new file mode 100644 index 000000000..83da6dd41 --- /dev/null +++ b/src/hooks/self-report-log.ts @@ -0,0 +1,119 @@ +/** + * Self Reports events for the daemon's log, from processes outside it: the + * stdio MCP server (`failproofai mcp`, a child of each agent) and the CLI's + * `self-report sync`. + * + * The daemon's log is what machine logs ship (crates/failproofaid/src/logship.rs), + * so an event belongs there and nowhere else. It goes over the daemon's own + * socket as one `selfReportLog` frame (crates/PROTOCOL.md): one-way, no reply + * read. An older daemon cannot parse the type and closes the connection, so + * it is dropped. No daemon, a slow one, or any error: dropped too, inside + * `SELF_REPORT_LOG_BUDGET_MS`. Nothing here ever throws or holds up an agent. + * + * Only a short start of a report's detail is sent; the daemon scrubs secrets + * from it and cuts it again before logging. + * + * Top-level names are prefixed for the same bundle reason as self-report.ts. + */ +import { existsSync } from "node:fs"; +import { createConnection } from "node:net"; +import { daemonSocket } from "./fp-home"; + +/** The whole budget for one event, connect to close. */ +export const SELF_REPORT_LOG_BUDGET_MS = 250; +/** How much detail is sent; the daemon logs at most its first 40 characters. */ +export const SELF_REPORT_LOG_PREVIEW_CHARS = 200; +const SELF_REPORT_LOG_PROTOCOL_VERSION = 2; + +export interface SelfReportLogEvent { + event: "initialize" | "tools/list" | "tools/call" | "sync" | "error"; + agent?: string; + transport?: "stdio" | "cli"; + outcome?: string; + reason?: string; + category?: string; + knownCategory?: boolean; + session?: string; + /** The report's detail; cut to `SELF_REPORT_LOG_PREVIEW_CHARS` here. */ + preview?: string; + summary?: string; +} + +const selfReportLogPending = new Set>(); + +function selfReportLogSocket(): string { + return process.env.FAILPROOFAI_DAEMON_SOCKET || daemonSocket(); +} + +/** + * Send one event, without waiting for it. Returns the send, which always + * resolves (in at most the budget); callers that are about to exit may await + * `flushSelfReportLogs` instead. + */ +export function sendSelfReportLog(event: SelfReportLogEvent): Promise { + const sent = selfReportLogSend(event); + selfReportLogPending.add(sent); + void sent.then(() => selfReportLogPending.delete(sent)); + return sent; +} + +/** Wait for every event still in flight, at most `maxMs`. */ +export async function flushSelfReportLogs(maxMs: number = SELF_REPORT_LOG_BUDGET_MS): Promise { + if (selfReportLogPending.size === 0) return; + let timer: ReturnType | undefined; + await Promise.race([ + Promise.all([...selfReportLogPending]), + new Promise((done) => { + timer = setTimeout(done, maxMs); + timer.unref?.(); + }), + ]); + if (timer) clearTimeout(timer); +} + +function selfReportLogSend(event: SelfReportLogEvent): Promise { + return new Promise((resolve) => { + let path: string; + let frame: Buffer; + try { + if (process.platform === "win32") return resolve(); + path = selfReportLogSocket(); + if (!existsSync(path)) return resolve(); + const body = Buffer.from( + JSON.stringify({ + type: "selfReportLog", + protocolVersion: SELF_REPORT_LOG_PROTOCOL_VERSION, + event: { + ...event, + ...(event.preview !== undefined ? { preview: [...event.preview].slice(0, SELF_REPORT_LOG_PREVIEW_CHARS).join("") } : {}), + }, + }), + "utf8", + ); + const header = Buffer.alloc(4); + header.writeUInt32BE(body.length, 0); + frame = Buffer.concat([header, body]); + } catch { + return resolve(); + } + let settled = false; + const socket = createConnection({ path }); + const done = (): void => { + if (settled) return; + settled = true; + clearTimeout(timer); + socket.removeAllListeners(); + socket.on("error", () => {}); + socket.destroy(); + resolve(); + }; + const timer = setTimeout(done, SELF_REPORT_LOG_BUDGET_MS); + timer.unref?.(); + socket.unref(); + socket.on("error", done); + socket.on("close", done); + socket.on("connect", () => { + socket.end(frame, done); + }); + }); +} diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts index cb0b05c0b..87ec7def6 100644 --- a/src/hooks/self-report-mcp.ts +++ b/src/hooks/self-report-mcp.ts @@ -41,7 +41,9 @@ import { selfReportClip, selfReportInputSchema, selfReportInstructions, + selfReportSettingsState, } from "./self-report"; +import { flushSelfReportLogs, sendSelfReportLog } from "./self-report-log"; /** * Set to `1` in the server's environment (by `self-report test`), it writes one @@ -406,9 +408,14 @@ export async function handleSelfReportRpc( if (!hasId) return null; // notifications/initialized and friends + const log = (event: Parameters[0]): void => { + void sendSelfReportLog({ transport: "stdio", ...(opts.agent ? { agent: opts.agent } : {}), ...event }); + }; + switch (method) { case "initialize": { const instructions = selfReportServerInstructions(); + log({ event: "initialize", outcome: instructions ? "on" : "off" }); return ok({ protocolVersion: typeof params.protocolVersion === "string" ? params.protocolVersion : SELF_REPORT_DEFAULT_PROTOCOL, capabilities: { tools: {} }, @@ -418,30 +425,44 @@ export async function handleSelfReportRpc( } case "ping": return ok({}); - case "tools/list": - return ok({ tools: selfReportToolList() }); + case "tools/list": { + const tools = selfReportToolList(); + log({ event: "tools/list", outcome: tools.length > 0 ? "report" : "no tool (off)" }); + return ok({ tools }); + } case "tools/call": { if (params.name !== SELF_REPORT_TOOL_NAME) { + log({ event: "tools/call", outcome: "skipped", reason: "unknown tool" }); return ok({ content: [{ type: "text", text: `Unknown tool: ${String(params.name)}` }], isError: true }); } const agent = opts.agent; - if (agent && readEnabledSelfReport() && (await selfReportServerShouldRecord(agent, params.arguments, opts.now?.()))) { - const { category, detail } = selfReportArgs(params.arguments ?? {}); + const { category, detail } = selfReportArgs(params.arguments ?? {}); + const call = { event: "tools/call" as const, category, preview: detail }; + const settings = readEnabledSelfReport(); + if (!agent) { + log({ ...call, outcome: "skipped", reason: "no --agent" }); + } else if (!settings) { + log({ ...call, outcome: "skipped", reason: selfReportSettingsState() === "unreadable" ? "settings unreadable" : "Self Reports is off" }); + } else if (!(await selfReportServerShouldRecord(agent, params.arguments, opts.now?.()))) { + log({ ...call, outcome: "skipped", reason: "its hook recorded it" }); + } else { + const knownCategory = settings.categories.some((c) => c.name === category); try { - const { path } = await writeSelfReportEvent({ + const { path, event } = await writeSelfReportEvent({ integration: agent, category, detail, cwd: opts.cwd ?? process.cwd(), now: opts.now?.(), }); + log({ ...call, outcome: "recorded", knownCategory, session: String(event.session_id) }); if (process.env[SELF_REPORT_RECEIPT_ENV] === "1") process.stderr.write(`${SELF_REPORT_RECEIPT_PREFIX}${path}\n`); } catch (err) { // The agent still hears "Recorded.": a report changes no decision, // and an error here would only make it retry. - process.stderr.write( - `[failproofai mcp] could not record a self report: ${err instanceof Error ? err.message : String(err)}\n`, - ); + const why = err instanceof Error ? err.message : String(err); + log({ ...call, outcome: "failed", knownCategory, reason: `write failed: ${why}` }); + process.stderr.write(`[failproofai mcp] could not record a self report: ${why}\n`); } } return ok({ content: [{ type: "text", text: SELF_REPORT_RESULT_TEXT }] }); @@ -491,7 +512,8 @@ export function runSelfReportMcpServer(opts: SelfReportMcpOptions = {}): Promise }); }); rl.on("close", () => { - void chain.then(() => resolveRun()); + // Events still on their way to the daemon's log get a moment, never more. + void chain.then(() => flushSelfReportLogs()).then(() => resolveRun()); }); }); } diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts index f5429a606..08b6b7a52 100644 --- a/src/hooks/self-report.ts +++ b/src/hooks/self-report.ts @@ -438,6 +438,29 @@ function selfReportOssMode(): boolean { } } +/** + * Why Self Reports is on or off, in the same order `resolveSelfReport` decides: + * `waiting` is a Cloud-enrolled machine with no setting from its org yet, and + * `unreadable` a settings file that cannot be read or parsed (both are off). + */ +export type SelfReportState = "on" | "off" | "waiting" | "unreadable"; + +export function selfReportSettingsState( + path: string = selfReportSettingsFile(), + enrolled: () => boolean = selfReportCloudEnrolled, +): SelfReportState { + const presence = selfReportFilePresence(path); + if (presence === "unreadable") return "unreadable"; + if (presence === "present") { + const file = readEffectiveSelfReport(path); + if (!file) return "unreadable"; + if (file.source !== "cloud" && enrolled()) return "waiting"; + return file.enabled ? "on" : "off"; + } + if (enrolled()) return "waiting"; + return selfReportLocalConfigOff() ? "off" : "on"; +} + /** The settings only when the feature is on (`resolveSelfReport`); `null` otherwise. */ export function readEnabledSelfReport(path?: string): SelfReportEffective | null { const s = resolveSelfReport(path); diff --git a/src/hooks/setup-finish.ts b/src/hooks/setup-finish.ts new file mode 100644 index 000000000..6ad35c690 --- /dev/null +++ b/src/hooks/setup-finish.ts @@ -0,0 +1,76 @@ +/** + * What `failproofai config` does after the wizard has applied: finish the + * upgrade (restart a Hermes or OpenClaw gateway that still runs an older + * plugin, or none) and bring every hooked agent's Self Reports MCP entry in + * line with `self-report.json`. + * + * All of it runs behind one spinner line and leaves at most the Self Reports + * line behind, plus a line for anything that needs the user: a gateway they + * must restart themselves, a Hermes failure, an agent the sync could not + * update. A gateway that is restarting by itself, and the per-agent MCP + * changes, are not the user's to act on, so they are not printed (`self-report + * sync` and `status` show those). + */ +import type { PluggedProfile } from "./update-run"; +import type { TTYOut } from "./tui"; + +export interface FinishSetupOptions { + /** This CLI's version. */ + version: string; + /** The plugged gateway profiles before the wizard ran. */ + pluggedBefore: PluggedProfile[]; + out?: TTYOut; +} + +/** Runs the steps; returns the exit code the upgrade part asks for (0 or 1). */ +export async function finishSetup(opts: FinishSetupOptions): Promise { + const out = opts.out ?? process.stdout; + const { runUpdateSteps, markUpdated, setupNeedsUpdateSteps, setupGatewayLine, restartNewlyPlugged } = await import("./update-run"); + const { progressLine, screenKit, colorsEnabled } = await import("./tui"); + const kit = screenKit({ color: colorsEnabled(out) }); + const keep: string[] = []; + let exit = 0; + const progress = progressLine(out, "Finishing setup…"); + try { + if (!setupNeedsUpdateSteps(opts.version)) { + // Already updated on this version: only a profile this run plugged in + // (one created since) has a gateway still running without the plugin. + const gateway = setupGatewayLine(await restartNewlyPlugged(opts.pluggedBefore).catch(() => [])); + if (gateway && !gateway.ok) keep.push(kit.caution(gateway.text)); + } else { + progress.set("Restarting agent gateways…"); + const run = await runUpdateSteps({ layout: false, daemon: false, restart: true }); + keep.push(...run.lines.filter((l) => l.startsWith("✕"))); + const gateway = setupGatewayLine(run.restarts); + if (gateway && !gateway.ok) keep.push(kit.caution(gateway.text)); + if (run.ok) markUpdated(opts.version); + else exit = 1; + } + // Self Reports (on by default): write self-report.json when it is missing + // off Cloud, then sync every hooked agent, also when setup found the + // machine already configured and wrote no hooks. Best-effort. + progress.set("Updating Self Reports…"); + const summary = await selfReportSetupSummary(); + if (summary) keep.push(summary.ok ? kit.ok(summary.text) : kit.caution(summary.text, summary.fix)); + } finally { + progress.done(keep); + } + return exit; +} + +/** Write the settings file if missing, sync, and say it in one line (or none). */ +export async function selfReportSetupSummary(): Promise<{ ok: boolean; text: string; fix?: string } | null> { + try { + const { ensureSelfReportSettingsFile, selfReportSettingsState } = await import("./self-report"); + try { + await ensureSelfReportSettingsFile(); + } catch { + // the readers apply the same default without the file + } + const { syncSelfReportMcp, selfReportSummary } = await import("./self-report-install"); + const results = await syncSelfReportMcp({ quiet: true }); + return selfReportSummary(results, selfReportSettingsState()); + } catch { + return null; // never fail setup over it + } +} diff --git a/src/hooks/tui.ts b/src/hooks/tui.ts index 7c7071927..2ce3ed30e 100644 --- a/src/hooks/tui.ts +++ b/src/hooks/tui.ts @@ -1662,6 +1662,45 @@ function ctx(opts?: RenderOpts): { cols: number; c: ReturnType } { return { cols: Math.max(20, opts?.cols ?? 80), c: paint(opts?.color ?? false) }; } +/** + * One spinner line for work that has nothing to show until it ends, drawn with + * the kit's `live()` block. `set` changes its text; `done` replaces it with the + * lines to keep (often none). Piped or under NO_COLOR nothing is drawn while it + * runs, and `done` prints its lines once. + */ +export function progressLine(out: TTYOut, text: string): { set(text: string): void; done(lines: string[]): void } { + if (!out.isTTY || !colorsEnabled(out)) { + return { + set() {}, + done(lines) { + if (lines.length > 0) out.write(`${lines.join("\n")}\n`); + }, + }; + } + const c = paint(true); + const region = screenKit(optsFor(out)).live(out); + const frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"; + let frame = 0; + let label = text; + const draw = (): void => region.draw(() => [`${c.ink3(frames[frame % frames.length])} ${c.ink3(label)}`]); + draw(); + const spin = setInterval(() => { + frame += 1; + draw(); + }, 100); + spin.unref?.(); + return { + set(next) { + label = next; + draw(); + }, + done(lines) { + clearInterval(spin); + region.done(lines); + }, + }; +} + /** Derive render options from a real stream, honouring NO_COLOR and non-TTY. */ export function optsFor(stdout: TTYOut = process.stdout): Required { return { cols: stdout.columns || 80, color: colorsEnabled(stdout) }; @@ -2461,6 +2500,13 @@ export function screenKit(opts: ScreenKitOpts = {}) { timer = null; pending = null; release(); + if (lines.length === 0) { + // Nothing to leave behind: erase the block and give the cursor back. + const clear = region.lastCount > 0 ? `${ESC}[${region.lastCount}A${ESC}[J` : ""; + if (clear || hidden) out.write(`${clear}${hidden ? `${ESC}[?25h` : ""}`); + region.lastCount = 0; + return; + } repaint(out, region, lines, { cut: false, tail: hidden ? `${ESC}[?25h` : "" }); }, }; From 60c53091d5132cda6d9ac1bf4b2e90509deb9737 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Sat, 28 Nov 2026 01:11:53 +0530 Subject: [PATCH 23/54] [self-reports] Test fake daemon ignores one-way selfReportLog frames (EPIPE in CI) Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/self-report-install.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/__tests__/hooks/self-report-install.test.ts b/__tests__/hooks/self-report-install.test.ts index a20b2ed10..e870ce21a 100644 --- a/__tests__/hooks/self-report-install.test.ts +++ b/__tests__/hooks/self-report-install.test.ts @@ -443,12 +443,16 @@ describe("which agents", () => { */ function fakeDaemon(path: string, answer = true, selfReport?: { instanceId: string; port: number }): Promise { const server = createNetServer((sock) => { + // The sync's one-way `selfReportLog` frames close their end straight away; + // answering one would write to a closed socket (EPIPE), so ignore the error. + sock.on("error", () => {}); let buf = Buffer.alloc(0); sock.on("data", (chunk) => { buf = Buffer.concat([buf, chunk as Buffer]); if (buf.length < 4 || buf.length < 4 + buf.readUInt32BE(0)) return; if (!answer) return; // accepted, never answered const req = JSON.parse(buf.subarray(4, 4 + buf.readUInt32BE(0)).toString("utf8")); + if (req.type === "selfReportLog") return; // one-way: never answered const body = Buffer.from(JSON.stringify({ type: "pong", protocolVersion: req.protocolVersion, ...(selfReport ? { selfReport } : {}) })); const head = Buffer.alloc(4); head.writeUInt32BE(body.length, 0); From e5187650519bcd124f65cfe8274c1ca1d6f75e74 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Sun, 29 Nov 2026 21:45:29 +0530 Subject: [PATCH 24/54] [self-reports] Visible report tool in every harness, failure hint, review blockers; 1.0.18-beta.4 Visibility: - Hermes: the plugin registers the tool natively and adds it to _HERMES_CORE_TOOLS, so tool search keeps it direct (checked against Hermes 0.20.0 and 0.21.3); instructions ride pre_llm_call. OpenClaw: a catalogMode "direct-only" plugin tool, instructions via before_prompt_build. Both hand calls to failproofaid's Self Reports server (instanceId-checked); sync writes no MCP entry for either. - Claude Code entry sets alwaysLoad, Antigravity's sets eager, Copilot gets a marked instructions file, Factory gets SessionStart context. Failure hint: one line of context after a clearly failed tool call, once per session, on Claude Code, Codex, Cursor, Copilot and Factory. Review blockers: Cloud settings bound to the enrolment (TS and Rust), SDK alias no longer early-allowed in the hook path, python -c exemption removed, hook-recorded dedup scoped to the call, Claude Code and Codex on stdio only. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 16 ++ Cargo.lock | 6 +- Cargo.toml | 2 +- .../fixtures/hermes-native-plugin-check.py | 114 ++++++++ __tests__/hooks/hermes-update.test.ts | 6 +- __tests__/hooks/integrations.test.ts | 4 +- __tests__/hooks/openclaw-self-report.test.ts | 133 +++++++++ __tests__/hooks/scope-attribution.test.ts | 2 +- __tests__/hooks/self-report-golden.test.ts | 8 +- __tests__/hooks/self-report-handler.test.ts | 27 ++ __tests__/hooks/self-report-hint.test.ts | 207 ++++++++++++++ .../hooks/self-report-hook-trust.test.ts | 97 ++++++- __tests__/hooks/self-report-install.test.ts | 125 +++++++-- __tests__/hooks/self-report.test.ts | 96 ++++++- __tests__/hooks/state-guard.test.ts | 44 ++- __tests__/hooks/two-tier/runner.ts | 9 + crates/failproofaid/src/cloud_client.rs | 37 ++- crates/failproofaid/src/self_report.rs | 150 ++++++++-- crates/failproofaid/tests/self_report_e2e.rs | 2 + crates/fpai-collect/src/self_report.rs | 218 ++++++++++++--- crates/fpai-collect/tests/self_report_mcp.rs | 18 +- docs/self-reports.mdx | 48 +++- hermes-plugin/__init__.py | 21 +- hermes-plugin/plugin.yaml | 2 +- hermes-plugin/self_report.py | 260 ++++++++++++++++++ openclaw-plugin/hooks.js | 3 +- openclaw-plugin/index.js | 5 +- openclaw-plugin/openclaw.plugin.json | 7 +- openclaw-plugin/self-report.js | 231 ++++++++++++++++ package.json | 2 +- src/hooks/builtin-policies.ts | 95 ++----- src/hooks/handler.ts | 16 +- src/hooks/integrations.ts | 2 +- src/hooks/self-report-cli.ts | 7 +- src/hooks/self-report-hint.ts | 225 +++++++++++++++ src/hooks/self-report-hook-trust.ts | 93 ++++++- src/hooks/self-report-install.ts | 195 ++++++++++--- src/hooks/self-report-mcp.ts | 9 +- src/hooks/self-report-names.ts | 7 +- src/hooks/self-report.ts | 100 ++++++- .../self-report/settings-cases.golden.json | 117 +++++++- 41 files changed, 2468 insertions(+), 298 deletions(-) create mode 100644 __tests__/hooks/openclaw-self-report.test.ts create mode 100644 __tests__/hooks/self-report-hint.test.ts create mode 100644 hermes-plugin/self_report.py create mode 100644 openclaw-plugin/self-report.js create mode 100644 src/hooks/self-report-hint.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 21893ace4..023dc9d0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## 1.0.18-beta.4 — 2026-11-29 + +### Features + +- Self Reports: the `report` tool is a direct tool on Hermes and OpenClaw, which defer MCP tools behind their tool search with no per-server switch (so the model saw only a name and never reported). failproofai's Hermes plugin registers it natively and puts it on Hermes' never-deferred list, and the OpenClaw plugin registers a `catalogMode: "direct-only"` tool; both put the server's instructions in the prompt (`pre_llm_call`, `before_prompt_build`) and hand each call to failproofaid's own Self Reports server, so the text, attribution, dedup and logs are the MCP path's. Sync writes no Hermes or OpenClaw MCP entry and removes the old ones (#1062) +- Self Reports: Claude Code's entry sets `alwaysLoad: true` (its tools are never deferred behind tool search), Antigravity's sets `eager: true` (direct tools rather than `call_mcp_tool`), Copilot gets the instructions in a marked `~/.copilot/instructions/failproofai-self-reports.instructions.md` (Copilot shows server instructions only for its built-in allowlist), and Factory droid, which defers every other MCP server, gets them as SessionStart context (#1062) +- Self Reports: after a tool call that clearly failed (a non-zero exit, a 401 or 403, `not found`, `permission denied`, an MCP `isError`, a tool error), one line of context once per session suggests calling `report` if the agent cannot fix it, on Claude Code, Codex, Cursor, Copilot (its failure event) and Factory. Never on success, on the report call, after a failproofai deny, or while Self Reports is off; it is not a policy and never replaces one's answer (#1062) + +### Fixes + +- Self Reports: a Cloud settings file is bound to the enrolment whose poll wrote it. After switching to another org, the previous org's "on" no longer records until the new org's setting arrives: every reader (CLI, hook, stdio server, the daemon's HTTP server) treats a file from another enrolment, or from before this change, as missing, which is off while enrolled (#1062) +- Self Reports: the SDK tool name `failproofai_report` is no longer let past the policies in the hook path. It is also OpenCode's name for a `report` tool on any MCP server called `failproofai`, so a foreign server's tool skipped every policy (#1062) +- `block-failproofai-commands` no longer treats any `python -c` program as a read: its read-only vetting could be bypassed with dynamic builtin lookups. Nothing in a command is treated as inert when the same command defines a function or alias, or sets `PATH` (#1062) +- Self Reports: the stdio server suppresses a Claude Code or Codex report only when that agent's hook recorded the same call: same working directory, and each hook row vouches for one call. A report the hook recorded in one project no longer swallows an identical one from another (#1062) +- Self Reports: Claude Code and Codex are registered over stdio, never on the daemon's endpoint, which records nothing for them. Their entry is user-wide while a project can turn the hooks off (`disableAllHooks` in `.claude/settings.local.json`), and every report from such a project was lost; the stdio server now records what the hook did not (#1062) + ## 1.0.18-beta.3 — 2026-11-27 ### Fixes diff --git a/Cargo.lock b/Cargo.lock index 769ed755c..8b9271b2b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -298,7 +298,7 @@ dependencies = [ [[package]] name = "failproofaid" -version = "1.0.18-beta.3" +version = "1.0.18-beta.4" dependencies = [ "fpai-collect", "fpai-ipc", @@ -361,7 +361,7 @@ dependencies = [ [[package]] name = "fpai-collect" -version = "1.0.18-beta.3" +version = "1.0.18-beta.4" dependencies = [ "axum", "getrandom 0.4.3", @@ -382,7 +382,7 @@ dependencies = [ [[package]] name = "fpai-ipc" -version = "1.0.18-beta.3" +version = "1.0.18-beta.4" dependencies = [ "libc", "proptest", diff --git a/Cargo.toml b/Cargo.toml index 9b2f8aee8..b5d2bd545 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "1.0.18-beta.3" +version = "1.0.18-beta.4" edition = "2024" license-file = "LICENSE" repository = "https://github.com/FailproofAI/failproofai" diff --git a/__tests__/fixtures/hermes-native-plugin-check.py b/__tests__/fixtures/hermes-native-plugin-check.py index e80aad162..b29af1aa8 100644 --- a/__tests__/fixtures/hermes-native-plugin-check.py +++ b/__tests__/fixtures/hermes-native-plugin-check.py @@ -1796,5 +1796,119 @@ def test_no_retry_below_the_oldest_supported_version(self) -> None: self.assertIn("protocol version mismatch", str(result)) self.assertEqual(len(received), 1) +self_report_mod = sys.modules[f"{plugin.__name__}.self_report"] + +SR_SERVER = {"instanceId": "inst-1", "port": 4319} +SR_SCHEMA = {"type": "object", "properties": {"category": {"type": "string"}, "detail": {"type": "string"}}} + + +def sr_rpc(calls: list, instance: str = "inst-1", tools: list | None = None): + def rpc(url, body, timeout): + calls.append((url, body)) + if body["method"] == "initialize": + return {"result": {"serverInfo": {"name": "failproofai_local", "instanceId": instance}, "instructions": "Report when stuck."}} + if body["method"] == "tools/list": + return {"result": {"tools": tools if tools is not None else [{"name": "report", "description": "Report it.", "inputSchema": SR_SCHEMA}]}} + return {"result": {"content": [{"type": "text", "text": "Recorded."}]}} + return rpc + + +class ToolContext(FakeContext): + def __init__(self, data_dir: Path) -> None: + super().__init__(data_dir) + self.tools: list[dict] = [] + + def register_tool(self, **kwargs) -> None: + self.tools.append(kwargs) + + +class SelfReportToolTests(unittest.TestCase): + """The report tool as a native Hermes tool (never behind tool search).""" + + def setUp(self) -> None: + self.fake_toolsets = ModuleType("toolsets") + self.fake_toolsets._HERMES_CORE_TOOLS = ["terminal"] + self._saved = sys.modules.get("toolsets") + sys.modules["toolsets"] = self.fake_toolsets + + def tearDown(self) -> None: + if self._saved is None: + sys.modules.pop("toolsets", None) + else: + sys.modules["toolsets"] = self._saved + + def test_discover_trusts_only_this_users_daemon(self) -> None: + calls: list = [] + tool = self_report_mod.discover_self_report_tool(lambda: SR_SERVER, sr_rpc(calls)) + self.assertEqual(tool["description"], "Report it.") + self.assertEqual(tool["inputSchema"], SR_SCHEMA) + self.assertEqual(tool["instructions"], "Report when stuck.") + self.assertTrue(calls[0][0].startswith("http://127.0.0.1:4319/mcp?agent=hermes")) + # Another daemon answering the port, Self Reports off, or no daemon: no tool. + self.assertIsNone(self_report_mod.discover_self_report_tool(lambda: SR_SERVER, sr_rpc([], instance="other"))) + self.assertIsNone(self_report_mod.discover_self_report_tool(lambda: SR_SERVER, sr_rpc([], tools=[]))) + self.assertIsNone(self_report_mod.discover_self_report_tool(lambda: None, sr_rpc([]))) + + def test_registers_a_direct_tool_with_the_servers_text(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + ctx = ToolContext(Path(tmp)) + state = self_report_mod.SelfReportTool(discover=lambda: {**SR_SERVER, "description": "Report it.", "inputSchema": SR_SCHEMA, "instructions": "Report when stuck."}) + self.assertIs(self_report_mod.register_self_report_tool(ctx, state), state) + [reg] = ctx.tools + self.assertEqual(reg["name"], "mcp_failproofai_local_report") + self.assertEqual(reg["toolset"], "failproofai") + self.assertEqual(reg["schema"], {"name": "mcp_failproofai_local_report", "description": "Report it.", "parameters": SR_SCHEMA}) + self.assertTrue(reg["check_fn"]()) + # On Hermes' never-deferred list, so tool search keeps it direct. + self.assertIn("mcp_failproofai_local_report", self.fake_toolsets._HERMES_CORE_TOOLS) + + def test_registers_nothing_while_self_reports_is_off_or_the_daemon_is_gone(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + ctx = ToolContext(Path(tmp)) + self.assertIsNone(self_report_mod.register_self_report_tool(ctx, self_report_mod.SelfReportTool(discover=lambda: None))) + self.assertEqual(ctx.tools, []) + self.assertNotIn("mcp_failproofai_local_report", self.fake_toolsets._HERMES_CORE_TOOLS) + + def test_a_register_tool_that_raises_never_breaks_register(self) -> None: + class Raising(ToolContext): + def register_tool(self, **kwargs) -> None: + raise RuntimeError("name taken") + with tempfile.TemporaryDirectory() as tmp: + state = self_report_mod.SelfReportTool(discover=lambda: {**SR_SERVER, "description": "d", "inputSchema": SR_SCHEMA, "instructions": ""}) + self.assertIsNone(self_report_mod.register_self_report_tool(Raising(Path(tmp)), state)) + + def test_a_call_goes_to_the_daemon_with_the_agent_cwd_and_normalised_arguments(self) -> None: + calls: list = [] + tool = {**SR_SERVER, "description": "d", "inputSchema": SR_SCHEMA} + text = self_report_mod.call_self_report_tool(tool, {"type": "looping", "summary": "again"}, "/work/p", lambda: SR_SERVER, sr_rpc(calls)) + self.assertEqual(text, "Recorded.") + url, body = calls[-1] + self.assertEqual(url, "http://127.0.0.1:4319/mcp?agent=hermes&cwd=%2Fwork%2Fp") + self.assertEqual(body["params"], {"name": "report", "arguments": {"category": "looping", "detail": "again"}}) + # The daemon restarted on another instance: nothing is sent there. + calls.clear() + self_report_mod.call_self_report_tool(tool, {}, "/w", lambda: {"instanceId": "new", "port": 4319}, sr_rpc(calls)) + self.assertEqual(calls, []) + + def test_pre_llm_call_carries_the_instructions_only_with_the_tool(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + instance = plugin.FailproofAIPlugin(FakeContext(Path(tmp))) + self.assertEqual(instance.pre_llm_call(), {"context": plugin._PROTOCOL_CONTEXT}) + instance.self_report = self_report_mod.SelfReportTool(discover=lambda: {**SR_SERVER, "description": "d", "inputSchema": SR_SCHEMA, "instructions": "Report when stuck."}) + context = instance.pre_llm_call()["context"] + self.assertTrue(context.startswith(plugin._PROTOCOL_CONTEXT)) + self.assertTrue(context.endswith("Report when stuck.")) + + def test_register_without_a_daemon_registers_hooks_and_no_tool(self) -> None: + with tempfile.TemporaryDirectory() as tmp, patch.dict(os.environ, {"FAILPROOFAI_DAEMON_SOCKET": str(Path(tmp) / "none.sock")}): + data_dir = Path(tmp) / "data" + ctx = ToolContext(data_dir) + plugin.register(ctx) + beat = json.loads((data_dir / "heartbeat.json").read_text()) + self.assertEqual(ctx.tools, []) + self.assertIs(beat["self_report_tool"], False) + self.assertIs(beat["register_ok"], True) + + if __name__ == "__main__": unittest.main() diff --git a/__tests__/hooks/hermes-update.test.ts b/__tests__/hooks/hermes-update.test.ts index 75c7cd94f..a6ff652e2 100644 --- a/__tests__/hooks/hermes-update.test.ts +++ b/__tests__/hooks/hermes-update.test.ts @@ -36,7 +36,7 @@ import { runHermesUpdateMigration } from "../../src/hooks/hermes-update"; import { FAILPROOFAI_HOOK_MARKER } from "../../src/hooks/types"; const ORIG_CWD = process.cwd(); -const PLUGIN_FILES = ["plugin.yaml", "__init__.py", "client.py", "ledger.py"]; +const PLUGIN_FILES = ["plugin.yaml", "__init__.py", "client.py", "ledger.py", "self_report.py"]; let tempDir: string; let packageRoot: string; @@ -158,7 +158,7 @@ describe("linked Hermes plugin install", () => { // plugin.yaml says name: failproofai. Neither is proof of ownership. const lookalike = resolve(tempDir, "vendor", "hermes-plugin"); mkdirSync(lookalike, { recursive: true }); - for (const f of ["plugin.yaml", "__init__.py", "client.py", "ledger.py"]) { + for (const f of ["plugin.yaml", "__init__.py", "client.py", "ledger.py", "self_report.py"]) { writeFileSync(resolve(lookalike, f), f === "plugin.yaml" ? "name: failproofai\n" : "# not ours\n"); } mkdirSync(resolve(home(), "plugins"), { recursive: true }); @@ -174,7 +174,7 @@ describe("linked Hermes plugin install", () => { const pkg = resolve(tempDir, "prefix", "lib", "node_modules", "failproofai"); mkdirSync(resolve(pkg, "hermes-plugin"), { recursive: true }); writeFileSync(resolve(pkg, "package.json"), JSON.stringify({ name: "failproofai", version: "1.0.9-beta.1" })); - for (const f of ["plugin.yaml", "__init__.py", "client.py", "ledger.py"]) { + for (const f of ["plugin.yaml", "__init__.py", "client.py", "ledger.py", "self_report.py"]) { writeFileSync(resolve(pkg, "hermes-plugin", f), f === "plugin.yaml" ? "name: failproofai\n" : "#\n"); } mkdirSync(resolve(home(), "plugins"), { recursive: true }); diff --git a/__tests__/hooks/integrations.test.ts b/__tests__/hooks/integrations.test.ts index 46038bd89..828d2b6b7 100644 --- a/__tests__/hooks/integrations.test.ts +++ b/__tests__/hooks/integrations.test.ts @@ -631,7 +631,7 @@ describe("Hermes integration", () => { /** What a 1.0.6–1.0.8 install left behind: a marked COPY of the plugin. */ function makeManagedCopy(destination: string): void { mkdirSync(destination, { recursive: true }); - for (const file of ["plugin.yaml", "__init__.py", "client.py", "ledger.py"]) { + for (const file of ["plugin.yaml", "__init__.py", "client.py", "ledger.py", "self_report.py"]) { cpSync(resolve(ORIG_CWD, "hermes-plugin", file), resolve(destination, file)); } writeFileSync(resolve(destination, ".failproofai-managed"), "Managed by failproofai.\n"); @@ -685,7 +685,7 @@ describe("Hermes integration", () => { const installedPlugin = pluginPath(path); expect(lstatSync(installedPlugin).isSymbolicLink()).toBe(true); expect(readlinkSync(installedPlugin)).toBe(resolve(packageRoot, "hermes-plugin")); - for (const file of ["plugin.yaml", "__init__.py", "client.py", "ledger.py"]) { + for (const file of ["plugin.yaml", "__init__.py", "client.py", "ledger.py", "self_report.py"]) { expect(existsSync(resolve(installedPlugin, file))).toBe(true); } expect(hermesProfileHealth()[0]).toMatchObject({ pluginMode: "link", healthy: true, cronUnchecked: false }); diff --git a/__tests__/hooks/openclaw-self-report.test.ts b/__tests__/hooks/openclaw-self-report.test.ts new file mode 100644 index 000000000..8248d92c5 --- /dev/null +++ b/__tests__/hooks/openclaw-self-report.test.ts @@ -0,0 +1,133 @@ +// @vitest-environment node +import { afterEach, describe, expect, it, vi } from "vitest"; +import { createServer, type Server } from "node:net"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { + SELF_REPORT_OPENCLAW_TOOL, + callSelfReportTool, + discoverSelfReportTool, + pingSelfReportServer, + prepareSelfReportArguments, + registerSelfReportTool, +} from "../../openclaw-plugin/self-report.js"; +import { isSelfReportToolName } from "../../src/hooks/self-report-names"; + +const SERVER = { instanceId: "inst-1", port: 4319 }; +const SCHEMA = { type: "object", properties: { category: { type: "string" }, detail: { type: "string" } } }; + +function fakeFetch(calls: Array<{ url: string; body: Record }>, opts: { instance?: string; tools?: unknown[] } = {}) { + return vi.fn(async (url: unknown, init?: { body?: unknown }) => { + const body = JSON.parse(String(init?.body)) as Record; + calls.push({ url: String(url), body }); + const reply = + body.method === "initialize" + ? { result: { serverInfo: { name: "failproofai_local", instanceId: opts.instance ?? "inst-1" }, instructions: "Report when stuck." } } + : body.method === "tools/list" + ? { result: { tools: opts.tools ?? [{ name: "report", description: "Report it.", inputSchema: SCHEMA }] } } + : { result: { content: [{ type: "text", text: "Recorded." }] } }; + return { ok: true, status: 200, json: async () => reply } as unknown as Response; + }) as unknown as typeof fetch; +} + +const servers: Server[] = []; +const dirs: string[] = []; +afterEach(() => { + for (const s of servers.splice(0)) s.close(); + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); +}); + +describe("OpenClaw Self Reports tool", () => { + it("is named with a spelling the hook lets past every policy", () => { + expect(isSelfReportToolName(SELF_REPORT_OPENCLAW_TOOL)).toBe(true); + const manifest = JSON.parse(readFileSync(resolve(__dirname, "../../openclaw-plugin/openclaw.plugin.json"), "utf8")); + expect(manifest.contracts.tools).toEqual([SELF_REPORT_OPENCLAW_TOOL]); + }); + + it("reads the daemon's selfReport server from its pong over the socket", async () => { + const dir = mkdtempSync(join(tmpdir(), "fpai-oc-sr-")); + dirs.push(dir); + const socketPath = join(dir, "d.sock"); + const server = createServer((sock) => { + sock.once("data", () => { + const body = Buffer.from(JSON.stringify({ type: "pong", protocolVersion: 2, selfReport: SERVER })); + const head = Buffer.alloc(4); + head.writeUInt32BE(body.length, 0); + sock.end(Buffer.concat([head, body])); + }); + }); + servers.push(server); + await new Promise((ok) => server.listen(socketPath, ok)); + expect(await pingSelfReportServer({ socketPath })).toEqual(SERVER); + expect(await pingSelfReportServer({ socketPath: join(dir, "none.sock") })).toBeNull(); + }); + + it("trusts only the endpoint that answers as this user's daemon, and offers nothing while off", async () => { + const calls: Array<{ url: string; body: Record }> = []; + const tool = await discoverSelfReportTool({ ping: async () => SERVER, fetchImpl: fakeFetch(calls) }); + expect(tool).toMatchObject({ description: "Report it.", inputSchema: SCHEMA, instructions: "Report when stuck.", port: 4319 }); + expect(calls[0].url).toBe("http://127.0.0.1:4319/mcp?agent=openclaw"); + expect(await discoverSelfReportTool({ ping: async () => SERVER, fetchImpl: fakeFetch([], { instance: "other" }) })).toBeNull(); + expect(await discoverSelfReportTool({ ping: async () => SERVER, fetchImpl: fakeFetch([], { tools: [] }) })).toBeNull(); + expect(await discoverSelfReportTool({ ping: async () => null, fetchImpl: fakeFetch([]) })).toBeNull(); + }); + + it("hands a call to the daemon with the workspace and normalised arguments", async () => { + const calls: Array<{ url: string; body: Record }> = []; + const tool = { ...SERVER, description: "d", inputSchema: SCHEMA }; + const text = await callSelfReportTool(tool, { category: "looping", detail: "again" }, "/work/p", { + ping: async () => SERVER, + fetchImpl: fakeFetch(calls), + }); + expect(text).toBe("Recorded."); + expect(calls[0].url).toBe("http://127.0.0.1:4319/mcp?agent=openclaw&cwd=%2Fwork%2Fp"); + expect(calls[0].body.params).toEqual({ name: "report", arguments: { category: "looping", detail: "again" } }); + // A different daemon instance now: nothing is sent. + const none: typeof calls = []; + await callSelfReportTool(tool, {}, "/w", { ping: async () => ({ instanceId: "new", port: 4319 }), fetchImpl: fakeFetch(none) }); + expect(none).toEqual([]); + expect(prepareSelfReportArguments({ type: "looping", summary: "s" })).toEqual({ category: "looping", detail: "s" }); + }); + + it("registers a direct-only tool and the system-prompt instructions once the daemon offers the tool", async () => { + let factory: ((ctx: unknown) => Record | null) | undefined; + const hooks: Record unknown> = {}; + const api = { + config: {}, + registerTool: vi.fn((f, opts) => { + factory = f; + expect(opts).toEqual({ name: SELF_REPORT_OPENCLAW_TOOL }); + }), + on: vi.fn((name: string, handler: (...a: unknown[]) => unknown) => { + hooks[name] = handler; + }), + }; + const call = vi.fn(async () => "Recorded."); + const workspace = { resolveWorkspace: vi.fn(() => "/work/p") }; + const sr = registerSelfReportTool(api, { + discover: async () => ({ ...SERVER, description: "Report it.", inputSchema: SCHEMA, instructions: "Report when stuck." }), + call, + workspace, + }); + await sr.refresh(); + const tool = factory!({ sessionKey: "s" })!; + expect(tool).toMatchObject({ name: SELF_REPORT_OPENCLAW_TOOL, description: "Report it.", parameters: SCHEMA, catalogMode: "direct-only" }); + const result = await (tool.execute as (id: string, p: unknown) => Promise)("call-1", { kind: "looping", reason: "r" }); + expect(call).toHaveBeenCalledWith(expect.objectContaining({ description: "Report it." }), { category: "looping", detail: "r" }, "/work/p"); + expect(result).toEqual({ content: [{ type: "text", text: "Recorded." }], details: { recorded: true } }); + expect(await hooks.before_prompt_build({}, {})).toEqual({ appendSystemContext: "Report when stuck." }); + }); + + it("offers no tool and no instructions while Self Reports is off or the daemon is gone", async () => { + let factory: ((ctx: unknown) => unknown) | undefined; + const hooks: Record unknown> = {}; + const sr = registerSelfReportTool( + { registerTool: (f: (ctx: unknown) => unknown) => (factory = f), on: (n: string, h: (...a: unknown[]) => unknown) => (hooks[n] = h) }, + { discover: async () => null }, + ); + await sr.refresh(); + expect(factory!({})).toBeNull(); + expect(await hooks.before_prompt_build({}, {})).toBeUndefined(); + }); +}); diff --git a/__tests__/hooks/scope-attribution.test.ts b/__tests__/hooks/scope-attribution.test.ts index 6ff6094ba..16727766a 100644 --- a/__tests__/hooks/scope-attribution.test.ts +++ b/__tests__/hooks/scope-attribution.test.ts @@ -58,7 +58,7 @@ describe("which scopes actually hold hooks", () => { ); const pluginDir = join(home, ".hermes", "plugins", "failproofai"); mkdirSync(pluginDir, { recursive: true }); - for (const file of ["plugin.yaml", "__init__.py", "client.py", "ledger.py", ".failproofai-managed"]) { + for (const file of ["plugin.yaml", "__init__.py", "client.py", "ledger.py", "self_report.py", ".failproofai-managed"]) { writeFileSync(join(pluginDir, file), "", "utf8"); } diff --git a/__tests__/hooks/self-report-golden.test.ts b/__tests__/hooks/self-report-golden.test.ts index 7ee275866..181c9bfb7 100644 --- a/__tests__/hooks/self-report-golden.test.ts +++ b/__tests__/hooks/self-report-golden.test.ts @@ -89,9 +89,13 @@ describe("Self Reports golden files (CLI)", () => { }); it("recognises every per-agent spelling of the tool, and nothing near it", () => { + // The golden list is the SDKs' and includes their own `failproofai_report`, + // which the hook path must never match: it is also OpenCode's name for + // tool `report` on a server called `failproofai`. for (const name of lines("tool-names.golden.txt")) { - expect(isSelfReportToolName(name), name).toBe(true); - expect(isSelfReportToolName(name.toUpperCase()), name).toBe(true); + const want = name !== "failproofai_report"; + expect(isSelfReportToolName(name), name).toBe(want); + expect(isSelfReportToolName(name.toUpperCase()), name).toBe(want); } // The Cloud gateway's server is `failproofai`; its tools are never ours. const gateway = ["mcp__failproofai__report", "failproofai__report", "failproofai___report", "mcp_failproofai_report", "failproofai-report", "failproofai/report"]; diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index c366c79f5..b73ce5bd3 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -37,6 +37,7 @@ import { readMergedHooksConfig } from "../../src/hooks/hooks-config"; import { jevChecksInstalled } from "../../src/hooks/effective-reviewers"; import { writePause } from "../../src/hooks/session-pause"; import { _resetForTest } from "../../src/hooks/hook-activity-store"; +import { INTEGRATION_TYPES } from "../../src/hooks/types"; import { HEALTH_PROBE_SOURCE } from "../../src/hooks/health-probe"; import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; @@ -307,6 +308,32 @@ describe("Self Reports short-circuit", () => { expect(rows().some((r) => r.selfReport !== undefined)).toBe(false); }); + // Review 4719314976: a foreign MCP server named `failproofai` (the Cloud + // gateway's usual name) must never have a tool early-allowed as ours, in any + // harness's spelling. `failproofai_report` is OpenCode's name for its + // `report` tool and also the SDK tool's name: neither skips the policies. + const FOREIGN_FAILPROOFAI_TOOLS = [ + "failproofai_report", + "mcp__failproofai__report", + "failproofai__report", + "failproofai___report", + "mcp_failproofai_report", + "failproofai-report", + "failproofai/report", + "failproofai.report", + "failproofai:report", + "mcp:failproofai:report", + ]; + it.each(INTEGRATION_TYPES.flatMap((cli) => FOREIGN_FAILPROOFAI_TOOLS.map((name) => [cli, name] as const)))( + "sends a foreign failproofai server's tool through the policies: %s %s", + async (cli, name) => { + const out = await evaluateHookEvent("PreToolUse", cli, payload(name, { category: "looping", detail: "x" })); + expect(out.evaluation?.decision).toBe("deny"); + expect(loadAllCustomHooks).toHaveBeenCalled(); + expect(rows().some((r) => r.selfReport !== undefined)).toBe(false); + }, + ); + it("does not early-allow Cursor or Antigravity calls naming the Cloud gateway's server failproofai", async () => { for (const event of ["preToolUse", "beforeMCPExecution"]) { const out = await evaluateHookEvent(event, "cursor", payload("report", { category: "looping", detail: "x" }, { mcp_server_name: "failproofai" })); diff --git a/__tests__/hooks/self-report-hint.test.ts b/__tests__/hooks/self-report-hint.test.ts new file mode 100644 index 000000000..1de50a350 --- /dev/null +++ b/__tests__/hooks/self-report-hint.test.ts @@ -0,0 +1,207 @@ +// @vitest-environment node +/** + * Self Reports' just-in-time hint: one line of model-visible context after a + * tool call that clearly failed, at most once per session, only while Self + * Reports is on, never on success, on the report call itself, or on a failure + * a failproofai deny caused. Not a policy: it never replaces a policy's answer. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +vi.mock("../../src/hooks/hooks-config", () => ({ + readMergedHooksConfig: vi.fn(() => ({ enabledPolicies: [] })), +})); +vi.mock("../../src/hooks/custom-hooks-loader", () => ({ loadAllCustomHooks: vi.fn() })); +vi.mock("../../src/hooks/hook-telemetry", () => ({ + trackHookEvent: vi.fn(() => Promise.resolve()), + flushHookTelemetry: vi.fn(() => Promise.resolve()), +})); +vi.mock("../../lib/telemetry-id", () => ({ getInstanceId: vi.fn(() => "test-instance-id") })); +vi.mock("../../src/hooks/untraced-note", () => ({ noteUntracedAgent: vi.fn(() => false) })); +vi.mock("../../src/hooks/pack-manifest", () => ({ + readInstalledPacks: vi.fn(() => ({ packs: [], errors: [] })), + hasInstalledPacks: vi.fn(() => false), + hasInstalledRegexPacks: vi.fn(() => false), +})); + +import { evaluateHookEvent } from "../../src/hooks/handler"; +import { loadAllCustomHooks } from "../../src/hooks/custom-hooks-loader"; +import { _resetForTest } from "../../src/hooks/hook-activity-store"; +import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; +import { SELF_REPORT_FAILURE_HINT, SELF_REPORT_HINT_CHANNELS, selfReportFailureHint, selfReportSessionStartContext, selfReportToolFailed } from "../../src/hooks/self-report-hint"; + +let home: string; +let policyDecision: "allow" | "deny" | "instruct" = "allow"; +let session = 0; +const sid = () => `hint-session-${session}`; + +function post(response: unknown, extra: Record = {}, tool = "Bash"): string { + return JSON.stringify({ session_id: sid(), cwd: "/tmp/project", tool_name: tool, tool_input: { command: "x" }, tool_response: response, ...extra }); +} +const FAILED = { stdout: "", stderr: "curl: (22) The requested URL returned error: 401 Unauthorized", interrupted: false }; +const OK = { stdout: "done", stderr: "", interrupted: false }; + +beforeEach(() => { + vi.clearAllMocks(); + session++; + policyDecision = "allow"; + home = mkdtempSync(join(tmpdir(), "fpai-sr-hint-")); + process.env.FAILPROOFAI_HOME = home; + process.env.FAILPROOFAI_STATE_DIR = join(home, "state"); + _resetForTest(join(home, "hook-activity")); + writeEffectiveSelfReport({ enabled: true }); + vi.mocked(loadAllCustomHooks).mockImplementation((async () => ({ + hooks: [ + Object.assign( + { + name: "switch", + description: "", + match: {}, + fn: async () => + policyDecision === "allow" ? { decision: "allow" } : { decision: policyDecision, reason: "policy says so" }, + }, + { __policyId: "custom:/tmp/switch.mjs:switch" }, + ), + ], + conventionSources: [], + })) as never); +}); + +afterEach(() => { + delete process.env.FAILPROOFAI_HOME; + delete process.env.FAILPROOFAI_STATE_DIR; + _resetForTest(); + rmSync(home, { recursive: true, force: true }); +}); + +describe("selfReportToolFailed", () => { + it.each([ + ["PostToolUseFailure", {}], + ["PostToolUse", { error: "boom" }], + ["PostToolUse", { tool_response: { isError: true, content: [{ type: "text", text: "x" }] } }], + ["PostToolUse", { tool_response: { exit_code: 1, output: "" } }], + ["PostToolUse", { tool_response: { success: false } }], + ["PostToolUse", { tool_response: { stderr: "bash: foo: command not found" } }], + ["PostToolUse", { tool_response: { stderr: "open /etc/x: permission denied" } }], + ["PostToolUse", { tool_response: "HTTP/1.1 403 Forbidden" }], + ["PostToolUse", { tool_response: { output: "Error: 401 Unauthorized" } }], + ["PostToolUse", { tool_response: "Process exited with code 2" }], + ])("%s %j is a failure", (event, payload) => { + expect(selfReportToolFailed(event, payload as Record)).toBe(true); + }); + it.each([ + ["PostToolUse", { tool_response: { stdout: "ok", stderr: "", exit_code: 0 } }], + ["PostToolUse", { tool_response: { output: `${"line of a file that says not found and 401 Unauthorized\n".repeat(40)}` } }], + ["PostToolUse", { tool_response: "all good" }], + ["PostToolUse", {}], + ["PreToolUse", { error: "x" }], + ])("%s %j is not a failure", (event, payload) => { + expect(selfReportToolFailed(event, payload as Record)).toBe(false); + }); +}); + +describe("the failure hint through the hook", () => { + it("adds one line of context after a failed call on Claude Code, once per session", async () => { + const first = await evaluateHookEvent("PostToolUse", "claude", post(FAILED)); + expect(first.exitCode).toBe(0); + expect(JSON.parse(first.stdout)).toEqual({ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: SELF_REPORT_FAILURE_HINT } }); + expect(first.evaluation?.decision).toBe("allow"); + const second = await evaluateHookEvent("PostToolUse", "claude", post(FAILED)); + expect(second.stdout).toBe(""); + // PostToolUseFailure is a failure by definition, but the session's hint is spent. + expect((await evaluateHookEvent("PostToolUseFailure", "claude", post({}))).stdout).toBe(""); + }); + + it("works with no policy installed at all", async () => { + vi.mocked(loadAllCustomHooks).mockImplementation((async () => ({ hooks: [], conventionSources: [] })) as never); + expect((await evaluateHookEvent("PostToolUse", "claude", post(FAILED))).stdout).toContain(SELF_REPORT_FAILURE_HINT); + }); + + it("says nothing after a successful call, and keeps the session's hint for a real failure", async () => { + expect((await evaluateHookEvent("PostToolUse", "claude", post(OK))).stdout).toBe(""); + expect((await evaluateHookEvent("PostToolUse", "claude", post(FAILED))).stdout).toContain(SELF_REPORT_FAILURE_HINT); + }); + + it("never follows the report call itself", async () => { + const out = await evaluateHookEvent("PostToolUse", "claude", post({ isError: true }, {}, "mcp__failproofai_local__report")); + expect(out.stdout).toBe(""); + }); + + it("is off while Self Reports is off", async () => { + writeEffectiveSelfReport({ enabled: false }); + expect((await evaluateHookEvent("PostToolUse", "claude", post(FAILED))).stdout).toBe(""); + }); + + it("never follows a failure a failproofai deny caused", async () => { + // The PreToolUse deny for this very call, then its failure. + policyDecision = "deny"; + const pre = await evaluateHookEvent("PreToolUse", "claude", post(undefined, { tool_use_id: "toolu_denied" })); + expect(pre.evaluation?.decision).toBe("deny"); + policyDecision = "allow"; + expect((await evaluateHookEvent("PostToolUseFailure", "claude", post({}, { tool_use_id: "toolu_denied" }))).stdout).toBe(""); + // A result that carries failproofai's own block message. + expect((await evaluateHookEvent("PostToolUse", "claude", post("Blocked by failproofai: no sudo"))).stdout).toBe(""); + // The hint was not spent: a genuine failure still gets it. + expect((await evaluateHookEvent("PostToolUse", "claude", post(FAILED))).stdout).toContain(SELF_REPORT_FAILURE_HINT); + }); + + it("never replaces a policy's own answer", async () => { + policyDecision = "instruct"; + const out = await evaluateHookEvent("PostToolUse", "claude", post(FAILED)); + expect(out.stdout).toContain("policy says so"); + expect(out.stdout).not.toContain(SELF_REPORT_FAILURE_HINT); + }); + + it("uses each agent's own channel", async () => { + const cursor = await evaluateHookEvent("postToolUse", "cursor", post(FAILED)); + expect(JSON.parse(cursor.stdout)).toEqual({ additional_context: SELF_REPORT_FAILURE_HINT }); + session++; + const factory = await evaluateHookEvent("PostToolUse", "factory", post(FAILED)); + expect(factory).toMatchObject({ exitCode: 2, stdout: "" }); + expect(factory.stderr).toContain(SELF_REPORT_FAILURE_HINT); + session++; + const codex = await evaluateHookEvent("PostToolUse", "codex", post(FAILED)); + expect(JSON.parse(codex.stdout).hookSpecificOutput.additionalContext).toBe(SELF_REPORT_FAILURE_HINT); + }); + + it("stays silent on agents with no after-a-tool channel", async () => { + for (const cli of ["opencode", "goose", "antigravity", "devin", "pi"] as const) { + session++; + const out = await evaluateHookEvent("PostToolUse", cli, post(FAILED)); + expect(out.stdout, cli).not.toContain(SELF_REPORT_FAILURE_HINT); + expect(out.stderr, cli).not.toContain(SELF_REPORT_FAILURE_HINT); + } + }); +}); + +describe("selfReportFailureHint", () => { + it("needs a session id to keep its once-per-session promise", () => { + expect(selfReportFailureHint({ cli: "claude", eventType: "PostToolUseFailure", payload: {}, sessionId: undefined, enabled: () => true })).toBeNull(); + expect(selfReportFailureHint({ cli: "claude", eventType: "PostToolUseFailure", payload: {}, sessionId: "s-direct", enabled: () => true })).not.toBeNull(); + }); + it("answers Copilot only on its failure event, in its flat shape", () => { + expect(SELF_REPORT_HINT_CHANNELS.copilot).toEqual({ PostToolUseFailure: "flat" }); + const out = selfReportFailureHint({ cli: "copilot", eventType: "PostToolUseFailure", payload: {}, sessionId: "s-cop", enabled: () => true }); + expect(JSON.parse(out!.stdout)).toEqual({ additionalContext: SELF_REPORT_FAILURE_HINT }); + }); +}); + +describe("SessionStart instructions where MCP tools are deferred with no switch", () => { + it("gives Factory droid the server's instructions at session start, only while on", async () => { + const out = await evaluateHookEvent("SessionStart", "factory", JSON.stringify({ session_id: sid(), cwd: "/tmp/project" })); + const ctx = JSON.parse(out.stdout).hookSpecificOutput; + expect(ctx.hookEventName).toBe("SessionStart"); + expect(ctx.additionalContext).toContain("call the `failproofai_local` MCP server's `report` tool once"); + expect(ctx.additionalContext).not.toContain("this server's"); + writeEffectiveSelfReport({ enabled: false }); + expect((await evaluateHookEvent("SessionStart", "factory", JSON.stringify({ session_id: sid(), cwd: "/tmp/project" }))).stdout).toBe(""); + }); + it("adds nothing for other agents or events", () => { + const on = { categories: [{ name: "looping", description: "d" }], guidance: null } as never; + expect(selfReportSessionStartContext("claude", "SessionStart", on)).toBeNull(); + expect(selfReportSessionStartContext("factory", "PreToolUse", on)).toBeNull(); + expect(selfReportSessionStartContext("factory", "SessionStart", null)).toBeNull(); + }); +}); diff --git a/__tests__/hooks/self-report-hook-trust.test.ts b/__tests__/hooks/self-report-hook-trust.test.ts index 0921f5867..be9cca7fa 100644 --- a/__tests__/hooks/self-report-hook-trust.test.ts +++ b/__tests__/hooks/self-report-hook-trust.test.ts @@ -135,12 +135,34 @@ describe("selfReportHookState (status, sync)", () => { deps: { daemonLive: async () => true, hooksInstalled: () => true, settings: { enabled: true, port: 4319 }, hookRecords: (a) => a === "claude", + // The HTTP path is off by default (next test); this exercises it. + httpAgents: ["claude", "codex"], }, }); expect(r.map((x) => [x.agent, x.transport])).toEqual([["claude", "http"], ["codex", "stdio"]]); expect(readFileSync(join(home, ".codex", "config.toml"), "utf8")).toContain('args = ["mcp", "--agent", "codex"]'); }); + // Review 4722003649: the entry is user-wide, but a Claude Code project can + // switch the hooks off (`.claude/settings.local.json`, `disableAllHooks`), + // and the daemon's endpoint records nothing for Claude Code. So by default + // no agent is put on HTTP, however healthy the daemon and the user hooks. + it("by default registers Claude Code and Codex over stdio even with a live daemon and hooks that record", async () => { + const project = join(home, "proj"); + mkdirSync(join(project, ".claude"), { recursive: true }); + writeFileSync(join(project, ".claude", "settings.local.json"), JSON.stringify({ disableAllHooks: true })); + const daemonLive = vi.fn(async () => true); + const r = await syncSelfReportMcp({ + quiet: true, binaryPath: BIN, agents: ["claude", "codex"], + deps: { daemonLive, hooksInstalled: () => true, settings: { enabled: true, port: 4319 }, hookRecords: () => true }, + }); + expect(r.map((x) => [x.agent, x.transport])).toEqual([["claude", "stdio"], ["codex", "stdio"]]); + expect(daemonLive).not.toHaveBeenCalled(); + expect(JSON.parse(readFileSync(join(home, ".claude.json"), "utf8")).mcpServers.failproofai_local).toEqual({ + type: "stdio", command: BIN, args: ["mcp", "--agent", "claude"], alwaysLoad: true, + }); + }); + it("status shows who records, repairs an untrusted Codex left on HTTP, and says how to trust the hooks", async () => { writeEffectiveSelfReport({ enabled: true }); let synced = 0; @@ -166,14 +188,23 @@ describe("selfReportHookState (status, sync)", () => { expect(text).toContain("reports recorded by the MCP server: Codex has not trusted failproofai's hooks"); expect(text).toContain("Trust them."); + // An HTTP entry is repaired even while the hook records: no agent belongs + // on HTTP any more (a project can switch the hooks off). const ok = await runSelfReportCommand(["status", "--verbose"], { probeEndpoint: async () => true, daemonLive: async () => true, registrations: () => [row("http", "http://127.0.0.1:4319/mcp?agent=codex")], hookState: () => ({ recorder: "hook" }), sync: async () => (synced++, []), }); - expect(synced).toBe(1); - expect(ok.lines.join("\n")).toContain("reports recorded by its hook"); + expect(synced).toBe(2); + const stdioOk = await runSelfReportCommand(["status", "--verbose"], { + probeEndpoint: async () => true, daemonLive: async () => true, + registrations: () => [row("stdio", BIN)], + hookState: () => ({ recorder: "hook" }), + sync: async () => (synced++, []), + }); + expect(synced).toBe(2); + expect(ok.lines.join("\n") + stdioOk.lines.join("\n")).toContain("reports recorded by its hook"); }); }); @@ -196,19 +227,57 @@ describe("the server records what the hook did not, once", () => { ); }; - it("a hook row with the same report suppresses it; a different one, an old one or another agent's does not", () => { + const projA = "/work/project-a"; + const projB = "/work/project-b"; + const hookRows = (...rows: Record[]) => { + mkdirSync(join(home, ".failproofai", "hook-activity"), { recursive: true }); + writeFileSync( + join(home, ".failproofai", "hook-activity", "current.jsonl"), + rows.map((over) => JSON.stringify({ timestamp: Date.now() - 1000, eventType: "PreToolUse", integration: "codex", sessionId: "s", decision: "allow", ...over })).join("\n") + "\n", + ); + }; + + it("a hook row with the same report in the same directory suppresses it; a different one, an old one or another agent's does not", () => { const args = { category: "invalid_tool_or_credential", detail: "token expired" }; - hookRow({ selfReport: { ...args, source: "mcp" } }); - expect(selfReportHookRecordedRecently("codex", args)).toBe(true); - expect(selfReportHookRecordedRecently("codex", { ...args, detail: "other" })).toBe(false); - expect(selfReportHookRecordedRecently("claude", args)).toBe(false); - hookRow({ selfReport: { ...args, source: "mcp" }, timestamp: Date.now() - 10 * 60 * 1000 }); - expect(selfReportHookRecordedRecently("codex", args)).toBe(false); - hookRow({ eventType: "PostToolUse", selfReport: { ...args, source: "mcp" } }); - expect(selfReportHookRecordedRecently("codex", args)).toBe(false); + const fresh = () => rmSync(join(home, ".failproofai", "cache"), { recursive: true, force: true }); + hookRow({ cwd: projA, selfReport: { ...args, source: "mcp" } }); + expect(selfReportHookRecordedRecently("codex", { ...args, detail: "other" }, Date.now(), projA)).toBe(false); + expect(selfReportHookRecordedRecently("claude", args, Date.now(), projA)).toBe(false); + expect(selfReportHookRecordedRecently("codex", args, Date.now())).toBe(false); // no cwd: never a match + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(true); + fresh(); + hookRow({ cwd: projA, selfReport: { ...args, source: "mcp" }, timestamp: Date.now() - 10 * 60 * 1000 }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); + hookRow({ cwd: projA, eventType: "PostToolUse", selfReport: { ...args, source: "mcp" } }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); + hookRow({ selfReport: { ...args, source: "mcp" } }); // a row with no cwd + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); // Aliased arguments are compared as the hook recorded them. - hookRow({ selfReport: { ...args, source: "mcp" } }); - expect(selfReportHookRecordedRecently("codex", { type: args.category, summary: args.detail })).toBe(true); + fresh(); + hookRow({ cwd: projA, selfReport: { ...args, source: "mcp" } }); + expect(selfReportHookRecordedRecently("codex", { type: args.category, summary: args.detail }, Date.now(), projA)).toBe(true); + }); + + // Review 4722003644: the same text in another project, or a second call, + // is a distinct report. + it("never lets one project's hook row suppress another project's report", () => { + const args = { category: "invalid_tool_or_credential", detail: "token expired" }; + hookRow({ cwd: projA, selfReport: { ...args, source: "mcp" } }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projB)).toBe(false); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(true); + }); + + it("lets each hook row vouch for one call only (repeated text, concurrent sessions)", () => { + const args = { category: "looping", detail: "same words" }; + // Two sessions in one directory, each with its own hook row. + hookRows( + { cwd: projA, sessionId: "s1", toolCallId: "t1", selfReport: { ...args, source: "mcp" } }, + { cwd: projA, sessionId: "s2", toolCallId: "t2", selfReport: { ...args, source: "mcp" } }, + ); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(true); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(true); + // A third identical call has no hook row of its own: recorded by the server. + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); }); it("an untrusted Codex's report lands once, on the session Codex's own rollout names", async () => { @@ -235,7 +304,7 @@ describe("the server records what the hook did not, once", () => { expect(events()).toEqual([expect.objectContaining({ integration: "codex", session_id: "codex-session-1", agent_id: "codex-proj", ...args })]); // The same call after the hook recorded it: nothing more. - hookRow({ selfReport: { ...args, source: "mcp" } }); + hookRow({ cwd: project, selfReport: { ...args, source: "mcp" } }); await handleSelfReportRpc(call(args), { agent: "codex", cwd: project }); expect(events()).toHaveLength(1); }); diff --git a/__tests__/hooks/self-report-install.test.ts b/__tests__/hooks/self-report-install.test.ts index e870ce21a..65ba7b702 100644 --- a/__tests__/hooks/self-report-install.test.ts +++ b/__tests__/hooks/self-report-install.test.ts @@ -9,6 +9,7 @@ import { parse as parseJsonc } from "jsonc-parser/lib/esm/main.js"; import { createServer as createHttpServer, type Server as HttpServer } from "node:http"; import { createServer as createNetServer, type Server as NetServer } from "node:net"; import { + SELF_REPORT_COMPANION_MARKER, SELF_REPORT_MCP_TARGETS, isOurMcpEntry, probeSelfReportHttp, @@ -45,6 +46,9 @@ function enabledOpts(extra: Partial = {}, daemon = tru hooksInstalled: () => true, hookRecords: () => true, settings: { enabled: true, port: 4319 }, + // No agent is on HTTP by default (SELF_REPORT_HTTP_AGENTS); most tests + // here exercise the HTTP path, which is kept, so they turn it on. + httpAgents: ["claude", "codex"], ...extra.deps, }, }; @@ -120,7 +124,7 @@ describe("syncSelfReportMcp: every agent round-trips", () => { // With a live daemon: HTTP for a hook-recorded agent, stdio for one the // server records (it must know the caller's cwd). - const want = selfReportHttpAllowed(agent) ? "http" : "stdio"; + const want = selfReportHttpAllowed(agent, ["claude", "codex"]) ? "http" : "stdio"; const first = await syncSelfReportMcp(enabledOpts({ agents: [agent] })); expect(first.map((r) => [r.action, r.status, r.transport])).toEqual( first.map(() => ["added", "ok", want]), @@ -154,11 +158,18 @@ describe("syncSelfReportMcp: every agent round-trips", () => { }); describe("transport choice", () => { - it("uses HTTP only for hook-recorded agents; every server-recorded agent stays on stdio", async () => { - expect(INTEGRATION_TYPES.filter((a) => selfReportHttpAllowed(a))).toEqual(["claude", "codex"]); - for (const a of SELF_REPORT_SERVER_RECORDS) expect(selfReportHttpAllowed(a as IntegrationType)).toBe(false); + it("puts no agent on HTTP by default, and when the HTTP path is on, never a server-recorded agent", async () => { + // Review 4722003649: Claude Code projects can switch the hooks off, so no + // agent relies on its hook through the daemon's endpoint by default. + expect(INTEGRATION_TYPES.filter((a) => selfReportHttpAllowed(a))).toEqual([]); + const defaults = await syncSelfReportMcp({ ...enabledOpts({}, true), deps: { ...enabledOpts({}, true).deps, httpAgents: undefined } }); + const extension = (a: IntegrationType) => SELF_REPORT_MCP_TARGETS[a].extension === true; + for (const x of defaults) expect(x.transport).toBe(extension(x.agent) ? "extension" : "stdio"); + const on = ["claude", "codex"] as const; + expect(INTEGRATION_TYPES.filter((a) => selfReportHttpAllowed(a, [...INTEGRATION_TYPES]))).toEqual(on); + for (const a of SELF_REPORT_SERVER_RECORDS) expect(selfReportHttpAllowed(a as IntegrationType, [...INTEGRATION_TYPES])).toBe(false); const r = await syncSelfReportMcp(enabledOpts({}, true)); - for (const x of r) expect(x.transport).toBe(x.agent === "pi" ? "extension" : selfReportHttpAllowed(x.agent) ? "http" : "stdio"); + for (const x of r) expect(x.transport).toBe(extension(x.agent) ? "extension" : selfReportHttpAllowed(x.agent, on) ? "http" : "stdio"); // Every agent's HTTP shape is still one we recognise (a stale one is moved). for (const a of INTEGRATION_TYPES) { const t = SELF_REPORT_MCP_TARGETS[a]; @@ -181,7 +192,7 @@ describe("transport choice", () => { it("uses stdio with the CLI path and --agent when no daemon is live", async () => { await syncSelfReportMcp(enabledOpts({ agents: ["claude", "codex", "opencode", "goose"] }, false)); - expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"] }); + expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"], alwaysLoad: true }); expect(entryIn("codex")).toEqual({ command: CLI, args: ["mcp", "--agent", "codex"] }); expect(entryIn("opencode")).toEqual({ type: "local", command: [CLI, "mcp", "--agent", "opencode"], enabled: true }); expect(entryIn("goose")).toMatchObject({ type: "stdio", cmd: CLI, args: ["mcp", "--agent", "goose"], enabled: true }); @@ -237,8 +248,8 @@ describe("transport choice", () => { const p = resolve(home, ".failproofai", "self-report.json"); put(p, JSON.stringify({ version: 1, enabled: true, mcp: { port: 5555, url: "http://127.0.0.1:5555/mcp" } })); expect(readSelfReportMcpSettings()).toEqual({ enabled: true, port: 5555 }); - await syncSelfReportMcp({ quiet: true, agents: ["claude"], deps: { daemonLive: async () => true, hooksInstalled: () => true } }); - expect(entryIn("claude")).toEqual({ type: "http", url: "http://127.0.0.1:5555/mcp?agent=claude" }); + await syncSelfReportMcp({ quiet: true, agents: ["claude"], deps: { daemonLive: async () => true, hooksInstalled: () => true, httpAgents: ["claude"] } }); + expect(entryIn("claude")).toEqual({ type: "http", url: "http://127.0.0.1:5555/mcp?agent=claude", alwaysLoad: true }); }); it("reads a missing file as on off Cloud, off on Cloud, and a broken file as off", async () => { @@ -298,15 +309,12 @@ describe("ownership", () => { (t) => (JSON.parse(t) as { mcp: Record }).mcp.failproofai], ["codex", `[mcp_servers.failproofai]\nurl = "${GATEWAY_URL}"\n`, (t) => (parseToml(t) as { mcp_servers: Record }).mcp_servers.failproofai], - ["hermes", `mcp_servers:\n failproofai:\n url: ${GATEWAY_URL}\n`, - (t) => (parseYaml(t) as { mcp_servers: Record }).mcp_servers.failproofai], ["goose", `extensions:\n failproofai:\n name: failproofai\n type: streamable_http\n enabled: true\n uri: ${GATEWAY_URL}\n`, (t) => (parseYaml(t) as { extensions: Record }).extensions.failproofai], ]; for (const [agent, text, gatewayOf] of gatewayFixtures) { it(`${agent}: leaves a Cloud gateway entry named failproofai untouched next to ours`, async () => { - if (agent === "hermes") put(resolve(home, ".hermes", "config.yaml"), text); - else put(pathOf(agent), text); + put(pathOf(agent), text); const path = pathOf(agent); const gateway = gatewayOf(read(path)); const added = await syncSelfReportMcp(enabledOpts({ agents: [agent] })); @@ -324,10 +332,10 @@ describe("ownership", () => { it("leaves a failproofai entry alone even when it is shaped like ours", async () => { const path = pathOf("claude"); - put(path, JSON.stringify({ mcpServers: { failproofai: { type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude" } } }, null, 2) + "\n"); + put(path, JSON.stringify({ mcpServers: { failproofai: { type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude", alwaysLoad: true } } }, null, 2) + "\n"); await syncSelfReportMcp(enabledOpts({ agents: ["claude"] })); removeSelfReportMcp({ agents: ["claude"], quiet: true }); - expect(JSON.parse(read(path)).mcpServers.failproofai).toEqual({ type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude" }); + expect(JSON.parse(read(path)).mcpServers.failproofai).toEqual({ type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude", alwaysLoad: true }); }); it("refuses a codex config whose inline mcp_servers table would collide, leaving it as is", async () => { @@ -373,12 +381,12 @@ describe("which agents", () => { it("keeps and repairs an existing registration whose hooks are only at project scope", async () => { // Installed with project-scope hooks (alsoHooked) while the daemon was up. await syncSelfReportMcp(enabledOpts({ agents: ["claude"], alsoHooked: ["claude"], deps: { hooksInstalled: () => false } }, true)); - expect(entryIn("claude")).toEqual({ type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude" }); + expect(entryIn("claude")).toEqual({ type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude", alwaysLoad: true }); // A later sync sees no user-scope hooks; the daemon is gone. The entry is // moved to stdio, not stranded on a dead endpoint. const r = await syncSelfReportMcp(enabledOpts({ agents: ["claude", "factory"], deps: { hooksInstalled: () => false } }, false)); expect(r.find((x) => x.agent === "claude")).toMatchObject({ action: "updated", transport: "stdio", status: "ok" }); - expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"] }); + expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"], alwaysLoad: true }); // An agent never registered and without hooks is still left alone. expect(r.find((x) => x.agent === "factory")).toMatchObject({ action: "skipped", status: "not-hooked" }); expect(existsSync(pathOf("factory"))).toBe(false); @@ -399,16 +407,78 @@ describe("which agents", () => { expect(entryIn("claude")).toBeUndefined(); }); - it("writes every Hermes profile", async () => { - put(resolve(home, ".hermes", "config.yaml"), "model: x\n"); - put(resolve(home, ".hermes", "profiles", "work", "config.yaml"), "model: y\n"); + // Hermes and OpenClaw defer MCP tools behind tool search with no + // per-server switch, so their tool now comes from failproofai's own plugin + // (hermes-plugin/self_report.py, openclaw-plugin/self-report.js): sync writes + // no MCP entry for either, takes out one an earlier version wrote in every + // profile, and keeps the user's own servers. + it("writes no Hermes or OpenClaw MCP entry and takes out every profile's old one", async () => { + const old = { command: CLI, args: ["mcp", "--agent", "hermes"] }; + put(resolve(home, ".hermes", "config.yaml"), `model: x\nmcp_servers:\n failproofai_local:\n command: ${CLI}\n args: [mcp, --agent, hermes]\n mine:\n command: node\n`); + put(resolve(home, ".hermes", "profiles", "work", "config.yaml"), `model: y\nmcp_servers:\n failproofai_local:\n command: ${CLI}\n args: [mcp, --agent, hermes]\n`); const r = await syncSelfReportMcp(enabledOpts({ agents: ["hermes"] })); - expect(r.map((x) => x.action)).toEqual(["added", "added"]); + expect(r.map((x) => x.action)).toEqual(["removed", "removed", "unchanged"]); + expect(r.at(-1)).toMatchObject({ transport: "extension", status: "ok" }); for (const p of [resolve(home, ".hermes", "config.yaml"), resolve(home, ".hermes", "profiles", "work", "config.yaml")]) { - const doc = parseYaml(read(p)) as { mcp_servers: { failproofai_local: unknown } }; - expect(doc.mcp_servers.failproofai_local).toEqual({ command: CLI, args: ["mcp", "--agent", "hermes"] }); - expect(read(p)).toContain("failproofai self-report MCP server"); + const doc = parseYaml(read(p)) as { mcp_servers?: Record }; + expect(doc.mcp_servers?.failproofai_local).toBeUndefined(); } + expect((parseYaml(read(resolve(home, ".hermes", "config.yaml"))) as { mcp_servers: Record }).mcp_servers.mine).toEqual({ command: "node" }); + expect(old.args).toEqual(["mcp", "--agent", "hermes"]); + // A second sync writes nothing. + const again = await syncSelfReportMcp(enabledOpts({ agents: ["hermes"] })); + expect(again.map((x) => x.action)).toEqual(["unchanged"]); + + put(pathOf("openclaw"), JSON.stringify({ mcp: { servers: { failproofai_local: { command: CLI, args: ["mcp", "--agent", "openclaw"] }, mine: { command: "node" } } } })); + const oc = await syncSelfReportMcp(enabledOpts({ agents: ["openclaw"] })); + expect(oc.map((x) => x.action)).toEqual(["removed", "unchanged"]); + const servers = (JSON.parse(read(pathOf("openclaw"))) as { mcp: { servers: Record } }).mcp.servers; + expect(servers.failproofai_local).toBeUndefined(); + expect(servers.mine).toEqual({ command: "node" }); + expect(selfReportRegistrationStatus({ agents: ["hermes", "openclaw"], hooksInstalled: () => true }).map((x) => [x.agent, x.transport])).toEqual([ + ["hermes", "extension"], + ["openclaw", "extension"], + ]); + }); + + it("keeps Claude Code's tools out of tool search (alwaysLoad) and Antigravity's out of call_mcp_tool (eager)", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["claude", "antigravity", "cursor"] }, false)); + expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"], alwaysLoad: true }); + expect(entryIn("antigravity")).toEqual({ command: CLI, args: ["mcp", "--agent", "antigravity"], eager: true }); + // Only our entries: another agent's shape is unchanged. + expect(entryIn("cursor")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "cursor"] }); + // An entry an earlier version wrote without the flag is updated in place. + put(pathOf("antigravity"), JSON.stringify({ mcpServers: { failproofai_local: { command: CLI, args: ["mcp", "--agent", "antigravity"] } } })); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["antigravity"] }, false)); + expect(r[0]).toMatchObject({ action: "updated" }); + expect(entryIn("antigravity")).toMatchObject({ eager: true }); + }); + + it("writes Copilot's instructions file beside its entry, and removes it with the entry", async () => { + const instructions = resolve(home, ".copilot", "instructions", "failproofai-self-reports.instructions.md"); + await syncSelfReportMcp(enabledOpts({ agents: ["copilot"] }, false)); + const text = read(instructions); + expect(text.startsWith('---\napplyTo: "**"\n---\n')).toBe(true); + expect(text).toContain(SELF_REPORT_COMPANION_MARKER); + expect(text).toContain("`report` tool of the `failproofai_local` MCP server"); + // Hooks no longer detected but our entry is still there: the entry is kept, and the file repaired. + rmSync(instructions); + await syncSelfReportMcp(enabledOpts({ agents: ["copilot"], deps: { hooksInstalled: () => false } }, false)); + expect(existsSync(instructions)).toBe(true); + removeSelfReportMcp({ agents: ["copilot"], quiet: true }); + expect(existsSync(instructions)).toBe(false); + // A file of the same name that is not ours is never touched. + put(instructions, "my own notes\n"); + await syncSelfReportMcp(enabledOpts({ agents: ["copilot"] }, false)); + expect(read(instructions)).toBe("my own notes\n"); + removeSelfReportMcp({ agents: ["copilot"], quiet: true }); + expect(read(instructions)).toBe("my own notes\n"); + }); + + it("puts Copilot's instructions file under COPILOT_HOME", async () => { + vi.stubEnv("COPILOT_HOME", resolve(home, "cop")); + await syncSelfReportMcp(enabledOpts({ agents: ["copilot"] }, false)); + expect(existsSync(resolve(home, "cop", "instructions", "failproofai-self-reports.instructions.md"))).toBe(true); }); it("honours CLAUDE_CONFIG_DIR, CODEX_HOME and COPILOT_HOME", async () => { @@ -506,7 +576,7 @@ describe("live transport check", () => { deps: { hooksInstalled: () => true, settings: { enabled: true, port } }, }); expect(r[0]).toMatchObject({ action: "added", transport: "stdio" }); - expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"] }); + expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"], alwaysLoad: true }); }); it("a daemon answering ping AND an MCP initialize gives http; a later sync moves it back once it is gone", async () => { @@ -514,9 +584,12 @@ describe("live transport check", () => { const { server, port } = await fakeMcp(); const daemon = await fakeDaemon(socket(), true, { instanceId: "inst-1", port }); expect(await selfReportDaemonLive(port)).toBe(true); - const opts = { quiet: true, agents: ["claude"] as IntegrationType[], binaryPath: CLI, deps: { hooksInstalled: () => true, settings: { enabled: true, port } } }; + const opts = { + quiet: true, agents: ["claude"] as IntegrationType[], binaryPath: CLI, + deps: { hooksInstalled: () => true, settings: { enabled: true, port }, httpAgents: ["claude"] as IntegrationType[] }, + }; expect((await syncSelfReportMcp(opts))[0]).toMatchObject({ action: "added", transport: "http" }); - expect(entryIn("claude")).toEqual({ type: "http", url: `http://127.0.0.1:${port}/mcp?agent=claude` }); + expect(entryIn("claude")).toEqual({ type: "http", url: `http://127.0.0.1:${port}/mcp?agent=claude`, alwaysLoad: true }); await new Promise((ok) => daemon.close(ok)); await new Promise((ok) => server.close(ok)); diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index de646a076..2478575d8 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -19,6 +19,9 @@ import { resolveSelfReport, selfReportArgs, selfReportCloudEnrolled, + selfReportEnrolmentId, + selfReportEnrolmentIdOf, + selfReportSettingsState, selfReportCloudManaged, validateSelfReportCategories, validateSelfReportGuidance, @@ -52,7 +55,7 @@ const savedEnv: Record = {}; beforeEach(() => { home = mkdtempSync(join(tmpdir(), "fpai-sr-")); - for (const k of ["FAILPROOFAI_HOME", "FAILPROOFAI_CLOUD_URL", "FAILPROOFAI_CLOUD_CREDENTIALS", "FAILPROOFAI_SELF_REPORT_PORT"]) { + for (const k of ["FAILPROOFAI_HOME", "FAILPROOFAI_CLOUD_URL", "FAILPROOFAI_CLOUD_TOKEN", "FAILPROOFAI_MACHINE_ID", "FAILPROOFAI_CLOUD_CREDENTIALS", "FAILPROOFAI_SELF_REPORT_PORT"]) { savedEnv[k] = process.env[k]; delete process.env[k]; } @@ -100,11 +103,11 @@ describe("tool text and schema (contract §3)", () => { }); describe("tool-name matching (contract §1)", () => { - it.each(["mcp__failproofai_local__report", "failproofai_local__report", "failproofai_report", "failproofai_local.report", "failproofai_local/report", "MCP__FAILPROOFAI_LOCAL__REPORT"])( + it.each(["mcp__failproofai_local__report", "failproofai_local__report", "failproofai_local.report", "failproofai_local/report", "MCP__FAILPROOFAI_LOCAL__REPORT"])( "matches %s", (name) => expect(isSelfReportToolName(name)).toBe(true), ); - it.each(["report", "mcp__other__report", "mcp__failproofai__report", "failproofai__report", "mcp__failproofai_local__report2", "xfailproofai_report", "Bash", "", undefined, 7])( + it.each(["report", "mcp__other__report", "mcp__failproofai__report", "failproofai__report", "mcp__failproofai_local__report2", "xfailproofai_report", "failproofai_report", "FAILPROOFAI_REPORT", "Bash", "", undefined, 7])( "does not match %s", (name) => expect(isSelfReportToolName(name)).toBe(false), ); @@ -198,15 +201,81 @@ describe("resolveSelfReport: on by default (contract §4)", () => { describe("settings-cases.golden.json: the same on/off as the daemon's readers", () => { const fixture = JSON.parse( readFileSync(resolve(__dirname, "..", "..", "test-fixtures", "self-report", "settings-cases.golden.json"), "utf8"), - ) as { cases: { name: string; file?: unknown; text?: string; enrolled: boolean; on: boolean }[] }; + ) as { + cases: { name: string; file?: unknown; text?: string; enrolled: boolean; currentEnrolment?: string; on: boolean }[]; + enrolmentIds: { url: string; machineId: string; token: string; id: string }[]; + }; for (const c of fixture.cases) { it(c.name, () => { const path = join(home, "self-report.json"); if (c.text !== undefined) writeFileSync(path, c.text); else if (c.file !== null && c.file !== undefined) writeFileSync(path, JSON.stringify(c.file, null, 2)); - expect(resolveSelfReport(path, () => c.enrolled)?.enabled === true).toBe(c.on); + expect(resolveSelfReport(path, () => c.enrolled, () => c.currentEnrolment ?? null)?.enabled === true).toBe(c.on); }); } + it("computes the same enrolment ids as the daemon", () => { + for (const v of fixture.enrolmentIds) expect(selfReportEnrolmentIdOf(v.url, v.machineId, v.token)).toBe(v.id); + }); +}); + +describe("a Cloud file is bound to the enrolment that wrote it (review 4719314971)", () => { + const cloudFile = (id: string | undefined, enabled = true) => ({ + version: 1, enabled, source: "cloud", categories: DEFAULT_CATEGORIES, guidance: null, + mcp: { port: 4319, url: "http://127.0.0.1:4319/mcp" }, updatedAt: "2026-11-29T00:00:00Z", + ...(id ? { enrolment: id } : {}), + }); + const enrol = (token: string) => + writeFileSync(join(home, "credentials.json"), JSON.stringify({ cloud: { url: "https://app.example.test", machine_id: "machine-1", token } })); + it("org A's 'on' stops deciding the moment the credential switches to org B", async () => { + enrol("tok-org-a"); + const idA = selfReportEnrolmentId(); + expect(idA).toBe(selfReportEnrolmentIdOf("https://app.example.test", "machine-1", "tok-org-a")); + writeFileSync(join(home, "self-report.json"), JSON.stringify(cloudFile(idA!))); + expect(resolveSelfReport()?.enabled).toBe(true); + expect(selfReportSettingsState()).toBe("on"); + // Switch to org B; B's first answer has not been written yet. + enrol("tok-org-b"); + expect(selfReportEnrolmentId()).not.toBe(idA); + expect(resolveSelfReport()).toBeNull(); + expect(selfReportSettingsState()).toBe("waiting"); + // Every reader agrees: the stdio server lists no tool and records nothing. + const listed = await handleSelfReportRpc({ jsonrpc: "2.0", id: 1, method: "tools/list" }); + expect((listed as { result: { tools: unknown[] } }).result.tools).toEqual([]); + // B's answer, bound to B, decides. + writeFileSync(join(home, "self-report.json"), JSON.stringify(cloudFile(selfReportEnrolmentId()!, false))); + expect(resolveSelfReport()?.enabled).toBe(false); + }); + it("a cloud file with no enrolment (an older daemon) or an unreadable credential is off while enrolled", () => { + enrol("tok-org-a"); + writeFileSync(join(home, "self-report.json"), JSON.stringify(cloudFile(undefined))); + expect(resolveSelfReport()).toBeNull(); + writeFileSync(join(home, "self-report.json"), JSON.stringify(cloudFile(selfReportEnrolmentId()!))); + expect(resolveSelfReport()?.enabled).toBe(true); + writeFileSync(join(home, "credentials.json"), "{broken"); + expect(selfReportCloudEnrolled()).toBe(true); + expect(selfReportEnrolmentId()).toBeNull(); + expect(resolveSelfReport()).toBeNull(); + }); + it("reads the id from the env, the named credential file and the legacy cloud.json like the daemon", () => { + process.env.FAILPROOFAI_CLOUD_URL = " https://app.example.test "; + expect(selfReportEnrolmentId()).toBeNull(); // no token or machine id: the daemon's resolve errors + process.env.FAILPROOFAI_CLOUD_TOKEN = "tok-org-a"; + process.env.FAILPROOFAI_MACHINE_ID = "machine-1"; + expect(selfReportEnrolmentId()).toBe(selfReportEnrolmentIdOf("https://app.example.test", "machine-1", "tok-org-a")); + delete process.env.FAILPROOFAI_CLOUD_URL; + delete process.env.FAILPROOFAI_CLOUD_TOKEN; + delete process.env.FAILPROOFAI_MACHINE_ID; + writeFileSync(join(home, "cloud.json"), JSON.stringify({ schemaVersion: 1, url: "u", machineId: "m", token: "t" })); + expect(selfReportEnrolmentId()).toBe(selfReportEnrolmentIdOf("u", "m", "t")); + const named = join(home, "named.json"); + writeFileSync(named, JSON.stringify({ schemaVersion: 1, url: "u2", machineId: "m", token: "t" })); + process.env.FAILPROOFAI_CLOUD_CREDENTIALS = named; + try { + expect(selfReportEnrolmentId()).toBe(selfReportEnrolmentIdOf("u2", "m", "t")); + } finally { + delete process.env.FAILPROOFAI_CLOUD_CREDENTIALS; + } + }); }); describe("enrolling with a local settings file in place", () => { @@ -215,6 +284,8 @@ describe("enrolling with a local settings file in place", () => { expect(resolveSelfReport()?.enabled).toBe(true); // Enrolled now; the daemon's first poll has not been applied yet. process.env.FAILPROOFAI_CLOUD_URL = "https://cloud.example.invalid"; + process.env.FAILPROOFAI_CLOUD_TOKEN = "tok"; + process.env.FAILPROOFAI_MACHINE_ID = "machine"; expect(resolveSelfReport()).toBeNull(); // Every reader agrees: the stdio server hides the tool, the hook records nothing. const listed = await handleSelfReportRpc({ jsonrpc: "2.0", id: 1, method: "tools/list" }); @@ -222,7 +293,12 @@ describe("enrolling with a local settings file in place", () => { const status = await runSelfReportCommand(["status", "--verbose"], { registrations: () => [], probeEndpoint: async () => false, daemonExpected: () => false }); expect(status.lines[0]).toContain("off (waiting for FailproofAI Cloud"); // The org's setting arrives (the daemon writes a cloud file): it decides. - const cloud = { ...JSON.parse(readFileSync(join(home, "self-report.json"), "utf8")), source: "cloud", enabled: true }; + const cloud = { + ...JSON.parse(readFileSync(join(home, "self-report.json"), "utf8")), + source: "cloud", + enabled: true, + enrolment: selfReportEnrolmentIdOf("https://cloud.example.invalid", "machine", "tok"), + }; writeFileSync(join(home, "self-report.json"), JSON.stringify(cloud)); expect(resolveSelfReport()?.enabled).toBe(true); writeFileSync(join(home, "self-report.json"), JSON.stringify({ ...cloud, enabled: false })); @@ -493,7 +569,7 @@ describe("failproofai mcp (stdio, spawned)", () => { join(home, "hook-activity", "current.jsonl"), JSON.stringify({ timestamp: Date.now() - 500, eventType: "PreToolUse", integration: "claude", sessionId: "c1", decision: "allow", - toolName: "mcp__failproofai_local__report", selfReport: { ...CALL_ARGS, source: "mcp" }, + cwd: home, toolName: "mcp__failproofai_local__report", selfReport: { ...CALL_ARGS, source: "mcp" }, }) + "\n", ); await runMcp(["--agent", "claude"], [INIT, CALL], home); @@ -725,12 +801,16 @@ describe("failproofai self-report enable | disable | status", () => { expect(text).toContain("updated in Claude Code (stdio)"); expect(text).toMatch(/claude +stdio/); - // Healthy, or skipSync: no write. + // An answering HTTP endpoint is still repaired: no agent belongs on HTTP + // any more (a Claude Code project can switch its hooks off). synced = 0; rows = [row({ transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" })]; await runSelfReportCommand(["status", "--verbose"], { probeEndpoint: async () => true, daemonLive: async () => true, registrations: () => rows, sync: async () => (synced++, []), }); + expect(synced).toBe(1); + // skipSync: no write. + synced = 0; await runSelfReportCommand(["status", "--verbose"], { skipSync: true, probeEndpoint: async () => false, registrations: () => rows, sync: async () => (synced++, []) }); expect(synced).toBe(0); }); diff --git a/__tests__/hooks/state-guard.test.ts b/__tests__/hooks/state-guard.test.ts index 3fc219e2f..271b589f5 100644 --- a/__tests__/hooks/state-guard.test.ts +++ b/__tests__/hooks/state-guard.test.ts @@ -673,11 +673,11 @@ describe("block-failproofai-commands — the state guard", () => { // enforcement silently; an allowlist miss denies a command the operator can // see and report. These two are misses of the second kind — a backup and a // read — and they are pinned so the next person knows they are a decision - // rather than an accident. A `python -c` read used to be the second one; - // it is allowed now only when `pythonCodeOnlyReads` can vet the program - // (see "reads and mentions are not tampering" below), and an interpreter - // program it cannot vet is still over-denied. - it("over-denies a tar backup and an interpreter read it cannot vet, which is the chosen failure", async () => { + // rather than an accident. A `python -c` read is the second one: no + // syntactic check can prove a Python program only reads (a vetting + // exemption was bypassed with dynamic builtin lookups), so every + // interpreter program that names the state is denied. + it("over-denies a tar backup and an interpreter read, which is the chosen failure", async () => { expect(await decide("tar -cf /tmp/backup.tar ~/.failproofai")).toBe("deny"); expect(await decide("python3 -c \"import os; print(open('/home/u/.failproofai/policies-config.json').read())\"")).toBe("deny"); expect(await decide("node -e \"console.log(require('fs').readFileSync('/home/u/.failproofai/policies-config.json','utf8'))\"")).toBe("deny"); @@ -815,13 +815,10 @@ describe("block-failproofai-commands — the state guard", () => { // server's name, and a heredoc that only wrote notes mentioning the CLI. describe("reads and mentions are not tampering", () => { const F = "fail" + "proofai"; - it("allows a jq whose filter has a pipe, and a vetted python -c read", async () => { + it("allows a jq whose filter has a pipe", async () => { for (const c of [ `jq '.categories | length' ~/.${F}/self-report.json`, `jq -r '.enabled, .source' ~/.${F}/self-report.json`, - `python3 -c "import json; print(json.load(open('/home/u/.${F}/self-report.json'))['enabled'])"`, - `python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(d["source"])' ~/.${F}/self-report.json`, - `python3 -c "import json; print(open('/home/u/.${F}/self-report.json', 'r', encoding='utf-8').read())"`, ]) expect(await decide(c), c).toBe("allow"); }); @@ -859,6 +856,24 @@ describe("block-failproofai-commands — the state guard", () => { ]) expect(await decide(c), c).toBe("deny"); }); + // A quoted grep/jq/cat argument is inert only while the command word is + // the real tool: a function, alias or PATH set up in the same command can + // make `grep` run its arguments. + it("treats nothing as inert when the same command can redefine the command word", async () => { + // Without this rule each is allowed (the cut hides the CLI inside a + // quoted pattern), and each runs the CLI, because the command word is not + // the real tool. + for (const c of [ + `grep() { eval "$1"; }; grep '(${F} config --pause)'`, + `function grep { eval "$1"; }; grep '(${F} config --pause)'`, + `PATH=/tmp/x grep '(${F} config --pause)' f`, + `export PATH=/tmp/x:$PATH; grep -E '(${F} config --pause)' f`, + `alias grep=eval; grep '(${F} config --pause)'`, + `jq() { eval "$1"; }; jq '(${F} config --pause)'`, + `cat() { sh; }; cat <<'EOF'\n${F} config --pause\nEOF`, + ]) expect(await decide(c), c).toBe("deny"); + }); + it("still runs a heredoc's body when it can execute", async () => { for (const c of [ `sh <<'EOF'\n${F} config --pause\nEOF`, @@ -892,8 +907,17 @@ describe("block-failproofai-commands — the state guard", () => { ]) expect(await denialIsAboutState(c), c).toBe(true); }); - it("denies a python -c it cannot vet as a read", async () => { + // Review 4722003642: the `python -c` read exemption is gone. Every one of + // these names the state from a Python program and is denied, the + // dynamic-builtin escapes that walked past the old vetting included. + it("denies every python -c that names the state, reads included", async () => { for (const c of [ + `python3 -c 'import sys; sys._getframe().f_builtins["o"+"pen"](sys.argv[1], "w")' ~/.${F}/self-report.json`, + `python3 -c 'import sys; b=sys._getframe().f_builtins; b["op"+"en"](sys.argv[1],"w")' ~/.${F}/policies-config.json`, + `python3 -c 'import json; json.loads.__globals__' ~/.${F}/a`, + `python3 -c "import json; print(json.load(open('/home/u/.${F}/self-report.json'))['enabled'])"`, + `python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(d["source"])' ~/.${F}/self-report.json`, + `python3 -c "import json; print(open('/home/u/.${F}/self-report.json', 'r', encoding='utf-8').read())"`, `python3 -c "import os; os.remove('/home/u/.${F}/self-report.json')"`, `python3 -c "open('/home/u/.${F}/self-report.json','w').write('{}')"`, `python3 -c "import json;o=open;o('/x/.${F}/a','w')"`, diff --git a/__tests__/hooks/two-tier/runner.ts b/__tests__/hooks/two-tier/runner.ts index e3342f117..3224766ef 100644 --- a/__tests__/hooks/two-tier/runner.ts +++ b/__tests__/hooks/two-tier/runner.ts @@ -52,6 +52,15 @@ export function enterSandbox(): CorpusSandbox { const packs = join(root, "packs"); mkdirSync(fpHome, { recursive: true }); mkdirSync(packs, { recursive: true }); + // Self Reports off. The golden was recorded before Self Reports existed, and + // on by default it now answers Factory's SessionStart with its instructions + // and adds a one-time hint after a failed tool call: intended, and pinned + // in __tests__/hooks/self-report-hint.test.ts, not here, where the claim is + // only that Jev unconfigured changes nothing. + writeFileSync( + join(fpHome, "self-report.json"), + JSON.stringify({ version: 1, enabled: false, source: "local", categories: [], guidance: null, mcp: { port: 4319, url: "http://127.0.0.1:4319/mcp" }, updatedAt: "" }), + ); process.env.HOME = home; process.env.FAILPROOFAI_HOME = fpHome; process.env.FAILPROOFAI_PACK_DIR = packs; diff --git a/crates/failproofaid/src/cloud_client.rs b/crates/failproofaid/src/cloud_client.rs index a01ec96fe..d2b4caffa 100644 --- a/crates/failproofaid/src/cloud_client.rs +++ b/crates/failproofaid/src/cloud_client.rs @@ -418,6 +418,9 @@ pub struct CloudClient { token: String, machine_id: String, client: Client, + /// [`fpai_collect::self_report::enrolment_id`] of the credential as + /// stored (before the URL is normalised), the value the CLI computes too. + self_report_enrolment: String, } /// On-disk enrolment, written by `failproofai config --connect`. @@ -600,12 +603,19 @@ fn enrolment_withdrawn() -> bool { matches!(Enrolment::resolve(), Ok(None)) } -/// Is this machine Cloud enrolled, for Self Reports' missing-file rule -/// (`fpai_collect::self_report::effective_settings`)? The same resolution as -/// the policy poll; an unreadable credential counts as enrolled, so a missing -/// `self-report.json` stays off rather than guessing on. -pub fn self_report_enrolled() -> bool { - !enrolment_withdrawn() +/// Which enrolment this machine is under, for Self Reports' settings readers +/// (`fpai_collect::self_report::effective_settings`). The same resolution as +/// the policy poll; an unreadable credential counts as enrolled with no known +/// identity, so neither a missing file nor any written one turns it on. +pub fn self_report_enrolled() -> fpai_collect::self_report::Enrolment { + use fpai_collect::self_report::{Enrolment as SrEnrolment, enrolment_id}; + match Enrolment::resolve() { + Ok(None) => SrEnrolment::NotEnrolled, + Ok(Some(e)) => { + SrEnrolment::Enrolled(Some(enrolment_id(&e.base_url, &e.machine_id, &e.token))) + } + Err(_) => SrEnrolment::Enrolled(None), + } } impl Enrolment { @@ -741,6 +751,8 @@ impl Enrolment { impl CloudClient { fn new(base_url: &str, token: String, machine_id: String) -> Result { + let self_report_enrolment = + fpai_collect::self_report::enrolment_id(base_url, &machine_id, &token); let mut base_url = Url::parse(base_url).map_err(|err| format!("invalid FAILPROOFAI_CLOUD_URL: {err}"))?; if !matches!(base_url.scheme(), "http" | "https") { @@ -793,6 +805,7 @@ impl CloudClient { token, machine_id, client, + self_report_enrolment, }) } @@ -1209,9 +1222,11 @@ pub fn spawn_maintenance( // Self Reports follow enrolment: written from the response just // accepted, or released when the machine left Cloud. Unknown // (unreadable credential) changes nothing. + // Enrolled answers are bound to the credential this pass polled + // with, so a later org never inherits an earlier one's file. let self_report_enrolment = match &cloud { - Ok(Some(_)) => Some(true), - Ok(None) => Some(false), + Ok(Some(client)) => Some(Some(client.self_report_enrolment.clone())), + Ok(None) => Some(None), Err(_) => None, }; if maintenance_tick( @@ -1223,7 +1238,11 @@ pub fn spawn_maintenance( ) { floor_reset_pending = false; } - crate::self_report::tick(self_report_enrolment, &enrolment_withdrawn); + crate::self_report::tick( + self_report_enrolment, + &self_report_enrolled, + &enrolment_withdrawn, + ); wait_until_shutdown( &shutdown, if enrolled { diff --git a/crates/failproofaid/src/self_report.rs b/crates/failproofaid/src/self_report.rs index 33ea5e330..99986d7a5 100644 --- a/crates/failproofaid/src/self_report.rs +++ b/crates/failproofaid/src/self_report.rs @@ -64,7 +64,8 @@ pub fn decode(raw: &Value) -> Option { } /// The last accepted response's block, waiting for the maintenance lane to -/// apply it. Outer `None`: no fresh response since the last apply. +/// apply it. Outer `None`: no fresh response since the last apply. The lane +/// writes it bound to the enrolment that polled ([`tick`]). static PENDING: Mutex>> = Mutex::new(None); /// Called with every ACCEPTED desired-state response. @@ -87,6 +88,7 @@ pub fn effective(desired: Option<&Desired>, port: u16, updated_at: String) -> Se guidance: sr::sanitize_guidance(desired.and_then(|d| d.guidance.as_deref())), mcp: McpEndpoint::on_port(port), updated_at, + enrolment: None, } } @@ -110,21 +112,34 @@ pub struct Applied { /// - `source`: a local file is set aside while the org's setting is awaited, /// which reads as off, so an org "on" that matches the old local "on" still /// has agents to register; +/// - `enrolment`: a file another enrolment wrote (a previous org) read as off +/// for this one, so the same holds; /// - `enabled`, and the endpoint while on (its port is in the HTTP entries). fn entries_may_change(previous: Option<&Settings>, next: &Settings) -> bool { let Some(previous) = previous else { return true; }; previous.source != next.source + || previous.enrolment != next.enrolment || previous.enabled != next.enabled || (next.enabled && previous.mcp != next.mcp) } /// Write `path` for this response, only when its content (not `updatedAt`) /// changed. -pub fn apply(path: &Path, desired: Option<&Desired>, port: u16) -> io::Result { +/// +/// `enrolment` is [`sr::enrolment_id`] of the credential whose poll produced +/// `desired`; readers honour the file only while the machine is enrolled as +/// that same credential. +pub fn apply( + path: &Path, + desired: Option<&Desired>, + port: u16, + enrolment: &str, +) -> io::Result { let previous = sr::read_settings(path); - let next = effective(desired, port, now_rfc3339()); + let mut next = effective(desired, port, now_rfc3339()); + next.enrolment = Some(enrolment.to_string()); if previous.as_ref().is_some_and(|p| p.same_content(&next)) { return Ok(Applied { written: false, @@ -153,7 +168,7 @@ pub fn release(path: &Path) -> io::Result { Ok(()) => { let now_on = path .parent() - .and_then(|home| sr::effective_settings(home, &|| false)) + .and_then(|home| sr::effective_settings(home, &|| sr::Enrolment::NotEnrolled)) .is_some_and(|s| s.enabled); Ok(previous.enabled || now_on) } @@ -162,15 +177,21 @@ pub fn release(path: &Path) -> io::Result { } } -/// One maintenance-lane pass. `enrolled`: `Some(true)` enrolled, `Some(false)` -/// definitely not, `None` unknown (credential unreadable: change nothing). -pub fn tick(enrolled: Option, withdrawn: &dyn Fn() -> bool) { +/// One maintenance-lane pass. `polled_as`: `Some(Some(id))` enrolled, with +/// [`sr::enrolment_id`] of the credential this pass polled with, +/// `Some(None)` definitely not enrolled, `None` unknown (credential +/// unreadable: change nothing). `current` is the enrolment right now. +pub fn tick( + polled_as: Option>, + current: &dyn Fn() -> sr::Enrolment, + withdrawn: &dyn Fn() -> bool, +) { let Ok(home) = crate::paths::failproofai_home() else { return; }; let path = sr::settings_path(&home); - match enrolled { - Some(true) => { + match polled_as { + Some(Some(enrolment)) => { let Some(desired) = take_pending() else { return; }; @@ -179,7 +200,18 @@ pub fn tick(enrolled: Option, withdrawn: &dyn Fn() -> bool) { if withdrawn() { return; } - match apply(&path, desired.as_ref(), port()) { + // The credential changed while the poll was in flight (another + // org): this answer is the previous enrolment's. Drop it; the next + // poll answers for the new one, and until then readers find no + // file of this enrolment's and treat the feature as off. + if !pending_still_applies(&enrolment, ¤t()) { + tracing::info!( + "Self Reports: the Cloud credential changed during the poll; \ + waiting for the new enrolment's setting" + ); + return; + } + match apply(&path, desired.as_ref(), port(), &enrolment) { Ok(Applied { written: true, needs_sync, @@ -203,7 +235,7 @@ pub fn tick(enrolled: Option, withdrawn: &dyn Fn() -> bool) { ), } } - Some(false) => { + Some(None) => { // Drop any response still pending from before the disconnect. let _ = take_pending(); match release(&path) { @@ -222,6 +254,12 @@ pub fn tick(enrolled: Option, withdrawn: &dyn Fn() -> bool) { } } +/// Whether an answer polled as `polled_as` may still be written: the machine +/// is enrolled right now as that same credential. +fn pending_still_applies(polled_as: &str, current: &sr::Enrolment) -> bool { + matches!(current, sr::Enrolment::Enrolled(Some(id)) if id == polled_as) +} + /// Log one Self Reports event that arrived over the socket (`selfReportLog`): /// the stdio server's MCP traffic, or a CLI sync's result. Written exactly as /// the HTTP server's own events, so the machine logs hold both the same way. @@ -268,7 +306,7 @@ const STARTUP_LISTEN_WAIT: Duration = Duration::from_secs(10); /// Whether the startup sync should run: Self Reports is on (a missing file is /// on off Cloud; `sr::effective_settings`). -fn enabled_on_disk(home: &Path, enrolled: &dyn Fn() -> bool) -> bool { +fn enabled_on_disk(home: &Path, enrolled: &dyn Fn() -> sr::Enrolment) -> bool { sr::effective_settings(home, enrolled).is_some_and(|s| s.enabled) } @@ -642,7 +680,7 @@ mod tests { // First write, even while off: before it the machine was on by default // (or off while it waited), so the agents' entries are unknown. assert_eq!( - apply(&path, None, 4319).unwrap(), + apply(&path, None, 4319, "enrolment-a").unwrap(), Applied { written: true, needs_sync: true @@ -650,7 +688,7 @@ mod tests { ); let first = std::fs::read_to_string(&path).unwrap(); assert_eq!( - apply(&path, None, 4319).unwrap(), + apply(&path, None, 4319, "enrolment-a").unwrap(), Applied { written: false, needs_sync: false @@ -659,7 +697,7 @@ mod tests { assert_eq!(std::fs::read_to_string(&path).unwrap(), first, "untouched"); assert_eq!( - apply(&path, Some(&on), 4319).unwrap(), + apply(&path, Some(&on), 4319, "enrolment-a").unwrap(), Applied { written: true, needs_sync: true @@ -677,7 +715,7 @@ mod tests { guidance: None, }; assert_eq!( - apply(&path, Some(&custom), 4319).unwrap(), + apply(&path, Some(&custom), 4319, "enrolment-a").unwrap(), Applied { written: true, needs_sync: false @@ -685,14 +723,14 @@ mod tests { ); // A new port does, while enabled. assert_eq!( - apply(&path, Some(&custom), 4400).unwrap(), + apply(&path, Some(&custom), 4400, "enrolment-a").unwrap(), Applied { written: true, needs_sync: true } ); assert_eq!( - apply(&path, None, 4400).unwrap(), + apply(&path, None, 4400, "enrolment-a").unwrap(), Applied { written: true, needs_sync: true @@ -718,7 +756,7 @@ mod tests { }; let path = temp_path("first-cloud"); assert_eq!( - apply(&path, Some(&on), 4319).unwrap(), + apply(&path, Some(&on), 4319, "enrolment-a").unwrap(), Applied { written: true, needs_sync: true @@ -731,7 +769,7 @@ mod tests { local.source = "local".into(); sr::write_settings(&path, &local).unwrap(); assert_eq!( - apply(&path, Some(&on), 4319).unwrap(), + apply(&path, Some(&on), 4319, "enrolment-a").unwrap(), Applied { written: true, needs_sync: true @@ -747,7 +785,8 @@ mod tests { guidance: Some("Be brief.".into()), ..Default::default() }), - 4319 + 4319, + "enrolment-a" ) .unwrap(), Applied { @@ -758,6 +797,52 @@ mod tests { let _ = std::fs::remove_dir_all(path.parent().unwrap()); } + /// Review 4719314971: a file written for org A must not decide for org B. + /// The file is bound to the enrolment that polled; a switch rewrites it + /// and syncs, and until then a reader enrolled as B finds it off. + #[test] + fn a_cloud_file_is_bound_to_the_enrolment_that_wrote_it() { + let path = temp_path("bound"); + let home = path.parent().unwrap().to_path_buf(); + let on = Desired { + enabled: true, + ..Default::default() + }; + apply(&path, Some(&on), 4319, "enrolment-a").unwrap(); + assert_eq!( + sr::read_settings(&path).unwrap().enrolment.as_deref(), + Some("enrolment-a") + ); + let as_a = || sr::Enrolment::Enrolled(Some("enrolment-a".into())); + let as_b = || sr::Enrolment::Enrolled(Some("enrolment-b".into())); + let unknown = || sr::Enrolment::Enrolled(None); + assert!(enabled_on_disk(&home, &as_a), "A's own file"); + assert!( + !enabled_on_disk(&home, &as_b), + "A's file while enrolled as B" + ); + assert!(!enabled_on_disk(&home, &unknown), "credential unreadable"); + // B's first answer rewrites the file (same content otherwise) and syncs. + assert_eq!( + apply(&path, Some(&on), 4319, "enrolment-b").unwrap(), + Applied { + written: true, + needs_sync: true + } + ); + assert!(enabled_on_disk(&home, &as_b)); + assert!(!enabled_on_disk(&home, &as_a)); + // An answer polled as A is not written once the machine is B. + assert!(pending_still_applies("enrolment-b", &as_b())); + assert!(!pending_still_applies("enrolment-a", &as_b())); + assert!(!pending_still_applies("enrolment-a", &unknown())); + assert!(!pending_still_applies( + "enrolment-a", + &sr::Enrolment::NotEnrolled + )); + let _ = std::fs::remove_dir_all(home); + } + #[test] fn leaving_cloud_removes_only_a_cloud_file() { let path = temp_path("release"); @@ -777,6 +862,7 @@ mod tests { ..Default::default() }), 4319, + "enrolment-a", ) .unwrap(); assert!( @@ -787,7 +873,7 @@ mod tests { // A disabled cloud file: the machine is open source now, where Self // Reports is on by default, so agents need the sync too... - apply(&path, None, 4319).unwrap(); + apply(&path, None, 4319, "enrolment-a").unwrap(); assert!( release(&path).unwrap(), "off -> the open-source default (on)" @@ -801,7 +887,7 @@ mod tests { r#"{"selfReport":{"enabled":false}}"#, ) .unwrap(); - apply(&path, None, 4319).unwrap(); + apply(&path, None, 4319, "enrolment-a").unwrap(); assert!( !release(&path).unwrap(), "a disabled one with a local off does not" @@ -836,8 +922,8 @@ mod tests { #[test] fn the_startup_sync_runs_only_when_self_reports_is_on() { let home = temp_path("startup").parent().unwrap().to_path_buf(); - let oss = || false; - let cloud = || true; + let oss = || sr::Enrolment::NotEnrolled; + let cloud = || sr::Enrolment::Enrolled(Some("enrolment-a".into())); assert!( enabled_on_disk(&home, &oss), "no file, open source: on by default" @@ -847,6 +933,7 @@ mod tests { "no file, enrolled: off until written" ); let mut s = effective(None, 4319, "2026-11-26T00:00:00Z".into()); + s.enrolment = Some("enrolment-a".into()); sr::write_settings(&sr::settings_path(&home), &s).unwrap(); assert!(!enabled_on_disk(&home, &oss), "disabled"); s.enabled = true; @@ -1056,7 +1143,14 @@ mod tests { #[test] fn the_first_cloud_write_after_an_enrolled_config_registers_every_hooked_agent() { let m = ServiceMachine::new("cloud-first-sync"); - std::fs::write(m.fp_home().join("credentials.json"), r#"{"cloud":{}}"#).unwrap(); + // A real enrolment: the org's file is bound to it, and the CLI's + // readers compute the same id from this credential. + std::fs::write( + m.fp_home().join("credentials.json"), + r#"{"cloud":{"url":"https://app.example.test","machine_id":"machine-1","token":"tok-org-a"}}"#, + ) + .unwrap(); + let enrolment = sr::enrolment_id("https://app.example.test", "machine-1", "tok-org-a"); let settings = sr::settings_path(&m.fp_home()); assert!(!settings.exists()); @@ -1084,7 +1178,7 @@ mod tests { enabled: true, ..Default::default() }; - let applied = apply(&settings, Some(&on), 4319).unwrap(); + let applied = apply(&settings, Some(&on), 4319, &enrolment).unwrap(); assert_eq!( applied, Applied { @@ -1109,7 +1203,7 @@ mod tests { assert!(m.config(".codex/config.toml").contains(&link)); // And the same answer again changes nothing. assert_eq!( - apply(&settings, Some(&on), 4319).unwrap(), + apply(&settings, Some(&on), 4319, &enrolment).unwrap(), Applied { written: false, needs_sync: false diff --git a/crates/failproofaid/tests/self_report_e2e.rs b/crates/failproofaid/tests/self_report_e2e.rs index 52159c280..66ac9fd74 100644 --- a/crates/failproofaid/tests/self_report_e2e.rs +++ b/crates/failproofaid/tests/self_report_e2e.rs @@ -129,6 +129,7 @@ fn an_oss_daemon_serves_the_report_tool() { guidance: None, mcp: fpai_collect::self_report::McpEndpoint::on_port(port), updated_at: "2026-11-25T10:00:00Z".into(), + enrolment: None, }, ) .unwrap(); @@ -252,6 +253,7 @@ fn self_report_mcp_events_reach_the_daemon_log() { guidance: None, mcp: fpai_collect::self_report::McpEndpoint::on_port(port), updated_at: "2026-11-25T10:00:00Z".into(), + enrolment: None, }, ) .unwrap(); diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index 034267f8c..ea4a724dd 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -216,6 +216,13 @@ pub struct Settings { pub mcp: McpEndpoint, #[serde(rename = "updatedAt")] pub updated_at: String, + /// A `cloud` file's enrolment: [`enrolment_id`] of the credential whose + /// poll wrote it. A cloud file decides only while the machine is enrolled + /// as that same credential; one left by a previous org (or one without + /// this field, from an older daemon) reads as missing until this + /// credential's own answer is written. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub enrolment: Option, } impl Settings { @@ -252,18 +259,64 @@ pub fn parse_settings(text: &str) -> Option { .filter(|s| s.version == SETTINGS_VERSION) } -/// Whether a file that parsed may decide anything. A file this machine wrote -/// itself (`source` anything but `cloud`) does not while it is Cloud enrolled: -/// there the organization decides, so until the daemon writes the org's -/// setting the feature is off, exactly as with no file at all. -fn authoritative(settings: Settings, enrolled: &dyn Fn() -> bool) -> Option { - (settings.source == "cloud" || !enrolled()).then_some(settings) +/// Whether a file that parsed may decide anything (identical to the CLI's +/// `resolveSelfReport`): +/// +/// - not enrolled: the file decides (a `cloud` one is released by the daemon's +/// next tick); +/// - enrolled: only a `cloud` file written for THIS enrolment +/// (`enrolment == Some(current id)`). This machine's own file, a file the +/// previous org's poll wrote, and any file while the credential cannot be +/// read (no current id) are set aside: off until this enrolment's answer is +/// written, exactly as with no file at all. +fn authoritative(settings: Settings, enrolment: &dyn Fn() -> Enrolment) -> Option { + match enrolment() { + Enrolment::NotEnrolled => Some(settings), + Enrolment::Enrolled(current) => { + (settings.source == "cloud" && current.is_some() && settings.enrolment == current) + .then_some(settings) + } + } } -/// Is this machine Cloud enrolled? Asked only when `self-report.json` is -/// missing. The daemon installs its own check (the same `Enrolment::resolve` -/// its policy poll uses) with [`set_enrolment_check`]. -pub type EnrolmentCheck = Arc bool + Send + Sync>; +/// Which Cloud enrolment this machine is under, for the settings readers. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Enrolment { + NotEnrolled, + /// Enrolled, as [`enrolment_id`] of the credential; `None` when the + /// credential cannot be read (enrolled, identity unknown). + Enrolled(Option), +} + +impl Enrolment { + pub fn is_enrolled(&self) -> bool { + matches!(self, Enrolment::Enrolled(_)) + } +} + +/// The id a `cloud` settings file is bound to: a hash of the Cloud URL, the +/// machine id and the token, so a switch to another org (whose token differs +/// even when the machine id is kept) or a re-enrolment changes it. One-way +/// and truncated: the file is world-readable. Same value as the CLI's +/// `selfReportEnrolmentId`. +pub fn enrolment_id(url: &str, machine_id: &str, token: &str) -> String { + use sha2::{Digest, Sha256}; + let mut hasher = Sha256::new(); + hasher.update(b"failproofai self-report enrolment v1"); + for part in [url, machine_id, token] { + hasher.update((part.len() as u64).to_be_bytes()); + hasher.update(part.as_bytes()); + } + hasher.finalize()[..16] + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// Which enrolment is this machine under? Asked on every read. The daemon +/// installs its own check (the same `Enrolment::resolve` its policy poll +/// uses) with [`set_enrolment_check`]. +pub type EnrolmentCheck = Arc Enrolment + Send + Sync>; static ENROLMENT_CHECK: OnceLock = OnceLock::new(); @@ -277,22 +330,23 @@ pub fn enrolment_check() -> EnrolmentCheck { ENROLMENT_CHECK .get() .cloned() - .unwrap_or_else(|| Arc::new(|| false)) + .unwrap_or_else(|| Arc::new(|| Enrolment::NotEnrolled)) } /// The settings a reader acts on (CONTRACT §4), identical to the TypeScript /// `resolveSelfReport` in src/hooks/self-report.ts: /// /// - the file, when it is there and parses as version [`SETTINGS_VERSION`], -/// except a local-source file on a Cloud-enrolled machine: `None`, off until -/// the daemon writes the organization's setting; +/// except, on a Cloud-enrolled machine, any file but a `cloud` one written +/// for this enrolment: `None`, off until the daemon writes the +/// organization's setting ([`authoritative`]); /// - an unparsable, unreadable or other-version file: `None`, off (fail safe: /// a half-written or hand-broken file must not turn recording on); /// - a missing file on a Cloud-enrolled machine: `None`, off until the daemon /// writes it from the org's setting; /// - a missing file otherwise: on with the default categories, unless /// `config.json`'s `selfReport.enabled` is `false` (an explicit off wins). -pub fn effective_settings(home: &Path, enrolled: &dyn Fn() -> bool) -> Option { +pub fn effective_settings(home: &Path, enrolled: &dyn Fn() -> Enrolment) -> Option { match fs::read_to_string(settings_path(home)) { Ok(text) => authoritative(parse_settings(&text)?, enrolled), Err(err) if err.kind() == io::ErrorKind::NotFound => missing_file_settings(home, enrolled), @@ -301,8 +355,8 @@ pub fn effective_settings(home: &Path, enrolled: &dyn Fn() -> bool) -> Option bool) -> Option { - if enrolled() || local_config_disabled(home) { +fn missing_file_settings(home: &Path, enrolled: &dyn Fn() -> Enrolment) -> Option { + if enrolled().is_enrolled() || local_config_disabled(home) { return None; } Some(default_settings(port_from_env())) @@ -319,6 +373,7 @@ pub fn default_settings(port: u16) -> Settings { guidance: None, mcp: McpEndpoint::on_port(port), updated_at: String::new(), + enrolment: None, } } @@ -1427,6 +1482,22 @@ mod tests { guidance: guidance.map(str::to_string), mcp: McpEndpoint::on_port(DEFAULT_PORT), updated_at: "2026-11-25T10:00:00Z".into(), + enrolment: None, + } + } + + /// The enrolment id the tests' enrolled machine runs under. + const TEST_ENROLMENT: &str = "test-enrolment"; + + fn enrolled_as_test() -> Enrolment { + Enrolment::Enrolled(Some(TEST_ENROLMENT.into())) + } + + fn test_enrolment(enrolled: bool) -> Enrolment { + if enrolled { + enrolled_as_test() + } else { + Enrolment::NotEnrolled } } @@ -1571,10 +1642,11 @@ mod tests { let home = temp_home("cache"); let path = settings_path(&home); // Enrolled: a missing file is off until the daemon writes it. - let cache = SettingsCache::new(&home, Arc::new(|| true)); + let cache = SettingsCache::new(&home, Arc::new(enrolled_as_test)); assert!(cache.current().is_none()); let mut on = enabled(default_categories(), None); on.source = "cloud".into(); + on.enrolment = Some(TEST_ENROLMENT.into()); write_settings(&path, &on).unwrap(); assert!(cache.current().unwrap().enabled); let mut off = on.clone(); @@ -1593,45 +1665,53 @@ mod tests { let home = temp_home("effective"); let path = settings_path(&home); // Fresh machine, not enrolled: on, defaults. - let s = effective_settings(&home, &|| false).expect("on by default"); + let s = effective_settings(&home, &|| Enrolment::NotEnrolled).expect("on by default"); assert!(s.enabled); assert_eq!(s.source, "local"); assert_eq!(s.categories, default_categories()); // Enrolled, file not written yet: off. - assert_eq!(effective_settings(&home, &|| true), None); + assert_eq!(effective_settings(&home, &enrolled_as_test), None); // An explicit local off in config.json wins over the default. fs::write( home.join("config.json"), r#"{"selfReport":{"enabled":false}}"#, ) .unwrap(); - assert_eq!(effective_settings(&home, &|| false), None); + assert_eq!(effective_settings(&home, &|| Enrolment::NotEnrolled), None); fs::write( home.join("config.json"), r#"{"selfReport":{"enabled":true}}"#, ) .unwrap(); - assert!(effective_settings(&home, &|| false).unwrap().enabled); + assert!( + effective_settings(&home, &|| Enrolment::NotEnrolled) + .unwrap() + .enabled + ); // A malformed file is off, enrolled or not (fail safe). fs::write(&path, "{not json").unwrap(); - assert_eq!(effective_settings(&home, &|| false), None); - assert_eq!(effective_settings(&home, &|| true), None); + assert_eq!(effective_settings(&home, &|| Enrolment::NotEnrolled), None); + assert_eq!(effective_settings(&home, &enrolled_as_test), None); // An explicit enabled:false file is off. let mut off = enabled(default_categories(), None); off.enabled = false; write_settings(&path, &off).unwrap(); - assert!(!effective_settings(&home, &|| false).unwrap().enabled); + assert!( + !effective_settings(&home, &|| Enrolment::NotEnrolled) + .unwrap() + .enabled + ); // The cache agrees with the reader. fs::remove_file(&path).unwrap(); fs::remove_file(home.join("config.json")).unwrap(); assert!( - SettingsCache::new(&home, Arc::new(|| false)) + SettingsCache::new(&home, Arc::new(|| Enrolment::NotEnrolled)) .current() .unwrap() .enabled ); assert!( - SettingsCache::new(&home, Arc::new(|| true)) + SettingsCache::new(&home, Arc::new(enrolled_as_test)) .current() .is_none() ); @@ -1828,7 +1908,7 @@ mod tests { Server { home: home.to_path_buf(), port: DEFAULT_PORT, - settings: SettingsCache::new(home, Arc::new(move || enrolled)), + settings: SettingsCache::new(home, Arc::new(move || test_enrolment(enrolled))), } } @@ -1865,6 +1945,7 @@ mod tests { // daemon writes from the org's setting. let org = |mut s: Settings| { s.source = "cloud".into(); + s.enrolment = Some(TEST_ENROLMENT.into()); s }; // Missing settings: answered, not recorded. @@ -2130,11 +2211,17 @@ mod tests { } else if !case["file"].is_null() { fs::write(&path, serde_json::to_string_pretty(&case["file"]).unwrap()).unwrap(); } - let enrolled = case["enrolled"].as_bool().unwrap(); + // `currentEnrolment`: the id the machine is enrolled as (absent: + // enrolled with an unreadable credential). + let enrolment = if case["enrolled"].as_bool().unwrap() { + Enrolment::Enrolled(case["currentEnrolment"].as_str().map(str::to_string)) + } else { + Enrolment::NotEnrolled + }; let want = case["on"].as_bool().unwrap(); - let read = effective_settings(&home, &|| enrolled).is_some_and(|s| s.enabled); + let read = effective_settings(&home, &|| enrolment.clone()).is_some_and(|s| s.enabled); assert_eq!(read, want, "effective_settings: {name}"); - let cache = SettingsCache::new(&home, Arc::new(move || enrolled)); + let cache = SettingsCache::new(&home, Arc::new(move || enrolment.clone())); assert_eq!( cache.current().is_some_and(|s| s.enabled), want, @@ -2149,6 +2236,72 @@ mod tests { } } + /// The id a cloud file is bound to: the same bytes as the CLI's + /// `selfReportEnrolmentIdOf` for every vector in the shared fixture. + #[test] + fn enrolment_ids_agree_with_the_cli() { + let fixture: Value = serde_json::from_str(&golden("settings-cases.golden.json")).unwrap(); + let vectors = fixture["enrolmentIds"].as_array().unwrap(); + assert!(!vectors.is_empty()); + for v in vectors { + assert_eq!( + enrolment_id( + v["url"].as_str().unwrap(), + v["machineId"].as_str().unwrap(), + v["token"].as_str().unwrap() + ), + v["id"].as_str().unwrap() + ); + } + } + + /// Review 4719314971: org A's "on" must stop deciding as soon as the + /// machine is enrolled as org B, before B's first answer is written. + #[test] + fn a_cloud_file_decides_only_for_the_enrolment_that_wrote_it() { + let home = temp_home("bound-enrolment"); + let path = settings_path(&home); + let mut org_a = enabled(default_categories(), None); + org_a.source = "cloud".into(); + org_a.enrolment = Some("enrolment-a".into()); + write_settings(&path, &org_a).unwrap(); + let as_a = || Enrolment::Enrolled(Some("enrolment-a".into())); + let as_b = || Enrolment::Enrolled(Some("enrolment-b".into())); + assert!(effective_settings(&home, &as_a).unwrap().enabled); + assert_eq!( + effective_settings(&home, &as_b), + None, + "A's file, enrolled as B" + ); + assert_eq!( + effective_settings(&home, &|| Enrolment::Enrolled(None)), + None, + "identity unknown" + ); + let switch = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let cache = { + let switch = switch.clone(); + SettingsCache::new( + &home, + Arc::new(move || { + if switch.load(std::sync::atomic::Ordering::SeqCst) { + as_b() + } else { + as_a() + } + }), + ) + }; + assert!(cache.current().unwrap().enabled); + switch.store(true, std::sync::atomic::Ordering::SeqCst); + assert!(cache.current().is_none(), "the cache re-asks on every call"); + // No enrolment at all (an older daemon's file): off while enrolled. + org_a.enrolment = None; + write_settings(&path, &org_a).unwrap(); + assert_eq!(effective_settings(&home, &as_a), None); + let _ = fs::remove_dir_all(home); + } + /// Enrolling with a local file in place: the cache stops serving it on /// the next call, with the file unchanged, and serves the org's file once /// the daemon writes it. @@ -2160,7 +2313,7 @@ mod tests { let flag = Arc::new(std::sync::atomic::AtomicBool::new(false)); let check = { let flag = flag.clone(); - Arc::new(move || flag.load(std::sync::atomic::Ordering::SeqCst)) + Arc::new(move || test_enrolment(flag.load(std::sync::atomic::Ordering::SeqCst))) }; let cache = SettingsCache::new(&home, check); assert!(cache.current().unwrap().enabled); @@ -2169,9 +2322,10 @@ mod tests { cache.current().is_none(), "enrolled: the local file no longer decides" ); - assert!(effective_settings(&home, &|| true).is_none()); + assert!(effective_settings(&home, &enrolled_as_test).is_none()); let mut org = enabled(default_categories(), None); org.source = "cloud".into(); + org.enrolment = Some(TEST_ENROLMENT.into()); org.enabled = false; org.guidance = Some("the org's own file, so the size changes".into()); write_settings(&path, &org).unwrap(); diff --git a/crates/fpai-collect/tests/self_report_mcp.rs b/crates/fpai-collect/tests/self_report_mcp.rs index d75faf5c6..ccdda7b30 100644 --- a/crates/fpai-collect/tests/self_report_mcp.rs +++ b/crates/fpai-collect/tests/self_report_mcp.rs @@ -37,6 +37,7 @@ fn write_settings(home: &Path, enabled: bool, categories: Vec) { guidance: Some("Prefer one report.".into()), mcp: McpEndpoint::on_port(4319), updated_at: "2026-11-25T10:00:00Z".into(), + enrolment: None, }, ) .unwrap(); @@ -61,9 +62,20 @@ impl Running { let sd = Shutdown::for_test(stop.clone()); let home = home.to_path_buf(); let task = tokio::spawn(async move { - self_report::serve_with_enrolment(listener, home, sd, Arc::new(move || enrolled)) - .await - .unwrap(); + self_report::serve_with_enrolment( + listener, + home, + sd, + Arc::new(move || { + if enrolled { + self_report::Enrolment::Enrolled(None) + } else { + self_report::Enrolment::NotEnrolled + } + }), + ) + .await + .unwrap(); }); Running { port, diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index 75824e47b..65aeeeeb3 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -21,6 +21,8 @@ Self Reports is on as soon as failproofai is installed. `failproofai policies -- Every connected machine picks the change up on its next policy poll. `failproofaid` writes `~/.failproofai/self-report.json` from it and adds the `failproofai_local` MCP server to every agent that has failproofai hooks, or removes it when the switch is off. Until the first poll after connecting writes that file, the machine treats Self Reports as off. The daemon updates the agents whenever what their entries depend on changes: the first time it writes the file, when the file's source changes (a machine's own file replaced by the organization's), when the switch flips, and when the port changes. + The file is bound to the enrolment whose poll wrote it. After the machine switches to another organization, or reconnects with a new token, the previous file reads as missing (off) until the new enrolment's setting is written. + On a Cloud-managed machine, `failproofai self-report enable` and `disable` refuse and point you to the dashboard. @@ -60,13 +62,30 @@ A report with a category that is not on the list is still recorded under the nam ## Agent support -failproofai registers one MCP server, named `failproofai_local`, in each agent's user-level MCP settings. Agents see its tool as `mcp__failproofai_local__report` (Claude Code, Codex, Factory, Devin, and Pi, whose tool comes from failproofai's Pi extension, see below), `failproofai_local_report` (OpenCode), `mcp_failproofai_local_report` (Hermes, Antigravity) or `failproofai_local__report` (OpenClaw, Goose). The name is not `failproofai`, which is the name the [Cloud MCP gateway](/reference/mcp) is usually added under, so the two coexist. For Claude Code and Codex, whose hooks record the report, the entry points at the daemon's local server, `http://127.0.0.1:4319/mcp` (set `FAILPROOFAI_SELF_REPORT_PORT` to move it), when `failproofaid` is serving it and the agent's hooks will run, and runs `failproofai mcp` over stdio otherwise (see [When the hooks do not run](#when-the-hooks-do-not-run)). Every other agent always gets `failproofai mcp` over stdio, because its report is recorded by the server, which needs the agent's working directory to find the session (see below). Every entry is marked as failproofai's, so removing it never touches a server you added. +failproofai registers one MCP server, named `failproofai_local`, in each agent's user-level MCP settings, except Pi, Hermes and OpenClaw, whose tool comes from failproofai's own extension or plugin (see below). Agents see the tool as `mcp__failproofai_local__report` (Claude Code, Codex, Factory, Devin, Pi), `failproofai_local_report` (OpenCode), `mcp_failproofai_local_report` (Hermes, Antigravity) or `failproofai_local__report` (OpenClaw, Goose). The name is not `failproofai`, which is the name the [Cloud MCP gateway](/reference/mcp) is usually added under, so the two coexist; no tool of a server named `failproofai` is ever let past your policies, in any agent's spelling. Every entry runs `failproofai mcp --agent ` over stdio. Claude Code and Codex used to point at the daemon's local server, `http://127.0.0.1:4319/mcp`, while their hooks would run, but the entry is per user and a project can switch the hooks off (`disableAllHooks` in `.claude/settings.local.json`), and that endpoint records nothing for an agent whose hook records, so such a project's reports were lost. Over stdio the server records any report the hook did not (see [When the hooks do not run](#when-the-hooks-do-not-run)), and every other agent's report is recorded by the server, which needs the agent's working directory to find the session (see below). Every entry is marked as failproofai's, so removing it never touches a server you added. + +The sync writes the stdio command as the `failproofai` that npm installed beside the daemon's Node, so it finds it even under the service's own `PATH`, and when it cannot update an agent the daemon's log names the agent and the reason. When the daemon starts, it re-runs `failproofai self-report sync`. An HTTP entry an earlier version wrote is moved to stdio by the next sync, and `failproofai self-report status` repairs one it finds. A running agent keeps the server it loaded at startup. The daemon's HTTP server (`FAILPROOFAI_SELF_REPORT_PORT` moves it) still serves the Hermes and OpenClaw plugins, which check that it answers as the daemon behind this account's socket (both carry the daemon's instance id) before they send it anything, and any entry written by hand. -The transport is chosen when the entries are written, from a live check: the daemon behind this account's socket must answer, and the endpoint must answer as that same daemon (both carry the daemon's instance id). A port held by another daemon, for example another user's, or one whose own server could not bind the port, gives stdio. When the daemon starts, it re-runs `failproofai self-report sync`, so Claude Code and Codex move to HTTP. The sync writes the stdio command as the `failproofai` that npm installed beside the daemon's Node, so it finds it even under the service's own `PATH`, and when it cannot update an agent the daemon's log names the agent and the reason. If the daemon stops, `failproofai self-report status` finds agents pointing at an endpoint that does not answer, or an agent the server records left on HTTP by an earlier version, and moves them to stdio. A running agent keeps the server it loaded at startup. +### How the tool reaches the model -Both transports send the model short server instructions in the MCP handshake: when to report, the category names, and your guidance. Some agents, Claude Code among them, load MCP tools only on demand. They add a server's instructions to the system prompt, though, so the model knows the tool exists. Copilot CLI passes a server's instructions to the model only for servers on its allowlist (or with `--allow-all-mcp-server-instructions`), so on Copilot the model may see only the tool's own description. +The server sends short instructions in the MCP handshake: when to report, the category names, and your guidance. Several agents load MCP tools only on demand, behind a tool search, which shows the model a name and no description. failproofai keeps the tool direct, or the instructions in front of the model, in every agent: -Pi has no MCP support before 0.99, so an MCP entry for it reaches no model. failproofai's Pi extension, which every Pi with failproofai hooks already loads, registers the tool itself as `mcp__failproofai_local__report` on every Pi version, with the server's instructions in Pi's system prompt. It asks `failproofai mcp --agent pi` for the tool when Pi starts (no tool while Self Reports is off) and hands each call to it, so the text, the categories and the recording are the same as every other agent's. `self-report sync` writes no Pi MCP entry and takes out one an earlier version wrote. Hermes and OpenClaw defer MCP tools behind their tool search (`tools.tool_search` / `tools.toolSearch`). Neither has a per-server setting to load one server directly, so failproofai leaves that setting alone, and the model sees `report` in the deferred tool listing. +| Agent | How the tool and its instructions reach the model | +| --- | --- | +| Claude Code | The entry sets `alwaysLoad: true`, so its tools are never deferred behind tool search. Server instructions go in the system prompt. | +| Codex | MCP tools are listed directly. | +| Cursor | MCP tools are listed directly. | +| Copilot CLI | Tools are listed directly. Copilot passes server instructions only for its built-in allowlist (or with `--allow-all-mcp-server-instructions`), so the same instructions go in a marked `~/.copilot/instructions/failproofai-self-reports.instructions.md` (under `COPILOT_HOME` when set), written and removed with the entry. | +| OpenCode | MCP tools are listed directly. | +| Pi | failproofai's Pi extension registers the tool, with the instructions in the system prompt. | +| Hermes | failproofai's Hermes plugin registers the tool natively and adds it to Hermes' never-deferred list, so `tools.tool_search` does not hide it, with the instructions in `pre_llm_call` context. | +| OpenClaw | failproofai's OpenClaw plugin registers a `catalogMode: "direct-only"` tool, which Tool Search never defers, with the instructions in the system prompt (`before_prompt_build`). | +| Factory | droid defers MCP tools behind its tool search, with no setting per server. The instructions arrive as SessionStart context, so the model knows to load `report` from the deferred list. | +| Devin | Devin can defer MCP tools behind its `tool_search`, with no setting per server, so the model may see the tool's name first and load it. | +| Antigravity | The entry sets `eager: true`, so the tools are direct rather than behind the `call_mcp_tool` wrapper. | +| Goose | Extensions' tools are listed directly. | + +Pi has no MCP support before 0.99, so an MCP entry for it reaches no model. failproofai's Pi extension, which every Pi with failproofai hooks already loads, registers the tool itself as `mcp__failproofai_local__report` on every Pi version, with the server's instructions in Pi's system prompt. It asks `failproofai mcp --agent pi` for the tool when Pi starts (no tool while Self Reports is off) and hands each call to it, so the text, the categories and the recording are the same as every other agent's. The Hermes and OpenClaw plugins do the same against the daemon's Self Reports server: they ask it for the tool when the gateway starts (and every minute after, for the instructions and the on/off switch) and send each call to it as `?agent=hermes` or `?agent=openclaw` with the gateway's working directory, so it is attributed, deduped and logged like an MCP call. Without a daemon, or while Self Reports is off, they offer no tool. On Hermes the tool's schema is fixed when it registers, so new categories reach it at the gateway's next start. `self-report sync` writes no Pi, Hermes or OpenClaw MCP entry and takes out one an earlier version wrote, in every profile. Where an agent's hooks see MCP tool calls and the server they belong to, the hook records the report. Where they do not, failproofai's MCP server records it. It attributes the report to that agent's newest session seen by the hooks in the last 6 hours: in the server's working directory if there is one, else in a directory above or below it. With neither, it takes the agent's newest session only when all of the agent's sessions in those 6 hours are in one directory, and files the report as `unattributed` otherwise, rather than guess between projects. The lookup reads every page of hook activity written in the 6 hours, however busy other agents or projects kept the hooks, so a session that is still in the window is found. The agent the report is filed under comes from that session's own hook events. @@ -77,11 +96,11 @@ These agents are registered over stdio for that reason: the MCP entry is per use | Claude Code | `~/.claude.json` | Hook, or the MCP server while hooks are off | | Codex | `~/.codex/config.toml` | Hook, or the MCP server while Codex has not trusted the hooks | | Cursor | `~/.cursor/mcp.json` | MCP server. Cursor's tool hook names the call `MCP:report`, without the server, so it cannot tell our `report` from another server's, and the call goes through the policies like any other. When the daemon cannot be reached, it is denied with every other call | -| Copilot CLI | `~/.copilot/mcp-config.json` | MCP server | +| Copilot CLI | `~/.copilot/mcp-config.json`, plus the instructions file above | MCP server | | OpenCode | `~/.config/opencode/opencode.json` | MCP server | | Pi | failproofai's Pi extension | MCP server | -| Hermes | Each profile's `config.yaml` | MCP server | -| OpenClaw | Each profile's `openclaw.json` | MCP server | +| Hermes | failproofai's Hermes plugin, in each profile | The daemon's Self Reports server | +| OpenClaw | failproofai's OpenClaw plugin, in each profile | The daemon's Self Reports server | | Factory | `~/.factory/mcp.json` | MCP server | | Devin | `~/.config/devin/mcp_config.json` | MCP server | | Antigravity | `~/.gemini/config/mcp_config.json` | MCP server | @@ -94,7 +113,7 @@ Claude Code and Codex can load the MCP server while skipping failproofai's hooks - Codex 0.129 and later runs a hook from `~/.codex/hooks.json` only once a person trusted it, at its current hash. Hooks in Codex's system config (`/etc/codex/config.toml`, where `failproofai config` puts them when it has sudo) run without trust. - Claude Code runs no hooks with `disableAllHooks: true`, and only managed ones with a managed `allowManagedHooksOnly: true`. -So the stdio server records a Claude Code or Codex report itself unless that agent's hook already recorded it: the agent runs its hook before it sends the MCP call, so the server looks for the hook's record of the same report from the last two minutes. A report is recorded once either way, and a person who trusts the hooks while the agent runs changes nothing. A report the server records goes on the session the agent's own files name (Codex's rollout, Claude Code's transcript for that directory). `self-report sync` registers such an agent over stdio, never on the daemon's endpoint, which records nothing for it. `self-report status --verbose` says who records each one's reports and, for an untrusted Codex, how to trust the hooks: re-run `failproofai config` and allow sudo, or open `codex` once and approve them. +So the stdio server records a Claude Code or Codex report itself unless that agent's hook already recorded that same call: the agent runs its hook before it sends the MCP call, so the server looks for the hook's record of the same report, from the last two minutes and in the same working directory, and each hook record vouches for one call only. The same words in another project, or a second identical call, are recorded. A report is recorded once either way, and a person who trusts the hooks while the agent runs changes nothing. A report the server records goes on the session the agent's own files name (Codex's rollout, Claude Code's transcript for that directory). `self-report sync` registers these agents over stdio, never on the daemon's endpoint, which records nothing for them. `self-report status --verbose` says who records each one's reports and, for an untrusted Codex, how to trust the hooks: re-run `failproofai config` and allow sudo, or open `codex` once and approve them. ### Other agents' servers @@ -112,6 +131,19 @@ On Antigravity, an MCP call can come through its `call_mcp_tool` wrapper. The ho If an MCP server named `failproofai_local` that failproofai did not write is already there, it is left alone and reported as a conflict. A server named `failproofai`, such as the [Cloud MCP gateway](/reference/mcp), is never touched or reported: it sits next to `failproofai_local`, and its tools go through your policies like any other server's. +## When a tool call fails + +Once per session, after a tool call that clearly failed, failproofai adds one line the model reads: "If this blocks you and you can't fix it, call failproofai_local's `report` tool once." A call failed when it exited non-zero, returned an error (an MCP `isError`), or its error output or a short result says 401, 403, `not found` or `permission denied`; a long successful result that happens to contain those words does not count. There is no line after a successful call, after the report call itself, after a failure a failproofai deny caused (that is already recorded as a block), or while Self Reports is off. It is part of Self Reports, not a policy, and it never replaces a policy's answer. + +| Agent | Where the line goes | +| --- | --- | +| Claude Code | `additionalContext` on PostToolUse and PostToolUseFailure | +| Codex | `additionalContext` on PostToolUse | +| Cursor | `additional_context` on postToolUse | +| Copilot CLI | `additionalContext` on postToolUseFailure (its postToolUse reads only a block) | +| Factory | PostToolUse feedback, which droid adds as a message only the model sees | +| OpenCode, Pi, Hermes, OpenClaw, Devin, Antigravity, Goose | None: these agents have no channel that adds context after a tool runs (OpenCode's only route is a new prompt) | + ## The daemon's log The daemon's log (`~/.failproofai/logs/daemon.log`, which machine logs upload) has a line for every Self Reports MCP event: each `initialize` and `tools/list`, each `tools/call` with the agent, the category, the session it was filed under, and whether it was recorded or skipped and why, and each sync's result. A write failure, a category the settings do not list, and an unreadable settings file are warnings. A line carries at most the first 40 characters of the report's detail, after secrets are scrubbed from it. The stdio server, which runs as a child of each agent, sends its events to the daemon over its socket and never waits for it: with no daemon, or a version that predates this, they are dropped. diff --git a/hermes-plugin/__init__.py b/hermes-plugin/__init__.py index 0c75071d7..ccd27f718 100644 --- a/hermes-plugin/__init__.py +++ b/hermes-plugin/__init__.py @@ -19,6 +19,7 @@ from .client import PolicyVerdict, evaluate_policy from .ledger import InstructionLedger, LedgerError +from .self_report import SelfReportTool, register_self_report_tool logger = logging.getLogger(__name__) @@ -665,6 +666,9 @@ def setting(key: str, default: Any) -> Any: ) self._handoff = _ReminderHandoff() self._delivered = _TurnDeliveries() + # Set by register() once the Self Reports tool is registered: its + # instructions then ride pre_llm_call with the protocol hint. + self.self_report: SelfReportTool | None = None def _fallback(self, error: Exception) -> dict[str, str] | None: logger.error("FailproofAI evaluator unavailable: %s", error) @@ -980,7 +984,13 @@ def subagent_stop(self, session_id: str = "", **kwargs: Any) -> None: @_guarded(_protocol_context) def pre_llm_call(self, **kwargs: Any) -> dict[str, str]: - return {"context": _PROTOCOL_CONTEXT} + instructions = "" + if self.self_report is not None: + try: + instructions = self.self_report.instructions() + except Exception as exc: + logger.warning("FailproofAI Self Reports instructions unavailable: %s", exc) + return {"context": f"{_PROTOCOL_CONTEXT}\n\n{instructions}" if instructions else _PROTOCOL_CONTEXT} @_guarded(_nothing) def on_session_reset(self, session_id: str = "", **kwargs: Any) -> None: @@ -1034,16 +1044,25 @@ def register(ctx: Any) -> None: except Exception as exc: logger.error("FailproofAI could not register Hermes tool_execution middleware: %s", exc) middleware = plugin.wraps_execution + # Self Reports: the report tool as a direct native tool (never behind + # Hermes' tool search), recorded by failproofaid like the MCP call was. + try: + plugin.self_report = register_self_report_tool(ctx) + except Exception as exc: + logger.error("FailproofAI could not register the Self Reports tool: %s", exc) + self_report_tool = plugin.self_report is not None except Exception as exc: logger.exception("FailproofAI plugin failed to register") error = f"{type(exc).__name__}: {exc}" middleware = False + self_report_tool = False beat.update( stage="end", register_ok=not error and hooks == list(_HOOKS), hooks_registered=hooks, middleware_registered=middleware, + self_report_tool=self_report_tool, ) if error: beat["error"] = error diff --git a/hermes-plugin/plugin.yaml b/hermes-plugin/plugin.yaml index e0a12eb90..41f656b1c 100644 --- a/hermes-plugin/plugin.yaml +++ b/hermes-plugin/plugin.yaml @@ -1,5 +1,5 @@ name: failproofai -version: 1.0.18-beta.3 +version: 1.0.18-beta.4 description: Real-time FailproofAI policy enforcement for Hermes manifest_version: 2 api_version: 1 diff --git a/hermes-plugin/self_report.py b/hermes-plugin/self_report.py new file mode 100644 index 000000000..57b565a5d --- /dev/null +++ b/hermes-plugin/self_report.py @@ -0,0 +1,260 @@ +"""Self Reports on Hermes: failproofai's ``report`` tool as a NATIVE plugin tool. + +Hermes defers MCP tools behind its tool search (``tools.tool_search``, on by +default), and plugin tools too: only names in ``toolsets._HERMES_CORE_TOOLS`` +never defer (``tools/tool_search.py`` ``is_deferrable_tool_name``, 0.20.0 and +0.21.x). There is no per-server or per-tool setting, so a ``failproofai_local`` +MCP entry reached the model only as a name in the deferred listing and the +model never reported (0/2 on a strong model). This plugin, which every hooked +Hermes profile already loads, registers the tool itself and adds its name to +that core list, so it is a direct tool, and puts the server's instructions in +``pre_llm_call`` context. ``self-report sync`` writes no Hermes MCP entry and +removes one an earlier version wrote. + +The text and the recording come from failproofaid's own Self Reports MCP +server, so this file holds no copy of either: the description and schema are +what its ``tools/list`` returns (no tool while Self Reports is off), and each +call is its ``tools/call``, sent as ``?agent=hermes&cwd=`` so the report +is attributed, deduped and logged exactly as the MCP path did. The endpoint is +trusted only when it answers ``initialize`` with the ``instanceId`` the daemon +behind this user's socket reports in its pong. +""" + +from __future__ import annotations + +import json +import logging +import os +import threading +import time +import urllib.parse +import urllib.request +from typing import Any, Callable, Mapping + +from .client import PROTOCOL_VERSION, _exchange + +logger = logging.getLogger(__name__) + +# Hermes' spelling of the MCP tool (``mcp__``): the hook lets it +# past every policy, exactly as it did the MCP call. +TOOL_NAME = "mcp_failproofai_local_report" +TOOLSET = "failproofai" + +_TIMEOUT_S = 3.0 +_CALL_TIMEOUT_S = 20.0 +_REFRESH_S = 60.0 +_ARG_ALIASES = { + "category": ("category", "type", "kind"), + "detail": ("detail", "summary", "sentence", "message", "description", "reason", "text", "details"), +} + + +def ping_self_report_server(timeout_s: float = _TIMEOUT_S) -> dict[str, Any] | None: + """The daemon's pong ``selfReport`` ({instanceId, port}), or None.""" + body = json.dumps({"type": "ping", "protocolVersion": PROTOCOL_VERSION}).encode("utf-8") + try: + reply = _exchange(body, int(timeout_s * 1000), time.monotonic() + timeout_s) + except Exception: + return None + server = reply.get("selfReport") if isinstance(reply, Mapping) and reply.get("type") == "pong" else None + if not isinstance(server, Mapping): + return None + instance, port = server.get("instanceId"), server.get("port") + if not isinstance(instance, str) or not isinstance(port, int) or isinstance(port, bool): + return None + return {"instanceId": instance, "port": port} + + +def _rpc(url: str, body: Mapping[str, Any], timeout_s: float) -> Any: + request = urllib.request.Request( + url, + data=json.dumps(body).encode("utf-8"), + headers={"content-type": "application/json", "accept": "application/json, text/event-stream"}, + method="POST", + ) + # A loopback URL only: no proxy may see a report. + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with opener.open(request, timeout=timeout_s) as response: + return json.loads(response.read().decode("utf-8")) + + +_INIT = { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "failproofai-hermes-plugin", "version": "1"}, + }, +} + + +def discover_self_report_tool( + ping: Callable[[], dict[str, Any] | None] = ping_self_report_server, + rpc: Callable[[str, Mapping[str, Any], float], Any] = _rpc, +) -> dict[str, Any] | None: + """The tool as failproofaid offers it now, or None (no daemon, not this + user's daemon on the port, or Self Reports off).""" + server = ping() + if not server: + return None + base = f"http://127.0.0.1:{server['port']}/mcp?agent=hermes" + try: + init = rpc(base, _INIT, _TIMEOUT_S) + result = init.get("result") if isinstance(init, Mapping) else None + info = result.get("serverInfo") if isinstance(result, Mapping) else None + if not isinstance(info, Mapping) or info.get("instanceId") != server["instanceId"]: + return None + listed = rpc(base, {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, _TIMEOUT_S) + tools = (listed.get("result") or {}).get("tools") if isinstance(listed, Mapping) else None + tool = tools[0] if isinstance(tools, list) and tools else None + if not isinstance(tool, Mapping) or not isinstance(tool.get("description"), str): + return None + schema = tool.get("inputSchema") + if not isinstance(schema, Mapping): + return None + instructions = result.get("instructions") + return { + "port": server["port"], + "instanceId": server["instanceId"], + "description": tool["description"], + "inputSchema": dict(schema), + "instructions": instructions if isinstance(instructions, str) and instructions else "", + } + except Exception: + return None + + +def prepare_arguments(raw: Any) -> dict[str, str]: + """A model that guessed the argument names still reports (contract §3).""" + args = raw if isinstance(raw, Mapping) else {} + out: dict[str, str] = {} + for key, aliases in _ARG_ALIASES.items(): + out[key] = "" + for alias in aliases: + value = args.get(alias) + if isinstance(value, str) and value.strip(): + out[key] = value + break + return out + + +def call_self_report_tool( + tool: Mapping[str, Any], + args: Any, + cwd: str, + ping: Callable[[], dict[str, Any] | None] = ping_self_report_server, + rpc: Callable[[str, Mapping[str, Any], float], Any] = _rpc, +) -> str: + """Hand one call to failproofaid's server; the text it answers.""" + server = ping() + if not server or server["instanceId"] != tool.get("instanceId") or server["port"] != tool.get("port"): + return "Recorded." + query = {"agent": "hermes", **({"cwd": cwd} if cwd else {})} + url = f"http://127.0.0.1:{tool['port']}/mcp?{urllib.parse.urlencode(query)}" + try: + reply = rpc( + url, + {"jsonrpc": "2.0", "id": 3, "method": "tools/call", + "params": {"name": "report", "arguments": prepare_arguments(args)}}, + _CALL_TIMEOUT_S, + ) + content = ((reply or {}).get("result") or {}).get("content") + first = content[0] if isinstance(content, list) and content else {} + text = first.get("text") if isinstance(first, Mapping) else None + return text if isinstance(text, str) else "Recorded." + except Exception: + return "Recorded." + + +def _keep_direct(name: str) -> bool: + """Put ``name`` on Hermes' never-deferred list (``toolsets._HERMES_CORE_TOOLS``).""" + try: + import toolsets # type: ignore[import-not-found] + except Exception: + return False + core = getattr(toolsets, "_HERMES_CORE_TOOLS", None) + try: + if isinstance(core, list): + if name not in core: + core.append(name) + return True + if isinstance(core, set): + core.add(name) + return True + except Exception: + return False + return False + + +class SelfReportTool: + """The registered tool's live state: refreshed from the daemon at most once a minute.""" + + def __init__( + self, + discover: Callable[[], dict[str, Any] | None] = discover_self_report_tool, + call: Callable[..., str] = call_self_report_tool, + clock: Callable[[], float] = time.monotonic, + ) -> None: + self._discover = discover + self._call = call + self._clock = clock + self._lock = threading.Lock() + self.current: dict[str, Any] | None = None + self._fetched = float("-inf") + + def refresh(self, force: bool = False) -> dict[str, Any] | None: + with self._lock: + if not force and self._clock() - self._fetched < _REFRESH_S: + return self.current + self._fetched = self._clock() + tool = None + try: + tool = self._discover() + except Exception: + tool = None + with self._lock: + self.current = tool + return tool + + def available(self) -> bool: + return self.refresh() is not None + + def instructions(self) -> str: + tool = self.refresh() + return (tool or {}).get("instructions") or "" + + def handler(self, args: Any = None, **kwargs: Any) -> str: + tool = self.current or self.refresh(force=True) + if not tool: + return "Recorded." + cwd = kwargs.get("cwd") if isinstance(kwargs.get("cwd"), str) and kwargs.get("cwd") else os.getcwd() + return self._call(tool, args, cwd) + + +def register_self_report_tool(ctx: Any, state: SelfReportTool | None = None) -> SelfReportTool | None: + """Register the native tool on ``ctx`` when failproofaid offers one right + now. Never raises. The schema is fixed at registration (Hermes' registry + keeps it), so new categories reach Hermes on the gateway's next start; the + switch itself is followed live through ``check_fn``.""" + state = state or SelfReportTool() + tool = state.refresh(force=True) + if not tool or not hasattr(ctx, "register_tool"): + return None + schema = {"name": TOOL_NAME, "description": tool["description"], "parameters": tool["inputSchema"]} + try: + ctx.register_tool( + name=TOOL_NAME, + toolset=TOOLSET, + schema=schema, + handler=state.handler, + check_fn=state.available, + description=tool["description"], + ) + except Exception as exc: + logger.warning("FailproofAI could not register the Self Reports tool: %s", exc) + return None + if not _keep_direct(TOOL_NAME): + logger.warning("FailproofAI could not keep the Self Reports tool out of Hermes' tool search") + return state diff --git a/openclaw-plugin/hooks.js b/openclaw-plugin/hooks.js index f4aa23dc4..5cc9cddb8 100644 --- a/openclaw-plugin/hooks.js +++ b/openclaw-plugin/hooks.js @@ -22,7 +22,8 @@ import { createWorkspaceContext } from "./workspace-context.js"; import { openclawAgentSettingsPath, requestHookVerdict } from "./daemon-client.js"; const sharedRetryGate = createInstructRetryGate(); -const sharedWorkspace = createWorkspaceContext(); +/** Shared with the Self Reports tool, so its reports land in the workspace the hooks saw. */ +export const sharedWorkspace = createWorkspaceContext(); const OBSERVATION_EVENTS = [ "after_tool_call", diff --git a/openclaw-plugin/index.js b/openclaw-plugin/index.js index e1cf93d65..b6f046071 100644 --- a/openclaw-plugin/index.js +++ b/openclaw-plugin/index.js @@ -27,7 +27,8 @@ * happens inside register()'s handlers. */ import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry"; -import { registerFailproofaiHooks } from "./hooks.js"; +import { registerFailproofaiHooks, sharedWorkspace } from "./hooks.js"; +import { registerSelfReportTool } from "./self-report.js"; export default definePluginEntry({ id: "failproofai", @@ -35,5 +36,7 @@ export default definePluginEntry({ description: "Real-time policy enforcement for OpenClaw by failproofai", register(api) { registerFailproofaiHooks(api); + // Self Reports: the `report` tool as a direct (never deferred) plugin tool. + registerSelfReportTool(api, { workspace: sharedWorkspace }); }, }); diff --git a/openclaw-plugin/openclaw.plugin.json b/openclaw-plugin/openclaw.plugin.json index 879fcde17..d47a454cb 100644 --- a/openclaw-plugin/openclaw.plugin.json +++ b/openclaw-plugin/openclaw.plugin.json @@ -2,5 +2,10 @@ "id": "failproofai", "name": "failproofai", "description": "Real-time policy enforcement for OpenClaw by failproofai", - "configSchema": {} + "configSchema": {}, + "contracts": { + "tools": [ + "failproofai_local__report" + ] + } } diff --git a/openclaw-plugin/self-report.js b/openclaw-plugin/self-report.js new file mode 100644 index 000000000..67e30489f --- /dev/null +++ b/openclaw-plugin/self-report.js @@ -0,0 +1,231 @@ +/** + * Self Reports on OpenClaw: failproofai's `report` tool as a NATIVE plugin tool. + * + * OpenClaw defers MCP tools behind its Tool Search (`tools.toolSearch`, on by + * default for embedded runs) and has no per-server setting that keeps one + * server's tools direct, so a `failproofai_local` MCP entry reached the model + * only as a name in the deferred directory; the model never read the tool's + * description and never reported (0/2 on a strong model). A plugin tool marked + * `catalogMode: "direct-only"` stays model-visible (docs/tools/tool-search.md), + * so this plugin, which every hooked OpenClaw already loads, registers the tool + * itself and puts the server's instructions in the system prompt + * (`before_prompt_build` → `appendSystemContext`). `self-report sync` writes + * no OpenClaw MCP entry and removes one an earlier version wrote. + * + * The text and the recording come from failproofaid's own Self Reports MCP + * server (crates/fpai-collect/src/self_report.rs), so this file holds no copy + * of either: the tool's description and schema are what its `tools/list` + * returns (none while Self Reports is off), and each call is its `tools/call`, + * sent as `?agent=openclaw&cwd=` so the report is attributed, deduped + * and logged exactly as the MCP path did. The endpoint is trusted only when it + * answers `initialize` with the `instanceId` the daemon behind THIS user's + * socket reports in its pong: a port held by another user's daemon is never + * sent a report. + * + * Node built-ins and siblings only (the plugin is loaded from a captured copy). + */ +import { createConnection } from "node:net"; +import { daemonSocketPath, PROTOCOL_VERSION } from "./daemon-client.js"; + +/** OpenClaw's spelling of the MCP tool (`__`): the hook lets it past every policy. */ +export const SELF_REPORT_OPENCLAW_TOOL = "failproofai_local__report"; + +const REFRESH_MS = 60_000; +const REQUEST_TIMEOUT_MS = 5_000; +const CALL_TIMEOUT_MS = 20_000; +const MAX_FRAME_BYTES = 1024 * 1024; + +/** The daemon's pong `selfReport` ({instanceId, port}) or null. */ +export function pingSelfReportServer({ socketPath = daemonSocketPath(), timeoutMs = REQUEST_TIMEOUT_MS } = {}) { + return new Promise((done) => { + let settled = false; + let buf = Buffer.alloc(0); + const finish = (value) => { + if (settled) return; + settled = true; + clearTimeout(timer); + try { sock.destroy(); } catch { /* closed */ } + done(value); + }; + const sock = createConnection(socketPath); + const timer = setTimeout(() => finish(null), timeoutMs); + sock.on("error", () => finish(null)); + sock.on("connect", () => { + const body = Buffer.from(JSON.stringify({ type: "ping", protocolVersion: PROTOCOL_VERSION }), "utf8"); + const head = Buffer.alloc(4); + head.writeUInt32BE(body.length, 0); + sock.write(Buffer.concat([head, body])); + }); + sock.on("data", (chunk) => { + buf = Buffer.concat([buf, chunk]); + if (buf.length < 4) return; + const len = buf.readUInt32BE(0); + if (len > MAX_FRAME_BYTES) return finish(null); + if (buf.length < 4 + len) return; + try { + const msg = JSON.parse(buf.subarray(4, 4 + len).toString("utf8")); + const sr = msg && msg.type === "pong" ? msg.selfReport : null; + finish(sr && typeof sr.instanceId === "string" && Number.isInteger(sr.port) ? sr : null); + } catch { + finish(null); + } + }); + sock.on("close", () => finish(null)); + }); +} + +async function rpc(url, body, timeoutMs, fetchImpl) { + const res = await fetchImpl(url, { + method: "POST", + headers: { "content-type": "application/json", accept: "application/json, text/event-stream" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs), + }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + return res.json(); +} + +const INIT = { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "failproofai-openclaw-plugin", version: "1" } }, +}; + +/** + * The report tool as failproofaid offers it right now, or null: no daemon, an + * endpoint that is not this user's daemon, or Self Reports off (empty list). + */ +export async function discoverSelfReportTool({ ping = pingSelfReportServer, fetchImpl = globalThis.fetch } = {}) { + const server = await ping(); + if (!server || typeof fetchImpl !== "function") return null; + const base = `http://127.0.0.1:${server.port}/mcp?agent=openclaw`; + try { + const init = await rpc(base, INIT, REQUEST_TIMEOUT_MS, fetchImpl); + if (init?.result?.serverInfo?.instanceId !== server.instanceId) return null; + const listed = await rpc(base, { jsonrpc: "2.0", id: 2, method: "tools/list" }, REQUEST_TIMEOUT_MS, fetchImpl); + const tool = Array.isArray(listed?.result?.tools) ? listed.result.tools[0] : undefined; + if (!tool || typeof tool.description !== "string" || !tool.inputSchema || typeof tool.inputSchema !== "object") return null; + const instructions = init.result.instructions; + return { + port: server.port, + instanceId: server.instanceId, + description: tool.description, + inputSchema: tool.inputSchema, + ...(typeof instructions === "string" && instructions ? { instructions } : {}), + }; + } catch { + return null; + } +} + +/** Hand one call to failproofaid's server; the text it answers (always "Recorded." today). */ +export async function callSelfReportTool(tool, args, cwd, { fetchImpl = globalThis.fetch, ping = pingSelfReportServer } = {}) { + // Re-check the port's owner: the daemon may have restarted on another port. + const server = await ping(); + if (!server || server.instanceId !== tool.instanceId || server.port !== tool.port) return "Recorded."; + const url = `http://127.0.0.1:${tool.port}/mcp?agent=openclaw${cwd ? `&cwd=${encodeURIComponent(cwd)}` : ""}`; + try { + const reply = await rpc( + url, + { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "report", arguments: args ?? {} } }, + CALL_TIMEOUT_MS, + fetchImpl, + ); + const first = Array.isArray(reply?.result?.content) ? reply.result.content[0] : undefined; + return typeof first?.text === "string" ? first.text : "Recorded."; + } catch { + return "Recorded."; + } +} + +function pick(args, keys) { + for (const k of keys) { + const v = args[k]; + if (typeof v === "string" && v.trim() !== "") return v; + } + return ""; +} + +/** A model that guessed the argument names still reports (contract §3), like the MCP server. */ +export function prepareSelfReportArguments(raw) { + const a = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {}; + return { + category: pick(a, ["category", "type", "kind"]), + detail: pick(a, ["detail", "summary", "sentence", "message", "description", "reason", "text", "details"]), + }; +} + +/** + * Register the native tool and the prompt instructions on `api`. The tool + * definition is fetched from the daemon at load and every minute after, so a + * Cloud switch or new categories reach the next turn; while none is known + * (off, or no daemon) the factory offers no tool and no instructions are added. + */ +export function registerSelfReportTool(api, { + discover = discoverSelfReportTool, + call = callSelfReportTool, + workspace = /** @type {{ resolveWorkspace?: (p: object, c: object, config: unknown) => string | undefined } | null} */ (null), + refreshMs = REFRESH_MS, + now = () => Date.now(), +} = {}) { + let current = null; + let fetchedAt = -Infinity; + let inflight = null; + const refresh = () => { + if (inflight) return inflight; + inflight = Promise.resolve() + .then(() => discover()) + .then((tool) => { current = tool ?? null; }) + .catch(() => { current = null; }) + .finally(() => { fetchedAt = now(); inflight = null; }); + return inflight; + }; + const maybeRefresh = () => { + if (now() - fetchedAt >= refreshMs) void refresh(); + }; + void refresh(); + + if (typeof api?.registerTool === "function") { + try { + api.registerTool( + (toolContext) => { + maybeRefresh(); + const tool = current; + if (!tool) return null; + return { + name: SELF_REPORT_OPENCLAW_TOOL, + label: "Report (FailproofAI)", + description: tool.description, + parameters: tool.inputSchema, + // Never behind Tool Search: the model must read when to call it. + catalogMode: "direct-only", + prepareArguments: prepareSelfReportArguments, + async execute(_toolCallId, params) { + const cwd = workspace?.resolveWorkspace?.({}, toolContext ?? {}, api.config) ?? process.cwd(); + const text = await call(tool, prepareSelfReportArguments(params), cwd); + return { content: [{ type: "text", text }], details: { recorded: true } }; + }, + }; + }, + { name: SELF_REPORT_OPENCLAW_TOOL }, + ); + } catch (err) { + try { api.logger?.error?.(`[failproofai] could not register the Self Reports tool: ${err?.message ?? String(err)}`); } catch { /* no logger */ } + } + } + + if (typeof api?.on === "function") { + api.on( + "before_prompt_build", + async () => { + if (now() - fetchedAt >= refreshMs) await refresh(); + const instructions = current?.instructions; + return instructions ? { appendSystemContext: instructions } : undefined; + }, + { priority: 100, timeoutMs: 10_000 }, + ); + } + + return { refresh, current: () => current }; +} diff --git a/package.json b/package.json index e6f73afde..fa7f99bfc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "failproofai", - "version": "1.0.18-beta.3", + "version": "1.0.18-beta.4", "description": "The reliability layer for AI agents: see every failure, stop it in realtime. Policies hooked into 12 agent harnesses — Claude Code, Codex, Cursor, Hermes, OpenClaw and more — block the tool call before it runs. Local dashboard included, no account needed.", "bin": { "failproofai": "./dist/cli.mjs", diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 64e139cda..bab381184 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1416,9 +1416,6 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo // `yq -i` edits in place. if (head === "yq" && args.some((a) => a === "-i" || a.startsWith("--inplace") || /^-[A-Za-z]*i[A-Za-z]*$/.test(a))) return true; - // A `python -c` whose program `pythonCodeOnlyReads` vetted, now the marker. - if (PYTHON_HEAD_RE.test(head) && readOnlyPythonMarker !== null && args.includes(readOnlyPythonMarker)) return false; - // `git` normally carries the path as prose in a message or a body. if (head === "git") { const subcommand = gitSubcommand(args); @@ -2658,9 +2655,15 @@ function blockWorkOnMain(ctx: PolicyContext): PolicyResult { // grep family, jq, yq), unless it names the state or holds a substitution; // - the body of a heredoc fed to a command that only writes it out (`cat`, // `tee`, `:`), when nothing in the same command could run what it wrote; -// - the program of a `python -c` that can only read (`pythonCodeOnlyReads`), -// replaced by a per-call marker that `simpleCommandDestroys` reads as a -// reader. +// +// A `python -c` program is never treated as inert. An earlier version vetted +// "read-only" programs with a blacklist, and dynamic lookups such as +// `sys._getframe().f_builtins["o"+"pen"](path, "w")` walked straight past it: +// no syntactic check of a Python program can prove it only reads. Use `jq`, +// `grep` or `cat` to read the state instead. Nothing is inert either when the +// same command could change what `grep` or `cat` resolves to +// (`COMMAND_REDEFINITION_RE`). A heredoc written out by `cat`/`tee` is no +// more than the Write tool already does, which is not judged by content. // // Anything the scan does not fully understand (an unbalanced quote, a heredoc // with no end) leaves the command exactly as it was, so a confusing command is @@ -2868,57 +2871,17 @@ function scannedHead(words: ShellWord[]): { word: ShellWord; at: number } | unde } /** - * True when a `python -c` program can only read files: it imports nothing - * beyond json/sys/pprint/tomllib, names no dunder, no escape sequence that - * could spell another name, no call that writes, deletes, renames, runs or - * looks a name up dynamically, and every `open(` is a read. - */ -function pythonCodeOnlyReads(code: string): boolean { - if (code.length > 2000 || code.includes("__")) return false; - if (/\\(?![nt])/.test(code)) return false; - const imported = [ - ...[...code.matchAll(/\bfrom\s+([\w.]+)\s+import\b/g)].map((m) => m[1]), - ...[...code.matchAll(/\bimport\s+([\w.]+(?:\s*,\s*[\w.]+)*)/g)].flatMap((m) => m[1].split(/\s*,\s*/)), - ]; - if (/\bimport\b/.test(code) && imported.length === 0) return false; - if (imported.some((m) => !["json", "sys", "pprint", "tomllib"].includes(m))) return false; - const FORBIDDEN = - /\b(?:exec|eval|compile|getattr|setattr|delattr|globals|locals|vars|breakpoint|memoryview|input|help|write|writelines|truncate|unlink|remove|rmdir|rmtree|rename|renames|replace|chmod|chown|symlink|link|mkdir|makedirs|system|popen|spawn\w*|fork|kill|modules|stdin|path_hooks|meta_path|settrace|setprofile|exit)\b/; - if (FORBIDDEN.test(code)) return false; - // Every `open` is a call, and every call reads. - const opens = [...code.matchAll(/\bopen\b/g)]; - for (const m of opens) { - const after = code.slice(m.index! + 4); - if (!/^\s*\(/.test(after)) return false; - let depth = 0; - let end = -1; - let topComma = -1; - for (let k = after.indexOf("("); k < after.length; k++) { - const ch = after[k]; - if (ch === "(" || ch === "[" || ch === "{") depth++; - else if (ch === ")" || ch === "]" || ch === "}") { - depth--; - if (depth === 0) { - end = k; - break; - } - } else if (ch === "," && depth === 1 && topComma === -1) topComma = k; - } - if (end === -1) return false; - if (topComma !== -1) { - const rest = after.slice(topComma + 1, end); - const READ_ARG = String.raw`\s*(?:(?:mode\s*=\s*)?['"](?:r|rb|rt|br|tr)['"]|encoding\s*=\s*['"][A-Za-z0-9_-]+['"])\s*`; - if (!new RegExp(`^${READ_ARG}(?:,${READ_ARG})*$`).test(rest)) return false; - } - } - return true; -} - -/** - * `cmd` with its inert pieces taken out (see above), and the marker that now - * stands for a read-only `python -c` program, or `cmd` unchanged. + * Anything in the command that can change what a later command word runs: + * a shell function definition (`grep() { "$@"; }`), an alias, `shopt`, + * `enable`, `hash -p`, or a `PATH` assignment (`PATH=/tmp/x grep …`). With + * any of them, `grep` is not known to be grep, so nothing is treated as inert. */ -function withoutInertArguments(cmd: string, marker: string): string { +const COMMAND_REDEFINITION_RE = + /(?:^|[\s;&|(){}])(?:function\s+[\w.:-]+|[\w.:-]+\s*\(\s*\)|alias\b|unalias\b|shopt\b|enable\b|hash\b|(?:export\s+|declare\s+[-\w\s]*|typeset\s+[-\w\s]*|readonly\s+)?PATH\+?=|BASH_ENV=|ENV=)/; + +/** `cmd` with its inert pieces taken out (see above), or `cmd` unchanged. */ +function withoutInertArguments(cmd: string): string { + if (COMMAND_REDEFINITION_RE.test(cmd)) return cmd; const scanned = scanShellCommands(cmd); if (!scanned) return cmd; const cuts: Array<{ start: number; end: number; text: string }> = []; @@ -2942,13 +2905,6 @@ function withoutInertArguments(cmd: string, marker: string): string { cuts.push({ start: w.start, end: w.end, text: "''" }); }); } - if (PYTHON_HEAD_RE.test(base)) { - const c = args.findIndex((w) => w.value === "-c"); - const code = c === -1 ? undefined : args[c + 1]; - if (code && !code.substitutes && pythonCodeOnlyReads(code.value)) { - cuts.push({ start: code.start, end: code.end, text: marker }); - } - } if (simple.heredocs.length > 0 && HEREDOC_DATA_HEADS.has(base) && !simple.pipedOut && !anyCodeRunner) { for (const h of simple.heredocs) if (!h.expands) cuts.push({ start: h.bodyStart, end: h.bodyEnd, text: "" }); } @@ -2993,20 +2949,9 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { return allow(); } if (ctx.toolName !== "Bash") return allow(); - // Per call, so no command can spell it. - const marker = `fpReadOnlyPython${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`; - const cmd = withoutInertArguments(getCommand(ctx), marker); - readOnlyPythonMarker = marker; - try { - return judgeFailproofaiCommand(cmd); - } finally { - readOnlyPythonMarker = null; - } + return judgeFailproofaiCommand(withoutInertArguments(getCommand(ctx))); } -/** The marker standing for a read-only `python -c` program in the command being judged. */ -let readOnlyPythonMarker: string | null = null; - function judgeFailproofaiCommand(cmd: string): PolicyResult { // The raw command AND its shell-unescaped form: a shell strips quotes and // backslashes before running the binary, so `fail\proofai config --pause` diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 668afd2c3..29739248e 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -64,6 +64,7 @@ import { SELF_REPORT_MCP_TOOL_NAME, SELF_REPORT_SERVER_RECORDS, } from "./self-report"; +import { selfReportFailureHint, selfReportSessionStartContext } from "./self-report-hint"; import { deliveryHealth, deliveryHealthLine } from "./delivery-health"; import { trackHookEvent, flushHookTelemetry } from "./hook-telemetry"; import * as hookTelemetry from "./hook-telemetry"; @@ -1534,10 +1535,19 @@ export async function evaluateHookEvent( } } + // Self Reports' one failure hint per session (self-report-hint.ts): only + // where every policy allowed with nothing to say, so it never replaces a + // policy's answer. + const hint = + result.decision === "allow" && result.exitCode === 0 && !result.stdout + ? (selfReportFailureHint({ cli, eventType: canonicalEventType, payload: parsed, sessionId: session.sessionId, toolCallId }) ?? + selfReportSessionStartContext(cli, canonicalEventType)) + : null; + return { - exitCode: result.exitCode, - stdout: result.stdout, - stderr: result.stderr, + exitCode: hint?.exitCode ?? result.exitCode, + stdout: hint?.stdout ?? result.stdout, + stderr: hint ? [result.stderr, hint.stderr].filter(Boolean).join("\n") : result.stderr, evaluation: { decision: result.decision, policyName: result.policyName, diff --git a/src/hooks/integrations.ts b/src/hooks/integrations.ts index bbd0c61c6..d7752734d 100644 --- a/src/hooks/integrations.ts +++ b/src/hooks/integrations.ts @@ -1506,7 +1506,7 @@ interface HermesPluginsConfig { const HERMES_PLUGIN_ID = "failproofai"; const HERMES_PLUGIN_MARKER = ".failproofai-managed"; -const HERMES_PLUGIN_FILES = ["plugin.yaml", "__init__.py", "client.py", "ledger.py"] as const; +const HERMES_PLUGIN_FILES = ["plugin.yaml", "__init__.py", "client.py", "ledger.py", "self_report.py"] as const; /** Basename of the plugin directory inside the npm package. */ const HERMES_PLUGIN_SOURCE_DIR = "hermes-plugin"; diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts index 200a6d167..1cc8e6045 100644 --- a/src/hooks/self-report-cli.ts +++ b/src/hooks/self-report-cli.ts @@ -23,6 +23,7 @@ import { readLocalSelfReportConfig, resolveSelfReport, selfReportCloudEnrolled, + selfReportFileDecides, selfReportCloudManaged, selfReportSettingsFile, validateSelfReportCategories, @@ -181,7 +182,7 @@ function selfReportRegistrationLines( const mine = ok && owned.get(port!) === true; state = `http ${r.endpoint ?? "?"} ${mine ? "(answering)" : ok ? "(answering, but NOT this home's daemon)" : "(NOT answering)"}`; } else if (r.registered && r.transport === "extension") { - state = "tool offered by failproofai's Pi extension (loaded with its hooks)"; + state = `tool offered by failproofai's ${r.agent === "pi" ? "Pi extension" : r.agent === "hermes" ? "Hermes plugin" : "OpenClaw plugin"} (loaded with its hooks)`; } else if (r.registered) { const ok = !!r.endpoint && selfReportCommandRunnable(r.endpoint); state = `stdio ${r.endpoint ?? "?"} ${ok ? "(runnable)" : "(NOT runnable)"}`; @@ -295,7 +296,9 @@ async function selfReportStatus(args: string[], deps: SelfReportCliDeps): Promis if (!settings) { const missing = !file && !selfReportFileExists(); // This machine's own file, set aside while the org's setting is awaited. - const awaitingCloud = !!file && file.source !== "cloud" && selfReportCloudEnrolled(); + // This machine's own file, or one another enrolment (a previous org) + // left, set aside while this enrolment's setting is awaited. + const awaitingCloud = !!file && selfReportCloudEnrolled() && !selfReportFileDecides(file); const why = awaitingCloud || (missing && selfReportCloudEnrolled()) ? "waiting" : missing ? "config" : "unreadable"; if (asJson) { return { diff --git a/src/hooks/self-report-hint.ts b/src/hooks/self-report-hint.ts new file mode 100644 index 000000000..025012aa9 --- /dev/null +++ b/src/hooks/self-report-hint.ts @@ -0,0 +1,225 @@ +/** + * Self Reports: one just-in-time hint when a tool call clearly failed. + * + * A built-in behaviour of Self Reports, not a policy: nobody toggles it, it + * never blocks or rewrites a decision, and it runs only after every policy + * allowed the PostToolUse event with nothing to say. When the call FAILED + * (`selfReportToolFailed`), the model gets one short line through the + * harness's own after-a-tool context channel: + * + * If this blocks you and you can't fix it, call failproofai_local's `report` tool once. + * + * At most once per session (a marker under `$FAILPROOFAI_HOME/cache`), only + * while Self Reports is on, never for the report call itself, and never for a + * failure a failproofai deny caused: those are already recorded as blocks. + * + * Where a hint can reach the model (`SELF_REPORT_HINT_CHANNELS`): + * + * | Agent | Event | Channel | + * |----------|-----------------------|---------| + * | claude | PostToolUse, PostToolUseFailure | `hookSpecificOutput.additionalContext` | + * | codex | PostToolUse | `hookSpecificOutput.additionalContext` | + * | cursor | PostToolUse | `{additional_context}` (postToolUse reads only that) | + * | copilot | PostToolUseFailure | `{additionalContext}` (postToolUse reads only a block) | + * | factory | PostToolUse | exit 2 + stderr: droid adds it as an llm-only system message | + * + * None elsewhere: OpenCode's only route is a queued follow-up prompt, Pi, + * Hermes and OpenClaw observe tool results only (through our hooks), Devin's + * PostToolUse answer never reached the transcript in probes, and Antigravity + * and Goose discard it (src/hooks/enforcement-capability.ts). + */ +import { closeSync, mkdirSync, openSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { join } from "node:path"; +import { failproofaiHome } from "./fp-home"; +import { getHookActivityEntriesSince } from "./hook-activity-store"; +import { readEnabledSelfReport, selfReportInstructions } from "./self-report"; +import { isSelfReportToolName, SELF_REPORT_SERVER_NAME, selfReportAntigravityWrappedArgs } from "./self-report-names"; +import type { IntegrationType } from "./types"; + +export const SELF_REPORT_FAILURE_HINT = `If this blocks you and you can't fix it, call ${SELF_REPORT_SERVER_NAME}'s \`report\` tool once.`; + +/** Agents and events whose answer can carry the hint, by how. */ +export const SELF_REPORT_HINT_CHANNELS: Partial>>> = { + claude: { PostToolUse: "hookSpecificOutput", PostToolUseFailure: "hookSpecificOutput" }, + codex: { PostToolUse: "hookSpecificOutput" }, + cursor: { PostToolUse: "cursor" }, + copilot: { PostToolUseFailure: "flat" }, + factory: { PostToolUse: "exit2" }, +}; + +const TEXT_LIMIT = 4000; +const SHORT_RESULT = 600; + +/** The text of a value, bounded. */ +function textOf(v: unknown): string { + if (typeof v === "string") return v.slice(0, TEXT_LIMIT); + if (v === undefined || v === null) return ""; + try { + return JSON.stringify(v).slice(0, TEXT_LIMIT); + } catch { + return ""; + } +} + +const FAILURE_TEXT: RegExp[] = [ + /\b(?:HTTP\/\d(?:\.\d)?\s+|status(?:\s*code)?[:=\s]+|error[:\s]+)40[13]\b/i, + /\b40[13]\s+(?:unauthori[sz]ed|forbidden)\b/i, + /\bunauthori[sz]ed\b|\bforbidden\b/i, + /\bpermission denied\b|\bEACCES\b|\bEPERM\b/i, + /\bnot found\b|\bENOENT\b|\bno such file or directory\b/i, + /\bexit(?:ed)?(?: with)? (?:code|status)[:\s]+[1-9]\d*\b/i, +]; + +function textLooksFailed(text: string): boolean { + return text !== "" && FAILURE_TEXT.some((re) => re.test(text)); +} + +function nonZeroExit(v: unknown): boolean { + return typeof v === "number" && Number.isFinite(v) && v !== 0; +} + +/** + * Whether a PostToolUse (or PostToolUseFailure) payload is a call that clearly + * FAILED: the failure event itself, an explicit error or error flag (an MCP + * `isError`), a non-zero exit code, or, in the error-ish text only (stderr, an + * error message, or a short result), a 401/403, `not found`, `permission + * denied` or a non-zero exit status. A long successful result that happens to + * contain such words (a file being read) is never judged by its text. + */ +export function selfReportToolFailed(eventType: string, payload: Record): boolean { + if (eventType === "PostToolUseFailure") return true; + if (eventType !== "PostToolUse") return false; + if (typeof payload.error === "string" && payload.error.trim() !== "") return true; + if (payload.is_error === true || payload.isError === true) return true; + const response = payload.tool_response ?? payload.tool_output ?? payload.toolResult ?? payload.tool_result ?? payload.result; + if (response && typeof response === "object" && !Array.isArray(response)) { + const r = response as Record; + if (r.isError === true || r.is_error === true || r.success === false) return true; + for (const k of ["exit_code", "exitCode", "returncode", "returnCode", "status_code"]) { + if (k === "status_code" ? typeof r[k] === "number" && (r[k] as number) >= 400 : nonZeroExit(r[k])) return true; + } + if (typeof r.error === "string" && r.error.trim() !== "") return true; + if (r.error && typeof r.error === "object") return true; + if (textLooksFailed(textOf(r.stderr))) return true; + for (const k of ["output", "content", "text", "message", "result"]) { + const t = textOf(r[k]); + if (t.length <= SHORT_RESULT && textLooksFailed(t)) return true; + } + return false; + } + const t = textOf(response); + return t.length <= SHORT_RESULT && textLooksFailed(t); +} + +/** The call's text mentions a failproofai block (a deny's own message). */ +function blockedByFailproofai(payload: Record): boolean { + const t = textOf(payload.tool_response ?? payload.error ?? payload.tool_output ?? payload.toolResult ?? ""); + return /\b(?:blocked|denied) by failproofai\b|\bfailproofai\b.*\b(?:blocked|denied)\b|FailproofAI could not check this call/i.test(t); +} + +/** A PreToolUse deny for this very call (same session and tool call id) in the last 10 minutes. */ +function deniedEarlier(sessionId: string, toolCallId: string | undefined, now: number): boolean { + if (!toolCallId) return false; + try { + return (getHookActivityEntriesSince(now - 10 * 60 * 1000) as unknown as Array>).some( + (row) => row.sessionId === sessionId && row.toolCallId === toolCallId && row.decision === "deny", + ); + } catch { + return false; + } +} + +/** Claim the per-session marker: true only for the first claim of this session. */ +function claimOnce(cli: string, sessionId: string): boolean { + const dir = join(failproofaiHome(), "cache", "self-report-hints"); + const id = createHash("sha256").update(`${cli}\0${sessionId}`).digest("hex").slice(0, 32); + try { + mkdirSync(dir, { recursive: true, mode: 0o700 }); + closeSync(openSync(join(dir, id), "wx", 0o600)); + return true; + } catch { + return false; + } +} + +export interface SelfReportHintInput { + cli: IntegrationType; + /** Canonical event: PostToolUse or PostToolUseFailure. */ + eventType: string; + payload: Record; + sessionId: string | undefined; + toolCallId?: string; + now?: number; + /** Test seam: whether Self Reports is on (default: the settings readers). */ + enabled?: () => boolean; +} + +/** + * The answer that carries the hint, or null to answer as usual. Consumes the + * session's one hint when it returns one. + */ +export function selfReportFailureHint(input: SelfReportHintInput): { exitCode: number; stdout: string; stderr: string } | null { + const channel = SELF_REPORT_HINT_CHANNELS[input.cli]?.[input.eventType]; + if (!channel || !input.sessionId) return null; + const { payload } = input; + const tool = payload.tool_name; + if (isSelfReportToolName(tool) || selfReportAntigravityWrappedArgs(tool, payload.tool_input)) return null; + if (typeof tool === "string" && /(^|[^a-z])report$/i.test(tool) && String(payload.mcp_server_name ?? "").toLowerCase() === SELF_REPORT_SERVER_NAME) return null; + if (!selfReportToolFailed(input.eventType, payload)) return null; + if (blockedByFailproofai(payload)) return null; + const now = input.now ?? Date.now(); + if (deniedEarlier(input.sessionId, input.toolCallId, now)) return null; + if (!(input.enabled ?? (() => readEnabledSelfReport() !== null))()) return null; + if (!claimOnce(input.cli, input.sessionId)) return null; + switch (channel) { + case "hookSpecificOutput": + return { + exitCode: 0, + stdout: JSON.stringify({ hookSpecificOutput: { hookEventName: input.eventType, additionalContext: SELF_REPORT_FAILURE_HINT } }), + stderr: "", + }; + case "cursor": + return { exitCode: 0, stdout: JSON.stringify({ additional_context: SELF_REPORT_FAILURE_HINT }), stderr: "" }; + case "flat": + return { exitCode: 0, stdout: JSON.stringify({ additionalContext: SELF_REPORT_FAILURE_HINT }), stderr: "" }; + case "exit2": + return { exitCode: 2, stdout: "", stderr: SELF_REPORT_FAILURE_HINT }; + } +} + +/** + * Agents whose MCP tools are deferred with no setting to keep ours direct, and + * whose SessionStart answer reaches the model: the server's instructions go + * there, so the model knows the tool exists before it needs it. Factory droid + * defers every MCP server's tools whose name does not contain `github` or + * `agentbrowser` (droid 0.17x, `McpToolSearch` on by default) and reads a + * SessionStart `additionalContext` (applySessionStartHookResults). + */ +export const SELF_REPORT_SESSION_START_CONTEXT_AGENTS: readonly IntegrationType[] = ["factory"]; + +/** The SessionStart answer that carries the instructions, or null. */ +export function selfReportSessionStartContext( + cli: IntegrationType, + eventType: string, + settings: ReturnType | undefined = undefined, +): { exitCode: number; stdout: string; stderr: string } | null { + if (eventType !== "SessionStart" || !SELF_REPORT_SESSION_START_CONTEXT_AGENTS.includes(cli)) return null; + const s = settings === undefined ? readEnabledSelfReport() : settings; + if (!s) return null; + return { + exitCode: 0, + stdout: JSON.stringify({ + hookSpecificOutput: { + hookEventName: "SessionStart", + // The handshake text says "this server's"; here it arrives outside the + // server, so name it. + additionalContext: selfReportInstructions(s.categories, s.guidance).replace( + "this server's `report` tool", + `the \`${SELF_REPORT_SERVER_NAME}\` MCP server's \`report\` tool`, + ), + }, + }), + stderr: "", + }; +} diff --git a/src/hooks/self-report-hook-trust.ts b/src/hooks/self-report-hook-trust.ts index e4b2bed01..4b8512deb 100644 --- a/src/hooks/self-report-hook-trust.ts +++ b/src/hooks/self-report-hook-trust.ts @@ -23,8 +23,9 @@ * prediction is wrong (a Codex whose hash scheme changed, say) or the state * changes while the agent runs (a person trusts the hooks mid-session). */ -import { existsSync, readFileSync } from "node:fs"; -import { dirname, resolve } from "node:path"; +import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { dirname, join, resolve } from "node:path"; import { CODEX_UNTRUSTED_NOTICE, codexGatesHookTrust, @@ -38,6 +39,7 @@ import { claudeConfigDir, getIntegration } from "./integrations"; import { getHookActivityEntriesSince } from "./hook-activity-store"; import { selfReportArgs } from "./self-report"; import { selfReportClip } from "./self-report-names"; +import { failproofaiHome } from "./fp-home"; /** The agents whose hook, when it runs, is the recorder. */ export const SELF_REPORT_HOOK_RECORDED_AGENTS: readonly string[] = ["claude", "codex"]; @@ -189,30 +191,105 @@ export function selfReportHookState(agent: string, deps: SelfReportHookTrustDeps export const SELF_REPORT_HOOK_DEDUPE_MS = 2 * 60 * 1000; /** - * Whether `agent`'s hook already recorded this report: a PreToolUse row from - * that integration, written in the last two minutes, carrying a `selfReport` - * with the same category and detail (as the hook would have clipped them). - * An unreadable activity store reads as "no", so a report is recorded rather - * than lost. + * Whether `agent`'s hook already recorded THIS call, and if so claim that + * record so it vouches for one call only (review 4722003644). + * + * A hook row matches when it is a PreToolUse row from that integration, + * written in the last two minutes, in the same working directory as this + * server (`cwd`; a row or a server without one never matches), carrying a + * `selfReport` with the same category and detail as the hook would have + * clipped them. Matching on the report's text alone suppressed distinct calls: + * a report the hook recorded in project A made an identical report in project + * B answer `Recorded.` with no event. + * + * Each row is consumed by the first call it matches: a receipt named after the + * row (its integration, session, tool call id and timestamp) is created with + * O_EXCL under `$FAILPROOFAI_HOME/cache/self-report-receipts/`, and a row whose + * receipt exists already vouched for another call. So two sessions in one + * directory sending the same text each need their own hook row, and a second + * identical call in one session is recorded unless its own hook row is there. + * + * An unreadable activity store reads as "no", and so does a receipt that + * cannot be written for any reason but "already there": a report is recorded + * rather than lost. */ export function selfReportHookRecordedRecently( agent: string, args: unknown, now: number = Date.now(), + cwd?: string, ): boolean { + if (!cwd) return false; const { category, detail } = selfReportArgs(args ?? {}); const want = { category: selfReportClip(category), detail: selfReportClip(detail) }; + const here = sameDir(cwd); let rows: Array>; try { rows = getHookActivityEntriesSince(now - SELF_REPORT_HOOK_DEDUPE_MS) as unknown as Array>; } catch { return false; } - return rows.some((row) => { + const candidates = rows.filter((row) => { if (row.integration !== agent || row.eventType !== "PreToolUse") return false; const ts = typeof row.timestamp === "number" ? row.timestamp : NaN; if (!Number.isFinite(ts) || now - ts > SELF_REPORT_HOOK_DEDUPE_MS || ts - now > 60_000) return false; + if (typeof row.cwd !== "string" || !row.cwd || sameDir(row.cwd) !== here) return false; const sr = row.selfReport as { category?: unknown; detail?: unknown } | undefined; return !!sr && sr.category === want.category && sr.detail === want.detail; }); + // Oldest first, so concurrent calls claim rows in the order the hooks ran. + candidates.sort((x, y) => (x.timestamp as number) - (y.timestamp as number)); + for (const row of candidates) { + const claimed = claimHookRow(row, now); + if (claimed === "claimed") return true; + if (claimed === "error") return false; + } + return false; +} + +/** A directory as the filesystem names it (symlinks resolved when it exists). */ +function sameDir(dir: string): string { + try { + return realpathSync(dir); + } catch { + return resolve(dir); + } +} + +/** `$FAILPROOFAI_HOME/cache/self-report-receipts`. */ +export function selfReportReceiptDir(): string { + return join(failproofaiHome(), "cache", "self-report-receipts"); +} + +/** Claim one hook row for one call: `taken` when another call already did. */ +function claimHookRow(row: Record, now: number): "claimed" | "taken" | "error" { + const dir = selfReportReceiptDir(); + const id = createHash("sha256") + .update(JSON.stringify([row.integration, row.sessionId ?? null, row.toolCallId ?? null, row.timestamp, row.cwd])) + .digest("hex") + .slice(0, 32); + try { + mkdirSync(dir, { recursive: true, mode: 0o700 }); + pruneReceipts(dir, now); + closeSync(openSync(join(dir, id), "wx", 0o600)); + return "claimed"; + } catch (err) { + return (err as NodeJS.ErrnoException)?.code === "EEXIST" ? "taken" : "error"; + } +} + +/** Receipts older than the window can match no row any more. */ +function pruneReceipts(dir: string, now: number): void { + try { + for (const name of readdirSync(dir)) { + try { + const path = join(dir, name); + if (now - statSync(path).mtimeMs > 2 * SELF_REPORT_HOOK_DEDUPE_MS) rmSync(path, { force: true }); + } catch { + // raced with another server's prune + } + } + } catch { + // nothing to prune + } } diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index f559b0a15..753b845e0 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -7,20 +7,20 @@ * register as `failproofai`; the two coexist. Which transport * an agent gets depends on who records its reports (CONTRACT §7, §8): * - * - Hook-recorded agents (claude, codex: not in `SELF_REPORT_SERVER_RECORDS`) - * are served by the daemon over Streamable HTTP at - * `http://127.0.0.1:/mcp?agent=` when the daemon behind this home's - * socket is serving that port (`selfReportDaemonLive`), else stdio. Their - * hook records the report against the exact session, so the server records - * nothing and needs no caller identity. - * - Server-recorded agents (everything in `SELF_REPORT_SERVER_RECORDS`) always - * get `failproofai mcp --agent ` over stdio. The server records their - * report itself and must pick the session; one user-scope HTTP entry serves - * every project and carries only `?agent=`, so over HTTP it could not tell - * which project called, while a stdio server knows its real cwd. - * - * The daemon runs `self-report sync` once it is listening, so hook-recorded - * agents move to HTTP when it comes up. + * - Every agent gets `failproofai mcp --agent ` over stdio. Hook-recorded + * agents (claude, codex: not in `SELF_REPORT_SERVER_RECORDS`) used to be + * served by the daemon over Streamable HTTP while their user-scope hook would + * record, but a project can turn the hooks off (Claude Code + * `disableAllHooks`) under a user-wide entry, and that endpoint records + * nothing for them. Over stdio the server records what the hook did not + * (`selfReportHookRecordedRecently`). The HTTP path is kept behind + * `SELF_REPORT_HTTP_AGENTS` (empty) and an HTTP entry is moved to stdio. + * - Server-recorded agents always got stdio: the server records their report + * itself and must pick the session; one user-scope HTTP entry serves every + * project and carries only `?agent=`, so over HTTP it could not tell which + * project called, while a stdio server knows its real cwd. + * - Pi, Hermes and OpenClaw get no MCP entry: failproofai's own extension or + * plugin registers the tool (see "Visibility" below). * * ## Where each agent keeps user-scope MCP servers (checked 2026-11-25) * @@ -31,17 +31,17 @@ * * | Agent | File (profile/env) | Key | HTTP entry | stdio entry | Hook sees MCP / name | * |-------------|------------------------------------------------------|----------------------------|----------------------------------------------|-------------------------------------|----------------------| - * | claude | `$CLAUDE_CONFIG_DIR/.claude.json`, else `~/.claude.json` | `mcpServers` | `{type:"http", url}` | `{type:"stdio", command, args}` | yes, PreToolUse `mcp__failproofai_local__report` | + * | claude | `$CLAUDE_CONFIG_DIR/.claude.json`, else `~/.claude.json` | `mcpServers` | `{type:"http", url, alwaysLoad}` | `{type:"stdio", command, args, alwaysLoad:true}` | yes, PreToolUse `mcp__failproofai_local__report` | * | codex | `$CODEX_HOME/config.toml` (TOML) | `[mcp_servers.failproofai_local]`| `url = "…"` | `command`, `args` | yes, PreToolUse `mcp__failproofai_local__report` | * | copilot | `$COPILOT_HOME/mcp-config.json`, else `~/.copilot/` | `mcpServers` | `{type:"http", url, tools:["*"]}` | `{type:"local", command, args, tools:["*"]}` | not documented; likely `failproofai_local-report` (exempt, with `failproofai_local/report`) | * | cursor | `~/.cursor/mcp.json` (editor and cursor-agent) | `mcpServers` | `{url}` | `{type:"stdio", command, args}` | `beforeMCPExecution` (tool_name `report` + mcp_server_name; not installed) and preToolUse `MCP:report` with no server, so the server records | * | opencode | `~/.config/opencode/opencode.json` (as the hooks) | v1 `mcp.`; v2 `mcp.servers.` | `{type:"remote", url, enabled:true}` (v2: no `enabled`) | `{type:"local", command:[…]}` | yes, plugin `tool.execute.before` `failproofai_local_report` | * | pi | `$PI_CODING_AGENT_DIR/mcp.json`, else `~/.pi/agent/` | `mcpServers` | `{url, exposure:"direct"}` | `{command, args, exposure:"direct"}` | yes per docs, `tool_call` `mcp__failproofai_local__report` | - * | hermes | every profile's `config.yaml` (YAML, HERMES_HOME) | `mcp_servers` | `{url}` | `{command, args}` | yes per source, `pre_tool_call` `mcp_failproofai_local_report` | - * | openclaw | every profile's `openclaw.json` | `mcp.servers` | `{url, transport:"streamable-http"}` | `{command, args}` | likely (source only), `before_tool_call` `failproofai_local__report` | + * | hermes | every profile's `config.yaml` (YAML, HERMES_HOME) | `mcp_servers` | (none written: plugin tool) | (removed if an earlier version wrote it) | yes per source, `pre_tool_call` `mcp_failproofai_local_report` | + * | openclaw | every profile's `openclaw.json` | `mcp.servers` | (none written: plugin tool) | (removed if an earlier version wrote it) | yes, `before_tool_call` `failproofai_local__report` | * | factory | `~/.factory/mcp.json` | `mcpServers` | `{type:"http", url}` | `{type:"stdio", command, args}` | yes, `mcp__failproofai_local__report` (regex sees `failproofai_local___report`) | * | devin | `~/.config/devin/mcp_config.json` | `mcpServers` | `{url, transport:"http"}` | `{command, args}` | yes, `mcp__failproofai_local__report` | - * | antigravity | `~/.gemini/config/mcp_config.json` | `mcpServers` | `{serverUrl}` | `{command, args}` | not documented; eager tools `mcp_failproofai_local_report`, lazy (default) via `call_mcp_tool` | + * | antigravity | `~/.gemini/config/mcp_config.json` | `mcpServers` | `{serverUrl, eager}` | `{command, args, eager:true}` | not documented; eager tools `mcp_failproofai_local_report`, lazy (default) via `call_mcp_tool` | * | goose | `$GOOSE_PATH_ROOT/config/config.yaml`, else `~/.config/goose/config.yaml` (YAML) | `extensions` | `{type:"streamable_http", name, enabled, uri, …}` | `{type:"stdio", name, enabled, cmd, args, …}` | not documented; would be `failproofai_local__report` | * * Cursor approval (cursor-agent 2026.11): servers from a *project* @@ -53,10 +53,22 @@ * failproofai writes no approval; sync and status point at * `cursor-agent mcp enable failproofai_local` instead. * - * Deferred tools: Pi's entry sets `exposure: "direct"` (its default `codemode` - * shows the model only the server's name). Hermes (`tools.tool_search`) and - * OpenClaw (`tools.toolSearch`) defer MCP tools with a global switch only; - * neither has a per-server "always load" option, so their entries set none. + * ## Visibility: how `report` reaches the model (checked 2026-11-29) + * + * | Agent | Deferred by default? | What failproofai does (evidence) | + * |-------------|----------------------------------------------|----------------------------------| + * | claude | yes, behind tool search | entry `alwaysLoad: true`: "never deferred behind tool search … Equivalent to setting defer_loading: false" (claude 2.1.332 MCP config schema) | + * | codex | no for user MCP servers (tool_search is for apps) | nothing; reported unprompted on a strong model | + * | copilot | tools direct; server instructions only for the built-in `mcpRegistryServerInstructionAllowlist` (github-mcp-server, bluebird, computer-use in 1.0.83), no setting extends it | marked `~/.copilot/instructions/failproofai-self-reports.instructions.md` (any `*.instructions.md` under `$HOME/.copilot/instructions` is a documented source) | + * | cursor | no | nothing; reported unprompted | + * | opencode | no (`defer_loading` only inside the AI SDK, never set by OpenCode) | nothing; reported unprompted | + * | pi | no MCP before 0.99 | Pi extension registers the tool | + * | hermes | yes: MCP and plugin tools, unless named in `toolsets._HERMES_CORE_TOOLS` (0.20.0 and 0.21.3 `is_deferrable_tool_name`); no per-server option | Hermes plugin registers it natively and adds it to that list; verified against both sources: deferrable before, direct after | + * | openclaw | yes, Tool Search on by default (2026.10.5); no per-server option | plugin tool with `catalogMode: "direct-only"` (tool-search catalog skips it) | + * | factory | yes: every MCP server whose name lacks `github`/`agentbrowser` (droid `McpToolSearch`, default on); no setting | the instructions as SessionStart `additionalContext` | + * | devin | can defer behind `tool_search` (namespaces); server config has no eager key (3000.15.14) | nothing possible beyond the name in its listing | + * | antigravity | yes, lazy via `call_mcp_tool` | entry `eager: true` (mcp_config.json server field, protobuf `force_all_tools_eager`, agy 1.5.18) | + * | goose | no (no tool search) | nothing; reported unprompted | * * Every agent supports Streamable HTTP; HTTP is still used only for the * hook-recorded ones (see above). Every path is the user-scope one: MCP servers are a per @@ -77,7 +89,7 @@ * as a conflict. An entry named `failproofai` (the Cloud MCP gateway, or * anything else) is not ours by name and is never read, changed or reported. */ -import { accessSync, constants as fsConstants, existsSync, readFileSync, realpathSync } from "node:fs"; +import { accessSync, constants as fsConstants, existsSync, mkdirSync, readFileSync, realpathSync, rmSync } from "node:fs"; import { execSync } from "node:child_process"; import { homedir, userInfo } from "node:os"; import { basename, dirname, resolve, sep } from "node:path"; @@ -154,11 +166,32 @@ export function readSelfReportMcpSettings(path = selfReportSettingsPath()): Self // ── Transports ────────────────────────────────────────────────────────────── /** - * Whether an agent may be registered over HTTP at all: only when its hook, - * not the server, records the report (see the header). + * The agents sync may register on the daemon's HTTP endpoint: none. + * + * The endpoint records nothing for Claude Code and Codex, because their hook + * records the report. But the MCP entry is user-wide while whether those hooks + * run is not: a Claude Code project can turn them off + * (`.claude/settings.local.json` with `disableAllHooks: true`, review + * 4722003649), a Codex project config can change its hook setup, and a hook + * can be switched off after the entry was written. Over HTTP every report from + * such a project answered `Recorded.` and was lost. Over stdio the server + * records whatever the hook did not, matched per call + * (`selfReportHookRecordedRecently`), so a report is recorded exactly once + * whichever way any project is set up. An HTTP entry an earlier version wrote + * is moved to stdio by the next sync, and `status` flags it. */ -export function selfReportHttpAllowed(agent: IntegrationType): boolean { - return SELF_REPORT_MCP_TARGETS[agent]?.http === true && !SELF_REPORT_SERVER_RECORDS.includes(agent); +export const SELF_REPORT_HTTP_AGENTS: readonly IntegrationType[] = []; + +/** Whether an agent may be registered over HTTP at all (see `SELF_REPORT_HTTP_AGENTS`). */ +export function selfReportHttpAllowed( + agent: IntegrationType, + httpAgents: readonly IntegrationType[] = SELF_REPORT_HTTP_AGENTS, +): boolean { + return ( + httpAgents.includes(agent) && + SELF_REPORT_MCP_TARGETS[agent]?.http === true && + !SELF_REPORT_SERVER_RECORDS.includes(agent) + ); } export type SelfReportTransport = @@ -298,6 +331,60 @@ interface McpTarget { * wrote. */ extension?: true; + /** + * A file of ours beside the MCP entry that puts the server's instructions + * in front of the model (Copilot): written while the entry is, removed with it. + */ + companion?: { path(): string; content(): string }; +} + +function copilotHome(): string { + return process.env.COPILOT_HOME?.trim() || resolve(homedir(), ".copilot"); +} + +/** The marker that makes a companion instructions file ours. */ +export const SELF_REPORT_COMPANION_MARKER = ""; + +/** + * Settings-independent instructions for a companion file: the categories and + * guidance stay in the tool's description, which the agent reads from the + * server on every start, so the file never goes stale. + */ +export function selfReportCompanionInstructions(): string { + return [ + "---", + 'applyTo: "**"', + "---", + SELF_REPORT_COMPANION_MARKER, + "", + "# FailproofAI Self Reports", + "", + "If you get stuck (you keep looping, a tool, credential, API key or token is broken or rejected, you", + "are missing context or access you cannot get, a command keeps failing, or you cannot do what was", + `asked), call the \`report\` tool of the \`${SELF_REPORT_SERVER_NAME}\` MCP server once, with a \`category\``, + "from its description and a one-sentence `detail`. It does not unblock you: continue, or tell the", + "user what is blocking you. There is no need to mention the report to the user.", + "", + ].join("\n"); +} + +/** Write (want) or remove (!want) a companion file; only ever touches one carrying our marker. */ +function syncCompanion(companion: NonNullable, want: boolean): "added" | "updated" | "removed" | "unchanged" | "foreign" { + const path = companion.path(); + const existing = existsSync(path) ? readFileSync(path, "utf8") : null; + if (existing !== null && !existing.includes(SELF_REPORT_COMPANION_MARKER)) return "foreign"; + if (!want) { + if (existing === null) return "unchanged"; + assertNotRealHomeUnderTest(path); + rmSync(path, { force: true }); + return "removed"; + } + const content = companion.content(); + if (existing === content) return "unchanged"; + assertNotRealHomeUnderTest(path); + mkdirSync(dirname(path), { recursive: true }); + writeConfigFileAtomic(path, content); + return existing === null ? "added" : "updated"; } const plainEntry = (t: SelfReportTransport, urlKey = "url"): Record => @@ -345,7 +432,14 @@ export const SELF_REPORT_MCP_TARGETS: Record = { agent: "claude", format: "json", http: true, paths: () => [claudeUserConfigPath()], container: () => ["mcpServers"], - entry: (t) => (t.kind === "http" ? { type: "http", url: t.url } : { type: "stdio", command: t.command, args: t.args }), + // `alwaysLoad: true`: Claude Code keeps this server's tools in the prompt + // instead of deferring them behind tool search (its own MCP schema: + // "never deferred behind tool search … Equivalent to setting + // defer_loading: false on the API"). For our entry only. + entry: (t) => + t.kind === "http" + ? { type: "http", url: t.url, alwaysLoad: true } + : { type: "stdio", command: t.command, args: t.args, alwaysLoad: true }, }, codex: { agent: "codex", format: "toml", http: true, @@ -355,12 +449,22 @@ export const SELF_REPORT_MCP_TARGETS: Record = { }, copilot: { agent: "copilot", format: "json", http: true, - paths: () => [resolve(process.env.COPILOT_HOME?.trim() || resolve(homedir(), ".copilot"), "mcp-config.json")], + paths: () => [resolve(copilotHome(), "mcp-config.json")], container: () => ["mcpServers"], entry: (t) => t.kind === "http" ? { type: "http", url: t.url, tools: ["*"] } : { type: "local", command: t.command, args: t.args, tools: ["*"] }, + // Copilot passes a server's instructions to the model only for its + // built-in allowlist (`mcpRegistryServerInstructionAllowlist`: + // github-mcp-server, bluebird, computer-use in 1.0.83; no setting extends + // it, only the per-run `--allow-all-mcp-server-instructions` flag). It + // does load user instructions from `~/.copilot/instructions/*.instructions.md`, + // so the same text goes there, in a file of ours. + companion: { + path: () => resolve(copilotHome(), "instructions", "failproofai-self-reports.instructions.md"), + content: () => selfReportCompanionInstructions(), + }, }, cursor: { agent: "cursor", format: "json", http: true, @@ -394,13 +498,23 @@ export const SELF_REPORT_MCP_TARGETS: Record = { agent: "hermes", format: "yaml", http: true, paths: () => listHermesProfiles().map((p) => resolve(p.home, "config.yaml")), container: () => ["mcp_servers"], + // Hermes defers MCP (and plugin) tools behind its tool search with no + // per-server switch, so an MCP entry reached the model as a bare name. + // failproofai's Hermes plugin registers the tool natively and keeps it + // direct (hermes-plugin/self_report.py); this file only loses an entry an + // earlier version wrote. The shape is kept so that one is recognised. entry: (t) => plainEntry(t), + extension: true, }, openclaw: { agent: "openclaw", format: "json", http: true, paths: () => listOpenClawProfiles().map((p) => resolve(p.home, "openclaw.json")), container: () => ["mcp", "servers"], + // Same as Hermes: Tool Search defers MCP tools and has no per-server + // setting; failproofai's OpenClaw plugin registers a `catalogMode: + // "direct-only"` tool instead (openclaw-plugin/self-report.js). entry: (t) => (t.kind === "http" ? { url: t.url, transport: "streamable-http" } : { command: t.command, args: t.args }), + extension: true, }, factory: { agent: "factory", format: "json", http: true, @@ -422,7 +536,9 @@ export const SELF_REPORT_MCP_TARGETS: Record = { agent: "antigravity", format: "json", http: true, paths: () => [resolve(homedir(), ".gemini", "config", "mcp_config.json")], container: () => ["mcpServers"], - entry: (t) => plainEntry(t, "serverUrl"), + // `eager: true` (agy's per-server `force_all_tools_eager`): the tools are + // direct, not behind the lazy `call_mcp_tool` wrapper (agy 1.5.18). + entry: (t) => ({ ...plainEntry(t, "serverUrl"), eager: true }), }, goose: { agent: "goose", format: "yaml", http: true, @@ -673,6 +789,8 @@ export interface SyncSelfReportMcpOptions { hookRecords?: (agent: IntegrationType) => boolean; settings?: SelfReportMcpSettings; resolveCliPath?: () => string | null; + /** Agents allowed on HTTP (default `SELF_REPORT_HTTP_AGENTS`, none); tests of the HTTP path set it. */ + httpAgents?: readonly IntegrationType[]; }; } @@ -750,7 +868,8 @@ export async function syncSelfReportMcp(opts: SyncSelfReportMcpOptions = {}): Pr // it runs only when some agent will get an HTTP-capable entry. const also = opts.alsoHooked ?? []; const wanted = - enabled && agents.some((a) => selfReportHttpAllowed(a) && (also.includes(a) || hooked(a) || ownedRegistrationIn(a))); + enabled && + agents.some((a) => selfReportHttpAllowed(a, opts.deps?.httpAgents) && (also.includes(a) || hooked(a) || ownedRegistrationIn(a))); const daemonHere = wanted ? await (opts.deps?.daemonLive ?? selfReportDaemonLive)(settings.port) : false; const results = applySelfReportMcp({ ...opts, deps: { ...opts.deps, settings, hooksInstalled: hooked } }, enabled, daemonHere); logSelfReportSync(results); @@ -850,7 +969,7 @@ function applySelfReportMcp(opts: SyncSelfReportMcpOptions, enabled: boolean, da // HTTP only while the hook will record: an untrusted Codex, or a Claude // Code with hooks off, gets stdio, whose server records what the hook // did not. - if (daemonHere && selfReportHttpAllowed(agent) && hookRecords(agent)) { + if (daemonHere && selfReportHttpAllowed(agent, opts.deps?.httpAgents) && hookRecords(agent)) { chosen = { kind: "http", url: selfReportHttpUrl(settings.port, agent) }; } else { if (cliPath === undefined) cliPath = (opts.deps?.resolveCliPath ?? resolveSelfReportCliPath)(); @@ -918,6 +1037,18 @@ function applySelfReportMcp(opts: SyncSelfReportMcpOptions, enabled: boolean, da results.push({ agent, path, action: "skipped", transport: null, status: "error", detail: errText(err) }); } } + + if (target.companion) { + // Kept while our entry is registered somewhere for this agent. + const registered = results.some( + (r) => r.agent === agent && r.status === "ok" && r.transport !== null && r.action !== "removed", + ); + try { + syncCompanion(target.companion, enabled && registered); + } catch (err) { + results.push({ agent, path: target.companion.path(), action: "skipped", transport: null, status: "error", detail: errText(err) }); + } + } } if (!opts.quiet) for (const line of selfReportSyncLines(results)) console.log(line); diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts index 87ec7def6..b2058cf06 100644 --- a/src/hooks/self-report-mcp.ts +++ b/src/hooks/self-report-mcp.ts @@ -277,16 +277,17 @@ export async function writeSelfReportEvent(input: SelfReportEventInput): Promise /** * Whether this server records a report from `agent`: always for an agent in * `SELF_REPORT_SERVER_RECORDS`; for Claude Code and Codex, whose hook is the - * recorder, only when that hook did not already record this call — it was + * recorder, only when that hook did not already record this call (same + * working directory, and each hook row vouches for one call) — it was * not trusted (Codex), hooks are off (Claude Code), or none is installed where * the agent runs. The hook runs before the agent sends the MCP call, so its * row is already on disk (self-report-hook-trust.ts). */ -export async function selfReportServerShouldRecord(agent: string, args: unknown, now?: number): Promise { +export async function selfReportServerShouldRecord(agent: string, args: unknown, now?: number, cwd?: string): Promise { if (SELF_REPORT_SERVER_RECORDS.includes(agent)) return true; const { SELF_REPORT_HOOK_RECORDED_AGENTS, selfReportHookRecordedRecently } = await import("./self-report-hook-trust"); if (!SELF_REPORT_HOOK_RECORDED_AGENTS.includes(agent)) return false; - return !selfReportHookRecordedRecently(agent, args ?? {}, now ?? Date.now()); + return !selfReportHookRecordedRecently(agent, args ?? {}, now ?? Date.now(), cwd ?? process.cwd()); } /** @@ -443,7 +444,7 @@ export async function handleSelfReportRpc( log({ ...call, outcome: "skipped", reason: "no --agent" }); } else if (!settings) { log({ ...call, outcome: "skipped", reason: selfReportSettingsState() === "unreadable" ? "settings unreadable" : "Self Reports is off" }); - } else if (!(await selfReportServerShouldRecord(agent, params.arguments, opts.now?.()))) { + } else if (!(await selfReportServerShouldRecord(agent, params.arguments, opts.now?.(), opts.cwd ?? process.cwd()))) { log({ ...call, outcome: "skipped", reason: "its hook recorded it" }); } else { const knownCategory = settings.categories.some((c) => c.name === category); diff --git a/src/hooks/self-report-names.ts b/src/hooks/self-report-names.ts index a770086a2..bcdc744b8 100644 --- a/src/hooks/self-report-names.ts +++ b/src/hooks/self-report-names.ts @@ -60,7 +60,11 @@ export function selfReportClip(text: string, max: number = SELF_REPORT_DETAIL_MA * - `failproofai_local___report`: Factory's matcher-regex form of the same name. * - `mcp_failproofai_local_report`: Hermes, and Antigravity's eager tools. * - `failproofai_local_report`: OpenCode (`_`). - * - `failproofai_report`: the SDK tool. + * - NOT `failproofai_report`, the SDK tool's name: it is OpenCode's spelling + * of tool `report` on a server named `failproofai` (the Cloud gateway's + * usual name, or anything else), so matching it would let a foreign + * server's tool skip every policy. The SDKs recognise it themselves + * (`isSelfReportTool`); the hook path never early-allows it. * - `failproofai_local__report`: OpenClaw and Goose (`__`). * - Cursor: see `isSelfReportCursorCall`; its preToolUse name `MCP:report` * carries no server, so it is never matched by name alone. @@ -78,7 +82,6 @@ const SELF_REPORT_TOOL_SPELLINGS: ReadonlySet = new Set([ SELF_REPORT_MCP_TOOL_NAME, "failproofai_local___report", "failproofai_local__report", - SELF_REPORT_SDK_TOOL_NAME, "failproofai_local_report", "failproofai_local.report", "failproofai_local/report", diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts index 08b6b7a52..8ebc96c4f 100644 --- a/src/hooks/self-report.ts +++ b/src/hooks/self-report.ts @@ -21,7 +21,7 @@ */ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeSync } from "node:fs"; import { dirname, join } from "node:path"; -import { randomBytes } from "node:crypto"; +import { createHash, randomBytes } from "node:crypto"; import { configFile, credentialsFile, failproofaiHome } from "./fp-home"; export { @@ -272,6 +272,13 @@ export interface SelfReportEffective { guidance: string | null; mcp: { port: number; url: string }; updatedAt: string; + /** + * A `cloud` file's enrolment: `selfReportEnrolmentId` of the credential + * whose poll the daemon wrote it from. It decides only while this machine is + * enrolled as that credential (a file left by a previous org must not keep + * recording for the next one). + */ + enrolment?: string; } /** `$FAILPROOFAI_HOME/self-report.json`. */ @@ -327,17 +334,39 @@ export function readEffectiveSelfReport(path: string = selfReportSettingsFile()) guidance: guidance.ok ? guidance.value : null, mcp: { port, url: typeof mcp.url === "string" && mcp.url ? mcp.url : selfReportMcpUrl(port) }, updatedAt: typeof rec.updatedAt === "string" ? rec.updatedAt : "", + ...(typeof rec.enrolment === "string" && rec.enrolment ? { enrolment: rec.enrolment } : {}), }; } +/** + * Whether a settings file that parsed may decide anything (the daemon's + * `authoritative`): off Cloud, any file; on a Cloud-enrolled machine, only a + * `cloud` file written for the enrolment the machine is under right now. + * This machine's own file, a previous org's, one from a daemon that predates + * the binding, and any file while the credential cannot be read are set + * aside: off until this enrolment's setting is written. + */ +export function selfReportFileDecides( + file: SelfReportEffective, + enrolled: () => boolean = selfReportCloudEnrolled, + enrolmentId: () => string | null = selfReportEnrolmentId, +): boolean { + if (!enrolled()) return true; + if (file.source !== "cloud") return false; + const current = enrolmentId(); + return current !== null && file.enrolment === current; +} + /** * The settings every reader acts on (contract §4). Self Reports is ON by * default. Identical to the daemon's `effective_settings` * (crates/fpai-collect/src/self_report.rs): * - * - the file, when it is there and parses, except a local-source file on a - * Cloud-enrolled machine: `null`, off until the daemon writes the org's - * setting (enrolling must not leave this machine's own switch in charge); + * - the file, when it is there and parses, except, on a Cloud-enrolled + * machine, any file but a `cloud` one written for this enrolment + * (`selfReportFileDecides`): `null`, off until the daemon writes the org's + * setting (enrolling must not leave this machine's own switch, or a + * previous org's, in charge); * - an unparsable file, or one in another version: `null`, off (fail safe: a half-written or hand-broken * file must not turn recording on); * - a missing file on a Cloud-enrolled machine: `null`, off until the daemon @@ -348,6 +377,7 @@ export function readEffectiveSelfReport(path: string = selfReportSettingsFile()) export function resolveSelfReport( path: string = selfReportSettingsFile(), enrolled: () => boolean = selfReportCloudEnrolled, + enrolmentId: () => string | null = selfReportEnrolmentId, ): SelfReportEffective | null { const presence = selfReportFilePresence(path); // Present: the file decides, except that this machine's own (local) file @@ -356,7 +386,7 @@ export function resolveSelfReport( // a broken file: off. if (presence === "present") { const file = readEffectiveSelfReport(path); - if (file && file.source !== "cloud" && enrolled()) return null; + if (file && !selfReportFileDecides(file, enrolled, enrolmentId)) return null; return file; } if (presence === "unreadable") return null; @@ -419,6 +449,63 @@ export function selfReportCloudEnrolled(): boolean { } } +/** + * The id `self-report.json` is bound to on a Cloud-enrolled machine: the + * daemon's `enrolment_id` (crates/fpai-collect/src/self_report.rs) of the + * credential `Enrolment::resolve` finds, or null when there is none or it + * cannot be read. A SHA-256 over a fixed tag and the length-prefixed URL, + * machine id and token exactly as stored, first 16 bytes in hex. + */ +export function selfReportEnrolmentId(): string | null { + const env = (name: string) => process.env[name]?.trim() || undefined; + const envUrl = env("FAILPROOFAI_CLOUD_URL"); + if (envUrl) { + const token = env("FAILPROOFAI_CLOUD_TOKEN"); + const machineId = env("FAILPROOFAI_MACHINE_ID"); + return token && machineId ? selfReportEnrolmentIdOf(envUrl, machineId, token) : null; + } + if (selfReportOssMode()) return null; + const stored = (path: string): string | null => { + try { + const raw = JSON.parse(readFileSync(path, "utf8")) as Record; + if (raw?.schemaVersion !== 1) return null; + const { url, machineId, token } = raw; + if (typeof url !== "string" || typeof machineId !== "string" || typeof token !== "string" || !token) return null; + return selfReportEnrolmentIdOf(url, machineId, token); + } catch { + return null; + } + }; + const override = process.env.FAILPROOFAI_CLOUD_CREDENTIALS; + if (override) return stored(override); + const creds = credentialsFile(); + if (selfReportFilePresence(creds) === "missing") return stored(join(failproofaiHome(), "cloud.json")); + try { + const raw = JSON.parse(readFileSync(creds, "utf8")) as Record; + const cloud = raw?.cloud as Record | undefined; + if (!cloud || typeof cloud !== "object") return null; + const { url, machine_id: machineId, token } = cloud; + if (typeof url !== "string" || typeof machineId !== "string" || typeof token !== "string" || !token) return null; + return selfReportEnrolmentIdOf(url, machineId, token); + } catch { + return null; + } +} + +/** `enrolment_id` in crates/fpai-collect/src/self_report.rs. */ +export function selfReportEnrolmentIdOf(url: string, machineId: string, token: string): string { + const h = createHash("sha256"); + h.update("failproofai self-report enrolment v1"); + for (const part of [url, machineId, token]) { + const bytes = Buffer.from(part, "utf8"); + const len = Buffer.alloc(8); + len.writeBigUInt64BE(BigInt(bytes.length)); + h.update(len); + h.update(bytes); + } + return h.digest().subarray(0, 16).toString("hex"); +} + function selfReportFilePresence(path: string): "present" | "missing" | "unreadable" { try { readFileSync(path); @@ -448,13 +535,14 @@ export type SelfReportState = "on" | "off" | "waiting" | "unreadable"; export function selfReportSettingsState( path: string = selfReportSettingsFile(), enrolled: () => boolean = selfReportCloudEnrolled, + enrolmentId: () => string | null = selfReportEnrolmentId, ): SelfReportState { const presence = selfReportFilePresence(path); if (presence === "unreadable") return "unreadable"; if (presence === "present") { const file = readEffectiveSelfReport(path); if (!file) return "unreadable"; - if (file.source !== "cloud" && enrolled()) return "waiting"; + if (!selfReportFileDecides(file, enrolled, enrolmentId)) return "waiting"; return file.enabled ? "on" : "off"; } if (enrolled()) return "waiting"; diff --git a/test-fixtures/self-report/settings-cases.golden.json b/test-fixtures/self-report/settings-cases.golden.json index 00f219864..b2f989df7 100644 --- a/test-fixtures/self-report/settings-cases.golden.json +++ b/test-fixtures/self-report/settings-cases.golden.json @@ -1,5 +1,5 @@ { - "_comment": "Every Self Reports settings reader (the CLI's resolveSelfReport, the daemon's effective_settings and its HTTP settings cache) must reach the same on/off for each case. `file` null means no self-report.json; `text` is a raw file body.", + "_comment": "Every Self Reports settings reader (the CLI's resolveSelfReport, the daemon's effective_settings and its HTTP settings cache) must reach the same on/off for each case. `file` null means no self-report.json; `text` is a raw file body. `currentEnrolment` is the enrolment id the machine is enrolled as (absent while enrolled: the credential cannot be read); a cloud file decides only when its `enrolment` matches it.", "cases": [ { "name": "no file, not enrolled: on by default", @@ -11,7 +11,8 @@ "name": "no file, enrolled: off until the daemon writes the org setting", "file": null, "enrolled": true, - "on": false + "on": false, + "currentEnrolment": "enrolment-a" }, { "name": "local file on, not enrolled", @@ -55,7 +56,8 @@ "updatedAt": "2026-11-27T10:00:00Z" }, "enrolled": true, - "on": false + "on": false, + "currentEnrolment": "enrolment-a" }, { "name": "local file off, not enrolled", @@ -81,6 +83,54 @@ }, { "name": "cloud file on, enrolled", + "file": { + "version": 1, + "enabled": true, + "source": "cloud", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z", + "enrolment": "enrolment-a" + }, + "enrolled": true, + "on": true, + "currentEnrolment": "enrolment-a" + }, + { + "name": "cloud file on, enrolled as another org: off until this org's setting arrives", + "file": { + "version": 1, + "enabled": true, + "source": "cloud", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z", + "enrolment": "enrolment-a" + }, + "enrolled": true, + "on": false, + "currentEnrolment": "enrolment-b" + }, + { + "name": "cloud file on with no enrolment (an older daemon), enrolled: off until rewritten", "file": { "version": 1, "enabled": true, @@ -99,7 +149,31 @@ "updatedAt": "2026-11-27T10:00:00Z" }, "enrolled": true, - "on": true + "on": false, + "currentEnrolment": "enrolment-a" + }, + { + "name": "cloud file on, enrolled with an unreadable credential: off", + "file": { + "version": 1, + "enabled": true, + "source": "cloud", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z", + "enrolment": "enrolment-a" + }, + "enrolled": true, + "on": false }, { "name": "cloud file off, enrolled", @@ -118,10 +192,12 @@ "port": 4319, "url": "http://127.0.0.1:4319/mcp" }, - "updatedAt": "2026-11-27T10:00:00Z" + "updatedAt": "2026-11-27T10:00:00Z", + "enrolment": "enrolment-a" }, "enrolled": true, - "on": false + "on": false, + "currentEnrolment": "enrolment-a" }, { "name": "cloud file on, not enrolled (left from an org; the daemon removes it)", @@ -140,7 +216,8 @@ "port": 4319, "url": "http://127.0.0.1:4319/mcp" }, - "updatedAt": "2026-11-27T10:00:00Z" + "updatedAt": "2026-11-27T10:00:00Z", + "enrolment": "enrolment-a" }, "enrolled": false, "on": true @@ -184,10 +261,12 @@ "port": 4319, "url": "http://127.0.0.1:4319/mcp" }, - "updatedAt": "2026-11-27T10:00:00Z" + "updatedAt": "2026-11-27T10:00:00Z", + "enrolment": "enrolment-a" }, "enrolled": true, - "on": false + "on": false, + "currentEnrolment": "enrolment-a" }, { "name": "version 0: unsupported, off", @@ -217,5 +296,25 @@ "enrolled": false, "on": false } + ], + "enrolmentIds": [ + { + "url": "https://app.example.test", + "machineId": "machine-1", + "token": "tok-org-a", + "id": "6717885485f102770227c9e8b66bd52f" + }, + { + "url": "https://app.example.test", + "machineId": "machine-1", + "token": "tok-org-b", + "id": "fad1c08a1a8ea89c571d6f3f942c3400" + }, + { + "url": "http://localhost:3000/", + "machineId": "m-ü", + "token": "t", + "id": "9cf9e654c5587423dd7500f1786f16af" + } ] } From 9b84b247eca8008e7c1343613d60539df63cf72e Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Sun, 29 Nov 2026 22:49:58 +0530 Subject: [PATCH 25/54] [self-reports] Record a Devin report once: skip the Claude path when Devin runs Claude's hooks Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/self-report-devin.test.ts | 85 ++++++++++++++ __tests__/hooks/self-report-handler.test.ts | 14 +++ bin/failproofai.mjs | 6 +- src/hooks/handler.ts | 11 +- src/hooks/self-report-devin.ts | 119 ++++++++++++++++++++ 6 files changed, 233 insertions(+), 3 deletions(-) create mode 100644 __tests__/hooks/self-report-devin.test.ts create mode 100644 src/hooks/self-report-devin.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 023dc9d0f..083c8f38b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ ### Fixes +- Self Reports: a Devin report is recorded once, as devin. Devin also runs Claude Code's hooks, so the Claude path recorded the same call as claude; it now recognises a Devin call (a `devin` process above the hook, or Devin's payload shape) and leaves it to Devin's MCP server (#1062) - Self Reports: a Cloud settings file is bound to the enrolment whose poll wrote it. After switching to another org, the previous org's "on" no longer records until the new org's setting arrives: every reader (CLI, hook, stdio server, the daemon's HTTP server) treats a file from another enrolment, or from before this change, as missing, which is off while enrolled (#1062) - Self Reports: the SDK tool name `failproofai_report` is no longer let past the policies in the hook path. It is also OpenCode's name for a `report` tool on any MCP server called `failproofai`, so a foreign server's tool skipped every policy (#1062) - `block-failproofai-commands` no longer treats any `python -c` program as a read: its read-only vetting could be bypassed with dynamic builtin lookups. Nothing in a command is treated as inert when the same command defines a function or alias, or sets `PATH` (#1062) diff --git a/__tests__/hooks/self-report-devin.test.ts b/__tests__/hooks/self-report-devin.test.ts new file mode 100644 index 000000000..548c43a65 --- /dev/null +++ b/__tests__/hooks/self-report-devin.test.ts @@ -0,0 +1,85 @@ +// @vitest-environment node +import { describe, it, expect } from "vitest"; +import { + selfReportAncestryIsDevin, + selfReportClaudeHookFromDevin, + selfReportMarkDevinOrigin, + SELF_REPORT_DEVIN_MARKER, + selfReportParentProcessNames, +} from "../../src/hooks/self-report-devin"; + +const none = () => [] as string[]; + +describe("selfReportClaudeHookFromDevin", () => { + it("a Claude Code payload (transcript_path, toolu_ id) is Claude's", () => { + expect( + selfReportClaudeHookFromDevin({ transcript_path: "/h/.claude/projects/x/s.jsonl", tool_use_id: "toolu_01A" }, none), + ).toBe(false); + }); + + it("a payload with no id and no transcript is not taken for Devin's on its own", () => { + expect(selfReportClaudeHookFromDevin({ session_id: "s" }, none)).toBe(false); + }); + + it("Devin's call- id with no transcript_path is Devin's", () => { + expect( + selfReportClaudeHookFromDevin({ tool_use_id: "call-46ba525a-305d-4f99-8053-0cf0d1a1da73" }, none), + ).toBe(true); + }); + + it("a call- id alongside a transcript_path is not enough", () => { + expect( + selfReportClaudeHookFromDevin( + { transcript_path: "/t.jsonl", tool_use_id: "call-46ba525a-305d-4f99-8053-0cf0d1a1da73" }, + none, + ), + ).toBe(false); + }); + + it("tool_provenance (a Devin-only field) is Devin's", () => { + expect(selfReportClaudeHookFromDevin({ transcript_path: "/t.jsonl", tool_provenance: "mcp" }, none)).toBe(true); + }); + + it("a devin process above the hook is Devin's", () => { + expect(selfReportClaudeHookFromDevin({ transcript_path: "/t.jsonl", tool_use_id: "toolu_1" }, () => ["sh", "devin"])).toBe(true); + }); +}); + +describe("selfReportAncestryIsDevin", () => { + it("nearest agent wins: Claude Code started from a Devin shell is Claude", () => { + expect(selfReportAncestryIsDevin(["sh", "claude", "bash", "devin"])).toBe(false); + expect(selfReportAncestryIsDevin(["sh", "/usr/local/bin/devin", "zsh"])).toBe(true); + expect(selfReportAncestryIsDevin(["sh", "bash", "tmux"])).toBe(false); + expect(selfReportAncestryIsDevin([])).toBe(false); + }); +}); + +describe("selfReportParentProcessNames", () => { + it("reads this process's real ancestry without throwing", () => { + const names = selfReportParentProcessNames(3); + expect(Array.isArray(names)).toBe(true); + if (process.platform === "linux") expect(names.length).toBeGreaterThan(0); + }); +}); + +describe("selfReportMarkDevinOrigin (runs in the hook process, before the daemon)", () => { + const call = JSON.stringify({ tool_name: "mcp__failproofai_local__report", tool_input: {}, transcript_path: "/t.jsonl" }); + const devin = () => ["sh", "devin"]; + + it("marks a Claude-path report call made under Devin, and the worker then reads it as Devin's", () => { + const out = selfReportMarkDevinOrigin("claude", call, devin); + const parsed = JSON.parse(out) as Record; + expect(parsed[SELF_REPORT_DEVIN_MARKER]).toBe(true); + expect(selfReportClaudeHookFromDevin(parsed, none)).toBe(true); + }); + + it("leaves everything else byte-for-byte alone", () => { + expect(selfReportMarkDevinOrigin("claude", call, () => ["sh", "claude"])).toBe(call); + expect(selfReportMarkDevinOrigin("devin", call, devin)).toBe(call); + const bash = JSON.stringify({ tool_name: "Bash", tool_input: { command: "ls" } }); + expect(selfReportMarkDevinOrigin("claude", bash, devin)).toBe(bash); + const other = JSON.stringify({ tool_name: "Bash", tool_input: { command: "cat failproofai_local.txt" } }); + expect(selfReportMarkDevinOrigin("claude", other, devin)).toBe(other); + expect(selfReportMarkDevinOrigin("claude", "not json failproofai_local", devin)).toBe("not json failproofai_local"); + }); +}); diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index b73ce5bd3..2360724fa 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -256,6 +256,20 @@ describe("Self Reports short-circuit", () => { expect(row.selfReport).toBeUndefined(); }); + it("Devin running Claude Code's hooks: the claude row carries no report, so it is filed once, as devin", async () => { + const devinish = { tool_use_id: "call-46ba525a-305d-4f99-8053-0cf0d1a1da73" }; + const out = await evaluateHookEvent("PreToolUse", "claude", report(devinish)); + expect(out.evaluation?.decision).toBe("allow"); + const row = rows().pop()!; + expect(row.integration).toBe("claude"); + expect(row.selfReport).toBeUndefined(); + await evaluateHookEvent("PreToolUse", "claude", report({ tool_provenance: "mcp", transcript_path: "/t.jsonl" })); + expect(rows().pop()!.selfReport).toBeUndefined(); + // Claude Code's own call still records. + await evaluateHookEvent("PreToolUse", "claude", report({ tool_use_id: "toolu_9", transcript_path: "/t.jsonl" })); + expect(rows().pop()!.selfReport).toMatchObject({ category: "invalid_tool_or_credential" }); + }); + it("records an unknown category as-is, a missing detail as empty, and cuts detail at 2000", async () => { await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "made_up" })); expect(rows().pop()!.selfReport).toEqual({ category: "made_up", detail: "", source: "mcp" }); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index fd6f5aebf..db50e1834 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -179,10 +179,14 @@ if (hookIdx >= 0) { const { evaluateHookEvent } = await import("../src/hooks/handler"); const stdinRead = await readStdinPayload(); + // Devin runs Claude Code's hooks too. Whether Devin is the agent above + // this process can only be read here (the worker's parent is the daemon), + // so a Claude-path report call made under Devin is marked for the worker. + const { selfReportMarkDevinOrigin } = await import("../src/hooks/self-report-devin"); const attempt = await attemptDaemonHook({ hookEvent: eventType, cli, - stdin: stdinRead.payload, + stdin: selfReportMarkDevinOrigin(cli, stdinRead.payload), // The client's own cwd IS the originating CLI session's cwd — this // process is spawned fresh, at that location, by the calling agent // CLI's own hook mechanism. See daemon-client.ts / PROTOCOL.md. diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 29739248e..cda94dae2 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -65,6 +65,7 @@ import { SELF_REPORT_SERVER_RECORDS, } from "./self-report"; import { selfReportFailureHint, selfReportSessionStartContext } from "./self-report-hint"; +import { selfReportClaudeHookFromDevin } from "./self-report-devin"; import { deliveryHealth, deliveryHealthLine } from "./delivery-health"; import { trackHookEvent, flushHookTelemetry } from "./hook-telemetry"; import * as hookTelemetry from "./hook-telemetry"; @@ -696,7 +697,11 @@ function recordSelfReportCall( // `self_report` event per row that has it, and a call that also raises a // PermissionRequest (or completes with a PostToolUse) is still one report. const isReportRow = canonicalEventType === "PreToolUse"; - const hookRecords = isReportRow && !SELF_REPORT_SERVER_RECORDS.includes(cli) && readEnabledSelfReport() !== null; + // Devin runs Claude Code's hooks too: a `--cli claude` call that is really + // Devin's is left to Devin's MCP server, so the report is filed once, as devin. + const devinViaClaude = isReportRow && cli === "claude" && selfReportClaudeHookFromDevin(parsed); + const hookRecords = + isReportRow && !devinViaClaude && !SELF_REPORT_SERVER_RECORDS.includes(cli) && readEnabledSelfReport() !== null; try { persistHookActivity({ timestamp: writtenAt, @@ -720,7 +725,9 @@ function recordSelfReportCall( } catch { hookLogWarn("activity persistence failed"); } - hookLogInfo(`event=${canonicalEventType} cli=${cli} self-report allowed duration=${durationMs}ms`); + hookLogInfo( + `event=${canonicalEventType} cli=${cli} self-report allowed${devinViaClaude ? " (Devin via Claude hooks, left to Devin)" : ""} duration=${durationMs}ms`, + ); return { exitCode: 0, stdout: "", diff --git a/src/hooks/self-report-devin.ts b/src/hooks/self-report-devin.ts new file mode 100644 index 000000000..8591eaf16 --- /dev/null +++ b/src/hooks/self-report-devin.ts @@ -0,0 +1,119 @@ +/** + * Devin runs Claude Code's hooks as well as its own: it reads the `hooks` in + * `~/.claude/settings.json` too, so one Devin call to `report` reaches the + * hook twice, once as `--cli devin` and once as `--cli claude`. Devin's report + * is written by its MCP server (it is in `SELF_REPORT_SERVER_RECORDS`), while + * the Claude hook is the recorder for Claude Code, so without this check the + * one report is filed twice: as devin and as claude. + * + * `selfReportClaudeHookFromDevin` says whether a `--cli claude` invocation was + * really Devin's, so the Claude path can leave the report to Devin's server. + * Signals, any one of which is enough: + * + * - the nearest agent above this process is a `devin` process (Linux reads + * `/proc`, macOS asks `ps` once; Windows has no check). A `claude` process + * met first wins, so Claude Code started from a Devin shell still records. + * - the payload carries `tool_provenance`, a field of Devin's Claude-hook + * input that Claude Code never sends. + * - no `transcript_path` (Claude Code sends one on every event; Devin keeps + * sessions in SQLite and sends none) together with Devin's `call-` + * tool call id (Claude Code's ids are `toolu_…`). + * + * The process walk has to run in the hook process Devin started, not in the + * daemon's warm worker (whose parent is the daemon). So the one-shot hook CLI + * calls `selfReportMarkDevinOrigin` before it forwards the payload, which + * adds `SELF_REPORT_DEVIN_MARKER` to a Claude-path report call made under + * Devin; the worker then reads the marker. Only a report call on the Claude + * path is looked at, so ordinary hook traffic pays nothing. + */ +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { basename } from "node:path"; +import { isSelfReportToolName } from "./self-report-names"; + +/** Every spelling of the report tool's name carries the server name. */ +const SELF_REPORT_SERVER_NAME_FRAGMENT = /failproofai_local/i; + +/** Payload key the hook CLI adds when a Claude-path report call runs under Devin. */ +export const SELF_REPORT_DEVIN_MARKER = "failproofai_via_devin"; +const SELF_REPORT_DEVIN_CALL_ID_RE = /^call-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const SELF_REPORT_ANCESTRY_DEPTH = 8; + +/** Names of the processes above this one, nearest first. Best effort: `[]` on any failure. */ +export function selfReportParentProcessNames(depth: number = SELF_REPORT_ANCESTRY_DEPTH): string[] { + const names: string[] = []; + try { + if (process.platform === "linux") { + let pid = process.ppid; + for (let i = 0; i < depth && pid > 1; i++) { + // " () …"; comm may itself hold ") ". + const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); + const close = stat.lastIndexOf(")"); + names.push(stat.slice(stat.indexOf("(") + 1, close)); + pid = Number(stat.slice(close + 2).split(" ")[1]); + } + } else if (process.platform === "darwin") { + const out = execFileSync("ps", ["-A", "-o", "pid=,ppid=,comm="], { encoding: "utf8", timeout: 1000 }); + const table = new Map(); + for (const line of out.split("\n")) { + const m = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line); + if (m) table.set(Number(m[1]), { ppid: Number(m[2]), comm: m[3].trim() }); + } + let pid = process.ppid; + for (let i = 0; i < depth && pid > 1; i++) { + const row = table.get(pid); + if (!row) break; + names.push(basename(row.comm)); + pid = row.ppid; + } + } + } catch { + // Unreadable /proc, no ps: no ancestry signal. + } + return names; +} + +/** Whether the nearest agent process above this one is Devin (a `claude` met first says no). */ +export function selfReportAncestryIsDevin(names: readonly string[]): boolean { + for (const raw of names) { + const name = basename(raw).toLowerCase(); + if (name === "claude") return false; + if (name === "devin") return true; + } + return false; +} + +/** Whether a `--cli claude` hook payload was sent by Devin rather than Claude Code. */ +export function selfReportClaudeHookFromDevin( + parsed: Record, + ancestry: () => readonly string[] = selfReportParentProcessNames, +): boolean { + if (parsed[SELF_REPORT_DEVIN_MARKER] === true || "tool_provenance" in parsed) return true; + const id = parsed.tool_use_id ?? parsed.tool_call_id; + if (typeof parsed.transcript_path !== "string" && typeof id === "string" && SELF_REPORT_DEVIN_CALL_ID_RE.test(id)) { + return true; + } + return selfReportAncestryIsDevin(ancestry()); +} + +/** + * In the hook process: return `stdin` with `SELF_REPORT_DEVIN_MARKER` set when + * this is a `--cli claude` report call and Devin is the agent above us, else + * `stdin` unchanged. Never throws. + */ +export function selfReportMarkDevinOrigin( + cli: string, + stdin: string, + ancestry: () => readonly string[] = selfReportParentProcessNames, +): string { + if (cli !== "claude" || !SELF_REPORT_SERVER_NAME_FRAGMENT.test(stdin)) return stdin; + try { + const parsed = JSON.parse(stdin) as unknown; + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return stdin; + const rec = parsed as Record; + if (!isSelfReportToolName(rec.tool_name) || !selfReportAncestryIsDevin(ancestry())) return stdin; + return JSON.stringify({ ...rec, [SELF_REPORT_DEVIN_MARKER]: true }); + } catch { + return stdin; + } +} From b975b927e0004b4060bcef861c4bfce05c2562f0 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Sun, 29 Nov 2026 22:52:32 +0530 Subject: [PATCH 26/54] [self-reports] Lead instructions and description with how to call report (Codex code mode keeps ~250 chars) Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/self-report-hint.test.ts | 2 +- __tests__/hooks/self-report.test.ts | 2 +- crates/fpai-collect/src/self_report.rs | 21 +++++++++++-------- crates/fpai-collect/tests/self_report_mcp.rs | 4 +++- sdk/python/failproofai_sdk/_self_report.py | 6 ++++-- sdk/python/tests/test_self_report.py | 2 +- sdk/typescript/src/self-report-spec.ts | 5 +++-- sdk/typescript/test/self-report.test.ts | 2 +- src/hooks/self-report-hint.ts | 8 ++----- src/hooks/self-report.ts | 19 ++++++++++------- .../description-guidance.golden.txt | 2 +- .../self-report/description.golden.txt | 2 +- .../instructions-guidance.golden.txt | 2 +- .../self-report/instructions.golden.txt | 2 +- 15 files changed, 45 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 083c8f38b..4f5233207 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ ### Fixes +- Self Reports: the server instructions and the tool description now open with what to do (when stuck, call the `report` tool with `category` and a one-sentence `detail`). Codex 0.172's code mode keeps only about 250 characters of each, so the old opening never got as far as how to call it (#1062) - Self Reports: a Devin report is recorded once, as devin. Devin also runs Claude Code's hooks, so the Claude path recorded the same call as claude; it now recognises a Devin call (a `devin` process above the hook, or Devin's payload shape) and leaves it to Devin's MCP server (#1062) - Self Reports: a Cloud settings file is bound to the enrolment whose poll wrote it. After switching to another org, the previous org's "on" no longer records until the new org's setting arrives: every reader (CLI, hook, stdio server, the daemon's HTTP server) treats a file from another enrolment, or from before this change, as missing, which is off while enrolled (#1062) - Self Reports: the SDK tool name `failproofai_report` is no longer let past the policies in the hook path. It is also OpenCode's name for a `report` tool on any MCP server called `failproofai`, so a foreign server's tool skipped every policy (#1062) diff --git a/__tests__/hooks/self-report-hint.test.ts b/__tests__/hooks/self-report-hint.test.ts index 1de50a350..bf74eeb0d 100644 --- a/__tests__/hooks/self-report-hint.test.ts +++ b/__tests__/hooks/self-report-hint.test.ts @@ -193,7 +193,7 @@ describe("SessionStart instructions where MCP tools are deferred with no switch" const out = await evaluateHookEvent("SessionStart", "factory", JSON.stringify({ session_id: sid(), cwd: "/tmp/project" })); const ctx = JSON.parse(out.stdout).hookSpecificOutput; expect(ctx.hookEventName).toBe("SessionStart"); - expect(ctx.additionalContext).toContain("call the `failproofai_local` MCP server's `report` tool once"); + expect(ctx.additionalContext).toContain("When you are stuck, call failproofai_local's `report` tool once"); expect(ctx.additionalContext).not.toContain("this server's"); writeEffectiveSelfReport({ enabled: false }); expect((await evaluateHookEvent("SessionStart", "factory", JSON.stringify({ session_id: sid(), cwd: "/tmp/project" }))).stdout).toBe(""); diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index 2478575d8..6f471ef62 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -39,7 +39,7 @@ import { runSelfReportCommand } from "../../src/hooks/self-report-cli"; const BINARY = resolve(__dirname, "..", "..", "bin", "failproofai.mjs"); -const EXPECTED_DESCRIPTION = `Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. +const EXPECTED_DESCRIPTION = `When you are stuck on something you cannot fix yourself, call this tool once with \`category\` (one of the categories below) and \`detail\` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. Categories: diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index ea4a724dd..8727b3662 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -93,7 +93,7 @@ pub const SERVER_RECORDS: &[&str] = &[ /// a client asking for one it does not know. const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05", "2025-11-25"]; -const DESCRIPTION_HEAD: &str = "Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem.\nReporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user."; +const DESCRIPTION_HEAD: &str = "When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem.\nReporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user."; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Category { @@ -474,16 +474,17 @@ pub fn input_schema(categories: &[Category]) -> Value { /// The MCP server's `instructions` (identical text in the TypeScript stdio /// server, `selfReportInstructions`). Claude Code defers MCP tools behind tool /// search, so the model never reads the tool description up front; a server's -/// instructions go into the system prompt. +/// instructions go into the system prompt. The first sentence alone says what +/// to do: Codex's code mode keeps only about 250 characters of it. pub fn instructions(categories: &[Category], guidance: Option<&str>) -> String { let names: Vec<&str> = categories.iter().map(|c| c.name.as_str()).collect(); let mut text = format!( - "FailproofAI records when an agent is blocked. Before your final answer, if something \ - failed that you cannot fix yourself (a missing or expired token or key, a 401 or 403, a \ - command or tool that keeps failing, information you cannot get, a request you cannot \ - do), call this server's `report` tool once with `category` (one of: {}) and `detail` \ - (one factual sentence). Not when the task succeeded. It does not unblock you, and there \ - is no need to mention it to the user.", + "When you are stuck, call failproofai_local's `report` tool once with `category` and \ + `detail` (one factual sentence: what is blocking you). Stuck means something you cannot \ + fix yourself: a missing or expired token or key, a 401 or 403, a command or tool that \ + keeps failing, information you cannot get, a request you cannot do. `category` is one \ + of: {}. Call it before your final answer, not when the task succeeded. It does not \ + unblock you, and there is no need to mention it to the user.", names.join(", ") ); if let Some(g) = guidance.filter(|g| !g.is_empty()) { @@ -1520,7 +1521,9 @@ mod tests { describe(&cats, Some("Be brief.")), format!("{want}\n\nBe brief.") ); - assert!(DESCRIPTION_HEAD.starts_with("Report to FailproofAI that you are blocked.")); + assert!(DESCRIPTION_HEAD.starts_with( + "When you are stuck on something you cannot fix yourself, call this tool once" + )); assert!(DESCRIPTION_HEAD.ends_with("There is no need to mention this report to the user.")); } diff --git a/crates/fpai-collect/tests/self_report_mcp.rs b/crates/fpai-collect/tests/self_report_mcp.rs index ccdda7b30..0fa7f34ea 100644 --- a/crates/fpai-collect/tests/self_report_mcp.rs +++ b/crates/fpai-collect/tests/self_report_mcp.rs @@ -306,7 +306,9 @@ async fn the_tool_list_follows_the_settings_file() { ); let text = instructions(server.rpc("", init.clone()).await.1).unwrap(); assert!( - text.as_str().unwrap().contains("(one of: org_custom)"), + text.as_str() + .unwrap() + .contains("`category` is one of: org_custom."), "{text}" ); assert!( diff --git a/sdk/python/failproofai_sdk/_self_report.py b/sdk/python/failproofai_sdk/_self_report.py index a7ed5ac98..920840862 100644 --- a/sdk/python/failproofai_sdk/_self_report.py +++ b/sdk/python/failproofai_sdk/_self_report.py @@ -72,8 +72,10 @@ ) _PREAMBLE = ( - "Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever " - "something stops you that you cannot fix yourself, for example a missing, invalid or " + "When you are stuck on something you cannot fix yourself, call this tool once with " + "`category` (one of the categories below) and `detail` (one factual sentence: what is " + "blocking you). It reports to FailproofAI. Call it BEFORE your final answer, for example " + "for a missing, invalid or " "expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, " "information or access you cannot get, or a request you cannot do here. Do not call it for " "normal work, clarifying questions or an error you then fixed. One call per distinct " diff --git a/sdk/python/tests/test_self_report.py b/sdk/python/tests/test_self_report.py index 8c543bdde..abd560d94 100644 --- a/sdk/python/tests/test_self_report.py +++ b/sdk/python/tests/test_self_report.py @@ -12,7 +12,7 @@ from failproofai_sdk import _runtime, _self_report from failproofai_sdk._events import EventNamespace -EXPECTED_DEFAULT_DESCRIPTION = """Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. +EXPECTED_DEFAULT_DESCRIPTION = """When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. Categories: diff --git a/sdk/typescript/src/self-report-spec.ts b/sdk/typescript/src/self-report-spec.ts index 7994c4475..c68e86e55 100644 --- a/sdk/typescript/src/self-report-spec.ts +++ b/sdk/typescript/src/self-report-spec.ts @@ -68,8 +68,9 @@ export const MAX_CATEGORY_DESCRIPTION = 500; export const MAX_GUIDANCE = 2000; const PREAMBLE = - "Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you " + - "cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP " + + "When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories " + + "below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your " + + "final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP " + "server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for " + "normal work, clarifying questions or an error you then fixed. One call per distinct problem.\n" + "Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what " + diff --git a/sdk/typescript/test/self-report.test.ts b/sdk/typescript/test/self-report.test.ts index 512377d20..c2cae9bc5 100644 --- a/sdk/typescript/test/self-report.test.ts +++ b/sdk/typescript/test/self-report.test.ts @@ -71,7 +71,7 @@ const quietLogger = () => { }; const DEFAULT_DESCRIPTION = [ - "Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem.", + "When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem.", "Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user.", "", "Categories:", diff --git a/src/hooks/self-report-hint.ts b/src/hooks/self-report-hint.ts index 025012aa9..82cf400db 100644 --- a/src/hooks/self-report-hint.ts +++ b/src/hooks/self-report-hint.ts @@ -212,12 +212,8 @@ export function selfReportSessionStartContext( stdout: JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", - // The handshake text says "this server's"; here it arrives outside the - // server, so name it. - additionalContext: selfReportInstructions(s.categories, s.guidance).replace( - "this server's `report` tool", - `the \`${SELF_REPORT_SERVER_NAME}\` MCP server's \`report\` tool`, - ), + // The instructions name the server themselves, so they read the same here. + additionalContext: selfReportInstructions(s.categories, s.guidance), }, }), stderr: "", diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts index 8ebc96c4f..791022eb0 100644 --- a/src/hooks/self-report.ts +++ b/src/hooks/self-report.ts @@ -130,8 +130,9 @@ export function validateSelfReportGuidance(input: unknown): SelfReportValidation // ── The tool (contract §3) ────────────────────────────────────────────────── const SELF_REPORT_DESCRIPTION_HEAD = - "Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you " + - "cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP " + + "When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories " + + "below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your " + + "final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP " + "server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for " + "normal work, clarifying questions or an error you then fixed. One call per distinct problem.\n" + "Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is " + @@ -170,6 +171,10 @@ export { describeSelfReportTool, describeSelfReportTool as describe, selfReportI * tool's description until it already decided to look for one; a server's * instructions go into the system prompt. One short paragraph naming the * categories, then the org's guidance when set. + * + * The first sentence says on its own what to do and how: Codex's code mode + * lists MCP servers as namespaces and keeps only about the first 250 + * characters of a server's instructions and of a tool's description. */ function selfReportInstructions( categories: readonly SelfReportCategory[], @@ -177,11 +182,11 @@ function selfReportInstructions( ): string { const names = categories.map((c) => c.name).join(", "); const body = - "FailproofAI records when an agent is blocked. Before your final answer, if something failed that you cannot fix " + - "yourself (a missing or expired token or key, a 401 or 403, a command or tool that keeps failing, information you " + - "cannot get, a request you cannot do), call this server's `report` tool once with `category` (one of: " + - `${names}) and \`detail\` (one factual sentence). Not when the task succeeded. It does not unblock you, and ` + - "there is no need to mention it to the user."; + "When you are stuck, call failproofai_local's `report` tool once with `category` and `detail` (one factual " + + "sentence: what is blocking you). Stuck means something you cannot fix yourself: a missing or expired token or " + + "key, a 401 or 403, a command or tool that keeps failing, information you cannot get, a request you cannot do. " + + `\`category\` is one of: ${names}. Call it before your final answer, not when the task succeeded. It does not ` + + "unblock you, and there is no need to mention it to the user."; return guidance ? `${body}\n\n${guidance}` : body; } diff --git a/test-fixtures/self-report/description-guidance.golden.txt b/test-fixtures/self-report/description-guidance.golden.txt index 9cd2c646e..2307af471 100644 --- a/test-fixtures/self-report/description-guidance.golden.txt +++ b/test-fixtures/self-report/description-guidance.golden.txt @@ -1,4 +1,4 @@ -Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. +When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. Categories: diff --git a/test-fixtures/self-report/description.golden.txt b/test-fixtures/self-report/description.golden.txt index 24a3bf298..7f257fe10 100644 --- a/test-fixtures/self-report/description.golden.txt +++ b/test-fixtures/self-report/description.golden.txt @@ -1,4 +1,4 @@ -Report to FailproofAI that you are blocked. Call this BEFORE your final answer whenever something stops you that you cannot fix yourself, for example a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. +When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. Categories: diff --git a/test-fixtures/self-report/instructions-guidance.golden.txt b/test-fixtures/self-report/instructions-guidance.golden.txt index c175a9bc9..050030c2f 100644 --- a/test-fixtures/self-report/instructions-guidance.golden.txt +++ b/test-fixtures/self-report/instructions-guidance.golden.txt @@ -1,3 +1,3 @@ -FailproofAI records when an agent is blocked. Before your final answer, if something failed that you cannot fix yourself (a missing or expired token or key, a 401 or 403, a command or tool that keeps failing, information you cannot get, a request you cannot do), call this server's `report` tool once with `category` (one of: looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure) and `detail` (one factual sentence). Not when the task succeeded. It does not unblock you, and there is no need to mention it to the user. +When you are stuck, call failproofai_local's `report` tool once with `category` and `detail` (one factual sentence: what is blocking you). Stuck means something you cannot fix yourself: a missing or expired token or key, a 401 or 403, a command or tool that keeps failing, information you cannot get, a request you cannot do. `category` is one of: looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure. Call it before your final answer, not when the task succeeded. It does not unblock you, and there is no need to mention it to the user. Report a missing repository as missing_context. \ No newline at end of file diff --git a/test-fixtures/self-report/instructions.golden.txt b/test-fixtures/self-report/instructions.golden.txt index 2863734e8..fda449a8f 100644 --- a/test-fixtures/self-report/instructions.golden.txt +++ b/test-fixtures/self-report/instructions.golden.txt @@ -1 +1 @@ -FailproofAI records when an agent is blocked. Before your final answer, if something failed that you cannot fix yourself (a missing or expired token or key, a 401 or 403, a command or tool that keeps failing, information you cannot get, a request you cannot do), call this server's `report` tool once with `category` (one of: looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure) and `detail` (one factual sentence). Not when the task succeeded. It does not unblock you, and there is no need to mention it to the user. \ No newline at end of file +When you are stuck, call failproofai_local's `report` tool once with `category` and `detail` (one factual sentence: what is blocking you). Stuck means something you cannot fix yourself: a missing or expired token or key, a 401 or 403, a command or tool that keeps failing, information you cannot get, a request you cannot do. `category` is one of: looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure. Call it before your final answer, not when the task succeeded. It does not unblock you, and there is no need to mention it to the user. \ No newline at end of file From 43073a26801f802ed033e7e023fff0b392ce664d Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Sun, 29 Nov 2026 22:57:32 +0530 Subject: [PATCH 27/54] [self-reports] Upgrade removes legacy Hermes/OpenClaw MCP entries before gateway restarts Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/update-run.test.ts | 33 ++++++++++++++++++++++++++++-- src/hooks/setup-finish.ts | 12 ++++++----- src/hooks/update-run.ts | 13 ++++++++++++ 4 files changed, 52 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f5233207..d62fbf67a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ ### Fixes +- Self Reports: upgrading takes the `failproofai_local` MCP entry an earlier version wrote out of Hermes' `config.yaml` and OpenClaw's `openclaw.json` (their tool now comes from the plugin) before their gateways restart, so a restarted OpenClaw no longer starts the stdio server for it. Setup also syncs Self Reports before it restarts gateways, for the same reason (#1062) - Self Reports: the server instructions and the tool description now open with what to do (when stuck, call the `report` tool with `category` and a one-sentence `detail`). Codex 0.172's code mode keeps only about 250 characters of each, so the old opening never got as far as how to call it (#1062) - Self Reports: a Devin report is recorded once, as devin. Devin also runs Claude Code's hooks, so the Claude path recorded the same call as claude; it now recognises a Devin call (a `devin` process above the hook, or Devin's payload shape) and leaves it to Devin's MCP server (#1062) - Self Reports: a Cloud settings file is bound to the enrolment whose poll wrote it. After switching to another org, the previous org's "on" no longer records until the new org's setting arrives: every reader (CLI, hook, stdio server, the daemon's HTTP server) treats a file from another enrolment, or from before this change, as missing, which is off while enrolled (#1062) diff --git a/__tests__/hooks/update-run.test.ts b/__tests__/hooks/update-run.test.ts index 66b8c2fc4..2077be1f1 100644 --- a/__tests__/hooks/update-run.test.ts +++ b/__tests__/hooks/update-run.test.ts @@ -4,9 +4,9 @@ * instead of leaving that to a `failproofai update` nobody knew to run. */ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; const svc = vi.hoisted(() => ({ isDaemonSupportedPlatform: vi.fn(() => true), @@ -124,6 +124,35 @@ describe("runUpdateSteps as config runs it (no layout, no daemon, restart)", () const run = await runUpdateSteps(AS_CONFIG); expect(run).toMatchObject({ ok: true, changed: false, lines: [] }); }); + + // An upgrade from a version that registered the MCP server in Hermes and + // OpenClaw: those entries come out before any gateway restarts, so no + // restarted gateway loads them again. The user's own servers stay. + it("takes out Hermes' and OpenClaw's old Self Reports MCP entries before restarting their gateways", async () => { + const hermesCfg = join(home, ".hermes", "config.yaml"); + const openclawCfg = join(home, ".openclaw", "openclaw.json"); + mkdirSync(dirname(hermesCfg), { recursive: true }); + mkdirSync(dirname(openclawCfg), { recursive: true }); + const cli = "/usr/local/bin/failproofai"; + writeFileSync(hermesCfg, `model: x\nmcp_servers:\n failproofai_local:\n url: http://127.0.0.1:4319/mcp?agent=hermes\n mine:\n command: node\n`); + writeFileSync( + openclawCfg, + JSON.stringify({ mcp: { servers: { failproofai_local: { command: cli, args: ["mcp", "--agent", "openclaw"] }, mine: { command: "node" } } } }), + ); + const seenAtRestart: string[] = []; + hermes.runHermesUpdateMigration.mockImplementation(async (deps: { restartGateway?: (p: unknown) => unknown }) => { + seenAtRestart.push(readFileSync(hermesCfg, "utf8"), readFileSync(openclawCfg, "utf8")); + deps.restartGateway?.({ name: "default", home: join(home, ".hermes") }); + return { ok: true, lines: [], profiles: [{ name: "default", status: "current" }] }; + }); + await runUpdateSteps(AS_CONFIG); + expect(gateways.restartHermesGateway).toHaveBeenCalledTimes(1); + expect(seenAtRestart.join("\n")).not.toContain("failproofai_local"); + expect(readFileSync(hermesCfg, "utf8")).toContain("mine:"); + expect((JSON.parse(readFileSync(openclawCfg, "utf8")) as { mcp: { servers: Record } }).mcp.servers).toEqual({ + mine: { command: "node" }, + }); + }); }); describe("runUpdateSteps as update runs it", () => { diff --git a/src/hooks/setup-finish.ts b/src/hooks/setup-finish.ts index 6ad35c690..4371f9337 100644 --- a/src/hooks/setup-finish.ts +++ b/src/hooks/setup-finish.ts @@ -32,6 +32,13 @@ export async function finishSetup(opts: FinishSetupOptions): Promise { let exit = 0; const progress = progressLine(out, "Finishing setup…"); try { + // Self Reports (on by default): write self-report.json when it is missing + // off Cloud, then sync every hooked agent, also when setup found the + // machine already configured and wrote no hooks. Best-effort. Ahead of the + // gateway restarts, so a Hermes or OpenClaw gateway restarts without the + // MCP entry an earlier version wrote (their tool comes from the plugin). + progress.set("Updating Self Reports…"); + const summary = await selfReportSetupSummary(); if (!setupNeedsUpdateSteps(opts.version)) { // Already updated on this version: only a profile this run plugged in // (one created since) has a gateway still running without the plugin. @@ -46,11 +53,6 @@ export async function finishSetup(opts: FinishSetupOptions): Promise { if (run.ok) markUpdated(opts.version); else exit = 1; } - // Self Reports (on by default): write self-report.json when it is missing - // off Cloud, then sync every hooked agent, also when setup found the - // machine already configured and wrote no hooks. Best-effort. - progress.set("Updating Self Reports…"); - const summary = await selfReportSetupSummary(); if (summary) keep.push(summary.ok ? kit.ok(summary.text) : kit.caution(summary.text, summary.fix)); } finally { progress.done(keep); diff --git a/src/hooks/update-run.ts b/src/hooks/update-run.ts index 320ca6135..bf7648500 100644 --- a/src/hooks/update-run.ts +++ b/src/hooks/update-run.ts @@ -140,6 +140,19 @@ export async function runUpdateSteps(opts: UpdateStepsOptions): Promise Date: Sun, 29 Nov 2026 23:01:16 +0530 Subject: [PATCH 28/54] [self-reports] Cut log previews on character boundaries, ASCII ellipsis Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/self-report-log.test.ts | 14 ++++++++ crates/fpai-collect/src/self_report.rs | 45 ++++++++++++++++++++++--- src/hooks/self-report-cli.ts | 3 +- src/hooks/self-report-log.ts | 3 +- 5 files changed, 60 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d62fbf67a..f8af29386 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ ### Fixes +- Self Reports: the daemon log's report preview is cut on a character boundary and marked with an ASCII `...`, so no multi-byte character is split (seen as `enviro�`); the stdio server and the CLI cut the preview and the guidance line by code point, never through a surrogate pair (#1062) - Self Reports: upgrading takes the `failproofai_local` MCP entry an earlier version wrote out of Hermes' `config.yaml` and OpenClaw's `openclaw.json` (their tool now comes from the plugin) before their gateways restart, so a restarted OpenClaw no longer starts the stdio server for it. Setup also syncs Self Reports before it restarts gateways, for the same reason (#1062) - Self Reports: the server instructions and the tool description now open with what to do (when stuck, call the `report` tool with `category` and a one-sentence `detail`). Codex 0.172's code mode keeps only about 250 characters of each, so the old opening never got as far as how to call it (#1062) - Self Reports: a Devin report is recorded once, as devin. Devin also runs Claude Code's hooks, so the Claude path recorded the same call as claude; it now recognises a Devin call (a `devin` process above the hook, or Devin's payload shape) and leaves it to Devin's MCP server (#1062) diff --git a/__tests__/hooks/self-report-log.test.ts b/__tests__/hooks/self-report-log.test.ts index f07e57068..cef12d1e6 100644 --- a/__tests__/hooks/self-report-log.test.ts +++ b/__tests__/hooks/self-report-log.test.ts @@ -125,6 +125,20 @@ describe("selfReportLog over the daemon socket", () => { } }); + it("cuts the preview on a character boundary, never through a surrogate pair", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + // 199 ASCII then emoji: the 200th code point is whole, nothing after it. + await sendSelfReportLog({ event: "tools/call", transport: "stdio", preview: `${"a".repeat(199)}😀😀 environment` }); + await vi.waitFor(() => expect(frames).toHaveLength(1)); + const preview = (frames[0].event as Record).preview; + expect(preview).toBe(`${"a".repeat(199)}😀`); + expect(preview).not.toContain("�"); + } finally { + server.close(); + } + }); + it("never waits on a daemon: none, a dead socket, or one that never reads", async () => { // None. let t = Date.now(); diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index 8727b3662..d9da417b5 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -1031,6 +1031,10 @@ pub struct McpLog<'a> { /// first [`LOG_PREVIEW_CHARS`] characters. Machine logs can leave the machine /// and scrub only the home directory and the machine key, so this is the /// whole of what protects the detail. +/// +/// Cut on a character boundary, never inside a UTF-8 sequence, and marked +/// with an ASCII `...`: a three-byte `…` at the very end was the one place a +/// reader that caps the line by bytes split a character (`enviro\u{FFFD}`). pub fn log_preview(detail: &str) -> String { let scrubbed = crate::redact::scrub_str(detail).map_or_else(|| detail.to_string(), |(s, _)| s); let flat: String = scrubbed @@ -1039,8 +1043,8 @@ pub fn log_preview(detail: &str) -> String { .collect(); let flat = flat.trim(); let cut = truncate_chars(flat, LOG_PREVIEW_CHARS); - if cut.chars().count() < flat.chars().count() { - format!("{cut}…") + if cut.len() < flat.len() { + format!("{}...", cut.trim_end()) } else { cut } @@ -1419,12 +1423,45 @@ mod tests { assert!(!preview.contains("abcdefghij"), "{preview}"); assert!(preview.starts_with("auth failed: "), "{preview}"); assert!( - preview.chars().count() <= LOG_PREVIEW_CHARS + 1, + preview.chars().count() <= LOG_PREVIEW_CHARS + 3, "{preview}" ); assert!(!preview.contains('\n')); assert_eq!(log_preview("short"), "short"); - assert_eq!(log_preview(&"é".repeat(50)), format!("{}…", "é".repeat(40))); + assert_eq!( + log_preview(&"é".repeat(50)), + format!("{}...", "é".repeat(40)) + ); + } + + #[test] + fn a_log_preview_never_splits_a_character() { + // A multi-byte character at, just before and just after the cut. + let cases = [ + "deploy.sh requires a DEPLOY_TOKEN environment variable that is not set".to_string(), + format!("{}é and more", "a".repeat(LOG_PREVIEW_CHARS - 1)), + format!("{}😀😀 more", "a".repeat(LOG_PREVIEW_CHARS - 1)), + format!("{}中文字 more", "a".repeat(LOG_PREVIEW_CHARS - 2)), + "😀".repeat(LOG_PREVIEW_CHARS + 5), + "e\u{301}".repeat(LOG_PREVIEW_CHARS), + ]; + for detail in &cases { + let preview = log_preview(detail); + assert!(!preview.contains('\u{FFFD}'), "{preview}"); + assert!(preview.is_ascii() || std::str::from_utf8(preview.as_bytes()).is_ok()); + let body = preview.strip_suffix("...").unwrap_or(&preview); + assert!( + detail.starts_with(body), + "{preview} is not a prefix of {detail}" + ); + assert!(body.chars().count() <= LOG_PREVIEW_CHARS, "{preview}"); + } + assert_eq!( + log_preview(&cases[0]), + "deploy.sh requires a DEPLOY_TOKEN enviro..." + ); + // The marker is ASCII, so the line's last bytes are whole characters. + assert!(log_preview(&cases[2]).ends_with("...")); } #[test] diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts index 1cc8e6045..312331b37 100644 --- a/src/hooks/self-report-cli.ts +++ b/src/hooks/self-report-cli.ts @@ -22,6 +22,7 @@ import { readEffectiveSelfReport, readLocalSelfReportConfig, resolveSelfReport, + selfReportClip, selfReportCloudEnrolled, selfReportFileDecides, selfReportCloudManaged, @@ -441,7 +442,7 @@ async function selfReportStatus(args: string[], deps: SelfReportCliDeps): Promis if (settings.updatedAt) lines.push(`Updated: ${settings.updatedAt}`); lines.push(`Categories: ${settings.categories.map((c) => c.name).join(", ")}`); lines.push(`MCP server: ${SELF_REPORT_SERVER_NAME} (tool \`${SELF_REPORT_TOOL_NAME}\`)`); - if (settings.guidance) lines.push(`Guidance: ${settings.guidance.length > 60 ? `${settings.guidance.slice(0, 57)}...` : settings.guidance}`); + if (settings.guidance) lines.push(`Guidance: ${[...settings.guidance].length > 60 ? `${selfReportClip(settings.guidance, 57)}...` : settings.guidance}`); lines.push(...repairedLines); lines.push(selfReportDaemonLine(settings.mcp.url, daemonAnswering, deps)); lines.push(...selfReportRegistrationLines(rows, health, owned, recorders)); diff --git a/src/hooks/self-report-log.ts b/src/hooks/self-report-log.ts index 83da6dd41..0a172b6b1 100644 --- a/src/hooks/self-report-log.ts +++ b/src/hooks/self-report-log.ts @@ -18,6 +18,7 @@ import { existsSync } from "node:fs"; import { createConnection } from "node:net"; import { daemonSocket } from "./fp-home"; +import { selfReportClip } from "./self-report-names"; /** The whole budget for one event, connect to close. */ export const SELF_REPORT_LOG_BUDGET_MS = 250; @@ -85,7 +86,7 @@ function selfReportLogSend(event: SelfReportLogEvent): Promise { protocolVersion: SELF_REPORT_LOG_PROTOCOL_VERSION, event: { ...event, - ...(event.preview !== undefined ? { preview: [...event.preview].slice(0, SELF_REPORT_LOG_PREVIEW_CHARS).join("") } : {}), + ...(event.preview !== undefined ? { preview: selfReportClip(event.preview, SELF_REPORT_LOG_PREVIEW_CHARS) } : {}), }, }), "utf8", From a7fc467cb077f419ba30e80f98e718364126cbbe Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Sun, 29 Nov 2026 23:03:42 +0530 Subject: [PATCH 29/54] [self-reports] Failure hint only for clearly-blocking failures (auth, or a repeat), never exploration Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/self-report-hint.test.ts | 54 +++++++- src/hooks/self-report-hint.ts | 155 ++++++++++++++++++++++- 3 files changed, 203 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f8af29386..c442585ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ - Self Reports: the `report` tool is a direct tool on Hermes and OpenClaw, which defer MCP tools behind their tool search with no per-server switch (so the model saw only a name and never reported). failproofai's Hermes plugin registers it natively and puts it on Hermes' never-deferred list, and the OpenClaw plugin registers a `catalogMode: "direct-only"` tool; both put the server's instructions in the prompt (`pre_llm_call`, `before_prompt_build`) and hand each call to failproofaid's own Self Reports server, so the text, attribution, dedup and logs are the MCP path's. Sync writes no Hermes or OpenClaw MCP entry and removes the old ones (#1062) - Self Reports: Claude Code's entry sets `alwaysLoad: true` (its tools are never deferred behind tool search), Antigravity's sets `eager: true` (direct tools rather than `call_mcp_tool`), Copilot gets the instructions in a marked `~/.copilot/instructions/failproofai-self-reports.instructions.md` (Copilot shows server instructions only for its built-in allowlist), and Factory droid, which defers every other MCP server, gets them as SessionStart context (#1062) -- Self Reports: after a tool call that clearly failed (a non-zero exit, a 401 or 403, `not found`, `permission denied`, an MCP `isError`, a tool error), one line of context once per session suggests calling `report` if the agent cannot fix it, on Claude Code, Codex, Cursor, Copilot (its failure event) and Factory. Never on success, on the report call, after a failproofai deny, or while Self Reports is off; it is not a policy and never replaces one's answer (#1062) +- Self Reports: after a tool call failure that clearly blocks (an auth or credential error such as a 401 or 403, an invalid or expired key or token, or a `*_TOKEN` that is not set; or the same tool or command failing a second time in the session), one line of context once per session suggests calling `report` if the agent cannot fix it. One non-zero exit, and read-only exploration (`ls`, `cat`, `grep`, `find`, `test`, Read, Glob) failing, never earn it. On Claude Code, Codex, Cursor, Copilot (its failure event) and Factory. Never on success, on the report call, after a failproofai deny, or while Self Reports is off; it is not a policy and never replaces one's answer (#1062) ### Fixes diff --git a/__tests__/hooks/self-report-hint.test.ts b/__tests__/hooks/self-report-hint.test.ts index bf74eeb0d..f249d4605 100644 --- a/__tests__/hooks/self-report-hint.test.ts +++ b/__tests__/hooks/self-report-hint.test.ts @@ -177,17 +177,65 @@ describe("the failure hint through the hook", () => { }); describe("selfReportFailureHint", () => { + const AUTH = { error: "HTTP 401 Unauthorized: invalid API key" }; it("needs a session id to keep its once-per-session promise", () => { - expect(selfReportFailureHint({ cli: "claude", eventType: "PostToolUseFailure", payload: {}, sessionId: undefined, enabled: () => true })).toBeNull(); - expect(selfReportFailureHint({ cli: "claude", eventType: "PostToolUseFailure", payload: {}, sessionId: "s-direct", enabled: () => true })).not.toBeNull(); + expect(selfReportFailureHint({ cli: "claude", eventType: "PostToolUseFailure", payload: AUTH, sessionId: undefined, enabled: () => true })).toBeNull(); + expect(selfReportFailureHint({ cli: "claude", eventType: "PostToolUseFailure", payload: AUTH, sessionId: "s-direct", enabled: () => true })).not.toBeNull(); }); it("answers Copilot only on its failure event, in its flat shape", () => { expect(SELF_REPORT_HINT_CHANNELS.copilot).toEqual({ PostToolUseFailure: "flat" }); - const out = selfReportFailureHint({ cli: "copilot", eventType: "PostToolUseFailure", payload: {}, sessionId: "s-cop", enabled: () => true }); + const out = selfReportFailureHint({ cli: "copilot", eventType: "PostToolUseFailure", payload: AUTH, sessionId: "s-cop", enabled: () => true }); expect(JSON.parse(out!.stdout)).toEqual({ additionalContext: SELF_REPORT_FAILURE_HINT }); }); }); +describe("only a failure that clearly blocks earns the hint", () => { + const call = (command: string, response: unknown, extra: Record = {}) => + ({ tool_name: "Bash", tool_input: { command }, tool_response: response, ...extra }) as Record; + const hint = (sessionId: string, payload: Record, eventType = "PostToolUse") => + selfReportFailureHint({ cli: "claude", eventType, payload, sessionId, enabled: () => true }); + const exit1 = (stderr: string) => ({ stdout: "", stderr, exit_code: 1 }); + + it("not for one non-zero exit of read-only exploration, however often", () => { + for (const command of ["ls missing.txt", "cat /nope", "grep -r TODO src", "find . -name x", "test -f a.txt", "ls a && cat b", "bash -lc 'ls -la /x'", "git status"]) { + expect(hint("s-explore", call(command, exit1("ls: cannot access 'missing.txt': No such file or directory"))), command).toBeNull(); + expect(hint("s-explore", call(command, exit1("No such file or directory"))), command).toBeNull(); + } + expect(hint("s-explore", { tool_name: "Read", tool_input: { file_path: "/x" }, error: "File does not exist." }, "PostToolUseFailure")).toBeNull(); + expect(hint("s-explore", { tool_name: "Read", tool_input: { file_path: "/x" }, error: "File does not exist." }, "PostToolUseFailure")).toBeNull(); + }); + + it("not for the first failure of anything else", () => { + expect(hint("s-first", call("npm test", exit1("1 test failed")))).toBeNull(); + expect(hint("s-first", call("./deploy.sh", exit1("deploy failed")))).toBeNull(); + }); + + it("for the same command failing a second time", () => { + expect(hint("s-repeat", call("./deploy.sh", exit1("deploy failed")))).toBeNull(); + expect(hint("s-repeat", call("npm run build", exit1("tsc error")))).toBeNull(); + expect(hint("s-repeat", call("./deploy.sh --force", exit1("deploy failed again")))!.stdout).toContain(SELF_REPORT_FAILURE_HINT); + }); + + it("for the same tool failing a second time", () => { + const mcp = { tool_name: "mcp__tracker__create_issue", tool_input: { title: "x" }, tool_response: { isError: true, content: [{ type: "text", text: "boom" }] } }; + expect(hint("s-tool", mcp)).toBeNull(); + expect(hint("s-tool", { ...mcp, tool_input: { title: "y" } })!.stdout).toContain(SELF_REPORT_FAILURE_HINT); + }); + + it("at once for an auth or credential failure, even from a read-only command", () => { + expect(hint("s-auth-1", call("curl -f https://api.example.test", exit1("curl: (22) The requested URL returned error: 403")))).not.toBeNull(); + expect(hint("s-auth-2", call("./deploy.sh", exit1("deploy.sh: DEPLOY_TOKEN is not set")))).not.toBeNull(); + expect(hint("s-auth-3", call("gh pr list", exit1("error: authentication failed")))).not.toBeNull(); + expect(hint("s-auth-4", call("cat out.json", { stdout: '{"error":"invalid api key"}', stderr: "", exit_code: 1 }))).not.toBeNull(); + expect(hint("s-auth-5", { tool_name: "mcp__tracker__list", tool_input: {}, tool_response: { isError: true, content: [{ type: "text", text: "Token expired" }] } })).not.toBeNull(); + }); + + it("still once per session", () => { + expect(hint("s-once", call("./deploy.sh", exit1("401 Unauthorized")))).not.toBeNull(); + expect(hint("s-once", call("./deploy.sh", exit1("401 Unauthorized")))).toBeNull(); + }); +}); + describe("SessionStart instructions where MCP tools are deferred with no switch", () => { it("gives Factory droid the server's instructions at session start, only while on", async () => { const out = await evaluateHookEvent("SessionStart", "factory", JSON.stringify({ session_id: sid(), cwd: "/tmp/project" })); diff --git a/src/hooks/self-report-hint.ts b/src/hooks/self-report-hint.ts index 82cf400db..25f9f6326 100644 --- a/src/hooks/self-report-hint.ts +++ b/src/hooks/self-report-hint.ts @@ -13,6 +13,13 @@ * while Self Reports is on, never for the report call itself, and never for a * failure a failproofai deny caused: those are already recorded as blocks. * + * Only a failure that clearly blocks (`selfReportFailureBlocks`) earns it: an + * auth or credential error (a 401 or 403, unauthorized, an invalid or expired + * key or token, a `*_TOKEN` that is not set), or the same tool or command + * failing a second time in the session. One non-zero exit is ordinary work, and + * read-only exploration (`ls`, `cat`, `grep`, `find`, `test`, Read, Glob...) + * failing, however often, is how an agent finds out what is there. + * * Where a hint can reach the model (`SELF_REPORT_HINT_CHANNELS`): * * | Agent | Event | Channel | @@ -28,7 +35,7 @@ * PostToolUse answer never reached the transcript in probes, and Antigravity * and Goose discard it (src/hooks/enforcement-capability.ts). */ -import { closeSync, mkdirSync, openSync } from "node:fs"; +import { closeSync, mkdirSync, openSync, readFileSync, writeFileSync } from "node:fs"; import { createHash } from "node:crypto"; import { join } from "node:path"; import { failproofaiHome } from "./fp-home"; @@ -112,6 +119,146 @@ export function selfReportToolFailed(eventType: string, payload: Record): string { + const parts: string[] = [textOf(payload.error)]; + const response = payload.tool_response ?? payload.tool_output ?? payload.toolResult ?? payload.tool_result ?? payload.result; + if (response && typeof response === "object" && !Array.isArray(response)) { + const r = response as Record; + parts.push(textOf(r.error), textOf(r.stderr)); + for (const k of ["output", "content", "text", "message", "result", "stdout"]) { + const t = textOf(r[k]); + if (t.length <= SHORT_RESULT) parts.push(t); + } + } else { + const t = textOf(response); + if (t.length <= SHORT_RESULT) parts.push(t); + } + return parts.filter((p) => p !== "").join("\n"); +} + +const AUTH_TEXT: RegExp[] = [ + /\b(?:HTTP\/\d(?:\.\d)?\s+|status(?:\s*code)?[:=\s]+|error[:\s]+)40[13]\b/i, + /\b40[13]\s+(?:unauthori[sz]ed|forbidden)\b/i, + /\bunauthori[sz]ed\b|\bforbidden\b|\bunauthenticated\b/i, + /\bauthentication (?:failed|required|error)\b|\bnot authenticated\b|\bnot logged in\b|\blogin required\b/i, + /\b(?:invalid|expired|revoked|missing|bad|incorrect)\s+(?:api[\s_-]?key|access[\s_-]?key|token|credentials?|password|secret)\b/i, + /\b(?:api[\s_-]?key|token|credentials?)\s+(?:is\s+)?(?:invalid|expired|revoked|missing|required|not (?:set|found|provided|valid))\b/i, + /\b[A-Z][A-Z0-9_]*(?:TOKEN|API_KEY|_KEY|SECRET|PASSWORD|CREDENTIALS?)\b[^\n]{0,40}\b(?:not set|unset|missing|required|is empty|undefined)\b/, +]; + +/** An auth or credential failure: the agent cannot fix it by trying again. */ +function authFailure(payload: Record): boolean { + const text = errorTextOf(payload); + return text !== "" && AUTH_TEXT.some((re) => re.test(text)); +} + +/** Tools that only look: a failure of one is finding out, not being blocked. */ +const SELF_REPORT_READ_ONLY_TOOLS = new Set([ + "read", "glob", "grep", "ls", "notebookread", "view", "read_file", "list_dir", "list_directory", "search_files", + "find_files", "file_search", "codebase_search", "tree", +]); +/** Programs that only look, as the first word of a shell command segment. */ +const SELF_REPORT_READ_ONLY_PROGRAMS = new Set([ + "ls", "cat", "head", "tail", "less", "more", "grep", "egrep", "fgrep", "rg", "ag", "find", "fd", "test", "[", "[[", + "stat", "file", "which", "whereis", "type", "command", "wc", "tree", "pwd", "echo", "printf", "readlink", "realpath", + "du", "df", "env", "printenv", "id", "whoami", "uname", "date", "true", "false", "jq", "sort", "uniq", "cut", "diff", + "basename", "dirname", +]); +const SELF_REPORT_READ_ONLY_GIT = new Set(["status", "log", "diff", "show", "branch", "ls-files", "rev-parse", "remote", "blame", "grep"]); + +function commandOf(payload: Record): string { + const input = payload.tool_input; + if (!input || typeof input !== "object" || Array.isArray(input)) return ""; + const rec = input as Record; + const c = rec.command ?? rec.cmd; + if (typeof c === "string") return c.trim(); + if (Array.isArray(c)) return c.filter((x) => typeof x === "string").join(" ").trim(); + return ""; +} + +/** The program each segment of a shell command runs (env assignments, `sudo`, `bash -lc` skipped). */ +function programsOf(command: string): string[] { + let cmd = command; + // `bash -lc '...'` / `sh -c "..."`: look at the inner command (Codex wraps this way). + const wrapped = /^(?:\S*\/)?(?:ba|z|da)?sh\s+-l?c\s+(['"])([\s\S]*)\1\s*$/.exec(cmd); + if (wrapped) cmd = wrapped[2]; + return cmd + .split(/&&|\|\||[;|\n]/) + .map((seg) => seg.trim().split(/\s+/).filter((w) => w !== "")) + .filter((words) => words.length > 0) + .map((words) => { + let i = 0; + while (i < words.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]) || words[i] === "sudo" || words[i] === "time" || words[i] === "!")) i++; + const prog = (words[i] ?? "").replace(/^.*\//, ""); + return prog === "git" ? `git ${words[i + 1] ?? ""}` : prog; + }); +} + +/** A call that only looks: a read-only tool, or a shell command whose every segment only looks. */ +export function selfReportReadOnlyCall(payload: Record): boolean { + const tool = typeof payload.tool_name === "string" ? payload.tool_name.toLowerCase() : ""; + if (SELF_REPORT_READ_ONLY_TOOLS.has(tool)) return true; + const command = commandOf(payload); + if (command === "") return false; + const programs = programsOf(command); + return ( + programs.length > 0 && + programs.every((p) => (p.startsWith("git ") ? SELF_REPORT_READ_ONLY_GIT.has(p.slice(4)) : SELF_REPORT_READ_ONLY_PROGRAMS.has(p))) + ); +} + +/** What "the same tool or command" means: the tool, and for a shell call the programs it ran. */ +function failureKey(payload: Record): string { + const tool = typeof payload.tool_name === "string" ? payload.tool_name : ""; + const command = commandOf(payload); + const programs = command === "" ? [] : programsOf(command); + return programs.length > 0 ? `${tool}\0${programs.join(" ")}` : tool; +} + +function hintDir(): string { + return join(failproofaiHome(), "cache", "self-report-hints"); +} + +function sessionDigest(cli: string, sessionId: string): string { + return createHash("sha256").update(`${cli}\0${sessionId}`).digest("hex").slice(0, 32); +} + +/** + * Note this failure for the session; true when the same tool or command had + * already failed in it (the second failure). Best effort: an unreadable file + * counts nothing. + */ +function failedBefore(cli: string, sessionId: string, key: string): boolean { + const file = join(hintDir(), `${sessionDigest(cli, sessionId)}.failures`); + const digest = createHash("sha256").update(key).digest("hex").slice(0, 16); + let seen: string[] = []; + try { + seen = readFileSync(file, "utf8").split("\n").filter((l) => l !== ""); + } catch { + seen = []; + } + if (seen.includes(digest)) return true; + try { + mkdirSync(hintDir(), { recursive: true, mode: 0o700 }); + writeFileSync(file, `${[...seen.slice(-49), digest].join("\n")}\n`, { mode: 0o600 }); + } catch { + // no record: the next failure counts as a first one again + } + return false; +} + +/** + * Whether a failed call clearly blocks the agent: an auth or credential error, + * or (for anything but read-only exploration) the same tool or command failing + * a second time this session. Records the failure for that count. + */ +export function selfReportFailureBlocks(cli: string, sessionId: string, payload: Record): boolean { + if (authFailure(payload)) return true; + if (selfReportReadOnlyCall(payload)) return false; + return failedBefore(cli, sessionId, failureKey(payload)); +} + /** The call's text mentions a failproofai block (a deny's own message). */ function blockedByFailproofai(payload: Record): boolean { const t = textOf(payload.tool_response ?? payload.error ?? payload.tool_output ?? payload.toolResult ?? ""); @@ -132,11 +279,10 @@ function deniedEarlier(sessionId: string, toolCallId: string | undefined, now: n /** Claim the per-session marker: true only for the first claim of this session. */ function claimOnce(cli: string, sessionId: string): boolean { - const dir = join(failproofaiHome(), "cache", "self-report-hints"); - const id = createHash("sha256").update(`${cli}\0${sessionId}`).digest("hex").slice(0, 32); + const dir = hintDir(); try { mkdirSync(dir, { recursive: true, mode: 0o700 }); - closeSync(openSync(join(dir, id), "wx", 0o600)); + closeSync(openSync(join(dir, sessionDigest(cli, sessionId)), "wx", 0o600)); return true; } catch { return false; @@ -171,6 +317,7 @@ export function selfReportFailureHint(input: SelfReportHintInput): { exitCode: n const now = input.now ?? Date.now(); if (deniedEarlier(input.sessionId, input.toolCallId, now)) return null; if (!(input.enabled ?? (() => readEnabledSelfReport() !== null))()) return null; + if (!selfReportFailureBlocks(input.cli, input.sessionId, payload)) return null; if (!claimOnce(input.cli, input.sessionId)) return null; switch (channel) { case "hookSpecificOutput": From 65d01ab54be38af930163edb230074f09638c4ca Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Sun, 29 Nov 2026 23:06:48 +0530 Subject: [PATCH 30/54] [self-reports] Quiet update/config output: routine gateway and Self Reports lines move to status --verbose Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/self-report-log.test.ts | 3 +- __tests__/hooks/self-report.test.ts | 17 +++++++ __tests__/hooks/update-run.test.ts | 21 +++++++-- src/hooks/manager.ts | 7 +-- src/hooks/self-report-cli.ts | 10 ++++ src/hooks/setup-finish.ts | 8 ++-- src/hooks/update-run.ts | 61 +++++++++++++++++++++---- 8 files changed, 109 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c442585ec..e27ea67c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ ### Fixes +- Quieter `update`, `config` and `policies --install`/`--uninstall`: no `Hermes: hermes/default already current, gateway restarting` or `OpenClaw: openclaw/default gateway restarting` rows and no `Self Reports: on for N agents` line when all went well. Only what needs the user is printed (a gateway to restart by hand, a Hermes failure, an agent the Self Reports sync could not update); `self-report status --verbose` shows the last update's gateway rows (#1062) - Self Reports: the daemon log's report preview is cut on a character boundary and marked with an ASCII `...`, so no multi-byte character is split (seen as `enviro�`); the stdio server and the CLI cut the preview and the guidance line by code point, never through a surrogate pair (#1062) - Self Reports: upgrading takes the `failproofai_local` MCP entry an earlier version wrote out of Hermes' `config.yaml` and OpenClaw's `openclaw.json` (their tool now comes from the plugin) before their gateways restart, so a restarted OpenClaw no longer starts the stdio server for it. Setup also syncs Self Reports before it restarts gateways, for the same reason (#1062) - Self Reports: the server instructions and the tool description now open with what to do (when stuck, call the `report` tool with `category` and a one-sentence `detail`). Codex 0.172's code mode keeps only about 250 characters of each, so the old opening never got as far as how to call it (#1062) diff --git a/__tests__/hooks/self-report-log.test.ts b/__tests__/hooks/self-report-log.test.ts index cef12d1e6..82ad5e0c6 100644 --- a/__tests__/hooks/self-report-log.test.ts +++ b/__tests__/hooks/self-report-log.test.ts @@ -273,8 +273,9 @@ describe("setup's finish step", () => { expect(out.trimEnd().split("\n")).toEqual([ "✕ Hermes: plugin could not be updated", "▲ hermes/work: restart the gateway", - "✓ Self Reports: on for 12 agents", ]); + // A sync that worked says nothing; `self-report status` does. + expect(out).not.toContain("Self Reports"); expect(out).not.toContain("gateway restarting"); expect(out).not.toContain("MCP server"); } finally { diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index 6f471ef62..162332479 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -744,6 +744,23 @@ describe("failproofai self-report enable | disable | status", () => { expect(lines.filter((l) => l.includes("cursor-agent mcp enable"))).toHaveLength(1); }); + it("status --verbose shows what the last update did to the gateways; plain status does not", async () => { + writeEffectiveSelfReport({ enabled: true }); + const deps = { + skipSync: true, + probeEndpoint: async () => false, + daemonExpected: () => false, + registrations: () => [], + gatewayReport: () => ({ at: "2026-11-29T16:25:41.000Z", rows: ["hermes/default already current, gateway restarting", "openclaw/default gateway restarting"] }), + }; + const verbose = (await runSelfReportCommand(["status", "--verbose"], deps)).lines.join("\n"); + expect(verbose).toContain("Gateways: at the last update (2026-11-29T16:25:41.000Z)"); + expect(verbose).toContain(" hermes/default already current, gateway restarting"); + expect(verbose).toContain(" openclaw/default gateway restarting"); + expect((await runSelfReportCommand(["status"], deps)).lines.join("\n")).not.toContain("gateway restarting"); + expect((await runSelfReportCommand(["status", "--verbose"], { ...deps, gatewayReport: () => null })).lines.join("\n")).not.toContain("Gateways:"); + }); + it("status says the daemon is not running, not \"not answering\", when there is no daemon", async () => { writeEffectiveSelfReport({ enabled: true }); const status = (expected: boolean) => diff --git a/__tests__/hooks/update-run.test.ts b/__tests__/hooks/update-run.test.ts index 2077be1f1..9e727f63d 100644 --- a/__tests__/hooks/update-run.test.ts +++ b/__tests__/hooks/update-run.test.ts @@ -42,6 +42,7 @@ vi.mock("../../src/hooks/codex-system-hooks", async (importOriginal) => ({ import { markUpdated, + readGatewayReport, readUpdatedVersion, restartNewlyPlugged, runUpdateSteps, @@ -95,7 +96,7 @@ describe("the version marker", () => { describe("runUpdateSteps as config runs it (no layout, no daemon, restart)", () => { const AS_CONFIG = { layout: false, daemon: false, restart: true } as const; - it("restarts running gateways onto the plugin on disk, and says so", async () => { + it("restarts running gateways onto the plugin on disk, printing nothing routine but keeping it for status", async () => { hermesWith("current"); gateways.restartOpenClawGateways.mockReturnValue([{ host: "openclaw", profile: "default", status: "restarting" }]); const run = await runUpdateSteps(AS_CONFIG); @@ -103,12 +104,26 @@ describe("runUpdateSteps as config runs it (no layout, no daemon, restart)", () expect(run.changed).toBe(true); expect(gateways.restartHermesGateway).toHaveBeenCalledTimes(1); expect(gateways.restartOpenClawGateways).toHaveBeenCalledTimes(1); - expect(run.lines).toContain(" hermes/default already current, gateway restarting"); - expect(run.lines).toContain(" openclaw/default gateway restarting"); + expect(run.lines.join("\n")).not.toMatch(/Hermes|OpenClaw|gateway restarting|already current/); + expect(readGatewayReport()?.rows).toEqual(["hermes/default already current, gateway restarting", "openclaw/default gateway restarting"]); // Setup already brought the daemon to this version. expect(svc.refreshDaemonToCliVersion).not.toHaveBeenCalled(); }); + it("still prints a gateway the user has to restart by hand", async () => { + hermesWith("current"); + gateways.restartHermesGateway.mockReturnValueOnce({ host: "hermes", profile: "default", status: "not-supervised" }); + gateways.restartOpenClawGateways.mockReturnValue([ + { host: "openclaw", profile: "default", status: "restarting" }, + { host: "openclaw", profile: "work", status: "failed" }, + ]); + const run = await runUpdateSteps(AS_CONFIG); + const text = run.lines.join("\n"); + expect(text).toContain("Hermes:"); + expect(text).toContain("OpenClaw:"); + expect(gateways.openclawRestartLines).toHaveBeenCalledWith([{ host: "openclaw", profile: "work", status: "failed" }]); + }); + it("touches no gateway when the daemon is not running", async () => { hermesWith("current"); svc.daemonServiceStatus.mockReturnValue("stopped"); diff --git a/src/hooks/manager.ts b/src/hooks/manager.ts index 38ed396bf..db4959406 100644 --- a/src/hooks/manager.ts +++ b/src/hooks/manager.ts @@ -1029,9 +1029,10 @@ async function installHooksImpl( alsoHooked: writtenSettingsPaths.map((written) => written.cli), binaryPath, }); - // One line; the per-agent changes are `self-report sync`'s and `status`'s. + // Nothing when it worked: `self-report status` and `sync` show where each + // agent stands. Only an agent that could not be updated gets a line. const summary = selfReportSummary(results, selfReportSettingsState()); - if (summary) console.log(summary.ok ? kit.ok(summary.text) : kit.caution(summary.text, summary.fix)); + if (summary && !summary.ok) console.log(kit.caution(summary.text, summary.fix)); } catch { // never block the install } @@ -1248,7 +1249,7 @@ export async function removeHooks(policyNames?: string[], scope: HookScope | "al try { const summary = selfReportSummary(removeSelfReportMcp({ agents: selectedClis, quiet: true }), "removed"); const kit = screenKit(optsFor(process.stdout)); - if (summary) say(summary.ok ? kit.ok(summary.text) : kit.caution(summary.text, summary.fix)); + if (summary && !summary.ok) say(kit.caution(summary.text, summary.fix)); } catch { // never block the removal } diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts index 312331b37..00ee8682d 100644 --- a/src/hooks/self-report-cli.ts +++ b/src/hooks/self-report-cli.ts @@ -81,6 +81,8 @@ export interface SelfReportCliDeps { hookState?: (agent: string) => SelfReportHookState; /** Skip the agent sync after enable/disable (tests). */ skipSync?: boolean; + /** The last update's routine gateway rows (tests; default `readGatewayReport`). */ + gatewayReport?: () => { at: string; rows: string[] } | null; cwd?: string; } @@ -446,6 +448,14 @@ async function selfReportStatus(args: string[], deps: SelfReportCliDeps): Promis lines.push(...repairedLines); lines.push(selfReportDaemonLine(settings.mcp.url, daemonAnswering, deps)); lines.push(...selfReportRegistrationLines(rows, health, owned, recorders)); + // What the last update did to Hermes and OpenClaw gateways: `update` and + // `config` print only a gateway the user must restart, so the routine rows + // are shown here. + const gateways = (deps.gatewayReport ?? (await import("./update-run")).readGatewayReport)(); + if (gateways) { + lines.push(`Gateways: at the last update (${gateways.at})`); + lines.push(...gateways.rows.map((row) => ` ${row}`)); + } return { exitCode: 0, lines }; } diff --git a/src/hooks/setup-finish.ts b/src/hooks/setup-finish.ts index 4371f9337..77745d581 100644 --- a/src/hooks/setup-finish.ts +++ b/src/hooks/setup-finish.ts @@ -4,8 +4,8 @@ * plugin, or none) and bring every hooked agent's Self Reports MCP entry in * line with `self-report.json`. * - * All of it runs behind one spinner line and leaves at most the Self Reports - * line behind, plus a line for anything that needs the user: a gateway they + * All of it runs behind one spinner line and leaves only a line for anything + * that needs the user: a gateway they * must restart themselves, a Hermes failure, an agent the sync could not * update. A gateway that is restarting by itself, and the per-agent MCP * changes, are not the user's to act on, so they are not printed (`self-report @@ -53,7 +53,9 @@ export async function finishSetup(opts: FinishSetupOptions): Promise { if (run.ok) markUpdated(opts.version); else exit = 1; } - if (summary) keep.push(summary.ok ? kit.ok(summary.text) : kit.caution(summary.text, summary.fix)); + // Nothing about Self Reports when it worked (`self-report status` says + // where it stands); only an agent the sync could not update needs the user. + if (summary && !summary.ok) keep.push(kit.caution(summary.text, summary.fix)); } finally { progress.done(keep); } diff --git a/src/hooks/update-run.ts b/src/hooks/update-run.ts index bf7648500..57d0a9b83 100644 --- a/src/hooks/update-run.ts +++ b/src/hooks/update-run.ts @@ -11,7 +11,7 @@ * already migrated the home, so `config` skips those two. */ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; -import { dirname } from "node:path"; +import { dirname, resolve } from "node:path"; import { updatedVersionFile } from "./fp-home"; import type { GatewayRestart } from "./gateway-restart"; @@ -156,6 +156,8 @@ export async function runUpdateSteps(opts: UpdateStepsOptions): Promise p.status === "migrated").length; if (hermesResult.lines.length > 0) { // Its lines open on a "Hermes:" heading over one row per profile; on a // failure the heading carries the ✕ and the rows say which profile. + // Printed only when something needs the user (a failure, a migration + // with its advice, a gateway to restart by hand). "already current, + // gateway restarting" is routine: it is kept for `self-report status + // --verbose` instead. const [heading, ...rest] = hermesResult.lines; - lines.push("", hermesResult.ok ? heading : `✕ ${heading}`, ...rest); + const needsUser = !hermesResult.ok || hermesMigrated > 0 || restarts.some(needsManualRestart); + if (needsUser) lines.push("", hermesResult.ok ? heading : `✕ ${heading}`, ...rest); + else gatewayRows.push(...rest); } - hermesOk = hermesResult.ok; - hermesMigrated = hermesResult.profiles.filter((p) => p.status === "migrated").length; // "already current" with no gateway touched is not news. changed = changed || !hermesOk || hermesMigrated > 0 || mentionsGateway(hermesResult.lines); @@ -190,16 +198,19 @@ export async function runUpdateSteps(opts: UpdateStepsOptions): Promise 0) { - lines.push("", ...restartLines); - changed = true; - } + // Only a gateway the user has to restart is printed; the rest is kept + // for `self-report status --verbose`. + const restartLines = restart.openclawRestartLines(openclaw.filter(needsManualRestart)); + if (restartLines.length > 0) lines.push("", ...restartLines); + gatewayRows.push(...restart.openclawRestartLines(openclaw).slice(1)); + if (openclaw.some((r) => r.status === "restarting" || needsManualRestart(r))) changed = true; } catch { // Restarting is a convenience; the update itself already succeeded. } } + if (gatewayRows.length > 0) writeGatewayReport(gatewayRows.map((l) => l.trim().replace(/\s{2,}/g, " "))); + return { lines, ok: daemonOk && !migrationFailed && hermesOk && codexOk, @@ -278,6 +289,38 @@ export async function restartNewlyPlugged( return fresh.map((p) => (p.host === "hermes" ? hermes(p) : openclaw(p))); } +function needsManualRestart(r: GatewayRestart): boolean { + return r.status === "not-supervised" || r.status === "failed"; +} + +/** Where the last update's routine gateway rows are kept. */ +export function gatewayReportFile(home?: string): string { + return resolve(dirname(updatedVersionFile(home)), "gateway-report.json"); +} + +/** Keep the last update's routine gateway rows (`hermes/default already current, gateway restarting`). Best effort. */ +export function writeGatewayReport(rows: string[], home?: string, now = new Date()): void { + try { + const file = gatewayReportFile(home); + if (!existsSync(dirname(file))) mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); + writeFileSync(file, `${JSON.stringify({ at: now.toISOString(), rows })}\n`, { mode: 0o600 }); + } catch { + // only `self-report status --verbose` reads it + } +} + +/** The last update's routine gateway rows, or null. */ +export function readGatewayReport(home?: string): { at: string; rows: string[] } | null { + try { + const parsed = JSON.parse(readFileSync(gatewayReportFile(home), "utf8")) as { at?: unknown; rows?: unknown }; + if (typeof parsed.at !== "string" || !Array.isArray(parsed.rows)) return null; + const rows = parsed.rows.filter((r): r is string => typeof r === "string"); + return rows.length > 0 ? { at: parsed.at, rows } : null; + } catch { + return null; + } +} + function mentionsGateway(lines: string[]): boolean { return lines.some((l) => /gateway/.test(l)); } From 99d2d53b8faf284e14dc44365efec1893346463c Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Sun, 29 Nov 2026 23:08:13 +0530 Subject: [PATCH 31/54] [self-reports] Docs: no Cloud Self Reports page; reports live on the session timeline and event Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ docs/self-reports.mdx | 23 ++++++++++++++++++----- sdk/python/README.md | 2 +- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e27ea67c5..81b21d3c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,10 @@ - Self Reports: the stdio server suppresses a Claude Code or Codex report only when that agent's hook recorded the same call: same working directory, and each hook row vouches for one call. A report the hook recorded in one project no longer swallows an identical one from another (#1062) - Self Reports: Claude Code and Codex are registered over stdio, never on the daemon's endpoint, which records nothing for them. Their entry is user-wide while a project can turn the hooks off (`disableAllHooks` in `.claude/settings.local.json`), and every report from such a project was lost; the stdio server now records what the hook did not (#1062) +### Docs + +- Self Reports docs: Cloud has no Self Reports page; a report shows on the agent's session timeline and on the event itself, and the Cloud audit agent always sees it in transcripts. Settings and alerts stay. Also covers the tighter failure hint, the quieter output and Devin running Claude Code's hooks (#1062) + ## 1.0.18-beta.3 — 2026-11-27 ### Fixes diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index 65aeeeeb3..b6a8c72f7 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -8,6 +8,10 @@ Self Reports gives every agent one extra tool, `report`. An agent that is blocke A report never unblocks the agent and never changes a decision. Afterwards the agent works around the problem or tells the user what is blocking it. No policy can block or rewrite a report: failproofai's hook allows the call before any policy, session pause, or Jev review runs. +## Where reports show up + +Reports are internal to your organization. In Failproof AI Cloud a report appears on the agent's session timeline, at the point the agent made it, and on the `self_report` event itself. The Cloud audit agent always sees reports when it reads a session's transcript. There is no separate Self Reports page: what Cloud keeps for Self Reports is its settings (on or off, categories, guidance) and alerts. + ## On by default Self Reports is on as soon as failproofai is installed. `failproofai policies --install` and `failproofai config` register the `failproofai_local` MCP server in every agent they install hooks for, and write `~/.failproofai/self-report.json` with the default categories so every reader sees the same settings. @@ -73,7 +77,7 @@ The server sends short instructions in the MCP handshake: when to report, the ca | Agent | How the tool and its instructions reach the model | | --- | --- | | Claude Code | The entry sets `alwaysLoad: true`, so its tools are never deferred behind tool search. Server instructions go in the system prompt. | -| Codex | MCP tools are listed directly. | +| Codex | MCP tools are listed directly. In code mode (Codex 0.172) MCP servers appear as namespaces and only about the first 250 characters of the server's instructions and of the tool's description are shown, so both open with what to do: when stuck, call `failproofai_local`'s `report` tool with a `category` and a one-sentence `detail`. | | Cursor | MCP tools are listed directly. | | Copilot CLI | Tools are listed directly. Copilot passes server instructions only for its built-in allowlist (or with `--allow-all-mcp-server-instructions`), so the same instructions go in a marked `~/.copilot/instructions/failproofai-self-reports.instructions.md` (under `COPILOT_HOME` when set), written and removed with the entry. | | OpenCode | MCP tools are listed directly. | @@ -85,7 +89,7 @@ The server sends short instructions in the MCP handshake: when to report, the ca | Antigravity | The entry sets `eager: true`, so the tools are direct rather than behind the `call_mcp_tool` wrapper. | | Goose | Extensions' tools are listed directly. | -Pi has no MCP support before 0.99, so an MCP entry for it reaches no model. failproofai's Pi extension, which every Pi with failproofai hooks already loads, registers the tool itself as `mcp__failproofai_local__report` on every Pi version, with the server's instructions in Pi's system prompt. It asks `failproofai mcp --agent pi` for the tool when Pi starts (no tool while Self Reports is off) and hands each call to it, so the text, the categories and the recording are the same as every other agent's. The Hermes and OpenClaw plugins do the same against the daemon's Self Reports server: they ask it for the tool when the gateway starts (and every minute after, for the instructions and the on/off switch) and send each call to it as `?agent=hermes` or `?agent=openclaw` with the gateway's working directory, so it is attributed, deduped and logged like an MCP call. Without a daemon, or while Self Reports is off, they offer no tool. On Hermes the tool's schema is fixed when it registers, so new categories reach it at the gateway's next start. `self-report sync` writes no Pi, Hermes or OpenClaw MCP entry and takes out one an earlier version wrote, in every profile. +Pi has no MCP support before 0.99, so an MCP entry for it reaches no model. failproofai's Pi extension, which every Pi with failproofai hooks already loads, registers the tool itself as `mcp__failproofai_local__report` on every Pi version, with the server's instructions in Pi's system prompt. It asks `failproofai mcp --agent pi` for the tool when Pi starts (no tool while Self Reports is off) and hands each call to it, so the text, the categories and the recording are the same as every other agent's. The Hermes and OpenClaw plugins do the same against the daemon's Self Reports server: they ask it for the tool when the gateway starts (and every minute after, for the instructions and the on/off switch) and send each call to it as `?agent=hermes` or `?agent=openclaw` with the gateway's working directory, so it is attributed, deduped and logged like an MCP call. Without a daemon, or while Self Reports is off, they offer no tool. On Hermes the tool's schema is fixed when it registers, so new categories reach it at the gateway's next start. `self-report sync` writes no Pi, Hermes or OpenClaw MCP entry and takes out one an earlier version wrote, in every profile. `failproofai update` (and the first `failproofai config` on a new version) takes out a Hermes or OpenClaw one before it restarts their gateways, so a restarted gateway does not load it again; OpenClaw would otherwise also start the stdio server for it. Where an agent's hooks see MCP tool calls and the server they belong to, the hook records the report. Where they do not, failproofai's MCP server records it. It attributes the report to that agent's newest session seen by the hooks in the last 6 hours: in the server's working directory if there is one, else in a directory above or below it. With neither, it takes the agent's newest session only when all of the agent's sessions in those 6 hours are in one directory, and files the report as `unattributed` otherwise, rather than guess between projects. The lookup reads every page of hook activity written in the 6 hours, however busy other agents or projects kept the hooks, so a session that is still in the window is found. The agent the report is filed under comes from that session's own hook events. @@ -115,6 +119,10 @@ Claude Code and Codex can load the MCP server while skipping failproofai's hooks So the stdio server records a Claude Code or Codex report itself unless that agent's hook already recorded that same call: the agent runs its hook before it sends the MCP call, so the server looks for the hook's record of the same report, from the last two minutes and in the same working directory, and each hook record vouches for one call only. The same words in another project, or a second identical call, are recorded. A report is recorded once either way, and a person who trusts the hooks while the agent runs changes nothing. A report the server records goes on the session the agent's own files name (Codex's rollout, Claude Code's transcript for that directory). `self-report sync` registers these agents over stdio, never on the daemon's endpoint, which records nothing for them. `self-report status --verbose` says who records each one's reports and, for an untrusted Codex, how to trust the hooks: re-run `failproofai config` and allow sudo, or open `codex` once and approve them. +### Devin and Claude Code's hooks + +Devin runs the hooks in `~/.claude/settings.json` as well as its own, so a Devin call to `report` reaches failproofai's hook twice, once as Devin and once as Claude Code. Devin's report is recorded by its MCP server, so the Claude Code hook leaves a call that came from Devin alone: it recognises one by a `devin` process above the hook, or by Devin's payload (a `call-…` tool call id and no transcript path). The report is recorded once, as Devin's. + ### Other agents' servers Devin also lists the MCP servers of other agents' configs: `~/.claude.json` (user and per-project servers), a project's `.mcp.json`, and `.cursor/mcp.json` in the directory it runs in. It keeps one server per name, and its own `~/.config/devin/mcp_config.json` wins over the imported ones, except that a `.cursor/mcp.json` in the working directory (so `~/.cursor/mcp.json` when Devin runs in your home directory) wins over Devin's own. Servers under other names are listed beside ours: a `failproofai` or `failproofai-local` that `devin mcp list` shows comes from one of those files (for example a Claude Code project's `mcpServers`), not from failproofai, which only ever writes `failproofai_local`. @@ -127,13 +135,18 @@ On Antigravity, an MCP call can come through its `call_mcp_tool` wrapper. The ho `failproofai self-report status` prints one header line (on or off, and where the setting comes from), one line with the agents whose server is registered and working, and a line with the fix for each agent that has a problem: not registered, an endpoint that does not answer, a command that cannot run, a config it cannot read. `--verbose` adds the settings file, the categories, the daemon's endpoint (`not running (agents use stdio)` when no daemon is set up here) and, per agent, the transport, the URL or command, and who records its reports. `--json` prints all of it as JSON. -`policies --install`, `config`, `policies --uninstall`, `enable` and `disable` each print one Self Reports line, such as `Self Reports: on for 12 agents`, which also names any agent they could not update. `self-report sync` lists every change. +`enable` and `disable` print one line, such as `Self Reports: on for 12 agents`, which also names any agent they could not update. `policies --install`, `policies --uninstall`, `config` and `update` print nothing about Self Reports when it all worked, and one line naming the agents they could not update when it did not. They also leave out routine gateway rows (`hermes/default already current, gateway restarting`) and print only a gateway you have to restart yourself; `self-report status --verbose` shows the rows from the last update. `self-report sync` lists every change. If an MCP server named `failproofai_local` that failproofai did not write is already there, it is left alone and reported as a conflict. A server named `failproofai`, such as the [Cloud MCP gateway](/reference/mcp), is never touched or reported: it sits next to `failproofai_local`, and its tools go through your policies like any other server's. ## When a tool call fails -Once per session, after a tool call that clearly failed, failproofai adds one line the model reads: "If this blocks you and you can't fix it, call failproofai_local's `report` tool once." A call failed when it exited non-zero, returned an error (an MCP `isError`), or its error output or a short result says 401, 403, `not found` or `permission denied`; a long successful result that happens to contain those words does not count. There is no line after a successful call, after the report call itself, after a failure a failproofai deny caused (that is already recorded as a block), or while Self Reports is off. It is part of Self Reports, not a policy, and it never replaces a policy's answer. +Once per session, after a tool call failure that clearly blocks the agent, failproofai adds one line the model reads: "If this blocks you and you can't fix it, call failproofai_local's `report` tool once." A failure clearly blocks when: + +- it is an auth or credential error: its error output or a short result says 401 or 403, unauthorized, forbidden, authentication failed, an invalid or expired key, token or credentials, or names a `*_TOKEN`, `*_KEY` or `*_SECRET` that is not set, or +- the same tool, or for a shell call the same program, already failed earlier in the session. + +One non-zero exit is ordinary work and gets no line. Neither does read-only exploration failing, however often: `ls`, `cat`, `grep`, `find`, `test` and similar commands, `git status` or `git log`, and tools such as Read, Glob and Grep, unless the failure is an auth error. There is no line after a successful call, after the report call itself, after a failure a failproofai deny caused (that is already recorded as a block), or while Self Reports is off. It is part of Self Reports, not a policy, and it never replaces a policy's answer. | Agent | Where the line goes | | --- | --- | @@ -146,7 +159,7 @@ Once per session, after a tool call that clearly failed, failproofai adds one li ## The daemon's log -The daemon's log (`~/.failproofai/logs/daemon.log`, which machine logs upload) has a line for every Self Reports MCP event: each `initialize` and `tools/list`, each `tools/call` with the agent, the category, the session it was filed under, and whether it was recorded or skipped and why, and each sync's result. A write failure, a category the settings do not list, and an unreadable settings file are warnings. A line carries at most the first 40 characters of the report's detail, after secrets are scrubbed from it. The stdio server, which runs as a child of each agent, sends its events to the daemon over its socket and never waits for it: with no daemon, or a version that predates this, they are dropped. +The daemon's log (`~/.failproofai/logs/daemon.log`, which machine logs upload) has a line for every Self Reports MCP event: each `initialize` and `tools/list`, each `tools/call` with the agent, the category, the session it was filed under, and whether it was recorded or skipped and why, and each sync's result. A write failure, a category the settings do not list, and an unreadable settings file are warnings. A line carries at most the first 40 characters of the report's detail, after secrets are scrubbed from it, cut on a character boundary and followed by `...` when there was more. The stdio server, which runs as a child of each agent, sends its events to the daemon over its socket and never waits for it: with no daemon, or a version that predates this, they are dropped. ## Containers diff --git a/sdk/python/README.md b/sdk/python/README.md index 6a3485ddb..f88c154d2 100644 --- a/sdk/python/README.md +++ b/sdk/python/README.md @@ -78,7 +78,7 @@ examples beside it. A tool your agent calls when it is stuck — looping, a broken tool or credential, missing context, a request it cannot do, a task it failed. Each call becomes a -`self_report` event on the session, shown on the Self Reports page in +`self_report` event on the session, shown on the session's timeline in FailproofAI Cloud. The tool always answers `Recorded.` and changes nothing. Ready-made tools, one per framework (each imports its framework only when called): From 749b7ba70090db8f72b663168d79c48c0ebf7ed5 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Sun, 29 Nov 2026 23:25:48 +0530 Subject: [PATCH 32/54] [self-reports] One status command: drop --verbose; plain status shows everything status prints the setting, paths, categories, daemon endpoint, each agent's transport and recorder, the fix for any agent with a problem, and the last update's gateway rows. --verbose and -v are no longer accepted. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- .../hooks/self-report-hook-trust.test.ts | 6 +- __tests__/hooks/self-report.test.ts | 74 ++++++++++--------- bin/failproofai.mjs | 2 +- docs/self-reports.mdx | 8 +- src/hooks/self-report-cli.ts | 38 +--------- src/hooks/update-run.ts | 6 +- 7 files changed, 56 insertions(+), 82 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 81b21d3c2..5b12be31f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ ### Fixes -- Quieter `update`, `config` and `policies --install`/`--uninstall`: no `Hermes: hermes/default already current, gateway restarting` or `OpenClaw: openclaw/default gateway restarting` rows and no `Self Reports: on for N agents` line when all went well. Only what needs the user is printed (a gateway to restart by hand, a Hermes failure, an agent the Self Reports sync could not update); `self-report status --verbose` shows the last update's gateway rows (#1062) +- Quieter `update`, `config` and `policies --install`/`--uninstall`: no `Hermes: hermes/default already current, gateway restarting` or `OpenClaw: openclaw/default gateway restarting` rows and no `Self Reports: on for N agents` line when all went well. Only what needs the user is printed (a gateway to restart by hand, a Hermes failure, an agent the Self Reports sync could not update); `self-report status` shows the last update's gateway rows (#1062) - Self Reports: the daemon log's report preview is cut on a character boundary and marked with an ASCII `...`, so no multi-byte character is split (seen as `enviro�`); the stdio server and the CLI cut the preview and the guidance line by code point, never through a surrogate pair (#1062) - Self Reports: upgrading takes the `failproofai_local` MCP entry an earlier version wrote out of Hermes' `config.yaml` and OpenClaw's `openclaw.json` (their tool now comes from the plugin) before their gateways restart, so a restarted OpenClaw no longer starts the stdio server for it. Setup also syncs Self Reports before it restarts gateways, for the same reason (#1062) - Self Reports: the server instructions and the tool description now open with what to do (when stuck, call the `report` tool with `category` and a one-sentence `detail`). Codex 0.172's code mode keeps only about 250 characters of each, so the old opening never got as far as how to call it (#1062) @@ -37,7 +37,7 @@ - `block-failproofai-commands` no longer blocks reads and mentions it mistook for tampering: a `jq` filter with a `|` in it, a `grep`/`rg` pattern with a `(`, a heredoc that only writes text mentioning the CLI (to a file outside failproofai's state, with nothing in the same command that could run it), and a `python -c` program that can only read. It still denies running the CLI however it is spelled, pausing, uninstalling, and every write, move, delete, `chmod` or redirect into failproofai's state, including `yq -i`, which it had read as a reader (#1062) - Self Reports output is one line: `config`, `policies --install`/`--uninstall`, `self-report enable` and `disable` print `Self Reports: on for 12 agents` (or `off`, naming any agent that could not be updated) instead of a line per agent and file. `config` finishes its gateway restarts and the Self Reports sync behind one spinner line and keeps only what needs you (a gateway to restart by hand, an agent not updated); it no longer prints the Codex trust notice, which `config --status` now gives in one line, since the MCP server records an untrusted Codex's reports (#1062) -- `failproofai self-report status` is a header, one line of working agents, and one line per agent with a problem and its fix; `--verbose` has the paths, URLs, categories, update time and per-agent transport (and the Cursor approval hint), and `--json` has everything (#1062) +- `failproofai self-report status` shows everything in one place (no `--verbose`): the setting and where it comes from, paths, URLs, categories, update time, per-agent transport and recorder, any fix needed, the Cursor approval hint and the last update's gateway rows; `--json` has the same as JSON (#1062) - Self Reports in the daemon's log, so machine logs carry it: every MCP `initialize`, `tools/list` and `tools/call` (agent, category, session, recorded or skipped and why), write failures, unknown categories, unreadable settings and sync results. The stdio server and CLI syncs send theirs over the daemon socket as a new one-way `selfReportLog` message (older daemons drop it; it never waits more than 250 ms); a line carries at most 40 characters of the detail, scrubbed of secrets (#1062) ### Docs diff --git a/__tests__/hooks/self-report-hook-trust.test.ts b/__tests__/hooks/self-report-hook-trust.test.ts index be9cca7fa..904671c60 100644 --- a/__tests__/hooks/self-report-hook-trust.test.ts +++ b/__tests__/hooks/self-report-hook-trust.test.ts @@ -170,7 +170,7 @@ describe("selfReportHookState (status, sync)", () => { agent: "codex" as const, path: "/x/config.toml", hooked: true, registered: true, transport, endpoint, conflict: false, }); let rows = [row("http", "http://127.0.0.1:4319/mcp?agent=codex")]; - const r = await runSelfReportCommand(["status", "--verbose"], { + const r = await runSelfReportCommand(["status"], { probeEndpoint: async () => true, daemonLive: async () => true, registrations: () => rows, @@ -190,14 +190,14 @@ describe("selfReportHookState (status, sync)", () => { // An HTTP entry is repaired even while the hook records: no agent belongs // on HTTP any more (a project can switch the hooks off). - const ok = await runSelfReportCommand(["status", "--verbose"], { + const ok = await runSelfReportCommand(["status"], { probeEndpoint: async () => true, daemonLive: async () => true, registrations: () => [row("http", "http://127.0.0.1:4319/mcp?agent=codex")], hookState: () => ({ recorder: "hook" }), sync: async () => (synced++, []), }); expect(synced).toBe(2); - const stdioOk = await runSelfReportCommand(["status", "--verbose"], { + const stdioOk = await runSelfReportCommand(["status"], { probeEndpoint: async () => true, daemonLive: async () => true, registrations: () => [row("stdio", BIN)], hookState: () => ({ recorder: "hook" }), diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index 162332479..cab4cfddd 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -290,7 +290,7 @@ describe("enrolling with a local settings file in place", () => { // Every reader agrees: the stdio server hides the tool, the hook records nothing. const listed = await handleSelfReportRpc({ jsonrpc: "2.0", id: 1, method: "tools/list" }); expect((listed as { result: { tools: unknown[] } }).result.tools).toEqual([]); - const status = await runSelfReportCommand(["status", "--verbose"], { registrations: () => [], probeEndpoint: async () => false, daemonExpected: () => false }); + const status = await runSelfReportCommand(["status"], { registrations: () => [], probeEndpoint: async () => false, daemonExpected: () => false }); expect(status.lines[0]).toContain("off (waiting for FailproofAI Cloud"); // The org's setting arrives (the daemon writes a cloud file): it decides. const cloud = { @@ -661,7 +661,7 @@ describe("failproofai self-report enable | disable | status", () => { expect(config.unrelated).toEqual({ keep: true }); expect(readEffectiveSelfReport()).toMatchObject({ enabled: true, source: "local", guidance: "say what tool", categories: DEFAULT_CATEGORIES }); - const status = await runSelfReportCommand(["status", "--verbose"], deps); + const status = await runSelfReportCommand(["status"], deps); expect(status.exitCode).toBe(0); const text = status.lines.join("\n"); expect(text).toContain("Self Reports: on"); @@ -719,7 +719,7 @@ describe("failproofai self-report enable | disable | status", () => { writeEffectiveSelfReport({ enabled: true }); const runnable = join(home, "failproofai"); writeFileSync(runnable, "#!/bin/sh\n", { mode: 0o755 }); - const r = await runSelfReportCommand(["status", "--verbose"], { + const r = await runSelfReportCommand(["status"], { skipSync: true, probeEndpoint: async (_url, port) => port === 4319, daemonLive: async (port) => port === 4319, @@ -744,7 +744,7 @@ describe("failproofai self-report enable | disable | status", () => { expect(lines.filter((l) => l.includes("cursor-agent mcp enable"))).toHaveLength(1); }); - it("status --verbose shows what the last update did to the gateways; plain status does not", async () => { + it("status shows what the last update did to the gateways, and nothing when there is no report", async () => { writeEffectiveSelfReport({ enabled: true }); const deps = { skipSync: true, @@ -753,18 +753,17 @@ describe("failproofai self-report enable | disable | status", () => { registrations: () => [], gatewayReport: () => ({ at: "2026-11-29T16:25:41.000Z", rows: ["hermes/default already current, gateway restarting", "openclaw/default gateway restarting"] }), }; - const verbose = (await runSelfReportCommand(["status", "--verbose"], deps)).lines.join("\n"); - expect(verbose).toContain("Gateways: at the last update (2026-11-29T16:25:41.000Z)"); - expect(verbose).toContain(" hermes/default already current, gateway restarting"); - expect(verbose).toContain(" openclaw/default gateway restarting"); - expect((await runSelfReportCommand(["status"], deps)).lines.join("\n")).not.toContain("gateway restarting"); - expect((await runSelfReportCommand(["status", "--verbose"], { ...deps, gatewayReport: () => null })).lines.join("\n")).not.toContain("Gateways:"); + const out = (await runSelfReportCommand(["status"], deps)).lines.join("\n"); + expect(out).toContain("Gateways: at the last update (2026-11-29T16:25:41.000Z)"); + expect(out).toContain(" hermes/default already current, gateway restarting"); + expect(out).toContain(" openclaw/default gateway restarting"); + expect((await runSelfReportCommand(["status"], { ...deps, gatewayReport: () => null })).lines.join("\n")).not.toContain("Gateways:"); }); it("status says the daemon is not running, not \"not answering\", when there is no daemon", async () => { writeEffectiveSelfReport({ enabled: true }); const status = (expected: boolean) => - runSelfReportCommand(["status", "--verbose"], { + runSelfReportCommand(["status"], { skipSync: true, probeEndpoint: async () => false, daemonExpected: () => expected, @@ -781,7 +780,7 @@ describe("failproofai self-report enable | disable | status", () => { it("status expects a daemon when setup configured one or its socket file is there", async () => { writeEffectiveSelfReport({ enabled: true }); const status = async () => - (await runSelfReportCommand(["status", "--verbose"], { + (await runSelfReportCommand(["status"], { skipSync: true, probeEndpoint: async () => false, registrations: () => [], @@ -803,7 +802,7 @@ describe("failproofai self-report enable | disable | status", () => { writeEffectiveSelfReport({ enabled: true }); let synced = 0; let rows = [row({ transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" })]; - const r = await runSelfReportCommand(["status", "--verbose"], { + const r = await runSelfReportCommand(["status"], { probeEndpoint: async () => false, registrations: () => rows, sync: async () => { @@ -822,13 +821,13 @@ describe("failproofai self-report enable | disable | status", () => { // any more (a Claude Code project can switch its hooks off). synced = 0; rows = [row({ transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" })]; - await runSelfReportCommand(["status", "--verbose"], { + await runSelfReportCommand(["status"], { probeEndpoint: async () => true, daemonLive: async () => true, registrations: () => rows, sync: async () => (synced++, []), }); expect(synced).toBe(1); // skipSync: no write. synced = 0; - await runSelfReportCommand(["status", "--verbose"], { skipSync: true, probeEndpoint: async () => false, registrations: () => rows, sync: async () => (synced++, []) }); + await runSelfReportCommand(["status"], { skipSync: true, probeEndpoint: async () => false, registrations: () => rows, sync: async () => (synced++, []) }); expect(synced).toBe(0); }); @@ -836,7 +835,7 @@ describe("failproofai self-report enable | disable | status", () => { writeEffectiveSelfReport({ enabled: true }); let synced = 0; const http = [row({ transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" })]; - const seen = await runSelfReportCommand(["status", "--verbose"], { + const seen = await runSelfReportCommand(["status"], { skipSync: true, probeEndpoint: async () => true, daemonLive: async () => false, @@ -844,7 +843,7 @@ describe("failproofai self-report enable | disable | status", () => { }); expect(seen.lines.join("\n")).toMatch(/claude +http +\S+ \(answering, but NOT this home's daemon\)/); let rows = http; - const r = await runSelfReportCommand(["status", "--verbose"], { + const r = await runSelfReportCommand(["status"], { probeEndpoint: async () => true, daemonLive: async () => false, registrations: () => rows, @@ -862,7 +861,7 @@ describe("failproofai self-report enable | disable | status", () => { writeEffectiveSelfReport({ enabled: true }); let synced = 0; let rows = [row({ agent: "copilot", transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=copilot" })]; - const r = await runSelfReportCommand(["status", "--verbose"], { + const r = await runSelfReportCommand(["status"], { probeEndpoint: async () => true, registrations: () => rows, sync: async () => { @@ -906,25 +905,30 @@ describe("failproofai self-report enable | disable | status", () => { row({ agent: "devin", hooked: false, registered: false, transport: null }), ], }); - expect(r.lines).toEqual([ - "Self Reports: on · this machine", - "Agents: claude, cursor, copilot", - "▲ factory: command not runnable · `failproofai self-report sync`", - "▲ goose: not registered · `failproofai self-report sync`", - ]); - // No paths, URLs, categories or Cursor hint by default. - expect(r.lines.join("\n")).not.toMatch(/http:|cursor-agent|looping|self-report\.json/); + const out = r.lines.join("\n"); + // One command shows everything: there is no --verbose. + expect(r.lines[0]).toBe("Self Reports: on"); + expect(out).toContain("Source: this machine (config.json)"); + expect(out).toContain("self-report.json"); + expect(out).toContain("Categories: looping"); + expect(out).toContain("http://127.0.0.1:4319/mcp?agent=claude"); + expect(out).toContain("▲ factory: command not runnable · `failproofai self-report sync`"); + expect(out).toContain("▲ goose: not registered · `failproofai self-report sync`"); + expect(out).toContain("cursor-agent mcp enable failproofai_local"); + expect((await runSelfReportCommand(["status", "--verbose"], { skipSync: true, registrations: () => [] })).exitCode).toBe(1); }); - it("status says off in one line, and --json carries what --verbose shows", async () => { + it("status says off, on by default, or unreadable, and --json carries the same", async () => { writeEffectiveSelfReport({ enabled: false }); - expect((await runSelfReportCommand(["status"], deps)).lines).toEqual(["Self Reports: off · this machine"]); + const off = (await runSelfReportCommand(["status"], deps)).lines; + expect(off[0]).toBe("Self Reports: off"); + expect(off.join("\n")).toContain("self-report enable`"); rmSync(join(home, "self-report.json")); - expect((await runSelfReportCommand(["status"], deps)).lines).toEqual(["Self Reports: on · default", "Agents: none with failproofai hooks"]); + const dflt = (await runSelfReportCommand(["status"], deps)).lines; + expect(dflt[0]).toBe("Self Reports: on"); + expect(dflt.join("\n")).toContain("the default (no settings file yet)"); writeFileSync(join(home, "self-report.json"), "{not json"); - expect((await runSelfReportCommand(["status"], deps)).lines).toEqual([ - "Self Reports: off · settings file unreadable · `failproofai self-report enable`", - ]); + expect((await runSelfReportCommand(["status"], deps)).lines[0]).toBe("Self Reports: off (the settings file cannot be read)"); writeEffectiveSelfReport({ enabled: true }); const j = await runSelfReportCommand(["status", "--json"], { @@ -944,7 +948,7 @@ describe("failproofai self-report enable | disable | status", () => { }); it("status with no settings file says it is on by default, and how to turn it off", async () => { - const r = await runSelfReportCommand(["status", "--verbose"], deps); + const r = await runSelfReportCommand(["status"], deps); expect(r.exitCode).toBe(0); expect(r.lines[0]).toBe("Self Reports: on"); expect(r.lines.join("\n")).toContain("the default (no settings file yet)"); @@ -953,13 +957,13 @@ describe("failproofai self-report enable | disable | status", () => { it("status with no settings file on a Cloud-enrolled machine says it is off until Cloud sends it", async () => { process.env.FAILPROOFAI_CLOUD_URL = "https://example.invalid"; - const r = await runSelfReportCommand(["status", "--verbose"], deps); + const r = await runSelfReportCommand(["status"], deps); expect(r.lines[0]).toContain("off (waiting for FailproofAI Cloud"); }); it("status with a malformed settings file says it is off", async () => { writeFileSync(join(home, "self-report.json"), "{not json"); - const r = await runSelfReportCommand(["status", "--verbose"], deps); + const r = await runSelfReportCommand(["status"], deps); expect(r.lines[0]).toBe("Self Reports: off (the settings file cannot be read)"); }); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index db50e1834..12c0cc88d 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -1097,7 +1097,7 @@ async function runCli() { await printHelp({ name: "self-report", usage: [ - ["failproofai self-report status [--verbose] [--json]", "Whether it is on, the agents it serves, and any that need a fix"], + ["failproofai self-report status [--json]", "Whether it is on, the agents it serves, and any that need a fix"], ["failproofai self-report enable [options]", "Turn it back on for this machine, or change its categories"], ["failproofai self-report disable", "Turn it off: removes the MCP entries and stops recording"], ["failproofai self-report test --agent ", "Send one test report end to end"], diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index b6a8c72f7..5bcbd3b9a 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -117,7 +117,7 @@ Claude Code and Codex can load the MCP server while skipping failproofai's hooks - Codex 0.129 and later runs a hook from `~/.codex/hooks.json` only once a person trusted it, at its current hash. Hooks in Codex's system config (`/etc/codex/config.toml`, where `failproofai config` puts them when it has sudo) run without trust. - Claude Code runs no hooks with `disableAllHooks: true`, and only managed ones with a managed `allowManagedHooksOnly: true`. -So the stdio server records a Claude Code or Codex report itself unless that agent's hook already recorded that same call: the agent runs its hook before it sends the MCP call, so the server looks for the hook's record of the same report, from the last two minutes and in the same working directory, and each hook record vouches for one call only. The same words in another project, or a second identical call, are recorded. A report is recorded once either way, and a person who trusts the hooks while the agent runs changes nothing. A report the server records goes on the session the agent's own files name (Codex's rollout, Claude Code's transcript for that directory). `self-report sync` registers these agents over stdio, never on the daemon's endpoint, which records nothing for them. `self-report status --verbose` says who records each one's reports and, for an untrusted Codex, how to trust the hooks: re-run `failproofai config` and allow sudo, or open `codex` once and approve them. +So the stdio server records a Claude Code or Codex report itself unless that agent's hook already recorded that same call: the agent runs its hook before it sends the MCP call, so the server looks for the hook's record of the same report, from the last two minutes and in the same working directory, and each hook record vouches for one call only. The same words in another project, or a second identical call, are recorded. A report is recorded once either way, and a person who trusts the hooks while the agent runs changes nothing. A report the server records goes on the session the agent's own files name (Codex's rollout, Claude Code's transcript for that directory). `self-report sync` registers these agents over stdio, never on the daemon's endpoint, which records nothing for them. `self-report status` says who records each one's reports and, for an untrusted Codex, how to trust the hooks: re-run `failproofai config` and allow sudo, or open `codex` once and approve them. ### Devin and Claude Code's hooks @@ -129,13 +129,13 @@ Devin also lists the MCP servers of other agents' configs: `~/.claude.json` (use ### Cursor approval -If `cursor-agent mcp list` shows `failproofai_local` as "not loaded (needs approval)", run `cursor-agent mcp enable failproofai_local`. cursor-agent asks for approval of servers in a project's `.cursor/mcp.json`, so this happens, for example, when it runs with your home directory as the project. The approval is per project and per entry, so failproofai does not write it for you. `self-report sync` and `self-report status --verbose` say so for Cursor. +If `cursor-agent mcp list` shows `failproofai_local` as "not loaded (needs approval)", run `cursor-agent mcp enable failproofai_local`. cursor-agent asks for approval of servers in a project's `.cursor/mcp.json`, so this happens, for example, when it runs with your home directory as the project. The approval is per project and per entry, so failproofai does not write it for you. `self-report sync` and `self-report status` say so for Cursor. On Antigravity, an MCP call can come through its `call_mcp_tool` wrapper. The hook lets that call through ahead of the policies only when the wrapper names server `failproofai_local` and tool `report`. A wrapped call to any other server goes through the policies as usual. -`failproofai self-report status` prints one header line (on or off, and where the setting comes from), one line with the agents whose server is registered and working, and a line with the fix for each agent that has a problem: not registered, an endpoint that does not answer, a command that cannot run, a config it cannot read. `--verbose` adds the settings file, the categories, the daemon's endpoint (`not running (agents use stdio)` when no daemon is set up here) and, per agent, the transport, the URL or command, and who records its reports. `--json` prints all of it as JSON. +`failproofai self-report status` prints everything in one place: on or off and where the setting comes from, the settings file, the categories, the daemon's endpoint (`not running (agents use stdio)` when no daemon is set up here), each agent's transport, URL or command, who records its reports and the fix for any agent with a problem, and the gateway rows from the last `update`. `--json` prints all of it as JSON. -`enable` and `disable` print one line, such as `Self Reports: on for 12 agents`, which also names any agent they could not update. `policies --install`, `policies --uninstall`, `config` and `update` print nothing about Self Reports when it all worked, and one line naming the agents they could not update when it did not. They also leave out routine gateway rows (`hermes/default already current, gateway restarting`) and print only a gateway you have to restart yourself; `self-report status --verbose` shows the rows from the last update. `self-report sync` lists every change. +`enable` and `disable` print one line, such as `Self Reports: on for 12 agents`, which also names any agent they could not update. `policies --install`, `policies --uninstall`, `config` and `update` print nothing about Self Reports when it all worked, and one line naming the agents they could not update when it did not. They also leave out routine gateway rows (`hermes/default already current, gateway restarting`) and print only a gateway you have to restart yourself; `self-report status` shows the rows from the last update. `self-report sync` lists every change. If an MCP server named `failproofai_local` that failproofai did not write is already there, it is left alone and reported as a conflict. A server named `failproofai`, such as the [Cloud MCP gateway](/reference/mcp), is never touched or reported: it sits next to `failproofai_local`, and its tools go through your policies like any other server's. diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts index 00ee8682d..d7a93dfb3 100644 --- a/src/hooks/self-report-cli.ts +++ b/src/hooks/self-report-cli.ts @@ -275,22 +275,9 @@ function selfReportAgentViews( return out; } -/** The lean view: a header, the healthy agents in one line, a line per problem. */ -function selfReportLeanLines(header: string, views: readonly SelfReportAgentView[], repaired: string | null): string[] { - const lines = [header]; - if (repaired) lines.push(repaired); - const healthy = views.filter((v) => v.healthy).map((v) => v.agent).filter((a, i, all) => all.indexOf(a) === i); - const problems = views.filter((v) => !v.healthy && v.problem); - if (healthy.length > 0) lines.push(`Agents: ${healthy.join(", ")}`); - else if (problems.length === 0) lines.push("Agents: none with failproofai hooks"); - for (const v of problems) lines.push(`▲ ${v.agent}: ${v.problem}${v.fix ? ` · \`${v.fix}\`` : ""}`); - return lines; -} - async function selfReportStatus(args: string[], deps: SelfReportCliDeps): Promise { - const unknown = args.find((a) => a !== "--verbose" && a !== "-v" && a !== "--json"); + const unknown = args.find((a) => a !== "--json"); if (unknown) return { exitCode: 1, lines: [`Unexpected argument: ${unknown}.`] }; - const verbose = args.includes("--verbose") || args.includes("-v"); const asJson = args.includes("--json"); const file = readEffectiveSelfReport(); const settings = resolveSelfReport(); @@ -315,16 +302,6 @@ async function selfReportStatus(args: string[], deps: SelfReportCliDeps): Promis }, }; } - if (!verbose) { - lines.push( - why === "waiting" - ? "Self Reports: off · waiting for Cloud" - : why === "unreadable" - ? "Self Reports: off · settings file unreadable · `failproofai self-report enable`" - : "Self Reports: off · turned off in config.json", - ); - return { exitCode: 0, lines }; - } lines.push( awaitingCloud ? "Self Reports: off (waiting for FailproofAI Cloud to send this machine's setting; this machine's own setting no longer applies)" @@ -358,7 +335,6 @@ async function selfReportStatus(args: string[], deps: SelfReportCliDeps): Promis // report into that home. Move it (live check: stdio unless this home's // daemon serves the endpoint). let repairedLines: string[] = []; - let repaired: string | null = null; let repairedAgents: string[] = []; if (settings.enabled && !deps.skipSync && rows.some((r) => selfReportStranded(r, health, owned, recorders))) { try { @@ -368,7 +344,6 @@ async function selfReportStatus(args: string[], deps: SelfReportCliDeps): Promis .filter((r) => r.action === "added" || r.action === "updated" || r.action === "removed") .map((r) => r.agent) .filter((a, i, all) => all.indexOf(a) === i); - repaired = `✓ Re-synced ${repairedAgents.join(", ")}`; repairedLines = [ "Repaired: agents on an HTTP endpoint that is not this home's answering daemon, or that belong on stdio, were re-synced:", ...selfReportSyncLines(results).map((l) => ` ${l}`), @@ -378,7 +353,6 @@ async function selfReportStatus(args: string[], deps: SelfReportCliDeps): Promis owned = await selfReportHttpOwnership(health, deps); } } catch { - repaired = `▲ Could not re-sync agents whose HTTP endpoint is not answering · \`${SELF_REPORT_SYNC_FIX}\``; repairedLines = [`▲ Could not re-sync agents whose HTTP endpoint is not answering. Run \`${SELF_REPORT_SYNC_FIX}\`.`]; } } @@ -420,13 +394,6 @@ async function selfReportStatus(args: string[], deps: SelfReportCliDeps): Promis }; } - if (!verbose) { - const from = source === "cloud" ? "from Cloud" : source === "local" ? "this machine" : "default"; - const header = `Self Reports: ${settings.enabled ? "on" : "off"} · ${from}`; - if (!settings.enabled) return { exitCode: 0, lines: [header] }; - return { exitCode: 0, lines: selfReportLeanLines(header, views, repaired) }; - } - lines.push(`Self Reports: ${settings.enabled ? "on" : "off"}`); lines.push( `Source: ${ @@ -448,6 +415,9 @@ async function selfReportStatus(args: string[], deps: SelfReportCliDeps): Promis lines.push(...repairedLines); lines.push(selfReportDaemonLine(settings.mcp.url, daemonAnswering, deps)); lines.push(...selfReportRegistrationLines(rows, health, owned, recorders)); + if (settings.enabled) { + for (const v of views) if (!v.healthy && v.problem) lines.push(`▲ ${v.agent}: ${v.problem}${v.fix ? ` · \`${v.fix}\`` : ""}`); + } // What the last update did to Hermes and OpenClaw gateways: `update` and // `config` print only a gateway the user must restart, so the routine rows // are shown here. diff --git a/src/hooks/update-run.ts b/src/hooks/update-run.ts index 57d0a9b83..4bbf1d24a 100644 --- a/src/hooks/update-run.ts +++ b/src/hooks/update-run.ts @@ -156,7 +156,7 @@ export async function runUpdateSteps(opts: UpdateStepsOptions): Promise 0) lines.push("", ...restartLines); gatewayRows.push(...restart.openclawRestartLines(openclaw).slice(1)); @@ -305,7 +305,7 @@ export function writeGatewayReport(rows: string[], home?: string, now = new Date if (!existsSync(dirname(file))) mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); writeFileSync(file, `${JSON.stringify({ at: now.toISOString(), rows })}\n`, { mode: 0o600 }); } catch { - // only `self-report status --verbose` reads it + // only `self-report status` reads it } } From 79af74808afc80fda3497023bbb6c42933fc99fd Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 00:14:52 +0530 Subject: [PATCH 33/54] [self-reports] File every report under a listed category A model can call `report` with no category (seen live from Copilot), a near-miss spelling, or a name off the list; it was recorded as given, so Cloud showed a blank or unknown category. Each recorder now resolves it against the active list: exact name, else the listed name it normalises to, else the first keyword rule (category + detail) whose target is listed, else task_failure, else the list's first category. The model still gets "Recorded.". Same rules in the stdio server, the hook path (and the hook-trust dedupe), the daemon's HTTP server (also Hermes/OpenClaw) and both SDKs' tool-call paths, pinned by test-fixtures/self-report/category-inference.json. The daemon log says inferred_category=true raw_category="..." (rawCategory on the selfReportLog frame; an older sender still logs unknown_category=true). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/self-report-golden.test.ts | 22 ++ __tests__/hooks/self-report-handler.test.ts | 26 ++- .../hooks/self-report-hook-trust.test.ts | 7 + __tests__/hooks/self-report-log.test.ts | 4 +- __tests__/hooks/self-report.test.ts | 14 ++ crates/PROTOCOL.md | 3 +- crates/failproofaid/src/self_report.rs | 1 + crates/failproofaid/tests/self_report_e2e.rs | 8 +- crates/fpai-collect/src/self_report.rs | 218 ++++++++++++++++-- crates/fpai-collect/tests/self_report_mcp.rs | 21 +- crates/fpai-ipc/src/envelope.rs | 10 +- docs/self-reports.mdx | 4 +- sdk/python/failproofai_sdk/_self_report.py | 93 +++++++- .../failproofai_sdk/integrations/crewai.py | 1 + .../failproofai_sdk/integrations/langchain.py | 1 + .../integrations/llama_index.py | 2 +- .../integrations/pydantic_ai.py | 2 +- sdk/python/tests/test_self_report.py | 42 +++- sdk/python/tests/test_self_report_golden.py | 13 ++ sdk/typescript/src/self-report-spec.ts | 70 +++++- sdk/typescript/src/self-report.ts | 12 +- .../test/self-report-golden.test.ts | 22 ++ sdk/typescript/test/self-report.test.ts | 30 ++- src/hooks/handler.ts | 18 +- src/hooks/self-report-hook-trust.ts | 13 +- src/hooks/self-report-log.ts | 6 + src/hooks/self-report-mcp.ts | 16 +- src/hooks/self-report.ts | 70 +++++- .../self-report/category-inference.json | 151 ++++++++++++ 30 files changed, 849 insertions(+), 52 deletions(-) create mode 100644 test-fixtures/self-report/category-inference.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b12be31f..a7722c12e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ - `block-failproofai-commands` no longer treats any `python -c` program as a read: its read-only vetting could be bypassed with dynamic builtin lookups. Nothing in a command is treated as inert when the same command defines a function or alias, or sets `PATH` (#1062) - Self Reports: the stdio server suppresses a Claude Code or Codex report only when that agent's hook recorded the same call: same working directory, and each hook row vouches for one call. A report the hook recorded in one project no longer swallows an identical one from another (#1062) - Self Reports: Claude Code and Codex are registered over stdio, never on the daemon's endpoint, which records nothing for them. Their entry is user-wide while a project can turn the hooks off (`disableAllHooks` in `.claude/settings.local.json`), and every report from such a project was lost; the stdio server now records what the hook did not (#1062) +- Self Reports: a report is always filed under a listed category. A call with no `category` (seen from Copilot), a near-miss spelling, or a name that is not on the list is resolved to the listed name it normalises to, else inferred from the category and detail by keyword (a missing token or a 401 is `invalid_tool_or_credential`), else `task_failure` (or an org list's first category); it was recorded with a blank or unknown category. The same rules run in the stdio server, the hook path, the daemon and both SDKs (test-fixtures/self-report/category-inference.json), and the daemon log says `inferred_category=true` with what the model sent (#1062) ### Docs diff --git a/__tests__/hooks/self-report-golden.test.ts b/__tests__/hooks/self-report-golden.test.ts index 181c9bfb7..e3598e374 100644 --- a/__tests__/hooks/self-report-golden.test.ts +++ b/__tests__/hooks/self-report-golden.test.ts @@ -14,7 +14,10 @@ import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { SELF_REPORT_ARG_ALIASES, + SELF_REPORT_CATEGORY_RULES, SELF_REPORT_DEFAULT_CATEGORIES, + SELF_REPORT_FALLBACK_CATEGORY, + resolveSelfReportCategory, SELF_REPORT_SERVER_RECORDS, selfReportArgs, selfReportClip, @@ -65,6 +68,25 @@ describe("Self Reports golden files (CLI)", () => { expect(JSON.stringify(selfReportArgs({ detail: "x\ud83d" }))).not.toMatch(/\\ud83d/); }); + it("resolves a report's category by the shared rules and runs every shared case", () => { + const fixture = JSON.parse(golden("category-inference.json")) as { + rules: { category: string; keywords: string[] }[]; + fallback: string; + cases: { name: string; categories?: string[]; args: Record; category: string; inferred: boolean }[]; + }; + expect(SELF_REPORT_CATEGORY_RULES).toEqual(fixture.rules); + expect(SELF_REPORT_FALLBACK_CATEGORY).toBe(fixture.fallback); + const defaults = SELF_REPORT_DEFAULT_CATEGORIES.map((c) => c.name); + expect(fixture.cases.length).toBeGreaterThan(0); + for (const c of fixture.cases) { + const { category, detail } = selfReportArgs(c.args); + expect(resolveSelfReportCategory(category, detail, c.categories ?? defaults), c.name).toEqual({ + category: c.category, + inferred: c.inferred, + }); + } + }); + it("reads argument aliases from the shared list, for raw and hook-wrapped arguments", () => { const fixture = JSON.parse(golden("arg-aliases.json")) as { aliases: { category: string[]; detail: string[] }; diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index 2360724fa..1d794d044 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -270,13 +270,35 @@ describe("Self Reports short-circuit", () => { expect(rows().pop()!.selfReport).toMatchObject({ category: "invalid_tool_or_credential" }); }); - it("records an unknown category as-is, a missing detail as empty, and cuts detail at 2000", async () => { + it("records an unknown category as the listed one it resolves to, a missing detail as empty, and cuts detail at 2000", async () => { await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "made_up" })); - expect(rows().pop()!.selfReport).toEqual({ category: "made_up", detail: "", source: "mcp" }); + expect(rows().pop()!.selfReport).toEqual({ category: "task_failure", detail: "", source: "mcp" }); await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "looping", detail: "y".repeat(5000) })); expect((rows().pop()!.selfReport as { detail: string }).detail).toHaveLength(2000); }); + it("infers the category of a call that left it out (the live case), and resolves a near-miss spelling", async () => { + const detail = 'Deployment is blocked because ./deploy.sh exits with "DEPLOY_TOKEN is not set" and no token is available in this environment.'; + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { detail })); + expect(rows().pop()!.selfReport).toEqual({ category: "invalid_tool_or_credential", detail, source: "mcp" }); + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "Missing Context", detail: "x" })); + expect(rows().pop()!.selfReport).toMatchObject({ category: "missing_context" }); + }); + + it("resolves against an org's custom list: its first category when nothing matches", async () => { + writeEffectiveSelfReport({ + enabled: true, + categories: [ + { name: "data_gap", description: "Data is missing." }, + { name: "blocked", description: "Blocked." }, + ], + }); + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "", detail: "Nothing matches here." })); + expect(rows().pop()!.selfReport).toMatchObject({ category: "data_gap" }); + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "blocked", detail: "The token expired." })); + expect(rows().pop()!.selfReport).toMatchObject({ category: "blocked" }); + }); + it("does not exempt a lookalike tool name", async () => { const out = await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai__report_evil", {})); expect(out.evaluation?.decision).toBe("deny"); diff --git a/__tests__/hooks/self-report-hook-trust.test.ts b/__tests__/hooks/self-report-hook-trust.test.ts index 904671c60..8260a554b 100644 --- a/__tests__/hooks/self-report-hook-trust.test.ts +++ b/__tests__/hooks/self-report-hook-trust.test.ts @@ -258,6 +258,13 @@ describe("the server records what the hook did not, once", () => { expect(selfReportHookRecordedRecently("codex", { type: args.category, summary: args.detail }, Date.now(), projA)).toBe(true); }); + it("matches a hook row that holds the inferred category to the call that left it out", () => { + writeEffectiveSelfReport({ enabled: true }); + const detail = "The DEPLOY_TOKEN is not set."; + hookRow({ cwd: projA, selfReport: { category: "invalid_tool_or_credential", detail, source: "mcp" } }); + expect(selfReportHookRecordedRecently("codex", { detail }, Date.now(), projA)).toBe(true); + }); + // Review 4722003644: the same text in another project, or a second call, // is a distinct report. it("never lets one project's hook row suppress another project's report", () => { diff --git a/__tests__/hooks/self-report-log.test.ts b/__tests__/hooks/self-report-log.test.ts index 82ad5e0c6..2a14ee4cf 100644 --- a/__tests__/hooks/self-report-log.test.ts +++ b/__tests__/hooks/self-report-log.test.ts @@ -186,7 +186,9 @@ describe("selfReportLog over the daemon socket", () => { expect(events[0]).toMatchObject({ event: "initialize", agent: "copilot", transport: "stdio", outcome: "on" }); expect(events[1]).toMatchObject({ event: "tools/list", outcome: "report" }); expect(events[2]).toMatchObject({ event: "tools/call", outcome: "recorded", category: "looping", knownCategory: true, session: "unattributed", preview: "stuck" }); - expect(events[3]).toMatchObject({ outcome: "recorded", category: "made_up", knownCategory: false }); + // An unlisted category is recorded as the one it resolves to; the log keeps what was sent. + expect(events[3]).toMatchObject({ outcome: "recorded", category: "task_failure", knownCategory: false, rawCategory: "made_up" }); + expect(events[2].rawCategory).toBeUndefined(); expect(events[4]).toMatchObject({ outcome: "skipped", reason: "Self Reports is off" }); expect(events[5]).toMatchObject({ outcome: "skipped", reason: "settings unreadable" }); expect(events[6]).toMatchObject({ outcome: "skipped", reason: "no --agent" }); diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index cab4cfddd..3b931c321 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -452,6 +452,20 @@ describe("MCP fallback recording helpers", () => { expect(event).toMatchObject({ session_id: "oc-1", agent_id: "openclaw-workspace", integration: "openclaw" }); }); + it("records a call with no category (seen live from Copilot) under the inferred one, and still answers Recorded.", async () => { + writeEffectiveSelfReport({ enabled: true }); + const detail = 'Deployment is blocked because ./deploy.sh exits with "DEPLOY_TOKEN is not set" and no token is available in this environment.'; + const reply = await handleSelfReportRpc( + { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "report", arguments: { detail } } }, + { agent: "copilot", cwd: "/work/ws" }, + ); + expect(reply).toEqual({ jsonrpc: "2.0", id: 1, result: { content: [{ type: "text", text: "Recorded." }] } }); + const dir = join(home, "custom-agents", "events"); + const [file] = readdirSync(dir); + const event = JSON.parse(readFileSync(join(dir, file), "utf8").trim()); + expect(event).toMatchObject({ type: "self_report", category: "invalid_tool_or_credential", detail, integration: "copilot" }); + }); + it("an unknown method gets -32601; a notification gets no reply; an unknown tool is an error result", async () => { expect(await handleSelfReportRpc({ jsonrpc: "2.0", id: 9, method: "resources/list" })).toMatchObject({ error: { code: -32601 } }); expect(await handleSelfReportRpc({ jsonrpc: "2.0", method: "notifications/initialized" })).toBeNull(); diff --git a/crates/PROTOCOL.md b/crates/PROTOCOL.md index e8e763bab..b15bea04d 100644 --- a/crates/PROTOCOL.md +++ b/crates/PROTOCOL.md @@ -81,7 +81,8 @@ Tagged JSON, `"type"` as the discriminant, camelCase field names. "outcome": "recorded", // recorded | skipped | failed (calls); on | off (initialize) "reason": "Self Reports is off", "category": "looping", - "knownCategory": true, + "knownCategory": true, // false: the category sent is not listed, and `category` was resolved from it + "rawCategory": "", // only when knownCategory is false: what was sent (maybe empty), ≤ 64 chars "session": "…", "preview": "≤ 200 chars of the detail; the daemon scrubs secrets and logs ≤ 40", "summary": "added claude (stdio); failed codex (…)" // sync only diff --git a/crates/failproofaid/src/self_report.rs b/crates/failproofaid/src/self_report.rs index 99986d7a5..84f70bb36 100644 --- a/crates/failproofaid/src/self_report.rs +++ b/crates/failproofaid/src/self_report.rs @@ -277,6 +277,7 @@ pub fn log_remote(ev: &fpai_ipc::SelfReportLogEvent) { reason: ev.reason.as_deref(), category: ev.category.as_deref(), known_category: ev.known_category, + raw_category: ev.raw_category.as_deref(), session: ev.session.as_deref(), detail: ev.preview.as_deref(), summary: ev.summary.as_deref(), diff --git a/crates/failproofaid/tests/self_report_e2e.rs b/crates/failproofaid/tests/self_report_e2e.rs index 66ac9fd74..cf989a2cd 100644 --- a/crates/failproofaid/tests/self_report_e2e.rs +++ b/crates/failproofaid/tests/self_report_e2e.rs @@ -332,13 +332,17 @@ fn self_report_mcp_events_reach_the_daemon_log() { "{log}" ); assert!(log.contains("session=sess-42"), "{log}"); - // An unknown category is a warning; a known one is not. + // An unlisted category is a warning; a listed one is not. let http_line = log .lines() .find(|l| l.contains("over http agent=copilot outcome=recorded")) .unwrap(); assert!(http_line.contains("WARN"), "{http_line}"); - assert!(http_line.contains("unknown_category=true"), "{http_line}"); + // Recorded under the category it resolves to (the 401), naming what was sent. + assert!( + http_line.contains("category=\"invalid_tool_or_credential\" inferred_category=true raw_category=\"not_a_category\""), + "{http_line}" + ); let stdio_line = log .lines() .find(|l| l.contains("over stdio agent=hermes")) diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index d9da417b5..dd5eadae6 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -941,16 +941,18 @@ impl Server { /// still send a call. Read from disk, not the cache, so a disable is /// honoured on the very next call (as the stdio server does). fn record(&self, args: &Value, caller: &Caller) { - let report = Report::from_args(args); + let mut report = Report::from_args(args); + let raw_category = report.category.clone(); let mut log = McpLog { event: "tools/call", transport: "http", agent: caller.agent.as_deref(), outcome: Some("skipped"), - category: Some(&report.category), - detail: Some(&report.detail), + category: Some(&raw_category), ..Default::default() }; + let detail = report.detail.clone(); + log.detail = Some(&detail); let Some(agent) = caller .agent .as_deref() @@ -976,11 +978,17 @@ impl Server { return; } }; - log.known_category = Some( - effective_categories(&settings) - .iter() - .any(|c| c.name == report.category), - ); + // A missing, unlisted or misspelt category is recorded as the listed + // one it resolves to; the log keeps what the model sent. + let categories = effective_categories(&settings); + let names: Vec<&str> = categories.iter().map(|c| c.name.as_str()).collect(); + let (resolved, inferred) = resolve_category(&raw_category, &report.detail, &names); + report.category = resolved; + log.known_category = Some(!inferred); + log.category = Some(&report.category); + if inferred { + log.raw_category = Some(&raw_category); + } let event = fallback_event(&self.home, agent, caller.cwd.as_deref(), &report, now_ms()); let session = event .get("session_id") @@ -1020,6 +1028,9 @@ pub struct McpLog<'a> { pub reason: Option<&'a str>, pub category: Option<&'a str>, pub known_category: Option, + /// What the model sent as the category (maybe empty), when `category` + /// was inferred from it ([`resolve_category`]). + pub raw_category: Option<&'a str>, pub session: Option<&'a str>, /// The report's detail; only [`log_preview`] of it is logged. pub detail: Option<&'a str>, @@ -1074,8 +1085,14 @@ pub fn log_line(ev: &McpLog) -> String { if let Some(v) = ev.category { field("category", format!("{:?}", word(v, 64))); } - if ev.known_category == Some(false) { - field("unknown_category", "true".to_string()); + match (ev.known_category, ev.raw_category) { + (Some(false), Some(raw)) => { + field("inferred_category", "true".to_string()); + field("raw_category", format!("{:?}", word(raw, 64))); + } + // A sender older than inference: it recorded the category as sent. + (Some(false), None) => field("unknown_category", "true".to_string()), + _ => {} } if let Some(v) = ev.session { field("session", word(v, 128)); @@ -1094,8 +1111,8 @@ pub fn log_line(ev: &McpLog) -> String { line } -/// Log one event: WARN for a failure, an `error` event, a report filed under -/// a category the settings do not list, or settings that cannot be read; +/// Log one event: WARN for a failure, an `error` event, a report whose +/// category was not on the settings' list as sent, or settings that cannot be read; /// INFO otherwise. pub fn log_event(ev: &McpLog) { let line = log_line(ev); @@ -1137,8 +1154,8 @@ pub const DETAIL_ALIASES: &[&str] = &[ "details", ]; -/// A call's arguments, as recorded: an unknown category is kept as-is; a -/// missing or empty argument falls back to its first non-empty alias, else ""; +/// A call's arguments, as the model sent them ([`Server::record`] then +/// resolves the category with [`resolve_category`]); a missing or empty argument falls back to its first non-empty alias, else ""; /// unknown keys are ignored. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Report { @@ -1163,6 +1180,133 @@ impl Report { } } +/// Keyword rules for a category the model did not name (or named wrongly), in +/// order: the first rule whose target is on the active list and whose keyword +/// appears in the lowercased `category + " " + detail` wins. Identical in the +/// CLI (`SELF_REPORT_CATEGORY_RULES`) and both SDKs; +/// test-fixtures/self-report/category-inference.json holds the rules and cases. +pub const CATEGORY_RULES: &[(&str, &[&str])] = &[ + ( + "invalid_tool_or_credential", + &[ + "token", + "api key", + "apikey", + "api_key", + "credential", + "unauthorized", + "unauthenticated", + "forbidden", + "401", + "403", + "expired", + "revoked", + "auth", + "password", + "secret", + ], + ), + ( + "looping", + &[ + "loop", + "looping", + "circular", + "in circles", + "repeating the same", + ], + ), + ( + "repeated_tool_failure", + &[ + "keeps failing", + "keep failing", + "repeatedly", + "several attempts", + "multiple attempts", + "retried", + "retries", + "again and again", + ], + ), + ( + "missing_context", + &[ + "missing", + "not found", + "no information", + "not provided", + "cannot find", + "can't find", + "need more information", + "unclear", + ], + ), + ( + "cannot_do_request", + &[ + "cannot", + "can't", + "unable", + "not possible", + "impossible", + "not supported", + "unsupported", + "not allowed", + ], + ), +]; + +/// The category a report falls back to when nothing matched, if it is listed. +pub const FALLBACK_CATEGORY: &str = "task_failure"; + +fn has_keyword(text: &str, keyword: &str) -> bool { + let word = |c: Option| c.is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit()); + text.match_indices(keyword).any(|(at, _)| { + !word(text[..at].chars().next_back()) && !word(text[at + keyword.len()..].chars().next()) + }) +} + +/// The category a report is recorded under, and whether it was inferred (is +/// not `raw` itself): `raw` when it is on `names`; else the listed name it +/// normalises to (lowercase, trimmed, runs of spaces and hyphens as `_`); else +/// the first [`CATEGORY_RULES`] rule that matches the category and detail and +/// targets a listed name; else [`FALLBACK_CATEGORY`] when listed, else the +/// first listed name. An empty list keeps `raw`. +pub fn resolve_category(raw: &str, detail: &str, names: &[&str]) -> (String, bool) { + if names.is_empty() || names.contains(&raw) { + return (raw.to_string(), false); + } + let mut normalised = String::new(); + let mut gap = false; + for c in raw.trim().to_lowercase().chars() { + if c.is_whitespace() || c == '-' { + if !gap { + normalised.push('_'); + } + gap = true; + } else { + normalised.push(c); + gap = false; + } + } + if names.contains(&normalised.as_str()) { + return (normalised, true); + } + let text = format!("{raw} {detail}").to_lowercase(); + for (target, keywords) in CATEGORY_RULES { + if names.contains(target) && keywords.iter().any(|k| has_keyword(&text, k)) { + return (target.to_string(), true); + } + } + let fallback = if names.contains(&FALLBACK_CATEGORY) { + FALLBACK_CATEGORY + } else { + names[0] + }; + (fallback.to_string(), true) +} + /// How closely a hook row's cwd matches the caller's: 2 the same directory, /// 1 an ancestor or descendant of it, 0 unrelated or unknown. Trailing slashes /// are ignored; `/` is an ancestor of every absolute path. Same as @@ -1474,6 +1618,7 @@ mod tests { reason: Some("Self Reports is off"), category: Some("looping"), known_category: Some(false), + raw_category: None, session: Some("s-1"), detail: Some("stuck\nin a loop"), summary: None, @@ -1484,6 +1629,21 @@ mod tests { category=\"looping\" unknown_category=true session=s-1 \ reason=\"Self Reports is off\" preview=\"stuck in a loop\"" ); + // An inferred category names what the model sent (here nothing). + let inferred = log_line(&McpLog { + event: "tools/call", + transport: "http", + outcome: Some("recorded"), + category: Some("invalid_tool_or_credential"), + known_category: Some(false), + raw_category: Some(""), + ..Default::default() + }); + assert_eq!( + inferred, + "Self Reports MCP tools/call over http outcome=recorded \ + category=\"invalid_tool_or_credential\" inferred_category=true raw_category=\"\"" + ); let bare = log_line(&McpLog { event: "initialize", transport: "http", @@ -2426,6 +2586,36 @@ mod tests { assert!(golden("instructions.golden.txt").chars().count() < 600); } + #[test] + fn golden_category_inference() { + let fixture: Value = serde_json::from_str(&golden("category-inference.json")).unwrap(); + let rules: Vec = CATEGORY_RULES + .iter() + .map(|(category, keywords)| json!({"category": category, "keywords": keywords})) + .collect(); + assert_eq!(fixture["rules"], json!(rules)); + assert_eq!(fixture["fallback"], FALLBACK_CATEGORY); + let defaults = default_categories(); + let cases = fixture["cases"].as_array().unwrap(); + assert!(!cases.is_empty()); + for case in cases { + let name = case["name"].as_str().unwrap(); + let names: Vec<&str> = match case["categories"].as_array() { + Some(list) => list.iter().map(|v| v.as_str().unwrap()).collect(), + None => defaults.iter().map(|c| c.name.as_str()).collect(), + }; + let report = Report::from_args(&case["args"]); + assert_eq!( + resolve_category(&report.category, &report.detail, &names), + ( + case["category"].as_str().unwrap().to_string(), + case["inferred"].as_bool().unwrap() + ), + "{name}" + ); + } + } + #[test] fn golden_arg_aliases() { let fixture: Value = serde_json::from_str(&golden("arg-aliases.json")).unwrap(); diff --git a/crates/fpai-collect/tests/self_report_mcp.rs b/crates/fpai-collect/tests/self_report_mcp.rs index 0fa7f34ea..f05ba6ddb 100644 --- a/crates/fpai-collect/tests/self_report_mcp.rs +++ b/crates/fpai-collect/tests/self_report_mcp.rs @@ -444,7 +444,26 @@ async fn a_server_recorded_agent_gets_its_report_written() { .find(|e| e["integration"] == "goose") .expect("recorded"); assert_eq!(goose["session_id"], "unattributed"); - assert_eq!(goose["category"], "made_up"); + // An unlisted category is recorded as the listed one it resolves to (the 401). + assert_eq!(goose["category"], "invalid_tool_or_credential"); + + // No category at all (seen live from Copilot): inferred from the detail. + let detail = "Deployment is blocked because ./deploy.sh exits with \"DEPLOY_TOKEN is not set\" and no token is available in this environment."; + let (_, reply) = server + .rpc( + "?agent=copilot", + json!({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{ + "name":"report","arguments":{"detail": detail}}}), + ) + .await; + assert_eq!(reply.unwrap()["result"]["content"][0]["text"], "Recorded."); + let events = event_files(&home); + let copilot = events + .iter() + .find(|e| e["integration"] == "copilot") + .expect("recorded"); + assert_eq!(copilot["category"], "invalid_tool_or_credential"); + assert_eq!(copilot["detail"], detail); // A model that guessed the argument names: the detail is kept, extras ignored. let (_, reply) = server diff --git a/crates/fpai-ipc/src/envelope.rs b/crates/fpai-ipc/src/envelope.rs index d73f871c2..1a7ce044d 100644 --- a/crates/fpai-ipc/src/envelope.rs +++ b/crates/fpai-ipc/src/envelope.rs @@ -106,9 +106,14 @@ pub struct SelfReportLogEvent { pub reason: Option, #[serde(skip_serializing_if = "Option::is_none")] pub category: Option, - /// Whether `category` is on the settings' list. + /// Whether the category the model sent is on the settings' list; when it + /// is not, `category` is the one it was resolved to. #[serde(skip_serializing_if = "Option::is_none")] pub known_category: Option, + /// What the model sent as the category (maybe empty), when `category` + /// was inferred from it. Absent from a sender older than inference. + #[serde(skip_serializing_if = "Option::is_none")] + pub raw_category: Option, #[serde(skip_serializing_if = "Option::is_none")] pub session: Option, /// The start of the report's detail. The daemon scrubs secrets from it @@ -406,7 +411,7 @@ mod tests { let msg: ClientMessage = serde_json::from_value(serde_json::json!({ "type": "selfReportLog", "protocolVersion": PROTOCOL_VERSION, - "event": {"event": "tools/call", "agent": "copilot", "knownCategory": false, "later": 1} + "event": {"event": "tools/call", "agent": "copilot", "knownCategory": false, "rawCategory": "", "later": 1} })) .unwrap(); let ClientMessage::SelfReportLog { event, .. } = msg else { @@ -415,6 +420,7 @@ mod tests { assert_eq!(event.event, "tools/call"); assert_eq!(event.agent.as_deref(), Some("copilot")); assert_eq!(event.known_category, Some(false)); + assert_eq!(event.raw_category.as_deref(), Some("")); assert_eq!(event.session, None); // Absent fields stay off the wire. let json = serde_json::to_value(ClientMessage::SelfReportLog { diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index 5bcbd3b9a..a2c49b5ea 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -62,7 +62,7 @@ An organization's own list replaces these entirely. Names are lowercase letters, | `repeated_tool_failure` | A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. | | `task_failure` | You genuinely tried and could not complete the task. Not for refusals or policy blocks. | -A report with a category that is not on the list is still recorded under the name the agent gave. The detail is cut to 2,000 characters (Unicode code points, so an emoji or other character outside the Basic Multilingual Plane counts once and is never split). An agent that calls the tool without loading its schema sometimes guesses the argument names, so when `detail` is missing or empty the first non-empty of `summary`, `sentence`, `message`, `description`, `reason`, `text` and `details` is recorded instead, and when `category` is, `type` or `kind`. Other unknown arguments are ignored; a call is never rejected. +A report is always filed under a category on the list. A missing category, a near-miss spelling such as `Invalid Tool Or Credential`, or a name that is not listed is resolved to the listed name it normalises to, else to the first listed category whose keywords appear in the category or detail (a missing token or a 401 is `invalid_tool_or_credential`, going in circles is `looping`), else to `task_failure`, or to the first category of a list without it. The detail is cut to 2,000 characters (Unicode code points, so an emoji or other character outside the Basic Multilingual Plane counts once and is never split). An agent that calls the tool without loading its schema sometimes guesses the argument names, so when `detail` is missing or empty the first non-empty of `summary`, `sentence`, `message`, `description`, `reason`, `text` and `details` is recorded instead, and when `category` is, `type` or `kind`. Other unknown arguments are ignored; a call is never rejected. ## Agent support @@ -159,7 +159,7 @@ One non-zero exit is ordinary work and gets no line. Neither does read-only expl ## The daemon's log -The daemon's log (`~/.failproofai/logs/daemon.log`, which machine logs upload) has a line for every Self Reports MCP event: each `initialize` and `tools/list`, each `tools/call` with the agent, the category, the session it was filed under, and whether it was recorded or skipped and why, and each sync's result. A write failure, a category the settings do not list, and an unreadable settings file are warnings. A line carries at most the first 40 characters of the report's detail, after secrets are scrubbed from it, cut on a character boundary and followed by `...` when there was more. The stdio server, which runs as a child of each agent, sends its events to the daemon over its socket and never waits for it: with no daemon, or a version that predates this, they are dropped. +The daemon's log (`~/.failproofai/logs/daemon.log`, which machine logs upload) has a line for every Self Reports MCP event: each `initialize` and `tools/list`, each `tools/call` with the agent, the category, the session it was filed under, and whether it was recorded or skipped and why, and each sync's result. A write failure, a report whose category was inferred (the line says `inferred_category=true` and gives the `raw_category` the agent sent, which may be empty), and an unreadable settings file are warnings. A line carries at most the first 40 characters of the report's detail, after secrets are scrubbed from it, cut on a character boundary and followed by `...` when there was more. The stdio server, which runs as a child of each agent, sends its events to the daemon over its socket and never waits for it: with no daemon, or a version that predates this, they are dropped. ## Containers diff --git a/sdk/python/failproofai_sdk/_self_report.py b/sdk/python/failproofai_sdk/_self_report.py index 920840862..9d0482ac1 100644 --- a/sdk/python/failproofai_sdk/_self_report.py +++ b/sdk/python/failproofai_sdk/_self_report.py @@ -337,6 +337,77 @@ def _coerce_text(value: Any) -> str: } +# Keyword rules for a category the model did not name (or named wrongly), in +# order: the first rule whose target is on the active list and whose keyword +# appears in the lowercased `category + " " + detail` wins. The same rules as +# the CLI and the daemon: test-fixtures/self-report/category-inference.json. +CATEGORY_RULES: tuple[tuple[str, tuple[str, ...]], ...] = ( + ( + "invalid_tool_or_credential", + ("token", "api key", "apikey", "api_key", "credential", "unauthorized", "unauthenticated", + "forbidden", "401", "403", "expired", "revoked", "auth", "password", "secret"), + ), + ("looping", ("loop", "looping", "circular", "in circles", "repeating the same")), + ( + "repeated_tool_failure", + ("keeps failing", "keep failing", "repeatedly", "several attempts", "multiple attempts", + "retried", "retries", "again and again"), + ), + ( + "missing_context", + ("missing", "not found", "no information", "not provided", "cannot find", "can't find", + "need more information", "unclear"), + ), + ( + "cannot_do_request", + ("cannot", "can't", "unable", "not possible", "impossible", "not supported", "unsupported", + "not allowed"), + ), +) + +#: The category a report falls back to when nothing matched, if it is listed. +FALLBACK_CATEGORY = "task_failure" + +def _has_keyword(text: str, keyword: str) -> bool: + pattern = r"(? tuple[str, bool]: + """`(category, inferred)`: the category a model's report is recorded under. + + `raw` when it is on `names`; else the listed name it normalises to + (lowercase, trimmed, runs of spaces and hyphens as `_`); else the first + `CATEGORY_RULES` rule that matches the category and detail and targets a + listed name; else `task_failure` when listed, else the first listed name. + `inferred` is True whenever the result is not `raw` itself. An empty list + keeps `raw`. + """ + if not names or raw in names: + return raw, False + normalised = re.sub(r"[\s\-]+", "_", raw.strip().lower()) + if normalised in names: + return normalised, True + text = f"{raw} {detail}".lower() + for target, keywords in CATEGORY_RULES: + if target in names and any(_has_keyword(text, k) for k in keywords): + return target, True + return (FALLBACK_CATEGORY if FALLBACK_CATEGORY in names else names[0]), True + + +def _category_names(categories: Any) -> list[str]: + """The names of `categories` (a list of `{"name", ...}` or of names), else + the current settings' list.""" + if categories is None: + categories = load_settings()["categories"] + out: list[str] = [] + for c in categories: + name = c.get("name") if isinstance(c, dict) else c + if isinstance(name, str): + out.append(name) + return out + + def _first_text(arguments: dict, key: str) -> str: for name in (key, *ARG_ALIASES[key]): text = _coerce_text(arguments.get(name)) @@ -372,9 +443,14 @@ def parse_arguments(arguments: Any) -> tuple[str, str]: _warned_unbound = False -def record_tool_call(arguments: Any, **fields: Any) -> str: +def record_tool_call(arguments: Any, *, categories: Any = None, **fields: Any) -> str: """Record a report from a model's tool call and return `"Recorded."`. + The category is resolved against `categories` (the list the tool was + built with; default: the current settings' list) by `resolve_category`, so + a call that left it out, misspelt it or named one not on the list is still + filed under a listed one. + Never raises into the agent loop. A report that cannot be recorded (a writer fault, an invalid explicit id) is logged (once at WARNING, then at DEBUG) and the model still gets `Recorded.`: the tool's contract is that it @@ -383,6 +459,7 @@ def record_tool_call(arguments: Any, **fields: Any) -> str: global _warned_unbound category, detail = parse_arguments(arguments) try: + category, _ = resolve_category(category, detail, _category_names(categories)) self_report(category, detail, **fields) except Exception as exc: # noqa: BLE001 - see docstring level = logging.DEBUG if _warned_unbound else logging.WARNING @@ -402,6 +479,7 @@ def handle_tool_call( session_id: str | None = None, agent_id: str | None = None, tool_call_id: str | None = None, + categories: list[dict[str, str]] | None = None, ) -> str: """Handle a report tool call from a raw model API. Returns `"Recorded."`. @@ -410,7 +488,10 @@ def handle_tool_call( out = fp.handle_tool_call(call.function.name, call.function.arguments, tool_call_id=call.id) - `arguments` may be a dict or a JSON string. Raises `ValueError` only when + `arguments` may be a dict or a JSON string. Pass `categories` when the tool + was built with its own list (`openai_tool(categories=...)`), so the + category is resolved against that list rather than the settings'. + Raises `ValueError` only when `name` is not the report tool, so a dispatcher bug is loud; recording itself never raises (see `record_tool_call`). """ @@ -425,7 +506,7 @@ def handle_tool_call( fields["agent_id"] = agent_id if tool_call_id: fields["tool_call_id"] = str(tool_call_id) - return record_tool_call(arguments, **fields) + return record_tool_call(arguments, categories=categories, **fields) # --------------------------------------------------------------------------- @@ -442,9 +523,13 @@ def record_framework_call( tool_call_id: Any = None, fields: dict | None = None, extra_args: dict | None = None, + categories: Any = None, ) -> str: """Record one framework tool call and return `"Recorded."`. Never raises. + `categories`: the names (or entries) the tool was built with, which the + category is resolved against (`resolve_category`). + Identity, most explicit first: the `session_id` / `agent_id` the developer gave the tool factory; then `identity`, which the adapter resolved from the framework's own run tree (so the report lands on the agent that made the @@ -467,7 +552,7 @@ def record_framework_call( # an aliased detail (`summary`, `sentence`, ...) is not lost. arguments = {k: v for k, v in (extra_args or {}).items() if isinstance(k, str)} arguments.update(category=category, detail=detail) - return record_tool_call(arguments, **out) + return record_tool_call(arguments, categories=categories, **out) def framework_signature(names: list[str]): diff --git a/sdk/python/failproofai_sdk/integrations/crewai.py b/sdk/python/failproofai_sdk/integrations/crewai.py index 2fdc28e6f..ac76c7772 100644 --- a/sdk/python/failproofai_sdk/integrations/crewai.py +++ b/sdk/python/failproofai_sdk/integrations/crewai.py @@ -1799,6 +1799,7 @@ def _run(self, category, detail) -> str: return _self_report.record_framework_call( category, detail, identity=identity, session_id=session_id, agent_id=agent_id, tool_call_id=tool_call_id, fields=extra, + categories=names, ) _run.__annotations__ = _self_report.framework_signature(names) diff --git a/sdk/python/failproofai_sdk/integrations/langchain.py b/sdk/python/failproofai_sdk/integrations/langchain.py index ba3e74a94..778d697e4 100644 --- a/sdk/python/failproofai_sdk/integrations/langchain.py +++ b/sdk/python/failproofai_sdk/integrations/langchain.py @@ -2247,6 +2247,7 @@ def _record(category: Any = "", detail: Any = "", callbacks: Any = None) -> str: return _self_report.record_framework_call( category, detail, identity=identity, session_id=session_id, agent_id=agent_id, tool_call_id=tool_call_id, fields=extra, + categories=spec["input_schema"]["properties"]["category"]["enum"], ) def report(category: str = "", detail: str = "", callbacks: Any = None) -> str: diff --git a/sdk/python/failproofai_sdk/integrations/llama_index.py b/sdk/python/failproofai_sdk/integrations/llama_index.py index 09bda0432..0b81f7c45 100644 --- a/sdk/python/failproofai_sdk/integrations/llama_index.py +++ b/sdk/python/failproofai_sdk/integrations/llama_index.py @@ -1649,7 +1649,7 @@ def failproofai_report(category, detail) -> str: logger.debug("failproofai_sdk: could not resolve the report's agent run", exc_info=True) return _self_report.record_framework_call( category, detail, identity=identity, session_id=session_id, - agent_id=agent_id, fields=extra, + agent_id=agent_id, fields=extra, categories=names, ) failproofai_report.__annotations__ = _self_report.framework_signature(names) diff --git a/sdk/python/failproofai_sdk/integrations/pydantic_ai.py b/sdk/python/failproofai_sdk/integrations/pydantic_ai.py index 9c025bcac..cb4886342 100644 --- a/sdk/python/failproofai_sdk/integrations/pydantic_ai.py +++ b/sdk/python/failproofai_sdk/integrations/pydantic_ai.py @@ -1059,7 +1059,7 @@ def failproofai_report(ctx: Any, category: Any = "", detail: Any = "", **raw: An return _self_report.record_framework_call( category, detail, session_id=session_id, agent_id=agent_id, tool_call_id=getattr(ctx, "tool_call_id", None), fields=extra, - extra_args=raw, + extra_args=raw, categories=spec["input_schema"]["properties"]["category"]["enum"], ) return Tool.from_schema( diff --git a/sdk/python/tests/test_self_report.py b/sdk/python/tests/test_self_report.py index abd560d94..396a07f18 100644 --- a/sdk/python/tests/test_self_report.py +++ b/sdk/python/tests/test_self_report.py @@ -261,10 +261,44 @@ def test_detail_is_truncated_and_none_becomes_empty(recorded): def test_unknown_category_is_recorded_as_is(recorded): + # The developer's own call is recorded as given; only a model's tool call + # is resolved against the list. fp.self_report("not_a_configured_one", "d", session_id="s") assert recorded[0]["category"] == "not_a_configured_one" +LIVE_DETAIL = ( + 'Deployment is blocked because ./deploy.sh exits with "DEPLOY_TOKEN is not set" ' + "and no token is available in this environment." +) + + +def test_a_tool_call_with_no_category_is_filed_under_the_inferred_one(recorded, home): + assert fp.handle_tool_call("failproofai_report", {"detail": LIVE_DETAIL}, session_id="s") == "Recorded." + assert recorded[0]["category"] == "invalid_tool_or_credential" + assert recorded[0]["detail"] == LIVE_DETAIL + fp.handle_tool_call( + "failproofai_report", '{"category": "Invalid Tool Or Credential", "detail": "x"}', session_id="s" + ) + assert recorded[1]["category"] == "invalid_tool_or_credential" + fp.handle_tool_call( + "failproofai_report", {"category": "command_nonzero_exit", "detail": "the build failed"}, session_id="s" + ) + assert recorded[2]["category"] == "task_failure" + + +def test_a_tool_call_resolves_against_the_orgs_list_or_the_tools_own(recorded, home): + write_settings(home, {"enabled": True, "categories": [ + {"name": "data_gap", "description": "Data is missing."}, + {"name": "blocked", "description": "Blocked."}, + ]}) + fp.handle_tool_call("failproofai_report", {"category": "", "detail": "Nothing matches."}, session_id="s") + assert recorded[0]["category"] == "data_gap" + own = [{"name": "blocked", "description": "B."}, {"name": "missing_context", "description": "M."}] + fp.handle_tool_call("failproofai_report", {"detail": "The ticket is missing."}, session_id="s", categories=own) + assert recorded[1]["category"] == "missing_context" + + @pytest.mark.parametrize("name", ["timestamp", "type", "environment", "source"]) def test_reserved_and_sdk_owned_fields_are_rejected(recorded, name): with pytest.raises(ValueError): @@ -486,7 +520,13 @@ def test_handle_tool_call_with_a_dict_and_explicit_identity(recorded): ) def test_handle_tool_call_tolerates_bad_arguments(recorded, arguments, expected): assert fp.handle_tool_call("failproofai_report", arguments, session_id="s") == "Recorded." - assert (recorded[0]["category"], recorded[0]["detail"]) == expected + # Parsed as before; a category that is missing or not listed is then + # recorded as the one it resolves to (nothing here matches a keyword). + from failproofai_sdk import _self_report + + assert _self_report.parse_arguments(arguments) == expected + category = "looping" if expected[0] == "looping" else "task_failure" + assert (recorded[0]["category"], recorded[0]["detail"]) == (category, expected[1]) def test_handle_tool_call_keeps_an_aliased_detail(recorded): diff --git a/sdk/python/tests/test_self_report_golden.py b/sdk/python/tests/test_self_report_golden.py index 38d11c6a2..b0b52333e 100644 --- a/sdk/python/tests/test_self_report_golden.py +++ b/sdk/python/tests/test_self_report_golden.py @@ -87,6 +87,19 @@ def test_event_field_order(): assert list(SelfReportEvent(**base, tool_call_id="call_1").to_dict()) == spec["order"] + spec["optional"] +def test_category_inference_matches_the_shared_rules_and_cases(): + fixture = json.loads(golden("category-inference.json")) + rules = [{"category": c, "keywords": list(k)} for c, k in _self_report.CATEGORY_RULES] + assert rules == fixture["rules"] + assert _self_report.FALLBACK_CATEGORY == fixture["fallback"] + defaults = [c["name"] for c in _self_report.DEFAULT_CATEGORIES] + assert fixture["cases"] + for case in fixture["cases"]: + category, detail = _self_report.parse_arguments(case["args"]) + got = _self_report.resolve_category(category, detail, case.get("categories", defaults)) + assert got == (case["category"], case["inferred"]), case["name"] + + def test_argument_aliases_match_the_shared_list(): fixture = json.loads(golden("arg-aliases.json")) assert {k: list(v) for k, v in _self_report.ARG_ALIASES.items()} == fixture["aliases"] diff --git a/sdk/typescript/src/self-report-spec.ts b/sdk/typescript/src/self-report-spec.ts index c68e86e55..d04d9fc00 100644 --- a/sdk/typescript/src/self-report-spec.ts +++ b/sdk/typescript/src/self-report-spec.ts @@ -211,8 +211,8 @@ export function isSelfReportTool(name: unknown, server?: unknown): boolean { /** * The call's arguments as the event records them. * - * Never rejects: a model that names an unknown category is still recorded - * under that name, a missing or empty argument falls back to its first + * Never rejects: the category is returned as sent (`recordToolCall` then + * resolves it with `resolveSelfReportCategory`), a missing or empty argument falls back to its first * non-empty alias (`SELF_REPORT_ARG_ALIASES`) else `""`, and arguments that * arrive as the JSON string a provider sent (OpenAI's `function.arguments`) * are parsed first. Anything unreadable becomes the empty strings — the call @@ -246,6 +246,72 @@ export const SELF_REPORT_ARG_ALIASES = Object.freeze({ detail: Object.freeze(["summary", "sentence", "message", "description", "reason", "text", "details"]), }); +/** + * Keyword rules for a category the model did not name (or named wrongly), in + * order: the first rule whose target is on the active list and whose keyword + * appears in the lowercased `category + " " + detail` wins. The same rules as + * the CLI and the daemon: test-fixtures/self-report/category-inference.json. + */ +export const SELF_REPORT_CATEGORY_RULES: ReadonlyArray<{ readonly category: string; readonly keywords: readonly string[] }> = + Object.freeze([ + { + category: "invalid_tool_or_credential", + keywords: ["token", "api key", "apikey", "api_key", "credential", "unauthorized", "unauthenticated", "forbidden", "401", "403", "expired", "revoked", "auth", "password", "secret"], + }, + { category: "looping", keywords: ["loop", "looping", "circular", "in circles", "repeating the same"] }, + { + category: "repeated_tool_failure", + keywords: ["keeps failing", "keep failing", "repeatedly", "several attempts", "multiple attempts", "retried", "retries", "again and again"], + }, + { + category: "missing_context", + keywords: ["missing", "not found", "no information", "not provided", "cannot find", "can't find", "need more information", "unclear"], + }, + { + category: "cannot_do_request", + keywords: ["cannot", "can't", "unable", "not possible", "impossible", "not supported", "unsupported", "not allowed"], + }, + ]); + +/** The category a report falls back to when nothing matched, if it is listed. */ +export const SELF_REPORT_FALLBACK_CATEGORY = "task_failure"; + +function isWordChar(ch: string | undefined): boolean { + return ch !== undefined && /[a-z0-9]/.test(ch); +} + +function hasKeyword(text: string, keyword: string): boolean { + for (let at = text.indexOf(keyword); at !== -1; at = text.indexOf(keyword, at + 1)) { + if (!isWordChar(text[at - 1]) && !isWordChar(text[at + keyword.length])) return true; + } + return false; +} + +/** + * The category a model's report is recorded under: `raw` when it is on + * `names`, else the listed name it normalises to (lowercase, trimmed, runs of + * spaces and hyphens as `_`), else the first `SELF_REPORT_CATEGORY_RULES` rule + * that matches the category and detail and targets a listed name, else + * `task_failure` when listed, else the first listed name. `inferred` is true + * whenever the result is not `raw` itself. An empty list keeps `raw`. + */ +export function resolveSelfReportCategory( + raw: string, + detail: string, + names: readonly string[], +): { category: string; inferred: boolean } { + if (names.length === 0 || names.includes(raw)) return { category: raw, inferred: false }; + const normalised = raw.trim().toLowerCase().replace(/[\s-]+/g, "_"); + if (names.includes(normalised)) return { category: normalised, inferred: true }; + const text = `${raw} ${detail}`.toLowerCase(); + for (const rule of SELF_REPORT_CATEGORY_RULES) { + if (names.includes(rule.category) && rule.keywords.some((k) => hasKeyword(text, k))) { + return { category: rule.category, inferred: true }; + } + } + return { category: names.includes(SELF_REPORT_FALLBACK_CATEGORY) ? SELF_REPORT_FALLBACK_CATEGORY : (names[0] ?? raw), inferred: true }; +} + function firstText(record: Record, key: string, aliases: readonly string[]): string { for (const name of [key, ...aliases]) { const text = asText(record[name]); diff --git a/sdk/typescript/src/self-report.ts b/sdk/typescript/src/self-report.ts index 4be1c0879..644a897d4 100644 --- a/sdk/typescript/src/self-report.ts +++ b/sdk/typescript/src/self-report.ts @@ -33,6 +33,7 @@ import { defaultCategories, isSelfReportTool, normalizeSelfReportArgs, + resolveSelfReportCategory, toAnthropicTool, toOpenAIResponsesTool, toOpenAITool, @@ -170,10 +171,17 @@ export function handleToolCall(name: string, args: unknown, fields: SelfReportOp return SELF_REPORT_RESULT; } -/** The shared body of every report tool: record, swallow, answer. */ +/** + * The shared body of every report tool: record, swallow, answer. A category + * the model left out, misspelt or named off the list is recorded as the + * listed one it resolves to (`resolveSelfReportCategory`, against the same + * settings the tool's schema came from). + */ export function recordToolCall(args: unknown, fields: SelfReportOptions = {}): string { try { - const { category, detail } = normalizeSelfReportArgs(args); + const { category: raw, detail } = normalizeSelfReportArgs(args); + const names = selfReportSettings().categories.map((c) => c.name); + const { category } = resolveSelfReportCategory(raw, detail, names); runtime.event.selfReport(category, detail, fields); } catch (error) { logger.warn(`self report was not recorded: ${error instanceof Error ? error.message : String(error)}`); diff --git a/sdk/typescript/test/self-report-golden.test.ts b/sdk/typescript/test/self-report-golden.test.ts index d77f20980..151878e1d 100644 --- a/sdk/typescript/test/self-report-golden.test.ts +++ b/sdk/typescript/test/self-report-golden.test.ts @@ -7,10 +7,13 @@ import * as schema from "../src/schema.js"; import { DEFAULT_SELF_REPORT_CATEGORIES, SELF_REPORT_ARG_ALIASES, + SELF_REPORT_CATEGORY_RULES, + SELF_REPORT_FALLBACK_CATEGORY, SELF_REPORT_TOOL_SPELLINGS, describeSelfReport, isSelfReportTool, normalizeSelfReportArgs, + resolveSelfReportCategory, selfReportInputSchema, } from "../src/self-report-spec.js"; @@ -32,6 +35,25 @@ describe("Self Reports golden files (TypeScript SDK)", () => { ).toBe(golden("description-guidance.golden.txt")); }); + it("resolves a report's category by the shared rules and runs every shared case", () => { + const fixture = JSON.parse(golden("category-inference.json")) as { + rules: { category: string; keywords: string[] }[]; + fallback: string; + cases: { name: string; categories?: string[]; args: Record; category: string; inferred: boolean }[]; + }; + expect(SELF_REPORT_CATEGORY_RULES).toEqual(fixture.rules); + expect(SELF_REPORT_FALLBACK_CATEGORY).toBe(fixture.fallback); + const defaults = DEFAULT_SELF_REPORT_CATEGORIES.map((c) => c.name); + expect(fixture.cases.length).toBeGreaterThan(0); + for (const c of fixture.cases) { + const { category, detail } = normalizeSelfReportArgs(c.args); + expect(resolveSelfReportCategory(category, detail, c.categories ?? defaults), c.name).toEqual({ + category: c.category, + inferred: c.inferred, + }); + } + }); + it("reads argument aliases from the shared list", () => { const fixture = JSON.parse(golden("arg-aliases.json")) as { aliases: { category: string[]; detail: string[] }; diff --git a/sdk/typescript/test/self-report.test.ts b/sdk/typescript/test/self-report.test.ts index c2cae9bc5..840181100 100644 --- a/sdk/typescript/test/self-report.test.ts +++ b/sdk/typescript/test/self-report.test.ts @@ -484,9 +484,37 @@ describe("the raw tool helpers", () => { }); const recorded = await reports(); expect(recorded).toHaveLength(1); - expect(recorded[0]).toMatchObject({ category: "", detail: "" }); + // Unreadable arguments: no category, so it falls back to task_failure. + expect(recorded[0]).toMatchObject({ category: "task_failure", detail: "" }); expect(String(warn.mock.calls[0]![0])).toContain("not recorded"); }); + + it("files a call with no category (seen live) under the inferred one, and a near-miss under the listed name", async () => { + const detail = 'Deployment is blocked because ./deploy.sh exits with "DEPLOY_TOKEN is not set" and no token is available in this environment.'; + await session({ sessionId: "s1" }, () => { + expect(failproofai.handleToolCall("failproofai_report", { detail })).toBe("Recorded."); + failproofai.handleToolCall("failproofai_report", { category: "Invalid Tool Or Credential", detail: "x" }); + failproofai.handleToolCall("failproofai_report", { category: "command_nonzero_exit", detail: "the build failed" }); + }); + const [live, nearMiss, unknown] = await reports(); + expect(live).toMatchObject({ category: "invalid_tool_or_credential", detail }); + expect(nearMiss).toMatchObject({ category: "invalid_tool_or_credential" }); + expect(unknown).toMatchObject({ category: "task_failure" }); + }); + + it("resolves a call against the org's list: its first category when nothing matches", async () => { + writeSettings({ + enabled: true, + categories: [ + { name: "data_gap", description: "Data is missing." }, + { name: "blocked", description: "Blocked." }, + ], + }); + await session({ sessionId: "s1" }, () => { + failproofai.handleToolCall("failproofai_report", { category: "", detail: "Nothing matches." }); + }); + expect((await reports())[0]).toMatchObject({ category: "data_gap" }); + }); }); describe("the framework tools", () => { diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index cda94dae2..910e2763d 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -59,11 +59,13 @@ import { isSelfReportCursorCall, isSelfReportToolName, readEnabledSelfReport, + resolveSelfReportCategory, selfReportAntigravityWrappedArgs, selfReportArgs, SELF_REPORT_MCP_TOOL_NAME, SELF_REPORT_SERVER_RECORDS, } from "./self-report"; +import { selfReportClip } from "./self-report-names"; import { selfReportFailureHint, selfReportSessionStartContext } from "./self-report-hint"; import { selfReportClaudeHookFromDevin } from "./self-report-devin"; import { deliveryHealth, deliveryHealthLine } from "./delivery-health"; @@ -700,8 +702,14 @@ function recordSelfReportCall( // Devin runs Claude Code's hooks too: a `--cli claude` call that is really // Devin's is left to Devin's MCP server, so the report is filed once, as devin. const devinViaClaude = isReportRow && cli === "claude" && selfReportClaudeHookFromDevin(parsed); - const hookRecords = - isReportRow && !devinViaClaude && !SELF_REPORT_SERVER_RECORDS.includes(cli) && readEnabledSelfReport() !== null; + const enabled = isReportRow && !devinViaClaude && !SELF_REPORT_SERVER_RECORDS.includes(cli) ? readEnabledSelfReport() : null; + const hookRecords = enabled !== null; + // The category is recorded as the listed name it resolves to (a model may + // leave it out or misspell it); the line below says when it was inferred. + const report = hookRecords ? selfReportArgs(parsed.tool_input) : null; + const resolved = report && enabled + ? resolveSelfReportCategory(report.category, report.detail, enabled.categories.map((c) => c.name)) + : null; try { persistHookActivity({ timestamp: writtenAt, @@ -720,13 +728,15 @@ function recordSelfReportCall( cwd: session.cwd, permissionMode: session.permissionMode, hookEventName: session.hookEventName, - ...(hookRecords ? { selfReport: { ...selfReportArgs(parsed.tool_input), source: "mcp" as const } } : {}), + ...(report && resolved ? { selfReport: { category: resolved.category, detail: report.detail, source: "mcp" as const } } : {}), }); } catch { hookLogWarn("activity persistence failed"); } hookLogInfo( - `event=${canonicalEventType} cli=${cli} self-report allowed${devinViaClaude ? " (Devin via Claude hooks, left to Devin)" : ""} duration=${durationMs}ms`, + `event=${canonicalEventType} cli=${cli} self-report allowed${devinViaClaude ? " (Devin via Claude hooks, left to Devin)" : ""}${ + resolved?.inferred ? ` category=${resolved.category} inferred_category=true raw_category=${JSON.stringify(selfReportClip(report?.category ?? "", 64))}` : "" + } duration=${durationMs}ms`, ); return { exitCode: 0, diff --git a/src/hooks/self-report-hook-trust.ts b/src/hooks/self-report-hook-trust.ts index 4b8512deb..caba1f5bc 100644 --- a/src/hooks/self-report-hook-trust.ts +++ b/src/hooks/self-report-hook-trust.ts @@ -37,7 +37,7 @@ import { } from "./codex-system-hooks"; import { claudeConfigDir, getIntegration } from "./integrations"; import { getHookActivityEntriesSince } from "./hook-activity-store"; -import { selfReportArgs } from "./self-report"; +import { readEnabledSelfReport, resolveSelfReportCategory, selfReportArgs } from "./self-report"; import { selfReportClip } from "./self-report-names"; import { failproofaiHome } from "./fp-home"; @@ -197,8 +197,8 @@ export const SELF_REPORT_HOOK_DEDUPE_MS = 2 * 60 * 1000; * A hook row matches when it is a PreToolUse row from that integration, * written in the last two minutes, in the same working directory as this * server (`cwd`; a row or a server without one never matches), carrying a - * `selfReport` with the same category and detail as the hook would have - * clipped them. Matching on the report's text alone suppressed distinct calls: + * `selfReport` with the same category (as sent, or as resolved against the + * list) and detail as the hook would have clipped them. Matching on the report's text alone suppressed distinct calls: * a report the hook recorded in project A made an identical report in project * B answer `Recorded.` with no event. * @@ -222,6 +222,11 @@ export function selfReportHookRecordedRecently( if (!cwd) return false; const { category, detail } = selfReportArgs(args ?? {}); const want = { category: selfReportClip(category), detail: selfReportClip(detail) }; + // The hook row holds the category as it was resolved against the list + // (resolveSelfReportCategory), so a call whose category was missing or + // misspelt matches it by that name; the name as sent still matches too. + const names = (readEnabledSelfReport()?.categories ?? []).map((c) => c.name); + const resolved = resolveSelfReportCategory(want.category, want.detail, names).category; const here = sameDir(cwd); let rows: Array>; try { @@ -235,7 +240,7 @@ export function selfReportHookRecordedRecently( if (!Number.isFinite(ts) || now - ts > SELF_REPORT_HOOK_DEDUPE_MS || ts - now > 60_000) return false; if (typeof row.cwd !== "string" || !row.cwd || sameDir(row.cwd) !== here) return false; const sr = row.selfReport as { category?: unknown; detail?: unknown } | undefined; - return !!sr && sr.category === want.category && sr.detail === want.detail; + return !!sr && (sr.category === want.category || sr.category === resolved) && sr.detail === want.detail; }); // Oldest first, so concurrent calls claim rows in the order the hooks ran. candidates.sort((x, y) => (x.timestamp as number) - (y.timestamp as number)); diff --git a/src/hooks/self-report-log.ts b/src/hooks/self-report-log.ts index 0a172b6b1..fe85416d2 100644 --- a/src/hooks/self-report-log.ts +++ b/src/hooks/self-report-log.ts @@ -24,6 +24,8 @@ import { selfReportClip } from "./self-report-names"; export const SELF_REPORT_LOG_BUDGET_MS = 250; /** How much detail is sent; the daemon logs at most its first 40 characters. */ export const SELF_REPORT_LOG_PREVIEW_CHARS = 200; +/** How much of an inferred report's raw category is sent; the daemon logs at most 64 characters. */ +export const SELF_REPORT_LOG_RAW_CATEGORY_CHARS = 64; const SELF_REPORT_LOG_PROTOCOL_VERSION = 2; export interface SelfReportLogEvent { @@ -33,7 +35,10 @@ export interface SelfReportLogEvent { outcome?: string; reason?: string; category?: string; + /** False when `category` was resolved from something the model sent that is not on the list. */ knownCategory?: boolean; + /** What the model sent as the category (maybe empty), when `category` was inferred; cut before sending. */ + rawCategory?: string; session?: string; /** The report's detail; cut to `SELF_REPORT_LOG_PREVIEW_CHARS` here. */ preview?: string; @@ -87,6 +92,7 @@ function selfReportLogSend(event: SelfReportLogEvent): Promise { event: { ...event, ...(event.preview !== undefined ? { preview: selfReportClip(event.preview, SELF_REPORT_LOG_PREVIEW_CHARS) } : {}), + ...(event.rawCategory !== undefined ? { rawCategory: selfReportClip(event.rawCategory, SELF_REPORT_LOG_RAW_CATEGORY_CHARS) } : {}), }, }), "utf8", diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts index b2058cf06..5fa0d00dd 100644 --- a/src/hooks/self-report-mcp.ts +++ b/src/hooks/self-report-mcp.ts @@ -37,6 +37,7 @@ import { SELF_REPORT_TOOL_NAME, describeSelfReportTool, readEnabledSelfReport, + resolveSelfReportCategory, selfReportArgs, selfReportClip, selfReportInputSchema, @@ -437,8 +438,8 @@ export async function handleSelfReportRpc( return ok({ content: [{ type: "text", text: `Unknown tool: ${String(params.name)}` }], isError: true }); } const agent = opts.agent; - const { category, detail } = selfReportArgs(params.arguments ?? {}); - const call = { event: "tools/call" as const, category, preview: detail }; + const { category: rawCategory, detail } = selfReportArgs(params.arguments ?? {}); + const call = { event: "tools/call" as const, category: rawCategory, preview: detail }; const settings = readEnabledSelfReport(); if (!agent) { log({ ...call, outcome: "skipped", reason: "no --agent" }); @@ -447,7 +448,12 @@ export async function handleSelfReportRpc( } else if (!(await selfReportServerShouldRecord(agent, params.arguments, opts.now?.(), opts.cwd ?? process.cwd()))) { log({ ...call, outcome: "skipped", reason: "its hook recorded it" }); } else { - const knownCategory = settings.categories.some((c) => c.name === category); + // A missing, unlisted or misspelt category is recorded as the listed + // one it resolves to; the log keeps what the model sent. + const resolved = resolveSelfReportCategory(rawCategory, detail, settings.categories.map((c) => c.name)); + const category = resolved.category; + const knownCategory = !resolved.inferred; + const logged = { ...call, category, knownCategory, ...(resolved.inferred ? { rawCategory } : {}) }; try { const { path, event } = await writeSelfReportEvent({ integration: agent, @@ -456,13 +462,13 @@ export async function handleSelfReportRpc( cwd: opts.cwd ?? process.cwd(), now: opts.now?.(), }); - log({ ...call, outcome: "recorded", knownCategory, session: String(event.session_id) }); + log({ ...logged, outcome: "recorded", session: String(event.session_id) }); if (process.env[SELF_REPORT_RECEIPT_ENV] === "1") process.stderr.write(`${SELF_REPORT_RECEIPT_PREFIX}${path}\n`); } catch (err) { // The agent still hears "Recorded.": a report changes no decision, // and an error here would only make it retry. const why = err instanceof Error ? err.message : String(err); - log({ ...call, outcome: "failed", knownCategory, reason: `write failed: ${why}` }); + log({ ...logged, outcome: "failed", reason: `write failed: ${why}` }); process.stderr.write(`[failproofai mcp] could not record a self report: ${why}\n`); } } diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts index 791022eb0..fe1b6cb39 100644 --- a/src/hooks/self-report.ts +++ b/src/hooks/self-report.ts @@ -196,8 +196,8 @@ export { selfReportInstructions }; export const SELF_REPORT_RESULT_TEXT = "Recorded."; /** - * A call's arguments as they are recorded: an unknown category is kept as-is - * (never rejected), a missing or empty argument falls back to its first + * A call's arguments as a model sent them (the recorders then resolve the + * category with `resolveSelfReportCategory`; a call is never rejected), a missing or empty argument falls back to its first * non-empty alias (`SELF_REPORT_ARG_ALIASES`), else `""`; unknown keys are ignored; detail is cut to 2000 * code points (`selfReportClip`). A category is cut to the same bound so a hostile argument cannot * grow every activity row without limit. @@ -243,6 +243,72 @@ export const SELF_REPORT_ARG_ALIASES = { detail: ["summary", "sentence", "message", "description", "reason", "text", "details"], } as const; +/** + * Keyword rules for a category the model did not name (or named wrongly), in + * order; the first rule whose target is on the active list and whose keyword + * appears in the lowercased `category + " " + detail` wins. Identical in the + * daemon and both SDKs; test-fixtures/self-report/category-inference.json + * holds the rules and the cases for all of them. + */ +export const SELF_REPORT_CATEGORY_RULES: readonly { category: string; keywords: readonly string[] }[] = [ + { + category: "invalid_tool_or_credential", + keywords: ["token", "api key", "apikey", "api_key", "credential", "unauthorized", "unauthenticated", "forbidden", "401", "403", "expired", "revoked", "auth", "password", "secret"], + }, + { category: "looping", keywords: ["loop", "looping", "circular", "in circles", "repeating the same"] }, + { + category: "repeated_tool_failure", + keywords: ["keeps failing", "keep failing", "repeatedly", "several attempts", "multiple attempts", "retried", "retries", "again and again"], + }, + { + category: "missing_context", + keywords: ["missing", "not found", "no information", "not provided", "cannot find", "can't find", "need more information", "unclear"], + }, + { + category: "cannot_do_request", + keywords: ["cannot", "can't", "unable", "not possible", "impossible", "not supported", "unsupported", "not allowed"], + }, +]; + +/** The category a report falls back to when nothing matched, if it is listed. */ +export const SELF_REPORT_FALLBACK_CATEGORY = "task_failure"; + +function selfReportIsWordChar(ch: string | undefined): boolean { + return ch !== undefined && /[a-z0-9]/.test(ch); +} + +function selfReportHasKeyword(text: string, keyword: string): boolean { + for (let at = text.indexOf(keyword); at !== -1; at = text.indexOf(keyword, at + 1)) { + if (!selfReportIsWordChar(text[at - 1]) && !selfReportIsWordChar(text[at + keyword.length])) return true; + } + return false; +} + +/** + * The category a report is recorded under: `raw` when it is on `names`, else + * the listed name it normalises to (lowercase, trimmed, runs of spaces and + * hyphens as `_`), else the first keyword rule (`SELF_REPORT_CATEGORY_RULES`) + * that matches the category and detail and targets a listed name, else + * `task_failure` when listed, else the first listed name. `inferred` is true + * whenever the result is not `raw` itself. An empty list keeps `raw`. + */ +export function resolveSelfReportCategory( + raw: string, + detail: string, + names: readonly string[], +): { category: string; inferred: boolean } { + if (names.length === 0 || names.includes(raw)) return { category: raw, inferred: false }; + const normalised = raw.trim().toLowerCase().replace(/[\s-]+/g, "_"); + if (names.includes(normalised)) return { category: normalised, inferred: true }; + const text = `${raw} ${detail}`.toLowerCase(); + for (const rule of SELF_REPORT_CATEGORY_RULES) { + if (names.includes(rule.category) && rule.keywords.some((k) => selfReportHasKeyword(text, k))) { + return { category: rule.category, inferred: true }; + } + } + return { category: names.includes(SELF_REPORT_FALLBACK_CATEGORY) ? SELF_REPORT_FALLBACK_CATEGORY : names[0], inferred: true }; +} + const SELF_REPORT_ARG_KEYS: readonly string[] = [ "category", "detail", diff --git a/test-fixtures/self-report/category-inference.json b/test-fixtures/self-report/category-inference.json new file mode 100644 index 000000000..c2567bbe4 --- /dev/null +++ b/test-fixtures/self-report/category-inference.json @@ -0,0 +1,151 @@ +{ + "rules": [ + { + "category": "invalid_tool_or_credential", + "keywords": ["token", "api key", "apikey", "api_key", "credential", "unauthorized", "unauthenticated", "forbidden", "401", "403", "expired", "revoked", "auth", "password", "secret"] + }, + { + "category": "looping", + "keywords": ["loop", "looping", "circular", "in circles", "repeating the same"] + }, + { + "category": "repeated_tool_failure", + "keywords": ["keeps failing", "keep failing", "repeatedly", "several attempts", "multiple attempts", "retried", "retries", "again and again"] + }, + { + "category": "missing_context", + "keywords": ["missing", "not found", "no information", "not provided", "cannot find", "can't find", "need more information", "unclear"] + }, + { + "category": "cannot_do_request", + "keywords": ["cannot", "can't", "unable", "not possible", "impossible", "not supported", "unsupported", "not allowed"] + } + ], + "fallback": "task_failure", + "cases": [ + { + "name": "the live case: no category, a missing token in the detail", + "args": {"detail": "Deployment is blocked because ./deploy.sh exits with \"DEPLOY_TOKEN is not set\" and no token is available in this environment."}, + "category": "invalid_tool_or_credential", + "inferred": true + }, + { + "name": "an exact listed name is kept", + "args": {"category": "looping", "detail": "The API key is rejected."}, + "category": "looping", + "inferred": false + }, + { + "name": "a near-miss spelling is normalised", + "args": {"category": "Invalid Tool Or Credential", "detail": "The build failed."}, + "category": "invalid_tool_or_credential", + "inferred": true + }, + { + "name": "hyphens and padding are normalised", + "args": {"category": " missing-context ", "detail": ""}, + "category": "missing_context", + "inferred": true + }, + { + "name": "empty category and no keyword falls back to task_failure", + "args": {"category": "", "detail": "The build never finishes."}, + "category": "task_failure", + "inferred": true + }, + { + "name": "no arguments at all falls back to task_failure", + "args": {}, + "category": "task_failure", + "inferred": true + }, + { + "name": "an unknown category with no keyword falls back to task_failure", + "args": {"category": "command_nonzero_exit", "detail": "the build failed"}, + "category": "task_failure", + "inferred": true + }, + { + "name": "the unknown category text is searched too", + "args": {"category": "auth_error", "detail": "Something broke."}, + "category": "invalid_tool_or_credential", + "inferred": true + }, + { + "name": "auth does not match inside author", + "args": {"detail": "The author of the change is unknown."}, + "category": "task_failure", + "inferred": true + }, + { + "name": "a 403 is a credential problem", + "args": {"detail": "The registry answers HTTP 403 for every push."}, + "category": "invalid_tool_or_credential", + "inferred": true + }, + { + "name": "looping", + "args": {"category": "stuck", "detail": "I am going in circles on the same test."}, + "category": "looping", + "inferred": true + }, + { + "name": "repeated tool failure", + "args": {"detail": "The linter keeps failing on the generated file."}, + "category": "repeated_tool_failure", + "inferred": true + }, + { + "name": "missing context", + "args": {"detail": "The staging database URL is not provided anywhere."}, + "category": "missing_context", + "inferred": true + }, + { + "name": "cannot do the request", + "args": {"detail": "Sending email is not supported here."}, + "category": "cannot_do_request", + "inferred": true + }, + { + "name": "the first matching rule wins", + "args": {"detail": "Unable to continue: the token expired."}, + "category": "invalid_tool_or_credential", + "inferred": true + }, + { + "name": "an alias carries the category", + "args": {"type": "Looping", "summary": "Same fix again."}, + "category": "looping", + "inferred": true + }, + { + "name": "a rule whose target is not listed is skipped", + "categories": ["data_gap", "blocked"], + "args": {"detail": "The token expired."}, + "category": "data_gap", + "inferred": true + }, + { + "name": "a custom list without task_failure falls back to its first category", + "categories": ["data_gap", "blocked"], + "args": {"category": "", "detail": "Nothing matches here."}, + "category": "data_gap", + "inferred": true + }, + { + "name": "a custom list keeps its own names and still infers listed targets", + "categories": ["blocked", "missing_context"], + "args": {"category": "whatever", "detail": "The ticket number is missing."}, + "category": "missing_context", + "inferred": true + }, + { + "name": "a custom name is kept exactly", + "categories": ["blocked", "missing_context"], + "args": {"category": "blocked", "detail": "The token expired."}, + "category": "blocked", + "inferred": false + } + ] +} From 209133968f056fdb58a541e6d85d693806cbbf0c Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 00:40:47 +0530 Subject: [PATCH 34/54] [self-reports] No gateway restart advice where Hermes or OpenClaw is not installed A missing hermes/openclaw binary made the gateway status probe read as failed, so every update and config on such a machine printed "restart the gateway". No program means no gateway: report it as not running, which prints nothing. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/gateway-restart.test.ts | 23 +++++++++++++++++++++++ src/hooks/gateway-restart.ts | 8 +++++++- 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a7722c12e..bde235ba3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ - Self Reports: after a tool call failure that clearly blocks (an auth or credential error such as a 401 or 403, an invalid or expired key or token, or a `*_TOKEN` that is not set; or the same tool or command failing a second time in the session), one line of context once per session suggests calling `report` if the agent cannot fix it. One non-zero exit, and read-only exploration (`ls`, `cat`, `grep`, `find`, `test`, Read, Glob) failing, never earn it. On Claude Code, Codex, Cursor, Copilot (its failure event) and Factory. Never on success, on the report call, after a failproofai deny, or while Self Reports is off; it is not a policy and never replaces one's answer (#1062) ### Fixes - +- `update` and `config` no longer say "restart the gateway" for Hermes or OpenClaw on a machine where that program is not installed: with no `hermes` or `openclaw` there is no gateway to restart (#1062) - Quieter `update`, `config` and `policies --install`/`--uninstall`: no `Hermes: hermes/default already current, gateway restarting` or `OpenClaw: openclaw/default gateway restarting` rows and no `Self Reports: on for N agents` line when all went well. Only what needs the user is printed (a gateway to restart by hand, a Hermes failure, an agent the Self Reports sync could not update); `self-report status` shows the last update's gateway rows (#1062) - Self Reports: the daemon log's report preview is cut on a character boundary and marked with an ASCII `...`, so no multi-byte character is split (seen as `enviro�`); the stdio server and the CLI cut the preview and the guidance line by code point, never through a surrogate pair (#1062) - Self Reports: upgrading takes the `failproofai_local` MCP entry an earlier version wrote out of Hermes' `config.yaml` and OpenClaw's `openclaw.json` (their tool now comes from the plugin) before their gateways restart, so a restarted OpenClaw no longer starts the stdio server for it. Setup also syncs Self Reports before it restarts gateways, for the same reason (#1062) diff --git a/__tests__/hooks/gateway-restart.test.ts b/__tests__/hooks/gateway-restart.test.ts index cc6bbaa0f..454e0f254 100644 --- a/__tests__/hooks/gateway-restart.test.ts +++ b/__tests__/hooks/gateway-restart.test.ts @@ -73,6 +73,29 @@ describe("Hermes gateway restart", () => { const run = () => { throw new Error("ENOENT"); }; expect(restartHermesGateway(PROFILE, { run }).status).toBe("failed"); }); + + it("says nothing when Hermes is not installed: there is no gateway to restart", () => { + const d = deps({ "hermes gateway status": { status: null, stdout: "", missing: true } }); + expect(restartHermesGateway(PROFILE, d).status).toBe("not-running"); + expect(d.spawnDetached).not.toHaveBeenCalled(); + }); +}); + +describe("a gateway whose program is not installed", () => { + it("reads as not running for OpenClaw too, so update prints no row for it", () => { + const d = deps({ "openclaw gateway status --json": { status: null, stdout: "", missing: true } }); + const r = restartOpenClawGateway({ name: "default", home: "/home/u/.openclaw" }, d); + expect(r.status).toBe("not-running"); + expect(openclawRestartLines([r])).toEqual([]); + }); + + it("is detected from a real spawn of a program that does not exist", () => { + const r = restartHermesGateway(PROFILE, { run: undefined, spawnDetached: () => false }); + // Only meaningful where no `hermes` is on PATH (CI); otherwise it is a real status. + if (!process.env.PATH?.split(":").some((d) => { try { return statSync(join(d, "hermes")).isFile(); } catch { return false; } })) { + expect(r.status).toBe("not-running"); + } + }); }); const RUNNING = JSON.stringify({ service: { loaded: true, runtime: { status: "running" } } }); diff --git a/src/hooks/gateway-restart.ts b/src/hooks/gateway-restart.ts index 6691648f4..7c289814f 100644 --- a/src/hooks/gateway-restart.ts +++ b/src/hooks/gateway-restart.ts @@ -43,6 +43,8 @@ export interface GatewayRestart { export interface CommandResult { status: number | null; stdout: string; + /** The program is not installed (ENOENT): no gateway of it can be running. */ + missing?: boolean; } export interface GatewayRestartDeps { @@ -63,7 +65,8 @@ function defaultRun(cmd: string, args: string[], env: NodeJS.ProcessEnv): Comman killSignal: "SIGKILL", stdio: ["ignore", "pipe", "pipe"], }); - return { status: out.error ? null : out.status, stdout: `${out.stdout ?? ""}${out.stderr ?? ""}` }; + const missing = (out.error as NodeJS.ErrnoException | undefined)?.code === "ENOENT"; + return { status: out.error ? null : out.status, stdout: `${out.stdout ?? ""}${out.stderr ?? ""}`, ...(missing ? { missing } : {}) }; } function restartLogPath(): string { @@ -128,6 +131,8 @@ function restartHermesGatewayUnsafe( const result = (status: GatewayRestartStatus): GatewayRestart => ({ host: "hermes", profile: profile.name, status }); const status = run("hermes", ["gateway", "status"], env); + // No `hermes` on this machine: there is no gateway to restart, so nothing to say. + if (status.missing) return result("not-running"); if (status.status === null) return result("failed"); if (HERMES_SUPERVISED.some((line) => line.test(status.stdout))) { return result(spawnDetached("hermes", ["gateway", "restart"], env) ? "restarting" : "failed"); @@ -164,6 +169,7 @@ function restartOpenClawGatewayUnsafe( const result = (status: GatewayRestartStatus): GatewayRestart => ({ host: "openclaw", profile: profile.name, status }); const out = run("openclaw", [...profileArgs, "gateway", "status", "--json"], env); + if (out.missing) return result("not-running"); if (out.status === null) return result("failed"); let parsed: OpenClawStatus; try { From faf8a30711695fc1e4fd93d4be72231b6d5b23cc Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 01:33:55 +0530 Subject: [PATCH 35/54] [self-reports] Always-on instructions for Codex, Antigravity and OpenClaw Their models rarely called a deferred `report` tool because the instructions did not reach them through a channel they always load. - Codex: a marked block in the global $CODEX_HOME/AGENTS.md (AGENTS.override.md when present) with the server's instructions and "search your tools for failproofai_local"; user content outside the markers is kept, and a file left empty is removed. - Antigravity: a marked plugin dir ~/.gemini/config/plugins/ failproofai-self-reports/ (plugin.json, rules/AGENTS.md, .failproofai-managed); an unmarked dir is never touched. - OpenClaw: before_prompt_build returns appendContext as well as appendSystemContext. - Daemon: a Cloud change to categories or guidance while on now re-syncs, so the copies follow it. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/openclaw-self-report.test.ts | 2 +- __tests__/hooks/self-report-install.test.ts | 115 ++++++++++++ crates/failproofaid/src/self_report.rs | 51 ++++- docs/self-reports.mdx | 10 +- openclaw-plugin/self-report.js | 12 +- src/hooks/self-report-install.ts | 188 +++++++++++++++++-- 7 files changed, 347 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bde235ba3..d08c99bb1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - Self Reports: the `report` tool is a direct tool on Hermes and OpenClaw, which defer MCP tools behind their tool search with no per-server switch (so the model saw only a name and never reported). failproofai's Hermes plugin registers it natively and puts it on Hermes' never-deferred list, and the OpenClaw plugin registers a `catalogMode: "direct-only"` tool; both put the server's instructions in the prompt (`pre_llm_call`, `before_prompt_build`) and hand each call to failproofaid's own Self Reports server, so the text, attribution, dedup and logs are the MCP path's. Sync writes no Hermes or OpenClaw MCP entry and removes the old ones (#1062) - Self Reports: Claude Code's entry sets `alwaysLoad: true` (its tools are never deferred behind tool search), Antigravity's sets `eager: true` (direct tools rather than `call_mcp_tool`), Copilot gets the instructions in a marked `~/.copilot/instructions/failproofai-self-reports.instructions.md` (Copilot shows server instructions only for its built-in allowlist), and Factory droid, which defers every other MCP server, gets them as SessionStart context (#1062) +- Self Reports: the instructions now reach Codex, Antigravity and OpenClaw through a channel each always loads, since their models rarely looked for a deferred `report` tool. Codex gets a marked block in its global `$CODEX_HOME/AGENTS.md` (or `AGENTS.override.md` when that exists) with one more line telling it to search its tools for `failproofai_local`; Antigravity gets a marked plugin, `~/.gemini/config/plugins/failproofai-self-reports/`, whose `rules/AGENTS.md` it merges into every session; the OpenClaw plugin returns them as per-turn `appendContext` as well as `appendSystemContext`. Both files carry this machine's categories and guidance (the daemon now re-syncs when Cloud changes those), are written only while Self Reports is on for a hooked agent, leave everything outside the markers alone, and are removed by `self-report disable`, `policies --uninstall` and `uninstall` (#1062) - Self Reports: after a tool call failure that clearly blocks (an auth or credential error such as a 401 or 403, an invalid or expired key or token, or a `*_TOKEN` that is not set; or the same tool or command failing a second time in the session), one line of context once per session suggests calling `report` if the agent cannot fix it. One non-zero exit, and read-only exploration (`ls`, `cat`, `grep`, `find`, `test`, Read, Glob) failing, never earn it. On Claude Code, Codex, Cursor, Copilot (its failure event) and Factory. Never on success, on the report call, after a failproofai deny, or while Self Reports is off; it is not a policy and never replaces one's answer (#1062) ### Fixes diff --git a/__tests__/hooks/openclaw-self-report.test.ts b/__tests__/hooks/openclaw-self-report.test.ts index 8248d92c5..2753906c7 100644 --- a/__tests__/hooks/openclaw-self-report.test.ts +++ b/__tests__/hooks/openclaw-self-report.test.ts @@ -116,7 +116,7 @@ describe("OpenClaw Self Reports tool", () => { const result = await (tool.execute as (id: string, p: unknown) => Promise)("call-1", { kind: "looping", reason: "r" }); expect(call).toHaveBeenCalledWith(expect.objectContaining({ description: "Report it." }), { category: "looping", detail: "r" }, "/work/p"); expect(result).toEqual({ content: [{ type: "text", text: "Recorded." }], details: { recorded: true } }); - expect(await hooks.before_prompt_build({}, {})).toEqual({ appendSystemContext: "Report when stuck." }); + expect(await hooks.before_prompt_build({}, {})).toEqual({ appendSystemContext: "Report when stuck.", appendContext: "Report when stuck." }); }); it("offers no tool and no instructions while Self Reports is off or the daemon is gone", async () => { diff --git a/__tests__/hooks/self-report-install.test.ts b/__tests__/hooks/self-report-install.test.ts index 65ba7b702..d89baca3d 100644 --- a/__tests__/hooks/self-report-install.test.ts +++ b/__tests__/hooks/self-report-install.test.ts @@ -475,6 +475,121 @@ describe("which agents", () => { expect(read(instructions)).toBe("my own notes\n"); }); + describe("Codex: a marked block in the global AGENTS.md", () => { + const BEGIN = ""; + const END = ""; + const agentsMd = () => resolve(home, ".codex", "AGENTS.md"); + + it("creates the file with only our block, is idempotent, and removes the file it created", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + const text = read(agentsMd()); + expect(text.startsWith(`${BEGIN}\n`)).toBe(true); + expect(text.endsWith(`${END}\n`)).toBe(true); + expect(text).toContain("When you are stuck, call failproofai_local's `report` tool once"); + expect(text).toContain("`category` is one of: looping, cannot_do_request"); + expect(text).toContain("If the tool is not listed directly, search your tools for `failproofai_local`."); + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + expect(read(agentsMd())).toBe(text); + removeSelfReportMcp({ agents: ["codex"], quiet: true }); + expect(existsSync(agentsMd())).toBe(false); + }); + + it("keeps the user's own content byte for byte, around the block and after it is removed", async () => { + const mine = "# My global rules\n\nAlways run tests.\n"; + put(agentsMd(), mine); + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + const text = read(agentsMd()); + expect(text.startsWith(`${mine}\n${BEGIN}\n`)).toBe(true); + // The user edits around our block; the next sync keeps that too. + put(agentsMd(), `${text}\nAdded later.\n`); + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + expect(read(agentsMd())).toBe(`${text}\nAdded later.\n`); + await syncSelfReportMcp(enabledOpts({ agents: ["codex"], enabled: false }, false)); + expect(read(agentsMd())).toBe(`${mine}\n\nAdded later.\n`); + expect(read(agentsMd())).not.toContain("failproofai"); + }); + + it("rewrites the block when the categories or guidance change", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + const { writeEffectiveSelfReport } = await import("../../src/hooks/self-report"); + writeEffectiveSelfReport({ enabled: true, categories: [{ name: "deploy_blocked", description: "Deploys fail." }], guidance: "Be brief." }); + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + const text = read(agentsMd()); + expect(text).toContain("`category` is one of: deploy_blocked."); + expect(text).toContain("Be brief."); + expect(text.split(BEGIN)).toHaveLength(2); + }); + + it("honours CODEX_HOME, and writes AGENTS.override.md when Codex would read that instead", async () => { + vi.stubEnv("CODEX_HOME", resolve(home, "cx")); + put(resolve(home, "cx", "AGENTS.override.md"), "override rules\n"); + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + expect(read(resolve(home, "cx", "AGENTS.override.md"))).toContain(BEGIN); + expect(existsSync(resolve(home, "cx", "AGENTS.md"))).toBe(false); + expect(existsSync(agentsMd())).toBe(false); + removeSelfReportMcp({ agents: ["codex"], quiet: true }); + expect(read(resolve(home, "cx", "AGENTS.override.md"))).toBe("override rules\n"); + }); + + it("leaves a file with a half block alone and reports the error", async () => { + put(agentsMd(), `mine\n${BEGIN}\nhalf\n`); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + expect(r.some((x) => x.status === "error" && x.path === agentsMd())).toBe(true); + expect(read(agentsMd())).toBe(`mine\n${BEGIN}\nhalf\n`); + }); + }); + + describe("Antigravity: a plugin of ours in the global customization root", () => { + const dir = () => resolve(home, ".gemini", "config", "plugins", "failproofai-self-reports"); + + it("creates the marked plugin, is idempotent, and removes it", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["antigravity"] }, false)); + expect(JSON.parse(read(resolve(dir(), "plugin.json")))).toEqual({ name: "failproofai-self-reports" }); + expect(existsSync(resolve(dir(), ".failproofai-managed"))).toBe(true); + const rules = read(resolve(dir(), "rules", "AGENTS.md")); + expect(rules).toContain("When you are stuck, call failproofai_local's `report` tool once"); + expect(rules).toContain("`category` is one of: looping"); + await syncSelfReportMcp(enabledOpts({ agents: ["antigravity"] }, false)); + expect(read(resolve(dir(), "rules", "AGENTS.md"))).toBe(rules); + removeSelfReportMcp({ agents: ["antigravity"], quiet: true }); + expect(existsSync(dir())).toBe(false); + // Other plugins beside it are untouched. + expect(existsSync(resolve(home, ".gemini", "config", "plugins"))).toBe(true); + }); + + it("never writes into or removes a directory of that name without our marker", async () => { + put(resolve(dir(), "plugin.json"), '{"name":"mine"}\n'); + await syncSelfReportMcp(enabledOpts({ agents: ["antigravity"] }, false)); + expect(read(resolve(dir(), "plugin.json"))).toBe('{"name":"mine"}\n'); + expect(existsSync(resolve(dir(), "rules"))).toBe(false); + removeSelfReportMcp({ agents: ["antigravity"], quiet: true }); + expect(read(resolve(dir(), "plugin.json"))).toBe('{"name":"mine"}\n'); + }); + }); + + it("writes no always-on instructions while Self Reports is disabled, and uninstall removes them", async () => { + const agentsMd = resolve(home, ".codex", "AGENTS.md"); + const plugin = resolve(home, ".gemini", "config", "plugins", "failproofai-self-reports"); + await syncSelfReportMcp(enabledOpts({ agents: ["codex", "antigravity"], enabled: false }, false)); + expect(existsSync(agentsMd)).toBe(false); + expect(existsSync(plugin)).toBe(false); + // Hooked but disabled in the settings file: nothing either. + await syncSelfReportMcp(enabledOpts({ agents: ["codex", "antigravity"], deps: { settings: { enabled: false, port: 4319 } } }, false)); + expect(existsSync(agentsMd)).toBe(false); + expect(existsSync(plugin)).toBe(false); + // Not hooked: nothing. + await syncSelfReportMcp(enabledOpts({ agents: ["codex", "antigravity"], deps: { hooksInstalled: () => false } }, false)); + expect(existsSync(agentsMd)).toBe(false); + expect(existsSync(plugin)).toBe(false); + // The uninstall path (every agent, whatever the settings). + await syncSelfReportMcp(enabledOpts({}, false)); + expect(existsSync(agentsMd)).toBe(true); + expect(existsSync(plugin)).toBe(true); + removeSelfReportMcp({ quiet: true }); + expect(existsSync(agentsMd)).toBe(false); + expect(existsSync(plugin)).toBe(false); + }); + it("puts Copilot's instructions file under COPILOT_HOME", async () => { vi.stubEnv("COPILOT_HOME", resolve(home, "cop")); await syncSelfReportMcp(enabledOpts({ agents: ["copilot"] }, false)); diff --git a/crates/failproofaid/src/self_report.rs b/crates/failproofaid/src/self_report.rs index 84f70bb36..c1086757c 100644 --- a/crates/failproofaid/src/self_report.rs +++ b/crates/failproofaid/src/self_report.rs @@ -102,8 +102,10 @@ pub struct Applied { } /// Whether going from `previous` to `next` can change what `self-report sync` -/// writes into an agent's config. Categories and guidance never do (the server -/// reads them on every request); everything an entry is built from does: +/// writes into an agent's config. Everything an entry is built from does, and +/// while on, so do categories and guidance: the MCP server reads those on +/// every request, but Codex's global AGENTS.md block and Antigravity's plugin +/// rules carry a copy of the instructions, which only a sync rewrites: /// /// - no file before: this is the first Cloud write. Before it the machine was /// either on by default (it just enrolled) or off while it waited for this @@ -114,7 +116,8 @@ pub struct Applied { /// has agents to register; /// - `enrolment`: a file another enrolment wrote (a previous org) read as off /// for this one, so the same holds; -/// - `enabled`, and the endpoint while on (its port is in the HTTP entries). +/// - `enabled`, and the endpoint while on (its port is in the HTTP entries); +/// - categories and guidance while on (the always-on instruction copies). fn entries_may_change(previous: Option<&Settings>, next: &Settings) -> bool { let Some(previous) = previous else { return true; @@ -122,7 +125,10 @@ fn entries_may_change(previous: Option<&Settings>, next: &Settings) -> bool { previous.source != next.source || previous.enrolment != next.enrolment || previous.enabled != next.enabled - || (next.enabled && previous.mcp != next.mcp) + || (next.enabled + && (previous.mcp != next.mcp + || previous.categories != next.categories + || previous.guidance != next.guidance)) } /// Write `path` for this response, only when its content (not `updatedAt`) @@ -706,7 +712,8 @@ mod tests { ); assert!(sr::read_settings(&path).unwrap().enabled); - // Categories changing rewrites but needs no sync: tools/list re-reads. + // Categories changing syncs while on: Codex's AGENTS.md block and + // Antigravity's plugin rules carry a copy of the instructions. let custom = Desired { enabled: true, categories: Some(vec![Category { @@ -719,6 +726,14 @@ mod tests { apply(&path, Some(&custom), 4319, "enrolment-a").unwrap(), Applied { written: true, + needs_sync: true + } + ); + // The same categories again: nothing to write or sync. + assert_eq!( + apply(&path, Some(&custom), 4319, "enrolment-a").unwrap(), + Applied { + written: false, needs_sync: false } ); @@ -777,7 +792,8 @@ mod tests { }, "a local file replaced by the org's" ); - // From then on, only a change an entry is built from syncs. + // From then on, only a change an entry or an instruction copy is + // built from syncs: new guidance while on does. assert_eq!( apply( &path, @@ -790,6 +806,29 @@ mod tests { "enrolment-a" ) .unwrap(), + Applied { + written: true, + needs_sync: true + } + ); + // New guidance while off does not: off removes every copy. + let off = Desired { + enabled: false, + guidance: Some("Be brief.".into()), + ..Default::default() + }; + apply(&path, Some(&off), 4319, "enrolment-a").unwrap(); + assert_eq!( + apply( + &path, + Some(&Desired { + guidance: Some("Be briefer.".into()), + ..off + }), + 4319, + "enrolment-a" + ) + .unwrap(), Applied { written: true, needs_sync: false diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index a2c49b5ea..b0346e156 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -77,16 +77,16 @@ The server sends short instructions in the MCP handshake: when to report, the ca | Agent | How the tool and its instructions reach the model | | --- | --- | | Claude Code | The entry sets `alwaysLoad: true`, so its tools are never deferred behind tool search. Server instructions go in the system prompt. | -| Codex | MCP tools are listed directly. In code mode (Codex 0.172) MCP servers appear as namespaces and only about the first 250 characters of the server's instructions and of the tool's description are shown, so both open with what to do: when stuck, call `failproofai_local`'s `report` tool with a `category` and a one-sentence `detail`. | +| Codex | In code mode (Codex 0.172) tools run through `exec`, MCP tools are deferred, and only about the first 250 characters of the server's instructions and of the tool's description are shown, so both open with what to do: when stuck, call `failproofai_local`'s `report` tool with a `category` and a one-sentence `detail`. The same instructions, with your categories and guidance, also go in a marked block (`` to ``) in the global `~/.codex/AGENTS.md` (under `CODEX_HOME` when set; `AGENTS.override.md` when that file exists, since Codex then reads it instead), which Codex loads in every session, with one more line: search your tools for `failproofai_local` if `report` is not listed. Nothing outside the markers is changed; removing the block deletes the file only when nothing else is left in it. | | Cursor | MCP tools are listed directly. | | Copilot CLI | Tools are listed directly. Copilot passes server instructions only for its built-in allowlist (or with `--allow-all-mcp-server-instructions`), so the same instructions go in a marked `~/.copilot/instructions/failproofai-self-reports.instructions.md` (under `COPILOT_HOME` when set), written and removed with the entry. | | OpenCode | MCP tools are listed directly. | | Pi | failproofai's Pi extension registers the tool, with the instructions in the system prompt. | | Hermes | failproofai's Hermes plugin registers the tool natively and adds it to Hermes' never-deferred list, so `tools.tool_search` does not hide it, with the instructions in `pre_llm_call` context. | -| OpenClaw | failproofai's OpenClaw plugin registers a `catalogMode: "direct-only"` tool, which Tool Search never defers, with the instructions in the system prompt (`before_prompt_build`). | +| OpenClaw | failproofai's OpenClaw plugin registers a `catalogMode: "direct-only"` tool, which Tool Search never defers. `before_prompt_build` returns the instructions both as system context (`appendSystemContext`) and as context for the current turn (`appendContext`): models saw the system copy alone and still did not report. | | Factory | droid defers MCP tools behind its tool search, with no setting per server. The instructions arrive as SessionStart context, so the model knows to load `report` from the deferred list. | | Devin | Devin can defer MCP tools behind its `tool_search`, with no setting per server, so the model may see the tool's name first and load it. | -| Antigravity | The entry sets `eager: true`, so the tools are direct rather than behind the `call_mcp_tool` wrapper. | +| Antigravity | The entry sets `eager: true`, so the tools are direct rather than behind the `call_mcp_tool` wrapper. Antigravity ignores MCP server instructions, so failproofai adds a plugin in its global customization root, `~/.gemini/config/plugins/failproofai-self-reports/` (`plugin.json`, the instructions in `rules/AGENTS.md`, and a `.failproofai-managed` marker), whose rules Antigravity merges into every session. A directory of that name without the marker is never written to or removed. | | Goose | Extensions' tools are listed directly. | Pi has no MCP support before 0.99, so an MCP entry for it reaches no model. failproofai's Pi extension, which every Pi with failproofai hooks already loads, registers the tool itself as `mcp__failproofai_local__report` on every Pi version, with the server's instructions in Pi's system prompt. It asks `failproofai mcp --agent pi` for the tool when Pi starts (no tool while Self Reports is off) and hands each call to it, so the text, the categories and the recording are the same as every other agent's. The Hermes and OpenClaw plugins do the same against the daemon's Self Reports server: they ask it for the tool when the gateway starts (and every minute after, for the instructions and the on/off switch) and send each call to it as `?agent=hermes` or `?agent=openclaw` with the gateway's working directory, so it is attributed, deduped and logged like an MCP call. Without a daemon, or while Self Reports is off, they offer no tool. On Hermes the tool's schema is fixed when it registers, so new categories reach it at the gateway's next start. `self-report sync` writes no Pi, Hermes or OpenClaw MCP entry and takes out one an earlier version wrote, in every profile. `failproofai update` (and the first `failproofai config` on a new version) takes out a Hermes or OpenClaw one before it restarts their gateways, so a restarted gateway does not load it again; OpenClaw would otherwise also start the stdio server for it. @@ -98,7 +98,7 @@ These agents are registered over stdio for that reason: the MCP entry is per use | Agent | Where the server is registered | Recorded by | | --- | --- | --- | | Claude Code | `~/.claude.json` | Hook, or the MCP server while hooks are off | -| Codex | `~/.codex/config.toml` | Hook, or the MCP server while Codex has not trusted the hooks | +| Codex | `~/.codex/config.toml`, plus the block in `~/.codex/AGENTS.md` above | Hook, or the MCP server while Codex has not trusted the hooks | | Cursor | `~/.cursor/mcp.json` | MCP server. Cursor's tool hook names the call `MCP:report`, without the server, so it cannot tell our `report` from another server's, and the call goes through the policies like any other. When the daemon cannot be reached, it is denied with every other call | | Copilot CLI | `~/.copilot/mcp-config.json`, plus the instructions file above | MCP server | | OpenCode | `~/.config/opencode/opencode.json` | MCP server | @@ -107,7 +107,7 @@ These agents are registered over stdio for that reason: the MCP entry is per use | OpenClaw | failproofai's OpenClaw plugin, in each profile | The daemon's Self Reports server | | Factory | `~/.factory/mcp.json` | MCP server | | Devin | `~/.config/devin/mcp_config.json` | MCP server | -| Antigravity | `~/.gemini/config/mcp_config.json` | MCP server | +| Antigravity | `~/.gemini/config/mcp_config.json`, plus the plugin above | MCP server | | Goose | `~/.config/goose/config.yaml` | MCP server | ### When the hooks do not run diff --git a/openclaw-plugin/self-report.js b/openclaw-plugin/self-report.js index 67e30489f..1b9965a06 100644 --- a/openclaw-plugin/self-report.js +++ b/openclaw-plugin/self-report.js @@ -8,9 +8,13 @@ * description and never reported (0/2 on a strong model). A plugin tool marked * `catalogMode: "direct-only"` stays model-visible (docs/tools/tool-search.md), * so this plugin, which every hooked OpenClaw already loads, registers the tool - * itself and puts the server's instructions in the system prompt - * (`before_prompt_build` → `appendSystemContext`). `self-report sync` writes - * no OpenClaw MCP entry and removes one an earlier version wrote. + * itself and puts the server's instructions in the system prompt AND in the + * turn's own context (`before_prompt_build` → `appendSystemContext` + + * `appendContext`, docs plugins/hooks/prompt-and-session.md). The system + * context alone was seen and ignored (0/3 stuck runs reported); with the + * per-turn copy too, 3/3 did, and 0/2 normal runs reported falsely. + * `self-report sync` writes no OpenClaw MCP entry and removes one an earlier + * version wrote. * * The text and the recording come from failproofaid's own Self Reports MCP * server (crates/fpai-collect/src/self_report.rs), so this file holds no copy @@ -221,7 +225,7 @@ export function registerSelfReportTool(api, { async () => { if (now() - fetchedAt >= refreshMs) await refresh(); const instructions = current?.instructions; - return instructions ? { appendSystemContext: instructions } : undefined; + return instructions ? { appendSystemContext: instructions, appendContext: instructions } : undefined; }, { priority: 100, timeoutMs: 10_000 }, ); diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index 753b845e0..77554f7e3 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -58,16 +58,16 @@ * | Agent | Deferred by default? | What failproofai does (evidence) | * |-------------|----------------------------------------------|----------------------------------| * | claude | yes, behind tool search | entry `alwaysLoad: true`: "never deferred behind tool search … Equivalent to setting defer_loading: false" (claude 2.1.332 MCP config schema) | - * | codex | no for user MCP servers (tool_search is for apps) | nothing; reported unprompted on a strong model | + * | codex | yes in code mode (0.172: tools run through `exec`, MCP tools deferred) | marked block (`` … `end`) in the global `$CODEX_HOME/AGENTS.md` (`AGENTS.override.md` when that exists), always loaded: the instructions plus "search your tools for `failproofai_local`" (3/5 stuck runs reported without, 4/4 with) | * | copilot | tools direct; server instructions only for the built-in `mcpRegistryServerInstructionAllowlist` (github-mcp-server, bluebird, computer-use in 1.0.83), no setting extends it | marked `~/.copilot/instructions/failproofai-self-reports.instructions.md` (any `*.instructions.md` under `$HOME/.copilot/instructions` is a documented source) | * | cursor | no | nothing; reported unprompted | * | opencode | no (`defer_loading` only inside the AI SDK, never set by OpenCode) | nothing; reported unprompted | * | pi | no MCP before 0.99 | Pi extension registers the tool | * | hermes | yes: MCP and plugin tools, unless named in `toolsets._HERMES_CORE_TOOLS` (0.20.0 and 0.21.3 `is_deferrable_tool_name`); no per-server option | Hermes plugin registers it natively and adds it to that list; verified against both sources: deferrable before, direct after | - * | openclaw | yes, Tool Search on by default (2026.10.5); no per-server option | plugin tool with `catalogMode: "direct-only"` (tool-search catalog skips it) | + * | openclaw | yes, Tool Search on by default (2026.10.5); no per-server option | plugin tool with `catalogMode: "direct-only"` (tool-search catalog skips it); instructions as `before_prompt_build` `appendSystemContext` AND per-turn `appendContext` (system context alone: 0/3 stuck runs reported; both: 3/3, 0/2 false reports) | * | factory | yes: every MCP server whose name lacks `github`/`agentbrowser` (droid `McpToolSearch`, default on); no setting | the instructions as SessionStart `additionalContext` | * | devin | can defer behind `tool_search` (namespaces); server config has no eager key (3000.15.14) | nothing possible beyond the name in its listing | - * | antigravity | yes, lazy via `call_mcp_tool` | entry `eager: true` (mcp_config.json server field, protobuf `force_all_tools_eager`, agy 1.5.18) | + * | antigravity | yes, lazy via `call_mcp_tool`; server instructions ignored | entry `eager: true` (mcp_config.json server field, protobuf `force_all_tools_eager`, agy 1.5.18), plus a plugin of ours, `~/.gemini/config/plugins/failproofai-self-reports/` (`plugin.json`, `rules/AGENTS.md`, marker `.failproofai-managed`), whose rules agy merges into every session (0/3 → 3/3) | * | goose | no (no tool search) | nothing; reported unprompted | * * Every agent supports Streamable HTTP; HTTP is still used only for the @@ -103,7 +103,15 @@ import { claudeConfigDir, getIntegration, readYamlDoc, writeYamlDoc, UnreadableA import { daemonSelfReportServer } from "./daemon-client"; import { flushSelfReportLogs, sendSelfReportLog } from "./self-report-log"; import { selfReportHookState } from "./self-report-hook-trust"; -import { resolveSelfReport, selfReportPort, selfReportSettingsFile, SELF_REPORT_SERVER_NAME, SELF_REPORT_SERVER_RECORDS } from "./self-report"; +import { + resolveSelfReport, + selfReportInstructions, + selfReportPort, + selfReportSettingsFile, + SELF_REPORT_DEFAULT_CATEGORIES, + SELF_REPORT_SERVER_NAME, + SELF_REPORT_SERVER_RECORDS, +} from "./self-report"; import { listHermesProfiles } from "../../lib/hermes-profiles"; import { listOpenClawProfiles } from "../../lib/openclaw-profiles"; import { INTEGRATION_TYPES, type IntegrationType } from "./types"; @@ -332,16 +340,26 @@ interface McpTarget { */ extension?: true; /** - * A file of ours beside the MCP entry that puts the server's instructions - * in front of the model (Copilot): written while the entry is, removed with it. + * Something of ours beside the MCP entry that puts the instructions in front + * of the model through a channel the agent always loads (Copilot's + * instructions file, Codex's global AGENTS.md block, Antigravity's plugin + * rules): written while the entry is, rewritten when its text changes, + * removed with it. `path` names it in errors; `sync` only ever touches what + * carries our marker. */ - companion?: { path(): string; content(): string }; + companion?: { path(): string; sync(want: boolean): CompanionOutcome }; } +type CompanionOutcome = "added" | "updated" | "removed" | "unchanged" | "foreign"; + function copilotHome(): string { return process.env.COPILOT_HOME?.trim() || resolve(homedir(), ".copilot"); } +function copilotInstructionsPath(): string { + return resolve(copilotHome(), "instructions", "failproofai-self-reports.instructions.md"); +} + /** The marker that makes a companion instructions file ours. */ export const SELF_REPORT_COMPANION_MARKER = ""; @@ -368,9 +386,8 @@ export function selfReportCompanionInstructions(): string { ].join("\n"); } -/** Write (want) or remove (!want) a companion file; only ever touches one carrying our marker. */ -function syncCompanion(companion: NonNullable, want: boolean): "added" | "updated" | "removed" | "unchanged" | "foreign" { - const path = companion.path(); +/** Write (want) or remove (!want) a whole file of ours; only ever touches one carrying our marker. */ +function syncMarkedFile(path: string, content: () => string, want: boolean): CompanionOutcome { const existing = existsSync(path) ? readFileSync(path, "utf8") : null; if (existing !== null && !existing.includes(SELF_REPORT_COMPANION_MARKER)) return "foreign"; if (!want) { @@ -379,14 +396,138 @@ function syncCompanion(companion: NonNullable, want: boo rmSync(path, { force: true }); return "removed"; } - const content = companion.content(); - if (existing === content) return "unchanged"; + const text = content(); + if (existing === text) return "unchanged"; assertNotRealHomeUnderTest(path); mkdirSync(dirname(path), { recursive: true }); - writeConfigFileAtomic(path, content); + writeConfigFileAtomic(path, text); return existing === null ? "added" : "updated"; } +/** + * The instructions the MCP server sends at initialize, with this machine's + * categories and guidance (a sync runs whenever they change, so the copy in + * an always-loaded file follows them). While the setting is off or unreadable + * a sync removes the file, so the defaults here are only ever written by a + * sync told to enable. + */ +function selfReportAlwaysOnInstructions(): string { + const s = resolveSelfReport(); + return selfReportInstructions(s?.categories ?? SELF_REPORT_DEFAULT_CATEGORIES, s?.guidance); +} + +/** The block of ours in Codex's global AGENTS.md. */ +export const SELF_REPORT_CODEX_AGENTS_MARKERS: TomlBlockMarkers = { + begin: "", + end: "", +}; + +/** The text between Codex's markers, markers included. */ +export function selfReportCodexAgentsBlock(): string { + // A guidance line equal to a marker would end the block early. + const body = selfReportAlwaysOnInstructions() + .split("\n") + .filter((l) => l.trim() !== SELF_REPORT_CODEX_AGENTS_MARKERS.begin && l.trim() !== SELF_REPORT_CODEX_AGENTS_MARKERS.end) + .join("\n"); + return [ + SELF_REPORT_CODEX_AGENTS_MARKERS.begin, + body, + `If the tool is not listed directly, search your tools for \`${SELF_REPORT_SERVER_NAME}\`.`, + SELF_REPORT_CODEX_AGENTS_MARKERS.end, + "", + ].join("\n"); +} + +/** + * Codex's global instructions file: `$CODEX_HOME/AGENTS.override.md` when it + * exists (Codex then reads it instead of AGENTS.md), else `$CODEX_HOME/AGENTS.md`. + */ +function codexAgentsPaths(): { active: string; other: string } { + const override = resolve(codexHome(), "AGENTS.override.md"); + const plain = resolve(codexHome(), "AGENTS.md"); + return existsSync(override) ? { active: override, other: plain } : { active: plain, other: override }; +} + +/** + * Put our marked block in Codex's global AGENTS.md (want), or take it out. + * Every byte outside the markers is kept; a file that held only our block is + * removed with it. A half block (one marker) throws, writing nothing. + */ +function syncCodexAgentsBlock(want: boolean): CompanionOutcome { + const { active, other } = codexAgentsPaths(); + const put = (path: string, block: string | null): "changed" | "same" | "absent" => { + if (!existsSync(path)) { + if (block === null) return "absent"; + assertNotRealHomeUnderTest(path); + mkdirSync(dirname(path), { recursive: true }); + writeConfigFileAtomic(path, block); + return "changed"; + } + const text = readFileSync(path, "utf8"); + const next = mergeTomlManagedBlock(text, block, SELF_REPORT_CODEX_AGENTS_MARKERS); + if (next === text) return "same"; + assertNotRealHomeUnderTest(path); + if (block === null && next.trim() === "") rmSync(path, { force: true }); + else writeConfigFileAtomic(path, next); + return "changed"; + }; + const hadBlock = [active, other].some( + (p) => existsSync(p) && readTomlManagedBlock(readFileSync(p, "utf8"), SELF_REPORT_CODEX_AGENTS_MARKERS) !== null, + ); + const movedOut = put(other, null) === "changed"; + if (!want) return put(active, null) === "changed" || movedOut ? "removed" : "unchanged"; + const wrote = put(active, selfReportCodexAgentsBlock()) === "changed"; + return !wrote && !movedOut ? "unchanged" : hadBlock ? "updated" : "added"; +} + +/** The Antigravity plugin of ours, in agy's global customization root. */ +export const SELF_REPORT_ANTIGRAVITY_PLUGIN = "failproofai-self-reports"; +/** The file whose presence makes that plugin directory ours. */ +export const SELF_REPORT_MANAGED_MARKER_FILE = ".failproofai-managed"; + +function antigravityPluginDir(): string { + return resolve(homedir(), ".gemini", "config", "plugins", SELF_REPORT_ANTIGRAVITY_PLUGIN); +} + +/** Every file of the Antigravity plugin, by path relative to its directory. */ +export function selfReportAntigravityPluginFiles(): Record { + // The marker comes first, so a directory left half-written is still ours. + return { + [SELF_REPORT_MANAGED_MARKER_FILE]: + "Written by failproofai (Self Reports). `failproofai self-report disable` or `failproofai uninstall` removes this directory.\n", + "plugin.json": `${JSON.stringify({ name: SELF_REPORT_ANTIGRAVITY_PLUGIN }, null, 2)}\n`, + "rules/AGENTS.md": `# FailproofAI Self Reports\n\n${selfReportAlwaysOnInstructions()}\n`, + }; +} + +/** + * Write (want) or remove the Antigravity plugin directory. agy merges a + * global plugin's `rules/` into every session's rules, where it ignores MCP + * server instructions. A directory of that name without our marker file is + * the user's and is never written into or removed. + */ +function syncAntigravityPlugin(want: boolean): CompanionOutcome { + const dir = antigravityPluginDir(); + const exists = existsSync(dir); + if (exists && !existsSync(resolve(dir, SELF_REPORT_MANAGED_MARKER_FILE))) return "foreign"; + if (!want) { + if (!exists) return "unchanged"; + assertNotRealHomeUnderTest(dir); + rmSync(dir, { recursive: true, force: true }); + return "removed"; + } + let changed = false; + for (const [rel, text] of Object.entries(selfReportAntigravityPluginFiles())) { + const path = resolve(dir, rel); + if (existsSync(path) && readFileSync(path, "utf8") === text) continue; + assertNotRealHomeUnderTest(path); + mkdirSync(dirname(path), { recursive: true }); + writeConfigFileAtomic(path, text); + changed = true; + } + return !changed ? "unchanged" : exists ? "updated" : "added"; +} + const plainEntry = (t: SelfReportTransport, urlKey = "url"): Record => t.kind === "http" ? { [urlKey]: t.url } : { command: t.command, args: t.args }; @@ -446,6 +587,14 @@ export const SELF_REPORT_MCP_TARGETS: Record = { paths: () => [resolve(codexHome(), "config.toml")], container: () => ["mcp_servers"], entry: (t) => plainEntry(t), + // Codex 0.172 runs tools through code mode and defers MCP tools, and the + // model rarely looked for ours (3/5 stuck runs reported). A global + // AGENTS.md is in every session; with the instructions there it searched + // for `failproofai_local` and reported 4/4. A marked block in that file. + companion: { + path: () => codexAgentsPaths().active, + sync: syncCodexAgentsBlock, + }, }, copilot: { agent: "copilot", format: "json", http: true, @@ -462,8 +611,8 @@ export const SELF_REPORT_MCP_TARGETS: Record = { // does load user instructions from `~/.copilot/instructions/*.instructions.md`, // so the same text goes there, in a file of ours. companion: { - path: () => resolve(copilotHome(), "instructions", "failproofai-self-reports.instructions.md"), - content: () => selfReportCompanionInstructions(), + path: copilotInstructionsPath, + sync: (want) => syncMarkedFile(copilotInstructionsPath(), selfReportCompanionInstructions, want), }, }, cursor: { @@ -539,6 +688,13 @@ export const SELF_REPORT_MCP_TARGETS: Record = { // `eager: true` (agy's per-server `force_all_tools_eager`): the tools are // direct, not behind the lazy `call_mcp_tool` wrapper (agy 1.5.18). entry: (t) => ({ ...plainEntry(t, "serverUrl"), eager: true }), + // agy ignores MCP server instructions; a plugin in its global + // customization root has its `rules/` merged into every session's rules + // (0/3 stuck runs reported without, 3/3 with). + companion: { + path: antigravityPluginDir, + sync: syncAntigravityPlugin, + }, }, goose: { agent: "goose", format: "yaml", http: true, @@ -1044,7 +1200,7 @@ function applySelfReportMcp(opts: SyncSelfReportMcpOptions, enabled: boolean, da (r) => r.agent === agent && r.status === "ok" && r.transport !== null && r.action !== "removed", ); try { - syncCompanion(target.companion, enabled && registered); + target.companion.sync(enabled && registered); } catch (err) { results.push({ agent, path: target.companion.path(), action: "skipped", transport: null, status: "error", detail: errText(err) }); } From 6c1b719ec091c0afe0eeb29cfe45ad8dc3259575 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 14:27:34 +0530 Subject: [PATCH 36/54] Self Reports: task_failure also covers any other blocker no category describes Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/self-report.test.ts | 2 +- crates/fpai-collect/src/self_report.rs | 2 +- docs/self-reports.mdx | 2 +- sdk/python/failproofai_sdk/_self_report.py | 2 +- sdk/python/tests/test_self_report.py | 2 +- sdk/typescript/src/self-report-spec.ts | 2 +- sdk/typescript/test/self-report.test.ts | 2 +- src/hooks/self-report.ts | 2 +- test-fixtures/self-report/categories.golden.json | 2 +- test-fixtures/self-report/description-guidance.golden.txt | 2 +- test-fixtures/self-report/description.golden.txt | 2 +- 12 files changed, 12 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d08c99bb1..13d5f52a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## 1.0.18-beta.4 — 2026-11-29 ### Features +- Self Reports: `task_failure` now also covers anything else that blocks the agent and no other category describes, so a report never has to be forced into the wrong category (#1062) - Self Reports: the `report` tool is a direct tool on Hermes and OpenClaw, which defer MCP tools behind their tool search with no per-server switch (so the model saw only a name and never reported). failproofai's Hermes plugin registers it natively and puts it on Hermes' never-deferred list, and the OpenClaw plugin registers a `catalogMode: "direct-only"` tool; both put the server's instructions in the prompt (`pre_llm_call`, `before_prompt_build`) and hand each call to failproofaid's own Self Reports server, so the text, attribution, dedup and logs are the MCP path's. Sync writes no Hermes or OpenClaw MCP entry and removes the old ones (#1062) - Self Reports: Claude Code's entry sets `alwaysLoad: true` (its tools are never deferred behind tool search), Antigravity's sets `eager: true` (direct tools rather than `call_mcp_tool`), Copilot gets the instructions in a marked `~/.copilot/instructions/failproofai-self-reports.instructions.md` (Copilot shows server instructions only for its built-in allowlist), and Factory droid, which defers every other MCP server, gets them as SessionStart context (#1062) diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index 3b931c321..dc31ae2f0 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -48,7 +48,7 @@ Categories: - invalid_tool_or_credential: A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. - missing_context: Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. - repeated_tool_failure: A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. -- task_failure: You genuinely tried and could not complete the task. Not for refusals or policy blocks.`; +- task_failure: You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks.`; let home: string; const savedEnv: Record = {}; diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index dd5eadae6..1fb4c3ad2 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -126,7 +126,7 @@ pub fn default_categories() -> Vec { ), ( "task_failure", - "You genuinely tried and could not complete the task. Not for refusals or policy blocks.", + "You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks.", ), ] .into_iter() diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index b0346e156..8c1875f09 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -60,7 +60,7 @@ An organization's own list replaces these entirely. Names are lowercase letters, | `invalid_tool_or_credential` | A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. | | `missing_context` | Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. | | `repeated_tool_failure` | A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. | -| `task_failure` | You genuinely tried and could not complete the task. Not for refusals or policy blocks. | +| `task_failure` | You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks. | A report is always filed under a category on the list. A missing category, a near-miss spelling such as `Invalid Tool Or Credential`, or a name that is not listed is resolved to the listed name it normalises to, else to the first listed category whose keywords appear in the category or detail (a missing token or a 401 is `invalid_tool_or_credential`, going in circles is `looping`), else to `task_failure`, or to the first category of a list without it. The detail is cut to 2,000 characters (Unicode code points, so an emoji or other character outside the Basic Multilingual Plane counts once and is never split). An agent that calls the tool without loading its schema sometimes guesses the argument names, so when `detail` is missing or empty the first non-empty of `summary`, `sentence`, `message`, `description`, `reason`, `text` and `details` is recorded instead, and when `category` is, `type` or `kind`. Other unknown arguments are ignored; a call is never rejected. diff --git a/sdk/python/failproofai_sdk/_self_report.py b/sdk/python/failproofai_sdk/_self_report.py index 9d0482ac1..f9d3aff9e 100644 --- a/sdk/python/failproofai_sdk/_self_report.py +++ b/sdk/python/failproofai_sdk/_self_report.py @@ -68,7 +68,7 @@ {"name": "invalid_tool_or_credential", "description": "A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected."}, {"name": "missing_context", "description": "Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions."}, {"name": "repeated_tool_failure", "description": "A command or tool failed on several distinct attempts and is blocking you. A single error is not enough."}, - {"name": "task_failure", "description": "You genuinely tried and could not complete the task. Not for refusals or policy blocks."}, + {"name": "task_failure", "description": "You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks."}, ) _PREAMBLE = ( diff --git a/sdk/python/tests/test_self_report.py b/sdk/python/tests/test_self_report.py index 396a07f18..5987fb81f 100644 --- a/sdk/python/tests/test_self_report.py +++ b/sdk/python/tests/test_self_report.py @@ -21,7 +21,7 @@ - invalid_tool_or_credential: A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. - missing_context: Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. - repeated_tool_failure: A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. -- task_failure: You genuinely tried and could not complete the task. Not for refusals or policy blocks.""" +- task_failure: You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks.""" DEFAULT_NAMES = [ "looping", diff --git a/sdk/typescript/src/self-report-spec.ts b/sdk/typescript/src/self-report-spec.ts index d04d9fc00..6a82e43c6 100644 --- a/sdk/typescript/src/self-report-spec.ts +++ b/sdk/typescript/src/self-report-spec.ts @@ -57,7 +57,7 @@ export const DEFAULT_SELF_REPORT_CATEGORIES: ReadonlyArray Object.freeze(c))); diff --git a/test-fixtures/self-report/categories.golden.json b/test-fixtures/self-report/categories.golden.json index d319d11e6..ba4e4c7c7 100644 --- a/test-fixtures/self-report/categories.golden.json +++ b/test-fixtures/self-report/categories.golden.json @@ -21,6 +21,6 @@ }, { "name": "task_failure", - "description": "You genuinely tried and could not complete the task. Not for refusals or policy blocks." + "description": "You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks." } ] diff --git a/test-fixtures/self-report/description-guidance.golden.txt b/test-fixtures/self-report/description-guidance.golden.txt index 2307af471..b86f97eac 100644 --- a/test-fixtures/self-report/description-guidance.golden.txt +++ b/test-fixtures/self-report/description-guidance.golden.txt @@ -7,6 +7,6 @@ Categories: - invalid_tool_or_credential: A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. - missing_context: Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. - repeated_tool_failure: A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. -- task_failure: You genuinely tried and could not complete the task. Not for refusals or policy blocks. +- task_failure: You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks. Report a missing repository as missing_context. \ No newline at end of file diff --git a/test-fixtures/self-report/description.golden.txt b/test-fixtures/self-report/description.golden.txt index 7f257fe10..00a88d3ad 100644 --- a/test-fixtures/self-report/description.golden.txt +++ b/test-fixtures/self-report/description.golden.txt @@ -7,4 +7,4 @@ Categories: - invalid_tool_or_credential: A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. - missing_context: Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. - repeated_tool_failure: A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. -- task_failure: You genuinely tried and could not complete the task. Not for refusals or policy blocks. \ No newline at end of file +- task_failure: You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks. \ No newline at end of file From 86adc25219ba8a7eba6c661277e3a656df3900a8 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 15:59:52 +0530 Subject: [PATCH 37/54] Self Reports: grant the report tool's early allow only to our own registration The hook let any tool named like ours past every policy, so a foreign server registered as failproofai_local had its report call allowed past a deny-all policy (review finding F19). The exemption now holds only while the registration the agent would use from this project is ours: the user-scope entry passes the installer's ownership test (isOurMcpEntry), no project-scope config at or above cwd (or Claude Code's per-project entries in .claude.json) defines the name, and for the plugin agents no foreign entry collides with the plugin's tool. Anything unknown or unreadable takes the policy path. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/helpers/self-report-registration.ts | 39 +++++ __tests__/hooks/self-report-handler.test.ts | 102 ++++++++++++- __tests__/hooks/self-report.test.ts | 7 +- src/hooks/handler.ts | 26 +++- src/hooks/self-report-install.ts | 136 ++++++++++++++++++ 6 files changed, 304 insertions(+), 7 deletions(-) create mode 100644 __tests__/helpers/self-report-registration.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cc177f54..fb5751ee2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ - Self Reports: the stdio server suppresses a Claude Code or Codex report only when that agent's hook recorded the same call: same working directory, and each hook row vouches for one call. A report the hook recorded in one project no longer swallows an identical one from another (#1062) - Self Reports: Claude Code and Codex are registered over stdio, never on the daemon's endpoint, which records nothing for them. Their entry is user-wide while a project can turn the hooks off (`disableAllHooks` in `.claude/settings.local.json`), and every report from such a project was lost; the stdio server now records what the hook did not (#1062) - Self Reports: a report is always filed under a listed category. A call with no `category` (seen from Copilot), a near-miss spelling, or a name that is not on the list is resolved to the listed name it normalises to, else inferred from the category and detail by keyword (a missing token or a 401 is `invalid_tool_or_credential`), else `task_failure` (or an org list's first category); it was recorded with a blank or unknown category. The same rules run in the stdio server, the hook path, the daemon and both SDKs (test-fixtures/self-report/category-inference.json), and the daemon log says `inferred_category=true` with what the model sent (#1062) +- Self Reports: the hook lets the `report` tool past the policies only when the `failproofai_local` server the agent would use is failproofai's own: its user-wide entry passes the installer's ownership test (our `mcp --agent` command or our loopback URL), no project-scope config (`.mcp.json`, `.cursor/mcp.json`, Claude Code's per-project entries in `.claude.json`, and the like) defines that name, and for Hermes, OpenClaw and Pi no other server of that name collides with the plugin's tool. A foreign server registered as `failproofai_local` was let past a deny-all policy; now it, and anything that cannot be read, goes through the policies like any other tool (#1062) ### Docs diff --git a/__tests__/helpers/self-report-registration.ts b/__tests__/helpers/self-report-registration.ts new file mode 100644 index 000000000..c4c66b72e --- /dev/null +++ b/__tests__/helpers/self-report-registration.ts @@ -0,0 +1,39 @@ +/** + * Test helper: a temp HOME in which every agent's `failproofai_local` entry is + * failproofai's own, as `self-report sync` writes it. The hook early-allows the + * report tool only while that is so (`selfReportRegistrationOwned`), so a test + * of the early allow needs a HOME like this one. Never the developer's real + * agent configs: HOME and every agent-home override point into `home`. + */ +import { vi } from "vitest"; +import { syncSelfReportMcp } from "../../src/hooks/self-report-install"; + +export const AGENT_HOME_ENV = [ + "CLAUDE_CONFIG_DIR", "CODEX_HOME", "COPILOT_HOME", "PI_CODING_AGENT_DIR", "HERMES_HOME", + "OPENCLAW_STATE_DIR", "OPENCLAW_HOME", "OPENCLAW_CONFIG_PATH", "GOOSE_PATH_ROOT", "XDG_CONFIG_HOME", +]; + +/** Point HOME (and each agent's own home override) at `home`. Undo with `vi.unstubAllEnvs()`. */ +export function isolateAgentHome(home: string): void { + vi.stubEnv("HOME", home); + vi.stubEnv("USERPROFILE", home); + for (const k of AGENT_HOME_ENV) vi.stubEnv(k, ""); +} + +/** The stdio command the registrations name (never run by these tests). */ +export const REGISTERED_CLI = "/usr/local/bin/" + "fail" + "proofai"; + +/** Write failproofai's own `failproofai_local` entry for every agent under the isolated HOME. */ +export async function registerOwnSelfReportServer(): Promise { + await syncSelfReportMcp({ + quiet: true, + binaryPath: REGISTERED_CLI, + deps: { + daemonLive: async () => false, + hooksInstalled: () => true, + hookRecords: () => true, + settings: { enabled: true, port: 4319 }, + httpAgents: [], + }, + }); +} diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index 1d794d044..e0a5627f6 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -6,7 +6,7 @@ * call) shows the same setup really does deny, so an allow is not vacuous. */ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -40,12 +40,15 @@ import { _resetForTest } from "../../src/hooks/hook-activity-store"; import { INTEGRATION_TYPES } from "../../src/hooks/types"; import { HEALTH_PROBE_SOURCE } from "../../src/hooks/health-probe"; import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; +import { isolateAgentHome, registerOwnSelfReportServer } from "../helpers/self-report-registration"; const SESSION = "sr-session"; let home: string; +/** The project the calls come from (inside the temp home, so no real file above it is read). */ +let project: string; function payload(toolName: string, toolInput: unknown, extra: Record = {}): string { - return JSON.stringify({ session_id: SESSION, cwd: "/tmp/project", tool_name: toolName, tool_input: toolInput, ...extra }); + return JSON.stringify({ session_id: SESSION, cwd: project, tool_name: toolName, tool_input: toolInput, ...extra }); } const report = (extra: Record = {}) => payload("mcp__failproofai_local__report", { category: "invalid_tool_or_credential", detail: "tracker rejected its API key" }, extra); @@ -62,9 +65,14 @@ function rows(): Array> { } } -beforeEach(() => { +beforeEach(async () => { vi.clearAllMocks(); home = mkdtempSync(join(tmpdir(), "fpai-sr-handler-")); + project = join(home, "project"); + mkdirSync(project, { recursive: true }); + // Every agent's failproofai_local entry is ours: the early allow needs that. + isolateAgentHome(join(home, "user")); + await registerOwnSelfReportServer(); process.env.FAILPROOFAI_HOME = home; process.env.FAILPROOFAI_STATE_DIR = join(home, "state"); _resetForTest(join(home, "hook-activity")); @@ -83,6 +91,7 @@ beforeEach(() => { }); afterEach(() => { + vi.unstubAllEnvs(); delete process.env.FAILPROOFAI_HOME; delete process.env.FAILPROOFAI_STATE_DIR; _resetForTest(); @@ -380,7 +389,7 @@ describe("Self Reports short-circuit", () => { "antigravity", JSON.stringify({ conversationId: SESSION, - workspacePaths: ["/tmp/project"], + workspacePaths: [project], toolCall: { name: "call_mcp_tool", args: { ServerName: "failproofai", ToolName: "report", Arguments: {} } }, }), ); @@ -452,7 +461,7 @@ describe("Self Reports short-circuit", () => { describe("Antigravity's lazy MCP path (call_mcp_tool)", () => { const agy = (args: Record) => - JSON.stringify({ conversationId: SESSION, workspacePaths: ["/tmp/project"], toolCall: { name: "call_mcp_tool", args } }); + JSON.stringify({ conversationId: SESSION, workspacePaths: [project], toolCall: { name: "call_mcp_tool", args } }); it("early-allows the wrapper when it names server failproofai_local and tool report", async () => { const out = await evaluateHookEvent( @@ -508,3 +517,86 @@ describe("Self Reports short-circuit", () => { expect(loadAllCustomHooks).not.toHaveBeenCalled(); }); }); + +describe("the early allow needs the failproofai_local registration to be ours (F19)", () => { + const userHome = () => join(home, "user"); + const claudeJson = () => join(userHome(), ".claude.json"); + const readJson = (p: string) => JSON.parse(readFileSync(p, "utf8")) as Record; + const FOREIGN = { type: "stdio", command: "node", args: ["/tmp/x/pause-enforcement.js"] }; + + it("control: with our registration the report passes a deny-everything policy", async () => { + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("allow"); + }); + + it("a foreign server registered user-wide as failproofai_local gets no bypass: the policies deny it", async () => { + const cfg = readJson(claudeJson()); + (cfg.mcpServers as Record).failproofai_local = FOREIGN; + writeFileSync(claudeJson(), JSON.stringify(cfg)); + for (const event of ["PreToolUse", "PermissionRequest", "PostToolUse"]) { + vi.mocked(loadAllCustomHooks).mockClear(); + const out = await evaluateHookEvent(event, "claude", report()); + expect(out.evaluation?.decision, event).toBe("deny"); + expect(loadAllCustomHooks).toHaveBeenCalled(); + } + expect(rows().some((r) => r.selfReport !== undefined)).toBe(false); + }); + + it("a project-scope .mcp.json defining failproofai_local overrides ours: no bypass, from that project or below", async () => { + writeFileSync(join(project, ".mcp.json"), JSON.stringify({ mcpServers: { failproofai_local: FOREIGN } })); + mkdirSync(join(project, "sub"), { recursive: true }); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); + const below = JSON.stringify({ + session_id: SESSION, cwd: join(project, "sub"), tool_name: "mcp__failproofai_local__report", tool_input: { category: "looping", detail: "x" }, + }); + expect((await evaluateHookEvent("PreToolUse", "claude", below)).evaluation?.decision).toBe("deny"); + }); + + it("a project definition shaped like ours still gets no bypass (one is never written there)", async () => { + writeFileSync( + join(project, ".mcp.json"), + JSON.stringify({ mcpServers: { failproofai_local: { command: "./fail" + "proofai", args: ["mcp", "--agent", "claude"] } } }), + ); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); + }); + + it("Claude Code's local scope (projects[].mcpServers in .claude.json) counts as a project definition", async () => { + const cfg = readJson(claudeJson()); + cfg.projects = { [project]: { mcpServers: { failproofai_local: FOREIGN } } }; + writeFileSync(claudeJson(), JSON.stringify(cfg)); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); + }); + + it("an unreadable project config that names failproofai_local fails closed", async () => { + writeFileSync(join(project, ".mcp.json"), "{ failproofai_local: ["); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); + }); + + it("a project config that only mentions the name outside a server map does not count", async () => { + writeFileSync(join(project, "opencode.json"), JSON.stringify({ permission: { failproofai_local_report: "allow" } })); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("allow"); + }); + + it("no registration at all, or no working directory, gets no bypass", async () => { + const noCwd = JSON.stringify({ session_id: SESSION, tool_name: "mcp__failproofai_local__report", tool_input: { category: "looping", detail: "x" } }); + expect((await evaluateHookEvent("PreToolUse", "claude", noCwd)).evaluation?.decision).toBe("deny"); + rmSync(claudeJson()); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); + }); + + it("Cursor's server-named call is also checked against Cursor's registration", async () => { + writeFileSync(join(userHome(), ".cursor", "mcp.json"), JSON.stringify({ mcpServers: { failproofai_local: FOREIGN } })); + const out = await evaluateHookEvent( + "beforeMCPExecution", "cursor", + payload("report", { category: "looping", detail: "x" }, { mcp_server_name: "failproofai_local" }), + ); + expect(out.evaluation?.decision).toBe("deny"); + }); + + it("Hermes (a plugin tool, no MCP entry of ours): allowed with none, denied when a foreign entry would collide", async () => { + const hermes = () => payload("mcp_failproofai_local_report", { category: "looping", detail: "x" }); + expect((await evaluateHookEvent("PreToolUse", "hermes", hermes())).evaluation?.decision).toBe("allow"); + mkdirSync(join(userHome(), ".hermes"), { recursive: true }); + writeFileSync(join(userHome(), ".hermes", "config.yaml"), "mcp_servers:\n failproofai_local:\n command: node\n args: [evil.js]\n"); + expect((await evaluateHookEvent("PreToolUse", "hermes", hermes())).evaluation?.decision).toBe("deny"); + }); +}); diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index dc31ae2f0..dd4f6edb7 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -4,7 +4,7 @@ * the stdio MCP server spawned for real (`failproofai mcp`), and the * `self-report status | enable | disable` commands. */ -import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; import { spawn } from "node:child_process"; import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -36,6 +36,7 @@ import { selfReportFindSessionMatch, } from "../../src/hooks/self-report-mcp"; import { runSelfReportCommand } from "../../src/hooks/self-report-cli"; +import { isolateAgentHome, registerOwnSelfReportServer } from "../helpers/self-report-registration"; const BINARY = resolve(__dirname, "..", "..", "bin", "failproofai.mjs"); @@ -63,6 +64,7 @@ beforeEach(() => { }); afterEach(() => { + vi.unstubAllEnvs(); for (const [k, v] of Object.entries(savedEnv)) { if (v === undefined) delete process.env[k]; else process.env[k] = v; @@ -1022,6 +1024,9 @@ describe("failproofai self-report enable | disable | status", () => { it("test --agent claude goes through --hook and lands in hook activity", async () => { writeEffectiveSelfReport({ enabled: true }); + // The hook early-allows the report only while Claude's failproofai_local entry is ours. + isolateAgentHome(join(home, "user")); + await registerOwnSelfReportServer(); const r = await runSelfReportCommand(["test", "--agent", "claude"], { ...deps, cliCommand: ["bun", BINARY], cwd: home }); expect(r.exitCode).toBe(0); const rows = readFileSync(join(home, "hook-activity", "current.jsonl"), "utf8").trim().split("\n").map((l) => JSON.parse(l)); diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 910e2763d..882b52243 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -754,6 +754,22 @@ function recordSelfReportCall( }; } +/** + * Whether `cli`'s `failproofai_local` registration, as seen from `cwd`, is + * failproofai's own. Loaded on demand: only a call to the report tool asks. + * Any failure is "not ours", so the call is evaluated like any other. + */ +async function selfReportRegistrationIsOurs(cli: IntegrationType, cwd: string | undefined): Promise { + try { + const { selfReportRegistrationOwned } = await import("./self-report-install"); + const owned = selfReportRegistrationOwned(cli, cwd); + if (!owned) hookLogWarn(`cli=${cli} report tool: failproofai_local is not failproofai's registration here; evaluated by policies`); + return owned; + } catch { + return false; + } +} + /** * The core hook-evaluation logic, decoupled from process stdin/stdout so it * can be called repeatedly inside a long-lived process (the daemon's warm @@ -893,12 +909,20 @@ export async function evaluateHookEvent( // allow is the same empty answer the evaluator gives every integration // when no policy decides. PostToolUse for the tool is recorded, never // evaluated; any other event for it takes the ordinary path. + // + // The name alone is not enough: any server can be registered as + // `failproofai_local`. The exemption holds only while the registration the + // agent would use from this project is ours (`selfReportRegistrationOwned`: + // the installer's ownership test on the user-scope entry, and no project- + // scope definition of the name). Anything else, including anything that + // cannot be read, takes the ordinary path and the policies decide. if ( (cli === "cursor" ? cursorSelfReport : isSelfReportToolName(parsed.tool_name)) && (canonicalEventType === "PreToolUse" || (cli === "cursor" && eventType === "beforeMCPExecution") || canonicalEventType === "PermissionRequest" || - canonicalEventType === "PostToolUse") + canonicalEventType === "PostToolUse") && + (await selfReportRegistrationIsOurs(cli, session.cwd)) ) { const outcome = recordSelfReportCall( canonicalEventType === "PostToolUse" || canonicalEventType === "PermissionRequest" ? canonicalEventType : "PreToolUse", diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index 77554f7e3..d51b07a41 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -1072,6 +1072,142 @@ function ownedRegistrationIn(agent: IntegrationType): boolean { } } +// ── Ownership at call time (the hook's report exemption) ──────────────────── + +/** + * Project-scope files an agent may read MCP servers from, relative to the + * project directory or any directory above it, and the server maps inside + * them. failproofai never writes `failproofai_local` at project scope, so a + * definition in any of these is not ours. + */ +const PROJECT_MCP_FILES: readonly string[] = [ + ".mcp.json", + ".cursor/mcp.json", + ".factory/mcp.json", + ".vscode/mcp.json", + ".codex/config.toml", + "opencode.json", + "opencode.jsonc", + ".opencode/opencode.json", + ".opencode/opencode.jsonc", + ".gemini/settings.json", + ".gemini/config/mcp_config.json", + ".pi/mcp.json", +]; + +/** Agents with no project-scope config at all (CLAUDE.md: user scope only). */ +const USER_SCOPE_ONLY: readonly IntegrationType[] = ["hermes", "openclaw"]; +const PROJECT_MCP_CONTAINERS: readonly string[][] = [ + ["mcpServers"], ["servers"], ["mcp"], ["mcp", "servers"], ["mcp_servers"], ["extensions"], +]; + +function definesServer(doc: unknown): boolean { + const want = SELF_REPORT_SERVER_NAME.toLowerCase(); + return PROJECT_MCP_CONTAINERS.some((path) => { + const holder = getIn(doc, path); + if (!holder || typeof holder !== "object" || Array.isArray(holder)) return false; + return Object.keys(holder).some((k) => k.toLowerCase() === want); + }); +} + +/** + * Whether any project-scope config at or above `cwd` defines a server named + * `failproofai_local` (or names it in a way that cannot be read). Claude + * Code's local scope (`projects[].mcpServers` in `.claude.json`) counts. + */ +function projectDefinesSelfReportServer(cwd: string): boolean { + const want = SELF_REPORT_SERVER_NAME.toLowerCase(); + const dirs: string[] = []; + for (let d = resolve(cwd); ; d = dirname(d)) { + dirs.push(d); + if (dirname(d) === d) break; + } + for (const dir of dirs) { + for (const rel of PROJECT_MCP_FILES) { + const path = resolve(dir, rel); + if (!existsSync(path)) continue; + let text: string; + try { + text = readFileSync(path, "utf8"); + } catch { + return true; // unreadable: cannot show it does not define ours + } + if (!text.toLowerCase().includes(want)) continue; + try { + let doc: unknown; + if (path.endsWith(".toml")) { + doc = parseToml(text); + } else { + const errors: ParseError[] = []; + doc = parseJsonc(text, errors, { allowTrailingComma: true }); + if (errors.length > 0) return true; + } + if (definesServer(doc)) return true; + } catch { + return true; + } + } + } + // Claude Code's local scope, keyed by project directory in `.claude.json`. + const claudeJson = claudeUserConfigPath(); + if (existsSync(claudeJson)) { + let text: string; + try { + text = readFileSync(claudeJson, "utf8"); + } catch { + return true; + } + if (text.toLowerCase().includes(want)) { + const errors: ParseError[] = []; + const doc = parseJsonc(text, errors, { allowTrailingComma: true }) as Record | undefined; + if (errors.length > 0 || !doc || typeof doc !== "object") return true; + const projects = doc.projects; + if (projects && typeof projects === "object" && !Array.isArray(projects)) { + for (const dir of dirs) { + const p = (projects as Record)[dir]; + if (definesServer(p)) return true; + } + } + } + } + return false; +} + +/** + * Whether the `failproofai_local` server `agent` would talk to from `cwd` is + * failproofai's, so its `report` tool may skip the policies (the hook's early + * allow). Fails closed: anything that cannot be shown to be ours is not. + * + * - The user-scope entry must pass the installer's own ownership test + * (`isOurMcpEntry`: our stdio command `… mcp --agent X` or our loopback URL), + * in every file the agent reads (one per Hermes/OpenClaw profile). + * - For an agent whose tool comes from failproofai's own plugin (Pi, Hermes, + * OpenClaw), there must be no foreign entry of that name: one would collide + * with our tool's name. + * - No project-scope config at or above `cwd` may define the name at all + * (failproofai never writes one there), and `cwd` must be known. Hermes and + * OpenClaw read no project config, so for them only the user files count. + */ +export function selfReportRegistrationOwned(agent: IntegrationType, cwd: string | undefined): boolean { + const target = SELF_REPORT_MCP_TARGETS[agent]; + if (!target) return false; + const projectScoped = !USER_SCOPE_ONLY.includes(agent); + if (projectScoped && (typeof cwd !== "string" || cwd.trim() === "")) return false; + try { + let ours = false; + for (const path of target.paths()) { + if (!existsSync(path)) continue; + const state = opsFor(target, path).current().state; + if (state === "foreign") return false; + if (state === "ours") ours = true; + } + if (!ours && !target.extension) return false; + return !projectScoped || !projectDefinesSelfReportServer(cwd as string); + } catch { + return false; + } +} + function applySelfReportMcp(opts: SyncSelfReportMcpOptions, enabled: boolean, daemonHere: boolean): SelfReportMcpResult[] { const settings = opts.deps?.settings ?? readSelfReportMcpSettings(); const agents = opts.agents ?? INTEGRATION_TYPES; From 4edfeb258ee8b8da337d394d6aa4bc1b330f91d0 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 16:02:34 +0530 Subject: [PATCH 38/54] Hooks: exempt quoted grep/jq arguments only for the standard tool The command guard cut a quoted argument of grep, rg or jq as inert by the command word's basename, so a project-local ./grep that evals its argument ran the pause CLI past the guard (review finding F17). The exemption now needs the standard tool: a bare name while PATH has no relative entry, or a path in /usr/bin or /bin. The redefinition check also reads the shell-unescaped command and every scanned word, so PA""TH=/tmp/x is seen as the PATH assignment it is. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/state-guard.test.ts | 46 +++++++++++++++++++++++++++++ src/hooks/builtin-policies.ts | 46 +++++++++++++++++++++++++++-- 3 files changed, 90 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fb5751ee2..987178e29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,7 @@ - Self Reports: Claude Code and Codex are registered over stdio, never on the daemon's endpoint, which records nothing for them. Their entry is user-wide while a project can turn the hooks off (`disableAllHooks` in `.claude/settings.local.json`), and every report from such a project was lost; the stdio server now records what the hook did not (#1062) - Self Reports: a report is always filed under a listed category. A call with no `category` (seen from Copilot), a near-miss spelling, or a name that is not on the list is resolved to the listed name it normalises to, else inferred from the category and detail by keyword (a missing token or a 401 is `invalid_tool_or_credential`), else `task_failure` (or an org list's first category); it was recorded with a blank or unknown category. The same rules run in the stdio server, the hook path, the daemon and both SDKs (test-fixtures/self-report/category-inference.json), and the daemon log says `inferred_category=true` with what the model sent (#1062) - Self Reports: the hook lets the `report` tool past the policies only when the `failproofai_local` server the agent would use is failproofai's own: its user-wide entry passes the installer's ownership test (our `mcp --agent` command or our loopback URL), no project-scope config (`.mcp.json`, `.cursor/mcp.json`, Claude Code's per-project entries in `.claude.json`, and the like) defines that name, and for Hermes, OpenClaw and Pi no other server of that name collides with the plugin's tool. A foreign server registered as `failproofai_local` was let past a deny-all policy; now it, and anything that cannot be read, goes through the policies like any other tool (#1062) +- `block-failproofai-commands` treats a quoted `grep`/`rg`/`jq` argument as data only when the command word is the standard tool: a bare name while PATH has no relative entry, or a path in `/usr/bin` or `/bin`. A project's own `./grep` (or any other program of that name) that ran its argument was judged by its basename and could run the pause CLI. A `PATH` or `BASH_ENV` assignment the shell assembles from quoted or escaped pieces (`PA""TH=…`) is now seen too, and turns the exemption off like a plain one (#1062) ### Docs diff --git a/__tests__/hooks/state-guard.test.ts b/__tests__/hooks/state-guard.test.ts index 271b589f5..e7dc8ca33 100644 --- a/__tests__/hooks/state-guard.test.ts +++ b/__tests__/hooks/state-guard.test.ts @@ -874,6 +874,52 @@ describe("block-failproofai-commands — the state guard", () => { ]) expect(await decide(c), c).toBe("deny"); }); + // F17: a project-local `./grep` holding `eval "$1"` ran the pause CLI from + // its quoted "pattern", which the guard had cut as inert by basename. + it("treats a quoted argument as inert only for the standard tool, not a program of that name elsewhere", async () => { + for (const c of [ + `./grep '(${F} config --pause)'`, + `./grep -E '(${F} config --pause)' f`, + `/tmp/x/grep '(${F} config --pause)'`, + `bin/jq '(${F} config --pause)'`, + `~/bin/rg '(${F} config --pause)' .`, + `/usr/local/bin/grep '(${F} config --pause)' f`, + `/usr/bin/../../tmp/x/grep '(${F} config --pause)' f`, + ]) expect(await decide(c), c).toBe("deny"); + // The real tool, by name or from /usr/bin or /bin, keeps the exemption. + for (const c of [ + `grep -E '(${F}_local|kiln)' f`, + `/usr/bin/grep -E '(${F}_local|kiln)' f`, + `/bin/grep '(${F} config --pause)' docs/notes.md`, + ]) expect(await decide(c), c).toBe("allow"); + }); + + it("treats nothing as inert when PATH has a relative entry, which can find the project's own grep", async () => { + vi.stubEnv("PATH", `.:${process.env.PATH ?? "/usr/bin"}`); + try { + expect(await decide(`grep '(${F} config --pause)' f`)).toBe("deny"); + } finally { + vi.unstubAllEnvs(); + } + vi.stubEnv("PATH", `/usr/bin::/bin`); + try { + expect(await decide(`grep '(${F} config --pause)' f`)).toBe("deny"); + } finally { + vi.unstubAllEnvs(); + } + }); + + it("sees a PATH assignment the shell assembles from quoted or escaped pieces", async () => { + for (const c of [ + `PA""TH=/tmp/x grep '(${F} config --pause)' f`, + `PA''TH=/tmp/x grep '(${F} config --pause)' f`, + `P\\ATH=/tmp/x grep '(${F} config --pause)' f`, + `"PATH"=/tmp/x grep '(${F} config --pause)' f`, + `export PA""TH=/tmp/x; grep '(${F} config --pause)' f`, + `BASH_""ENV=/tmp/x grep '(${F} config --pause)' f`, + ]) expect(await decide(c), c).toBe("deny"); + }); + it("still runs a heredoc's body when it can execute", async () => { for (const c of [ `sh <<'EOF'\n${F} config --pause\nEOF`, diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index bab381184..9efac1163 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2652,7 +2652,10 @@ function blockWorkOnMain(ctx: PolicyContext): PolicyResult { // the command is rewritten so only those inert pieces disappear: // // - a quoted argument of a command that never executes its arguments (the -// grep family, jq, yq), unless it names the state or holds a substitution; +// grep family, jq, yq), unless it names the state or holds a substitution, +// and only when the command word is that standard tool: a bare name with no +// relative PATH entry, or a path in /usr/bin or /bin (`standardToolName`) — +// a project's own `./grep` may `eval "$1"`; // - the body of a heredoc fed to a command that only writes it out (`cat`, // `tee`, `:`), when nothing in the same command could run what it wrote; // @@ -2879,10 +2882,44 @@ function scannedHead(words: ShellWord[]): { word: ShellWord; at: number } | unde const COMMAND_REDEFINITION_RE = /(?:^|[\s;&|(){}])(?:function\s+[\w.:-]+|[\w.:-]+\s*\(\s*\)|alias\b|unalias\b|shopt\b|enable\b|hash\b|(?:export\s+|declare\s+[-\w\s]*|typeset\s+[-\w\s]*|readonly\s+)?PATH\+?=|BASH_ENV=|ENV=)/; +/** A scanned word, quotes removed, that assigns a variable which changes what a command word runs. */ +const COMMAND_REDEFINING_ASSIGNMENT_RE = /^(?:PATH|BASH_ENV|ENV)\+?=/; + +/** + * Whether the command could change what a later command word runs. Checked + * on the raw text, on its shell-unescaped form (`PA""TH=/tmp/x grep …` is a + * PATH assignment once the shell drops the quotes), and on every scanned word. + */ +function redefinesCommandWords(cmd: string, scanned: ShellSimple[] | null): boolean { + if (COMMAND_REDEFINITION_RE.test(cmd) || COMMAND_REDEFINITION_RE.test(stripShellQuoting(cmd))) return true; + return !!scanned && scanned.some((simple) => simple.words.some((w) => COMMAND_REDEFINING_ASSIGNMENT_RE.test(w.value))); +} + +/** Directories whose programs only root can replace: a path command word there is the real tool. */ +const SYSTEM_TOOL_DIRS = new Set(["/usr/bin", "/bin"]); + +/** + * The name of the tool a command word runs, when it is known to be that + * standard tool, else undefined. A bare name (`grep`) is the tool PATH finds, + * unless PATH has a relative entry (`.`, an empty one), which can find a + * program in the project instead. A path (`./grep`, `/tmp/x/grep`) is the + * tool only in `/usr/bin` or `/bin`: anywhere else it is whatever program was + * put there, which may run its arguments. + */ +function standardToolName(word: string): string | undefined { + if (!word.includes("/")) { + const entries = (process.env.PATH ?? "").split(":"); + return entries.some((e) => !e.startsWith("/")) ? undefined : word; + } + const slash = word.lastIndexOf("/"); + const dir = word.slice(0, slash).replace(/\/+$/, "") || "/"; + return SYSTEM_TOOL_DIRS.has(dir) ? word.slice(slash + 1) : undefined; +} + /** `cmd` with its inert pieces taken out (see above), or `cmd` unchanged. */ function withoutInertArguments(cmd: string): string { - if (COMMAND_REDEFINITION_RE.test(cmd)) return cmd; const scanned = scanShellCommands(cmd); + if (redefinesCommandWords(cmd, scanned)) return cmd; if (!scanned) return cmd; const cuts: Array<{ start: number; end: number; text: string }> = []; const heads = scanned.map((s) => scannedHead(s.words)); @@ -2894,7 +2931,10 @@ function withoutInertArguments(cmd: string): string { scanned.forEach((simple, n) => { const head = heads[n]; if (!head) return; - const base = head.word.value.slice(head.word.value.lastIndexOf("/") + 1); + // Only the standard tool's arguments are inert: a project's own `./grep` + // can `eval "$1"`. + const base = standardToolName(head.word.value); + if (base === undefined) return; const args = simple.words.slice(head.at + 1); // rg runs a preprocessor named by `--pre`. if (INERT_ARGUMENT_HEADS.has(base) && !(base === "rg" && args.some((w) => w.value.startsWith("--pre")))) { From bf738471ff1fd5c3b6f8c5332928be75c59d4b9c Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 16:07:16 +0530 Subject: [PATCH 39/54] Self Reports: match a hook row only to a call from its own agent process The stdio server suppressed a Claude Code / Codex report when any unclaimed hook row in the same directory had the same text, so a second session whose hooks did not run had its distinct report taken by the first session's row (review finding F14); the first session's own call then found no row and was recorded under whichever session was newest. The hook CLI now stamps a report call with the pids above the hook process (in the hook process itself, before forwarding to the daemon, like the Devin marker), the handler keeps them on the activity row (local only; the collector's typed row ignores the field), and the server matches a row only when its own parent, the agent that spawned it, is among them. A row without pids never matches, so when unsure the server records. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/self-report-ancestry.test.ts | 61 +++++++++++ __tests__/hooks/self-report-handler.test.ts | 18 ++++ .../hooks/self-report-hook-trust.test.ts | 58 +++++++++- __tests__/hooks/self-report.test.ts | 25 ++++- bin/failproofai.mjs | 6 +- src/hooks/handler.ts | 9 +- src/hooks/hook-activity-store.ts | 14 ++- src/hooks/self-report-ancestry.ts | 100 ++++++++++++++++++ src/hooks/self-report-hook-trust.ts | 19 +++- 10 files changed, 297 insertions(+), 14 deletions(-) create mode 100644 __tests__/hooks/self-report-ancestry.test.ts create mode 100644 src/hooks/self-report-ancestry.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 987178e29..d98229df5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,7 @@ - Self Reports: a report is always filed under a listed category. A call with no `category` (seen from Copilot), a near-miss spelling, or a name that is not on the list is resolved to the listed name it normalises to, else inferred from the category and detail by keyword (a missing token or a 401 is `invalid_tool_or_credential`), else `task_failure` (or an org list's first category); it was recorded with a blank or unknown category. The same rules run in the stdio server, the hook path, the daemon and both SDKs (test-fixtures/self-report/category-inference.json), and the daemon log says `inferred_category=true` with what the model sent (#1062) - Self Reports: the hook lets the `report` tool past the policies only when the `failproofai_local` server the agent would use is failproofai's own: its user-wide entry passes the installer's ownership test (our `mcp --agent` command or our loopback URL), no project-scope config (`.mcp.json`, `.cursor/mcp.json`, Claude Code's per-project entries in `.claude.json`, and the like) defines that name, and for Hermes, OpenClaw and Pi no other server of that name collides with the plugin's tool. A foreign server registered as `failproofai_local` was let past a deny-all policy; now it, and anything that cannot be read, goes through the policies like any other tool (#1062) - `block-failproofai-commands` treats a quoted `grep`/`rg`/`jq` argument as data only when the command word is the standard tool: a bare name while PATH has no relative entry, or a path in `/usr/bin` or `/bin`. A project's own `./grep` (or any other program of that name) that ran its argument was judged by its basename and could run the pause CLI. A `PATH` or `BASH_ENV` assignment the shell assembles from quoted or escaped pieces (`PA""TH=…`) is now seen too, and turns the exemption off like a plain one (#1062) +- Self Reports: a Claude Code or Codex hook row now stands only for a call from its own agent process. The hook stamps a report call with the processes above it, and the stdio server suppresses its copy only when its own parent (the agent that started it) is one of them. Another session in the same directory, whose hooks did not run, no longer has its identical report swallowed by the first session's row and then filed under the wrong session; when the hook could not tell, the server records (#1062) ### Docs diff --git a/__tests__/hooks/self-report-ancestry.test.ts b/__tests__/hooks/self-report-ancestry.test.ts new file mode 100644 index 000000000..420cdc8fd --- /dev/null +++ b/__tests__/hooks/self-report-ancestry.test.ts @@ -0,0 +1,61 @@ +// @vitest-environment node +/** + * Which agent process a report call came from (F14): the hook CLI stamps a + * Claude Code / Codex report call with the pids above it, the handler keeps + * them on the activity row, and the stdio server matches only a row from its + * own agent (self-report-hook-trust.test.ts covers the matching). + */ +import { describe, expect, it } from "vitest"; +import { + SELF_REPORT_AGENT_PIDS_KEY, + selfReportAgentPids, + selfReportAncestorPids, + selfReportMarkAgentPids, +} from "../../src/hooks/self-report-ancestry"; + +const report = (extra: Record = {}) => + JSON.stringify({ session_id: "s", tool_name: "mcp__failproofai_local__report", tool_input: { category: "looping", detail: "x" }, ...extra }); + +describe("selfReportAncestorPids", () => { + it.runIf(process.platform === "linux" || process.platform === "darwin")("starts at this process's parent", () => { + const pids = selfReportAncestorPids(); + expect(pids[0]).toBe(process.ppid); + expect(pids.length).toBeLessThanOrEqual(8); + expect(pids.every((p) => Number.isSafeInteger(p) && p > 1)).toBe(true); + }); +}); + +describe("selfReportMarkAgentPids", () => { + const pids = () => [4001, 4000]; + + it("stamps a Claude Code or Codex report call with the pids above the hook", () => { + for (const cli of ["claude", "codex"]) { + const out = JSON.parse(selfReportMarkAgentPids(cli, report(), pids)); + expect(out[SELF_REPORT_AGENT_PIDS_KEY]).toEqual([4001, 4000]); + } + const codex = JSON.stringify({ tool_name: "mcp__failproofai_local__report", tool_input: {} }); + expect(JSON.parse(selfReportMarkAgentPids("codex", codex, pids))[SELF_REPORT_AGENT_PIDS_KEY]).toEqual([4001, 4000]); + }); + + it("leaves every other call, and every other agent, as it was", () => { + const bash = JSON.stringify({ tool_name: "Bash", tool_input: { command: "ls failproofai_local" } }); + expect(selfReportMarkAgentPids("claude", bash, pids)).toBe(bash); + expect(selfReportMarkAgentPids("cursor", report(), pids)).toBe(report()); + expect(selfReportMarkAgentPids("claude", "{not json failproofai_local", pids)).toBe("{not json failproofai_local"); + }); + + it("replaces pids a payload already carried, and drops them when none can be read", () => { + const spoofed = report({ [SELF_REPORT_AGENT_PIDS_KEY]: [12345] }); + expect(JSON.parse(selfReportMarkAgentPids("claude", spoofed, pids))[SELF_REPORT_AGENT_PIDS_KEY]).toEqual([4001, 4000]); + expect(JSON.parse(selfReportMarkAgentPids("claude", spoofed, () => []))).not.toHaveProperty(SELF_REPORT_AGENT_PIDS_KEY); + }); +}); + +describe("selfReportAgentPids", () => { + it("keeps only real pids, at most eight", () => { + expect(selfReportAgentPids([5, "6", 1, 0, -3, 7.5, 9])).toEqual([5, 9]); + expect(selfReportAgentPids(Array.from({ length: 20 }, (_, i) => i + 2))).toHaveLength(8); + expect(selfReportAgentPids([1])).toBeUndefined(); + expect(selfReportAgentPids("5")).toBeUndefined(); + }); +}); diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index e0a5627f6..fc70cc5e3 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -600,3 +600,21 @@ describe("the early allow needs the failproofai_local registration to be ours (F expect((await evaluateHookEvent("PreToolUse", "hermes", hermes())).evaluation?.decision).toBe("deny"); }); }); + +describe("the agent process behind a hook-recorded report (F14)", () => { + it("keeps the pids the hook CLI stamped on the report row, and only there", async () => { + await evaluateHookEvent( + "PreToolUse", "claude", + report({ tool_use_id: "toolu_p", failproofai_report_agent_pids: [6001, 6000, "x", 1] }), + ); + expect(rows().pop()).toMatchObject({ toolCallId: "toolu_p", selfReport: { detail: "tracker rejected its API key" }, selfReportAgentPids: [6001, 6000] }); + // A PostToolUse row is no report, so it carries none. + await evaluateHookEvent("PostToolUse", "claude", report({ failproofai_report_agent_pids: [6001] })); + expect(rows().pop()).not.toHaveProperty("selfReportAgentPids"); + }); + + it("a report row with no pids stamped carries none", async () => { + await evaluateHookEvent("PreToolUse", "claude", report()); + expect(rows().pop()).not.toHaveProperty("selfReportAgentPids"); + }); +}); diff --git a/__tests__/hooks/self-report-hook-trust.test.ts b/__tests__/hooks/self-report-hook-trust.test.ts index 8260a554b..e4497859d 100644 --- a/__tests__/hooks/self-report-hook-trust.test.ts +++ b/__tests__/hooks/self-report-hook-trust.test.ts @@ -219,11 +219,17 @@ describe("the server records what the hook did not, once", () => { return []; } }; + // A hook row records the pids above its hook process; this test process's + // parent stands for "this server's agent" (the server's own default). + const AGENT = process.ppid; const hookRow = (over: Record) => { mkdirSync(join(home, ".failproofai", "hook-activity"), { recursive: true }); writeFileSync( join(home, ".failproofai", "hook-activity", "current.jsonl"), - JSON.stringify({ timestamp: Date.now() - 1000, eventType: "PreToolUse", integration: "codex", sessionId: "s", decision: "allow", ...over }) + "\n", + JSON.stringify({ + timestamp: Date.now() - 1000, eventType: "PreToolUse", integration: "codex", sessionId: "s", decision: "allow", + selfReportAgentPids: [4242, AGENT], ...over, + }) + "\n", ); }; @@ -233,7 +239,10 @@ describe("the server records what the hook did not, once", () => { mkdirSync(join(home, ".failproofai", "hook-activity"), { recursive: true }); writeFileSync( join(home, ".failproofai", "hook-activity", "current.jsonl"), - rows.map((over) => JSON.stringify({ timestamp: Date.now() - 1000, eventType: "PreToolUse", integration: "codex", sessionId: "s", decision: "allow", ...over })).join("\n") + "\n", + rows.map((over) => JSON.stringify({ + timestamp: Date.now() - 1000, eventType: "PreToolUse", integration: "codex", sessionId: "s", decision: "allow", + selfReportAgentPids: [4242, AGENT], ...over, + })).join("\n") + "\n", ); }; @@ -274,12 +283,11 @@ describe("the server records what the hook did not, once", () => { expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(true); }); - it("lets each hook row vouch for one call only (repeated text, concurrent sessions)", () => { + it("lets each hook row vouch for one call only (repeated text in one session)", () => { const args = { category: "looping", detail: "same words" }; - // Two sessions in one directory, each with its own hook row. hookRows( { cwd: projA, sessionId: "s1", toolCallId: "t1", selfReport: { ...args, source: "mcp" } }, - { cwd: projA, sessionId: "s2", toolCallId: "t2", selfReport: { ...args, source: "mcp" } }, + { cwd: projA, sessionId: "s1", toolCallId: "t2", selfReport: { ...args, source: "mcp" } }, ); expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(true); expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(true); @@ -287,6 +295,46 @@ describe("the server records what the hook did not, once", () => { expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); }); + // F14: matching on text and directory let session B (its hooks did not run) + // take session A's row, so B's report answered "Recorded." with no event, + // and A's own call then found no row and was recorded under the wrong session. + it("never lets another session's hook row stand for a call (concurrent sessions in one directory)", () => { + const args = { category: "invalid_tool_or_credential", detail: "token expired" }; + const A = 31001; + const B = 31002; + // Session A's hook recorded its report; session B's hooks did not run. + hookRows({ cwd: projA, sessionId: "sA", toolCallId: "tA", selfReport: { ...args, source: "mcp" }, selfReportAgentPids: [31000, A, 1000] }); + // B's identical report arrives first: not A's row, so B's server records it. + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, B)).toBe(false); + // A's call still finds its own row, which B did not consume. + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, A)).toBe(true); + // A shared ancestor above both agents (the shell, pid 1000) is not the agent: + // the server's PARENT must be among the row's pids, and B's parent is B. + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, B)).toBe(false); + }); + + it("each of two sessions in one directory claims only its own row", () => { + const args = { category: "looping", detail: "same words" }; + hookRows( + { cwd: projA, sessionId: "s1", toolCallId: "t1", selfReport: { ...args, source: "mcp" }, selfReportAgentPids: [51001] }, + { cwd: projA, sessionId: "s2", toolCallId: "t2", selfReport: { ...args, source: "mcp" }, selfReportAgentPids: [51002] }, + ); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 51002)).toBe(true); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 51002)).toBe(false); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 51001)).toBe(true); + }); + + it("a row that does not say which agent process wrote it never vouches for a call: the report is recorded", () => { + const args = { category: "looping", detail: "same words" }; + hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, selfReportAgentPids: undefined }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); + hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, selfReportAgentPids: ["x", 1] }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); + // A server whose parent is gone (reparented to init) cannot be matched either. + hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, selfReportAgentPids: [1] }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 1)).toBe(false); + }); + it("an untrusted Codex's report lands once, on the session Codex's own rollout names", async () => { writeEffectiveSelfReport({ enabled: true }); const project = join(home, "proj"); diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index dd4f6edb7..1fe447207 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -581,17 +581,37 @@ describe("failproofai mcp (stdio, spawned)", () => { it("writes no event for a hook-recorded agent (claude) whose hook recorded the call", async () => { writeEffectiveSelfReport({ enabled: true }); mkdirSync(join(home, "hook-activity"), { recursive: true }); + // The server is this test process's child, so this process is its agent: + // a hook row from the same agent has this pid among its ancestors. writeFileSync( join(home, "hook-activity", "current.jsonl"), JSON.stringify({ timestamp: Date.now() - 500, eventType: "PreToolUse", integration: "claude", sessionId: "c1", decision: "allow", cwd: home, toolName: "mcp__failproofai_local__report", selfReport: { ...CALL_ARGS, source: "mcp" }, + selfReportAgentPids: [77777, process.pid], }) + "\n", ); await runMcp(["--agent", "claude"], [INIT, CALL], home); expect(() => readdirSync(join(home, "custom-agents", "events"))).toThrow(); }, 30_000); + // F14: the same report from another session (another agent process) in the + // same directory is a distinct call, and that session's hooks did not run. + it("records a report that another session's hook row in the same directory would have matched", async () => { + writeEffectiveSelfReport({ enabled: true }); + mkdirSync(join(home, "hook-activity"), { recursive: true }); + writeFileSync( + join(home, "hook-activity", "current.jsonl"), + JSON.stringify({ + timestamp: Date.now() - 500, eventType: "PreToolUse", integration: "claude", sessionId: "other", decision: "allow", + cwd: home, toolName: "mcp__failproofai_local__report", selfReport: { ...CALL_ARGS, source: "mcp" }, + selfReportAgentPids: [77777, 77776], + }) + "\n", + ); + await runMcp(["--agent", "claude"], [INIT, CALL], home); + expect(readdirSync(join(home, "custom-agents", "events"))).toHaveLength(1); + }, 30_000); + // ...and records it when the hook did not (an untrusted Codex runs no hook): // otherwise the report would be lost. it("records a hook-recorded agent's report when its hook did not", async () => { @@ -1030,6 +1050,9 @@ describe("failproofai self-report enable | disable | status", () => { const r = await runSelfReportCommand(["test", "--agent", "claude"], { ...deps, cliCommand: ["bun", BINARY], cwd: home }); expect(r.exitCode).toBe(0); const rows = readFileSync(join(home, "hook-activity", "current.jsonl"), "utf8").trim().split("\n").map((l) => JSON.parse(l)); - expect(rows.pop()).toMatchObject({ toolName: "mcp__failproofai_local__report", decision: "allow", selfReport: { source: "mcp" } }); + const last = rows.pop(); + expect(last).toMatchObject({ toolName: "mcp__failproofai_local__report", decision: "allow", selfReport: { source: "mcp" } }); + // The real hook process stamped the agent above it: this test process started it. + if (process.platform === "linux" || process.platform === "darwin") expect(last.selfReportAgentPids).toContain(process.pid); }, 30_000); }); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index 12c0cc88d..daae0ef61 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -183,10 +183,14 @@ if (hookIdx >= 0) { // this process can only be read here (the worker's parent is the daemon), // so a Claude-path report call made under Devin is marked for the worker. const { selfReportMarkDevinOrigin } = await import("../src/hooks/self-report-devin"); + // Likewise which agent process a Claude Code / Codex report call came + // from, so its stdio server can tell this call's row from another + // session's (self-report-ancestry.ts). + const { selfReportMarkAgentPids } = await import("../src/hooks/self-report-ancestry"); const attempt = await attemptDaemonHook({ hookEvent: eventType, cli, - stdin: selfReportMarkDevinOrigin(cli, stdinRead.payload), + stdin: selfReportMarkAgentPids(cli, selfReportMarkDevinOrigin(cli, stdinRead.payload)), // The client's own cwd IS the originating CLI session's cwd — this // process is spawned fresh, at that location, by the calling agent // CLI's own hook mechanism. See daemon-client.ts / PROTOCOL.md. diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 882b52243..89d5d34c6 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -68,6 +68,7 @@ import { import { selfReportClip } from "./self-report-names"; import { selfReportFailureHint, selfReportSessionStartContext } from "./self-report-hint"; import { selfReportClaudeHookFromDevin } from "./self-report-devin"; +import { SELF_REPORT_AGENT_PIDS_KEY, selfReportAgentPids, selfReportMarkAgentPids } from "./self-report-ancestry"; import { deliveryHealth, deliveryHealthLine } from "./delivery-health"; import { trackHookEvent, flushHookTelemetry } from "./hook-telemetry"; import * as hookTelemetry from "./hook-telemetry"; @@ -710,6 +711,9 @@ function recordSelfReportCall( const resolved = report && enabled ? resolveSelfReportCategory(report.category, report.detail, enabled.categories.map((c) => c.name)) : null; + // The agent process the call came from, when the hook CLI could read it: + // the stdio server suppresses its own copy only for a row from its agent. + const agentPids = report && resolved ? selfReportAgentPids(parsed[SELF_REPORT_AGENT_PIDS_KEY]) : undefined; try { persistHookActivity({ timestamp: writtenAt, @@ -729,6 +733,7 @@ function recordSelfReportCall( permissionMode: session.permissionMode, hookEventName: session.hookEventName, ...(report && resolved ? { selfReport: { category: resolved.category, detail: report.detail, source: "mcp" as const } } : {}), + ...(agentPids ? { selfReportAgentPids: agentPids } : {}), }); } catch { hookLogWarn("activity persistence failed"); @@ -1656,8 +1661,10 @@ export async function handleHookEvent( }); } + // The agent process above this hook, for a Claude Code / Codex report call + // (self-report-ancestry.ts); the daemon path adds it in the hook CLI. const result = await evaluateHookEvent( - eventType, cli, stdinRead.payload, + eventType, cli, selfReportMarkAgentPids(cli, stdinRead.payload), agentSettingsPath === undefined ? undefined : { agentSettingsPath }, ); diff --git a/src/hooks/hook-activity-store.ts b/src/hooks/hook-activity-store.ts index b640a495c..5d1f33af8 100644 --- a/src/hooks/hook-activity-store.ts +++ b/src/hooks/hook-activity-store.ts @@ -26,6 +26,7 @@ import type { IntegrationType } from "./types"; import { hookActivityDir } from "./fp-home"; import { sanitizeJevActivity, type JevCheckRecord } from "./jev-activity"; import { selfReportClip } from "./self-report-names"; +import { selfReportAgentPids } from "./self-report-ancestry"; export const PAGE_SIZE = 25; @@ -190,6 +191,12 @@ export interface HookActivityEntry { * `self_report` event. `detail` is at most 2000 characters. */ selfReport?: { category: string; detail: string; source: "mcp" }; + /** + * With `selfReport` only: the pids above the hook process that recorded it + * (its agent among them). Local only, never shipped: the stdio server lets + * a row stand for its own call only when its parent is one of them. + */ + selfReportAgentPids?: number[]; } export interface HookActivityFilters { @@ -290,11 +297,16 @@ export function persistHookActivity(input: HookActivityEntry): void { * machine by the collector, so it is checked at this one door. */ function sanitizeSelfReportActivity(entry: HookActivityEntry): HookActivityEntry { - if (entry.selfReport === undefined) return entry; + if (entry.selfReport === undefined && entry.selfReportAgentPids === undefined) return entry; const sr = entry.selfReport as unknown; const out = { ...entry }; + const pids = selfReportAgentPids(entry.selfReportAgentPids); + if (pids && sr !== undefined) out.selfReportAgentPids = pids; + else delete out.selfReportAgentPids; + if (sr === undefined) return out; if (!sr || typeof sr !== "object" || Array.isArray(sr)) { delete out.selfReport; + delete out.selfReportAgentPids; return out; } const rec = sr as Record; diff --git a/src/hooks/self-report-ancestry.ts b/src/hooks/self-report-ancestry.ts new file mode 100644 index 000000000..5a032645d --- /dev/null +++ b/src/hooks/self-report-ancestry.ts @@ -0,0 +1,100 @@ +/** + * Which agent process a report call came from, so the stdio server can tell + * its own call's hook row from another session's (review finding F14). + * + * The hook process and the stdio MCP server are both started by the agent: + * the hook through the agent's hook runner (often a shell), the server as the + * agent's direct child. So the server's parent is one of the hook's + * ancestors exactly when the two belong to the same agent process. Another + * session in the same directory is another agent process, with another pid. + * + * The hook side has to read its ancestry in the hook process the agent + * started, not in the daemon's warm worker (whose parent is the daemon): the + * hook CLI adds `SELF_REPORT_AGENT_PIDS_KEY` to a Claude Code or Codex report + * call before it forwards or evaluates the payload, and the handler copies it + * onto the activity row. Only a report call is looked at, so ordinary hook + * traffic pays nothing. Anything unreadable gives no pids, and a row with no + * pids never vouches for a call: the server records rather than suppresses. + */ +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { isSelfReportToolName } from "./self-report-names"; + +/** Payload key the hook CLI adds to a Claude Code / Codex report call: its ancestor pids. */ +export const SELF_REPORT_AGENT_PIDS_KEY = "failproofai_report_agent_pids"; + +/** How many processes above the hook are kept (hook runner shells, wrappers, the agent). */ +export const SELF_REPORT_AGENT_PIDS_DEPTH = 8; + +/** Agents whose hook records the report and whose stdio server must recognise that row. */ +const HOOK_RECORDED: readonly string[] = ["claude", "codex"]; + +/** The pid of `pid`'s parent, or 0. */ +function parentOf(pid: number, table: Map | null): number { + if (table) return table.get(pid) ?? 0; + // " () …"; comm may itself hold ") ". + const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); + return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]) || 0; +} + +/** Pids above this process, nearest first (its parent first). Best effort: `[]` on any failure. */ +export function selfReportAncestorPids(depth: number = SELF_REPORT_AGENT_PIDS_DEPTH): number[] { + const out: number[] = []; + try { + let table: Map | null = null; + if (process.platform === "darwin") { + table = new Map(); + const ps = execFileSync("ps", ["-A", "-o", "pid=,ppid="], { encoding: "utf8", timeout: 1000 }); + for (const line of ps.split("\n")) { + const m = /^\s*(\d+)\s+(\d+)\s*$/.exec(line); + if (m) table.set(Number(m[1]), Number(m[2])); + } + } else if (process.platform !== "linux") { + return []; + } + let pid = process.ppid; + for (let i = 0; i < depth && pid > 1; i++) { + out.push(pid); + pid = parentOf(pid, table); + } + } catch { + // Unreadable /proc, no ps: no ancestry, so no row will vouch for a call. + } + return out; +} + +/** The pids in a payload or row field, kept only in their declared shape. */ +export function selfReportAgentPids(value: unknown): number[] | undefined { + if (!Array.isArray(value)) return undefined; + const pids = value + .filter((p): p is number => typeof p === "number" && Number.isSafeInteger(p) && p > 1) + .slice(0, SELF_REPORT_AGENT_PIDS_DEPTH); + return pids.length > 0 ? pids : undefined; +} + +/** + * In the hook process: return `stdin` with `SELF_REPORT_AGENT_PIDS_KEY` set + * when this is a Claude Code or Codex report call, else `stdin` unchanged. + * Never throws. + */ +export function selfReportMarkAgentPids( + cli: string, + stdin: string, + ancestry: () => number[] = selfReportAncestorPids, +): string { + if (!HOOK_RECORDED.includes(cli) || !/failproofai_local/i.test(stdin)) return stdin; + try { + const parsed = JSON.parse(stdin) as unknown; + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return stdin; + const rec = parsed as Record; + if (!isSelfReportToolName(rec.tool_name)) return stdin; + const pids = ancestry(); + if (pids.length === 0) { + const { [SELF_REPORT_AGENT_PIDS_KEY]: _drop, ...rest } = rec; + return _drop === undefined ? stdin : JSON.stringify(rest); + } + return JSON.stringify({ ...rec, [SELF_REPORT_AGENT_PIDS_KEY]: pids }); + } catch { + return stdin; + } +} diff --git a/src/hooks/self-report-hook-trust.ts b/src/hooks/self-report-hook-trust.ts index caba1f5bc..393228c6c 100644 --- a/src/hooks/self-report-hook-trust.ts +++ b/src/hooks/self-report-hook-trust.ts @@ -39,6 +39,7 @@ import { claudeConfigDir, getIntegration } from "./integrations"; import { getHookActivityEntriesSince } from "./hook-activity-store"; import { readEnabledSelfReport, resolveSelfReportCategory, selfReportArgs } from "./self-report"; import { selfReportClip } from "./self-report-names"; +import { selfReportAgentPids } from "./self-report-ancestry"; import { failproofaiHome } from "./fp-home"; /** The agents whose hook, when it runs, is the recorder. */ @@ -196,11 +197,17 @@ export const SELF_REPORT_HOOK_DEDUPE_MS = 2 * 60 * 1000; * * A hook row matches when it is a PreToolUse row from that integration, * written in the last two minutes, in the same working directory as this - * server (`cwd`; a row or a server without one never matches), carrying a - * `selfReport` with the same category (as sent, or as resolved against the - * list) and detail as the hook would have clipped them. Matching on the report's text alone suppressed distinct calls: + * server (`cwd`; a row or a server without one never matches), recorded by a + * hook running under this server's own agent process (`agentPid`, the + * server's parent, is among the row's `selfReportAgentPids`; a row without + * them never matches), carrying a `selfReport` with the same category (as + * sent, or as resolved against the list) and detail as the hook would have + * clipped them. Matching on the report's text alone suppressed distinct calls: * a report the hook recorded in project A made an identical report in project - * B answer `Recorded.` with no event. + * B answer `Recorded.` with no event; and matching on text and directory + * alone let a session whose hooks did not run take the row another session's + * hook wrote in the same directory (F14). Each agent process is one session's + * (or one process's sessions'), so another session's row never matches. * * Each row is consumed by the first call it matches: a receipt named after the * row (its integration, session, tool call id and timestamp) is created with @@ -218,8 +225,9 @@ export function selfReportHookRecordedRecently( args: unknown, now: number = Date.now(), cwd?: string, + agentPid: number = process.ppid, ): boolean { - if (!cwd) return false; + if (!cwd || !Number.isSafeInteger(agentPid) || agentPid <= 1) return false; const { category, detail } = selfReportArgs(args ?? {}); const want = { category: selfReportClip(category), detail: selfReportClip(detail) }; // The hook row holds the category as it was resolved against the list @@ -239,6 +247,7 @@ export function selfReportHookRecordedRecently( const ts = typeof row.timestamp === "number" ? row.timestamp : NaN; if (!Number.isFinite(ts) || now - ts > SELF_REPORT_HOOK_DEDUPE_MS || ts - now > 60_000) return false; if (typeof row.cwd !== "string" || !row.cwd || sameDir(row.cwd) !== here) return false; + if (!selfReportAgentPids(row.selfReportAgentPids)?.includes(agentPid)) return false; const sr = row.selfReport as { category?: unknown; detail?: unknown } | undefined; return !!sr && (sr.category === want.category || sr.category === resolved) && sr.detail === want.detail; }); From 17ef5ebe4c3cf45b6cb6e81cb7eb17de233c5d1c Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 16:08:33 +0530 Subject: [PATCH 40/54] Self Reports: register Hermes' report tool even while reporting is off When Hermes started with Self Reports off, or with failproofaid briefly unreachable, register() kept no tool, and pre_llm_call only refreshed an existing one, so enabling reporting later never reached that gateway (review finding F16). The tool is now always registered: its check_fn follows the daemon live (hidden while off), pre_llm_call adds the instructions only while the daemon offers them, and a registration made before the daemon answered carries a short generic description that is replaced in place by the daemon's text once it answers. The heartbeat gains self_report_on_at_start. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../fixtures/hermes-native-plugin-check.py | 58 +++++++++++++++--- hermes-plugin/__init__.py | 5 ++ hermes-plugin/self_report.py | 60 +++++++++++++++---- 4 files changed, 106 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d98229df5..d59bbbdd2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,7 @@ - Self Reports: the hook lets the `report` tool past the policies only when the `failproofai_local` server the agent would use is failproofai's own: its user-wide entry passes the installer's ownership test (our `mcp --agent` command or our loopback URL), no project-scope config (`.mcp.json`, `.cursor/mcp.json`, Claude Code's per-project entries in `.claude.json`, and the like) defines that name, and for Hermes, OpenClaw and Pi no other server of that name collides with the plugin's tool. A foreign server registered as `failproofai_local` was let past a deny-all policy; now it, and anything that cannot be read, goes through the policies like any other tool (#1062) - `block-failproofai-commands` treats a quoted `grep`/`rg`/`jq` argument as data only when the command word is the standard tool: a bare name while PATH has no relative entry, or a path in `/usr/bin` or `/bin`. A project's own `./grep` (or any other program of that name) that ran its argument was judged by its basename and could run the pause CLI. A `PATH` or `BASH_ENV` assignment the shell assembles from quoted or escaped pieces (`PA""TH=…`) is now seen too, and turns the exemption off like a plain one (#1062) - Self Reports: a Claude Code or Codex hook row now stands only for a call from its own agent process. The hook stamps a report call with the processes above it, and the stdio server suppresses its copy only when its own parent (the agent that started it) is one of them. Another session in the same directory, whose hooks did not run, no longer has its identical report swallowed by the first session's row and then filed under the wrong session; when the hook could not tell, the server records (#1062) +- Self Reports: the Hermes plugin registers the `report` tool even when Self Reports is off (or failproofaid cannot be reached) as the gateway starts. A gateway started that way kept no tool, so `self-report enable` never reached it until a restart; now the tool's availability and the instructions in `pre_llm_call` follow the daemon live, at most a minute behind, and the heartbeat records whether reporting was on at start (#1062) ### Docs diff --git a/__tests__/fixtures/hermes-native-plugin-check.py b/__tests__/fixtures/hermes-native-plugin-check.py index b29af1aa8..0b57a1142 100644 --- a/__tests__/fixtures/hermes-native-plugin-check.py +++ b/__tests__/fixtures/hermes-native-plugin-check.py @@ -1862,12 +1862,54 @@ def test_registers_a_direct_tool_with_the_servers_text(self) -> None: # On Hermes' never-deferred list, so tool search keeps it direct. self.assertIn("mcp_failproofai_local_report", self.fake_toolsets._HERMES_CORE_TOOLS) - def test_registers_nothing_while_self_reports_is_off_or_the_daemon_is_gone(self) -> None: + def test_registers_a_hidden_tool_while_self_reports_is_off_or_the_daemon_is_gone(self) -> None: with tempfile.TemporaryDirectory() as tmp: ctx = ToolContext(Path(tmp)) - self.assertIsNone(self_report_mod.register_self_report_tool(ctx, self_report_mod.SelfReportTool(discover=lambda: None))) - self.assertEqual(ctx.tools, []) - self.assertNotIn("mcp_failproofai_local_report", self.fake_toolsets._HERMES_CORE_TOOLS) + state = self_report_mod.SelfReportTool(discover=lambda: None) + self.assertIs(self_report_mod.register_self_report_tool(ctx, state), state) + [reg] = ctx.tools + self.assertEqual(reg["name"], "mcp_failproofai_local_report") + self.assertEqual(reg["schema"]["parameters"]["required"], ["category", "detail"]) + self.assertFalse(reg["check_fn"]()) # hidden from the model while off + self.assertEqual(state.instructions(), "") + self.assertIn("mcp_failproofai_local_report", self.fake_toolsets._HERMES_CORE_TOOLS) + + # F16: a gateway that started while Self Reports was off kept no tool, so + # enabling it later never reached that gateway until a restart. + def test_off_at_start_then_enabled_shows_the_tool_and_its_instructions_without_a_restart(self) -> None: + offered = {"on": False} + clock = {"t": 0.0} + + def discover(): + if not offered["on"]: + return None + return {**SR_SERVER, "description": "Report it.", "inputSchema": SR_SCHEMA, "instructions": "Report when stuck."} + + with tempfile.TemporaryDirectory() as tmp: + ctx = ToolContext(Path(tmp)) + state = self_report_mod.SelfReportTool(discover=discover, clock=lambda: clock["t"]) + instance = plugin.FailproofAIPlugin(FakeContext(Path(tmp))) + instance.self_report = self_report_mod.register_self_report_tool(ctx, state) + [reg] = ctx.tools + self.assertFalse(reg["check_fn"]()) + self.assertEqual(instance.pre_llm_call(), {"context": plugin._PROTOCOL_CONTEXT}) + # Self Reports is turned on; within a minute the tool and its text follow. + offered["on"] = True + clock["t"] += 61.0 + self.assertTrue(reg["check_fn"]()) + self.assertTrue(instance.pre_llm_call()["context"].endswith("Report when stuck.")) + # The registered schema took the daemon's text in place. + self.assertEqual(reg["schema"]["description"], "Report it.") + self.assertEqual(reg["schema"]["parameters"], SR_SCHEMA) + # And a call is handed to the daemon. + calls: list = [] + state._call = lambda tool, args, cwd: self_report_mod.call_self_report_tool(tool, args, cwd, lambda: SR_SERVER, sr_rpc(calls)) + self.assertEqual(reg["handler"]({"category": "looping", "detail": "again"}, cwd="/w"), "Recorded.") + self.assertEqual(calls[-1][1]["params"]["arguments"], {"category": "looping", "detail": "again"}) + # Turned off again: hidden again. + offered["on"] = False + clock["t"] += 61.0 + self.assertFalse(reg["check_fn"]()) def test_a_register_tool_that_raises_never_breaks_register(self) -> None: class Raising(ToolContext): @@ -1899,14 +1941,16 @@ def test_pre_llm_call_carries_the_instructions_only_with_the_tool(self) -> None: self.assertTrue(context.startswith(plugin._PROTOCOL_CONTEXT)) self.assertTrue(context.endswith("Report when stuck.")) - def test_register_without_a_daemon_registers_hooks_and_no_tool(self) -> None: + def test_register_without_a_daemon_registers_hooks_and_a_hidden_tool(self) -> None: with tempfile.TemporaryDirectory() as tmp, patch.dict(os.environ, {"FAILPROOFAI_DAEMON_SOCKET": str(Path(tmp) / "none.sock")}): data_dir = Path(tmp) / "data" ctx = ToolContext(data_dir) plugin.register(ctx) beat = json.loads((data_dir / "heartbeat.json").read_text()) - self.assertEqual(ctx.tools, []) - self.assertIs(beat["self_report_tool"], False) + [reg] = ctx.tools + self.assertFalse(reg["check_fn"]()) + self.assertIs(beat["self_report_tool"], True) + self.assertIs(beat["self_report_on_at_start"], False) self.assertIs(beat["register_ok"], True) diff --git a/hermes-plugin/__init__.py b/hermes-plugin/__init__.py index ccd27f718..f6359dd0b 100644 --- a/hermes-plugin/__init__.py +++ b/hermes-plugin/__init__.py @@ -1046,16 +1046,20 @@ def register(ctx: Any) -> None: middleware = plugin.wraps_execution # Self Reports: the report tool as a direct native tool (never behind # Hermes' tool search), recorded by failproofaid like the MCP call was. + # Registered even while Self Reports is off: its check_fn and the + # pre_llm_call instructions follow the daemon live. try: plugin.self_report = register_self_report_tool(ctx) except Exception as exc: logger.error("FailproofAI could not register the Self Reports tool: %s", exc) self_report_tool = plugin.self_report is not None + self_report_on = self_report_tool and plugin.self_report.current is not None except Exception as exc: logger.exception("FailproofAI plugin failed to register") error = f"{type(exc).__name__}: {exc}" middleware = False self_report_tool = False + self_report_on = False beat.update( stage="end", @@ -1063,6 +1067,7 @@ def register(ctx: Any) -> None: hooks_registered=hooks, middleware_registered=middleware, self_report_tool=self_report_tool, + self_report_on_at_start=self_report_on, ) if error: beat["error"] = error diff --git a/hermes-plugin/self_report.py b/hermes-plugin/self_report.py index 57b565a5d..34d3847cd 100644 --- a/hermes-plugin/self_report.py +++ b/hermes-plugin/self_report.py @@ -12,12 +12,20 @@ removes one an earlier version wrote. The text and the recording come from failproofaid's own Self Reports MCP -server, so this file holds no copy of either: the description and schema are -what its ``tools/list`` returns (no tool while Self Reports is off), and each -call is its ``tools/call``, sent as ``?agent=hermes&cwd=`` so the report +server: the description and schema are what its ``tools/list`` returns, and +each call is its ``tools/call``, sent as ``?agent=hermes&cwd=`` so the report is attributed, deduped and logged exactly as the MCP path did. The endpoint is trusted only when it answers ``initialize`` with the ``instanceId`` the daemon behind this user's socket reports in its pong. + +The tool is registered whether or not Self Reports is on when Hermes starts +(review finding F16): a gateway that started while it was off, or while the +daemon could not be reached, kept no tool, so turning it on later never +reached that gateway. Its ``check_fn`` follows the daemon live (at most a +minute behind), so the model sees the tool, and ``pre_llm_call`` its +instructions, only while the daemon offers them. Registered before the daemon +answered, it carries a short generic description (``_FALLBACK_*``) until the +first answer, which is copied into the registered schema in place. """ from __future__ import annotations @@ -43,6 +51,21 @@ _TIMEOUT_S = 3.0 _CALL_TIMEOUT_S = 20.0 _REFRESH_S = 60.0 +# The registration's text when the daemon has not offered the tool yet. The +# categories and guidance reach the model in the instructions, which are live. +_FALLBACK_DESCRIPTION = ( + "When you are stuck on something you cannot fix yourself, call this tool once with " + "`category` and `detail` (one factual sentence: what is blocking you). It reports to " + "FailproofAI. It does not unblock you: continue, or tell the user what is blocking you." +) +_FALLBACK_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "category": {"type": "string", "description": "What kind of blocker this is."}, + "detail": {"type": "string", "description": "One factual sentence: what is blocking you."}, + }, + "required": ["category", "detail"], +} _ARG_ALIASES = { "category": ("category", "type", "kind"), "detail": ("detail", "summary", "sentence", "message", "description", "reason", "text", "details"), @@ -203,6 +226,8 @@ def __init__( self._lock = threading.Lock() self.current: dict[str, Any] | None = None self._fetched = float("-inf") + # The schema dict handed to Hermes at registration; refreshed in place. + self.schema: dict[str, Any] | None = None def refresh(self, force: bool = False) -> dict[str, Any] | None: with self._lock: @@ -216,6 +241,13 @@ def refresh(self, force: bool = False) -> dict[str, Any] | None: tool = None with self._lock: self.current = tool + if tool and self.schema is not None: + # Best effort: a registry that kept our dict sees the daemon's text. + try: + self.schema["description"] = tool["description"] + self.schema["parameters"] = tool["inputSchema"] + except Exception: + pass return tool def available(self) -> bool: @@ -234,15 +266,21 @@ def handler(self, args: Any = None, **kwargs: Any) -> str: def register_self_report_tool(ctx: Any, state: SelfReportTool | None = None) -> SelfReportTool | None: - """Register the native tool on ``ctx`` when failproofaid offers one right - now. Never raises. The schema is fixed at registration (Hermes' registry - keeps it), so new categories reach Hermes on the gateway's next start; the - switch itself is followed live through ``check_fn``.""" + """Register the native tool on ``ctx``, whether or not failproofaid offers + one right now. Never raises. ``check_fn`` follows the daemon live, so a + tool registered while Self Reports was off (or the daemon was down) shows + up once it is on, without restarting the gateway. The schema is the + daemon's when it answered here, else the generic fallback; Hermes keeps + what it was given, so new categories reach its schema on the gateway's + next start (they reach the model at once through the instructions).""" state = state or SelfReportTool() - tool = state.refresh(force=True) - if not tool or not hasattr(ctx, "register_tool"): + if not hasattr(ctx, "register_tool"): return None - schema = {"name": TOOL_NAME, "description": tool["description"], "parameters": tool["inputSchema"]} + tool = state.refresh(force=True) + description = tool["description"] if tool else _FALLBACK_DESCRIPTION + parameters = tool["inputSchema"] if tool else dict(_FALLBACK_SCHEMA) + schema = {"name": TOOL_NAME, "description": description, "parameters": parameters} + state.schema = schema try: ctx.register_tool( name=TOOL_NAME, @@ -250,7 +288,7 @@ def register_self_report_tool(ctx: Any, state: SelfReportTool | None = None) -> schema=schema, handler=state.handler, check_fn=state.available, - description=tool["description"], + description=description, ) except Exception as exc: logger.warning("FailproofAI could not register the Self Reports tool: %s", exc) From a32ff85b49bce6933e87ee6f4e6b7cc3b76a3757 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 16:10:46 +0530 Subject: [PATCH 41/54] Self Reports: let Pi pick up the report tool after it started A Pi loaded while Self Reports was off (or while it waited for Cloud's setting) skipped registering the native tool for the whole process (review finding F21). The extension now asks the stdio server again, at most once a minute and never awaited, on session_start and before_agent_start. Pi accepts registerTool after startup and replaces a tool of the same name, so a tool that appears or changes is registered then; one that goes away is taken out of the active tools with setActiveTools until it is back. The docs now say so for Pi, and describe the Hermes plugin's always-registered hidden tool. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/pi-self-report-sync.test.ts | 125 ++++++++++++++++++++ docs/self-reports.mdx | 2 +- pi-extension/index.ts | 100 ++++++++++++++-- 4 files changed, 217 insertions(+), 11 deletions(-) create mode 100644 __tests__/hooks/pi-self-report-sync.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d59bbbdd2..6d085665e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,7 @@ - `block-failproofai-commands` treats a quoted `grep`/`rg`/`jq` argument as data only when the command word is the standard tool: a bare name while PATH has no relative entry, or a path in `/usr/bin` or `/bin`. A project's own `./grep` (or any other program of that name) that ran its argument was judged by its basename and could run the pause CLI. A `PATH` or `BASH_ENV` assignment the shell assembles from quoted or escaped pieces (`PA""TH=…`) is now seen too, and turns the exemption off like a plain one (#1062) - Self Reports: a Claude Code or Codex hook row now stands only for a call from its own agent process. The hook stamps a report call with the processes above it, and the stdio server suppresses its copy only when its own parent (the agent that started it) is one of them. Another session in the same directory, whose hooks did not run, no longer has its identical report swallowed by the first session's row and then filed under the wrong session; when the hook could not tell, the server records (#1062) - Self Reports: the Hermes plugin registers the `report` tool even when Self Reports is off (or failproofaid cannot be reached) as the gateway starts. A gateway started that way kept no tool, so `self-report enable` never reached it until a restart; now the tool's availability and the instructions in `pre_llm_call` follow the daemon live, at most a minute behind, and the heartbeat records whether reporting was on at start (#1062) +- Self Reports: the Pi extension asks for the `report` tool again, at most once a minute, when a session starts or a prompt is sent, not only when Pi loads. A Pi started while Self Reports was off, or while it waited for FailproofAI Cloud's setting, kept no tool until it was reloaded; it now gets the tool from its next prompt, and turning Self Reports off takes the tool out of Pi's active tools (#1062) ### Docs diff --git a/__tests__/hooks/pi-self-report-sync.test.ts b/__tests__/hooks/pi-self-report-sync.test.ts new file mode 100644 index 000000000..32349fd45 --- /dev/null +++ b/__tests__/hooks/pi-self-report-sync.test.ts @@ -0,0 +1,125 @@ +// @vitest-environment node +/** + * F21: a Pi started while Self Reports was off (or while it waited for + * FailproofAI Cloud's setting) kept no report tool for the whole process. + * The extension now asks again on session_start / before_agent_start, at most + * once a minute, registers the tool when it appears, and takes it out of the + * active tools when it goes away. + */ +import { describe, expect, it, vi } from "vitest"; + +vi.mock("node:child_process", () => ({ + // No server in these tests: every lookup goes through the injected `discover`. + spawn: () => { + throw new Error("no server in this test"); + }, + spawnSync: () => ({ pid: 0, output: [], status: 0, signal: null, stderr: "", stdout: "" }), +})); + +import failproofaiBridge, { selfReportToolSync } from "../../pi-extension/index"; + +const TOOL = { description: "Report it.", inputSchema: { type: "object", properties: {} }, instructions: "Report when stuck." }; +const NAME = "mcp__failproofai_local__report"; + +function fakePi(bound = true) { + const tools = new Map>(); + let active: string[] = ["read", "bash"]; + const pi = { + on: vi.fn(), + registerTool: vi.fn((t: Record) => { + tools.set(t.name as string, t); + if (!active.includes(t.name as string)) active = [...active, t.name as string]; + }), + getActiveTools: vi.fn(() => { + if (!bound) throw new Error("Extension runtime not initialized"); + return active; + }), + setActiveTools: vi.fn((names: string[]) => { + active = names; + }), + }; + return { pi, tools, active: () => active }; +} + +describe("selfReportToolSync", () => { + it("off at start, then turned on: the tool is registered on the next look, without a restart", async () => { + let offered: typeof TOOL | null = null; + let now = 0; + const { pi, tools, active } = fakePi(); + const sync = selfReportToolSync(pi, async () => offered, () => now); + await sync.refresh(true); + expect(tools.size).toBe(0); + expect(sync.offered()).toBe(false); + offered = TOOL; + // Within the minute: not asked again. + await sync.refresh(); + expect(tools.size).toBe(0); + now += 60_000; + await sync.refresh(); + expect(tools.get(NAME)).toMatchObject({ name: NAME, description: "Report it.", promptGuidelines: ["Report when stuck."] }); + expect(active()).toContain(NAME); + expect(sync.offered()).toBe(true); + }); + + it("turned off again: taken out of the active tools; back on: active again, re-registered only when its text changed", async () => { + let offered: typeof TOOL | null = TOOL; + let now = 0; + const { pi, active } = fakePi(); + const sync = selfReportToolSync(pi, async () => offered, () => now); + await sync.refresh(true); + expect(pi.registerTool).toHaveBeenCalledTimes(1); + offered = null; + now += 60_000; + await sync.refresh(); + expect(active()).not.toContain(NAME); + expect(sync.offered()).toBe(false); + offered = TOOL; + now += 60_000; + await sync.refresh(); + expect(active()).toContain(NAME); + expect(pi.registerTool).toHaveBeenCalledTimes(1); + offered = { ...TOOL, instructions: "New guidance." }; + now += 60_000; + await sync.refresh(); + expect(pi.registerTool).toHaveBeenCalledTimes(2); + }); + + it("a lookup that fails or throws leaves nothing registered and never rejects", async () => { + const { pi, tools } = fakePi(); + const sync = selfReportToolSync(pi, async () => { + throw new Error("spawn failed"); + }); + await expect(sync.refresh(true)).resolves.toBeUndefined(); + expect(tools.size).toBe(0); + }); + + it("does not ask twice at once", async () => { + let calls = 0; + let release: (v: typeof TOOL | null) => void = () => {}; + const { pi } = fakePi(); + const sync = selfReportToolSync(pi, () => { + calls++; + return new Promise((r) => (release = r)); + }); + const a = sync.refresh(true); + const b = sync.refresh(true); + release(TOOL); + await Promise.all([a, b]); + expect(calls).toBe(1); + }); +}); + +describe("the extension asks again on session_start and before_agent_start", () => { + it("registers handlers that start a lookup without waiting on it", async () => { + const handlers: Record unknown> = {}; + const { pi } = fakePi(false); + pi.on.mockImplementation((name: string, fn: (e: unknown) => unknown) => { + handlers[name] = fn; + }); + await failproofaiBridge(pi); + // No server here, so no tool; the handlers still answer synchronously. + expect(pi.registerTool).not.toHaveBeenCalled(); + expect(handlers.session_start({ type: "session_start", cwd: "/p" })).toBeUndefined(); + expect(handlers.before_agent_start({ type: "before_agent_start", cwd: "/p", systemPrompt: "" })).toBeUndefined(); + }); +}); diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index 8c1875f09..6ba486bf4 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -89,7 +89,7 @@ The server sends short instructions in the MCP handshake: when to report, the ca | Antigravity | The entry sets `eager: true`, so the tools are direct rather than behind the `call_mcp_tool` wrapper. Antigravity ignores MCP server instructions, so failproofai adds a plugin in its global customization root, `~/.gemini/config/plugins/failproofai-self-reports/` (`plugin.json`, the instructions in `rules/AGENTS.md`, and a `.failproofai-managed` marker), whose rules Antigravity merges into every session. A directory of that name without the marker is never written to or removed. | | Goose | Extensions' tools are listed directly. | -Pi has no MCP support before 0.99, so an MCP entry for it reaches no model. failproofai's Pi extension, which every Pi with failproofai hooks already loads, registers the tool itself as `mcp__failproofai_local__report` on every Pi version, with the server's instructions in Pi's system prompt. It asks `failproofai mcp --agent pi` for the tool when Pi starts (no tool while Self Reports is off) and hands each call to it, so the text, the categories and the recording are the same as every other agent's. The Hermes and OpenClaw plugins do the same against the daemon's Self Reports server: they ask it for the tool when the gateway starts (and every minute after, for the instructions and the on/off switch) and send each call to it as `?agent=hermes` or `?agent=openclaw` with the gateway's working directory, so it is attributed, deduped and logged like an MCP call. Without a daemon, or while Self Reports is off, they offer no tool. On Hermes the tool's schema is fixed when it registers, so new categories reach it at the gateway's next start. `self-report sync` writes no Pi, Hermes or OpenClaw MCP entry and takes out one an earlier version wrote, in every profile. `failproofai update` (and the first `failproofai config` on a new version) takes out a Hermes or OpenClaw one before it restarts their gateways, so a restarted gateway does not load it again; OpenClaw would otherwise also start the stdio server for it. +Pi has no MCP support before 0.99, so an MCP entry for it reaches no model. failproofai's Pi extension, which every Pi with failproofai hooks already loads, registers the tool itself as `mcp__failproofai_local__report` on every Pi version, with the server's instructions in Pi's system prompt. It asks `failproofai mcp --agent pi` for the tool when Pi starts, and again at most once a minute when a session starts or a prompt is sent, and hands each call to it, so the text, the categories and the recording are the same as every other agent's. A Pi started while Self Reports was off (or while it waited for FailproofAI Cloud's setting) gets the tool from its next prompt after Self Reports is turned on, without a reload, and turning it off takes the tool out of Pi's active tools. The Hermes and OpenClaw plugins do the same against the daemon's Self Reports server: they ask it for the tool when the gateway starts (and every minute after, for the instructions and the on/off switch) and send each call to it as `?agent=hermes` or `?agent=openclaw` with the gateway's working directory, so it is attributed, deduped and logged like an MCP call. Without a daemon, or while Self Reports is off, the model sees no tool. The Hermes plugin registers the tool even then, hidden, so a gateway started while Self Reports was off shows it within a minute of `self-report enable`, without a restart. On Hermes the tool's schema is fixed when it registers (a short generic one when the daemon had not answered yet), so new categories reach the schema at the gateway's next start; they reach the model at once through the instructions. `self-report sync` writes no Pi, Hermes or OpenClaw MCP entry and takes out one an earlier version wrote, in every profile. `failproofai update` (and the first `failproofai config` on a new version) takes out a Hermes or OpenClaw one before it restarts their gateways, so a restarted gateway does not load it again; OpenClaw would otherwise also start the stdio server for it. Where an agent's hooks see MCP tool calls and the server they belong to, the hook records the report. Where they do not, failproofai's MCP server records it. It attributes the report to that agent's newest session seen by the hooks in the last 6 hours: in the server's working directory if there is one, else in a directory above or below it. With neither, it takes the agent's newest session only when all of the agent's sessions in those 6 hours are in one directory, and files the report as `unattributed` otherwise, rather than guess between projects. The lookup reads every page of hook activity written in the 6 hours, however busy other agents or projects kept the hooks, so a session that is still in the window is found. The agent the report is filed under comes from that session's own hook events. diff --git a/pi-extension/index.ts b/pi-extension/index.ts index 08a49b4a9..de3571720 100644 --- a/pi-extension/index.ts +++ b/pi-extension/index.ts @@ -335,6 +335,9 @@ interface PiExtensionApi { on(event: string, handler: (event: unknown) => unknown): void; /** Pi's custom tools (every Pi failproofai supports has it; checked anyway). */ registerTool?(tool: Record): void; + /** Which tools the model sees; only callable once Pi has bound the extension (not during load). */ + getActiveTools?(): string[]; + setActiveTools?(toolNames: string[]): void; } // ── Self Reports ──────────────────────────────────────────────────────────── @@ -345,8 +348,16 @@ interface PiExtensionApi { // already loads, offers the report tool itself instead, on every Pi version. // The tool's text and the recording both come from failproofai's own stdio MCP // server (`failproofai mcp --agent pi`), so this file holds no copy of either: -// at load it asks the server for the tool (none while Self Reports is off), -// and a call is handed to the server, which records it against Pi's session. +// it asks the server for the tool (none while Self Reports is off), and a call +// is handed to the server, which records it against Pi's session. +// +// It asks at load and again, at most once a minute, on `session_start` and +// `before_agent_start` (review finding F21): a Pi started while Self Reports +// was off, or while it waited for FailproofAI Cloud's setting, otherwise kept +// no tool until it was restarted. Pi takes `registerTool` after startup too +// (refreshed into the same session) and replaces a tool of the same name, so +// a tool that appears or changes is registered then, and one that goes away +// is taken out of the active tools (`setActiveTools`) until it is back. /** Pi spells it like Claude Code: one of the names the hook lets past every policy. */ const SELF_REPORT_PI_TOOL = "mcp__failproofai_local__report"; @@ -428,8 +439,8 @@ function selfReportPick(args: Record, keys: string[]): string { return ""; } -function registerSelfReportTool(pi: PiExtensionApi, tool: SelfReportTool): void { - if (typeof pi.registerTool !== "function") return; +function registerSelfReportTool(pi: PiExtensionApi, tool: SelfReportTool): boolean { + if (typeof pi.registerTool !== "function") return false; pi.registerTool({ name: SELF_REPORT_PI_TOOL, label: "Report (FailproofAI)", @@ -462,9 +473,78 @@ function registerSelfReportTool(pi: PiExtensionApi, tool: SelfReportTool): void return { content: [{ type: "text", text }], details: {} }; }, }); + return true; +} + +/** How often the extension asks the server again whether it offers the tool. */ +const SELF_REPORT_REFRESH_MS = 60_000; + +/** Keeps the registered report tool in step with what the server offers. */ +export interface SelfReportToolSync { + /** Ask the server (at most once a minute unless `force`); resolves when done. Never rejects. */ + refresh(force?: boolean): Promise; + /** Whether a tool is registered and not taken out of the active tools. */ + offered(): boolean; +} + +export function selfReportToolSync( + pi: PiExtensionApi, + discover: () => Promise = selfReportToolFromServer, + clock: () => number = Date.now, +): SelfReportToolSync { + let registeredAs: string | null = null; + let hidden = false; + let last = -Infinity; + let inflight: Promise | null = null; + const setActive = (on: boolean): void => { + if (typeof pi.getActiveTools !== "function" || typeof pi.setActiveTools !== "function") return; + try { + const active = pi.getActiveTools(); + const has = active.includes(SELF_REPORT_PI_TOOL); + if (on && !has) pi.setActiveTools([...active, SELF_REPORT_PI_TOOL]); + if (!on && has) pi.setActiveTools(active.filter((n) => n !== SELF_REPORT_PI_TOOL)); + hidden = !on; + } catch { + // Not bound yet (during load): nothing to switch. + } + }; + const run = async (): Promise => { + let tool: SelfReportTool | null = null; + try { + tool = await discover(); + } catch (err) { + debug(`self-report tool lookup failed: ${err instanceof Error ? err.message : String(err)}`); + } + if (tool) { + const key = JSON.stringify(tool); + if (key !== registeredAs) { + try { + if (registerSelfReportTool(pi, tool)) registeredAs = key; + } catch (err) { + debug(`self-report tool not registered: ${err instanceof Error ? err.message : String(err)}`); + } + } + if (registeredAs !== null && hidden) setActive(true); + } else if (registeredAs !== null && !hidden) { + setActive(false); + } + }; + return { + refresh(force = false) { + if (inflight) return inflight; + if (!force && clock() - last < SELF_REPORT_REFRESH_MS) return Promise.resolve(); + last = clock(); + inflight = run().finally(() => { + inflight = null; + }); + return inflight; + }, + offered: () => registeredAs !== null && !hidden, + }; } export default async function failproofaiBridge(pi: PiExtensionApi) { + const selfReport = selfReportToolSync(pi); // tool_call → PreToolUse. Block tool execution when failproofai denies. pi.on("tool_call", (event: unknown): unknown => { const e = event as PiToolCallEvent; @@ -557,6 +637,8 @@ export default async function failproofaiBridge(pi: PiExtensionApi) { // activity feed records the session and any UserPromptSubmit policies that // need session_id continuity see the metadata. pi.on("session_start", (event: unknown): unknown => { + // Self Reports may have been turned on since the last look; never awaited. + void selfReport.refresh(); const e = event as PiSessionStartEvent; callPolicy("session_start", { session_id: resolveSessionId(e.sessionId, resolveCwd(e.cwd)), @@ -621,6 +703,9 @@ export default async function failproofaiBridge(pi: PiExtensionApi) { // already carries the policy-attributed MANDATORY ACTION wording from // policy-evaluator's Pi-Stop branch. pi.on("before_agent_start", (event: unknown): unknown => { + // Self Reports may have been turned on since the last look; never awaited, + // so a prompt never waits on it (the tool shows from the next turn). + void selfReport.refresh(); const e = event as PiBeforeAgentStartEvent; const cwd = resolveCwd(e.cwd); const sessionId = resolveSessionId(e.sessionId, cwd); @@ -665,10 +750,5 @@ export default async function failproofaiBridge(pi: PiExtensionApi) { }); // Last, so the policy hooks above are in place whatever this does. - try { - const tool = await selfReportToolFromServer(); - if (tool) registerSelfReportTool(pi, tool); - } catch (err) { - debug(`self-report tool not registered: ${err instanceof Error ? err.message : String(err)}`); - } + await selfReport.refresh(true); } From 66d3cffc15389c2caf46582bd96b7d197783ca0a Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 16:14:29 +0530 Subject: [PATCH 42/54] Self Reports: scrub before cutting, and never log a raw category verbatim F18: the stdio server cut a report's detail to 200 characters before sending it to the daemon for its log line, so a JWT longer than that reached the daemon's scrubber in pieces and its raw prefix was logged (the HTTP path, which scrubs the whole detail, logged [redacted:jwt]). The whole detail, already bounded at 2000 code points, is sent now, and the daemon scrubs all of it before it cuts the preview to 40 characters, as it always did. F20: the model's category was logged verbatim as raw_category (and as category for a call skipped before resolving), over stdio and HTTP, so a token passed as the category was logged whole. Both the daemon's log_line (log_category_text) and the hook's own log line (selfReportLogCategoryText) now show it only when it is shaped like a category name: lowercase ASCII, digits, _ - . or space, starting with a letter, at most 32 characters and 4 digits; anything else is "(N characters, not shown)". Listed names pass. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + __tests__/hooks/self-report-log.test.ts | 57 +++++++++++-- crates/PROTOCOL.md | 4 +- crates/fpai-collect/src/self_report.rs | 107 +++++++++++++++++++++++- docs/self-reports.mdx | 2 +- src/hooks/handler.ts | 4 +- src/hooks/self-report-log.ts | 20 +++-- src/hooks/self-report-names.ts | 20 +++++ 8 files changed, 194 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d085665e..f4a739077 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,8 @@ - Self Reports: a Claude Code or Codex hook row now stands only for a call from its own agent process. The hook stamps a report call with the processes above it, and the stdio server suppresses its copy only when its own parent (the agent that started it) is one of them. Another session in the same directory, whose hooks did not run, no longer has its identical report swallowed by the first session's row and then filed under the wrong session; when the hook could not tell, the server records (#1062) - Self Reports: the Hermes plugin registers the `report` tool even when Self Reports is off (or failproofaid cannot be reached) as the gateway starts. A gateway started that way kept no tool, so `self-report enable` never reached it until a restart; now the tool's availability and the instructions in `pre_llm_call` follow the daemon live, at most a minute behind, and the heartbeat records whether reporting was on at start (#1062) - Self Reports: the Pi extension asks for the `report` tool again, at most once a minute, when a session starts or a prompt is sent, not only when Pi loads. A Pi started while Self Reports was off, or while it waited for FailproofAI Cloud's setting, kept no tool until it was reloaded; it now gets the tool from its next prompt, and turning Self Reports off takes the tool out of Pi's active tools (#1062) +- Self Reports: the stdio server sends the daemon a report's whole detail (bounded at 2000 characters) for its log line, so secrets are scrubbed from all of it before the line is cut to 40 characters. It used to cut the detail to 200 characters first, and a JWT longer than that reached the scrubber in pieces and its start was logged (#1062) +- Self Reports: the daemon and hook log lines show the category the model sent (`category`, `raw_category`) only when it is shaped like a category name (lowercase, at most 32 characters, at most 4 digits); anything else, such as a token passed as the category, is logged as `(N characters, not shown)`. It was logged verbatim over both stdio and HTTP (#1062) ### Docs diff --git a/__tests__/hooks/self-report-log.test.ts b/__tests__/hooks/self-report-log.test.ts index 2a14ee4cf..b911c6bfc 100644 --- a/__tests__/hooks/self-report-log.test.ts +++ b/__tests__/hooks/self-report-log.test.ts @@ -21,6 +21,7 @@ import { SELF_REPORT_LOG_BUDGET_MS, flushSelfReportLogs, sendSelfReportLog } fro import { handleSelfReportRpc, runSelfReportMcpServer } from "../../src/hooks/self-report-mcp"; import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; import { progressLine } from "../../src/hooks/tui"; +import { selfReportLogCategoryText } from "../../src/hooks/self-report-names"; import { PassThrough } from "node:stream"; let home: string; @@ -113,26 +114,44 @@ function fakeDaemon(path: string): Promise<{ server: Server; frames: Array { - it("sends one framed selfReportLog and cuts the preview", async () => { + it("sends one framed selfReportLog with the whole (bounded) detail, for the daemon to scrub before it cuts", async () => { const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); try { - await sendSelfReportLog({ event: "tools/call", agent: "hermes", transport: "stdio", outcome: "recorded", preview: "x".repeat(500) }); + await sendSelfReportLog({ event: "tools/call", agent: "hermes", transport: "stdio", outcome: "recorded", preview: "x".repeat(2500) }); await vi.waitFor(() => expect(frames).toHaveLength(1)); expect(frames[0]).toMatchObject({ type: "selfReportLog", protocolVersion: 2, event: { event: "tools/call", agent: "hermes", outcome: "recorded" } }); - expect(((frames[0].event as Record).preview).length).toBe(200); + expect(((frames[0].event as Record).preview).length).toBe(2000); } finally { server.close(); } }); - it("cuts the preview on a character boundary, never through a surrogate pair", async () => { + // F18: cutting the detail to 200 characters here cut a long JWT into two + // segments, which the daemon's scrubber no longer recognised, so its raw + // start reached the daemon log over stdio (HTTP logged [redacted:jwt]). + it("sends a JWT longer than 200 characters whole, and the raw category whole", async () => { const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); try { - // 199 ASCII then emoji: the 200th code point is whole, nothing after it. - await sendSelfReportLog({ event: "tools/call", transport: "stdio", preview: `${"a".repeat(199)}😀😀 environment` }); + const seg = (n: number) => "a".repeat(n); + const jwt = `eyJhbGciOiJIUzI1NiJ9.eyJ${seg(250)}.${seg(43)}`; + await sendSelfReportLog({ event: "tools/call", transport: "stdio", preview: `token ${jwt} rejected`, rawCategory: `ghp_${"A".repeat(36)}` }); + await vi.waitFor(() => expect(frames).toHaveLength(1)); + const event = frames[0].event as Record; + expect(event.preview).toBe(`token ${jwt} rejected`); + expect(event.rawCategory).toBe(`ghp_${"A".repeat(36)}`); + } finally { + server.close(); + } + }); + + it("bounds the preview on a character boundary, never through a surrogate pair", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + // 1999 ASCII then emoji: the 2000th code point is whole, nothing after it. + await sendSelfReportLog({ event: "tools/call", transport: "stdio", preview: `${"a".repeat(1999)}😀😀 environment` }); await vi.waitFor(() => expect(frames).toHaveLength(1)); const preview = (frames[0].event as Record).preview; - expect(preview).toBe(`${"a".repeat(199)}😀`); + expect(preview).toBe(`${"a".repeat(1999)}😀`); expect(preview).not.toContain("�"); } finally { server.close(); @@ -287,3 +306,27 @@ describe("setup's finish step", () => { } }); }); + +// F20: the model's category was logged verbatim (raw_category=""). +describe("selfReportLogCategoryText", () => { + it("shows a category-shaped name as written", () => { + for (const c of ["", "looping", "token_expired", "auth-failure", "operator_blocker", "error 401", "v2.api_down"]) { + expect(selfReportLogCategoryText(c), c).toBe(c); + } + }); + + it("hides anything else, tokens included, saying only how long it was", () => { + const cases: Array<[string, number]> = [ + [`ghp_${"A".repeat(36)}`, 40], + ["AKIAIOSFODNN7EXAMPLE", 20], + ["sk-proj-abc123def456ghi789", 26], + ["eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.sig", 40], + ["d41d8cd98f00b204e9800998ecf8427e", 32], + ["Looping", 7], + ["a".repeat(33), 33], + ["xoxb-123456789012-abcdefghijkl", 30], + ["token=hunter2", 13], + ]; + for (const [raw, n] of cases) expect(selfReportLogCategoryText(raw), raw).toBe(`(${n} characters, not shown)`); + }); +}); diff --git a/crates/PROTOCOL.md b/crates/PROTOCOL.md index b15bea04d..ef46e2657 100644 --- a/crates/PROTOCOL.md +++ b/crates/PROTOCOL.md @@ -82,9 +82,9 @@ Tagged JSON, `"type"` as the discriminant, camelCase field names. "reason": "Self Reports is off", "category": "looping", "knownCategory": true, // false: the category sent is not listed, and `category` was resolved from it - "rawCategory": "", // only when knownCategory is false: what was sent (maybe empty), ≤ 64 chars + "rawCategory": "", // only when knownCategory is false: what was sent (maybe empty), ≤ 2000 chars; logged only when shaped like a name "session": "…", - "preview": "≤ 200 chars of the detail; the daemon scrubs secrets and logs ≤ 40", + "preview": "the detail, ≤ 2000 chars; the daemon scrubs secrets from all of it, then logs ≤ 40", "summary": "added claude (stdio); failed codex (…)" // sync only } } diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index 1fb4c3ad2..08ba1656e 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -1061,6 +1061,33 @@ pub fn log_preview(detail: &str) -> String { } } +/// The longest agent-sent category [`log_category_text`] shows as written. +pub const LOG_CATEGORY_CHARS: usize = 32; + +/// A category the model sent, as a log line may show it: as written only +/// when it is shaped like a category name (lowercase ASCII letters, digits, +/// `_`, `-`, `.` or a space, starting with a letter, at most +/// [`LOG_CATEGORY_CHARS`] characters and at most 4 digits), else +/// `(N characters, not shown)`. The model can put anything in the field, a +/// token included, and machine logs can leave the machine; no credential +/// format is that short, lowercase and digit-poor. The TypeScript side +/// (`selfReportLogCategoryText`, src/hooks/self-report-names.ts) applies the +/// same rule to the hook's own log line. +pub fn log_category_text(raw: &str) -> String { + let n = raw.chars().count(); + let digits = raw.chars().filter(char::is_ascii_digit).count(); + let mut chars = raw.chars(); + let shaped = matches!(chars.next(), Some(c) if c.is_ascii_lowercase()) + && chars.all(|c| { + c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | ' ' | '-') + }); + if raw.is_empty() || (shaped && n <= LOG_CATEGORY_CHARS && digits <= 4) { + raw.to_string() + } else { + format!("({n} characters, not shown)") + } +} + /// The line [`log_event`] writes (without its level). pub fn log_line(ev: &McpLog) -> String { fn word(v: &str, max: usize) -> String { @@ -1082,13 +1109,16 @@ pub fn log_line(ev: &McpLog) -> String { if let Some(v) = ev.outcome { field("outcome", word(v, 32)); } + // `category` is the listed name a call resolved to, or, for a call that + // was skipped before resolving, what the model sent; either way it goes + // through the same rule as `raw_category`, which a listed name passes. if let Some(v) = ev.category { - field("category", format!("{:?}", word(v, 64))); + field("category", format!("{:?}", log_category_text(v))); } match (ev.known_category, ev.raw_category) { (Some(false), Some(raw)) => { field("inferred_category", "true".to_string()); - field("raw_category", format!("{:?}", word(raw, 64))); + field("raw_category", format!("{:?}", log_category_text(raw))); } // A sender older than inference: it recorded the category as sent. (Some(false), None) => field("unknown_category", "true".to_string()), @@ -1557,6 +1587,54 @@ pub fn write_event_file(home: &Path, events: &[Value]) -> io::Result { mod tests { use super::*; + /// F18: the stdio sender used to cut the detail to 200 characters before + /// sending it, so a JWT longer than that reached this scrubber in pieces + /// and its raw start was logged. The sender now sends the whole (bounded) + /// detail; this is what the daemon does with it. + #[test] + fn a_log_preview_scrubs_a_jwt_longer_than_two_hundred_characters() { + let jwt = format!( + "eyJhbGciOiJIUzI1NiJ9.eyJ{}.{}", + "a".repeat(250), + "b".repeat(43) + ); + assert!(jwt.len() > 200); + let preview = log_preview(&format!("token {jwt} rejected")); + assert!(!preview.contains("eyJhbGci"), "{preview}"); + assert!(preview.contains("[redacted:"), "{preview}"); + } + + #[test] + fn a_category_is_logged_only_when_it_is_shaped_like_a_name() { + for name in [ + "", + "looping", + "token_expired", + "auth-failure", + "operator_blocker", + "error 401", + "v2.api_down", + ] { + assert_eq!(log_category_text(name), name); + } + for (raw, n) in [ + (format!("ghp_{}", "A".repeat(36)), 40), + ("AKIAIOSFODNN7EXAMPLE".to_string(), 20), + ("sk-proj-abc123def456ghi789".to_string(), 26), + ("d41d8cd98f00b204e9800998ecf8427e".to_string(), 32), + ("Looping".to_string(), 7), + ("a".repeat(33), 33), + ("token=hunter2".to_string(), 13), + ("ünïcode".to_string(), 7), + ] { + assert_eq!( + log_category_text(&raw), + format!("({n} characters, not shown)"), + "{raw}" + ); + } + } + #[test] fn a_log_preview_is_scrubbed_before_it_is_cut() { // The key starts inside the first 40 characters and ends after them: @@ -1644,6 +1722,31 @@ mod tests { "Self Reports MCP tools/call over http outcome=recorded \ category=\"invalid_tool_or_credential\" inferred_category=true raw_category=\"\"" ); + // F20: the model's category is shown only when it is shaped like a + // name; a token sent as the category is never logged. + let token = format!("ghp_{}", "A".repeat(36)); + let tokened = log_line(&McpLog { + event: "tools/call", + transport: "stdio", + outcome: Some("recorded"), + category: Some("invalid_tool_or_credential"), + known_category: Some(false), + raw_category: Some(&token), + ..Default::default() + }); + assert!(!tokened.contains("AAAA"), "{tokened}"); + assert!( + tokened.ends_with("inferred_category=true raw_category=\"(40 characters, not shown)\""), + "{tokened}" + ); + let skipped = log_line(&McpLog { + event: "tools/call", + transport: "http", + outcome: Some("skipped"), + category: Some(&token), + ..Default::default() + }); + assert!(!skipped.contains("AAAA"), "{skipped}"); let bare = log_line(&McpLog { event: "initialize", transport: "http", diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index 6ba486bf4..da2bca431 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -159,7 +159,7 @@ One non-zero exit is ordinary work and gets no line. Neither does read-only expl ## The daemon's log -The daemon's log (`~/.failproofai/logs/daemon.log`, which machine logs upload) has a line for every Self Reports MCP event: each `initialize` and `tools/list`, each `tools/call` with the agent, the category, the session it was filed under, and whether it was recorded or skipped and why, and each sync's result. A write failure, a report whose category was inferred (the line says `inferred_category=true` and gives the `raw_category` the agent sent, which may be empty), and an unreadable settings file are warnings. A line carries at most the first 40 characters of the report's detail, after secrets are scrubbed from it, cut on a character boundary and followed by `...` when there was more. The stdio server, which runs as a child of each agent, sends its events to the daemon over its socket and never waits for it: with no daemon, or a version that predates this, they are dropped. +The daemon's log (`~/.failproofai/logs/daemon.log`, which machine logs upload) has a line for every Self Reports MCP event: each `initialize` and `tools/list`, each `tools/call` with the agent, the category, the session it was filed under, and whether it was recorded or skipped and why, and each sync's result. A write failure, a report whose category was inferred (the line says `inferred_category=true` and gives the `raw_category` the agent sent, which may be empty; a category not shaped like a name, such as a token, is shown only as `(N characters, not shown)`), and an unreadable settings file are warnings. A line carries at most the first 40 characters of the report's detail, after secrets are scrubbed from the whole of it, cut on a character boundary and followed by `...` when there was more. The stdio server, which runs as a child of each agent, sends its events to the daemon over its socket and never waits for it: with no daemon, or a version that predates this, they are dropped. ## Containers diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 89d5d34c6..b4df2913f 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -65,7 +65,7 @@ import { SELF_REPORT_MCP_TOOL_NAME, SELF_REPORT_SERVER_RECORDS, } from "./self-report"; -import { selfReportClip } from "./self-report-names"; +import { selfReportLogCategoryText } from "./self-report-names"; import { selfReportFailureHint, selfReportSessionStartContext } from "./self-report-hint"; import { selfReportClaudeHookFromDevin } from "./self-report-devin"; import { SELF_REPORT_AGENT_PIDS_KEY, selfReportAgentPids, selfReportMarkAgentPids } from "./self-report-ancestry"; @@ -740,7 +740,7 @@ function recordSelfReportCall( } hookLogInfo( `event=${canonicalEventType} cli=${cli} self-report allowed${devinViaClaude ? " (Devin via Claude hooks, left to Devin)" : ""}${ - resolved?.inferred ? ` category=${resolved.category} inferred_category=true raw_category=${JSON.stringify(selfReportClip(report?.category ?? "", 64))}` : "" + resolved?.inferred ? ` category=${resolved.category} inferred_category=true raw_category=${JSON.stringify(selfReportLogCategoryText(report?.category ?? ""))}` : "" } duration=${durationMs}ms`, ); return { diff --git a/src/hooks/self-report-log.ts b/src/hooks/self-report-log.ts index fe85416d2..77bcfef0b 100644 --- a/src/hooks/self-report-log.ts +++ b/src/hooks/self-report-log.ts @@ -10,22 +10,26 @@ * it is dropped. No daemon, a slow one, or any error: dropped too, inside * `SELF_REPORT_LOG_BUDGET_MS`. Nothing here ever throws or holds up an agent. * - * Only a short start of a report's detail is sent; the daemon scrubs secrets - * from it and cuts it again before logging. + * A report's whole detail is sent (it is already bounded at 2000 code points): + * the daemon scrubs secrets from the whole text and only then cuts it for the + * log line. Cutting it here first cut long credentials (a JWT past 200 + * characters) into pieces the scrubber no longer recognised (F18). The model's + * category is sent whole too, and the daemon shows it only when it is shaped + * like a category name (F20). * * Top-level names are prefixed for the same bundle reason as self-report.ts. */ import { existsSync } from "node:fs"; import { createConnection } from "node:net"; import { daemonSocket } from "./fp-home"; -import { selfReportClip } from "./self-report-names"; +import { SELF_REPORT_DETAIL_MAX, selfReportClip } from "./self-report-names"; /** The whole budget for one event, connect to close. */ export const SELF_REPORT_LOG_BUDGET_MS = 250; -/** How much detail is sent; the daemon logs at most its first 40 characters. */ -export const SELF_REPORT_LOG_PREVIEW_CHARS = 200; -/** How much of an inferred report's raw category is sent; the daemon logs at most 64 characters. */ -export const SELF_REPORT_LOG_RAW_CATEGORY_CHARS = 64; +/** How much detail is sent: all of it, so the daemon scrubs before it cuts (it logs at most 40 characters). */ +export const SELF_REPORT_LOG_PREVIEW_CHARS = SELF_REPORT_DETAIL_MAX; +/** How much of an inferred report's raw category is sent: all of it, for the same reason. */ +export const SELF_REPORT_LOG_RAW_CATEGORY_CHARS = SELF_REPORT_DETAIL_MAX; const SELF_REPORT_LOG_PROTOCOL_VERSION = 2; export interface SelfReportLogEvent { @@ -40,7 +44,7 @@ export interface SelfReportLogEvent { /** What the model sent as the category (maybe empty), when `category` was inferred; cut before sending. */ rawCategory?: string; session?: string; - /** The report's detail; cut to `SELF_REPORT_LOG_PREVIEW_CHARS` here. */ + /** The report's detail; bounded at `SELF_REPORT_LOG_PREVIEW_CHARS` here, scrubbed then cut by the daemon. */ preview?: string; summary?: string; } diff --git a/src/hooks/self-report-names.ts b/src/hooks/self-report-names.ts index bcdc744b8..eb5beaa78 100644 --- a/src/hooks/self-report-names.ts +++ b/src/hooks/self-report-names.ts @@ -49,6 +49,26 @@ export function selfReportClip(text: string, max: number = SELF_REPORT_DETAIL_MA return out; } +/** The longest agent-sent category a log line shows as written. */ +export const SELF_REPORT_LOG_CATEGORY_MAX = 32; + +/** + * A category the model sent, as a log line may show it: as written only when + * it is shaped like a category name (lowercase letters, digits, `_`, `-`, `.` + * or a space, starting with a letter, at most 32 characters and at most 4 + * digits), else `(N characters, not shown)`. The model can put anything in + * the field, a token included, and a log line can leave the machine; no + * credential format is that short, lowercase and digit-poor. The daemon + * (`log_category_text`, crates/fpai-collect/src/self_report.rs) applies the + * same rule to what it logs. + */ +export function selfReportLogCategoryText(raw: string): string { + const n = [...raw].length; + const digits = (raw.match(/[0-9]/g) ?? []).length; + if (raw === "" || (n <= SELF_REPORT_LOG_CATEGORY_MAX && digits <= 4 && /^[a-z][a-z0-9_. -]*$/.test(raw))) return raw; + return `(${n} characters, not shown)`; +} + /** * Every spelling of the report tool an agent's hook can deliver. Exact matches * only: a prefix or substring match would let any tool whose name merely From 85d231d57b52a318020e8a33e302502ef9baec37 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 16:20:10 +0530 Subject: [PATCH 43/54] Hooks: a bare grep/rg/jq is the real tool only where PATH finds it in /usr/bin or /bin A user-writable directory earlier on PATH (~/.local/bin, ~/.cargo/bin) can hold a grep that runs its arguments, so the inert-argument exemption now checks where PATH actually resolves the name, not only that PATH has no relative entry. Follow-up to review finding F17. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/state-guard.test.ts | 29 ++++++++++++++++++++++++++++- src/hooks/builtin-policies.ts | 17 +++++++++++++++-- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/__tests__/hooks/state-guard.test.ts b/__tests__/hooks/state-guard.test.ts index e7dc8ca33..17b5d718e 100644 --- a/__tests__/hooks/state-guard.test.ts +++ b/__tests__/hooks/state-guard.test.ts @@ -3,6 +3,9 @@ import { describe, it, expect, vi } from "vitest"; import { BUILTIN_POLICIES } from "../../src/hooks/builtin-policies"; import { POLICY_CATALOG } from "../../src/hooks/policy-catalog"; import type { PolicyContext } from "../../src/hooks/policy-types"; +import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; // Same mocks as builtin-policies.test.ts. Nothing under test reads a file or // spawns a process, and these keep it that way: a state guard whose test suite @@ -827,9 +830,17 @@ describe("block-failproofai-commands — the state guard", () => { `grep '${F}_local' ~/.codex/config.toml`, `grep -E '(${F}_local|kiln)' ~/.codex/config.toml`, `grep -rn '${F} config --pause' docs/`, - `rg '(${F}_local)' ~/.config`, `grep -r 'npm uninstall -g ${F}' docs`, ]) expect(await decide(c), c).toBe("allow"); + // rg counts as the real tool only where PATH finds it in /usr/bin or /bin + // (a user-writable ~/.cargo/bin rg could run its arguments). + const systemRg = ["/usr/bin/rg", "/bin/rg"].some((p) => existsSync(p)); + vi.stubEnv("PATH", "/usr/bin:/bin"); + try { + expect(await decide(`rg '(${F}_local)' ~/.config`)).toBe(systemRg ? "allow" : "deny"); + } finally { + vi.unstubAllEnvs(); + } }); it("allows a heredoc that only writes text mentioning the CLI", async () => { @@ -909,6 +920,22 @@ describe("block-failproofai-commands — the state guard", () => { } }); + it("treats a bare tool name as the real tool only when PATH finds it in a system directory", async () => { + // A user-writable directory earlier on PATH (~/.local/bin, a package + // manager's bin) can hold a `grep` that runs its arguments. + const dir = mkdtempSync(join(tmpdir(), "fp-guard-path-")); + try { + writeFileSync(join(dir, "grep"), '#!/bin/sh\neval "$1"\n', { mode: 0o755 }); + vi.stubEnv("PATH", `${dir}:/usr/bin:/bin`); + expect(await decide(`grep '(${F} config --pause)' f`)).toBe("deny"); + vi.stubEnv("PATH", `/usr/bin:/bin:${dir}`); + expect(await decide(`grep -E '(${F}_local|kiln)' f`)).toBe("allow"); + } finally { + vi.unstubAllEnvs(); + rmSync(dir, { recursive: true, force: true }); + } + }); + it("sees a PATH assignment the shell assembles from quoted or escaped pieces", async () => { for (const c of [ `PA""TH=/tmp/x grep '(${F} config --pause)' f`, diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 9efac1163..43040f55c 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2,7 +2,7 @@ * Built-in security policies for Claude Code hooks. */ import { resolve, join } from "node:path"; -import { lstatSync, readlinkSync, statSync } from "node:fs"; +import { accessSync, constants as fsConstants, lstatSync, readlinkSync, statSync } from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; import { execSync, execFileSync } from "node:child_process"; import { homedir } from "node:os"; @@ -2909,7 +2909,20 @@ const SYSTEM_TOOL_DIRS = new Set(["/usr/bin", "/bin"]); function standardToolName(word: string): string | undefined { if (!word.includes("/")) { const entries = (process.env.PATH ?? "").split(":"); - return entries.some((e) => !e.startsWith("/")) ? undefined : word; + if (entries.some((e) => !e.startsWith("/"))) return undefined; + // The program PATH finds first must itself be in a system directory: a + // user-writable PATH entry (~/.local/bin, a package manager's bin) earlier + // than /usr/bin could hold a `grep` that runs its arguments. + for (const e of entries) { + const dir = e.replace(/\/+$/, "") || "/"; + try { + accessSync(`${dir}/${word}`, fsConstants.X_OK); + } catch { + continue; + } + return SYSTEM_TOOL_DIRS.has(dir) ? word : undefined; + } + return undefined; } const slash = word.lastIndexOf("/"); const dir = word.slice(0, slash).replace(/\/+$/, "") || "/"; From f1aa4d8f8dcabc0dd3d943e37511915b8180e556 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 17:04:16 +0530 Subject: [PATCH 44/54] Self Reports: strict ownership for the report exemption; skip HOME's own configs Review round 2 on F19. Two problems in the early-allow ownership check: - isOurMcpEntry trusts any command whose basename contains "failproofai", so a foreign executable named like ours, registered with our arguments, got the exemption and ran the pause CLI. The exemption now uses a strict test (selfReportEntryStrictlyOurs): a stdio entry whose command realpaths to this failproofai's own CLI entry point (the package's bin/failproofai.mjs or dist/cli.mjs, from FAILPROOFAI_PACKAGE_ROOT or the module's own location), with exactly `mcp --agent `. Loopback HTTP entries are refused for the exemption (sync no longer writes them, and the hook cannot cheaply prove who answers the port). isOurMcpEntry still serves install and uninstall. - For a cwd beneath HOME, the project-override walk reached the installer's own user-scope files (~/.codex/config.toml, ~/.cursor/mcp.json, ...) and refused the genuine registration (fail-closed when the daemon is down). Every agent's user-scope config path, honouring CODEX_HOME and the other overrides, is now skipped by the project scan; real project overrides are still refused. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/helpers/self-report-registration.ts | 8 +- __tests__/hooks/self-report-handler.test.ts | 78 ++++++++++- src/hooks/self-report-install.ts | 128 +++++++++++++++++- 4 files changed, 205 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 23687953c..318acbaf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,7 @@ - Self Reports: the Pi extension asks for the `report` tool again, at most once a minute, when a session starts or a prompt is sent, not only when Pi loads. A Pi started while Self Reports was off, or while it waited for FailproofAI Cloud's setting, kept no tool until it was reloaded; it now gets the tool from its next prompt, and turning Self Reports off takes the tool out of Pi's active tools (#1062) - Self Reports: the stdio server sends the daemon a report's whole detail (bounded at 2000 characters) for its log line, so secrets are scrubbed from all of it before the line is cut to 40 characters. It used to cut the detail to 200 characters first, and a JWT longer than that reached the scrubber in pieces and its start was logged (#1062) - Self Reports: the daemon and hook log lines show the category the model sent (`category`, `raw_category`) only when it is shaped like a category name (lowercase, at most 32 characters, at most 4 digits); anything else, such as a token passed as the category, is logged as `(N characters, not shown)`. It was logged verbatim over both stdio and HTTP (#1062) +- Self Reports: the `report` tool's exemption from the policies now needs a stdio entry whose command, followed through every link, is this failproofai's own CLI entry point, run as `mcp --agent `; a foreign program merely named like failproofai, or a loopback HTTP entry, takes the policy path. A project beneath your home directory no longer has the agents' own user-wide configs (`~/.codex/config.toml`, `~/.cursor/mcp.json`, …) read as project overrides, which refused the genuine tool there (#1062) ### Docs diff --git a/__tests__/helpers/self-report-registration.ts b/__tests__/helpers/self-report-registration.ts index c4c66b72e..759ef760c 100644 --- a/__tests__/helpers/self-report-registration.ts +++ b/__tests__/helpers/self-report-registration.ts @@ -5,6 +5,7 @@ * of the early allow needs a HOME like this one. Never the developer's real * agent configs: HOME and every agent-home override point into `home`. */ +import { resolve } from "node:path"; import { vi } from "vitest"; import { syncSelfReportMcp } from "../../src/hooks/self-report-install"; @@ -20,8 +21,11 @@ export function isolateAgentHome(home: string): void { for (const k of AGENT_HOME_ENV) vi.stubEnv(k, ""); } -/** The stdio command the registrations name (never run by these tests). */ -export const REGISTERED_CLI = "/usr/local/bin/" + "fail" + "proofai"; +/** + * The stdio command the registrations name: this checkout's own CLI entry + * point, which the report exemption requires (never run by these tests). + */ +export const REGISTERED_CLI = resolve(__dirname, "..", "..", "bin", "fail" + "proofai.mjs"); /** Write failproofai's own `failproofai_local` entry for every agent under the isolated HOME. */ export async function registerOwnSelfReportServer(): Promise { diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index fc70cc5e3..113750c94 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -6,7 +6,7 @@ * call) shows the same setup really does deny, so an allow is not vacuous. */ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -40,7 +40,7 @@ import { _resetForTest } from "../../src/hooks/hook-activity-store"; import { INTEGRATION_TYPES } from "../../src/hooks/types"; import { HEALTH_PROBE_SOURCE } from "../../src/hooks/health-probe"; import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; -import { isolateAgentHome, registerOwnSelfReportServer } from "../helpers/self-report-registration"; +import { REGISTERED_CLI, isolateAgentHome, registerOwnSelfReportServer } from "../helpers/self-report-registration"; const SESSION = "sr-session"; let home: string; @@ -618,3 +618,77 @@ describe("the agent process behind a hook-recorded report (F14)", () => { expect(rows().pop()).not.toHaveProperty("selfReportAgentPids"); }); }); + +describe("the early allow, round 2 (F19): strict ownership, and HOME's own configs are not project overrides", () => { + const userHome = () => join(home, "user"); + const claudeJson = () => join(userHome(), ".claude.json"); + const readJson = (p: string) => JSON.parse(readFileSync(p, "utf8")) as Record; + const at = (cwd: string, tool = "mcp__failproofai_local__report") => + JSON.stringify({ session_id: SESSION, cwd, tool_name: tool, tool_input: { category: "looping", detail: "x" } }); + + it("a project beneath HOME: the installer's own user-wide files on the way up are not overrides", async () => { + // sync wrote ~/.claude.json, ~/.codex/config.toml, ~/.cursor/mcp.json, … under this HOME. + const below = join(userHome(), "work", "project"); + mkdirSync(below, { recursive: true }); + expect(readFileSync(join(userHome(), ".codex", "config.toml"), "utf8")).toContain("failproofai_local"); + expect(readFileSync(join(userHome(), ".cursor", "mcp.json"), "utf8")).toContain("failproofai_local"); + for (const [cli, tool] of [["claude", "mcp__failproofai_local__report"], ["codex", "mcp__failproofai_local__report"], ["factory", "failproofai_local___report"]] as const) { + const out = await evaluateHookEvent("PreToolUse", cli, at(below, tool)); + expect(out.evaluation?.decision, cli).toBe("allow"); + } + // A cwd of HOME itself too. + expect((await evaluateHookEvent("PreToolUse", "claude", at(userHome()))).evaluation?.decision).toBe("allow"); + }); + + it("a genuine project override beneath HOME is still refused", async () => { + const below = join(userHome(), "work", "project"); + mkdirSync(join(below, ".cursor"), { recursive: true }); + writeFileSync(join(below, ".mcp.json"), JSON.stringify({ mcpServers: { failproofai_local: { command: "node", args: ["x.js"] } } })); + expect((await evaluateHookEvent("PreToolUse", "claude", at(below))).evaluation?.decision).toBe("deny"); + }); + + it("CODEX_HOME elsewhere: that file is Codex's user config and is skipped too", async () => { + const codexHome = join(home, "codex-home"); + mkdirSync(codexHome, { recursive: true }); + // No ~/.codex left over: with CODEX_HOME elsewhere it would be project config. + rmSync(join(userHome(), ".codex"), { recursive: true, force: true }); + vi.stubEnv("CODEX_HOME", codexHome); + await registerOwnSelfReportServer(); + const below = join(userHome(), "p"); + mkdirSync(below, { recursive: true }); + expect((await evaluateHookEvent("PreToolUse", "codex", at(below))).evaluation?.decision).toBe("allow"); + }); + + it("a foreign program named like failproofai, registered with our arguments, gets no exemption", async () => { + const dir = join(home, "x"); + mkdirSync(dir, { recursive: true }); + const foreign = join(dir, "fail" + "proofai-mcp"); + writeFileSync(foreign, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + for (const command of [foreign, join(dir, "fail" + "proofai")]) { + if (command !== foreign) writeFileSync(command, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + const cfg = readJson(claudeJson()); + (cfg.mcpServers as Record).failproofai_local = { type: "stdio", command, args: ["mcp", "--agent", "claude"], alwaysLoad: true }; + writeFileSync(claudeJson(), JSON.stringify(cfg)); + vi.mocked(loadAllCustomHooks).mockClear(); + const out = await evaluateHookEvent("PreToolUse", "claude", report()); + expect(out.evaluation?.decision, command).toBe("deny"); + expect(loadAllCustomHooks).toHaveBeenCalled(); + } + }); + + it("our CLI by another path that resolves to it is ours; another agent's arguments or an HTTP entry is not", async () => { + const link = join(home, "fail" + "proofai-link"); + symlinkSync(REGISTERED_CLI, link); + const set = (entry: Record) => { + const cfg = readJson(claudeJson()); + (cfg.mcpServers as Record).failproofai_local = entry; + writeFileSync(claudeJson(), JSON.stringify(cfg)); + }; + set({ type: "stdio", command: link, args: ["mcp", "--agent", "claude"] }); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("allow"); + set({ type: "stdio", command: link, args: ["mcp", "--agent", "codex"] }); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); + set({ type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude" }); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); + }); +}); diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index d51b07a41..0b71a3f61 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -93,6 +93,7 @@ import { accessSync, constants as fsConstants, existsSync, mkdirSync, readFileSy import { execSync } from "node:child_process"; import { homedir, userInfo } from "node:os"; import { basename, dirname, resolve, sep } from "node:path"; +import { fileURLToPath } from "node:url"; import { parse as parseToml } from "smol-toml"; import { applyEdits, modify, parse as parseJsonc, type ParseError } from "jsonc-parser/lib/esm/main.js"; import { isMap, type Document } from "yaml"; @@ -1110,10 +1111,47 @@ function definesServer(doc: unknown): boolean { }); } +/** `path` with symlinks resolved when it exists, else as given (absolute). */ +function realOrResolved(path: string): string { + try { + return realpathSync(path); + } catch { + return resolve(path); + } +} + +/** + * Every agent's USER-scope config file, as the installer writes them (each + * honours its own override: `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, `XDG_CONFIG_HOME`, + * `PI_CODING_AGENT_DIR`, the Hermes/OpenClaw profiles, …). A walk up from a + * project beneath HOME meets several of them (`~/.codex/config.toml`, + * `~/.cursor/mcp.json`); they hold our own user-wide registration, not a + * project override, so the project scan skips them. + */ +function userScopeConfigPaths(): Set { + const out = new Set(); + for (const agent of INTEGRATION_TYPES) { + const target = SELF_REPORT_MCP_TARGETS[agent]; + if (!target) continue; + try { + for (const p of target.paths()) out.add(realOrResolved(p)); + } catch { + // A profile list that cannot be read adds nothing: the scan stays strict. + } + } + // OpenCode's user config may be either spelling. + const opencodeDir = resolve(homedir(), ".config", "opencode"); + out.add(realOrResolved(resolve(opencodeDir, "opencode.json"))); + out.add(realOrResolved(resolve(opencodeDir, "opencode.jsonc"))); + return out; +} + /** * Whether any project-scope config at or above `cwd` defines a server named * `failproofai_local` (or names it in a way that cannot be read). Claude * Code's local scope (`projects[].mcpServers` in `.claude.json`) counts. + * Agents' user-scope files met on the way up are not project config and are + * skipped (`userScopeConfigPaths`). */ function projectDefinesSelfReportServer(cwd: string): boolean { const want = SELF_REPORT_SERVER_NAME.toLowerCase(); @@ -1122,10 +1160,12 @@ function projectDefinesSelfReportServer(cwd: string): boolean { dirs.push(d); if (dirname(d) === d) break; } + const userFiles = userScopeConfigPaths(); for (const dir of dirs) { for (const rel of PROJECT_MCP_FILES) { const path = resolve(dir, rel); if (!existsSync(path)) continue; + if (userFiles.has(realOrResolved(path))) continue; let text: string; try { text = readFileSync(path, "utf8"); @@ -1173,14 +1213,86 @@ function projectDefinesSelfReportServer(cwd: string): boolean { return false; } +/** + * The real paths of this failproofai's own CLI entry points: the package's + * `bin/failproofai.mjs` (what npm's and bun's global `failproofai` link to, + * and what the installer writes as the stdio command) and its bundled + * `dist/cli.mjs`. The package is `FAILPROOFAI_PACKAGE_ROOT` (set by the CLI + * and the daemon's worker), else found by walking up from this module. + */ +function selfReportOwnCliEntries(): Set { + const out = new Set(); + const roots: string[] = []; + const fromEnv = process.env.FAILPROOFAI_PACKAGE_ROOT?.trim(); + if (fromEnv) roots.push(fromEnv); + try { + let dir = dirname(fileURLToPath(import.meta.url)); + for (let i = 0; i < 8; i++) { + if (existsSync(resolve(dir, "bin", "failproofai.mjs")) && existsSync(resolve(dir, "package.json"))) { + roots.push(dir); + break; + } + const up = dirname(dir); + if (up === dir) break; + dir = up; + } + } catch { + // No module URL (a CJS bundle): the environment is the only source. + } + for (const root of roots) { + for (const rel of [["bin", "failproofai.mjs"], ["dist", "cli.mjs"]]) { + try { + out.add(realpathSync(resolve(root, ...rel))); + } catch { + // not in this layout + } + } + } + return out; +} + +/** + * The strict test the report exemption uses (stricter than `isOurMcpEntry`, + * which install and uninstall use and which trusts any command whose name + * contains `failproofai`): a stdio entry whose command, followed through every + * symlink, IS this failproofai's own CLI entry point, run as `mcp --agent + * ` and nothing else. A loopback HTTP entry is not accepted: sync + * writes none any more, and the hook cannot cheaply prove which process + * answers that port, so it takes the policy path until sync moves it to stdio. + */ +export function selfReportEntryStrictlyOurs(entry: unknown, agent: IntegrationType, ownEntries: Set = selfReportOwnCliEntries()): boolean { + if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false; + const e = entry as Record; + if (["url", "serverUrl", "uri"].some((k) => e[k] !== undefined)) return false; + let command: unknown; + let args: unknown; + if (Array.isArray(e.command)) { + command = e.command[0]; + args = e.command.slice(1); + } else { + command = typeof e.command === "string" ? e.command : e.cmd; + args = e.args; + } + if (typeof command !== "string" || !command.startsWith("/")) return false; + if (!Array.isArray(args) || args.length !== 3 || args[0] !== "mcp" || args[1] !== "--agent" || args[2] !== agent) return false; + let real: string; + try { + real = realpathSync(command); + } catch { + return false; + } + return ownEntries.has(real); +} + /** * Whether the `failproofai_local` server `agent` would talk to from `cwd` is * failproofai's, so its `report` tool may skip the policies (the hook's early * allow). Fails closed: anything that cannot be shown to be ours is not. * - * - The user-scope entry must pass the installer's own ownership test - * (`isOurMcpEntry`: our stdio command `… mcp --agent X` or our loopback URL), - * in every file the agent reads (one per Hermes/OpenClaw profile). + * - The user-scope entry must be strictly ours (`selfReportEntryStrictlyOurs`: + * a stdio command that resolves to this failproofai's own CLI entry point, + * `mcp --agent `), in every file the agent reads (one per + * Hermes/OpenClaw profile). A foreign program merely named like ours is not. * - For an agent whose tool comes from failproofai's own plugin (Pi, Hermes, * OpenClaw), there must be no foreign entry of that name: one would collide * with our tool's name. @@ -1195,11 +1307,15 @@ export function selfReportRegistrationOwned(agent: IntegrationType, cwd: string if (projectScoped && (typeof cwd !== "string" || cwd.trim() === "")) return false; try { let ours = false; + const ownEntries = selfReportOwnCliEntries(); for (const path of target.paths()) { if (!existsSync(path)) continue; - const state = opsFor(target, path).current().state; - if (state === "foreign") return false; - if (state === "ours") ours = true; + const cur = opsFor(target, path).current(); + if (cur.state === "foreign") return false; + if (cur.state === "ours") { + if (!selfReportEntryStrictlyOurs(cur.entry, agent, ownEntries)) return false; + ours = true; + } } if (!ours && !target.extension) return false; return !projectScoped || !projectDefinesSelfReportServer(cwd as string); From 4d760e3d4158e6d1f75d65e2290df466cef96a84 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 17:06:47 +0530 Subject: [PATCH 45/54] Hooks: judge a bare grep by the agent's PATH, carried from the hook client Review round 2 on F17: the guard's PATH lookup for a bare grep/rg/jq ran in the daemon's warm worker and so used the service's PATH, not the agent's; a shadow grep early on the agent's PATH ran its quoted argument (the pause CLI) on daemon-backed hooks. The hook client (bin/failproofai.mjs on the daemon path, handleHookEvent in process) now puts its own PATH in the stdin payload as failproofai_agent_path, only on a payload naming a PATH-sensitive command, bounded at 16,384 characters, and always replacing or dropping a value the payload already had (src/hooks/agent-path.ts). The guard reads the PATH from the payload only; with none (an older client, the Hermes/OpenClaw plugins that call the daemon directly) a bare name is not the standard tool and nothing is exempt. The daemon relays stdin untouched, so older daemons and clients stay compatible; crates/PROTOCOL.md documents the client-added keys. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/agent-path.test.ts | 108 ++++++++++++++++++++++++++++ __tests__/hooks/state-guard.test.ts | 12 +++- bin/failproofai.mjs | 5 +- crates/PROTOCOL.md | 16 +++++ src/hooks/agent-path.ts | 60 ++++++++++++++++ src/hooks/builtin-policies.ts | 28 +++++--- src/hooks/handler.ts | 3 +- 8 files changed, 219 insertions(+), 14 deletions(-) create mode 100644 __tests__/hooks/agent-path.test.ts create mode 100644 src/hooks/agent-path.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 318acbaf1..92a8675ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,7 @@ - Self Reports: the stdio server sends the daemon a report's whole detail (bounded at 2000 characters) for its log line, so secrets are scrubbed from all of it before the line is cut to 40 characters. It used to cut the detail to 200 characters first, and a JWT longer than that reached the scrubber in pieces and its start was logged (#1062) - Self Reports: the daemon and hook log lines show the category the model sent (`category`, `raw_category`) only when it is shaped like a category name (lowercase, at most 32 characters, at most 4 digits); anything else, such as a token passed as the category, is logged as `(N characters, not shown)`. It was logged verbatim over both stdio and HTTP (#1062) - Self Reports: the `report` tool's exemption from the policies now needs a stdio entry whose command, followed through every link, is this failproofai's own CLI entry point, run as `mcp --agent `; a foreign program merely named like failproofai, or a loopback HTTP entry, takes the policy path. A project beneath your home directory no longer has the agents' own user-wide configs (`~/.codex/config.toml`, `~/.cursor/mcp.json`, …) read as project overrides, which refused the genuine tool there (#1062) +- `block-failproofai-commands` decides whether a bare `grep`/`rg`/`jq` (or `cat`/`tee` for a heredoc) is the standard tool from the agent's own PATH, which the hook client now carries in the payload, not from the PATH of the process evaluating it. Through failproofaid that was the daemon's PATH, so a shadow `grep` early on the agent's PATH could run a quoted argument; with no agent PATH (an older client, the Hermes and OpenClaw plugins) no bare name is exempt (#1062) ### Docs diff --git a/__tests__/hooks/agent-path.test.ts b/__tests__/hooks/agent-path.test.ts new file mode 100644 index 000000000..18388681a --- /dev/null +++ b/__tests__/hooks/agent-path.test.ts @@ -0,0 +1,108 @@ +// @vitest-environment node +/** + * F17 round 2: the guard's "is this bare `grep` the real grep" question is + * answered from the AGENT's PATH, which the hook CLI carries in the payload, + * never from the evaluating process's own PATH: in the daemon's warm worker + * that is the service's PATH, and a shadow `grep` early on the agent's PATH + * was judged by it and ran its argument. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +vi.mock("../../src/hooks/hooks-config", () => ({ + readMergedHooksConfig: vi.fn(() => ({ enabledPolicies: [] })), +})); +vi.mock("../../src/hooks/custom-hooks-loader", () => ({ + loadAllCustomHooks: vi.fn(async () => ({ hooks: [], conventionSources: [] })), +})); +vi.mock("../../src/hooks/hook-telemetry", () => ({ + trackHookEvent: vi.fn(() => Promise.resolve()), + flushHookTelemetry: vi.fn(() => Promise.resolve()), +})); +vi.mock("../../lib/telemetry-id", () => ({ getInstanceId: vi.fn(() => "test-instance-id") })); +vi.mock("../../src/hooks/untraced-note", () => ({ noteUntracedAgent: vi.fn(() => false) })); +vi.mock("../../src/hooks/pack-manifest", () => ({ + readInstalledPacks: vi.fn(() => ({ packs: [], errors: [] })), + hasInstalledPacks: vi.fn(() => false), + hasInstalledRegexPacks: vi.fn(() => false), +})); + +import { AGENT_PATH_KEY, AGENT_PATH_MAX, agentPathOf, markAgentPath } from "../../src/hooks/agent-path"; +import { evaluateHookEvent } from "../../src/hooks/handler"; +import { _resetForTest } from "../../src/hooks/hook-activity-store"; + +const F = "fail" + "proofai"; +const bash = (command: string, extra: Record = {}) => + JSON.stringify({ session_id: "s", cwd: "/tmp", tool_name: "Bash", tool_input: { command }, ...extra }); + +describe("markAgentPath (the hook CLI side)", () => { + it("carries this process's PATH on a payload that names a PATH-sensitive command", () => { + const out = JSON.parse(markAgentPath(bash("grep x f"), "/usr/bin:/bin")); + expect(out[AGENT_PATH_KEY]).toBe("/usr/bin:/bin"); + expect(agentPathOf(out)).toBe("/usr/bin:/bin"); + }); + + it("leaves any other payload untouched, and replaces or drops a value the payload already had", () => { + const ls = bash("ls"); + expect(markAgentPath(ls, "/usr/bin")).toBe(ls); + const spoofed = bash("grep x f", { [AGENT_PATH_KEY]: "/usr/bin:/bin" }); + expect(JSON.parse(markAgentPath(spoofed, "/evil:/usr/bin"))[AGENT_PATH_KEY]).toBe("/evil:/usr/bin"); + expect(JSON.parse(markAgentPath(bash("ls", { [AGENT_PATH_KEY]: "/usr/bin" }), "/usr/bin"))).not.toHaveProperty(AGENT_PATH_KEY); + // No PATH, or one past the bound: none carried (so nothing is exempt). + expect(JSON.parse(markAgentPath(spoofed, ""))).not.toHaveProperty(AGENT_PATH_KEY); + expect(JSON.parse(markAgentPath(spoofed, "/x".repeat(AGENT_PATH_MAX)))).not.toHaveProperty(AGENT_PATH_KEY); + expect(markAgentPath("{not json grep", "/usr/bin")).toBe("{not json grep"); + }); +}); + +describe("the guard in evaluateHookEvent (what the daemon's worker runs)", () => { + let home: string; + let shadow: string; + + beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "fpai-agent-path-")); + process.env.FAILPROOFAI_HOME = home; + process.env.FAILPROOFAI_STATE_DIR = join(home, "state"); + _resetForTest(join(home, "hook-activity")); + shadow = join(home, "shadow-bin"); + mkdirSync(shadow); + writeFileSync(join(shadow, "grep"), '#!/bin/sh\neval "$1"\n', { mode: 0o755 }); + // The evaluating process (the worker) has a clean PATH throughout. + vi.stubEnv("PATH", "/usr/bin:/bin"); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + delete process.env.FAILPROOFAI_HOME; + delete process.env.FAILPROOFAI_STATE_DIR; + _resetForTest(); + rmSync(home, { recursive: true, force: true }); + }); + + const cmd = `grep '(${F} config --pause)' f`; + const decide = async (payload: string) => (await evaluateHookEvent("PreToolUse", "claude", payload)).evaluation?.decision; + + it("denies when the agent's PATH finds a shadow grep, though the worker's own PATH is clean", async () => { + expect(await decide(bash(cmd, { [AGENT_PATH_KEY]: `${shadow}:/usr/bin:/bin` }))).toBe("deny"); + }); + + it("denies when no agent PATH came with the payload (an older client, a native plugin)", async () => { + expect(await decide(bash(cmd))).toBe("deny"); + }); + + it.runIf(["/usr/bin/grep", "/bin/grep"].some((p) => existsSync(p)))( + "keeps the exemption when the agent's PATH finds the system grep", + async () => { + expect(await decide(bash(`grep -E '(${F}_local|kiln)' f`, { [AGENT_PATH_KEY]: "/usr/bin:/bin" }))).toBe("allow"); + }, + ); + + it("the one-shot hook path stamps the hook process's own PATH (markAgentPath on the real payload)", async () => { + vi.stubEnv("PATH", `${shadow}:/usr/bin:/bin`); + const stamped = markAgentPath(bash(cmd)); + vi.stubEnv("PATH", "/usr/bin:/bin"); + expect(await decide(stamped)).toBe("deny"); + }); +}); diff --git a/__tests__/hooks/state-guard.test.ts b/__tests__/hooks/state-guard.test.ts index 17b5d718e..43f505bde 100644 --- a/__tests__/hooks/state-guard.test.ts +++ b/__tests__/hooks/state-guard.test.ts @@ -3,6 +3,7 @@ import { describe, it, expect, vi } from "vitest"; import { BUILTIN_POLICIES } from "../../src/hooks/builtin-policies"; import { POLICY_CATALOG } from "../../src/hooks/policy-catalog"; import type { PolicyContext } from "../../src/hooks/policy-types"; +import { AGENT_PATH_KEY } from "../../src/hooks/agent-path"; import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -22,8 +23,17 @@ vi.mock("node:child_process", () => ({ execFileSync: vi.fn(), })); +// The payload carries the agent's PATH, as the hook CLI puts it there +// (agent-path.ts); this process's PATH stands for the agent's, read at call +// time so a test's vi.stubEnv("PATH", …) is what the "agent" has. function makeCtx(overrides: Partial = {}): PolicyContext { - return { eventType: "PreToolUse", payload: {}, toolName: undefined, toolInput: undefined, ...overrides }; + return { + eventType: "PreToolUse", + payload: { [AGENT_PATH_KEY]: process.env.PATH }, + toolName: undefined, + toolInput: undefined, + ...overrides, + }; } const policy = BUILTIN_POLICIES.find((p) => p.name === "block-failproofai-commands")!; diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index 82d5df4e3..565e0d329 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -197,10 +197,13 @@ if (hookIdx >= 0) { // from, so its stdio server can tell this call's row from another // session's (self-report-ancestry.ts). const { selfReportMarkAgentPids } = await import("../src/hooks/self-report-ancestry"); + // And this process's PATH (the agent's, unlike the daemon worker's), for + // the guard that asks where a bare `grep` really resolves (agent-path.ts). + const { markAgentPath } = await import("../src/hooks/agent-path"); const attempt = await attemptDaemonHook({ hookEvent: eventType, cli, - stdin: selfReportMarkAgentPids(cli, selfReportMarkDevinOrigin(cli, stdinRead.payload)), + stdin: markAgentPath(selfReportMarkAgentPids(cli, selfReportMarkDevinOrigin(cli, stdinRead.payload))), // The client's own cwd IS the originating CLI session's cwd — this // process is spawned fresh, at that location, by the calling agent // CLI's own hook mechanism. See daemon-client.ts / PROTOCOL.md. diff --git a/crates/PROTOCOL.md b/crates/PROTOCOL.md index ef46e2657..a8f03da8d 100644 --- a/crates/PROTOCOL.md +++ b/crates/PROTOCOL.md @@ -66,6 +66,22 @@ Tagged JSON, `"type"` as the discriminant, camelCase field names. } ``` +`stdin` is the agent's payload with top-level keys added by the hook client, +because only the process the agent started can know them (the daemon's +worker has the daemon's PATH and parent). The client overwrites or removes +each one, so none is ever taken from the payload the agent sent, and the +daemon relays `stdin` untouched, so neither side needs a version bump: an +older daemon carries them, and from an older client they are simply absent. + +- `failproofai_agent_path` (string, at most 16,384 characters): the client's + `PATH`, set only on a payload that names `grep`, `rg`, `jq`, `cat` or `tee`. + `block-failproofai-commands` decides whether a bare command word is the + standard tool from this PATH alone; without it (an older client, or the + Hermes and OpenClaw plugins, which call the daemon directly) nothing is + exempt. +- `failproofai_via_devin` (true): a Claude-path Self Reports call made under + Devin. + ```jsonc // One Self Reports MCP event from outside the daemon — the stdio server // `failproofai mcp` (a child of each agent) or a CLI `self-report sync` — diff --git a/src/hooks/agent-path.ts b/src/hooks/agent-path.ts new file mode 100644 index 000000000..e7c37e23d --- /dev/null +++ b/src/hooks/agent-path.ts @@ -0,0 +1,60 @@ +/** + * The agent's own PATH, carried to wherever a hook is evaluated (review + * finding F17). + * + * `block-failproofai-commands` treats a quoted argument of `grep`/`rg`/`jq` + * (and a heredoc fed to `cat`/`tee`) as data only when the command word is + * the standard tool, which for a bare name means: where the AGENT's PATH finds + * it. On a daemon-configured machine the policy runs in the daemon's warm + * worker, whose PATH is the service's, not the agent's; a shadow `grep` early + * on the agent's PATH was judged by the daemon's PATH and ran its argument. + * + * So the hook CLI, running in the process the agent started, puts its own + * PATH in the stdin payload as `AGENT_PATH_KEY` before it forwards or + * evaluates it (crates/PROTOCOL.md: the daemon relays stdin untouched, so an + * older daemon carries it too, and an older client simply sends none). The + * guard reads it from the payload only; with none (an older client, the + * Hermes/OpenClaw plugins that talk to the daemon directly, a PATH past the + * bound) a bare name is not known to be the standard tool and nothing is + * exempt. Only a payload that could reach that exemption is touched, and a + * value already in the payload is replaced or dropped, never trusted. + */ + +/** Payload key the hook CLI sets to its own PATH. */ +export const AGENT_PATH_KEY = "failproofai_agent_path"; + +/** Longest PATH carried; a longer one is dropped (no exemption). */ +export const AGENT_PATH_MAX = 16_384; + +/** Command words whose exemption depends on PATH (see builtin-policies.ts). */ +const PATH_SENSITIVE_RE = /(?:e|f)?grep|\brg\b|\bjq\b|\bcat\b|\btee\b/; + +/** + * In the hook process: `stdin` with `AGENT_PATH_KEY` set to `path` when the + * payload mentions a PATH-sensitive command word, and with any value it + * already carried removed otherwise. Never throws; an unparseable payload is + * returned as it was. + */ +export function markAgentPath(stdin: string, path: string | undefined = process.env.PATH): string { + const sensitive = PATH_SENSITIVE_RE.test(stdin); + const carried = stdin.includes(AGENT_PATH_KEY); + if (!sensitive && !carried) return stdin; + try { + const parsed = JSON.parse(stdin) as unknown; + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return stdin; + const { [AGENT_PATH_KEY]: _dropped, ...rest } = parsed as Record; + if (sensitive && typeof path === "string" && path.length > 0 && path.length <= AGENT_PATH_MAX) { + return JSON.stringify({ ...rest, [AGENT_PATH_KEY]: path }); + } + return _dropped === undefined ? stdin : JSON.stringify(rest); + } catch { + return stdin; + } +} + +/** The agent PATH a payload carries, or undefined. */ +export function agentPathOf(payload: unknown): string | undefined { + if (!payload || typeof payload !== "object" || Array.isArray(payload)) return undefined; + const v = (payload as Record)[AGENT_PATH_KEY]; + return typeof v === "string" && v.length > 0 && v.length <= AGENT_PATH_MAX ? v : undefined; +} diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 43040f55c..5d74010e3 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2,6 +2,7 @@ * Built-in security policies for Claude Code hooks. */ import { resolve, join } from "node:path"; +import { agentPathOf } from "./agent-path"; import { accessSync, constants as fsConstants, lstatSync, readlinkSync, statSync } from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; import { execSync, execFileSync } from "node:child_process"; @@ -2900,15 +2901,20 @@ const SYSTEM_TOOL_DIRS = new Set(["/usr/bin", "/bin"]); /** * The name of the tool a command word runs, when it is known to be that - * standard tool, else undefined. A bare name (`grep`) is the tool PATH finds, - * unless PATH has a relative entry (`.`, an empty one), which can find a - * program in the project instead. A path (`./grep`, `/tmp/x/grep`) is the - * tool only in `/usr/bin` or `/bin`: anywhere else it is whatever program was - * put there, which may run its arguments. - */ -function standardToolName(word: string): string | undefined { + * standard tool, else undefined. A bare name (`grep`) is the tool the AGENT's + * PATH (`agentPath`, carried in the payload by the hook CLI: agent-path.ts) + * finds, and only when that is in `/usr/bin` or `/bin` and PATH has no + * relative entry (`.`, an empty one), which can find a program in the + * project instead. Never this process's own PATH: in the daemon's worker that + * is the service's. With no agent PATH, a bare name is not known to be the + * tool. A path (`./grep`, `/tmp/x/grep`) is the tool only in `/usr/bin` or + * `/bin`: anywhere else it is whatever program was put there, which may run + * its arguments. + */ +function standardToolName(word: string, agentPath: string | undefined): string | undefined { if (!word.includes("/")) { - const entries = (process.env.PATH ?? "").split(":"); + if (agentPath === undefined) return undefined; + const entries = agentPath.split(":"); if (entries.some((e) => !e.startsWith("/"))) return undefined; // The program PATH finds first must itself be in a system directory: a // user-writable PATH entry (~/.local/bin, a package manager's bin) earlier @@ -2930,7 +2936,7 @@ function standardToolName(word: string): string | undefined { } /** `cmd` with its inert pieces taken out (see above), or `cmd` unchanged. */ -function withoutInertArguments(cmd: string): string { +function withoutInertArguments(cmd: string, agentPath: string | undefined): string { const scanned = scanShellCommands(cmd); if (redefinesCommandWords(cmd, scanned)) return cmd; if (!scanned) return cmd; @@ -2946,7 +2952,7 @@ function withoutInertArguments(cmd: string): string { if (!head) return; // Only the standard tool's arguments are inert: a project's own `./grep` // can `eval "$1"`. - const base = standardToolName(head.word.value); + const base = standardToolName(head.word.value, agentPath); if (base === undefined) return; const args = simple.words.slice(head.at + 1); // rg runs a preprocessor named by `--pre`. @@ -3002,7 +3008,7 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { return allow(); } if (ctx.toolName !== "Bash") return allow(); - return judgeFailproofaiCommand(withoutInertArguments(getCommand(ctx))); + return judgeFailproofaiCommand(withoutInertArguments(getCommand(ctx), agentPathOf(ctx.payload))); } function judgeFailproofaiCommand(cmd: string): PolicyResult { diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index b4df2913f..4aa20fa62 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -69,6 +69,7 @@ import { selfReportLogCategoryText } from "./self-report-names"; import { selfReportFailureHint, selfReportSessionStartContext } from "./self-report-hint"; import { selfReportClaudeHookFromDevin } from "./self-report-devin"; import { SELF_REPORT_AGENT_PIDS_KEY, selfReportAgentPids, selfReportMarkAgentPids } from "./self-report-ancestry"; +import { markAgentPath } from "./agent-path"; import { deliveryHealth, deliveryHealthLine } from "./delivery-health"; import { trackHookEvent, flushHookTelemetry } from "./hook-telemetry"; import * as hookTelemetry from "./hook-telemetry"; @@ -1664,7 +1665,7 @@ export async function handleHookEvent( // The agent process above this hook, for a Claude Code / Codex report call // (self-report-ancestry.ts); the daemon path adds it in the hook CLI. const result = await evaluateHookEvent( - eventType, cli, selfReportMarkAgentPids(cli, stdinRead.payload), + eventType, cli, markAgentPath(selfReportMarkAgentPids(cli, stdinRead.payload)), agentSettingsPath === undefined ? undefined : { agentSettingsPath }, ); From e940852cb0d847d6662a7ddbaba0a379763876eb Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 17:10:29 +0530 Subject: [PATCH 46/54] Self Reports: match rows and sessions to the exact agent process Review round 2 on F14: an agent B started inside agent A (A's shell tool, same directory) had both of its stdio reports attributed to A's session, and "server's parent is any ancestor of the hook" matching let A's server claim B's hook row, since A sits above B's hooks too. Each side now names its agent as the nearest process above it that is not a shell or exec wrapper (sh/bash/env/npx/npm exec, ...), and the two match only when that pid is the same, exactly (selfReportAgentPid). The hook client stamps it (failproofai_report_agent_pid) on Claude Code / Codex report calls and on every agent's SessionStart and UserPromptSubmit events; the worker keeps it on the row as agentPid (local only, replacing the earlier selfReportAgentPids list). The stdio server's session choice takes a session stamped with its own agent first; a session stamped only with another agent's pid is never taken, whatever directory it shares, and is also kept from the Codex rollout and Claude transcript fallbacks; with nothing left the report is unattributed. Unstamped sessions (no readable ancestry, rows from before this) keep the directory ranking. The daemon's HTTP find_session (Hermes/OpenClaw, no process to match) is unchanged. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/self-report-ancestry.test.ts | 80 +++++---- __tests__/hooks/self-report-handler.test.ts | 10 +- .../hooks/self-report-hook-trust.test.ts | 91 ++++++++-- __tests__/hooks/self-report.test.ts | 6 +- bin/failproofai.mjs | 7 +- crates/PROTOCOL.md | 5 + src/hooks/handler.ts | 14 +- src/hooks/hook-activity-store.ts | 21 +-- src/hooks/self-report-ancestry.ts | 168 ++++++++++++------ src/hooks/self-report-hook-trust.ts | 15 +- src/hooks/self-report-mcp.ts | 87 +++++++-- 12 files changed, 347 insertions(+), 158 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 92a8675ab..78091a299 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,7 @@ - Self Reports: the daemon and hook log lines show the category the model sent (`category`, `raw_category`) only when it is shaped like a category name (lowercase, at most 32 characters, at most 4 digits); anything else, such as a token passed as the category, is logged as `(N characters, not shown)`. It was logged verbatim over both stdio and HTTP (#1062) - Self Reports: the `report` tool's exemption from the policies now needs a stdio entry whose command, followed through every link, is this failproofai's own CLI entry point, run as `mcp --agent `; a foreign program merely named like failproofai, or a loopback HTTP entry, takes the policy path. A project beneath your home directory no longer has the agents' own user-wide configs (`~/.codex/config.toml`, `~/.cursor/mcp.json`, …) read as project overrides, which refused the genuine tool there (#1062) - `block-failproofai-commands` decides whether a bare `grep`/`rg`/`jq` (or `cat`/`tee` for a heredoc) is the standard tool from the agent's own PATH, which the hook client now carries in the payload, not from the PATH of the process evaluating it. Through failproofaid that was the daemon's PATH, so a shadow `grep` early on the agent's PATH could run a quoted argument; with no agent PATH (an older client, the Hermes and OpenClaw plugins) no bare name is exempt (#1062) +- Self Reports: the stdio server matches hook rows and picks the session for a report by its own agent process, exactly: each side names the nearest process above it that is not a shell or exec wrapper, and session-start and prompt rows now carry it too. An agent started inside another one in the same directory no longer has its hook rows claimed, or its reports filed, under the outer agent's session; with no session of its own it takes its own transcript, else `unattributed` (#1062) ### Docs diff --git a/__tests__/hooks/self-report-ancestry.test.ts b/__tests__/hooks/self-report-ancestry.test.ts index 420cdc8fd..43dbc25d3 100644 --- a/__tests__/hooks/self-report-ancestry.test.ts +++ b/__tests__/hooks/self-report-ancestry.test.ts @@ -1,61 +1,69 @@ // @vitest-environment node /** - * Which agent process a report call came from (F14): the hook CLI stamps a - * Claude Code / Codex report call with the pids above it, the handler keeps - * them on the activity row, and the stdio server matches only a row from its - * own agent (self-report-hook-trust.test.ts covers the matching). + * Which agent process a hook event or a stdio report came from (F14): the + * nearest process above that is not a shell or exec wrapper, matched EXACTLY + * (self-report-hook-trust.test.ts covers the dedup and the session choice). */ import { describe, expect, it } from "vitest"; import { - SELF_REPORT_AGENT_PIDS_KEY, - selfReportAgentPids, - selfReportAncestorPids, - selfReportMarkAgentPids, + SELF_REPORT_AGENT_PID_KEY, + selfReportAgentPid, + selfReportAgentPidOf, + selfReportAncestry, + selfReportMarkAgentPid, } from "../../src/hooks/self-report-ancestry"; const report = (extra: Record = {}) => JSON.stringify({ session_id: "s", tool_name: "mcp__failproofai_local__report", tool_input: { category: "looping", detail: "x" }, ...extra }); -describe("selfReportAncestorPids", () => { +describe("selfReportAncestry / selfReportAgentPid", () => { it.runIf(process.platform === "linux" || process.platform === "darwin")("starts at this process's parent", () => { - const pids = selfReportAncestorPids(); - expect(pids[0]).toBe(process.ppid); - expect(pids.length).toBeLessThanOrEqual(8); - expect(pids.every((p) => Number.isSafeInteger(p) && p > 1)).toBe(true); + const up = selfReportAncestry(); + expect(up[0].pid).toBe(process.ppid); + expect(up.length).toBeLessThanOrEqual(8); + }); + + it("skips shells and exec wrappers to the agent, and only them", () => { + const tree = (...names: string[]) => () => names.map((name, i) => ({ pid: 100 + i, name })); + expect(selfReportAgentPid(tree("sh", "claude", "bash"))).toBe(101); + expect(selfReportAgentPid(tree("bash", "npm exec failpr", "sh", "codex"))).toBe(103); + expect(selfReportAgentPid(tree("-zsh", "env", "node"))).toBe(102); + // A nested agent: B (its hook runs under B's shell) is found before A. + expect(selfReportAgentPid(tree("sh", "claude", "bash", "claude"))).toBe(101); + expect(selfReportAgentPid(tree("sh", "bash"))).toBeUndefined(); + expect(selfReportAgentPid(() => [])).toBeUndefined(); }); }); -describe("selfReportMarkAgentPids", () => { - const pids = () => [4001, 4000]; +describe("selfReportMarkAgentPid", () => { + const pid = () => 4001; - it("stamps a Claude Code or Codex report call with the pids above the hook", () => { + it("stamps a Claude Code or Codex report call, and any agent's session-start and prompt events", () => { for (const cli of ["claude", "codex"]) { - const out = JSON.parse(selfReportMarkAgentPids(cli, report(), pids)); - expect(out[SELF_REPORT_AGENT_PIDS_KEY]).toEqual([4001, 4000]); + expect(JSON.parse(selfReportMarkAgentPid(cli, "PreToolUse", report(), pid))[SELF_REPORT_AGENT_PID_KEY]).toBe(4001); + } + for (const [cli, event] of [["cursor", "SessionStart"], ["claude", "UserPromptSubmit"], ["copilot", "UserPromptSubmit"]]) { + const payload = JSON.stringify({ session_id: "s", prompt: "hi" }); + expect(JSON.parse(selfReportMarkAgentPid(cli, event, payload, pid))[SELF_REPORT_AGENT_PID_KEY], `${cli} ${event}`).toBe(4001); } - const codex = JSON.stringify({ tool_name: "mcp__failproofai_local__report", tool_input: {} }); - expect(JSON.parse(selfReportMarkAgentPids("codex", codex, pids))[SELF_REPORT_AGENT_PIDS_KEY]).toEqual([4001, 4000]); }); - it("leaves every other call, and every other agent, as it was", () => { + it("leaves every other call as it was, and replaces or drops a value the payload carried", () => { const bash = JSON.stringify({ tool_name: "Bash", tool_input: { command: "ls failproofai_local" } }); - expect(selfReportMarkAgentPids("claude", bash, pids)).toBe(bash); - expect(selfReportMarkAgentPids("cursor", report(), pids)).toBe(report()); - expect(selfReportMarkAgentPids("claude", "{not json failproofai_local", pids)).toBe("{not json failproofai_local"); - }); - - it("replaces pids a payload already carried, and drops them when none can be read", () => { - const spoofed = report({ [SELF_REPORT_AGENT_PIDS_KEY]: [12345] }); - expect(JSON.parse(selfReportMarkAgentPids("claude", spoofed, pids))[SELF_REPORT_AGENT_PIDS_KEY]).toEqual([4001, 4000]); - expect(JSON.parse(selfReportMarkAgentPids("claude", spoofed, () => []))).not.toHaveProperty(SELF_REPORT_AGENT_PIDS_KEY); + expect(selfReportMarkAgentPid("claude", "PreToolUse", bash, pid)).toBe(bash); + expect(selfReportMarkAgentPid("cursor", "PreToolUse", report(), pid)).toBe(report()); + const spoofed = report({ [SELF_REPORT_AGENT_PID_KEY]: 12345 }); + expect(JSON.parse(selfReportMarkAgentPid("claude", "PreToolUse", spoofed, pid))[SELF_REPORT_AGENT_PID_KEY]).toBe(4001); + expect(JSON.parse(selfReportMarkAgentPid("claude", "PreToolUse", spoofed, () => undefined))).not.toHaveProperty(SELF_REPORT_AGENT_PID_KEY); + const bashSpoof = JSON.stringify({ tool_name: "Bash", [SELF_REPORT_AGENT_PID_KEY]: 5 }); + expect(JSON.parse(selfReportMarkAgentPid("claude", "PreToolUse", bashSpoof, pid))).not.toHaveProperty(SELF_REPORT_AGENT_PID_KEY); + expect(selfReportMarkAgentPid("claude", "SessionStart", "{not json", pid)).toBe("{not json"); }); }); -describe("selfReportAgentPids", () => { - it("keeps only real pids, at most eight", () => { - expect(selfReportAgentPids([5, "6", 1, 0, -3, 7.5, 9])).toEqual([5, 9]); - expect(selfReportAgentPids(Array.from({ length: 20 }, (_, i) => i + 2))).toHaveLength(8); - expect(selfReportAgentPids([1])).toBeUndefined(); - expect(selfReportAgentPids("5")).toBeUndefined(); +describe("selfReportAgentPidOf", () => { + it("keeps only a real pid", () => { + expect(selfReportAgentPidOf(5)).toBe(5); + for (const v of [1, 0, -3, 7.5, "6", [5], undefined]) expect(selfReportAgentPidOf(v)).toBeUndefined(); }); }); diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index 113750c94..0ef9a9e60 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -605,17 +605,17 @@ describe("the agent process behind a hook-recorded report (F14)", () => { it("keeps the pids the hook CLI stamped on the report row, and only there", async () => { await evaluateHookEvent( "PreToolUse", "claude", - report({ tool_use_id: "toolu_p", failproofai_report_agent_pids: [6001, 6000, "x", 1] }), + report({ tool_use_id: "toolu_p", failproofai_report_agent_pid: 6001 }), ); - expect(rows().pop()).toMatchObject({ toolCallId: "toolu_p", selfReport: { detail: "tracker rejected its API key" }, selfReportAgentPids: [6001, 6000] }); + expect(rows().pop()).toMatchObject({ toolCallId: "toolu_p", selfReport: { detail: "tracker rejected its API key" }, agentPid: 6001 }); // A PostToolUse row is no report, so it carries none. - await evaluateHookEvent("PostToolUse", "claude", report({ failproofai_report_agent_pids: [6001] })); - expect(rows().pop()).not.toHaveProperty("selfReportAgentPids"); + await evaluateHookEvent("PostToolUse", "claude", report({ failproofai_report_agent_pid: "6001" })); + expect(rows().pop()).not.toHaveProperty("agentPid"); }); it("a report row with no pids stamped carries none", async () => { await evaluateHookEvent("PreToolUse", "claude", report()); - expect(rows().pop()).not.toHaveProperty("selfReportAgentPids"); + expect(rows().pop()).not.toHaveProperty("agentPid"); }); }); diff --git a/__tests__/hooks/self-report-hook-trust.test.ts b/__tests__/hooks/self-report-hook-trust.test.ts index e4497859d..5d04c10b1 100644 --- a/__tests__/hooks/self-report-hook-trust.test.ts +++ b/__tests__/hooks/self-report-hook-trust.test.ts @@ -22,6 +22,8 @@ import { } from "../../src/hooks/self-report-mcp"; import { selfReportCliDirs, resolveSelfReportCliPath, syncSelfReportMcp } from "../../src/hooks/self-report-install"; import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; +import { selfReportServerAgentPid } from "../../src/hooks/self-report-ancestry"; +import { selfReportFindSessionMatch, writeSelfReportEvent } from "../../src/hooks/self-report-mcp"; import { runSelfReportCommand } from "../../src/hooks/self-report-cli"; const BIN = "/usr/local/bin/failproofai"; @@ -219,16 +221,16 @@ describe("the server records what the hook did not, once", () => { return []; } }; - // A hook row records the pids above its hook process; this test process's - // parent stands for "this server's agent" (the server's own default). - const AGENT = process.ppid; + // A hook row records the agent process above its hook; this server's own + // agent (what the server reads from its process tree) stands for "ours". + const AGENT = selfReportServerAgentPid() ?? 0; const hookRow = (over: Record) => { mkdirSync(join(home, ".failproofai", "hook-activity"), { recursive: true }); writeFileSync( join(home, ".failproofai", "hook-activity", "current.jsonl"), JSON.stringify({ timestamp: Date.now() - 1000, eventType: "PreToolUse", integration: "codex", sessionId: "s", decision: "allow", - selfReportAgentPids: [4242, AGENT], ...over, + agentPid: AGENT, ...over, }) + "\n", ); }; @@ -241,7 +243,7 @@ describe("the server records what the hook did not, once", () => { join(home, ".failproofai", "hook-activity", "current.jsonl"), rows.map((over) => JSON.stringify({ timestamp: Date.now() - 1000, eventType: "PreToolUse", integration: "codex", sessionId: "s", decision: "allow", - selfReportAgentPids: [4242, AGENT], ...over, + agentPid: AGENT, ...over, })).join("\n") + "\n", ); }; @@ -303,21 +305,79 @@ describe("the server records what the hook did not, once", () => { const A = 31001; const B = 31002; // Session A's hook recorded its report; session B's hooks did not run. - hookRows({ cwd: projA, sessionId: "sA", toolCallId: "tA", selfReport: { ...args, source: "mcp" }, selfReportAgentPids: [31000, A, 1000] }); + hookRows({ cwd: projA, sessionId: "sA", toolCallId: "tA", selfReport: { ...args, source: "mcp" }, agentPid: A }); // B's identical report arrives first: not A's row, so B's server records it. expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, B)).toBe(false); // A's call still finds its own row, which B did not consume. expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, A)).toBe(true); - // A shared ancestor above both agents (the shell, pid 1000) is not the agent: - // the server's PARENT must be among the row's pids, and B's parent is B. - expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, B)).toBe(false); + }); + + // Round 2: B started INSIDE A (A's shell tool runs it, same directory). A is + // an ancestor of B's hooks, so "any ancestor" matching let A's server claim + // B's row; the match is now the exact agent pid each side names. + it("a nested agent's hook row is never claimed by the agent it runs inside", () => { + const args = { category: "looping", detail: "same words" }; + const A = 61001; + const B = 61002; // a child of A's shell + hookRows({ cwd: projA, sessionId: "sB", toolCallId: "tB", selfReport: { ...args, source: "mcp" }, agentPid: B }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, A)).toBe(false); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, B)).toBe(true); + }); + + it("a nested agent's report is filed under its own session, never the outer agent's", async () => { + writeEffectiveSelfReport({ enabled: true }); + const A = 71001; + const B = 71002; + // A's session is known (its session-start/prompt rows carry A); B's hooks + // did not run, so B has no rows at all. + hookRows( + { cwd: projA, sessionId: "session-A", eventType: "SessionStart", agentPid: A }, + { cwd: projA, sessionId: "session-A", eventType: "UserPromptSubmit", agentPid: A }, + ); + const excluded = new Set(); + expect(selfReportFindSessionMatch("claude", projA, Date.now(), B, excluded)).toBeNull(); + expect([...excluded]).toEqual([]); // other integration's rows are not looked at + hookRows( + { integration: "claude", cwd: projA, sessionId: "session-A", eventType: "SessionStart", agentPid: A }, + { integration: "claude", cwd: projA, sessionId: "session-A", eventType: "UserPromptSubmit", agentPid: A }, + ); + expect(selfReportFindSessionMatch("claude", projA, Date.now(), B, excluded)).toBeNull(); + expect([...excluded]).toEqual(["session-A"]); + // A's own server still finds A's session. + expect(selfReportFindSessionMatch("claude", projA, Date.now(), A)?.sessionId).toBe("session-A"); + // Once B's own rows exist they win, exactly. + hookRows( + { integration: "claude", cwd: projA, sessionId: "session-A", eventType: "UserPromptSubmit", agentPid: A }, + { integration: "claude", cwd: projA, sessionId: "session-B", eventType: "SessionStart", agentPid: B, timestamp: Date.now() - 5000 }, + ); + expect(selfReportFindSessionMatch("claude", projA, Date.now(), B)?.sessionId).toBe("session-B"); + // Written end to end: B's report with no rows of its own is not A's. The + // transcript fallback may not hand back A's session either. + hookRows( + { integration: "claude", cwd: projA, sessionId: "session-A", eventType: "SessionStart", agentPid: A }, + ); + const transcripts = join(home, ".claude", "projects", projA.replace(/[^A-Za-z0-9]/g, "-")); + mkdirSync(transcripts, { recursive: true }); + writeFileSync(join(transcripts, "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa.jsonl"), "{}\n"); + vi.stubEnv("CLAUDE_CONFIG_DIR", join(home, ".claude")); + try { + const fromB = await writeSelfReportEvent({ integration: "claude", category: "looping", detail: "x", cwd: projA, agentPid: B }); + expect(fromB.event.session_id).toBe("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"); + hookRows( + { integration: "claude", cwd: projA, sessionId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", eventType: "SessionStart", agentPid: A }, + ); + const again = await writeSelfReportEvent({ integration: "claude", category: "looping", detail: "x", cwd: projA, agentPid: B }); + expect(again.event.session_id).toBe("unattributed"); + } finally { + vi.unstubAllEnvs(); + } }); it("each of two sessions in one directory claims only its own row", () => { const args = { category: "looping", detail: "same words" }; hookRows( - { cwd: projA, sessionId: "s1", toolCallId: "t1", selfReport: { ...args, source: "mcp" }, selfReportAgentPids: [51001] }, - { cwd: projA, sessionId: "s2", toolCallId: "t2", selfReport: { ...args, source: "mcp" }, selfReportAgentPids: [51002] }, + { cwd: projA, sessionId: "s1", toolCallId: "t1", selfReport: { ...args, source: "mcp" }, agentPid: 51001 }, + { cwd: projA, sessionId: "s2", toolCallId: "t2", selfReport: { ...args, source: "mcp" }, agentPid: 51002 }, ); expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 51002)).toBe(true); expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 51002)).toBe(false); @@ -326,13 +386,14 @@ describe("the server records what the hook did not, once", () => { it("a row that does not say which agent process wrote it never vouches for a call: the report is recorded", () => { const args = { category: "looping", detail: "same words" }; - hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, selfReportAgentPids: undefined }); + hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, agentPid: undefined }); expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); - hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, selfReportAgentPids: ["x", 1] }); + hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, agentPid: "x" }); expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); - // A server whose parent is gone (reparented to init) cannot be matched either. - hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, selfReportAgentPids: [1] }); + // A server whose agent is gone (reparented to init) cannot be matched either. + hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, agentPid: 1 }); expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 1)).toBe(false); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, undefined)).toBe(false); }); it("an untrusted Codex's report lands once, on the session Codex's own rollout names", async () => { diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index 1fe447207..5d124f14c 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -588,7 +588,7 @@ describe("failproofai mcp (stdio, spawned)", () => { JSON.stringify({ timestamp: Date.now() - 500, eventType: "PreToolUse", integration: "claude", sessionId: "c1", decision: "allow", cwd: home, toolName: "mcp__failproofai_local__report", selfReport: { ...CALL_ARGS, source: "mcp" }, - selfReportAgentPids: [77777, process.pid], + agentPid: process.pid, }) + "\n", ); await runMcp(["--agent", "claude"], [INIT, CALL], home); @@ -605,7 +605,7 @@ describe("failproofai mcp (stdio, spawned)", () => { JSON.stringify({ timestamp: Date.now() - 500, eventType: "PreToolUse", integration: "claude", sessionId: "other", decision: "allow", cwd: home, toolName: "mcp__failproofai_local__report", selfReport: { ...CALL_ARGS, source: "mcp" }, - selfReportAgentPids: [77777, 77776], + agentPid: 77776, }) + "\n", ); await runMcp(["--agent", "claude"], [INIT, CALL], home); @@ -1053,6 +1053,6 @@ describe("failproofai self-report enable | disable | status", () => { const last = rows.pop(); expect(last).toMatchObject({ toolName: "mcp__failproofai_local__report", decision: "allow", selfReport: { source: "mcp" } }); // The real hook process stamped the agent above it: this test process started it. - if (process.platform === "linux" || process.platform === "darwin") expect(last.selfReportAgentPids).toContain(process.pid); + if (process.platform === "linux" || process.platform === "darwin") expect(last.agentPid).toBe(process.pid); }, 30_000); }); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index 565e0d329..f449c3599 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -196,14 +196,17 @@ if (hookIdx >= 0) { // Likewise which agent process a Claude Code / Codex report call came // from, so its stdio server can tell this call's row from another // session's (self-report-ancestry.ts). - const { selfReportMarkAgentPids } = await import("../src/hooks/self-report-ancestry"); + const { selfReportMarkAgentPid } = await import("../src/hooks/self-report-ancestry"); + const { canonicalizeEventType } = await import("../src/hooks/handler"); // And this process's PATH (the agent's, unlike the daemon worker's), for // the guard that asks where a bare `grep` really resolves (agent-path.ts). const { markAgentPath } = await import("../src/hooks/agent-path"); const attempt = await attemptDaemonHook({ hookEvent: eventType, cli, - stdin: markAgentPath(selfReportMarkAgentPids(cli, selfReportMarkDevinOrigin(cli, stdinRead.payload))), + stdin: markAgentPath( + selfReportMarkAgentPid(cli, canonicalizeEventType(eventType, cli), selfReportMarkDevinOrigin(cli, stdinRead.payload)), + ), // The client's own cwd IS the originating CLI session's cwd — this // process is spawned fresh, at that location, by the calling agent // CLI's own hook mechanism. See daemon-client.ts / PROTOCOL.md. diff --git a/crates/PROTOCOL.md b/crates/PROTOCOL.md index a8f03da8d..183a57285 100644 --- a/crates/PROTOCOL.md +++ b/crates/PROTOCOL.md @@ -79,6 +79,11 @@ older daemon carries them, and from an older client they are simply absent. standard tool from this PATH alone; without it (an older client, or the Hermes and OpenClaw plugins, which call the daemon directly) nothing is exempt. +- `failproofai_report_agent_pid` (number): the agent process above the hook + (the nearest that is not a shell or exec wrapper), on a Claude Code / Codex + Self Reports call and on every agent's session-start and prompt events. The + worker keeps it on the activity row as `agentPid` (local only), and the + stdio server matches rows and sessions to its own agent by it, exactly. - `failproofai_via_devin` (true): a Claude-path Self Reports call made under Devin. diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 4aa20fa62..78090d5d9 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -68,7 +68,7 @@ import { import { selfReportLogCategoryText } from "./self-report-names"; import { selfReportFailureHint, selfReportSessionStartContext } from "./self-report-hint"; import { selfReportClaudeHookFromDevin } from "./self-report-devin"; -import { SELF_REPORT_AGENT_PIDS_KEY, selfReportAgentPids, selfReportMarkAgentPids } from "./self-report-ancestry"; +import { SELF_REPORT_AGENT_PID_KEY, selfReportAgentPidOf, selfReportMarkAgentPid } from "./self-report-ancestry"; import { markAgentPath } from "./agent-path"; import { deliveryHealth, deliveryHealthLine } from "./delivery-health"; import { trackHookEvent, flushHookTelemetry } from "./hook-telemetry"; @@ -714,7 +714,7 @@ function recordSelfReportCall( : null; // The agent process the call came from, when the hook CLI could read it: // the stdio server suppresses its own copy only for a row from its agent. - const agentPids = report && resolved ? selfReportAgentPids(parsed[SELF_REPORT_AGENT_PIDS_KEY]) : undefined; + const agentPid = selfReportAgentPidOf(parsed[SELF_REPORT_AGENT_PID_KEY]); try { persistHookActivity({ timestamp: writtenAt, @@ -734,7 +734,7 @@ function recordSelfReportCall( permissionMode: session.permissionMode, hookEventName: session.hookEventName, ...(report && resolved ? { selfReport: { category: resolved.category, detail: report.detail, source: "mcp" as const } } : {}), - ...(agentPids ? { selfReportAgentPids: agentPids } : {}), + ...(agentPid !== undefined ? { agentPid } : {}), }); } catch { hookLogWarn("activity persistence failed"); @@ -1487,6 +1487,12 @@ export async function evaluateHookEvent( cwd: session.cwd, permissionMode: session.permissionMode, hookEventName: session.hookEventName, + // The agent process behind the session (stamped by the hook CLI on + // session-start and prompt events): the stdio server attributes a + // report only to a session of its own agent (self-report-ancestry.ts). + ...(selfReportAgentPidOf(parsed[SELF_REPORT_AGENT_PID_KEY]) !== undefined + ? { agentPid: selfReportAgentPidOf(parsed[SELF_REPORT_AGENT_PID_KEY]) } + : {}), // Attribution. A builtin is anything registered that is not in the map, // so its absence is meaningful rather than missing — but only when a // policy actually decided; a plain allow names nobody. When Jev's own @@ -1665,7 +1671,7 @@ export async function handleHookEvent( // The agent process above this hook, for a Claude Code / Codex report call // (self-report-ancestry.ts); the daemon path adds it in the hook CLI. const result = await evaluateHookEvent( - eventType, cli, markAgentPath(selfReportMarkAgentPids(cli, stdinRead.payload)), + eventType, cli, markAgentPath(selfReportMarkAgentPid(cli, canonicalizeEventType(eventType, cli), stdinRead.payload)), agentSettingsPath === undefined ? undefined : { agentSettingsPath }, ); diff --git a/src/hooks/hook-activity-store.ts b/src/hooks/hook-activity-store.ts index 5d1f33af8..7ebd77c8c 100644 --- a/src/hooks/hook-activity-store.ts +++ b/src/hooks/hook-activity-store.ts @@ -26,7 +26,7 @@ import type { IntegrationType } from "./types"; import { hookActivityDir } from "./fp-home"; import { sanitizeJevActivity, type JevCheckRecord } from "./jev-activity"; import { selfReportClip } from "./self-report-names"; -import { selfReportAgentPids } from "./self-report-ancestry"; +import { selfReportAgentPidOf } from "./self-report-ancestry"; export const PAGE_SIZE = 25; @@ -192,11 +192,13 @@ export interface HookActivityEntry { */ selfReport?: { category: string; detail: string; source: "mcp" }; /** - * With `selfReport` only: the pids above the hook process that recorded it - * (its agent among them). Local only, never shipped: the stdio server lets - * a row stand for its own call only when its parent is one of them. + * The agent process behind the hook (the nearest process above it that is + * not a shell or exec wrapper), stamped on Self Reports calls and on + * session-start and prompt events (self-report-ancestry.ts). Local only, + * never shipped: the stdio server matches a row, and picks a session, only + * for its own agent's pid. */ - selfReportAgentPids?: number[]; + agentPid?: number; } export interface HookActivityFilters { @@ -297,16 +299,15 @@ export function persistHookActivity(input: HookActivityEntry): void { * machine by the collector, so it is checked at this one door. */ function sanitizeSelfReportActivity(entry: HookActivityEntry): HookActivityEntry { - if (entry.selfReport === undefined && entry.selfReportAgentPids === undefined) return entry; + if (entry.selfReport === undefined && entry.agentPid === undefined) return entry; const sr = entry.selfReport as unknown; const out = { ...entry }; - const pids = selfReportAgentPids(entry.selfReportAgentPids); - if (pids && sr !== undefined) out.selfReportAgentPids = pids; - else delete out.selfReportAgentPids; + const pid = selfReportAgentPidOf(entry.agentPid); + if (pid !== undefined) out.agentPid = pid; + else delete out.agentPid; if (sr === undefined) return out; if (!sr || typeof sr !== "object" || Array.isArray(sr)) { delete out.selfReport; - delete out.selfReportAgentPids; return out; } const rec = sr as Record; diff --git a/src/hooks/self-report-ancestry.ts b/src/hooks/self-report-ancestry.ts index 5a032645d..3f30c3c35 100644 --- a/src/hooks/self-report-ancestry.ts +++ b/src/hooks/self-report-ancestry.ts @@ -1,99 +1,149 @@ /** - * Which agent process a report call came from, so the stdio server can tell - * its own call's hook row from another session's (review finding F14). + * Which agent process a hook event or a stdio report came from, so the stdio + * server can tell its own agent's hook rows and session from another's + * (review finding F14). * * The hook process and the stdio MCP server are both started by the agent: - * the hook through the agent's hook runner (often a shell), the server as the - * agent's direct child. So the server's parent is one of the hook's - * ancestors exactly when the two belong to the same agent process. Another - * session in the same directory is another agent process, with another pid. + * the hook through the agent's hook runner (often a shell, sometimes `npx`), + * the server as the agent's child. Each side names its agent as the NEAREST + * process above it that is not such a runner (`selfReportAgentPid`), and the + * two match only when that is the same pid, exactly. An ancestor further up + * is never enough: an agent B started inside agent A (A's shell tool running + * `claude -p …` in the same directory) has A above it too, and B's hook rows + * and reports are B's, not A's. * * The hook side has to read its ancestry in the hook process the agent * started, not in the daemon's warm worker (whose parent is the daemon): the - * hook CLI adds `SELF_REPORT_AGENT_PIDS_KEY` to a Claude Code or Codex report - * call before it forwards or evaluates the payload, and the handler copies it - * onto the activity row. Only a report call is looked at, so ordinary hook - * traffic pays nothing. Anything unreadable gives no pids, and a row with no - * pids never vouches for a call: the server records rather than suppresses. + * hook CLI adds `SELF_REPORT_AGENT_PID_KEY` to the payload before it forwards + * or evaluates it, and the handler copies it onto the activity row as + * `agentPid`. It is added to a Claude Code / Codex report call (the stdio + * server's dedup) and to every agent's session-start and prompt events (the + * server's session attribution), so ordinary tool traffic pays nothing. + * Anything unreadable gives no pid, and a row with no pid never vouches for a + * call: the server records rather than suppresses. */ import { execFileSync } from "node:child_process"; import { readFileSync } from "node:fs"; +import { basename } from "node:path"; import { isSelfReportToolName } from "./self-report-names"; -/** Payload key the hook CLI adds to a Claude Code / Codex report call: its ancestor pids. */ -export const SELF_REPORT_AGENT_PIDS_KEY = "failproofai_report_agent_pids"; +/** Payload key the hook CLI adds: the pid of the agent process above the hook. */ +export const SELF_REPORT_AGENT_PID_KEY = "failproofai_report_agent_pid"; -/** How many processes above the hook are kept (hook runner shells, wrappers, the agent). */ -export const SELF_REPORT_AGENT_PIDS_DEPTH = 8; +/** How many processes above this one are looked at. */ +export const SELF_REPORT_ANCESTRY_DEPTH = 8; /** Agents whose hook records the report and whose stdio server must recognise that row. */ const HOOK_RECORDED: readonly string[] = ["claude", "codex"]; -/** The pid of `pid`'s parent, or 0. */ -function parentOf(pid: number, table: Map | null): number { - if (table) return table.get(pid) ?? 0; - // " () …"; comm may itself hold ") ". - const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); - return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]) || 0; +/** Canonical events that stamp the agent pid on every agent: they name the session. */ +const SESSION_EVENTS: readonly string[] = ["SessionStart", "UserPromptSubmit"]; + +/** + * Processes that run something on an agent's behalf and are not the agent: + * shells and the usual exec wrappers. `npm exec`/`npx` (a project-scope hook + * is `npx -y failproofai --hook …`) show as `npm…`/`npx…` once npm sets its + * process title. + */ +const RUNNER_NAMES: ReadonlySet = new Set([ + "sh", "bash", "zsh", "dash", "ash", "ksh", "mksh", "fish", "csh", "tcsh", + "env", "timeout", "nice", "nohup", "setsid", "stdbuf", "xargs", + "npx", "npm", "pnpm", "pnpx", "yarn", "bunx", +]); + +function isRunner(name: string): boolean { + const n = basename(name).toLowerCase().replace(/^-/, ""); // a login shell's `-bash` + return RUNNER_NAMES.has(n) || /^(?:npm|npx)[\s-]/.test(n); } -/** Pids above this process, nearest first (its parent first). Best effort: `[]` on any failure. */ -export function selfReportAncestorPids(depth: number = SELF_REPORT_AGENT_PIDS_DEPTH): number[] { - const out: number[] = []; +export interface SelfReportProcess { + pid: number; + name: string; +} + +/** The processes above this one, nearest first (its parent first). Best effort: `[]` on any failure. */ +export function selfReportAncestry(depth: number = SELF_REPORT_ANCESTRY_DEPTH): SelfReportProcess[] { + const out: SelfReportProcess[] = []; try { - let table: Map | null = null; - if (process.platform === "darwin") { - table = new Map(); - const ps = execFileSync("ps", ["-A", "-o", "pid=,ppid="], { encoding: "utf8", timeout: 1000 }); + if (process.platform === "linux") { + let pid = process.ppid; + for (let i = 0; i < depth && pid > 1; i++) { + // " () …"; comm may itself hold ") ". + const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); + const close = stat.lastIndexOf(")"); + out.push({ pid, name: stat.slice(stat.indexOf("(") + 1, close) }); + pid = Number(stat.slice(close + 2).split(" ")[1]) || 0; + } + } else if (process.platform === "darwin") { + const ps = execFileSync("ps", ["-A", "-o", "pid=,ppid=,comm="], { encoding: "utf8", timeout: 1000 }); + const table = new Map(); for (const line of ps.split("\n")) { - const m = /^\s*(\d+)\s+(\d+)\s*$/.exec(line); - if (m) table.set(Number(m[1]), Number(m[2])); + const m = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line); + if (m) table.set(Number(m[1]), { ppid: Number(m[2]), comm: m[3].trim() }); + } + let pid = process.ppid; + for (let i = 0; i < depth && pid > 1; i++) { + const row = table.get(pid); + if (!row) break; + out.push({ pid, name: basename(row.comm) }); + pid = row.ppid; } - } else if (process.platform !== "linux") { - return []; - } - let pid = process.ppid; - for (let i = 0; i < depth && pid > 1; i++) { - out.push(pid); - pid = parentOf(pid, table); } } catch { - // Unreadable /proc, no ps: no ancestry, so no row will vouch for a call. + // Unreadable /proc, no ps: no ancestry, so no agent pid. } return out; } -/** The pids in a payload or row field, kept only in their declared shape. */ -export function selfReportAgentPids(value: unknown): number[] | undefined { - if (!Array.isArray(value)) return undefined; - const pids = value - .filter((p): p is number => typeof p === "number" && Number.isSafeInteger(p) && p > 1) - .slice(0, SELF_REPORT_AGENT_PIDS_DEPTH); - return pids.length > 0 ? pids : undefined; +/** The nearest process above this one that is not a shell or exec wrapper: the agent. */ +export function selfReportAgentPid(ancestry: () => SelfReportProcess[] = selfReportAncestry): number | undefined { + for (const p of ancestry()) { + if (!isRunner(p.name)) return p.pid > 1 ? p.pid : undefined; + } + return undefined; } +let serverAgentPid: { value: number | undefined } | null = null; + /** - * In the hook process: return `stdin` with `SELF_REPORT_AGENT_PIDS_KEY` set - * when this is a Claude Code or Codex report call, else `stdin` unchanged. - * Never throws. + * This stdio server's agent: the nearest process above it that is not a shell + * or exec wrapper (normally its parent). Read once per server process. */ -export function selfReportMarkAgentPids( +export function selfReportServerAgentPid(): number | undefined { + if (!serverAgentPid) serverAgentPid = { value: selfReportAgentPid() }; + return serverAgentPid.value; +} + +/** A pid in a payload or row field, kept only in its declared shape. */ +export function selfReportAgentPidOf(value: unknown): number | undefined { + return typeof value === "number" && Number.isSafeInteger(value) && value > 1 ? value : undefined; +} + +/** + * In the hook process: `stdin` with `SELF_REPORT_AGENT_PID_KEY` set to the + * agent's pid on a Claude Code / Codex report call and on any agent's + * session-start or prompt event (`canonicalEvent`), else `stdin` unchanged + * (a value it already carried is replaced or dropped, never trusted). Never + * throws. + */ +export function selfReportMarkAgentPid( cli: string, + canonicalEvent: string, stdin: string, - ancestry: () => number[] = selfReportAncestorPids, + agentPid: () => number | undefined = selfReportAgentPid, ): string { - if (!HOOK_RECORDED.includes(cli) || !/failproofai_local/i.test(stdin)) return stdin; + const sessionEvent = SESSION_EVENTS.includes(canonicalEvent); + const maybeReport = HOOK_RECORDED.includes(cli) && /failproofai_local/i.test(stdin); + const carried = stdin.includes(SELF_REPORT_AGENT_PID_KEY); + if (!sessionEvent && !maybeReport && !carried) return stdin; try { const parsed = JSON.parse(stdin) as unknown; if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return stdin; - const rec = parsed as Record; - if (!isSelfReportToolName(rec.tool_name)) return stdin; - const pids = ancestry(); - if (pids.length === 0) { - const { [SELF_REPORT_AGENT_PIDS_KEY]: _drop, ...rest } = rec; - return _drop === undefined ? stdin : JSON.stringify(rest); - } - return JSON.stringify({ ...rec, [SELF_REPORT_AGENT_PIDS_KEY]: pids }); + const { [SELF_REPORT_AGENT_PID_KEY]: dropped, ...rest } = parsed as Record; + const stamp = sessionEvent || (maybeReport && isSelfReportToolName(rest.tool_name)); + const pid = stamp ? agentPid() : undefined; + if (pid !== undefined) return JSON.stringify({ ...rest, [SELF_REPORT_AGENT_PID_KEY]: pid }); + return dropped === undefined ? stdin : JSON.stringify(rest); } catch { return stdin; } diff --git a/src/hooks/self-report-hook-trust.ts b/src/hooks/self-report-hook-trust.ts index 393228c6c..40d722c74 100644 --- a/src/hooks/self-report-hook-trust.ts +++ b/src/hooks/self-report-hook-trust.ts @@ -39,7 +39,7 @@ import { claudeConfigDir, getIntegration } from "./integrations"; import { getHookActivityEntriesSince } from "./hook-activity-store"; import { readEnabledSelfReport, resolveSelfReportCategory, selfReportArgs } from "./self-report"; import { selfReportClip } from "./self-report-names"; -import { selfReportAgentPids } from "./self-report-ancestry"; +import { selfReportAgentPidOf, selfReportServerAgentPid } from "./self-report-ancestry"; import { failproofaiHome } from "./fp-home"; /** The agents whose hook, when it runs, is the recorder. */ @@ -198,9 +198,10 @@ export const SELF_REPORT_HOOK_DEDUPE_MS = 2 * 60 * 1000; * A hook row matches when it is a PreToolUse row from that integration, * written in the last two minutes, in the same working directory as this * server (`cwd`; a row or a server without one never matches), recorded by a - * hook running under this server's own agent process (`agentPid`, the - * server's parent, is among the row's `selfReportAgentPids`; a row without - * them never matches), carrying a `selfReport` with the same category (as + * hook running under this server's own agent process (the row's `agentPid` + * is exactly this server's agent, `selfReportServerAgentPid`; not merely an + * ancestor, and a row without one never matches), carrying a `selfReport` + * with the same category (as * sent, or as resolved against the list) and detail as the hook would have * clipped them. Matching on the report's text alone suppressed distinct calls: * a report the hook recorded in project A made an identical report in project @@ -225,9 +226,9 @@ export function selfReportHookRecordedRecently( args: unknown, now: number = Date.now(), cwd?: string, - agentPid: number = process.ppid, + agentPid: number | undefined = selfReportServerAgentPid(), ): boolean { - if (!cwd || !Number.isSafeInteger(agentPid) || agentPid <= 1) return false; + if (!cwd || agentPid === undefined || !Number.isSafeInteger(agentPid) || agentPid <= 1) return false; const { category, detail } = selfReportArgs(args ?? {}); const want = { category: selfReportClip(category), detail: selfReportClip(detail) }; // The hook row holds the category as it was resolved against the list @@ -247,7 +248,7 @@ export function selfReportHookRecordedRecently( const ts = typeof row.timestamp === "number" ? row.timestamp : NaN; if (!Number.isFinite(ts) || now - ts > SELF_REPORT_HOOK_DEDUPE_MS || ts - now > 60_000) return false; if (typeof row.cwd !== "string" || !row.cwd || sameDir(row.cwd) !== here) return false; - if (!selfReportAgentPids(row.selfReportAgentPids)?.includes(agentPid)) return false; + if (selfReportAgentPidOf(row.agentPid) !== agentPid) return false; const sr = row.selfReport as { category?: unknown; detail?: unknown } | undefined; return !!sr && (sr.category === want.category || sr.category === resolved) && sr.detail === want.detail; }); diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts index 5fa0d00dd..86769a438 100644 --- a/src/hooks/self-report-mcp.ts +++ b/src/hooks/self-report-mcp.ts @@ -45,6 +45,7 @@ import { selfReportSettingsState, } from "./self-report"; import { flushSelfReportLogs, sendSelfReportLog } from "./self-report-log"; +import { selfReportAgentPidOf, selfReportServerAgentPid } from "./self-report-ancestry"; /** * Set to `1` in the server's environment (by `self-report test`), it writes one @@ -134,11 +135,23 @@ export interface SelfReportSessionMatch { * (`getHookActivityEntriesSince`), not just the newest ones: `current.jsonl` * rotates every 25 rows, so another busy project's hooks can push this * project's rows several pages back within minutes. + * + * The agent process comes first (F14). Hook rows carry the pid of the agent + * behind them (`agentPid`, on session-start, prompt and report rows). With + * `agentPid` known (this server's own agent), a session stamped with it is + * the answer, exactly; a session stamped only with another agent's pid is + * never taken, whatever directory it shares (an agent started inside + * another, in the same project, is its own session). Only sessions with no + * stamp at all (a hook that could not read its ancestry, rows from before + * this) are left to the directory ranking below. `excluded` receives the + * sessions known to be another agent's, for the transcript fallbacks. */ export function selfReportFindSessionMatch( integration: string, cwd: string | undefined, now: number = Date.now(), + agentPid?: number, + excluded?: Set, ): SelfReportSessionMatch | null { let entries: ReturnType; try { @@ -146,26 +159,53 @@ export function selfReportFindSessionMatch( } catch { return null; // No readable activity: nothing to attribute to. } + const rows = (entries as unknown as Array>).filter((row) => { + const ts = typeof row.timestamp === "number" ? row.timestamp : NaN; + return ( + row.integration === integration && + typeof row.sessionId === "string" && + !!row.sessionId && + Number.isFinite(ts) && + now - ts <= SELF_REPORT_SESSION_WINDOW_MS && + ts - now <= 60_000 + ); + }); + if (agentPid !== undefined) { + const stamps = new Map>(); + for (const row of rows) { + const pid = selfReportAgentPidOf(row.agentPid); + if (pid === undefined) continue; + const set = stamps.get(row.sessionId as string) ?? new Set(); + set.add(pid); + stamps.set(row.sessionId as string, set); + } + let own: { ts: number; id: string; cwd: string | undefined } | null = null; + for (const row of rows) { + if (!stamps.get(row.sessionId as string)?.has(agentPid)) continue; + const ts = row.timestamp as number; + if (!own || ts > own.ts) own = { ts, id: row.sessionId as string, cwd: typeof row.cwd === "string" && row.cwd ? row.cwd : undefined }; + } + if (own) return { sessionId: own.id, cwd: own.cwd }; + for (const [id, pids] of stamps) { + if (!pids.has(agentPid)) excluded?.add(id); + } + return selfReportRankSessions(rows.filter((row) => !stamps.has(row.sessionId as string)), cwd); + } + return selfReportRankSessions(rows, cwd); +} + +/** The directory ranking of `selfReportFindSessionMatch`, over rows already in the window. */ +function selfReportRankSessions(rows: Array>, cwd: string | undefined): SelfReportSessionMatch | null { let best: { rank: number; ts: number; id: string; cwd: string | undefined } | null = null; // The distinct cwds of this integration's rows, to tell one project from several. const cwds = new Set(); - for (const row of entries as unknown as Array>) { - const ts = typeof row.timestamp === "number" ? row.timestamp : NaN; - if ( - row.integration !== integration || - typeof row.sessionId !== "string" || - !row.sessionId || - !Number.isFinite(ts) || - now - ts > SELF_REPORT_SESSION_WINDOW_MS || - ts - now > 60_000 - ) { - continue; - } + for (const row of rows) { + const ts = row.timestamp as number; const rowCwd = typeof row.cwd === "string" && row.cwd ? row.cwd : undefined; cwds.add(rowCwd === undefined ? "" : rowCwd.replace(/\/+$/, "") || "/"); const rank = cwd ? selfReportCwdAffinity(cwd, row.cwd) : 0; if (!best || rank > best.rank || (rank === best.rank && ts > best.ts)) { - best = { rank, ts, id: row.sessionId, cwd: rowCwd }; + best = { rank, ts, id: row.sessionId as string, cwd: rowCwd }; } } if (!best || (best.rank === 0 && cwds.size > 1)) return null; @@ -218,6 +258,8 @@ export interface SelfReportEventInput { now?: number; /** Overrides session attribution (the `self-report test` command). */ sessionId?: string; + /** This server's agent process (default: read from the process tree); see `selfReportFindSessionMatch`. */ + agentPid?: number | null; } /** @@ -228,13 +270,19 @@ export interface SelfReportEventInput { */ export async function writeSelfReportEvent(input: SelfReportEventInput): Promise<{ path: string; event: Record }> { const now = input.now ?? Date.now(); + // Sessions the hooks show to be another agent process's: never taken, not + // even by the transcript fallbacks (an agent started inside another one, in + // the same directory, has its own session). + const excluded = new Set(); + const agentPid = input.agentPid === undefined ? selfReportServerAgentPid() : input.agentPid ?? undefined; + const fallback = (m: SelfReportSessionMatch | null) => (m && !excluded.has(m.sessionId) ? m : null); const match = input.sessionId === undefined - ? selfReportFindSessionMatch(input.integration, input.cwd, now) ?? + ? selfReportFindSessionMatch(input.integration, input.cwd, now, agentPid, excluded) ?? (input.integration === "codex" - ? selfReportCodexRolloutSession(input.cwd, now) + ? fallback(selfReportCodexRolloutSession(input.cwd, now, undefined, excluded)) : input.integration === "claude" - ? selfReportClaudeTranscriptSession(input.cwd, now) + ? fallback(selfReportClaudeTranscriptSession(input.cwd, now, undefined, excluded)) : null) : null; const sessionId = input.sessionId ?? match?.sessionId ?? "unattributed"; @@ -302,6 +350,7 @@ export function selfReportCodexRolloutSession( cwd: string, now: number = Date.now(), home: string = process.env.CODEX_HOME?.trim() || join(homedirForCodex(), ".codex"), + excluded: ReadonlySet = new Set(), ): SelfReportSessionMatch | null { const dayDirs = new Set(); for (const t of [now, now - SELF_REPORT_SESSION_WINDOW_MS]) { @@ -325,6 +374,7 @@ export function selfReportCodexRolloutSession( const head = readFirstLine(file); const meta = JSON.parse(head) as { type?: unknown; payload?: { id?: unknown; cwd?: unknown } }; if (meta.type !== "session_meta" || typeof meta.payload?.id !== "string" || typeof meta.payload.cwd !== "string") continue; + if (excluded.has(meta.payload.id)) continue; const rank = selfReportCwdAffinity(cwd, meta.payload.cwd); if (rank === 0) continue; if (!best || rank > best.rank || (rank === best.rank && mtime > best.mtime)) { @@ -347,6 +397,7 @@ export function selfReportClaudeTranscriptSession( cwd: string, now: number = Date.now(), configDir: string = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedirForCodex(), ".claude"), + excluded: ReadonlySet = new Set(), ): SelfReportSessionMatch | null { const dir = join(configDir, "projects", cwd.replace(/\/+$/, "").replace(/[^A-Za-z0-9]/g, "-")); let best: { mtime: number; id: string } | null = null; @@ -360,7 +411,9 @@ export function selfReportClaudeTranscriptSession( try { const mtime = statSync(join(dir, name)).mtimeMs; if (now - mtime > SELF_REPORT_SESSION_WINDOW_MS) continue; - if (!best || mtime > best.mtime) best = { mtime, id: name.slice(0, -".jsonl".length) }; + const id = name.slice(0, -".jsonl".length); + if (excluded.has(id)) continue; + if (!best || mtime > best.mtime) best = { mtime, id }; } catch { // gone since the listing } From a2e6509ed55819d0ed146bae96c800453dd97bed Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 17:12:31 +0530 Subject: [PATCH 47/54] Self Reports: scrub the log preview from the detail as sent Review round 2 on F18: both transports still logged a long JWT's prefix. The report's detail is cut to 2000 code points before anything else, and the log preview was scrubbed from that cut text, so a JWT that starts in the preview and runs past the cut had two segments left and the scrubber passed it. The log now gets the detail as the agent sent it, bounded by the transport: the stdio server sends it in the selfReportLog frame (at most 64 KiB) and the HTTP server reads it from the request (Report::log_detail, at most the 64 KiB body cap); log_preview scrubs all of it before the 40-character cut. The report itself is still cut at 2000. The hook path writes no detail to any log line. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/self-report-log.test.ts | 38 +++++++-- crates/PROTOCOL.md | 2 +- crates/failproofaid/tests/self_report_e2e.rs | 83 ++++++++++++++++++++ crates/fpai-collect/src/self_report.rs | 57 +++++++++++--- src/hooks/self-report-log.ts | 16 ++-- src/hooks/self-report-mcp.ts | 8 +- src/hooks/self-report.ts | 8 +- 8 files changed, 184 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78091a299..430f71a1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,7 @@ - Self Reports: the `report` tool's exemption from the policies now needs a stdio entry whose command, followed through every link, is this failproofai's own CLI entry point, run as `mcp --agent `; a foreign program merely named like failproofai, or a loopback HTTP entry, takes the policy path. A project beneath your home directory no longer has the agents' own user-wide configs (`~/.codex/config.toml`, `~/.cursor/mcp.json`, …) read as project overrides, which refused the genuine tool there (#1062) - `block-failproofai-commands` decides whether a bare `grep`/`rg`/`jq` (or `cat`/`tee` for a heredoc) is the standard tool from the agent's own PATH, which the hook client now carries in the payload, not from the PATH of the process evaluating it. Through failproofaid that was the daemon's PATH, so a shadow `grep` early on the agent's PATH could run a quoted argument; with no agent PATH (an older client, the Hermes and OpenClaw plugins) no bare name is exempt (#1062) - Self Reports: the stdio server matches hook rows and picks the session for a report by its own agent process, exactly: each side names the nearest process above it that is not a shell or exec wrapper, and session-start and prompt rows now carry it too. An agent started inside another one in the same directory no longer has its hook rows claimed, or its reports filed, under the outer agent's session; with no session of its own it takes its own transcript, else `unattributed` (#1062) +- Self Reports: the daemon log's report preview is scrubbed from the detail as the agent sent it (bounded at 64 KiB), not from the 2000-character report. A credential that straddled that cut, such as a JWT starting near the beginning and running past it, was cut into something the scrubber no longer recognised, and its start reached the log over both stdio and HTTP (#1062) ### Docs diff --git a/__tests__/hooks/self-report-log.test.ts b/__tests__/hooks/self-report-log.test.ts index b911c6bfc..cf1675c01 100644 --- a/__tests__/hooks/self-report-log.test.ts +++ b/__tests__/hooks/self-report-log.test.ts @@ -8,7 +8,7 @@ * - setup's finish step: one spinner, then only what needs the user. */ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createServer, type Server } from "node:net"; @@ -117,10 +117,10 @@ describe("selfReportLog over the daemon socket", () => { it("sends one framed selfReportLog with the whole (bounded) detail, for the daemon to scrub before it cuts", async () => { const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); try { - await sendSelfReportLog({ event: "tools/call", agent: "hermes", transport: "stdio", outcome: "recorded", preview: "x".repeat(2500) }); + await sendSelfReportLog({ event: "tools/call", agent: "hermes", transport: "stdio", outcome: "recorded", preview: "x".repeat(70_000) }); await vi.waitFor(() => expect(frames).toHaveLength(1)); expect(frames[0]).toMatchObject({ type: "selfReportLog", protocolVersion: 2, event: { event: "tools/call", agent: "hermes", outcome: "recorded" } }); - expect(((frames[0].event as Record).preview).length).toBe(2000); + expect(((frames[0].event as Record).preview).length).toBe(64 * 1024); } finally { server.close(); } @@ -147,11 +147,11 @@ describe("selfReportLog over the daemon socket", () => { it("bounds the preview on a character boundary, never through a surrogate pair", async () => { const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); try { - // 1999 ASCII then emoji: the 2000th code point is whole, nothing after it. - await sendSelfReportLog({ event: "tools/call", transport: "stdio", preview: `${"a".repeat(1999)}😀😀 environment` }); + // 65535 ASCII then emoji: the 65536th code point is whole, nothing after it. + await sendSelfReportLog({ event: "tools/call", transport: "stdio", preview: `${"a".repeat(64 * 1024 - 1)}😀😀 environment` }); await vi.waitFor(() => expect(frames).toHaveLength(1)); const preview = (frames[0].event as Record).preview; - expect(preview).toBe(`${"a".repeat(1999)}😀`); + expect(preview).toBe(`${"a".repeat(64 * 1024 - 1)}😀`); expect(preview).not.toContain("�"); } finally { server.close(); @@ -218,6 +218,32 @@ describe("selfReportLog over the daemon socket", () => { } }); + // F18 round 2: a JWT that starts in the preview and runs past the + // 2,000-character report cut. The report is cut there, but the log frame + // carries the detail as sent, so the daemon's scrubber sees the whole token + // (crates/failproofaid/tests/self_report_e2e.rs checks the daemon's half). + it("the stdio server sends the log the detail as sent, not the 2000-character report cut", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + writeEffectiveSelfReport({ enabled: true }); + const jwt = `eyJhbGciOiJIUzI1NiJ9.eyJ${"a".repeat(2500)}.${"b".repeat(43)}`; + const detail = `token ${jwt} rejected`; + await handleSelfReportRpc( + { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "report", arguments: { category: "looping", detail } } }, + { agent: "copilot", cwd: home }, + ); + await flushSelfReportLogs(1000); + await vi.waitFor(() => expect(frames).toHaveLength(1)); + expect((frames[0].event as Record).preview).toBe(detail); + // The report itself is still cut at 2000. + const [file] = readdirSync(join(home, "custom-agents", "events")).filter((f) => f.endsWith(".jsonl")); + const event = JSON.parse(readFileSync(join(home, "custom-agents", "events", file), "utf8")); + expect([...event.detail]).toHaveLength(2000); + } finally { + server.close(); + } + }); + it("the stdio server's run waits for its events, at most the budget, before it ends", async () => { const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); try { diff --git a/crates/PROTOCOL.md b/crates/PROTOCOL.md index 183a57285..9d6486f14 100644 --- a/crates/PROTOCOL.md +++ b/crates/PROTOCOL.md @@ -105,7 +105,7 @@ older daemon carries them, and from an older client they are simply absent. "knownCategory": true, // false: the category sent is not listed, and `category` was resolved from it "rawCategory": "", // only when knownCategory is false: what was sent (maybe empty), ≤ 2000 chars; logged only when shaped like a name "session": "…", - "preview": "the detail, ≤ 2000 chars; the daemon scrubs secrets from all of it, then logs ≤ 40", + "preview": "the detail as the agent sent it (before the 2000-char report cut), ≤ 65,536 chars; the daemon scrubs secrets from all of it, then logs ≤ 40", "summary": "added claude (stdio); failed codex (…)" // sync only } } diff --git a/crates/failproofaid/tests/self_report_e2e.rs b/crates/failproofaid/tests/self_report_e2e.rs index cf989a2cd..063decce6 100644 --- a/crates/failproofaid/tests/self_report_e2e.rs +++ b/crates/failproofaid/tests/self_report_e2e.rs @@ -351,3 +351,86 @@ fn self_report_mcp_events_reach_the_daemon_log() { assert!(!log.contains(secret), "the key reached the log:\n{log}"); assert!(!log.contains("everything after this point"), "{log}"); } + +/// F18 round 2: a JWT that starts inside the 40-character preview and runs +/// past the 2,000-character report cut is scrubbed from the daemon log over +/// both transports (HTTP: the daemon's own server; stdio: the frame the stdio +/// server now sends with the detail as sent). +#[test] +fn a_jwt_straddling_the_report_cut_never_reaches_the_daemon_log() { + let port = free_port(); + let daemon = spawn(port); + fpai_collect::self_report::write_settings( + &daemon.home.join("self-report.json"), + &fpai_collect::self_report::Settings { + version: 1, + enabled: true, + source: "local".into(), + categories: fpai_collect::self_report::default_categories(), + guidance: None, + mcp: fpai_collect::self_report::McpEndpoint::on_port(port), + updated_at: "2026-11-25T10:00:00Z".into(), + enrolment: None, + }, + ) + .unwrap(); + wait("the MCP endpoint", || initialize(port).is_some()); + wait("the socket", || { + daemon.home.join("run/failproofaid.sock").exists() + }); + let jwt = format!( + "eyJhbGciOiJIUzI1NiJ9.eyJ{}.{}", + "a".repeat(2500), + "b".repeat(43) + ); + let detail = format!("token {jwt} rejected"); + let call = serde_json::json!({ + "jsonrpc": "2.0", "id": 3, "method": "tools/call", + "params": {"name": "report", "arguments": {"category": "looping", "detail": detail}} + }); + let reply = reqwest::blocking::Client::new() + .post(format!("http://127.0.0.1:{port}/mcp?agent=copilot")) + .header("Content-Type", "application/json") + .body(call.to_string()) + .send() + .unwrap(); + assert!(reply.status().is_success()); + wait("the HTTP tools/call line", || { + daemon + .log + .lock() + .unwrap() + .contains("Self Reports MCP tools/call over http agent=copilot outcome=recorded") + }); + let mut stream = UnixStream::connect(daemon.home.join("run/failproofaid.sock")).unwrap(); + write_message( + &mut stream, + &ClientMessage::SelfReportLog { + protocol_version: PROTOCOL_VERSION, + event: fpai_ipc::SelfReportLogEvent { + event: "tools/call".into(), + agent: Some("claude".into()), + transport: Some("stdio".into()), + outcome: Some("recorded".into()), + category: Some("looping".into()), + known_category: Some(true), + preview: Some(detail.clone()), + ..Default::default() + }, + }, + ) + .unwrap(); + wait("the stdio tools/call line", || { + daemon + .log + .lock() + .unwrap() + .contains("Self Reports MCP tools/call over stdio agent=claude outcome=recorded") + }); + let log = daemon.log.lock().unwrap().clone(); + assert!( + !log.contains("eyJhbGci"), + "a JWT prefix reached the log:\n{log}" + ); + assert!(log.matches("[redacted:").count() >= 2, "{log}"); +} diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index 08ba1656e..a5e3d8179 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -951,7 +951,8 @@ impl Server { category: Some(&raw_category), ..Default::default() }; - let detail = report.detail.clone(); + // The log line gets the detail as sent, scrubbed whole before its cut. + let detail = Report::log_detail(args); log.detail = Some(&detail); let Some(agent) = caller .agent @@ -1195,19 +1196,31 @@ pub struct Report { impl Report { pub fn from_args(args: &Value) -> Self { - let text = |key: &str, aliases: &[&str]| { - std::iter::once(key) - .chain(aliases.iter().copied()) - .filter_map(|k| args.get(k).and_then(Value::as_str)) - .find(|v| !v.is_empty()) - .unwrap_or_default() - .to_string() - }; Report { - category: text("category", CATEGORY_ALIASES), - detail: truncate_chars(&text("detail", DETAIL_ALIASES), MAX_DETAIL_CHARS), + category: arg_text(args, "category", CATEGORY_ALIASES), + detail: truncate_chars(&arg_text(args, "detail", DETAIL_ALIASES), MAX_DETAIL_CHARS), } } + + /// The detail exactly as sent, for the log line only: [`log_preview`] + /// scrubs secrets from the whole of it before it cuts. Cutting to + /// [`MAX_DETAIL_CHARS`] first could split a credential that straddles the + /// cut (a JWT whose second segment runs past it) into something the + /// scrubber no longer recognises, and its start was logged (F18). Bounded + /// by the transport: the HTTP body is at most [`MAX_BODY_BYTES`]. + pub fn log_detail(args: &Value) -> String { + truncate_chars(&arg_text(args, "detail", DETAIL_ALIASES), MAX_BODY_BYTES) + } +} + +/// The first non-empty string among `key` and its aliases. +fn arg_text(args: &Value, key: &str, aliases: &[&str]) -> String { + std::iter::once(key) + .chain(aliases.iter().copied()) + .filter_map(|k| args.get(k).and_then(Value::as_str)) + .find(|v| !v.is_empty()) + .unwrap_or_default() + .to_string() } /// Keyword rules for a category the model did not name (or named wrongly), in @@ -1604,6 +1617,28 @@ mod tests { assert!(preview.contains("[redacted:"), "{preview}"); } + /// F18 round 2: a JWT that starts in the preview and runs past the + /// 2,000-character report cut. Cut first, it has two segments and the + /// scrubber passes it; the log gets the detail as sent. + #[test] + fn a_jwt_straddling_the_report_cut_is_scrubbed_from_the_log_preview() { + let jwt = format!( + "eyJhbGciOiJIUzI1NiJ9.eyJ{}.{}", + "a".repeat(2500), + "b".repeat(43) + ); + let args = json!({"category": "looping", "detail": format!("token {jwt} rejected")}); + let clipped = Report::from_args(&args).detail; + assert_eq!(clipped.chars().count(), MAX_DETAIL_CHARS); + let raw = Report::log_detail(&args); + assert!(raw.ends_with(" rejected")); + let preview = log_preview(&raw); + assert!(!preview.contains("eyJhbGci"), "{preview}"); + assert!(preview.contains("[redacted:"), "{preview}"); + // The aliases resolve as for the report itself. + assert_eq!(Report::log_detail(&json!({"summary": "s"})), "s"); + } + #[test] fn a_category_is_logged_only_when_it_is_shaped_like_a_name() { for name in [ diff --git a/src/hooks/self-report-log.ts b/src/hooks/self-report-log.ts index 77bcfef0b..c75452cd4 100644 --- a/src/hooks/self-report-log.ts +++ b/src/hooks/self-report-log.ts @@ -10,9 +10,9 @@ * it is dropped. No daemon, a slow one, or any error: dropped too, inside * `SELF_REPORT_LOG_BUDGET_MS`. Nothing here ever throws or holds up an agent. * - * A report's whole detail is sent (it is already bounded at 2000 code points): - * the daemon scrubs secrets from the whole text and only then cuts it for the - * log line. Cutting it here first cut long credentials (a JWT past 200 + * A report's detail is sent as the agent sent it, before the 2000-code-point + * report cut, bounded at 64 KiB: the daemon scrubs secrets from the whole text + * and only then cuts it for the log line. Cutting it here first cut long credentials (a JWT past 200 * characters) into pieces the scrubber no longer recognised (F18). The model's * category is sent whole too, and the daemon shows it only when it is shaped * like a category name (F20). @@ -24,10 +24,16 @@ import { createConnection } from "node:net"; import { daemonSocket } from "./fp-home"; import { SELF_REPORT_DETAIL_MAX, selfReportClip } from "./self-report-names"; + /** The whole budget for one event, connect to close. */ export const SELF_REPORT_LOG_BUDGET_MS = 250; -/** How much detail is sent: all of it, so the daemon scrubs before it cuts (it logs at most 40 characters). */ -export const SELF_REPORT_LOG_PREVIEW_CHARS = SELF_REPORT_DETAIL_MAX; +/** + * How much detail is sent: the detail AS SENT, not the 2,000-character report + * (a credential straddling that cut was split into something the daemon's + * scrubber no longer recognised, F18), bounded like the daemon's own HTTP + * body (64 KiB). The daemon scrubs all of it, then logs at most 40 characters. + */ +export const SELF_REPORT_LOG_PREVIEW_CHARS = 64 * 1024; /** How much of an inferred report's raw category is sent: all of it, for the same reason. */ export const SELF_REPORT_LOG_RAW_CATEGORY_CHARS = SELF_REPORT_DETAIL_MAX; const SELF_REPORT_LOG_PROTOCOL_VERSION = 2; diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts index 86769a438..7a310ec4b 100644 --- a/src/hooks/self-report-mcp.ts +++ b/src/hooks/self-report-mcp.ts @@ -44,7 +44,7 @@ import { selfReportInstructions, selfReportSettingsState, } from "./self-report"; -import { flushSelfReportLogs, sendSelfReportLog } from "./self-report-log"; +import { SELF_REPORT_LOG_PREVIEW_CHARS, flushSelfReportLogs, sendSelfReportLog } from "./self-report-log"; import { selfReportAgentPidOf, selfReportServerAgentPid } from "./self-report-ancestry"; /** @@ -492,7 +492,11 @@ export async function handleSelfReportRpc( } const agent = opts.agent; const { category: rawCategory, detail } = selfReportArgs(params.arguments ?? {}); - const call = { event: "tools/call" as const, category: rawCategory, preview: detail }; + // The log gets the detail as sent (bounded), scrubbed whole by the + // daemon before its cut; the 2000-character report cut could split a + // credential so the scrubber no longer recognises it. + const asSent = selfReportArgs(params.arguments ?? {}, SELF_REPORT_LOG_PREVIEW_CHARS).detail; + const call = { event: "tools/call" as const, category: rawCategory, preview: asSent }; const settings = readEnabledSelfReport(); if (!agent) { log({ ...call, outcome: "skipped", reason: "no --agent" }); diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts index 98203ebcf..212c1c043 100644 --- a/src/hooks/self-report.ts +++ b/src/hooks/self-report.ts @@ -37,7 +37,7 @@ export { selfReportAntigravityWrappedArgs, selfReportClip, } from "./self-report-names"; -import { SELF_REPORT_DEFAULT_PORT, selfReportClip } from "./self-report-names"; +import { SELF_REPORT_DEFAULT_PORT, SELF_REPORT_DETAIL_MAX, selfReportClip } from "./self-report-names"; // ── Categories (contract §2) ──────────────────────────────────────────────── @@ -206,7 +206,7 @@ export const SELF_REPORT_RESULT_TEXT = "Recorded."; * (`{arguments: {...}}`, `{args: {...}}`, or either as a JSON string), because * agents differ in how they hand an MCP call to their hooks. */ -export function selfReportArgs(input: unknown): { category: string; detail: string } { +export function selfReportArgs(input: unknown, max: number = SELF_REPORT_DETAIL_MAX): { category: string; detail: string } { let args: unknown = input; if (typeof args === "string") args = selfReportParseJson(args); if (args && typeof args === "object" && !Array.isArray(args)) { @@ -226,8 +226,8 @@ export function selfReportArgs(input: unknown): { category: string; detail: stri const category = selfReportArg(rec, "category", SELF_REPORT_ARG_ALIASES.category); const detail = selfReportArg(rec, "detail", SELF_REPORT_ARG_ALIASES.detail); return { - category: selfReportClip(category), - detail: selfReportClip(detail), + category: selfReportClip(category, max), + detail: selfReportClip(detail, max), }; } From a31a6f5d2fddf8029e2a1858a1aa51e1cbea66db Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 17:20:15 +0530 Subject: [PATCH 48/54] Self Reports docs: Pi has MCP from 0.99; keep the extension's report tool Checked on Pi 1.7.0: a failproofai_local MCP entry connects, but Pi hides MCP tools behind codemode unless the entry sets exposure: direct, and the extension already gives the tool under the same name (and carries the hooks). Extension verified on Pi 0.85.1 and 1.7.0: tool visible, stuck task reported, normal task not, gone while off. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/self-reports.mdx | 2 +- src/hooks/self-report-install.ts | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bebcd8fc..ab86e7a81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,6 +62,7 @@ ### Docs +- Self Reports docs: Pi has MCP from 0.99, but its MCP tools default to `codemode`; failproofai keeps giving Pi the report tool through its extension, verified on Pi 0.85.1 and 1.7.0 (#1062) - Self Reports docs: Cloud has no Self Reports page; a report shows on the agent's session timeline and on the event itself, and the Cloud audit agent always sees it in transcripts. Settings and alerts stay. Also covers the tighter failure hint, the quieter output and Devin running Claude Code's hooks (#1062) ## 1.0.18-beta.3 — 2026-11-27 diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index da2bca431..45229d414 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -89,7 +89,7 @@ The server sends short instructions in the MCP handshake: when to report, the ca | Antigravity | The entry sets `eager: true`, so the tools are direct rather than behind the `call_mcp_tool` wrapper. Antigravity ignores MCP server instructions, so failproofai adds a plugin in its global customization root, `~/.gemini/config/plugins/failproofai-self-reports/` (`plugin.json`, the instructions in `rules/AGENTS.md`, and a `.failproofai-managed` marker), whose rules Antigravity merges into every session. A directory of that name without the marker is never written to or removed. | | Goose | Extensions' tools are listed directly. | -Pi has no MCP support before 0.99, so an MCP entry for it reaches no model. failproofai's Pi extension, which every Pi with failproofai hooks already loads, registers the tool itself as `mcp__failproofai_local__report` on every Pi version, with the server's instructions in Pi's system prompt. It asks `failproofai mcp --agent pi` for the tool when Pi starts, and again at most once a minute when a session starts or a prompt is sent, and hands each call to it, so the text, the categories and the recording are the same as every other agent's. A Pi started while Self Reports was off (or while it waited for FailproofAI Cloud's setting) gets the tool from its next prompt after Self Reports is turned on, without a reload, and turning it off takes the tool out of Pi's active tools. The Hermes and OpenClaw plugins do the same against the daemon's Self Reports server: they ask it for the tool when the gateway starts (and every minute after, for the instructions and the on/off switch) and send each call to it as `?agent=hermes` or `?agent=openclaw` with the gateway's working directory, so it is attributed, deduped and logged like an MCP call. Without a daemon, or while Self Reports is off, the model sees no tool. The Hermes plugin registers the tool even then, hidden, so a gateway started while Self Reports was off shows it within a minute of `self-report enable`, without a restart. On Hermes the tool's schema is fixed when it registers (a short generic one when the daemon had not answered yet), so new categories reach the schema at the gateway's next start; they reach the model at once through the instructions. `self-report sync` writes no Pi, Hermes or OpenClaw MCP entry and takes out one an earlier version wrote, in every profile. `failproofai update` (and the first `failproofai config` on a new version) takes out a Hermes or OpenClaw one before it restarts their gateways, so a restarted gateway does not load it again; OpenClaw would otherwise also start the stdio server for it. +Pi before 0.99 has no MCP support, and from 0.99 (checked on 1.7.0) an MCP server's tools are hidden behind Pi's `codemode` unless its entry sets `"exposure": "direct"`. Rather than an MCP entry, failproofai's Pi extension, which every Pi with failproofai hooks already loads, registers the tool itself as `mcp__failproofai_local__report` on every Pi version, with the server's instructions in Pi's system prompt. It asks `failproofai mcp --agent pi` for the tool when Pi starts, and again at most once a minute when a session starts or a prompt is sent, and hands each call to it, so the text, the categories and the recording are the same as every other agent's. A Pi started while Self Reports was off (or while it waited for FailproofAI Cloud's setting) gets the tool from its next prompt after Self Reports is turned on, without a reload, and turning it off takes the tool out of Pi's active tools. The Hermes and OpenClaw plugins do the same against the daemon's Self Reports server: they ask it for the tool when the gateway starts (and every minute after, for the instructions and the on/off switch) and send each call to it as `?agent=hermes` or `?agent=openclaw` with the gateway's working directory, so it is attributed, deduped and logged like an MCP call. Without a daemon, or while Self Reports is off, the model sees no tool. The Hermes plugin registers the tool even then, hidden, so a gateway started while Self Reports was off shows it within a minute of `self-report enable`, without a restart. On Hermes the tool's schema is fixed when it registers (a short generic one when the daemon had not answered yet), so new categories reach the schema at the gateway's next start; they reach the model at once through the instructions. `self-report sync` writes no Pi, Hermes or OpenClaw MCP entry and takes out one an earlier version wrote, in every profile. `failproofai update` (and the first `failproofai config` on a new version) takes out a Hermes or OpenClaw one before it restarts their gateways, so a restarted gateway does not load it again; OpenClaw would otherwise also start the stdio server for it. Where an agent's hooks see MCP tool calls and the server they belong to, the hook records the report. Where they do not, failproofai's MCP server records it. It attributes the report to that agent's newest session seen by the hooks in the last 6 hours: in the server's working directory if there is one, else in a directory above or below it. With neither, it takes the agent's newest session only when all of the agent's sessions in those 6 hours are in one directory, and files the report as `unattributed` otherwise, rather than guess between projects. The lookup reads every page of hook activity written in the 6 hours, however busy other agents or projects kept the hooks, so a session that is still in the window is found. The agent the report is filed under comes from that session's own hook events. diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index 0b71a3f61..f0dac64f1 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -62,7 +62,7 @@ * | copilot | tools direct; server instructions only for the built-in `mcpRegistryServerInstructionAllowlist` (github-mcp-server, bluebird, computer-use in 1.0.83), no setting extends it | marked `~/.copilot/instructions/failproofai-self-reports.instructions.md` (any `*.instructions.md` under `$HOME/.copilot/instructions` is a documented source) | * | cursor | no | nothing; reported unprompted | * | opencode | no (`defer_loading` only inside the AI SDK, never set by OpenCode) | nothing; reported unprompted | - * | pi | no MCP before 0.99 | Pi extension registers the tool | + * | pi | no MCP before 0.99; from 0.99 MCP tools default to codemode (1.7.0) | Pi extension registers the tool (same name on every version; it also carries the hooks, so no MCP entry is written) | * | hermes | yes: MCP and plugin tools, unless named in `toolsets._HERMES_CORE_TOOLS` (0.20.0 and 0.21.3 `is_deferrable_tool_name`); no per-server option | Hermes plugin registers it natively and adds it to that list; verified against both sources: deferrable before, direct after | * | openclaw | yes, Tool Search on by default (2026.10.5); no per-server option | plugin tool with `catalogMode: "direct-only"` (tool-search catalog skips it); instructions as `before_prompt_build` `appendSystemContext` AND per-turn `appendContext` (system context alone: 0/3 stuck runs reported; both: 3/3, 0/2 false reports) | * | factory | yes: every MCP server whose name lacks `github`/`agentbrowser` (droid `McpToolSearch`, default on); no setting | the instructions as SessionStart `additionalContext` | From bd93edd8b5bbd9d5f25795443823ee7b3a3d13cd Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 17:32:34 +0530 Subject: [PATCH 49/54] Self Reports: keep the stdio log lines on macOS On macOS the stdio server's process lookup runs ps synchronously. Run mid-request, it blocked the event loop while a selfReportLog frame was connecting, so the 250 ms budget timer fired first and tools/list and tools/call never reached the daemon log (reports themselves were recorded). The lookup now runs once when the server starts, and a budget timer that fires late (a blocked loop, not a slow daemon) gets one more budget. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/self-report-log.test.ts | 19 +++++++++++++++++++ src/hooks/self-report-log.ts | 21 ++++++++++++++++++++- src/hooks/self-report-mcp.ts | 4 ++++ 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ab86e7a81..cb6d77a49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ - Self Reports: after a tool call failure that clearly blocks (an auth or credential error such as a 401 or 403, an invalid or expired key or token, or a `*_TOKEN` that is not set; or the same tool or command failing a second time in the session), one line of context once per session suggests calling `report` if the agent cannot fix it. One non-zero exit, and read-only exploration (`ls`, `cat`, `grep`, `find`, `test`, Read, Glob) failing, never earn it. On Claude Code, Codex, Cursor, Copilot (its failure event) and Factory. Never on success, on the report call, after a failproofai deny, or while Self Reports is off; it is not a policy and never replaces one's answer (#1062) ### Fixes +- Self Reports on macOS: the stdio server's `tools/list` and `tools/call` lines reached the daemon log again. Its process lookup runs `ps` synchronously on macOS; done mid-request it blocked the event loop while a log frame connected, so the frame's 250 ms budget fired first and the line was dropped. The lookup now runs once at start, and a budget timer that fires late gets one more budget before dropping (#1062) - `update` and `config` no longer say "restart the gateway" for Hermes or OpenClaw on a machine where that program is not installed: with no `hermes` or `openclaw` there is no gateway to restart (#1062) - Quieter `update`, `config` and `policies --install`/`--uninstall`: no `Hermes: hermes/default already current, gateway restarting` or `OpenClaw: openclaw/default gateway restarting` rows and no `Self Reports: on for N agents` line when all went well. Only what needs the user is printed (a gateway to restart by hand, a Hermes failure, an agent the Self Reports sync could not update); `self-report status` shows the last update's gateway rows (#1062) - Self Reports: the daemon log's report preview is cut on a character boundary and marked with an ASCII `...`, so no multi-byte character is split (seen as `enviro�`); the stdio server and the CLI cut the preview and the guidance line by code point, never through a surrogate pair (#1062) diff --git a/__tests__/hooks/self-report-log.test.ts b/__tests__/hooks/self-report-log.test.ts index cf1675c01..a814f55bc 100644 --- a/__tests__/hooks/self-report-log.test.ts +++ b/__tests__/hooks/self-report-log.test.ts @@ -158,6 +158,25 @@ describe("selfReportLog over the daemon socket", () => { } }); + // macOS: the stdio server's process lookup runs `ps` synchronously. A blocked + // event loop made the budget timer fire before the (already finished) + // connect was delivered, and the line was dropped as if no daemon answered. + it("still delivers when the event loop was blocked past the budget while it connected", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + const sent = sendSelfReportLog({ event: "tools/call", agent: "claude", transport: "stdio", outcome: "recorded" }); + const until = Date.now() + SELF_REPORT_LOG_BUDGET_MS + 200; + while (Date.now() < until) { + // a synchronous call holding the event loop, like execFileSync("ps") + } + await sent; + await vi.waitFor(() => expect(frames).toHaveLength(1)); + expect(frames[0]).toMatchObject({ event: { event: "tools/call", outcome: "recorded" } }); + } finally { + server.close(); + } + }); + it("never waits on a daemon: none, a dead socket, or one that never reads", async () => { // None. let t = Date.now(); diff --git a/src/hooks/self-report-log.ts b/src/hooks/self-report-log.ts index c75452cd4..fa21776e7 100644 --- a/src/hooks/self-report-log.ts +++ b/src/hooks/self-report-log.ts @@ -27,6 +27,8 @@ import { SELF_REPORT_DETAIL_MAX, selfReportClip } from "./self-report-names"; /** The whole budget for one event, connect to close. */ export const SELF_REPORT_LOG_BUDGET_MS = 250; +/** How late a budget timer may fire before it counts as a blocked event loop, not a slow daemon. */ +export const SELF_REPORT_LOG_LATE_MS = 50; /** * How much detail is sent: the detail AS SENT, not the 2,000-character report * (a credential straddling that cut was split into something the daemon's @@ -124,7 +126,24 @@ function selfReportLogSend(event: SelfReportLogEvent): Promise { socket.destroy(); resolve(); }; - const timer = setTimeout(done, SELF_REPORT_LOG_BUDGET_MS); + // A timer that fires late means the event loop was blocked (a synchronous + // call elsewhere), not that the daemon is slow: the connect may already be + // done and simply not delivered yet. Give it one more budget before + // dropping, so a busy process never reads as an unreachable daemon (#1024). + let armedAt = Date.now(); + let extended = false; + const expire = (): void => { + const late = Date.now() - armedAt - SELF_REPORT_LOG_BUDGET_MS; + if (!extended && late > SELF_REPORT_LOG_LATE_MS) { + extended = true; + armedAt = Date.now(); + timer = setTimeout(expire, SELF_REPORT_LOG_BUDGET_MS); + timer.unref?.(); + return; + } + done(); + }; + let timer = setTimeout(expire, SELF_REPORT_LOG_BUDGET_MS); timer.unref?.(); socket.unref(); socket.on("error", done); diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts index 7a310ec4b..c961bd901 100644 --- a/src/hooks/self-report-mcp.ts +++ b/src/hooks/self-report-mcp.ts @@ -544,6 +544,10 @@ export function runSelfReportMcpServer(opts: SelfReportMcpOptions = {}): Promise const input = opts.input ?? process.stdin; const output = opts.output ?? process.stdout; const handlerOpts = { agent: opts.agent, cwd: opts.cwd, now: opts.now }; + // Read this server's agent now, before any request: on macOS it runs `ps` + // synchronously, and doing that later blocked the event loop while a log + // frame was connecting, so its short budget fired first and the line was lost. + if (!opts.input) selfReportServerAgentPid(); let chain: Promise = Promise.resolve(); const send = (msg: unknown) => { output.write(`${JSON.stringify(msg)}\n`); From f77881c3f8c148a2875eea33d5240ed44ee61206 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 17:35:16 +0530 Subject: [PATCH 50/54] Self Reports: wait for the daemon to close before dropping a log connection On macOS every stdio log line after the first was lost: the client destroyed the connection as soon as its write finished, and macOS drops a connection the daemon has not accepted yet, data and all. It now half-closes and waits for the daemon to close (still bounded by the budget). Verified on macOS 27.2.1 arm64: every tools/call line logged. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- src/hooks/self-report-log.ts | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb6d77a49..a17a46fe3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,7 +36,7 @@ - Self Reports: after a tool call failure that clearly blocks (an auth or credential error such as a 401 or 403, an invalid or expired key or token, or a `*_TOKEN` that is not set; or the same tool or command failing a second time in the session), one line of context once per session suggests calling `report` if the agent cannot fix it. One non-zero exit, and read-only exploration (`ls`, `cat`, `grep`, `find`, `test`, Read, Glob) failing, never earn it. On Claude Code, Codex, Cursor, Copilot (its failure event) and Factory. Never on success, on the report call, after a failproofai deny, or while Self Reports is off; it is not a policy and never replaces one's answer (#1062) ### Fixes -- Self Reports on macOS: the stdio server's `tools/list` and `tools/call` lines reached the daemon log again. Its process lookup runs `ps` synchronously on macOS; done mid-request it blocked the event loop while a log frame connected, so the frame's 250 ms budget fired first and the line was dropped. The lookup now runs once at start, and a budget timer that fires late gets one more budget before dropping (#1062) +- Self Reports on macOS: the stdio server's log lines after the first reached the daemon log again. Each line's connection was torn down as soon as its write finished, and macOS drops a connection the daemon has not accepted yet, data and all; the client now half-closes and waits for the daemon to close. The process lookup (`ps`, synchronous on macOS) also runs once at start, and a budget timer that fires late gets one more budget (#1062) - `update` and `config` no longer say "restart the gateway" for Hermes or OpenClaw on a machine where that program is not installed: with no `hermes` or `openclaw` there is no gateway to restart (#1062) - Quieter `update`, `config` and `policies --install`/`--uninstall`: no `Hermes: hermes/default already current, gateway restarting` or `OpenClaw: openclaw/default gateway restarting` rows and no `Self Reports: on for N agents` line when all went well. Only what needs the user is printed (a gateway to restart by hand, a Hermes failure, an agent the Self Reports sync could not update); `self-report status` shows the last update's gateway rows (#1062) - Self Reports: the daemon log's report preview is cut on a character boundary and marked with an ASCII `...`, so no multi-byte character is split (seen as `enviro�`); the stdio server and the CLI cut the preview and the guidance line by code point, never through a surrogate pair (#1062) diff --git a/src/hooks/self-report-log.ts b/src/hooks/self-report-log.ts index fa21776e7..e485f4b4b 100644 --- a/src/hooks/self-report-log.ts +++ b/src/hooks/self-report-log.ts @@ -149,7 +149,11 @@ function selfReportLogSend(event: SelfReportLogEvent): Promise { socket.on("error", done); socket.on("close", done); socket.on("connect", () => { - socket.end(frame, done); + // Half-close and wait for the daemon to close its side (`close` above), + // not just for our write to finish: on macOS a connection the daemon has + // not accepted yet is dropped, data and all, when the client destroys it, + // so tearing down on `finish` lost every line after the first. + socket.end(frame); }); }); } From 0db0f853fd56b237b7550853fcb471b69cd5005d Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 18:26:52 +0530 Subject: [PATCH 51/54] Self Reports: keep the process alive while a log event is in flight Since the log client half-closes and waits for the daemon to close (the macOS fix), a process with nothing else left to do found its flush pending with the socket and the budget timer both unref'd, and Node exited 13 (unsettled top-level await): packaged MCP probes and enable/disable all exited 13. The budget timer is no longer unref'd. It keeps the loop alive for at most the budget (one more when it fires late) and done() clears it, so a daemon that closes promptly costs nothing and one that never closes costs the budget. The half-close and wait for close is unchanged. The new test builds the CLI the way build:cli does and runs it under Node (Bun does not report an unsettled top-level await), against a fake daemon that closes late or never: exit 0, bounded time; enable/disable exit 0. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/self-report-log-exit.test.ts | 125 +++++++++++++++++++ src/hooks/self-report-log.ts | 9 +- 3 files changed, 133 insertions(+), 2 deletions(-) create mode 100644 __tests__/hooks/self-report-log-exit.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index a17a46fe3..2ae1dcd57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -60,6 +60,7 @@ - `block-failproofai-commands` decides whether a bare `grep`/`rg`/`jq` (or `cat`/`tee` for a heredoc) is the standard tool from the agent's own PATH, which the hook client now carries in the payload, not from the PATH of the process evaluating it. Through failproofaid that was the daemon's PATH, so a shadow `grep` early on the agent's PATH could run a quoted argument; with no agent PATH (an older client, the Hermes and OpenClaw plugins) no bare name is exempt (#1062) - Self Reports: the stdio server matches hook rows and picks the session for a report by its own agent process, exactly: each side names the nearest process above it that is not a shell or exec wrapper, and session-start and prompt rows now carry it too. An agent started inside another one in the same directory no longer has its hook rows claimed, or its reports filed, under the outer agent's session; with no session of its own it takes its own transcript, else `unattributed` (#1062) - Self Reports: the daemon log's report preview is scrubbed from the detail as the agent sent it (bounded at 64 KiB), not from the 2000-character report. A credential that straddled that cut, such as a JWT starting near the beginning and running past it, was cut into something the scrubber no longer recognised, and its start reached the log over both stdio and HTTP (#1062) +- Self Reports: commands that send a log event to the daemon (the stdio MCP server, `self-report enable`/`disable`) exit 0 again instead of 13. The log client now waits for the daemon to close the connection, and with both its socket and its budget timer unref'd nothing kept Node running while it waited; the budget timer now does, for at most the budget (#1062) ### Docs diff --git a/__tests__/hooks/self-report-log-exit.test.ts b/__tests__/hooks/self-report-log-exit.test.ts new file mode 100644 index 000000000..8b42ffe75 --- /dev/null +++ b/__tests__/hooks/self-report-log-exit.test.ts @@ -0,0 +1,125 @@ +// @vitest-environment node +/** + * The real CLI exits 0 after its Self Reports log events, whatever the daemon + * does with the connection. The log client half-closes and waits for the + * daemon to close (macOS drops a not-yet-accepted connection's data when the + * client destroys it), and that wait is bounded by the budget. With both the + * socket and the budget timer unref'd, a process with nothing else to do + * found its flush pending and Node exited 13 (unsettled top-level await). + */ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { execFileSync, spawn } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { createServer, type Server, type Socket } from "node:net"; + +const ROOT = resolve(__dirname, "..", ".."); +const ENTRY = resolve(ROOT, "bin", "fail" + "proofai.mjs"); +// The packaged CLI is the bundle run by Node (package.json "bin"), where an +// unsettled top-level await is exit 13; Bun does not report it. Built the way +// `build:cli` builds it, into a cache directory beside node_modules so its +// externals resolve. +const BUNDLE = resolve(ROOT, "node_modules", ".cache", `fp-exit-test-${process.pid}`, "cli.mjs"); + +beforeAll(() => { + execFileSync("bun", ["build", "--target=node", "--format=esm", `--outfile=${BUNDLE}`, ENTRY, "--external", "sql.js"], { + cwd: ROOT, + stdio: "ignore", + }); +}, 120_000); + +afterAll(() => { + rmSync(dirname(BUNDLE), { recursive: true, force: true }); +}); +const INIT = { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "t", version: "1" } } }; +const LIST = { jsonrpc: "2.0", id: 2, method: "tools/list" }; + +let home: string; +let server: Server | null = null; +const held: Socket[] = []; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "fpai-srlog-exit-")); +}); + +afterEach(async () => { + for (const s of held.splice(0)) s.destroy(); + await new Promise((ok) => (server ? server.close(() => ok()) : ok())); + server = null; + rmSync(home, { recursive: true, force: true }); +}); + +/** A fake daemon socket: reads every frame, then closes after `closeAfterMs`, or never (null). */ +function fakeDaemon(path: string, closeAfterMs: number | null): Promise<{ frames: () => number }> { + let frames = 0; + server = createServer((socket) => { + held.push(socket); + socket.on("data", () => frames++); + socket.on("error", () => {}); + socket.on("end", () => { + if (closeAfterMs !== null) setTimeout(() => socket.destroy(), closeAfterMs); + }); + }); + return new Promise((ok) => server!.listen(path, () => ok({ frames: () => frames }))); +} + +function run(args: string[], input: string): Promise<{ code: number | null; ms: number; stdout: string; stderr: string }> { + return new Promise((done, fail) => { + const started = Date.now(); + const child = spawn(process.execPath, [BUNDLE, ...args], { + env: { + ...process.env, + HOME: join(home, "user"), + FAILPROOFAI_HOME: home, + FAILPROOFAI_DAEMON_SOCKET: join(home, "d.sock"), + FAILPROOFAI_TELEMETRY_DISABLED: "1", + FAILPROOFAI_CODEX_SYSTEM_CONFIG: "off", + }, + stdio: ["pipe", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (b: Buffer) => (stdout += b.toString())); + child.stderr.on("data", (b: Buffer) => (stderr += b.toString())); + child.on("error", fail); + child.on("close", (code) => done({ code, ms: Date.now() - started, stdout, stderr })); + child.stdin.end(input); + }); +} + +const mcpInput = [INIT, LIST].map((m) => JSON.stringify(m)).join("\n") + "\n"; + +describe("the CLI exits 0 after its log events", () => { + it("mcp: the daemon reads and closes late (within the budget)", async () => { + const daemon = await fakeDaemon(join(home, "d.sock"), 120); + const r = await run(["mcp", "--agent", "claude"], mcpInput); + expect(r.code, r.stderr).toBe(0); + expect(r.stdout).toContain('"id":2'); + expect(daemon.frames()).toBeGreaterThan(0); + }, 30_000); + + it("mcp: the daemon reads and never closes: exits 0 once the budget runs out, not later", async () => { + const daemon = await fakeDaemon(join(home, "d.sock"), null); + const control = await run(["--version"], ""); + const r = await run(["mcp", "--agent", "claude"], mcpInput); + expect(r.code, r.stderr).toBe(0); + expect(daemon.frames()).toBeGreaterThan(0); + // Startup varies; the wait for a daemon that never closes is bounded by + // the budget (250 ms, at most once more when the timer fires late). + expect(r.ms - control.ms).toBeLessThan(1_500); + }, 30_000); + + it("mcp: no daemon socket at all", async () => { + const r = await run(["mcp", "--agent", "claude"], mcpInput); + expect(r.code, r.stderr).toBe(0); + }, 30_000); + + it("self-report enable and disable exit 0 with a daemon that never closes", async () => { + await fakeDaemon(join(home, "d.sock"), null); + for (const sub of ["disable", "enable"]) { + const r = await run(["self-report", sub], ""); + expect(r.code, `${sub}: ${r.stderr}${r.stdout}`).toBe(0); + } + }, 60_000); +}); diff --git a/src/hooks/self-report-log.ts b/src/hooks/self-report-log.ts index e485f4b4b..1d2cd2e3f 100644 --- a/src/hooks/self-report-log.ts +++ b/src/hooks/self-report-log.ts @@ -130,6 +130,13 @@ function selfReportLogSend(event: SelfReportLogEvent): Promise { // call elsewhere), not that the daemon is slow: the connect may already be // done and simply not delivered yet. Give it one more budget before // dropping, so a busy process never reads as an unreachable daemon (#1024). + // + // The budget timer is NOT unref'd: it is what keeps the process alive + // while a send is in flight, and it bounds that to the budget (one more + // when it fires late). Unref'd along with the socket, a process whose + // other work had finished saw a pending flush with nothing keeping the + // loop alive and exited 13 (unsettled top-level await) instead of waiting + // the few milliseconds for the daemon to close. `done` clears it. let armedAt = Date.now(); let extended = false; const expire = (): void => { @@ -138,13 +145,11 @@ function selfReportLogSend(event: SelfReportLogEvent): Promise { extended = true; armedAt = Date.now(); timer = setTimeout(expire, SELF_REPORT_LOG_BUDGET_MS); - timer.unref?.(); return; } done(); }; let timer = setTimeout(expire, SELF_REPORT_LOG_BUDGET_MS); - timer.unref?.(); socket.unref(); socket.on("error", done); socket.on("close", done); From 6047d736cb3efe07c433253ba2d36b8950dbacf1 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 18:29:37 +0530 Subject: [PATCH 52/54] Self Reports: no exemption for an entry that can change what runs; sync leaves foreign programs alone Review round 3: - F19: an entry whose command is our CLI could still run something else through an env (NODE_OPTIONS=--require, PATH, LD_PRELOAD, BUN_*), envFile, cwd or extra arguments, and kept the exemption. selfReportEntryStrictlyOurs now also requires the entry to be exactly what the installer writes for that agent and container (key order aside; only an empty env/envs/env_keys an agent may add is tolerated). - Installer ownership: isOurMcpEntry trusted any command whose name contained "failproofai", so sync replaced a foreign failproofai-foreign server. A stdio command is now ours only when it resolves to a failproofai package's CLI entry point (/bin/failproofai.mjs or dist/cli.mjs with a package.json named failproofai; any version, so an earlier install's npm-link entry is still recognised and migrated), or is a failproofai launcher path that no longer exists (a link an old install left, which runs nothing). Anything else is a conflict and left alone. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/self-report-handler.test.ts | 48 ++++++++++- __tests__/hooks/self-report-install.test.ts | 41 +++++++++- src/hooks/self-report-install.ts | 90 ++++++++++++++++++++- 4 files changed, 173 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ae1dcd57..66696e7bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,6 +61,7 @@ - Self Reports: the stdio server matches hook rows and picks the session for a report by its own agent process, exactly: each side names the nearest process above it that is not a shell or exec wrapper, and session-start and prompt rows now carry it too. An agent started inside another one in the same directory no longer has its hook rows claimed, or its reports filed, under the outer agent's session; with no session of its own it takes its own transcript, else `unattributed` (#1062) - Self Reports: the daemon log's report preview is scrubbed from the detail as the agent sent it (bounded at 64 KiB), not from the 2000-character report. A credential that straddled that cut, such as a JWT starting near the beginning and running past it, was cut into something the scrubber no longer recognised, and its start reached the log over both stdio and HTTP (#1062) - Self Reports: commands that send a log event to the daemon (the stdio MCP server, `self-report enable`/`disable`) exit 0 again instead of 13. The log client now waits for the daemon to close the connection, and with both its socket and its budget timer unref'd nothing kept Node running while it waited; the budget timer now does, for at most the budget (#1062) +- Self Reports: the `report` tool's exemption also needs the entry to be exactly what the installer writes for that agent: any `env` (`NODE_OPTIONS`, `PATH`, `LD_PRELOAD`, …), `envFile`, `cwd`, extra argument or other field can change what runs, so such an entry takes the policy path. Sync and uninstall now treat an entry as theirs only when its command resolves to a failproofai package's CLI (any version, so an earlier install's entry is still upgraded) or is a failproofai launcher that no longer exists; a foreign program merely named like failproofai is reported as a conflict and left alone instead of replaced (#1062) ### Docs diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index 0ef9a9e60..297df7133 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -684,11 +684,55 @@ describe("the early allow, round 2 (F19): strict ownership, and HOME's own confi (cfg.mcpServers as Record).failproofai_local = entry; writeFileSync(claudeJson(), JSON.stringify(cfg)); }; - set({ type: "stdio", command: link, args: ["mcp", "--agent", "claude"] }); + set({ type: "stdio", command: link, args: ["mcp", "--agent", "claude"], alwaysLoad: true }); expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("allow"); - set({ type: "stdio", command: link, args: ["mcp", "--agent", "codex"] }); + set({ type: "stdio", command: link, args: ["mcp", "--agent", "codex"], alwaysLoad: true }); expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); set({ type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude" }); expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); }); }); + +describe("the early allow, round 3 (F19): nothing in the entry may change what runs", () => { + const userHome = () => join(home, "user"); + const claudeJson = () => join(userHome(), ".claude.json"); + const readJson = (p: string) => JSON.parse(readFileSync(p, "utf8")) as Record; + const ours = () => ({ type: "stdio", command: REGISTERED_CLI, args: ["mcp", "--agent", "claude"], alwaysLoad: true }); + const set = (entry: Record) => { + const cfg = readJson(claudeJson()); + (cfg.mcpServers as Record).failproofai_local = entry; + writeFileSync(claudeJson(), JSON.stringify(cfg)); + }; + + it("control: the installer's exact entry, and one with an empty env an agent added, are ours", async () => { + set(ours()); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("allow"); + set({ ...ours(), env: {} }); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("allow"); + }); + + it.each([ + ["env NODE_OPTIONS", { env: { NODE_OPTIONS: "--require /tmp/x.js" } }], + ["env PATH", { env: { PATH: "/tmp/x:/usr/bin" } }], + ["env LD_PRELOAD", { env: { LD_PRELOAD: "/tmp/x.so" } }], + ["env BUN_OPTIONS", { env: { BUN_OPTIONS: "--preload /tmp/x.ts" } }], + ["envFile", { envFile: "/tmp/x.env" }], + ["cwd", { cwd: "/tmp/x" }], + ["an extra argument", { args: ["mcp", "--agent", "claude", "--x"] }], + ["another field", { wrapper: "/tmp/x" }], + ])("an otherwise exact entry plus %s gets no exemption", async (_what, extra) => { + set({ ...ours(), ...extra }); + vi.mocked(loadAllCustomHooks).mockClear(); + const out = await evaluateHookEvent("PreToolUse", "claude", report()); + expect(out.evaluation?.decision).toBe("deny"); + expect(loadAllCustomHooks).toHaveBeenCalled(); + }); + + it("Goose's entry (cmd, empty envs/env_keys) is ours only exactly as written", async () => { + const goose = () => payload("failproofai_local__report", { category: "looping", detail: "x" }); + expect((await evaluateHookEvent("PreToolUse", "goose", goose())).evaluation?.decision).toBe("allow"); + const path = join(userHome(), ".config", "goose", "config.yaml"); + writeFileSync(path, readFileSync(path, "utf8").replace("envs: {}", "envs:\n NODE_OPTIONS: --require /tmp/x.js")); + expect((await evaluateHookEvent("PreToolUse", "goose", goose())).evaluation?.decision).toBe("deny"); + }); +}); diff --git a/__tests__/hooks/self-report-install.test.ts b/__tests__/hooks/self-report-install.test.ts index d89baca3d..c4c6567d9 100644 --- a/__tests__/hooks/self-report-install.test.ts +++ b/__tests__/hooks/self-report-install.test.ts @@ -1,6 +1,6 @@ // @vitest-environment node import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, resolve } from "node:path"; import { parse as parseToml } from "smol-toml"; @@ -288,6 +288,45 @@ describe("ownership", () => { expect(read(path)).toBe(before); }); + // Review round 3: a name containing "failproofai" made a foreign program ours, + // and sync replaced it. Ours now means: resolves to a failproofai package's + // CLI entry point (any version), or a dangling failproofai launcher. + it("leaves a foreign program named like ours alone, with our arguments, and reports it as a conflict", async () => { + const dir = resolve(home, "x"); + mkdirSync(dir, { recursive: true }); + for (const name of ["fail" + "proofai-foreign", "fail" + "proofai"]) { + const program = resolve(dir, name); + writeFileSync(program, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + const path = pathOf("claude"); + put(path, JSON.stringify({ mcpServers: { failproofai_local: { type: "stdio", command: program, args: ["mcp", "--agent", "claude"] } } }, null, 2) + "\n"); + const before = read(path); + expect(isOurMcpEntry(entryIn("claude")), name).toBe(false); + expect((await syncSelfReportMcp(enabledOpts({ agents: ["claude"] })))[0], name).toMatchObject({ status: "conflict", action: "skipped" }); + expect(removeSelfReportMcp({ agents: ["claude"], quiet: true })[0], name).toMatchObject({ status: "conflict" }); + expect(read(path), name).toBe(before); + } + }); + + it("still recognises and migrates what an earlier install wrote: a launcher into any failproofai package, or a dangling one", async () => { + // An earlier version's npm link: /bin/failproofai -> /bin/failproofai.mjs. + const pkg = resolve(home, "old-prefix", "lib", "node_modules", "fail" + "proofai"); + mkdirSync(resolve(pkg, "bin"), { recursive: true }); + writeFileSync(resolve(pkg, "package.json"), JSON.stringify({ name: "fail" + "proofai", version: "1.0.0" })); + writeFileSync(resolve(pkg, "bin", "fail" + "proofai.mjs"), "#!/usr/bin/env node\n", { mode: 0o755 }); + const binDir = resolve(home, "old-prefix", "bin"); + mkdirSync(binDir, { recursive: true }); + const link = resolve(binDir, "fail" + "proofai"); + symlinkSync(resolve(pkg, "bin", "fail" + "proofai.mjs"), link); + const dangling = resolve(home, "gone", "bin", "fail" + "proofai"); + for (const command of [link, dangling]) { + put(pathOf("claude"), JSON.stringify({ mcpServers: { failproofai_local: { type: "stdio", command, args: ["mcp", "--agent", "claude"] } } }, null, 2) + "\n"); + expect(isOurMcpEntry(entryIn("claude")), command).toBe(true); + const [r] = await syncSelfReportMcp(enabledOpts({ agents: ["claude"], deps: { httpAgents: [] } })); + expect(r, command).toMatchObject({ status: "ok", action: "updated" }); + expect(entryIn("claude")?.command).toBe(CLI); + } + }); + it("treats a hand-written codex [mcp_servers.failproofai_local] outside our markers as foreign", async () => { const path = pathOf("codex"); put(path, '[mcp_servers.failproofai_local]\nurl = "http://127.0.0.1:4319/mcp?agent=codex"\n'); diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts index f0dac64f1..784e201c6 100644 --- a/src/hooks/self-report-install.ts +++ b/src/hooks/self-report-install.ts @@ -217,8 +217,51 @@ export function selfReportStdioArgs(agent: IntegrationType): string[] { const OUR_URL_RE = /^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/mcp\?agent=[a-z][a-z0-9_-]*$/; +/** Launcher names a failproofai install puts on disk (npm's and bun's bin link, the package's own bin). */ +const LAUNCHER_NAMES: ReadonlySet = new Set(["failproofai", "failproofai.cmd", "failproofai.mjs"]); + +/** + * Whether `real` (a resolved path) is the CLI entry point of SOME failproofai + * package: `/bin/failproofai.mjs` or `/dist/cli.mjs` where + * `/package.json` names `failproofai`. Any version: an entry an earlier + * install wrote points at the same npm link, which now resolves to whatever + * version is installed (or the one it was). + */ +function isFailproofaiPackageEntry(real: string): boolean { + const root = resolve(dirname(real), ".."); + const rel = real.slice(root.length + 1); + if (rel !== `bin${sep}failproofai.mjs` && rel !== `dist${sep}cli.mjs`) return false; + try { + const pkg = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")) as { name?: unknown }; + return pkg.name === "failproofai"; + } catch { + return false; + } +} + +/** + * Whether a stdio command is one failproofai wrote (install, sync, uninstall): + * it resolves, through every link, to a failproofai package's CLI entry point + * (`isFailproofaiPackageEntry`). A path that no longer resolves at all counts + * only when its name is exactly a failproofai launcher: a link an earlier + * install left behind, which runs nothing. A program merely NAMED like ours + * (`failproofai-foreign`, or a script called `failproofai` that is not a + * failproofai package) is foreign, so sync reports it as a conflict and + * leaves it alone (review round 3). + */ +function isOurCliCommand(command: string): boolean { + if (!command.startsWith("/")) return false; + let real: string; + try { + real = realpathSync(command); + } catch { + return LAUNCHER_NAMES.has(basename(command).toLowerCase()) && !existsSync(command); + } + return isFailproofaiPackageEntry(real); +} + function isOurCommand(command: unknown, args: unknown): boolean { - if (typeof command !== "string" || !basename(command).toLowerCase().includes("failproofai")) return false; + if (typeof command !== "string" || !isOurCliCommand(command)) return false; return Array.isArray(args) && args[0] === "mcp" && args[1] === "--agent" && typeof args[2] === "string"; } @@ -1260,7 +1303,12 @@ function selfReportOwnCliEntries(): Set { * writes none any more, and the hook cannot cheaply prove which process * answers that port, so it takes the policy path until sync moves it to stdio. */ -export function selfReportEntryStrictlyOurs(entry: unknown, agent: IntegrationType, ownEntries: Set = selfReportOwnCliEntries()): boolean { +export function selfReportEntryStrictlyOurs( + entry: unknown, + agent: IntegrationType, + ownEntries: Set = selfReportOwnCliEntries(), + container?: string[], +): boolean { if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false; const e = entry as Record; if (["url", "serverUrl", "uri"].some((k) => e[k] !== undefined)) return false; @@ -1275,6 +1323,15 @@ export function selfReportEntryStrictlyOurs(entry: unknown, agent: IntegrationTy } if (typeof command !== "string" || !command.startsWith("/")) return false; if (!Array.isArray(args) || args.length !== 3 || args[0] !== "mcp" || args[1] !== "--agent" || args[2] !== agent) return false; + // Nothing beyond what the installer writes for this agent: an `env` + // (NODE_OPTIONS, PATH, LD_PRELOAD, BUN_*…), an `envFile`, a `cwd`, a + // wrapper or any other field can change what runs while the command stays + // ours (review round 3). + const target = SELF_REPORT_MCP_TARGETS[agent]; + if (!target) return false; + const containers = container ? [container] : [["mcpServers"], ["mcp"], ["mcp", "servers"], ["mcp_servers"], ["extensions"]]; + const transport: SelfReportTransport = { kind: "stdio", command, args: selfReportStdioArgs(agent) }; + if (!containers.some((c) => sameShape(e, target.entry(transport, c)))) return false; let real: string; try { real = realpathSync(command); @@ -1284,6 +1341,30 @@ export function selfReportEntryStrictlyOurs(entry: unknown, agent: IntegrationTy return ownEntries.has(real); } +/** + * `entry` holds exactly the installer's `expected` fields and values (key order + * aside). The only extra fields allowed are an empty `env`/`envs`/`env_keys` + * (some agents add an empty one when they rewrite their file), which change + * nothing. + */ +function sameShape(entry: Record, expected: Record): boolean { + const canon = (v: unknown): string => + JSON.stringify(v, (_k, x: unknown) => + x && typeof x === "object" && !Array.isArray(x) + ? Object.fromEntries(Object.entries(x as Record).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) + : x, + ); + for (const [k, v] of Object.entries(entry)) { + if (k in expected) continue; + const empty = (Array.isArray(v) && v.length === 0) || (!!v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).length === 0); + if (!(["env", "envs", "env_keys"].includes(k) && empty)) return false; + } + for (const [k, v] of Object.entries(expected)) { + if (canon(entry[k]) !== canon(v)) return false; + } + return true; +} + /** * Whether the `failproofai_local` server `agent` would talk to from `cwd` is * failproofai's, so its `report` tool may skip the policies (the hook's early @@ -1310,10 +1391,11 @@ export function selfReportRegistrationOwned(agent: IntegrationType, cwd: string const ownEntries = selfReportOwnCliEntries(); for (const path of target.paths()) { if (!existsSync(path)) continue; - const cur = opsFor(target, path).current(); + const ops = opsFor(target, path); + const cur = ops.current(); if (cur.state === "foreign") return false; if (cur.state === "ours") { - if (!selfReportEntryStrictlyOurs(cur.entry, agent, ownEntries)) return false; + if (!selfReportEntryStrictlyOurs(cur.entry, agent, ownEntries, ops.container)) return false; ours = true; } } From d76ce83101bda24012941e37e2b4e79ecb9dbc0e Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 18:31:22 +0530 Subject: [PATCH 53/54] Self Reports: dedup across builds while an upgrade is half done After `npm i -g` of a newer build, the daemon's warm worker keeps running the previous build until the daemon restarts. The new hook client stamped only `failproofai_report_agent_pid`, the old worker copied only the earlier `failproofai_report_agent_pids` list onto the row, so the row had no stamp and the new stdio server recorded a duplicate Claude report (seen on a real machine; one event again after a daemon restart). - The client stamps both forms: the pid, and the list `[pid]`, so an older worker still copies a stamp (selfReportAgentPids) onto the row. Both are replaced or dropped, never taken from the agent's payload. - The server matches a row by `agentPid`, or by the FIRST pid of `selfReportAgentPids` (selfReportRowAgentPid). Only the first: a longer list from an older client may hold an outer agent further up, and matching that would suppress a report that is not its own. Unsure means record. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/hooks/self-report-ancestry.test.ts | 8 ++++- .../hooks/self-report-hook-trust.test.ts | 32 ++++++++++++++++- crates/PROTOCOL.md | 4 +++ src/hooks/self-report-ancestry.ts | 34 ++++++++++++++++--- src/hooks/self-report-hook-trust.ts | 6 ++-- 6 files changed, 77 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 66696e7bb..3b5b195ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,6 +62,7 @@ - Self Reports: the daemon log's report preview is scrubbed from the detail as the agent sent it (bounded at 64 KiB), not from the 2000-character report. A credential that straddled that cut, such as a JWT starting near the beginning and running past it, was cut into something the scrubber no longer recognised, and its start reached the log over both stdio and HTTP (#1062) - Self Reports: commands that send a log event to the daemon (the stdio MCP server, `self-report enable`/`disable`) exit 0 again instead of 13. The log client now waits for the daemon to close the connection, and with both its socket and its budget timer unref'd nothing kept Node running while it waited; the budget timer now does, for at most the budget (#1062) - Self Reports: the `report` tool's exemption also needs the entry to be exactly what the installer writes for that agent: any `env` (`NODE_OPTIONS`, `PATH`, `LD_PRELOAD`, …), `envFile`, `cwd`, extra argument or other field can change what runs, so such an entry takes the policy path. Sync and uninstall now treat an entry as theirs only when its command resolves to a failproofai package's CLI (any version, so an earlier install's entry is still upgraded) or is a failproofai launcher that no longer exists; a foreign program merely named like failproofai is reported as a conflict and left alone instead of replaced (#1062) +- Self Reports: right after an upgrade, while failproofaid still runs the previous build's worker, a Claude Code or Codex report is no longer recorded twice. The hook client stamps the report call in both the current and the earlier form, and the stdio server matches a row stamped either way; a row whose stamp it cannot read is still recorded rather than dropped (#1062) ### Docs diff --git a/__tests__/hooks/self-report-ancestry.test.ts b/__tests__/hooks/self-report-ancestry.test.ts index 43dbc25d3..7e26b9999 100644 --- a/__tests__/hooks/self-report-ancestry.test.ts +++ b/__tests__/hooks/self-report-ancestry.test.ts @@ -7,6 +7,7 @@ import { describe, expect, it } from "vitest"; import { SELF_REPORT_AGENT_PID_KEY, + SELF_REPORT_AGENT_PIDS_KEY_V1, selfReportAgentPid, selfReportAgentPidOf, selfReportAncestry, @@ -40,8 +41,13 @@ describe("selfReportMarkAgentPid", () => { it("stamps a Claude Code or Codex report call, and any agent's session-start and prompt events", () => { for (const cli of ["claude", "codex"]) { - expect(JSON.parse(selfReportMarkAgentPid(cli, "PreToolUse", report(), pid))[SELF_REPORT_AGENT_PID_KEY]).toBe(4001); + const out = JSON.parse(selfReportMarkAgentPid(cli, "PreToolUse", report(), pid)); + expect(out[SELF_REPORT_AGENT_PID_KEY]).toBe(4001); + // And the earlier list form, which a worker of the previous build copies. + expect(out[SELF_REPORT_AGENT_PIDS_KEY_V1]).toEqual([4001]); } + const spoofedV1 = report({ [SELF_REPORT_AGENT_PIDS_KEY_V1]: [9, 8] }); + expect(JSON.parse(selfReportMarkAgentPid("claude", "PreToolUse", spoofedV1, () => undefined))).not.toHaveProperty(SELF_REPORT_AGENT_PIDS_KEY_V1); for (const [cli, event] of [["cursor", "SessionStart"], ["claude", "UserPromptSubmit"], ["copilot", "UserPromptSubmit"]]) { const payload = JSON.stringify({ session_id: "s", prompt: "hi" }); expect(JSON.parse(selfReportMarkAgentPid(cli, event, payload, pid))[SELF_REPORT_AGENT_PID_KEY], `${cli} ${event}`).toBe(4001); diff --git a/__tests__/hooks/self-report-hook-trust.test.ts b/__tests__/hooks/self-report-hook-trust.test.ts index 5d04c10b1..779764ff1 100644 --- a/__tests__/hooks/self-report-hook-trust.test.ts +++ b/__tests__/hooks/self-report-hook-trust.test.ts @@ -22,7 +22,7 @@ import { } from "../../src/hooks/self-report-mcp"; import { selfReportCliDirs, resolveSelfReportCliPath, syncSelfReportMcp } from "../../src/hooks/self-report-install"; import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; -import { selfReportServerAgentPid } from "../../src/hooks/self-report-ancestry"; +import { SELF_REPORT_AGENT_PIDS_KEY_V1, selfReportMarkAgentPid, selfReportServerAgentPid } from "../../src/hooks/self-report-ancestry"; import { selfReportFindSessionMatch, writeSelfReportEvent } from "../../src/hooks/self-report-mcp"; import { runSelfReportCommand } from "../../src/hooks/self-report-cli"; @@ -384,6 +384,36 @@ describe("the server records what the hook did not, once", () => { expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 51001)).toBe(true); }); + // Round 3, item 6: after `npm i -g` the daemon's warm worker keeps running the + // previous build until the daemon restarts. That worker copies only the + // earlier list form of the stamp onto the row. + describe("mixed builds during an upgrade", () => { + const args = { category: "looping", detail: "same words" }; + + it("new hook client + a row written by the previous build's worker: the new server still matches it", () => { + // The new client stamps both forms (self-report-ancestry.test.ts). + const payload = JSON.parse( + selfReportMarkAgentPid("codex", "PreToolUse", JSON.stringify({ tool_name: "mcp__failproofai_local__report", tool_input: args }), () => 81001), + ) as Record; + // What the previous build's handler did with it: copy the list form only. + const oldWorkerRow = { cwd: projA, selfReport: { ...args, source: "mcp" }, agentPid: undefined, selfReportAgentPids: payload[SELF_REPORT_AGENT_PIDS_KEY_V1] }; + expect(oldWorkerRow.selfReportAgentPids).toEqual([81001]); + hookRows(oldWorkerRow); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 81002)).toBe(false); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 81001)).toBe(true); + }); + + it("an earlier-format row read by the new server: matched only by its first pid, else recorded", () => { + // The previous build's own client wrote the whole ancestry, nearest first. + hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, agentPid: undefined, selfReportAgentPids: [82001, 82000] }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 82000)).toBe(false); // an outer process: record + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 82001)).toBe(true); + // A shell first (the usual hook runner): the agent cannot be told, so the report is recorded. + hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, agentPid: undefined, selfReportAgentPids: [83005, 83001] }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 83001)).toBe(false); + }); + }); + it("a row that does not say which agent process wrote it never vouches for a call: the report is recorded", () => { const args = { category: "looping", detail: "same words" }; hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, agentPid: undefined }); diff --git a/crates/PROTOCOL.md b/crates/PROTOCOL.md index 9d6486f14..9abd52cd8 100644 --- a/crates/PROTOCOL.md +++ b/crates/PROTOCOL.md @@ -84,6 +84,10 @@ older daemon carries them, and from an older client they are simply absent. Self Reports call and on every agent's session-start and prompt events. The worker keeps it on the activity row as `agentPid` (local only), and the stdio server matches rows and sessions to its own agent by it, exactly. + The client also sends `failproofai_report_agent_pids: [pid]`, the earlier + list form, which a worker of the previous build (still running after an + upgrade until the daemon restarts) copies onto the row as + `selfReportAgentPids`; the server reads the first pid of that list too. - `failproofai_via_devin` (true): a Claude-path Self Reports call made under Devin. diff --git a/src/hooks/self-report-ancestry.ts b/src/hooks/self-report-ancestry.ts index 3f30c3c35..e6af55003 100644 --- a/src/hooks/self-report-ancestry.ts +++ b/src/hooks/self-report-ancestry.ts @@ -30,6 +30,16 @@ import { isSelfReportToolName } from "./self-report-names"; /** Payload key the hook CLI adds: the pid of the agent process above the hook. */ export const SELF_REPORT_AGENT_PID_KEY = "failproofai_report_agent_pid"; +/** + * The earlier form of the stamp: a pid list a worker of the previous build + * copies onto a report row as `selfReportAgentPids`. The client writes BOTH, + * the list holding just the agent pid, because after `npm i -g` the daemon's + * warm worker keeps running the previous build until the daemon restarts, and + * a row it wrote without a stamp made the new stdio server record the report + * a second time. + */ +export const SELF_REPORT_AGENT_PIDS_KEY_V1 = "failproofai_report_agent_pids"; + /** How many processes above this one are looked at. */ export const SELF_REPORT_ANCESTRY_DEPTH = 8; @@ -114,6 +124,22 @@ export function selfReportServerAgentPid(): number | undefined { return serverAgentPid.value; } +/** + * The agent pid a hook-activity row was stamped with, in either form: this + * build's `agentPid`, or `selfReportAgentPids` (a list, nearest process + * first) from a worker of the previous build. Only the list's FIRST pid + * counts: the client stamps `[pid]`, and a longer list from an older client + * names the agent only there when the hook ran with no shell between; any + * later entry may be an outer agent, and taking it would suppress a report + * that is not its own. With neither, undefined: the server records. + */ +export function selfReportRowAgentPid(row: Record): number | undefined { + const pid = selfReportAgentPidOf(row.agentPid); + if (pid !== undefined) return pid; + const list = row.selfReportAgentPids; + return Array.isArray(list) ? selfReportAgentPidOf(list[0]) : undefined; +} + /** A pid in a payload or row field, kept only in its declared shape. */ export function selfReportAgentPidOf(value: unknown): number | undefined { return typeof value === "number" && Number.isSafeInteger(value) && value > 1 ? value : undefined; @@ -134,16 +160,16 @@ export function selfReportMarkAgentPid( ): string { const sessionEvent = SESSION_EVENTS.includes(canonicalEvent); const maybeReport = HOOK_RECORDED.includes(cli) && /failproofai_local/i.test(stdin); - const carried = stdin.includes(SELF_REPORT_AGENT_PID_KEY); + const carried = stdin.includes(SELF_REPORT_AGENT_PID_KEY); // also matches the V1 key, which it prefixes if (!sessionEvent && !maybeReport && !carried) return stdin; try { const parsed = JSON.parse(stdin) as unknown; if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return stdin; - const { [SELF_REPORT_AGENT_PID_KEY]: dropped, ...rest } = parsed as Record; + const { [SELF_REPORT_AGENT_PID_KEY]: dropped, [SELF_REPORT_AGENT_PIDS_KEY_V1]: droppedV1, ...rest } = parsed as Record; const stamp = sessionEvent || (maybeReport && isSelfReportToolName(rest.tool_name)); const pid = stamp ? agentPid() : undefined; - if (pid !== undefined) return JSON.stringify({ ...rest, [SELF_REPORT_AGENT_PID_KEY]: pid }); - return dropped === undefined ? stdin : JSON.stringify(rest); + if (pid !== undefined) return JSON.stringify({ ...rest, [SELF_REPORT_AGENT_PID_KEY]: pid, [SELF_REPORT_AGENT_PIDS_KEY_V1]: [pid] }); + return dropped === undefined && droppedV1 === undefined ? stdin : JSON.stringify(rest); } catch { return stdin; } diff --git a/src/hooks/self-report-hook-trust.ts b/src/hooks/self-report-hook-trust.ts index 40d722c74..1370c029f 100644 --- a/src/hooks/self-report-hook-trust.ts +++ b/src/hooks/self-report-hook-trust.ts @@ -39,7 +39,7 @@ import { claudeConfigDir, getIntegration } from "./integrations"; import { getHookActivityEntriesSince } from "./hook-activity-store"; import { readEnabledSelfReport, resolveSelfReportCategory, selfReportArgs } from "./self-report"; import { selfReportClip } from "./self-report-names"; -import { selfReportAgentPidOf, selfReportServerAgentPid } from "./self-report-ancestry"; +import { selfReportRowAgentPid, selfReportServerAgentPid } from "./self-report-ancestry"; import { failproofaiHome } from "./fp-home"; /** The agents whose hook, when it runs, is the recorder. */ @@ -248,7 +248,9 @@ export function selfReportHookRecordedRecently( const ts = typeof row.timestamp === "number" ? row.timestamp : NaN; if (!Number.isFinite(ts) || now - ts > SELF_REPORT_HOOK_DEDUPE_MS || ts - now > 60_000) return false; if (typeof row.cwd !== "string" || !row.cwd || sameDir(row.cwd) !== here) return false; - if (selfReportAgentPidOf(row.agentPid) !== agentPid) return false; + // Either stamp: a worker of the previous build (still running until the + // daemon restarts after an upgrade) writes `selfReportAgentPids`. + if (selfReportRowAgentPid(row) !== agentPid) return false; const sr = row.selfReport as { category?: unknown; detail?: unknown } | undefined; return !!sr && (sr.category === want.category || sr.category === resolved) && sr.detail === want.detail; }); From f256a53c78bf6ed3f0da1085c623f4cffe9fae9d Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Mon, 30 Nov 2026 18:41:12 +0530 Subject: [PATCH 54/54] Self Reports: never keep part of a token at a detail cut Review round 3 (new blocker, and F18 still open): every cut of a report's detail kept a straddling credential as a fragment no scrubber recognises. - The 2,000-code-point report cut ran before the collector's upload redaction, so a long JWT was uploaded as a raw 2,000-character fragment through the hook, stdio, HTTP and both SDKs. - The 64 KiB log bound (stdio frame, HTTP log_detail) cut a JWT straddling it, and the daemon's scrubber passed the prefix. One rule now, in every implementation (selfReportCutDetail in the CLI, used by the hook, the stdio server, the activity store, dedup and the log client; cut_detail in the daemon for HTTP reports, the HTTP log bound and hook rows; cut_report_detail in the Python SDK; clipDetail in the TS SDK): cut to max code points; if the code point after the cut is not whitespace, drop the trailing run of non-whitespace; drop trailing whitespace; an empty result is "[detail cut]". Whitespace is ASCII only (space, tab, LF, CR, FF, VT) so all four agree. Text that fits is kept whole. test-fixtures/self-report/truncation.golden.json gains a `detail_cut` section (marker, whitespace, nine cases including a JWT straddling 2,000 and one longer than 2,000) that the CLI, daemon and both SDK golden tests run; its plain `cases` still pin the code-point cut used for other text. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + __tests__/hooks/self-report-golden.test.ts | 29 +++++- __tests__/hooks/self-report-handler.test.ts | 7 +- __tests__/hooks/self-report-log.test.ts | 32 ++++++- __tests__/hooks/self-report.test.ts | 4 +- crates/fpai-collect/src/self_report.rs | 94 +++++++++++++++++-- .../src/sources/hooks/transform.rs | 2 +- crates/fpai-collect/tests/hooks_source.rs | 5 +- docs/reference/events-and-configuration.mdx | 2 +- docs/self-reports.mdx | 2 +- sdk/python/CHANGELOG.md | 5 +- sdk/python/failproofai_sdk/_events.py | 38 +++++++- sdk/python/failproofai_sdk/_self_report.py | 6 +- sdk/python/tests/test_self_report.py | 7 +- sdk/python/tests/test_self_report_golden.py | 22 ++++- sdk/typescript/CHANGELOG.md | 5 +- sdk/typescript/src/self-report-spec.ts | 28 +++++- sdk/typescript/test/self-report.test.ts | 36 +++++-- src/hooks/hook-activity-store.ts | 4 +- src/hooks/self-report-hook-trust.ts | 4 +- src/hooks/self-report-log.ts | 6 +- src/hooks/self-report-mcp.ts | 3 +- src/hooks/self-report-names.ts | 29 ++++++ src/hooks/self-report.ts | 6 +- .../self-report/truncation.golden.json | 20 +++- 25 files changed, 348 insertions(+), 50 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b5b195ed..30004b8da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,6 +63,8 @@ - Self Reports: commands that send a log event to the daemon (the stdio MCP server, `self-report enable`/`disable`) exit 0 again instead of 13. The log client now waits for the daemon to close the connection, and with both its socket and its budget timer unref'd nothing kept Node running while it waited; the budget timer now does, for at most the budget (#1062) - Self Reports: the `report` tool's exemption also needs the entry to be exactly what the installer writes for that agent: any `env` (`NODE_OPTIONS`, `PATH`, `LD_PRELOAD`, …), `envFile`, `cwd`, extra argument or other field can change what runs, so such an entry takes the policy path. Sync and uninstall now treat an entry as theirs only when its command resolves to a failproofai package's CLI (any version, so an earlier install's entry is still upgraded) or is a failproofai launcher that no longer exists; a foreign program merely named like failproofai is reported as a conflict and left alone instead of replaced (#1062) - Self Reports: right after an upgrade, while failproofaid still runs the previous build's worker, a Claude Code or Codex report is no longer recorded twice. The hook client stamps the report call in both the current and the earlier form, and the stdio server matches a row stamped either way; a row whose stamp it cannot read is still recorded rather than dropped (#1062) +- Self Reports: a report's detail is cut to 2,000 characters without ever keeping part of a word: when the cut lands inside one, that whole word goes (a detail that is one long word reads `[detail cut]`). A credential that ran past the cut, such as a long JWT, was kept as a 2,000-character fragment that upload redaction no longer recognised, and was uploaded raw through the hook, the stdio and HTTP servers and both SDKs. The same rule runs in all of them and is pinned in the shared golden fixture (#1062) +- Self Reports: the daemon log's detail, bounded at 64 KiB before the daemon scrubs it, is cut the same way, so a token straddling that bound no longer reaches the log as a recognisable-to-no-one prefix (#1062) ### Docs diff --git a/__tests__/hooks/self-report-golden.test.ts b/__tests__/hooks/self-report-golden.test.ts index e3598e374..7cb42974e 100644 --- a/__tests__/hooks/self-report-golden.test.ts +++ b/__tests__/hooks/self-report-golden.test.ts @@ -21,6 +21,8 @@ import { SELF_REPORT_SERVER_RECORDS, selfReportArgs, selfReportClip, + selfReportCutDetail, + SELF_REPORT_DETAIL_CUT_MARKER, describeSelfReportTool, isSelfReportCursorCall, isSelfReportToolName, @@ -50,7 +52,7 @@ describe("Self Reports golden files (CLI)", () => { expect(golden("instructions.golden.txt").length).toBeLessThan(600); }); - it("cuts detail in code points, as the shared truncation cases say", () => { + it("cuts text in code points, as the shared truncation cases say", () => { const fixture = JSON.parse(golden("truncation.golden.json")) as { max: number; cases: { pad_char: string; pad: number; tail: string; expected_tail: string }[]; @@ -60,7 +62,6 @@ describe("Self Reports golden files (CLI)", () => { const want = c.pad_char.repeat(c.pad) + c.expected_tail; const label = `${c.pad} x ${JSON.stringify(c.pad_char)} + ${JSON.stringify(c.tail)}`; expect(selfReportClip(input, fixture.max), label).toBe(want); - expect(selfReportArgs({ category: "looping", detail: input }).detail, label).toBe(want); } // A lone surrogate (which no golden JSON can carry) becomes U+FFFD, never an unpaired escape. expect(selfReportClip("a\ud83d")).toBe("a\ufffd"); @@ -68,6 +69,30 @@ describe("Self Reports golden files (CLI)", () => { expect(JSON.stringify(selfReportArgs({ detail: "x\ud83d" }))).not.toMatch(/\\ud83d/); }); + // Round 3: a credential running past the 2000 cut was kept as a fragment no + // scrubber recognised, and uploaded raw. The detail cut never leaves part of + // a token at the end, the same way in every implementation. + it("cuts a report's detail without leaving part of a token, as the shared detail_cut cases say", () => { + const fixture = JSON.parse(golden("truncation.golden.json")) as { + max: number; + detail_cut: { marker: string; whitespace: string; cases: { name: string; input: [string, number][]; expected: [string, number][] }[] }; + }; + const join = (parts: [string, number][]) => parts.map(([t, n]) => t.repeat(n)).join(""); + expect(SELF_REPORT_DETAIL_CUT_MARKER).toBe(fixture.detail_cut.marker); + expect(fixture.detail_cut.cases.length).toBeGreaterThan(5); + for (const c of fixture.detail_cut.cases) { + const input = join(c.input); + const want = join(c.expected); + expect(selfReportCutDetail(input, fixture.max), c.name).toBe(want); + expect(selfReportArgs({ category: "looping", detail: input }).detail, c.name).toBe(want); + } + // Every whitespace character in the list splits a token; nothing else does. + for (const ws of fixture.detail_cut.whitespace) { + expect(selfReportCutDetail(`ok${ws}${"t".repeat(2100)}`, fixture.max), JSON.stringify(ws)).toBe("ok"); + } + expect(selfReportCutDetail(`ok\u00a0${"t".repeat(2100)}`, fixture.max)).toBe(SELF_REPORT_DETAIL_CUT_MARKER); + }); + it("resolves a report's category by the shared rules and runs every shared case", () => { const fixture = JSON.parse(golden("category-inference.json")) as { rules: { category: string; keywords: string[] }[]; diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts index 297df7133..1b8e20839 100644 --- a/__tests__/hooks/self-report-handler.test.ts +++ b/__tests__/hooks/self-report-handler.test.ts @@ -282,8 +282,11 @@ describe("Self Reports short-circuit", () => { it("records an unknown category as the listed one it resolves to, a missing detail as empty, and cuts detail at 2000", async () => { await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "made_up" })); expect(rows().pop()!.selfReport).toEqual({ category: "task_failure", detail: "", source: "mcp" }); - await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "looping", detail: "y".repeat(5000) })); - expect((rows().pop()!.selfReport as { detail: string }).detail).toHaveLength(2000); + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "looping", detail: "y ".repeat(2500) })); + expect((rows().pop()!.selfReport as { detail: string }).detail).toBe("y ".repeat(1000).trimEnd()); + // A token running past the cut is never kept in part (round 3). + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "looping", detail: `token eyJ${"a".repeat(3000)}` })); + expect((rows().pop()!.selfReport as { detail: string }).detail).toBe("token"); }); it("infers the category of a call that left it out (the live case), and resolves a near-miss spelling", async () => { diff --git a/__tests__/hooks/self-report-log.test.ts b/__tests__/hooks/self-report-log.test.ts index a814f55bc..ac76bc832 100644 --- a/__tests__/hooks/self-report-log.test.ts +++ b/__tests__/hooks/self-report-log.test.ts @@ -117,10 +117,11 @@ describe("selfReportLog over the daemon socket", () => { it("sends one framed selfReportLog with the whole (bounded) detail, for the daemon to scrub before it cuts", async () => { const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); try { - await sendSelfReportLog({ event: "tools/call", agent: "hermes", transport: "stdio", outcome: "recorded", preview: "x".repeat(70_000) }); + await sendSelfReportLog({ event: "tools/call", agent: "hermes", transport: "stdio", outcome: "recorded", preview: "x ".repeat(35_000) }); await vi.waitFor(() => expect(frames).toHaveLength(1)); expect(frames[0]).toMatchObject({ type: "selfReportLog", protocolVersion: 2, event: { event: "tools/call", agent: "hermes", outcome: "recorded" } }); - expect(((frames[0].event as Record).preview).length).toBe(64 * 1024); + // Bounded at 64 KiB, at a word boundary (the trailing space goes too). + expect(((frames[0].event as Record).preview).length).toBe(64 * 1024 - 1); } finally { server.close(); } @@ -144,11 +145,32 @@ describe("selfReportLog over the daemon socket", () => { } }); + // F18 round 3: a JWT straddling the 64 KiB bound was cut into a fragment the + // daemon's scrubber no longer recognised, and its start reached the log. + it("never sends part of a token at the 64 KiB bound", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + const jwt = `eyJhbGciOiJIUzI1NiJ9.eyJ${"a".repeat(70_000)}.sig`; + await sendSelfReportLog({ event: "tools/call", transport: "stdio", preview: `token ${jwt} rejected` }); + await handleSelfReportRpc( + { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "report", arguments: { category: "looping", detail: jwt } } }, + { agent: "copilot", cwd: home }, + ); + await flushSelfReportLogs(1000); + await vi.waitFor(() => expect(frames.length).toBeGreaterThanOrEqual(2)); + const previews = frames.map((f) => (f.event as Record).preview); + expect(previews[0]).toBe("token"); + expect(previews.some((p) => p?.includes("eyJ"))).toBe(false); + } finally { + server.close(); + } + }); + it("bounds the preview on a character boundary, never through a surrogate pair", async () => { const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); try { // 65535 ASCII then emoji: the 65536th code point is whole, nothing after it. - await sendSelfReportLog({ event: "tools/call", transport: "stdio", preview: `${"a".repeat(64 * 1024 - 1)}😀😀 environment` }); + await sendSelfReportLog({ event: "tools/call", transport: "stdio", preview: `${"a".repeat(64 * 1024 - 1)}😀 environment` }); await vi.waitFor(() => expect(frames).toHaveLength(1)); const preview = (frames[0].event as Record).preview; expect(preview).toBe(`${"a".repeat(64 * 1024 - 1)}😀`); @@ -254,10 +276,10 @@ describe("selfReportLog over the daemon socket", () => { await flushSelfReportLogs(1000); await vi.waitFor(() => expect(frames).toHaveLength(1)); expect((frames[0].event as Record).preview).toBe(detail); - // The report itself is still cut at 2000. + // The report itself is cut at 2000, without the part of the token before the cut. const [file] = readdirSync(join(home, "custom-agents", "events")).filter((f) => f.endsWith(".jsonl")); const event = JSON.parse(readFileSync(join(home, "custom-agents", "events", file), "utf8")); - expect([...event.detail]).toHaveLength(2000); + expect(event.detail).toBe("token"); } finally { server.close(); } diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts index 5d124f14c..27b4e6fd6 100644 --- a/__tests__/hooks/self-report.test.ts +++ b/__tests__/hooks/self-report.test.ts @@ -97,7 +97,9 @@ describe("tool text and schema (contract §3)", () => { it("selfReportArgs keeps unknown categories, defaults detail to empty, cuts at 2000, and unwraps arguments", () => { expect(selfReportArgs({ category: "nope" })).toEqual({ category: "nope", detail: "" }); - expect(selfReportArgs({ category: "looping", detail: "z".repeat(3000) }).detail).toHaveLength(2000); + // Cut at 2000 code points, never leaving part of a token at the end. + expect(selfReportArgs({ category: "looping", detail: "z ".repeat(1500) }).detail).toBe("z ".repeat(1000).trimEnd()); + expect(selfReportArgs({ category: "looping", detail: "z".repeat(3000) }).detail).toBe("[detail cut]"); expect(selfReportArgs({ arguments: { category: "looping", detail: "d" } })).toEqual({ category: "looping", detail: "d" }); expect(selfReportArgs({ arguments: '{"category":"looping","detail":"s"}' })).toEqual({ category: "looping", detail: "s" }); expect(selfReportArgs(undefined)).toEqual({ category: "", detail: "" }); diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs index a5e3d8179..d9987c681 100644 --- a/crates/fpai-collect/src/self_report.rs +++ b/crates/fpai-collect/src/self_report.rs @@ -189,6 +189,40 @@ pub fn truncate_chars(s: &str, max: usize) -> String { } } +/// What a detail cut down to nothing reads as +/// (test-fixtures/self-report/truncation.golden.json `detail_cut`). +pub const DETAIL_CUT_MARKER: &str = "[detail cut]"; + +/// The whitespace [`cut_detail`] splits on: ASCII only, so every +/// implementation agrees (Rust's `char::is_whitespace` is wider). +fn is_cut_whitespace(c: char) -> bool { + matches!(c, ' ' | '\t' | '\n' | '\r' | '\u{0c}' | '\u{0b}') +} + +/// A report's detail cut to `max` chars without leaving part of a token at +/// the end. A credential running past the cut (a long JWT or key) would +/// otherwise be kept as a fragment no secret scrubber recognises, and be +/// uploaded and logged as such. When the char right after the cut is not +/// whitespace, the trailing run of non-whitespace is dropped; then trailing +/// whitespace; an empty result is [`DETAIL_CUT_MARKER`]. Text that fits is +/// kept whole. The CLI (`selfReportCutDetail`) and both SDKs do the same; +/// truncation.golden.json `detail_cut` holds the cases. +pub fn cut_detail(s: &str, max: usize) -> String { + let Some((at, next)) = s.char_indices().nth(max) else { + return s.to_string(); + }; + let mut head = &s[..at]; + if !is_cut_whitespace(next) { + head = head.trim_end_matches(|c: char| !is_cut_whitespace(c)); + } + let head = head.trim_end_matches(is_cut_whitespace); + if head.is_empty() { + DETAIL_CUT_MARKER.to_string() + } else { + head.to_string() + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct McpEndpoint { pub port: u16, @@ -1198,7 +1232,7 @@ impl Report { pub fn from_args(args: &Value) -> Self { Report { category: arg_text(args, "category", CATEGORY_ALIASES), - detail: truncate_chars(&arg_text(args, "detail", DETAIL_ALIASES), MAX_DETAIL_CHARS), + detail: cut_detail(&arg_text(args, "detail", DETAIL_ALIASES), MAX_DETAIL_CHARS), } } @@ -1209,7 +1243,8 @@ impl Report { /// scrubber no longer recognises, and its start was logged (F18). Bounded /// by the transport: the HTTP body is at most [`MAX_BODY_BYTES`]. pub fn log_detail(args: &Value) -> String { - truncate_chars(&arg_text(args, "detail", DETAIL_ALIASES), MAX_BODY_BYTES) + // Bounded without leaving part of a token at the bound either. + cut_detail(&arg_text(args, "detail", DETAIL_ALIASES), MAX_BODY_BYTES) } } @@ -1628,8 +1663,9 @@ mod tests { "b".repeat(43) ); let args = json!({"category": "looping", "detail": format!("token {jwt} rejected")}); + // The report itself keeps no part of the token (round 3). let clipped = Report::from_args(&args).detail; - assert_eq!(clipped.chars().count(), MAX_DETAIL_CHARS); + assert_eq!(clipped, "token"); let raw = Report::log_detail(&args); assert!(raw.ends_with(" rejected")); let preview = log_preview(&raw); @@ -2140,9 +2176,12 @@ mod tests { #[test] fn report_arguments_are_kept_as_given() { - let r = Report::from_args(&json!({"category": "made_up", "detail": "x".repeat(3000)})); + let r = Report::from_args(&json!({"category": "made_up", "detail": "x ".repeat(1500)})); assert_eq!(r.category, "made_up"); - assert_eq!(r.detail.chars().count(), 2000); + // Cut at 2000 chars without part of a token (the trailing space goes too). + assert_eq!(r.detail.chars().count(), 1999); + let r = Report::from_args(&json!({"detail": "x".repeat(3000)})); + assert_eq!(r.detail, DETAIL_CUT_MARKER); let r = Report::from_args(&json!({})); assert_eq!( r, @@ -2687,12 +2726,55 @@ mod tests { let input = format!("{pad}{}", case["tail"].as_str().unwrap()); let want = format!("{pad}{}", case["expected_tail"].as_str().unwrap()); assert_eq!(truncate_chars(&input, max), want, "{case}"); + } + } + + #[test] + fn golden_detail_cut_never_leaves_part_of_a_token() { + let fixture: Value = serde_json::from_str(&golden("truncation.golden.json")).unwrap(); + let max = fixture["max"].as_u64().unwrap() as usize; + let spec = &fixture["detail_cut"]; + assert_eq!(spec["marker"].as_str().unwrap(), DETAIL_CUT_MARKER); + let join = |parts: &Value| -> String { + parts + .as_array() + .unwrap() + .iter() + .map(|p| { + p[0].as_str() + .unwrap() + .repeat(p[1].as_u64().unwrap() as usize) + }) + .collect() + }; + let cases = spec["cases"].as_array().unwrap(); + assert!(cases.len() > 5); + for case in cases { + let input = join(&case["input"]); + let want = join(&case["expected"]); + assert_eq!(cut_detail(&input, max), want, "{}", case["name"]); assert_eq!( Report::from_args(&json!({"category": "looping", "detail": input})).detail, want, - "{case}" + "{}", + case["name"] ); } + for ws in spec["whitespace"].as_str().unwrap().chars() { + let text = format!("ok{ws}{}", "t".repeat(2100)); + assert_eq!(cut_detail(&text, max), "ok", "{ws:?}"); + } + let nbsp = format!("ok\u{a0}{}", "t".repeat(2100)); + assert_eq!(cut_detail( , max), DETAIL_CUT_MARKER); + } + + /// F18 round 3: the HTTP log bound (the 64 KiB body) never leaves part of + /// a token either. + #[test] + fn the_log_detail_bound_never_leaves_part_of_a_token() { + let jwt = format!("eyJhbGciOiJIUzI1NiJ9.eyJ{}.sig", "a".repeat(70_000)); + let args = json!({"detail": format!("token {jwt} rejected")}); + assert_eq!(Report::log_detail(&args), "token"); } #[test] diff --git a/crates/fpai-collect/src/sources/hooks/transform.rs b/crates/fpai-collect/src/sources/hooks/transform.rs index 1ea305b6a..3b3c4b2fe 100644 --- a/crates/fpai-collect/src/sources/hooks/transform.rs +++ b/crates/fpai-collect/src/sources/hooks/transform.rs @@ -1002,7 +1002,7 @@ fn self_report_event(row: &HookRow, session_id: &str, environment: &str) -> Opti ); m.insert( "detail".into(), - json!(crate::self_report::truncate_chars( + json!(crate::self_report::cut_detail( report.detail.as_deref().unwrap_or_default(), crate::self_report::MAX_DETAIL_CHARS )), diff --git a/crates/fpai-collect/tests/hooks_source.rs b/crates/fpai-collect/tests/hooks_source.rs index 87b54358e..8b7ed4883 100644 --- a/crates/fpai-collect/tests/hooks_source.rs +++ b/crates/fpai-collect/tests/hooks_source.rs @@ -895,12 +895,13 @@ fn a_self_report_row_also_emits_a_self_report_event() { #[test] fn a_self_report_with_missing_fields_is_still_recorded() { let mut v: Value = serde_json::from_str(&self_report_row(1785740912184)).unwrap(); - v["selfReport"] = serde_json::json!({"category": "made_up", "detail": "x".repeat(2500)}); + v["selfReport"] = serde_json::json!({"category": "made_up", "detail": "x ".repeat(1250)}); v.as_object_mut().unwrap().remove("toolCallId"); let events = transform::to_events(&parse(&v.to_string()), 0, "local"); let report = &events[2]; assert_eq!(report["category"], "made_up", "unknown categories are kept"); - assert_eq!(report["detail"].as_str().unwrap().chars().count(), 2000); + // Cut at 2000 chars, never leaving part of a token (the trailing space goes too). + assert_eq!(report["detail"].as_str().unwrap().chars().count(), 1999); assert_eq!(report["source"], "mcp"); assert!(report.get("tool_call_id").is_none()); diff --git a/docs/reference/events-and-configuration.mdx b/docs/reference/events-and-configuration.mdx index 54d2d68ea..2e5e3064b 100644 --- a/docs/reference/events-and-configuration.mdx +++ b/docs/reference/events-and-configuration.mdx @@ -23,7 +23,7 @@ Written when an agent calls the [Self Reports](/self-reports) tool. Besides the | Field | Value | | --- | --- | | `category` | The category the agent chose, recorded as given even when it is not on the list | -| `detail` | The agent's one-sentence description of what blocks it, at most 2,000 characters; `""` when it gave none | +| `detail` | The agent's one-sentence description of what blocks it, at most 2,000 characters, cut between words (a single longer word reads `[detail cut]`); `""` when it gave none | | `source` | `mcp` from a coding agent (its hook or failproofai's MCP server), `sdk` from the Python or TypeScript SDK | | `tool_call_id` | The model's id for the call, when known | | `integration` | The coding agent it came from, such as `claude` or `hermes` (not set by the SDKs) | diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx index 45229d414..6dcd74c30 100644 --- a/docs/self-reports.mdx +++ b/docs/self-reports.mdx @@ -62,7 +62,7 @@ An organization's own list replaces these entirely. Names are lowercase letters, | `repeated_tool_failure` | A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. | | `task_failure` | You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks. | -A report is always filed under a category on the list. A missing category, a near-miss spelling such as `Invalid Tool Or Credential`, or a name that is not listed is resolved to the listed name it normalises to, else to the first listed category whose keywords appear in the category or detail (a missing token or a 401 is `invalid_tool_or_credential`, going in circles is `looping`), else to `task_failure`, or to the first category of a list without it. The detail is cut to 2,000 characters (Unicode code points, so an emoji or other character outside the Basic Multilingual Plane counts once and is never split). An agent that calls the tool without loading its schema sometimes guesses the argument names, so when `detail` is missing or empty the first non-empty of `summary`, `sentence`, `message`, `description`, `reason`, `text` and `details` is recorded instead, and when `category` is, `type` or `kind`. Other unknown arguments are ignored; a call is never rejected. +A report is always filed under a category on the list. A missing category, a near-miss spelling such as `Invalid Tool Or Credential`, or a name that is not listed is resolved to the listed name it normalises to, else to the first listed category whose keywords appear in the category or detail (a missing token or a 401 is `invalid_tool_or_credential`, going in circles is `looping`), else to `task_failure`, or to the first category of a list without it. The detail is cut to 2,000 characters (Unicode code points, so an emoji or other character outside the Basic Multilingual Plane counts once and is never split), and never in the middle of a word: when the cut lands inside one, that whole word goes, so a long token or key running past the cut is never kept in part, where redaction could no longer recognise it. A detail that is a single word longer than that reads `[detail cut]`. An agent that calls the tool without loading its schema sometimes guesses the argument names, so when `detail` is missing or empty the first non-empty of `summary`, `sentence`, `message`, `description`, `reason`, `text` and `details` is recorded instead, and when `category` is, `type` or `kind`. Other unknown arguments are ignored; a call is never rejected. ## Agent support diff --git a/sdk/python/CHANGELOG.md b/sdk/python/CHANGELOG.md index 28e5753b1..d1465e969 100644 --- a/sdk/python/CHANGELOG.md +++ b/sdk/python/CHANGELOG.md @@ -29,7 +29,10 @@ see `scripts/changelog-section.py`. open in several sessions is never resolved by the tool name instead, and with an explicit session the call id is taken only from the one open report call of that session and agent. `detail` is cut to 2000 code points with no lone - surrogate, as the daemon cuts it. `openai_responses_tool()` sets + surrogate, as the daemon cuts it, and never with part of a token left at the + end: a credential running past the cut is dropped whole, so upload redaction + still recognises what is kept (a detail that is one long token reads + `[detail cut]`). `openai_responses_tool()` sets `strict: True`. `uninstrument("pydantic_ai")` leaves runs of a hand-attached `FailproofAI()` to finish. The CrewAI tool is never cached and runs in the caller's context on CrewAI's async path. Still no runtime dependencies. diff --git a/sdk/python/failproofai_sdk/_events.py b/sdk/python/failproofai_sdk/_events.py index b947e1935..0dd939d2a 100644 --- a/sdk/python/failproofai_sdk/_events.py +++ b/sdk/python/failproofai_sdk/_events.py @@ -85,6 +85,42 @@ def clip_report_text(text: str, limit: "int | None" = SELF_REPORT_DETAIL_LIMIT) return text if limit is None else text[:limit] +#: What a detail cut down to nothing reads as (truncation.golden.json `detail_cut`). +DETAIL_CUT_MARKER = "[detail cut]" + +#: The whitespace the detail cut splits on: ASCII only, so every implementation +#: agrees (`str.isspace` is wider). +_CUT_WHITESPACE = frozenset(" \t\n\r\f\v") + + +def cut_report_detail(text: str, limit: int = SELF_REPORT_DETAIL_LIMIT) -> str: + """A report's detail cut to `limit` code points without leaving part of a token. + + A credential running past the cut (a long JWT or key) would otherwise be + kept as a fragment that no secret scrubber recognises, and be uploaded as + such. When the code point right after the cut is not whitespace, the + trailing run of non-whitespace is dropped; then trailing whitespace; an + empty result is `DETAIL_CUT_MARKER`. Text that fits is kept whole (with + lone surrogates replaced, as `clip_report_text` does). The CLI, the daemon + and the TypeScript SDK do the same; truncation.golden.json `detail_cut` + holds the cases. + """ + text = clip_report_text(text, None) + if len(text) <= limit: + return text + head = text[:limit] + if text[limit] not in _CUT_WHITESPACE: + end = len(head) + while end > 0 and head[end - 1] not in _CUT_WHITESPACE: + end -= 1 + head = head[:end] + end = len(head) + while end > 0 and head[end - 1] in _CUT_WHITESPACE: + end -= 1 + head = head[:end] + return head if head else DETAIL_CUT_MARKER + + #: The session a `self_report` is filed under when nothing else identifies one — #: the same value the MCP server fallback uses. UNATTRIBUTED_SESSION = "unattributed" @@ -962,7 +998,7 @@ def self_report( session_id=session_id, agent_id=agent_id, category=clip_report_text(category, None), - detail=clip_report_text(detail), + detail=cut_report_detail(detail), tool_call_id=tool_call_id, extra_fields=fields, ).to_dict() diff --git a/sdk/python/failproofai_sdk/_self_report.py b/sdk/python/failproofai_sdk/_self_report.py index f9d3aff9e..044ef50f6 100644 --- a/sdk/python/failproofai_sdk/_self_report.py +++ b/sdk/python/failproofai_sdk/_self_report.py @@ -33,7 +33,7 @@ from typing import Any from failproofai_sdk import _runtime -from failproofai_sdk._events import clip_report_text +from failproofai_sdk._events import clip_report_text, cut_report_detail from failproofai_sdk._resolver import failproofai_home logger = logging.getLogger(__name__) @@ -432,11 +432,11 @@ def parse_arguments(arguments: Any) -> tuple[str, str]: try: arguments = json.loads(text) except ValueError: - return "", clip_report_text(text) + return "", cut_report_detail(text) if arguments is None: arguments = {} if not isinstance(arguments, dict): - return "", clip_report_text(_coerce_text(arguments)) + return "", cut_report_detail(_coerce_text(arguments)) return _first_text(arguments, "category"), _first_text(arguments, "detail") diff --git a/sdk/python/tests/test_self_report.py b/sdk/python/tests/test_self_report.py index 5987fb81f..d6246980f 100644 --- a/sdk/python/tests/test_self_report.py +++ b/sdk/python/tests/test_self_report.py @@ -254,10 +254,13 @@ def test_written_to_the_spool_by_the_real_writer(tmp_path): def test_detail_is_truncated_and_none_becomes_empty(recorded): - fp.self_report("looping", "x" * 5000, session_id="s") + fp.self_report("looping", "x " * 2500, session_id="s") fp.self_report("looping", None, session_id="s") - assert len(recorded[0]["detail"]) == 2000 + fp.self_report("looping", "token " + "eyJ" + "a" * 3000, session_id="s") + # Cut at 2000 code points, never leaving part of a token at the end. + assert recorded[0]["detail"] == ("x " * 1000).rstrip() assert recorded[1]["detail"] == "" + assert recorded[2]["detail"] == "token" def test_unknown_category_is_recorded_as_is(recorded): diff --git a/sdk/python/tests/test_self_report_golden.py b/sdk/python/tests/test_self_report_golden.py index b0b52333e..14f2d424b 100644 --- a/sdk/python/tests/test_self_report_golden.py +++ b/sdk/python/tests/test_self_report_golden.py @@ -120,5 +120,25 @@ def test_truncation_counts_code_points_like_every_recorder(): pad = case["pad_char"] * case["pad"] text, want = pad + case["tail"], pad + case["expected_tail"] assert clip_report_text(text) == want, case + + +def test_detail_cut_never_leaves_part_of_a_token_like_every_recorder(): + """Round 3: a credential running past the cut was uploaded as a fragment.""" + from failproofai_sdk._events import DETAIL_CUT_MARKER, cut_report_detail + + fixture = json.loads(golden("truncation.golden.json")) + spec = fixture["detail_cut"] + assert spec["marker"] == DETAIL_CUT_MARKER + assert len(spec["cases"]) > 5 + + def join(parts): + return "".join(text * n for text, n in parts) + + for case in spec["cases"]: + text, want = join(case["input"]), join(case["expected"]) + assert cut_report_detail(text, fixture["max"]) == want, case["name"] # Arguments that are not JSON are kept whole as the detail, cut the same way. - assert _self_report.parse_arguments(text) == ("", want), case + assert _self_report.parse_arguments(text) == ("", want), case["name"] + for ws in spec["whitespace"]: + assert cut_report_detail("ok" + ws + "t" * 2100) == "ok", repr(ws) + assert cut_report_detail("ok\u00a0" + "t" * 2100) == DETAIL_CUT_MARKER diff --git a/sdk/typescript/CHANGELOG.md b/sdk/typescript/CHANGELOG.md index 3f4400516..3133940a5 100644 --- a/sdk/typescript/CHANGELOG.md +++ b/sdk/typescript/CHANGELOG.md @@ -25,7 +25,10 @@ section is missing or empty is refused before anything is built. several sessions is never resolved by the tool name instead; with an explicit `sessionId` the call id is taken only from the one open report call of that session and agent. `detail` is cut to 2000 code points (as the daemon and the - Python SDK count) with no lone surrogate. `openaiResponsesTool()` sets + Python SDK count) with no lone surrogate, and never with part + of a token left at the end: a credential running past the cut is dropped whole, + so upload redaction still recognises what is kept (a detail that is one long + token reads `[detail cut]`). `openaiResponsesTool()` sets `strict: true`, as openai's `FunctionTool` type requires. The `/langchain` tool also reads the call id from `configurable.tool_call_id`. The `/ai` tool carries both schema keys for a `module` passed in, and the Edge `/langchain` tool builds a diff --git a/sdk/typescript/src/self-report-spec.ts b/sdk/typescript/src/self-report-spec.ts index 6a82e43c6..7e69ae5c5 100644 --- a/sdk/typescript/src/self-report-spec.ts +++ b/sdk/typescript/src/self-report-spec.ts @@ -351,9 +351,31 @@ export function clipReportText(text: string, max: number = SELF_REPORT_DETAIL_LI return out; } -/** `detail` cut to `SELF_REPORT_DETAIL_LIMIT` code points, never through a surrogate pair. */ -export function clipDetail(detail: string): string { - return clipReportText(detail); +/** What a detail cut down to nothing reads as (truncation.golden.json `detail_cut`). */ +export const DETAIL_CUT_MARKER = "[detail cut]"; + +/** The whitespace the detail cut splits on: ASCII only, so every implementation agrees. */ +const CUT_WHITESPACE = new Set([" ", "\t", "\n", "\r", "\f", "\v"]); + +/** + * `detail` cut to `max` code points (never through a surrogate pair) without + * leaving part of a token at the end. A credential running past the cut (a + * long JWT or key) would otherwise be kept as a fragment that no secret + * scrubber recognises, and be uploaded as such. When the code point right + * after the cut is not whitespace, the trailing run of non-whitespace is + * dropped; then trailing whitespace; an empty result is `DETAIL_CUT_MARKER`. + * The CLI, the daemon and the Python SDK do the same; + * `test-fixtures/self-report/truncation.golden.json` `detail_cut` holds the cases. + */ +export function clipDetail(detail: string, max: number = SELF_REPORT_DETAIL_LIMIT): string { + const points = [...clipReportText(detail, Infinity)]; + if (points.length <= max) return points.join(""); + const head = points.slice(0, max); + if (!CUT_WHITESPACE.has(points[max]!)) { + while (head.length > 0 && !CUT_WHITESPACE.has(head[head.length - 1]!)) head.pop(); + } + while (head.length > 0 && CUT_WHITESPACE.has(head[head.length - 1]!)) head.pop(); + return head.length > 0 ? head.join("") : DETAIL_CUT_MARKER; } /** diff --git a/sdk/typescript/test/self-report.test.ts b/sdk/typescript/test/self-report.test.ts index 2f393c894..dc2bca4bf 100644 --- a/sdk/typescript/test/self-report.test.ts +++ b/sdk/typescript/test/self-report.test.ts @@ -20,7 +20,7 @@ import { setLogger } from "../src/logger.js"; import { runtime } from "../src/runtime.js"; import * as schema from "../src/schema.js"; import { agent, session, toolCall } from "../src/scopes.js"; -import { DEFAULT_SELF_REPORT_CATEGORIES, clipDetail } from "../src/self-report-spec.js"; +import { DEFAULT_SELF_REPORT_CATEGORIES, DETAIL_CUT_MARKER, clipDetail, clipReportText } from "../src/self-report-spec.js"; import { flushed, useSpool } from "./helpers.js"; import type { Spool } from "./helpers.js"; @@ -154,12 +154,13 @@ describe("event.selfReport and selfReport()", () => { it("records an unknown category as-is, a missing detail as empty, and cuts detail at 2000", async () => { await session({ sessionId: "s1" }, () => { failproofai.selfReport("not_a_category"); - failproofai.event.selfReport("looping", "x".repeat(2500)); + failproofai.event.selfReport("looping", "x ".repeat(1250)); failproofai.selfReport("looping", `${"y".repeat(1999)}😀`); }); const [unknown, long, surrogate] = await reports(); expect(unknown).toMatchObject({ category: "not_a_category", detail: "" }); - expect((long!.detail as string).length).toBe(2000); + // Cut at 2000 code points, never leaving part of a token (the trailing space goes too). + expect(long!.detail).toBe("x ".repeat(1000).trimEnd()); // 2000 code points, as the daemon and the Python SDK count: the emoji is the 2000th. expect(surrogate!.detail).toBe(`${"y".repeat(1999)}😀`); }); @@ -174,13 +175,36 @@ describe("event.selfReport and selfReport()", () => { failproofai.selfReport("lo\ud83dping", "x\ud83d"); }); const recorded = await reports(); - fixture.cases.forEach((c, i) => { - expect(recorded[i]!.detail, JSON.stringify(c.tail)).toBe(c.pad_char.repeat(c.pad) + c.expected_tail); - expect(clipDetail(c.pad_char.repeat(c.pad) + c.tail)).toBe(c.pad_char.repeat(c.pad) + c.expected_tail); + // The plain code-point cut (categories, any text) follows `cases`; a + // report's detail follows `detail_cut` (below). + fixture.cases.forEach((c) => { + expect(clipReportText(c.pad_char.repeat(c.pad) + c.tail, fixture.max)).toBe(c.pad_char.repeat(c.pad) + c.expected_tail); }); expect(recorded.at(-1)).toMatchObject({ category: "lo\ufffdping", detail: "x\ufffd" }); }); + // Round 3: a credential running past the 2000 cut was uploaded as a fragment + // no scrubber recognised. Every implementation cuts the same way. + it("cuts a detail without leaving part of a token, as the shared detail_cut cases say", async () => { + const fixture = JSON.parse(readFileSync(join(__dirname, "..", "..", "..", "test-fixtures", "self-report", "truncation.golden.json"), "utf8")) as { + max: number; + detail_cut: { marker: string; whitespace: string; cases: { name: string; input: [string, number][]; expected: [string, number][] }[] }; + }; + const joinParts = (parts: [string, number][]) => parts.map(([t, n]) => t.repeat(n)).join(""); + expect(DETAIL_CUT_MARKER).toBe(fixture.detail_cut.marker); + expect(fixture.detail_cut.cases.length).toBeGreaterThan(5); + await session({ sessionId: "cut" }, () => { + for (const c of fixture.detail_cut.cases) failproofai.selfReport("looping", joinParts(c.input)); + }); + const recorded = await reports(); + fixture.detail_cut.cases.forEach((c, i) => { + expect(clipDetail(joinParts(c.input), fixture.max), c.name).toBe(joinParts(c.expected)); + expect(recorded[i]!.detail, c.name).toBe(joinParts(c.expected)); + }); + for (const ws of fixture.detail_cut.whitespace) expect(clipDetail(`ok${ws}${"t".repeat(2100)}`), JSON.stringify(ws)).toBe("ok"); + expect(clipDetail(`ok\u00a0${"t".repeat(2100)}`)).toBe(DETAIL_CUT_MARKER); + }); + it("takes an explicit session, agent, tool call id and custom fields", async () => { failproofai.selfReport("task_failure", "d", { sessionId: "s9", agentId: "worker", toolCallId: "c1", fw_note: "n" }); expect((await reports())[0]).toMatchObject({ diff --git a/src/hooks/hook-activity-store.ts b/src/hooks/hook-activity-store.ts index 7ebd77c8c..c3df1608f 100644 --- a/src/hooks/hook-activity-store.ts +++ b/src/hooks/hook-activity-store.ts @@ -25,7 +25,7 @@ import { join } from "node:path"; import type { IntegrationType } from "./types"; import { hookActivityDir } from "./fp-home"; import { sanitizeJevActivity, type JevCheckRecord } from "./jev-activity"; -import { selfReportClip } from "./self-report-names"; +import { selfReportClip, selfReportCutDetail } from "./self-report-names"; import { selfReportAgentPidOf } from "./self-report-ancestry"; export const PAGE_SIZE = 25; @@ -313,7 +313,7 @@ function sanitizeSelfReportActivity(entry: HookActivityEntry): HookActivityEntry const rec = sr as Record; out.selfReport = { category: typeof rec.category === "string" ? selfReportClip(rec.category) : "", - detail: typeof rec.detail === "string" ? selfReportClip(rec.detail) : "", + detail: typeof rec.detail === "string" ? selfReportCutDetail(rec.detail) : "", source: "mcp", }; return out; diff --git a/src/hooks/self-report-hook-trust.ts b/src/hooks/self-report-hook-trust.ts index 1370c029f..7ba635191 100644 --- a/src/hooks/self-report-hook-trust.ts +++ b/src/hooks/self-report-hook-trust.ts @@ -38,7 +38,7 @@ import { import { claudeConfigDir, getIntegration } from "./integrations"; import { getHookActivityEntriesSince } from "./hook-activity-store"; import { readEnabledSelfReport, resolveSelfReportCategory, selfReportArgs } from "./self-report"; -import { selfReportClip } from "./self-report-names"; +import { selfReportClip, selfReportCutDetail } from "./self-report-names"; import { selfReportRowAgentPid, selfReportServerAgentPid } from "./self-report-ancestry"; import { failproofaiHome } from "./fp-home"; @@ -230,7 +230,7 @@ export function selfReportHookRecordedRecently( ): boolean { if (!cwd || agentPid === undefined || !Number.isSafeInteger(agentPid) || agentPid <= 1) return false; const { category, detail } = selfReportArgs(args ?? {}); - const want = { category: selfReportClip(category), detail: selfReportClip(detail) }; + const want = { category: selfReportClip(category), detail: selfReportCutDetail(detail) }; // The hook row holds the category as it was resolved against the list // (resolveSelfReportCategory), so a call whose category was missing or // misspelt matches it by that name; the name as sent still matches too. diff --git a/src/hooks/self-report-log.ts b/src/hooks/self-report-log.ts index 1d2cd2e3f..4dd4d29fe 100644 --- a/src/hooks/self-report-log.ts +++ b/src/hooks/self-report-log.ts @@ -22,7 +22,7 @@ import { existsSync } from "node:fs"; import { createConnection } from "node:net"; import { daemonSocket } from "./fp-home"; -import { SELF_REPORT_DETAIL_MAX, selfReportClip } from "./self-report-names"; +import { SELF_REPORT_DETAIL_MAX, selfReportClip, selfReportCutDetail } from "./self-report-names"; /** The whole budget for one event, connect to close. */ @@ -103,7 +103,9 @@ function selfReportLogSend(event: SelfReportLogEvent): Promise { protocolVersion: SELF_REPORT_LOG_PROTOCOL_VERSION, event: { ...event, - ...(event.preview !== undefined ? { preview: selfReportClip(event.preview, SELF_REPORT_LOG_PREVIEW_CHARS) } : {}), + // Bounded without leaving part of a token at the cut (F18): a + // fragment is what the daemon's scrubber cannot recognise. + ...(event.preview !== undefined ? { preview: selfReportCutDetail(event.preview, SELF_REPORT_LOG_PREVIEW_CHARS) } : {}), ...(event.rawCategory !== undefined ? { rawCategory: selfReportClip(event.rawCategory, SELF_REPORT_LOG_RAW_CATEGORY_CHARS) } : {}), }, }), diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts index c961bd901..a4429f27a 100644 --- a/src/hooks/self-report-mcp.ts +++ b/src/hooks/self-report-mcp.ts @@ -40,6 +40,7 @@ import { resolveSelfReportCategory, selfReportArgs, selfReportClip, + selfReportCutDetail, selfReportInputSchema, selfReportInstructions, selfReportSettingsState, @@ -295,7 +296,7 @@ export async function writeSelfReportEvent(input: SelfReportEventInput): Promise agent_id: selfReportAgentId(input.integration, match?.cwd ?? input.cwd), type: "self_report", category: selfReportClip(input.category), - detail: selfReportClip(input.detail), + detail: selfReportCutDetail(input.detail), source: "mcp", // Wire order as the SDK writers build it: environment after the event's own fields. environment: await selfReportEnvironment(), diff --git a/src/hooks/self-report-names.ts b/src/hooks/self-report-names.ts index eb5beaa78..9a80c5ab9 100644 --- a/src/hooks/self-report-names.ts +++ b/src/hooks/self-report-names.ts @@ -69,6 +69,35 @@ export function selfReportLogCategoryText(raw: string): string { return `(${n} characters, not shown)`; } +/** What a detail cut down to nothing reads as (test-fixtures/self-report/truncation.golden.json `detail_cut`). */ +export const SELF_REPORT_DETAIL_CUT_MARKER = "[detail cut]"; + +/** The whitespace the detail cut splits on: ASCII only, so every implementation agrees. */ +const SELF_REPORT_CUT_WHITESPACE = new Set([" ", "\t", "\n", "\r", "\f", "\v"]); + +/** + * A report's detail cut to `max` code points without leaving part of a token + * at the end. A credential that runs past the cut (a JWT, a long key) would + * otherwise be kept as a fragment that no secret scrubber recognises any more, + * and be uploaded and logged as such (review round 3). So when the cut lands + * inside a run of non-whitespace, that whole trailing run is dropped; trailing + * whitespace goes too; and if nothing is left the detail is + * `SELF_REPORT_DETAIL_CUT_MARKER`. Text that fits is returned whole (with + * lone surrogates replaced, as `selfReportClip` does). The same rule runs in + * the daemon (`cut_detail`) and both SDKs; truncation.golden.json `detail_cut` + * holds the cases. + */ +export function selfReportCutDetail(text: string, max: number = SELF_REPORT_DETAIL_MAX): string { + const points = [...selfReportClip(text, Number.MAX_SAFE_INTEGER)]; + if (points.length <= max) return points.join(""); + const head = points.slice(0, max); + if (!SELF_REPORT_CUT_WHITESPACE.has(points[max])) { + while (head.length > 0 && !SELF_REPORT_CUT_WHITESPACE.has(head[head.length - 1])) head.pop(); + } + while (head.length > 0 && SELF_REPORT_CUT_WHITESPACE.has(head[head.length - 1])) head.pop(); + return head.length > 0 ? head.join("") : SELF_REPORT_DETAIL_CUT_MARKER; +} + /** * Every spelling of the report tool an agent's hook can deliver. Exact matches * only: a prefix or substring match would let any tool whose name merely diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts index 212c1c043..6a9a3eef7 100644 --- a/src/hooks/self-report.ts +++ b/src/hooks/self-report.ts @@ -36,8 +36,10 @@ export { isSelfReportCursorCall, selfReportAntigravityWrappedArgs, selfReportClip, + selfReportCutDetail, + SELF_REPORT_DETAIL_CUT_MARKER, } from "./self-report-names"; -import { SELF_REPORT_DEFAULT_PORT, SELF_REPORT_DETAIL_MAX, selfReportClip } from "./self-report-names"; +import { SELF_REPORT_DEFAULT_PORT, SELF_REPORT_DETAIL_MAX, selfReportClip, selfReportCutDetail } from "./self-report-names"; // ── Categories (contract §2) ──────────────────────────────────────────────── @@ -227,7 +229,7 @@ export function selfReportArgs(input: unknown, max: number = SELF_REPORT_DETAIL_ const detail = selfReportArg(rec, "detail", SELF_REPORT_ARG_ALIASES.detail); return { category: selfReportClip(category, max), - detail: selfReportClip(detail, max), + detail: selfReportCutDetail(detail, max), }; } diff --git a/test-fixtures/self-report/truncation.golden.json b/test-fixtures/self-report/truncation.golden.json index 25d0bec66..fde34a014 100644 --- a/test-fixtures/self-report/truncation.golden.json +++ b/test-fixtures/self-report/truncation.golden.json @@ -1,5 +1,5 @@ { - "comment": "How detail is cut to 2000 characters, counted in Unicode code points (never UTF-16 units, never through a surrogate pair). input = pad_char repeated pad times + tail; the recorded value = the same pad + expected_tail. Every implementation (CLI, daemon, both SDKs) is tested against these cases.", + "comment": "How text is cut to 2000 characters, counted in Unicode code points (never UTF-16 units, never through a surrogate pair). input = pad_char repeated pad times + tail; the recorded value = the same pad + expected_tail. Every implementation (CLI, daemon, both SDKs) tests its plain code-point cut against `cases`.", "max": 2000, "cases": [ {"pad_char": "a", "pad": 1999, "tail": "😀 and more text", "expected_tail": "😀"}, @@ -9,5 +9,21 @@ {"pad_char": "😀", "pad": 2000, "tail": "x", "expected_tail": ""}, {"pad_char": "😀", "pad": 1999, "tail": "中文", "expected_tail": "中"}, {"pad_char": "a", "pad": 0, "tail": "short 😀", "expected_tail": "short 😀"} - ] + ], + "detail_cut": { + "comment": "A report's DETAIL is cut to `max` code points without leaving part of a token at the end: a credential running past the cut would be kept as a fragment no secret scrubber recognises. If the code point right after the cut is not whitespace, the trailing run of non-whitespace is dropped; then trailing whitespace is dropped; an empty result is `marker`. Whitespace is exactly the characters in `whitespace`. Text that fits is kept whole. input and expected are lists of [text, repeat] joined in order. Every implementation's detail path (CLI hook and stdio, daemon HTTP, both SDKs) is tested against these.", + "marker": "[detail cut]", + "whitespace": " \t\n\r\f\u000b", + "cases": [ + {"name": "fits", "input": [["short 😀", 1]], "expected": [["short 😀", 1]]}, + {"name": "exactly max, one run", "input": [["a", 2000]], "expected": [["a", 2000]]}, + {"name": "cut lands before a space", "input": [["a", 2000], [" more", 1]], "expected": [["a", 2000]]}, + {"name": "a JWT straddling the cut", "input": [["token ", 1], ["eyJhbGciOiJIUzI1NiJ9.eyJ", 1], ["a", 2500], [".sig rejected", 1]], "expected": [["token", 1]]}, + {"name": "one token longer than max", "input": [["eyJhbGciOiJIUzI1NiJ9.eyJ", 1], ["a", 3000], [".sig", 1]], "expected": [["[detail cut]", 1]]}, + {"name": "cut lands just after a space", "input": [["a", 1999], [" ", 1], ["b", 10]], "expected": [["a", 1999]]}, + {"name": "an emoji run past the cut", "input": [["x ", 1], ["😀", 2100]], "expected": [["x", 1]]}, + {"name": "a newline before the token", "input": [["line one\n", 1], ["k", 2500]], "expected": [["line one", 1]]}, + {"name": "trailing whitespace before the cut", "input": [["a b", 1], [" ", 1997], ["c", 5]], "expected": [["a b", 1]]} + ] + } }