From 725494d660748cfda28f068166805703a2b92971 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 12:50:00 +0530 Subject: [PATCH 01/41] fix(daemon): answer the previous plugin protocol instead of denying A Hermes or OpenClaw gateway keeps the plugin it imported at start. After an upgrade across the v1 -> v2 protocol bump, the gateway still spoke v1, the new daemon refused it, and the plugin's fail-closed path blocked every Slack/Telegram tool call until someone restarted the gateway. The Hermes CLI worked because it is a fresh process that loads the new files. - The daemon accepts MIN_PROTOCOL_VERSION..=PROTOCOL_VERSION (1..=2) and stamps the reply with the client's version, so an old plugin's own equality check accepts it. v1 and v2 messages differ only by the optional agentSettingsPath, so nothing is inferred. - A request is read without fields its version predates: a v1 request's agentSettingsPath is dropped and its profile is unknown, never trusted. - The CLI hook client, the Hermes plugin and the OpenClaw plugin re-ask an older daemon once in its version, without the newer fields. The answer to the original request is never used. No CLI output changes. Verified with the real v1.0.11 Hermes client.py against a daemon built from this branch: sudo denied by block-sudo, ls allowed. --- CHANGELOG.md | 6 + CLAUDE.md | 16 ++- .../fixtures/hermes-native-plugin-check.py | 50 ++++++- __tests__/hooks/daemon-client.test.ts | 50 ++++--- __tests__/hooks/openclaw-plugin.test.ts | 36 ++++- crates/PROTOCOL.md | 21 ++- crates/failproofaid/src/server.rs | 123 ++++++++++++++++-- crates/fpai-ipc/src/envelope.rs | 85 +++++++++++- crates/fpai-ipc/src/lib.rs | 5 +- hermes-plugin/client.py | 96 ++++++++------ openclaw-plugin/daemon-client.js | 48 ++++--- src/hooks/daemon-client.ts | 64 ++++++--- 12 files changed, 487 insertions(+), 113 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01c3166f7..53a8e17dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 1.0.16-beta.0 — 2026-11-18 + +### Fixes + +- The daemon answers the previous plugin protocol, and clients re-ask an older daemon in its version, so a Hermes or OpenClaw gateway still running the plugin it loaded before an upgrade keeps getting real verdicts instead of denying every call (#PR) + ## 1.0.15 — 2026-11-18 The stable release of the OpenClaw plugin fix for tool calls blocked as "failproofaid could not be reached" while the daemon was healthy, plus the refreshed README and docs and the dependency updates that landed on `main` since 1.0.14. diff --git a/CLAUDE.md b/CLAUDE.md index 47c86dab1..0ec4bbc9f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -909,13 +909,15 @@ in-process fallback on that path: a second policy engine reachable by breaking t is not a guarantee, and a machine where stopping one service silently disables every guardrail is not a guarded machine. -The mismatch case denies with a message naming the version and `failproofai update`, -because the remedy differs from "the daemon is down" and that difference is the whole -value of telling them apart. The accepted cost: both sides hardcode `PROTOCOL_VERSION`, -so the first time it is bumped a machine whose CLI updated via npm before its daemon did -denies until `failproofai update` runs. `publish.yml` ships both from one commit and -`daemonVersionSkew()` hints on every CLI command, so the window is bounded and announces -itself. +A version mismatch outside the supported range denies with a message naming the version +and `failproofai update`, because the remedy differs from "the daemon is down". Inside the +range it does not deny: the daemon answers every version from `MIN_PROTOCOL_VERSION` to +`PROTOCOL_VERSION` in the client's own version, and a client facing an older daemon asks +again in the daemon's version (crates/PROTOCOL.md). This was strict until 1.0.15: a Hermes +gateway still holding the v1 plugin it loaded before an upgrade was refused by the v2 +daemon, and every Slack/Telegram tool call denied until the gateway was restarted. A +request older than a field is read without it — a v1 request is evaluated with its profile +unknown — so compatibility never widens what a scoped deployment applies to. **In-process evaluation still exists**, reachable only when `daemonConfigured` is false — which means the machine is not yet set up. No hooks are installed then either, so diff --git a/__tests__/fixtures/hermes-native-plugin-check.py b/__tests__/fixtures/hermes-native-plugin-check.py index 51e852b41..ce4ae13e2 100644 --- a/__tests__/fixtures/hermes-native-plugin-check.py +++ b/__tests__/fixtures/hermes-native-plugin-check.py @@ -1631,7 +1631,10 @@ def server() -> None: thread.start() self.assertTrue(ready.wait(timeout=2)) with patch.dict("os.environ", {"FAILPROOFAI_DAEMON_SOCKET": str(socket_path)}): - with self.assertRaisesRegex(client.EvaluationError, "version mismatch"): + # The v1 allow answers a v2 request it may have read without + # agentSettingsPath, so it is never taken as the verdict: the + # client re-asks in v1, which this one-shot server never answers. + with self.assertRaises(client.EvaluationError): client.evaluate_policy(event="pre_tool_call", payload={}, cwd="/tmp") thread.join(timeout=2) @@ -1698,5 +1701,50 @@ def server() -> None: thread.join(timeout=2) + +class ProtocolCompatibilityTests(unittest.TestCase): + """Files on disk can be newer than the daemon still running. An older daemon + inside the supported range is asked again in its own version, not refused.""" + + def _evaluate(self, responses: list[dict[str, object]]) -> tuple[object, list]: + with tempfile.TemporaryDirectory() as tmp: + socket_path = Path(tmp) / "d.sock" + received: list = [] + thread = serve_verdicts(socket_path, responses, received) + with patch.dict("os.environ", {"FAILPROOFAI_DAEMON_SOCKET": str(socket_path)}): + try: + result: object = client.evaluate_policy( + event="pre_tool_call", + payload={}, + cwd="/tmp", + agent_settings_path="/home/a/.hermes/config.yaml", + evaluation_timeout_ms=2_000, + ) + except client.EvaluationError as exc: + result = exc + thread.join(timeout=2) + return result, received + + def test_an_older_daemon_is_asked_again_in_its_version(self) -> None: + result, received = self._evaluate([ + {"type": "error", "protocolVersion": 1, "message": "protocol version mismatch"}, + {"protocolVersion": 1, "decision": "deny", "policyNames": ["p"], "reason": "no", + "matchedPolicies": ["p"], "durationMs": 1, "toolName": "Bash"}, + ]) + self.assertIsInstance(result, client.PolicyVerdict) + self.assertEqual(result.decision, "deny") + self.assertEqual([r["protocolVersion"] for r in received], [2, 1]) + self.assertIn("agentSettingsPath", received[0]) + # The answer accepted is the one to a request that never claimed a profile. + self.assertNotIn("agentSettingsPath", received[1]) + + def test_no_retry_below_the_oldest_supported_version(self) -> None: + result, received = self._evaluate([ + {"type": "error", "protocolVersion": 0, "message": "protocol version mismatch"}, + ]) + self.assertIsInstance(result, client.EvaluationError) + self.assertIn("protocol version mismatch", str(result)) + self.assertEqual(len(received), 1) + if __name__ == "__main__": unittest.main() diff --git a/__tests__/hooks/daemon-client.test.ts b/__tests__/hooks/daemon-client.test.ts index 4077f4b29..8c02653b0 100644 --- a/__tests__/hooks/daemon-client.test.ts +++ b/__tests__/hooks/daemon-client.test.ts @@ -227,28 +227,30 @@ describe("hooks/daemon-client", () => { expect(attempt).toEqual({ ok: false, failure: "protocol-mismatch" }); }); - it("catches a mismatch when an old daemon responds to a new client", async () => { - // Newer CLI against older daemon, and older CLI against newer daemon, both - // land here: the daemon stamps its own version on the error it sends back, - // so the versions disagree either way. + it("re-asks an older daemon in its own version instead of denying", async () => { + // npm replaced the CLI before the daemon was replaced. The older daemon + // refuses v2; the client asks again in v1 rather than deny every call. + const requests: Record[] = []; await startServer(async (socket) => { - await readFrame(socket); - socket.end(encodeFrame({ type: "error", protocolVersion: 1, message: "protocol version mismatch" })); + const request = (await readFrame(socket)) as Record; + requests.push(request); + socket.end(encodeFrame( + request.protocolVersion === 1 + ? { type: "hookResult", protocolVersion: 1, exitCode: 0, stdout: "ok", stderr: "" } + : { type: "error", protocolVersion: 1, message: "protocol version mismatch" }, + )); }); const { attemptDaemonHook } = await import("../../src/hooks/daemon-client"); const attempt = await attemptDaemonHook({ hookEvent: "PreToolUse", cli: "claude", stdin: "{}" }); - expect(attempt).toEqual({ ok: false, failure: "protocol-mismatch" }); + expect(attempt).toEqual({ ok: true, response: { exitCode: 0, stdout: "ok", stderr: "" } }); + expect(requests.map((r) => r.protocolVersion)).toEqual([2, 1]); }); - it("rejects an allow from a v1 daemon that ignored the profile-scoping field", async () => { + it("never accepts a v1 answer to a scoped v2 request; it re-asks unscoped", async () => { + const requests: Record[] = []; await startServer(async (socket) => { - const request = await readFrame(socket); - expect(request).toMatchObject({ - type: "hook", - protocolVersion: 2, - agentSettingsPath: "/home/agent/claude/settings.json", - }); + requests.push((await readFrame(socket)) as Record); // A v1 daemon ignores unknown JSON fields. Its allow is not proof that // it identified this profile or applied schema-3 targets. socket.end(encodeFrame({ @@ -261,7 +263,25 @@ describe("hooks/daemon-client", () => { cli: "claude", stdin: "{}", agentSettingsPath: "/home/agent/claude/settings.json", - })).resolves.toEqual({ ok: false, failure: "protocol-mismatch" }); + })).resolves.toMatchObject({ ok: true }); + expect(requests[0]).toMatchObject({ protocolVersion: 2, agentSettingsPath: "/home/agent/claude/settings.json" }); + // The answer accepted is the one to a request that never claimed a profile. + expect(requests[1].protocolVersion).toBe(1); + expect(requests[1]).not.toHaveProperty("agentSettingsPath"); + expect(requests).toHaveLength(2); + }); + + it("does not retry below the oldest supported version", async () => { + let connections = 0; + await startServer(async (socket) => { + connections++; + await readFrame(socket); + socket.end(encodeFrame({ type: "error", protocolVersion: 0, message: "protocol version mismatch" })); + }); + const { attemptDaemonHook } = await import("../../src/hooks/daemon-client"); + const attempt = await attemptDaemonHook({ hookEvent: "PreToolUse", cli: "claude", stdin: "{}" }); + expect(attempt).toEqual({ ok: false, failure: "protocol-mismatch" }); + expect(connections).toBe(1); }); it("an error at a MATCHING protocol version is unreachable, not skew", async () => { diff --git a/__tests__/hooks/openclaw-plugin.test.ts b/__tests__/hooks/openclaw-plugin.test.ts index 90a5ed025..12ca6c549 100644 --- a/__tests__/hooks/openclaw-plugin.test.ts +++ b/__tests__/hooks/openclaw-plugin.test.ts @@ -222,7 +222,7 @@ describe("openclaw-plugin daemon-client: requestHookVerdict", () => { it.each([ ["an error frame", { type: "error", protocolVersion: 2, message: "worker is down" }, "evaluation"], - ["another protocol version", { type: "hookResult", protocolVersion: 1, exitCode: 0, stdout: "" }, "protocol-mismatch"], + ["a newer protocol version", { type: "hookResult", protocolVersion: 999, exitCode: 0, stdout: "", stderr: "" }, "protocol-mismatch"], ["an unknown message type", { type: "pong", protocolVersion: 2 }, "invalid"], ["a non-zero exit", hookResult("", 1), "evaluation"], ["stdout that is not JSON", hookResult("not json"), "invalid"], @@ -246,6 +246,40 @@ describe("openclaw-plugin daemon-client: requestHookVerdict", () => { } }); + it("re-asks an older daemon in its own version, without agentSettingsPath", async () => { + const daemon = await fakeDaemon(socketPath, (request) => + request.protocolVersion === 1 + ? { ...hookResult(JSON.stringify({ permission: "deny", reason: "no" })), protocolVersion: 1 } + : { type: "error", protocolVersion: 1, message: "protocol version mismatch" }, + ); + try { + const result = await requestHookVerdict({ + event: "before_tool_call", + payload: {}, + socketPath, + agentSettingsPath: "/home/a/.openclaw/openclaw.json", + }); + expect(result).toEqual({ ok: true, verdict: { permission: "deny", reason: "no" } }); + expect(daemon.requests.map((r) => r.protocolVersion)).toEqual([2, 1]); + expect(daemon.requests[0]).toHaveProperty("agentSettingsPath"); + expect(daemon.requests[1]).not.toHaveProperty("agentSettingsPath"); + } finally { + await daemon.close(); + } + }); + + it("does not retry below the oldest supported version", async () => { + const daemon = await fakeDaemon(socketPath, () => ({ type: "error", protocolVersion: 0, message: "x" })); + try { + const result = await requestHookVerdict({ event: "before_tool_call", payload: {}, socketPath }); + expect(result).toMatchObject({ ok: false, failure: "protocol-mismatch" }); + expect(result).not.toHaveProperty("daemonVersion"); + expect(daemon.requests).toHaveLength(1); + } finally { + await daemon.close(); + } + }); + it("refuses a declared response length over 16 MiB", async () => { const header = Buffer.alloc(4); header.writeUInt32BE(16 * 1024 * 1024 + 1, 0); diff --git a/crates/PROTOCOL.md b/crates/PROTOCOL.md index 6ac9fedbf..d9ad9d8e0 100644 --- a/crates/PROTOCOL.md +++ b/crates/PROTOCOL.md @@ -102,11 +102,22 @@ operator to reinstall/restart the daemon before evaluation resumes. ## Protocol versioning -`protocolVersion` is carried on every message in both directions. A mismatch -gets an explicit `error` response from the daemon. A daemon-configured client -fails closed on every missing or unusable verdict; it preserves the mismatch -category only to print the correct repair instructions. There is no protocol -negotiation: the CLI and daemon must agree exactly. +`protocolVersion` is carried on every message in both directions. The daemon +answers every version from `MIN_PROTOCOL_VERSION` (1) to `PROTOCOL_VERSION` (2) +and stamps its reply with the version the client sent. A request older than the +field it carries is read without it: a v1 request's `agentSettingsPath` is +dropped, so its profile is unknown, never trusted. + +A client that gets a reply stamped with an older version still inside that range +asks once more in that version, without the fields that version predates. The +answer to the original request is never used. Anything outside the range gets an +explicit `error`, and a daemon-configured client fails closed on it. + +This exists because a long-lived host (a Hermes or OpenClaw gateway) keeps the +plugin it loaded at start: after an upgrade it speaks the previous version until +it restarts, and refusing it denied every call it made. Versions only add +optional fields; raise `MIN_PROTOCOL_VERSION` only when an older request can no +longer be answered safely. ## Peer verification diff --git a/crates/failproofaid/src/server.rs b/crates/failproofaid/src/server.rs index 2224f44f5..c72c8553f 100644 --- a/crates/failproofaid/src/server.rs +++ b/crates/failproofaid/src/server.rs @@ -7,7 +7,10 @@ //! connection-handling thread. use crate::worker::Worker; -use fpai_ipc::{ClientMessage, PROTOCOL_VERSION, ServerMessage, peer, read_message, write_message}; +use fpai_ipc::{ + ClientMessage, MIN_PROTOCOL_VERSION, PROTOCOL_VERSION, ServerMessage, + is_supported_protocol_version, peer, read_message, write_message, +}; use std::fs; use std::io; use std::os::unix::fs::PermissionsExt; @@ -332,16 +335,19 @@ fn worker_agent_settings_path(settings_path: Option<&str>) -> Option<&str> { } fn dispatch(request: ClientMessage, worker: &Worker) -> ServerMessage { - if request.protocol_version() != PROTOCOL_VERSION { + let version = request.protocol_version(); + if !is_supported_protocol_version(version) { return ServerMessage::Error { protocol_version: PROTOCOL_VERSION, message: format!( - "protocol version mismatch: daemon speaks {PROTOCOL_VERSION}, client sent {}", - request.protocol_version() + "protocol version mismatch: daemon speaks {MIN_PROTOCOL_VERSION}-{PROTOCOL_VERSION}, client sent {version}" ), }; } + evaluate(request.without_fields_newer_than_its_version(), worker).with_protocol_version(version) +} +fn evaluate(request: ClientMessage, worker: &Worker) -> ServerMessage { match request { ClientMessage::Ping { .. } => ServerMessage::Pong { protocol_version: PROTOCOL_VERSION, @@ -739,6 +745,48 @@ mod tests { other => panic!("expected PolicyResult, got {other:?}"), } + // The request a Hermes plugin loaded before 1.0.12 sends: v1, no + // agentSettingsPath. It gets the real verdict, stamped v1 so that + // plugin's own version check accepts it. + let mut stream = UnixStream::connect(&socket_path).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(15))) + .unwrap(); + write_message( + &mut stream, + &ClientMessage::PolicyEvaluation { + protocol_version: 1, + integration: "hermes".to_string(), + event: "pre_tool_call".to_string(), + payload: serde_json::json!({ + "cwd": project_dir.to_string_lossy(), + "tool_name": "terminal", + "tool_input": { "command": "sudo rm -rf /" } + }), + cwd: Some(project_dir.to_string_lossy().to_string()), + agent_settings_path: None, + }, + ) + .unwrap(); + let response: ServerMessage = read_message(&mut stream).unwrap(); + match response { + ServerMessage::PolicyResult { + protocol_version, + decision, + policy_names, + .. + } => { + assert_eq!(protocol_version, 1); + assert_eq!(decision, "deny"); + assert!( + policy_names + .iter() + .any(|name| name.ends_with("/block-sudo")) + ); + } + other => panic!("expected a v1 PolicyResult, got {other:?}"), + } + std::fs::remove_dir_all(&project_dir).ok(); } @@ -775,10 +823,29 @@ mod tests { } #[test] - fn old_hook_protocol_cannot_evaluate_a_scoped_agent() { - let socket_path = temp_socket_path("old-scoped-hook"); + fn previous_protocol_is_answered_in_its_own_version() { + // A gateway that loaded the previous plugin before an upgrade keeps + // speaking v1 until it restarts. It must get an answer it accepts, + // not a mismatch that its fail-closed path turns into a deny. + let socket_path = temp_socket_path("old-protocol"); let _guard = start_test_server(socket_path.clone()); + let mut stream = UnixStream::connect(&socket_path).unwrap(); + write_message( + &mut stream, + &ClientMessage::Ping { + protocol_version: 1, + }, + ) + .unwrap(); + let response: ServerMessage = read_message(&mut stream).unwrap(); + assert_eq!( + response, + ServerMessage::Pong { + protocol_version: 1 + } + ); + let mut stream = UnixStream::connect(&socket_path).unwrap(); write_message( &mut stream, @@ -788,21 +855,57 @@ mod tests { cli: "claude".into(), stdin: "{}".into(), cwd: None, - agent_settings_path: Some("/home/agent/claude/settings.json".into()), + agent_settings_path: None, }, ) .unwrap(); let response: ServerMessage = read_message(&mut stream).unwrap(); + // The broken test worker cannot evaluate; what matters is that the + // request reached it instead of stopping at the version gate. match response { ServerMessage::Error { protocol_version, message, } => { - assert_eq!(protocol_version, PROTOCOL_VERSION); - assert!(message.contains("protocol version mismatch")); + assert_eq!(protocol_version, 1); + assert!(!message.contains("protocol version mismatch"), "{message}"); } - other => panic!("old protocol was evaluated: {other:?}"), + other => panic!("expected the worker's error, got {other:?}"), + } + } + + #[test] + fn old_protocol_never_evaluates_a_scoped_agent() { + // v1 predates agentSettingsPath. A v1 request carrying one is not a + // real v1 client, and must be evaluated as profile-unknown, never for + // the profile it names. + let scoped = |protocol_version| ClientMessage::PolicyEvaluation { + protocol_version, + integration: "hermes".into(), + event: "pre_tool_call".into(), + payload: serde_json::json!({}), + cwd: None, + agent_settings_path: Some("/home/agent/.hermes/config.yaml".into()), + }; + match scoped(1).without_fields_newer_than_its_version() { + ClientMessage::PolicyEvaluation { + agent_settings_path, + .. + } => assert_eq!(agent_settings_path, None), + other => panic!("unexpected {other:?}"), } + assert_eq!( + scoped(PROTOCOL_VERSION).without_fields_newer_than_its_version(), + scoped(PROTOCOL_VERSION) + ); + } + + #[test] + fn versions_outside_the_supported_range_are_refused() { + assert!(is_supported_protocol_version(MIN_PROTOCOL_VERSION)); + assert!(is_supported_protocol_version(PROTOCOL_VERSION)); + assert!(!is_supported_protocol_version(0)); + assert!(!is_supported_protocol_version(PROTOCOL_VERSION + 1)); } #[test] diff --git a/crates/fpai-ipc/src/envelope.rs b/crates/fpai-ipc/src/envelope.rs index 83ab91e39..ae7808144 100644 --- a/crates/fpai-ipc/src/envelope.rs +++ b/crates/fpai-ipc/src/envelope.rs @@ -8,12 +8,29 @@ use serde::{Deserialize, Serialize}; -/// Bumped whenever a wire-incompatible change is made to either message -/// enum below. A daemon-configured client fails closed on a mismatch and uses -/// the distinct failure category only to explain how to repair the skew. -/// There is no protocol negotiation. +/// Bumped whenever a change is made to either message enum below. pub const PROTOCOL_VERSION: u32 = 2; +/// The oldest version the daemon still answers, and the oldest a client will +/// fall back to when an older daemon answers it. +/// +/// A long-lived host (a Hermes or OpenClaw gateway) keeps the plugin it loaded +/// at start, so after an upgrade it speaks the previous version until it is +/// restarted. Refusing it denied every tool call that host made. Each version +/// only ADDS optional fields, so an older request is answered by dropping +/// nothing and inferring nothing: the fields it predates stay absent, and the +/// reply carries the version the client sent. +/// +/// Raise this only when an older request can no longer be answered safely. +pub const MIN_PROTOCOL_VERSION: u32 = 1; + +/// The first version that carries `agentSettingsPath`. +pub const AGENT_SETTINGS_PATH_SINCE: u32 = 2; + +pub fn is_supported_protocol_version(version: u32) -> bool { + (MIN_PROTOCOL_VERSION..=PROTOCOL_VERSION).contains(&version) +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type", rename_all = "camelCase")] pub enum ClientMessage { @@ -106,7 +123,67 @@ impl ClientMessage { } } +impl ClientMessage { + /// Drops fields the request's own version predates. A v1 client never + /// sends `agentSettingsPath`, so one that does is not a v1 client, and its + /// profile is treated as unknown rather than trusted. + pub fn without_fields_newer_than_its_version(self) -> Self { + let keep_settings = self.protocol_version() >= AGENT_SETTINGS_PATH_SINCE; + match self { + ClientMessage::Hook { + protocol_version, + hook_event, + cli, + stdin, + cwd, + agent_settings_path, + } => ClientMessage::Hook { + protocol_version, + hook_event, + cli, + stdin, + cwd, + agent_settings_path: agent_settings_path.filter(|_| keep_settings), + }, + ClientMessage::PolicyEvaluation { + protocol_version, + integration, + event, + payload, + cwd, + agent_settings_path, + } => ClientMessage::PolicyEvaluation { + protocol_version, + integration, + event, + payload, + cwd, + agent_settings_path: agent_settings_path.filter(|_| keep_settings), + }, + ping @ ClientMessage::Ping { .. } => ping, + } + } +} + impl ServerMessage { + /// Stamps the reply with the version the client spoke, so a client that + /// 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::HookResult { + protocol_version, .. + } + | ServerMessage::PolicyResult { + protocol_version, .. + } + | ServerMessage::Error { + protocol_version, .. + } => *protocol_version = version, + } + self + } + pub fn protocol_version(&self) -> u32 { match self { ServerMessage::Pong { protocol_version } => *protocol_version, diff --git a/crates/fpai-ipc/src/lib.rs b/crates/fpai-ipc/src/lib.rs index 3fc9aa0c4..af3d2e0f3 100644 --- a/crates/fpai-ipc/src/lib.rs +++ b/crates/fpai-ipc/src/lib.rs @@ -6,5 +6,8 @@ pub mod envelope; pub mod framing; pub mod peer; -pub use envelope::{ClientMessage, PROTOCOL_VERSION, ServerMessage}; +pub use envelope::{ + ClientMessage, MIN_PROTOCOL_VERSION, PROTOCOL_VERSION, ServerMessage, + is_supported_protocol_version, +}; pub use framing::{FramingError, MAX_FRAME_LEN, read_message, write_message}; diff --git a/hermes-plugin/client.py b/hermes-plugin/client.py index 39ea78ee1..70f17ffe9 100644 --- a/hermes-plugin/client.py +++ b/hermes-plugin/client.py @@ -12,6 +12,10 @@ from typing import Any, Mapping, Sequence PROTOCOL_VERSION = 2 +# Oldest daemon version this plugin falls back to (crates/fpai-ipc +# MIN_PROTOCOL_VERSION), and the first that carries agentSettingsPath. +MIN_PROTOCOL_VERSION = 1 +AGENT_SETTINGS_PATH_SINCE = 2 MAX_FRAME_BYTES = 16 * 1024 * 1024 MAX_REQUEST_BYTES = 1024 * 1024 @@ -70,41 +74,8 @@ def _string_list(value: object, field: str) -> tuple[str, ...]: return tuple(value) -def evaluate_policy( - *, - event: str, - payload: Mapping[str, Any], - cwd: str | None, - agent_settings_path: str | None = None, - connect_timeout_ms: int = 250, - evaluation_timeout_ms: int = 12_000, -) -> PolicyVerdict: - request = { - "type": "policyEvaluation", - "protocolVersion": PROTOCOL_VERSION, - "integration": "hermes", - "event": event, - "payload": dict(payload), - "cwd": cwd, - # An unknown profile is explicit. Omitting this field would let a new - # daemon's warm worker attribute the call to its own Hermes home. - "agentSettingsPath": agent_settings_path or "", - } - try: - body = json.dumps( - request, - ensure_ascii=False, - separators=(",", ":"), - default=lambda value: repr(value), - ).encode("utf-8") - except (TypeError, ValueError) as exc: - raise EvaluationError(f"could not encode policy request: {exc}") from exc - if len(body) > MAX_REQUEST_BYTES: - raise EvaluationError("policy request exceeds the 1 MiB limit") - - # One deadline covers connect, send and read: evaluation_timeout_ms is the - # longest a tool call can wait here. Connect is bounded by both budgets. - deadline = time.monotonic() + max(evaluation_timeout_ms, 1) / 1000 +def _exchange(body: bytes, connect_timeout_ms: int, deadline: float) -> Any: + """One framed request and its framed reply over a fresh connection.""" try: with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock: sock.settimeout(min(max(connect_timeout_ms, 1) / 1000, _remaining_timeout(deadline))) @@ -117,15 +88,66 @@ def evaluate_policy( declared_length = struct.unpack(">I", _read_exact(sock, 4, deadline))[0] if declared_length > MAX_FRAME_BYTES: raise EvaluationError("failproofaid response exceeds the 16 MiB limit") - response = json.loads(_read_exact(sock, declared_length, deadline).decode("utf-8")) + return json.loads(_read_exact(sock, declared_length, deadline).decode("utf-8")) except EvaluationError: raise except (OSError, UnicodeError, ValueError, struct.error) as exc: raise EvaluationError(f"failproofaid evaluation failed: {exc}") from exc + +def evaluate_policy( + *, + event: str, + payload: Mapping[str, Any], + cwd: str | None, + agent_settings_path: str | None = None, + connect_timeout_ms: int = 250, + evaluation_timeout_ms: int = 12_000, +) -> PolicyVerdict: + def build(version: int) -> bytes: + request: dict[str, Any] = { + "type": "policyEvaluation", + "protocolVersion": version, + "integration": "hermes", + "event": event, + "payload": dict(payload), + "cwd": cwd, + } + if version >= AGENT_SETTINGS_PATH_SINCE: + # An unknown profile is explicit. Omitting this field would let a new + # daemon's warm worker attribute the call to its own Hermes home. + request["agentSettingsPath"] = agent_settings_path or "" + try: + body = json.dumps( + request, + ensure_ascii=False, + separators=(",", ":"), + default=lambda value: repr(value), + ).encode("utf-8") + except (TypeError, ValueError) as exc: + raise EvaluationError(f"could not encode policy request: {exc}") from exc + if len(body) > MAX_REQUEST_BYTES: + raise EvaluationError("policy request exceeds the 1 MiB limit") + return body + + # One deadline covers connect, send and read: evaluation_timeout_ms is the + # longest a tool call can wait here. Connect is bounded by both budgets. + deadline = time.monotonic() + max(evaluation_timeout_ms, 1) / 1000 + version = PROTOCOL_VERSION + response = _exchange(build(version), connect_timeout_ms, deadline) + answered = response.get("protocolVersion") if isinstance(response, dict) else None + # An older daemon still inside the supported range: ask again in its version + # rather than block every call until it is replaced. + if ( + type(answered) is int + and MIN_PROTOCOL_VERSION <= answered < PROTOCOL_VERSION + ): + version = answered + response = _exchange(build(version), connect_timeout_ms, deadline) + if not isinstance(response, dict): raise EvaluationError("failproofaid returned a non-object response") - if response.get("protocolVersion") != PROTOCOL_VERSION: + if response.get("protocolVersion") != version: raise EvaluationError("failproofaid protocol version mismatch") if response.get("type") == "error": message = response.get("message") diff --git a/openclaw-plugin/daemon-client.js b/openclaw-plugin/daemon-client.js index baa1da4f1..121767f5b 100644 --- a/openclaw-plugin/daemon-client.js +++ b/openclaw-plugin/daemon-client.js @@ -21,6 +21,10 @@ import { homedir } from "node:os"; import { resolve } from "node:path"; export const PROTOCOL_VERSION = 2; +// Oldest daemon version this plugin falls back to (crates/fpai-ipc +// MIN_PROTOCOL_VERSION), and the first that carries agentSettingsPath. +export const MIN_PROTOCOL_VERSION = 1; +const AGENT_SETTINGS_PATH_SINCE = 2; // The daemon's frame limit (crates/fpai-ipc/src/framing.rs), both ways. const MAX_FRAME_BYTES = 16 * 1024 * 1024; // The payload limit the CLI applies to its stdin (handler.ts, read-stdin.ts). @@ -92,12 +96,12 @@ function failed(failure, message) { * OpenClaw the evaluator always exits 0 and prints either nothing (allow) or * one JSON object, so anything else is an evaluation failure — never an allow. */ -function readHookResult(message) { +function readHookResult(message, protocolVersion) { if (message === null || typeof message !== "object" || Array.isArray(message)) { return failed("invalid", "failproofaid returned a non-object response"); } - if (message.protocolVersion !== PROTOCOL_VERSION) { - return failed("protocol-mismatch", PROTOCOL_MISMATCH_MESSAGE); + if (message.protocolVersion !== protocolVersion) { + return { ...failed("protocol-mismatch", PROTOCOL_MISMATCH_MESSAGE), daemonVersion: message.protocolVersion }; } if (message.type === "error") { const detail = typeof message.message === "string" && message.message ? message.message : "no detail"; @@ -158,8 +162,23 @@ function isVerdict(verdict) { * CLI discards an oversized stdin and evaluates an empty payload; * `oversized: true` lets the caller say so instead of discarding it silently. */ -export function requestHookVerdict(request) { - return requestWithRetry(request); +export async function requestHookVerdict(request) { + // One deadline for the whole call, shared by every attempt below (#1029). + const startedAt = performance.now(); + const budgetMs = request.responseTimeoutMs ?? RESPONSE_TIMEOUT_MS; + const clock = { startedAt, budgetMs, deadline: startedAt + budgetMs }; + + const first = await requestWithRetry(PROTOCOL_VERSION, request, clock); + // An older daemon still inside the supported range: ask again in its version + // rather than block every call until it is replaced. + const older = first.ok ? undefined : first.daemonVersion; + if (!Number.isInteger(older) || older < MIN_PROTOCOL_VERSION || older >= PROTOCOL_VERSION) { + if (!first.ok) delete first.daemonVersion; + return first; + } + const retried = await requestWithRetry(older, request, clock); + if (!retried.ok) delete retried.daemonVersion; + return retried; } /** @@ -168,7 +187,7 @@ export function requestHookVerdict(request) { * evaluate a call twice. Every other failure came from a daemon that saw the * request, and is returned as it is. * - * Both attempts share ONE deadline of `responseTimeoutMs`, set before the + * Every attempt shares ONE deadline of `responseTimeoutMs`, set before the * first and passed to each attempt as an absolute time: an attempt arms its * timer with what is left of it just before connecting (so encoding time * counts too), and the retry is skipped when the pause before it would use the @@ -180,14 +199,11 @@ export function requestHookVerdict(request) { * (gateway log only) names both attempts, so the first attempt's cause is * never lost behind the second's. */ -async function requestWithRetry(request) { - const startedAt = performance.now(); - const budgetMs = request.responseTimeoutMs ?? RESPONSE_TIMEOUT_MS; - const deadline = startedAt + budgetMs; +async function requestWithRetry(protocolVersion, request, { startedAt, budgetMs, deadline }) { const noTimeToRetry = (first) => ({ ...first, detail: `${first.detail}; no time left in the ${budgetMs} ms budget to retry` }); - const first = await requestOnce({ ...request, deadline, budgetMs }); + const first = await requestOnce(protocolVersion, { ...request, deadline, budgetMs }); if (first.ok || first.failure !== "unreachable") return first; const delayMs = request.retryDelayMs ?? UNREACHABLE_RETRY_DELAY_MS; @@ -195,7 +211,7 @@ async function requestWithRetry(request) { await new Promise((resume) => setTimeout(resume, delayMs)); if (deadline - performance.now() <= 0) return noTimeToRetry(first); - const second = await requestOnce({ ...request, deadline, budgetMs }); + const second = await requestOnce(protocolVersion, { ...request, deadline, budgetMs }); if (second.ok) return second; return { ...second, @@ -205,7 +221,7 @@ async function requestWithRetry(request) { }; } -function requestOnce({ +function requestOnce(protocolVersion, { event, payload, cwd = "", @@ -230,12 +246,12 @@ function requestOnce({ body = Buffer.from( JSON.stringify({ type: "hook", - protocolVersion: PROTOCOL_VERSION, + protocolVersion, hookEvent: event, cli: "openclaw", stdin, ...(typeof cwd === "string" && cwd ? { cwd } : {}), - agentSettingsPath: agentSettingsPath || "", + ...(protocolVersion >= AGENT_SETTINGS_PATH_SINCE ? { agentSettingsPath: agentSettingsPath || "" } : {}), }), "utf8", ); @@ -308,7 +324,7 @@ function requestOnce({ finish(failed("invalid", "failproofaid returned a response that is not JSON")); return; } - const result = readHookResult(message); + const result = readHookResult(message, protocolVersion); finish(result.ok && oversized ? { ...result, oversized: true } : result); }); socket.on("error", (err) => { diff --git a/src/hooks/daemon-client.ts b/src/hooks/daemon-client.ts index 4387d5252..7f29e02c2 100644 --- a/src/hooks/daemon-client.ts +++ b/src/hooks/daemon-client.ts @@ -17,6 +17,10 @@ import { daemonSocket as daemonSocketPath } from "./fp-home"; import { readConfig } from "./fp-config"; const PROTOCOL_VERSION = 2; +/** Oldest daemon version this client falls back to (crates/fpai-ipc MIN_PROTOCOL_VERSION). */ +const MIN_PROTOCOL_VERSION = 1; +/** First version carrying `agentSettingsPath`; an older daemon is sent none. */ +const AGENT_SETTINGS_PATH_SINCE = 2; /** * Reaching the daemon and getting an answer out of it are two different @@ -114,7 +118,7 @@ interface DaemonRequestOptions { type DaemonWireAttempt = | { ok: true; message: Record } - | { ok: false; failure: DaemonFailure }; + | { ok: false; failure: DaemonFailure; daemonVersion?: number }; /** * Whether a daemon is listening, regardless of how it was started. @@ -205,9 +209,34 @@ function encodeFrame(value: unknown): Buffer { * integrations share the transport, but require different response variants. */ async function attemptDaemonRequest( - request: Record, + build: (protocolVersion: number) => Record, + opts?: DaemonRequestOptions, +): Promise { + const first = await attemptDaemonRequestAt(PROTOCOL_VERSION, build, opts); + // An older daemon still inside the supported range: ask again in its version + // rather than deny every call until it is replaced. + const older = !first.ok ? first.daemonVersion : undefined; + if ( + older === undefined || + !Number.isInteger(older) || + older < MIN_PROTOCOL_VERSION || + older >= PROTOCOL_VERSION + ) { + return withoutDaemonVersion(first); + } + return withoutDaemonVersion(await attemptDaemonRequestAt(older, build, opts)); +} + +function withoutDaemonVersion(attempt: DaemonWireAttempt): DaemonWireAttempt { + return attempt.ok ? attempt : { ok: false, failure: attempt.failure }; +} + +async function attemptDaemonRequestAt( + protocolVersion: number, + build: (protocolVersion: number) => Record, opts?: DaemonRequestOptions, ): Promise { + const request = build(protocolVersion); // Windows never has a daemon in this phase (see the plan's platform // scope) — skip the attempt outright rather than depending on however // Node happens to behave when handed a POSIX socket path on Windows. @@ -278,12 +307,11 @@ async function attemptDaemonRequest( } const message = parsed as Record; - if (message.protocolVersion !== PROTOCOL_VERSION) { - // Catches BOTH directions. A newer CLI sends v2 and the daemon replies - // with an error stamped v1; an older CLI sends v1 and a newer daemon - // replies stamped v2. Either way the versions disagree here, and either - // way a daemon answered — so this is skew, not absence. - fail("protocol-mismatch"); + if (message.protocolVersion !== protocolVersion) { + // A daemon answered in another version — skew, not absence. When it is + // older, the caller retries once in that version. + const daemonVersion = typeof message.protocolVersion === "number" ? message.protocolVersion : undefined; + finish({ ok: false, failure: "protocol-mismatch", daemonVersion }); return; } finish({ ok: true, message }); @@ -294,21 +322,25 @@ async function attemptDaemonRequest( }); } +function settingsPathFor(protocolVersion: number, agentSettingsPath: string | undefined) { + return protocolVersion >= AGENT_SETTINGS_PATH_SINCE ? { agentSettingsPath } : {}; +} + /** Attempts a shell-hook daemon evaluation while preserving the failure category. */ export async function attemptDaemonHook( req: DaemonHookRequest, opts?: DaemonRequestOptions, ): Promise { const attempt = await attemptDaemonRequest( - { + (protocolVersion) => ({ type: "hook", - protocolVersion: PROTOCOL_VERSION, + protocolVersion, hookEvent: req.hookEvent, cli: req.cli, stdin: req.stdin, cwd: req.cwd, - agentSettingsPath: req.agentSettingsPath, - }, + ...settingsPathFor(protocolVersion, req.agentSettingsPath), + }), opts, ); if (!attempt.ok) return attempt; @@ -351,15 +383,15 @@ export async function attemptDaemonPolicyEvaluation( opts?: DaemonRequestOptions, ): Promise { const attempt = await attemptDaemonRequest( - { + (protocolVersion) => ({ type: "policyEvaluation", - protocolVersion: PROTOCOL_VERSION, + protocolVersion, integration: req.integration, event: req.event, payload: req.payload, cwd: req.cwd, - agentSettingsPath: req.agentSettingsPath, - }, + ...settingsPathFor(protocolVersion, req.agentSettingsPath), + }), opts, ); if (!attempt.ok) return attempt; From 621ec67ac544628bf7f08fccb6b94ba06b90cf5f Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 13:00:29 +0530 Subject: [PATCH 02/41] feat(update): restart running Hermes and OpenClaw gateways when idle A gateway imports the plugin once, at start. npm replaces the files on disk, but a running gateway keeps the code it already imported until it restarts, and nothing told it to: after the 1.0.13 upgrade every Slack/Telegram call through a stale gateway was blocked until someone restarted it by hand. `failproofai update` now restarts each running gateway of a profile that uses FailproofAI, through the host's own drain-aware restart, spawned detached so update returns at once: - Hermes: `hermes gateway restart` (SIGUSR1: refuse new turns, drain, exit; the service manager relaunches it), per profile via HERMES_HOME. - OpenClaw: `openclaw gateway restart --safe` (after active work drains), per profile via --profile; skipped on builds without --safe. Only a service-managed gateway is touched (systemd user scope, launchd). Without a service, `hermes gateway restart` runs the new gateway in the caller's foreground, so a hand-run gateway is left alone and its row says "restart the gateway". Gateways restart only onto a daemon this run left current. `--no-restart` opts out. Output stays the existing Hermes rows plus a short suffix, and one OpenClaw block of the same shape. --- CHANGELOG.md | 1 + CLAUDE.md | 7 +- __tests__/hooks/gateway-restart.test.ts | 138 ++++++++++++++++ __tests__/hooks/hermes-update.test.ts | 18 ++ bin/failproofai.mjs | 21 ++- src/hooks/gateway-restart.ts | 211 ++++++++++++++++++++++++ src/hooks/hermes-update.ts | 11 +- 7 files changed, 403 insertions(+), 4 deletions(-) create mode 100644 __tests__/hooks/gateway-restart.test.ts create mode 100644 src/hooks/gateway-restart.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 53a8e17dd..43b6bb0b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Fixes - The daemon answers the previous plugin protocol, and clients re-ask an older daemon in its version, so a Hermes or OpenClaw gateway still running the plugin it loaded before an upgrade keeps getting real verdicts instead of denying every call (#PR) +- `failproofai update` restarts running Hermes and OpenClaw gateways through their own drain-aware restart (after in-flight work finishes) so they load the updated plugin; only service-managed gateways are touched, and `--no-restart` opts out (#PR) ## 1.0.15 — 2026-11-18 diff --git a/CLAUDE.md b/CLAUDE.md index 0ec4bbc9f..eabbb4a02 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -262,7 +262,12 @@ only a marked copy or a link into a FailproofAI `hermes-plugin/`, refuses anythi else with the same name, and uses the `yaml` package's comment-preserving `Document` API for config changes. `failproofai update` migrates profiles already using FailproofAI (legacy shell hooks or a copy) to the link, gated on the daemon -answering `policyEvaluation`; legacy shell hooks never run for Hermes cron jobs. +answering `policyEvaluation`; legacy shell hooks never run for Hermes cron jobs. It then +restarts each running gateway (Hermes and OpenClaw) through the host's own drain-aware +restart (`hermes gateway restart`, `openclaw gateway restart --safe`) so it loads the +updated plugin — a gateway keeps the plugin it imported at start. Only a service-managed +gateway is touched: without a service, `hermes gateway restart` runs the new gateway in the +caller's foreground (`src/hooks/gateway-restart.ts`; `update --no-restart` opts out). Settings file paths: diff --git a/__tests__/hooks/gateway-restart.test.ts b/__tests__/hooks/gateway-restart.test.ts new file mode 100644 index 000000000..e855a11c0 --- /dev/null +++ b/__tests__/hooks/gateway-restart.test.ts @@ -0,0 +1,138 @@ +/** + * `failproofai update` restarts a running gateway so it loads the plugin now on + * disk — but only one a service manager runs, and only through the host's own + * drain-aware restart. A hand-run gateway is never touched: without a service, + * `hermes gateway restart` runs the new gateway in the caller's foreground. + */ +import { describe, it, expect, vi } from "vitest"; +import { + openclawRestartLines, + restartHermesGateway, + restartOpenClawGateway, + restartOpenClawGateways, + type CommandResult, +} from "../../src/hooks/gateway-restart"; + +const PROFILE = { name: "work", home: "/home/u/.hermes/profiles/work" }; + +function deps(outputs: Record, spawned = true) { + const run = vi.fn((cmd: string, args: string[], _env: NodeJS.ProcessEnv) => { + const out = outputs[`${cmd} ${args.join(" ")}`]; + if (!out) throw new Error(`unexpected command: ${cmd} ${args.join(" ")}`); + return out; + }); + const spawnDetached = vi.fn((_cmd: string, _args: string[], _env: NodeJS.ProcessEnv) => spawned); + return { run, spawnDetached }; +} + +const ok = (stdout: string): CommandResult => ({ status: 0, stdout }); + +describe("Hermes gateway restart", () => { + it.each([ + ["systemd", "● hermes-gateway.service\n✓ User gateway service is running\n"], + ["launchd", "Launchd plist: x\n✓ Gateway is supervised by launchd (PID 42)\n"], + ])("restarts a %s-supervised gateway with the host's drain-aware restart", (_kind, status) => { + const d = deps({ "hermes gateway status": ok(status) }); + expect(restartHermesGateway(PROFILE, d)).toEqual({ host: "hermes", profile: "work", status: "restarting" }); + expect(d.spawnDetached).toHaveBeenCalledTimes(1); + const [cmd, args, env] = d.spawnDetached.mock.calls[0]; + expect([cmd, ...args]).toEqual(["hermes", "gateway", "restart"]); + // The profile is selected the way Hermes derives its service name. + expect(env.HERMES_HOME).toBe(PROFILE.home); + expect(d.run.mock.calls[0][2].HERMES_HOME).toBe(PROFILE.home); + }); + + it.each([ + ["a system-scope service (needs root)", "✓ System gateway service is running\n"], + ["a detached fallback", "⚠ Gateway service is registered but launchd is not supervising it\n✓ Detached fallback process is running (PID 7)\n"], + ])("never restarts %s", (_kind, status) => { + const d = deps({ "hermes gateway status": ok(status) }); + expect(restartHermesGateway(PROFILE, d).status).toBe("not-supervised"); + expect(d.spawnDetached).not.toHaveBeenCalled(); + }); + + it("leaves a gateway that is not running alone", () => { + const d = deps({ "hermes gateway status": { status: 1, stdout: "✗ Gateway service is not installed\n" } }); + expect(restartHermesGateway(PROFILE, d).status).toBe("not-running"); + expect(d.spawnDetached).not.toHaveBeenCalled(); + }); + + it("reports a status that never came back, or a restart that could not start, as failed", () => { + expect(restartHermesGateway(PROFILE, deps({ "hermes gateway status": { status: null, stdout: "" } })).status) + .toBe("failed"); + const d = deps({ "hermes gateway status": ok("✓ User gateway service is running") }, false); + expect(restartHermesGateway(PROFILE, d).status).toBe("failed"); + }); + + it("never throws", () => { + const run = () => { throw new Error("ENOENT"); }; + expect(restartHermesGateway(PROFILE, { run }).status).toBe("failed"); + }); +}); + +const RUNNING = JSON.stringify({ service: { loaded: true, runtime: { status: "running" } } }); +const SAFE_HELP = ok(" --safe Request an OpenClaw-aware restart after active work drains\n"); + +describe("OpenClaw gateway restart", () => { + it("restarts a running service with --safe, so active work drains first", () => { + const d = deps({ + "openclaw gateway status --json": ok(RUNNING), + "openclaw gateway restart --help": SAFE_HELP, + }); + expect(restartOpenClawGateway({ name: "default", home: "/h/.openclaw" }, d).status).toBe("restarting"); + const [cmd, args] = d.spawnDetached.mock.calls[0]; + expect([cmd, ...args]).toEqual(["openclaw", "gateway", "restart", "--safe"]); + }); + + it("selects a named profile with --profile", () => { + const d = deps({ + "openclaw --profile ops gateway status --json": ok(`warning: x\n${RUNNING}`), + "openclaw gateway restart --help": SAFE_HELP, + }); + expect(restartOpenClawGateway({ name: "ops", home: "/h/.openclaw-ops" }, d).status).toBe("restarting"); + expect(d.spawnDetached.mock.calls[0][1]).toEqual(["--profile", "ops", "gateway", "restart", "--safe"]); + }); + + it("does not plain-restart an OpenClaw that has no --safe", () => { + const d = deps({ + "openclaw gateway status --json": ok(RUNNING), + "openclaw gateway restart --help": ok(" --force Begin restart now\n"), + }); + expect(restartOpenClawGateway({ name: "default", home: "/h" }, d).status).toBe("not-supervised"); + expect(d.spawnDetached).not.toHaveBeenCalled(); + }); + + it.each([ + ["stopped", JSON.stringify({ service: { loaded: true, runtime: { status: "stopped" } } }), "not-running"], + ["running without a service", JSON.stringify({ service: { loaded: false, runtime: { status: "running" } } }), "not-supervised"], + ["unreadable", "not json", "failed"], + ])("does not restart a gateway whose status is %s", (_label, stdout, status) => { + const d = deps({ "openclaw gateway status --json": ok(stdout) }); + expect(restartOpenClawGateway({ name: "default", home: "/h" }, d).status).toBe(status); + expect(d.spawnDetached).not.toHaveBeenCalled(); + }); + + it("restarts only the profiles it is given", () => { + const d = deps({ + "openclaw gateway status --json": ok(RUNNING), + "openclaw gateway restart --help": SAFE_HELP, + }); + const out = restartOpenClawGateways({ ...d, openclawProfiles: () => [{ name: "default", home: "/h" }] }); + expect(out).toEqual([{ host: "openclaw", profile: "default", status: "restarting" }]); + }); +}); + +describe("update's OpenClaw rows", () => { + it("prints one row per gateway that has something to say, and nothing otherwise", () => { + expect(openclawRestartLines([{ host: "openclaw", profile: "default", status: "not-running" }])).toEqual([]); + expect(openclawRestartLines([ + { host: "openclaw", profile: "default", status: "restarting" }, + { host: "openclaw", profile: "ops", status: "not-supervised" }, + { host: "openclaw", profile: "idle", status: "not-running" }, + ])).toEqual([ + "OpenClaw:", + " openclaw/default gateway restarting", + " openclaw/ops restart the gateway", + ]); + }); +}); diff --git a/__tests__/hooks/hermes-update.test.ts b/__tests__/hooks/hermes-update.test.ts index f3d03167f..02840ef95 100644 --- a/__tests__/hooks/hermes-update.test.ts +++ b/__tests__/hooks/hermes-update.test.ts @@ -291,6 +291,24 @@ describe("failproofai update → Hermes migration", () => { expect(result.lines.join("\n")).toMatch(/Cron jobs load the plugin on their next run/); }); + it("restarts the gateway of a profile on the linked plugin, and says so on its row", async () => { + writeConfig("default", LEGACY_CONFIG); + writeConfig("work", "model: other\n"); + const restartGateway = vi.fn((p: { name: string }) => ({ + host: "hermes" as const, profile: p.name, status: "restarting" as const, + })); + const result = await runHermesUpdateMigration({ daemonSupportsPolicyEvaluation: daemonYes(), restartGateway }); + expect(restartGateway).toHaveBeenCalledTimes(1); + expect(restartGateway.mock.calls[0][0]).toMatchObject({ name: "default", home: home() }); + expect(result.lines.join("\n")).toMatch(/hermes\/default\s+migrated — shell hooks → linked plugin, gateway restarting/); + }); + + it("without a restarter (update --no-restart) the rows are unchanged", async () => { + writeConfig("default", LEGACY_CONFIG); + const result = await runHermesUpdateMigration({ daemonSupportsPolicyEvaluation: daemonYes() }); + expect(result.lines.join("\n")).not.toMatch(/, gateway restarting|, restart the gateway/); + }); + it("migrates a copied plugin (1.0.6–1.0.8) to the link", async () => { makeManagedCopy(); const result = await runHermesUpdateMigration({ daemonSupportsPolicyEvaluation: daemonYes() }); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index 8289ca364..ec85354ad 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -1143,13 +1143,16 @@ async function runCli() { await printHelp({ name: "update", usage: [["npm i -g failproofai@latest && failproofai update"]], - options: [["--no-daemon", "Migrate everything but leave the daemon as is"]], + options: [ + ["--no-daemon", "Migrate everything but leave the daemon as is"], + ["--no-restart", "Leave running Hermes and OpenClaw gateways as they are"], + ], optionsCol: 20, }); process.exit(0); } - const KNOWN = new Set(["--no-daemon"]); + const KNOWN = new Set(["--no-daemon", "--no-restart"]); const unknown = subArgs.find((a) => a.startsWith("-") && !KNOWN.has(a)); if (unknown) { throw new CliError( @@ -1233,13 +1236,17 @@ async function runCli() { // now running can do: the native plugin needs `policyEvaluation`, which // ≤1.0.5 daemons lack, so when the swap above could not happen (a sudo // system service with no sudo) the shell hooks stay and this fails loudly. + // Gateways are restarted only onto a daemon this run left current. + const restartsGateways = daemonOk && !subArgs.includes("--no-daemon") && !subArgs.includes("--no-restart"); let hermesOk = true; let hermesMigrated = 0; try { const { runHermesUpdateMigration } = await import("../src/hooks/hermes-update"); const svc = await import("../src/hooks/daemon-service"); + const restart = await import("../src/hooks/gateway-restart"); const hermesResult = await runHermesUpdateMigration({ daemonSupportsPolicyEvaluation: () => svc.probeDaemonPolicyEvaluation(), + restartGateway: restartsGateways ? (p) => restart.restartHermesGateway(p) : undefined, }); if (hermesResult.lines.length > 0) { // Its lines open on a "Hermes:" heading over one row per profile; on a @@ -1254,6 +1261,16 @@ async function runCli() { hermesOk = false; } + if (restartsGateways) { + try { + const restart = await import("../src/hooks/gateway-restart"); + const lines = restart.openclawRestartLines(restart.restartOpenClawGateways()); + if (lines.length > 0) report.push("", ...lines); + } catch { + // Restarting is a convenience; the update itself already succeeded. + } + } + const updateOk = daemonOk && !migrationFailed && hermesOk; // No `v${version}` meta: the header already names the version. await printReport("update", report, { ok: updateOk }); diff --git a/src/hooks/gateway-restart.ts b/src/hooks/gateway-restart.ts new file mode 100644 index 000000000..e9d5b43d6 --- /dev/null +++ b/src/hooks/gateway-restart.ts @@ -0,0 +1,211 @@ +/** + * Restart running Hermes and OpenClaw gateways after `failproofai update`, when + * they are next idle. + * + * A gateway is one long-lived process that imported our plugin when it + * started. npm replaces the plugin files on disk, but the gateway keeps running + * the code it already imported until it restarts — which nobody told it to. + * + * Both hosts ship a restart that waits for in-flight work, so this never has to + * judge "idle" itself: + * - Hermes: `hermes gateway restart` (SIGUSR1: refuse new turns, drain, exit; + * the service manager relaunches it). + * - OpenClaw: `openclaw gateway restart --safe` (restart after active work + * drains, bounded). + * + * Only a gateway a service manager is running is touched. Without one, + * `hermes gateway restart` stops the gateway and runs the new one in the + * FOREGROUND of the caller — `update` would hang holding someone's gateway. A + * hand-run gateway (tmux, `gateway run`) is left alone and reported as such. + * + * The restart is spawned detached, so `update` returns immediately while the + * host waits out its drain. + */ +import { spawn, spawnSync } from "node:child_process"; +import { closeSync, mkdirSync, openSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { listOpenClawProfiles, OPENCLAW_DEFAULT_PROFILE } from "../../lib/openclaw-profiles"; +import { logsDir } from "./fp-home"; + +// integrations.ts's OPENCLAW_PLUGIN_ID; restated rather than imported so this +// module does not pull the whole integration table into `update`. +const OPENCLAW_PLUGIN_ID = "failproofai"; + +export type GatewayRestartStatus = "restarting" | "not-running" | "not-supervised" | "failed"; + +export interface GatewayRestart { + host: "hermes" | "openclaw"; + profile: string; + status: GatewayRestartStatus; +} + +export interface CommandResult { + status: number | null; + stdout: string; +} + +export interface GatewayRestartDeps { + run?: (cmd: string, args: string[], env: NodeJS.ProcessEnv) => CommandResult; + spawnDetached?: (cmd: string, args: string[], env: NodeJS.ProcessEnv) => boolean; + openclawProfiles?: () => Array<{ name: string; home: string }>; +} + +const STATUS_TIMEOUT_MS = 20_000; + +function defaultRun(cmd: string, args: string[], env: NodeJS.ProcessEnv): CommandResult { + const out = spawnSync(cmd, args, { + env, + encoding: "utf8", + timeout: STATUS_TIMEOUT_MS, + stdio: ["ignore", "pipe", "pipe"], + }); + return { status: out.error ? null : out.status, stdout: `${out.stdout ?? ""}${out.stderr ?? ""}` }; +} + +function restartLogPath(): string { + return `${logsDir()}/gateway-restart.log`; +} + +function defaultSpawnDetached(cmd: string, args: string[], env: NodeJS.ProcessEnv): boolean { + let fd: number | undefined; + try { + const log = restartLogPath(); + mkdirSync(dirname(log), { recursive: true }); + fd = openSync(log, "a"); + const child = spawn(cmd, args, { env, detached: true, stdio: ["ignore", fd, fd] }); + child.on("error", () => {}); + child.unref(); + return typeof child.pid === "number"; + } catch { + return false; + } finally { + if (fd !== undefined) closeSync(fd); + } +} + +/** + * What `hermes gateway status` prints when a service manager is running the + * gateway, verified on Hermes 0.20.0 and 0.21.3: + * - systemd: `✓ User gateway service is running` (`System …` for the system + * scope, which needs root to restart and is left alone); + * - launchd: `✓ Gateway is supervised by launchd (PID n)`. + * A detached fallback or hand-run gateway prints neither. + */ +const HERMES_SUPERVISED = [/user gateway service is running/i, /supervised by launchd \(PID/i]; +export function restartHermesGateway( + profile: { name: string; home: string }, + deps: GatewayRestartDeps = {}, +): GatewayRestart { + try { + return restartHermesGatewayUnsafe(profile, deps); + } catch { + return { host: "hermes", profile: profile.name, status: "failed" }; + } +} + +function restartHermesGatewayUnsafe( + profile: { name: string; home: string }, + deps: GatewayRestartDeps, +): GatewayRestart { + const run = deps.run ?? defaultRun; + const spawnDetached = deps.spawnDetached ?? defaultSpawnDetached; + const env = { ...process.env, HERMES_HOME: profile.home }; + const result = (status: GatewayRestartStatus): GatewayRestart => ({ host: "hermes", profile: profile.name, status }); + + const status = run("hermes", ["gateway", "status"], env); + 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"); + } + // Running, but not under a service we may restart (system scope, a detached + // fallback, or by hand): every such status names the gateway's PID. + if (/gateway service is running|\(PID \d+\)/i.test(status.stdout)) return result("not-supervised"); + return result("not-running"); +} + +interface OpenClawStatus { + service?: { loaded?: boolean; runtime?: { status?: string } }; +} + +export function restartOpenClawGateway( + profile: { name: string; home: string }, + deps: GatewayRestartDeps = {}, +): GatewayRestart { + try { + return restartOpenClawGatewayUnsafe(profile, deps); + } catch { + return { host: "openclaw", profile: profile.name, status: "failed" }; + } +} + +function restartOpenClawGatewayUnsafe( + profile: { name: string; home: string }, + deps: GatewayRestartDeps, +): GatewayRestart { + const run = deps.run ?? defaultRun; + const spawnDetached = deps.spawnDetached ?? defaultSpawnDetached; + const profileArgs = profile.name === OPENCLAW_DEFAULT_PROFILE ? [] : ["--profile", profile.name]; + const env = { ...process.env }; + const result = (status: GatewayRestartStatus): GatewayRestart => ({ host: "openclaw", profile: profile.name, status }); + + const out = run("openclaw", [...profileArgs, "gateway", "status", "--json"], env); + if (out.status === null) return result("failed"); + let parsed: OpenClawStatus; + try { + const start = out.stdout.indexOf("{"); + parsed = JSON.parse(start >= 0 ? out.stdout.slice(start) : out.stdout) as OpenClawStatus; + } catch { + return result("failed"); + } + if (parsed.service?.runtime?.status !== "running") return result("not-running"); + if (parsed.service.loaded !== true) return result("not-supervised"); + + // `--safe` waits for active work. Older OpenClaw has no such flag; a plain + // restart there would cut a turn off, so it is left to the user. + const help = run("openclaw", ["gateway", "restart", "--help"], env); + if (!/--safe\b/.test(help.stdout)) return result("not-supervised"); + return result( + spawnDetached("openclaw", [...profileArgs, "gateway", "restart", "--safe"], env) ? "restarting" : "failed", + ); +} + +/** Profiles whose openclaw.json loads our plugin; only their gateways run it. */ +function openclawProfilesUsingFailproofai(): Array<{ name: string; home: string }> { + return listOpenClawProfiles().filter((profile) => { + try { + const settings = JSON.parse(readFileSync(join(profile.home, "openclaw.json"), "utf8")) as { + plugins?: { entries?: Record }; + }; + return settings.plugins?.entries?.[OPENCLAW_PLUGIN_ID]?.enabled === true; + } catch { + return false; + } + }); +} + +export function restartOpenClawGateways(deps: GatewayRestartDeps = {}): GatewayRestart[] { + const profiles = (deps.openclawProfiles ?? openclawProfilesUsingFailproofai)(); + return profiles.map((profile) => restartOpenClawGateway(profile, deps)); +} + +/** + * `update`'s OpenClaw block, shaped like its Hermes block: a heading over one + * row per profile, and nothing at all when no gateway had anything to report. + */ +export function openclawRestartLines(restarts: GatewayRestart[]): string[] { + const rows = restarts.filter((r) => GATEWAY_STATUS_LABEL[r.status]); + if (rows.length === 0) return []; + const width = Math.max(...rows.map((r) => `openclaw/${r.profile}`.length)); + return [ + "OpenClaw:", + ...rows.map((r) => ` ${`openclaw/${r.profile}`.padEnd(width)} ${GATEWAY_STATUS_LABEL[r.status]}`), + ]; +} + +/** The word appended to a gateway's existing report row. */ +export const GATEWAY_STATUS_LABEL: Record = { + restarting: "gateway restarting", + "not-running": "", + "not-supervised": "restart the gateway", + failed: "restart the gateway", +}; diff --git a/src/hooks/hermes-update.ts b/src/hooks/hermes-update.ts index 182d017ae..575ae662e 100644 --- a/src/hooks/hermes-update.ts +++ b/src/hooks/hermes-update.ts @@ -15,6 +15,7 @@ * invisible. */ import { migrateHermesProfiles, type HermesPluginInstallDeps, type HermesProfileMigration } from "./integrations"; +import { GATEWAY_STATUS_LABEL, type GatewayRestart } from "./gateway-restart"; export interface HermesUpdateResult { ok: boolean; @@ -33,6 +34,11 @@ const STATUS_LABEL: Record = { export async function runHermesUpdateMigration(deps: { daemonSupportsPolicyEvaluation: () => Promise; installDeps?: HermesPluginInstallDeps; + /** + * Restarts a profile's running gateway so it loads the plugin now on disk. + * Left out (`update --no-restart`), gateways are not touched. + */ + restartGateway?: (profile: { name: string; home: string }) => GatewayRestart; }): Promise { const profiles = await migrateHermesProfiles(deps); const relevant = profiles.filter((p) => p.status !== "untouched"); @@ -44,7 +50,10 @@ export async function runHermesUpdateMigration(deps: { for (const p of profiles) { const label = ("hermes/" + p.name).padEnd(width); const detail = p.status === "current" ? "" : ` — ${p.detail}`; - lines.push(` ${label} ${STATUS_LABEL[p.status]}${detail}`); + // Only a profile now on the linked plugin has new code for its gateway. + const loaded = p.status === "migrated" || p.status === "current"; + const gateway = loaded && deps.restartGateway ? GATEWAY_STATUS_LABEL[deps.restartGateway(p).status] : ""; + lines.push(` ${label} ${STATUS_LABEL[p.status]}${detail}${gateway ? `, ${gateway}` : ""}`); } const blocked = profiles.filter((p) => p.status === "blocked"); From 5aa21fb68473f564d38f7fb3c4db022f7cc42506 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 13:26:21 +0530 Subject: [PATCH 03/41] fix(collector): leave a replaced key's refusals for the new key; split 413s After a reconnect the running collector keeps the old key until its next config tick and posts with it. Every batch it sent in that window came back 401/403 and was parked as a refusal, so `config --status` reported "the cloud is refusing this machine's key" right after a successful connect, and kept reporting it until a fresh batch was accepted and health rewritten. - On a 401/403 the uploader re-reads the key from credentials.json. If it was replaced, the batch is NOT parked: it stays in the spool for the uploader built with the new key, and this uploader sends nothing more. A refusal of the key still in use is parked exactly as before. - A 413 halves the body on line boundaries and re-sends the pieces in order until each fits; only a single event the server still refuses is parked. A server whose body limit is below ours otherwise refused the batch for good, though every event in it was within its limit. --- CHANGELOG.md | 2 + crates/failproofaid/src/main.rs | 1 + crates/fpai-collect/src/config.rs | 8 ++ crates/fpai-collect/src/uploader.rs | 96 +++++++++++++++- crates/fpai-collect/tests/uploader.rs | 159 ++++++++++++++++++++++++++ 5 files changed, 263 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 43b6bb0b3..122555596 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ - The daemon answers the previous plugin protocol, and clients re-ask an older daemon in its version, so a Hermes or OpenClaw gateway still running the plugin it loaded before an upgrade keeps getting real verdicts instead of denying every call (#PR) - `failproofai update` restarts running Hermes and OpenClaw gateways through their own drain-aware restart (after in-flight work finishes) so they load the updated plugin; only service-managed gateways are touched, and `--no-restart` opts out (#PR) +- A batch refused with a key the machine has since replaced (the seconds after a reconnect) is left for the new key instead of being parked as a refusal, so `config --status` no longer reports "the cloud is refusing this machine's key" right after a successful connect (#PR) +- A batch the server refuses as too large (413) is split in half and re-sent until each piece fits, instead of being parked for good (#PR) ## 1.0.15 — 2026-11-18 diff --git a/crates/failproofaid/src/main.rs b/crates/failproofaid/src/main.rs index d3a0b34b6..9aa58110b 100644 --- a/crates/failproofaid/src/main.rs +++ b/crates/failproofaid/src/main.rs @@ -986,6 +986,7 @@ fn collector_tasks(config: Option) -> Vec std::sync::Arc::new(u), Err(err) => { diff --git a/crates/fpai-collect/src/config.rs b/crates/fpai-collect/src/config.rs index aa4ee91e4..7b22fb852 100644 --- a/crates/fpai-collect/src/config.rs +++ b/crates/fpai-collect/src/config.rs @@ -599,6 +599,14 @@ fn read_credential_doc(home: &Path) -> Result, ConfigE } } +/// The ingest key a collector built from `home` right now would use, or `None` +/// when there is none. Read fresh on every call: it is how a running uploader +/// learns that the key it holds was replaced since it was built. +pub fn current_ingest_key(home: &Path) -> Option { + let doc = read_credential_doc(home).ok().flatten(); + load_ingest(doc.as_ref()).map(|ingest| ingest.key) +} + fn load_ingest(doc: Option<&serde_json::Value>) -> Option { let from_file = doc.and_then(|doc| doc.get("ingest")).and_then(|t| { let key = t.get("key")?.as_str()?.to_string(); diff --git a/crates/fpai-collect/src/uploader.rs b/crates/fpai-collect/src/uploader.rs index 0a25beea9..ea4a0d15b 100644 --- a/crates/fpai-collect/src/uploader.rs +++ b/crates/fpai-collect/src/uploader.rs @@ -108,6 +108,12 @@ pub enum UploadError { skipped: u64, }, Io(std::io::Error), + /// Refused with a key the machine has since replaced. Not parked: the + /// batch stays where it is for the uploader built with the new key, and + /// this one sends nothing more. + KeySuperseded, + /// 413 on a body that can still be halved. Internal: the caller splits it. + TooLarge, } impl std::fmt::Display for UploadError { @@ -134,6 +140,11 @@ impl std::fmt::Display for UploadError { write!(f, "network error after {attempts} attempt(s): {detail}") } UploadError::Io(e) => write!(f, "io error: {e}"), + UploadError::KeySuperseded => write!( + f, + "refused with a key this machine has since replaced; left for the new key" + ), + UploadError::TooLarge => write!(f, "too large for the server; split and re-sent"), } } } @@ -195,6 +206,13 @@ pub struct Uploader { /// this uploader parks one. Taken by `Delivery` after a delivery the /// server accepted, which proves the key in use now works. credential_refusals: std::sync::atomic::AtomicBool, + /// Where the key it was built with came from. A credential refusal is + /// checked against it: a key replaced since (a reconnect) means the + /// refusal is about the old key, not the batch. + key_source: Option, + /// Set once a refusal proved the key replaced. From then on this uploader + /// sends nothing: the collector built with the new key delivers instead. + superseded: std::sync::atomic::AtomicBool, } /// Credential-refusal policy. Both variants preserve the entire source batch. @@ -247,9 +265,25 @@ impl Uploader { metrics: Arc::new(UploadMetrics::default()), since_ms: None, credential_refusals: std::sync::atomic::AtomicBool::new(true), + key_source: None, + superseded: std::sync::atomic::AtomicBool::new(false), }) } + /// The failproofai home this uploader's key was read from. + pub fn with_key_source(mut self, home: PathBuf) -> Self { + self.key_source = Some(home); + self + } + + /// Whether the key on disk is no longer the one this uploader sends. + fn key_replaced(&self) -> bool { + self.key_source + .as_deref() + .and_then(crate::config::current_ingest_key) + .is_some_and(|current| current != self.key) + } + pub fn with_boundary(mut self, since_ms: Option) -> Self { self.since_ms = since_ms; self @@ -329,7 +363,7 @@ impl Uploader { let bytes = filter_boundary(&bytes, self.since_ms, crate::org_boundary::mtime_ms(path)); let bytes = redact_batch(&bytes, self.redact); for chunk in split_lines(&bytes, self.max_upload_bytes) { - self.post_batch(path, chunk).await?; + self.post_splitting(path, chunk).await?; } match tokio::fs::remove_file(path).await { @@ -339,12 +373,43 @@ impl Uploader { } } + /// POST one chunk, halving it on a 413 until each piece fits or is a + /// single line. A server whose body limit is below ours otherwise refused + /// the batch for good, though every event in it was within its limit. + /// Pieces go in their original order; a later failure leaves the whole + /// batch for a byte-identical resend, which the server dedups. + async fn post_splitting(&self, path: &Path, chunk: Vec) -> Result<(), UploadError> { + let mut pending = vec![chunk]; + while let Some(piece) = pending.pop() { + let lines = piece.split_inclusive(|b| *b == b'\n').count(); + match self.post_batch(path, piece.clone(), lines > 1).await { + Err(UploadError::TooLarge) => { + let (first, second) = halve_lines(&piece); + pending.push(second); + pending.push(first); + } + other => other?, + } + } + Ok(()) + } + /// POST one body, retrying per policy. `path` is used only for parking and - /// log context — this never deletes it. - async fn post_batch(&self, path: &Path, bytes: Vec) -> Result<(), UploadError> { + /// log context — this never deletes it. `can_split` answers a 413 with + /// [`UploadError::TooLarge`] instead of parking. + async fn post_batch( + &self, + path: &Path, + bytes: Vec, + can_split: bool, + ) -> Result<(), UploadError> { let mut attempt: u32 = 0; let batch_id = batch_id(path); + if self.superseded.load(Ordering::SeqCst) { + return Err(UploadError::KeySuperseded); + } + loop { // New per attempt: one attempt is one server request. let request_id = new_request_id(); @@ -434,6 +499,23 @@ impl Uploader { // than "you are wrong". Treating them as definitive would // park a batch the server explicitly asked us to resend. let retryable = status.is_server_error() || code == 408 || code == 429; + if code == 413 && can_split { + return Err(UploadError::TooLarge); + } + if !retryable && is_credential_status(code) && self.key_replaced() { + // The machine reconnected with a new key while this + // uploader was still running on the old one. Parking it + // read as "the cloud is refusing this machine's key" + // right after a successful connect. + self.superseded.store(true, Ordering::SeqCst); + tracing::info!( + file = %path.display(), + request_id = %request_id, + batch_id = %batch_id, + "refused with a replaced key; leaving the batch for the new one" + ); + return Err(UploadError::KeySuperseded); + } if !retryable { if is_credential_status(code) { self.credential_refusals.store(true, Ordering::SeqCst); @@ -970,6 +1052,14 @@ fn split_lines(bytes: &[u8], max: u64) -> Vec> { out } +/// Two halves of a body, split on the line boundary nearest its middle line. +/// Called only on a body with more than one line, so neither half is empty. +fn halve_lines(bytes: &[u8]) -> (Vec, Vec) { + let lines: Vec<&[u8]> = bytes.split_inclusive(|b| *b == b'\n').collect(); + let mid = lines.len().div_ceil(2); + (lines[..mid].concat(), lines[mid..].concat()) +} + /// A `Retry-After` in seconds, capped so a bad header cannot stall delivery. fn retry_after(resp: &reqwest::Response) -> Option { let raw = resp.headers().get(reqwest::header::RETRY_AFTER)?; diff --git a/crates/fpai-collect/tests/uploader.rs b/crates/fpai-collect/tests/uploader.rs index 8c4a4a476..86758ac20 100644 --- a/crates/fpai-collect/tests/uploader.rs +++ b/crates/fpai-collect/tests/uploader.rs @@ -1170,3 +1170,162 @@ async fn interrupted_success_acknowledgements_remain_retryable() { fs::remove_dir_all(spool).unwrap(); fs::remove_dir_all(failed).unwrap(); } + +fn write_key(home: &Path, key: &str) { + fpai_collect::config::write_ingest( + home, + &fpai_collect::config::Ingest { + url: "https://example.invalid/v1/events".into(), + key: key.into(), + }, + ) + .unwrap(); +} + +#[tokio::test] +async fn a_refusal_of_a_replaced_key_is_left_for_the_new_key_not_parked() { + // Reconnecting writes a new key; the running collector keeps the old one + // until its next config tick. What it sends in that window is refused, and + // parking it read as "the cloud is refusing this machine's key" right + // after a successful connect. + for status in [401, 403] { + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(status)) + .mount(&server) + .await; + let root = tmpdir("replaced-key"); + let (home, spool, failed) = (root.join("home"), root.join("spool"), root.join("failed")); + fs::create_dir_all(&spool).unwrap(); + write_key(&home, "new-key"); + let batch = write_batch(&spool, "hooks-a-1-0.jsonl", 3); + let original = fs::read(&batch).unwrap(); + let up = uploader(&server, &failed).with_key_source(home.clone()); + + let result = up.upload_file(&batch).await; + assert!( + matches!(result, Err(UploadError::KeySuperseded)), + "{result:?}" + ); + assert_eq!( + fs::read(&batch).unwrap(), + original, + "the batch stays for the new key" + ); + assert!(parked(&failed).is_empty(), "nothing is parked as a refusal"); + + // Nothing more goes out on the dead key. + let other = write_batch(&spool, "hooks-a-2-0.jsonl", 1); + assert!(matches!( + up.upload_file(&other).await, + Err(UploadError::KeySuperseded) + )); + assert_eq!(server.received_requests().await.unwrap().len(), 1); + fs::remove_dir_all(root).ok(); + } +} + +#[tokio::test] +async fn a_refusal_of_the_current_key_is_still_parked() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(401)) + .mount(&server) + .await; + let root = tmpdir("current-key"); + let (home, spool, failed) = (root.join("home"), root.join("spool"), root.join("failed")); + fs::create_dir_all(&spool).unwrap(); + write_key(&home, "test-key"); + let batch = write_batch(&spool, "hooks-a-1-0.jsonl", 2); + let up = uploader(&server, &failed).with_key_source(home); + + let result = up.upload_file(&batch).await; + assert!( + matches!(result, Err(UploadError::Client { status: 401 })), + "{result:?}" + ); + assert_eq!(parked(&failed), ["hooks-a-1-0.a1.r1.c401.jsonl"]); + fs::remove_dir_all(root).ok(); +} + +#[tokio::test] +async fn a_413_halves_the_body_until_it_fits_and_keeps_the_order() { + use wiremock::Request; + let server = MockServer::start().await; + // The server takes at most two events per request. + Mock::given(method("POST")) + .respond_with(|req: &Request| { + let lines = req + .body + .split(|b| *b == b'\n') + .filter(|l| !l.is_empty()) + .count(); + if lines > 2 { + ResponseTemplate::new(413) + } else { + ResponseTemplate::new(200) + .set_body_json(serde_json::json!({"accepted": lines, "skipped": 0})) + } + }) + .mount(&server) + .await; + let root = tmpdir("split-413"); + let failed = root.join("failed"); + let batch = write_batch(&root, "hooks-a-1-0.jsonl", 7); + let original = fs::read(&batch).unwrap(); + + uploader(&server, &failed) + .upload_file(&batch) + .await + .unwrap(); + + assert!(!batch.exists(), "every event landed, so the batch is gone"); + assert!(parked(&failed).is_empty()); + let delivered: Vec = server + .received_requests() + .await + .unwrap() + .into_iter() + .filter(|r| { + r.body + .split(|b| *b == b'\n') + .filter(|l| !l.is_empty()) + .count() + <= 2 + }) + .flat_map(|r| r.body) + .collect(); + assert_eq!( + delivered, original, + "accepted pieces, in order, are the whole batch" + ); + fs::remove_dir_all(root).ok(); +} + +#[tokio::test] +async fn a_413_on_a_single_event_is_parked_as_before() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(413)) + .mount(&server) + .await; + let root = tmpdir("single-413"); + let failed = root.join("failed"); + let batch = write_batch(&root, "hooks-a-1-0.jsonl", 2); + + let result = uploader(&server, &failed).upload_file(&batch).await; + assert!( + matches!(result, Err(UploadError::Client { status: 413 })), + "{result:?}" + ); + // Two lines -> two single-line requests; the first single line is parked. + assert_eq!(server.received_requests().await.unwrap().len(), 2); + assert_eq!(parked(&failed), ["hooks-a-1-0.a1.r1.c413.jsonl"]); + let kept = fs::read(failed.join("hooks-a-1-0.a1.r1.c413.jsonl")).unwrap(); + assert_eq!( + kept.iter().filter(|b| **b == b'\n').count(), + 2, + "the whole batch is kept" + ); + fs::remove_dir_all(root).ok(); +} From 66327575599e4c77b8edd46cd8240cfe97708922 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 13:34:52 +0530 Subject: [PATCH 04/41] fix(status): point cloud-managed machines at Cloud; count Jev-only deployments - config --status counted only JS cloud policies in its policies row, while the "not enforcing" line beside it also counted Cloud Jev assignments: a Jev-only deployment read "None installed" next to a line calling it enforcing. Both now read manager.ts's cloudPolicyStatus(). - A machine that pulls policies from Cloud deploys them there, so it is no longer told to install packs: the policies row says "None deployed from Cloud", the "not enforcing" fix is the dashboard URL, and the policies screen's empty state is one "Deploy from Cloud" line. Machines that only report to Cloud, or are not connected, read exactly as before. - The legacy-shim "no pack is installed" warning is logged once per process. The warm worker evaluates every hook on the machine, and the per-hook repeat buried the daemon log (seen on a customer Mac mini). --- CHANGELOG.md | 3 ++ __tests__/hooks/config-status.test.ts | 25 +++++++++-- .../hooks/enforcement-from-packs.test.ts | 4 +- __tests__/hooks/manager-cloud-status.test.ts | 12 +++++ __tests__/hooks/policies-listing.test.ts | 13 ++++++ src/hooks/config-status.ts | 33 +++++++------- src/hooks/handler.ts | 8 +++- src/hooks/manager.ts | 45 +++++++++++++++---- 8 files changed, 111 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 122555596..000132103 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,9 @@ - `failproofai update` restarts running Hermes and OpenClaw gateways through their own drain-aware restart (after in-flight work finishes) so they load the updated plugin; only service-managed gateways are touched, and `--no-restart` opts out (#PR) - A batch refused with a key the machine has since replaced (the seconds after a reconnect) is left for the new key instead of being parked as a refusal, so `config --status` no longer reports "the cloud is refusing this machine's key" right after a successful connect (#PR) - A batch the server refuses as too large (413) is split in half and re-sent until each piece fits, instead of being parked for good (#PR) +- `config --status` counts Cloud Jev-only deployments in its policies row; it showed "None installed" beside a deployment the line under it called enforcing (#PR) +- A machine that pulls policies from Cloud is pointed at Cloud, not at installing packs: `config --status` says "None deployed from Cloud" with the dashboard as its fix, and the `failproofai policies` empty state says "Deploy from Cloud" (#PR) +- The "no pack is installed" warning is logged once per process instead of on every hook call, which buried the daemon log (#PR) ## 1.0.15 — 2026-11-18 diff --git a/__tests__/hooks/config-status.test.ts b/__tests__/hooks/config-status.test.ts index 81046264b..b080b1e8d 100644 --- a/__tests__/hooks/config-status.test.ts +++ b/__tests__/hooks/config-status.test.ts @@ -359,7 +359,21 @@ describe("config --status — ENFORCEMENT", () => { it("names the pack that is installed with everything off, and an empty machine as empty", () => { expect(policiesRow({ packOn: 0, firstPack: undefined })).toBe("0 on from FailproofAI/policies@06b802b1c2d3"); - expect(policiesRow({ packOn: 0, firstPack: undefined, packsInstalled: 0, anyPack: undefined })).toBe("None installed"); + const empty = { ...facts().policies, packOn: 0, firstPack: undefined, packsInstalled: 0, anyPack: undefined }; + expect(rowValue(renderStatusScreen(facts({ cloud: { kind: "none" }, policies: empty }), PLAIN), "policies")) + .toBe("None installed"); + }); + + it("says an empty machine that pulls from Cloud has nothing deployed, not nothing installed", () => { + // Its policies are deployed on the dashboard; "installed" sent cloud users + // to install packs locally. + expect(policiesRow({ packOn: 0, firstPack: undefined, packsInstalled: 0, anyPack: undefined })) + .toBe("None deployed from Cloud"); + const reportingOnly = facts({ + cloud: { kind: "file", host: "be.failproof.ai", pullsPolicies: false, sendsEvents: true }, + policies: { ...facts().policies, packOn: 0, firstPack: undefined, packsInstalled: 0, anyPack: undefined }, + }); + expect(rowValue(renderStatusScreen(reportingOnly, PLAIN), "policies")).toBe("None installed"); }); it("has no per-day counts and no per-agent rows: one row per fact about the machine", () => { @@ -419,7 +433,8 @@ describe("config --status — the attention line", () => { expect(pickStatusAttention(f)).toEqual({ severity: "caution", text: "Policies are not enforcing yet.", - fix: "failproofai policies add", + // A machine that pulls policies from Cloud deploys them there. + fix: "https://be.failproof.ai", }); f.notEnforcing = null; @@ -447,12 +462,14 @@ describe("config --status — the attention line", () => { }); it("fixes 'not enforcing' with the command for its cause", () => { - const fixFor = (reason: StatusFacts["notEnforcing"], packsInstalled = 1) => - pickStatusAttention(facts({ notEnforcing: reason, policies: { ...facts().policies, packsInstalled } }))?.fix; + const fixFor = (reason: StatusFacts["notEnforcing"], packsInstalled = 1, cloud: StatusFacts["cloud"] = { kind: "none" }) => + pickStatusAttention(facts({ cloud, notEnforcing: reason, policies: { ...facts().policies, packsInstalled } }))?.fix; expect(fixFor("no-hooks")).toBe("failproofai config"); expect(fixFor("observe-only")).toBe("failproofai policies"); expect(fixFor("no-policies", 1)).toBe("failproofai policies add"); expect(fixFor("no-policies", 0)).toBe("failproofai policies add FailproofAI/policies"); + // Policies for a machine that pulls from Cloud are deployed there. + expect(fixFor("no-policies", 0, facts().cloud)).toBe("https://be.failproof.ai"); }); it("never calls a machine with a refused pack 'not enforcing': it is denying", () => { diff --git a/__tests__/hooks/enforcement-from-packs.test.ts b/__tests__/hooks/enforcement-from-packs.test.ts index 23a7e2df5..f94b3db79 100644 --- a/__tests__/hooks/enforcement-from-packs.test.ts +++ b/__tests__/hooks/enforcement-from-packs.test.ts @@ -181,11 +181,13 @@ describe("the migration shim", () => { }); try { await evaluate("sudo rm -rf /tmp/x"); + // The warm worker evaluates every hook on the machine: once per process. + await evaluate("sudo rm -rf /tmp/y"); } finally { spy.mockRestore(); } const log = written.join(""); - expect(log).toMatch(/no pack is installed/); + expect(log.match(/no pack is installed/g)).toHaveLength(1); expect(log).toMatch(/failproofai policies add FailproofAI\/policies/); expect(log).not.toMatch(/failproofai update/); }); diff --git a/__tests__/hooks/manager-cloud-status.test.ts b/__tests__/hooks/manager-cloud-status.test.ts index 83a990122..644b56ba7 100644 --- a/__tests__/hooks/manager-cloud-status.test.ts +++ b/__tests__/hooks/manager-cloud-status.test.ts @@ -5,6 +5,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { enforcingPolicyCount, listHooks, notEnforcingReason } from "../../src/hooks/manager"; +import { summarizePolicySources } from "../../src/hooks/config-status"; const ARTIFACT = "throw new Error('status must not import Cloud policy code');\n"; const DIGEST = createHash("sha256").update(ARTIFACT).digest("hex"); @@ -72,6 +73,17 @@ describe("manager Cloud Jev enforcement status", () => { expectStatus(null, 2); }); + it("counts a Jev-only deployment in config --status's policies row, as the line beside it does", () => { + // The row counted JS policies only: "None installed" beside a deployment + // the "not enforcing" line correctly called enforcing. + deploy("enforce", [ + { id: "jev-only", version: 1, effect: "enforce" }, + { id: "watch-jev", version: 1, effect: "observe" }, + ]); + expect(notEnforcingReason(project)).toBeNull(); + expect(summarizePolicySources(project)).toMatchObject({ cloudOn: 1, observing: 1 }); + }); + it("keeps observe-effect Jev-only assignments watching in enforce mode", () => { deploy("enforce", [{ id: "watch-jev", version: 1, effect: "observe" }]); expectStatus("observe-only", 0); diff --git a/__tests__/hooks/policies-listing.test.ts b/__tests__/hooks/policies-listing.test.ts index e5dd1534e..a5ef14b46 100644 --- a/__tests__/hooks/policies-listing.test.ts +++ b/__tests__/hooks/policies-listing.test.ts @@ -460,6 +460,19 @@ describe("renderPoliciesScreen", () => { ]); }); + it("points an empty machine that pulls from Cloud at Cloud, not at installing packs", async () => { + const { renderPoliciesScreen } = await import("@/src/hooks/manager"); + const empty = { ...SCREEN, packs: [], refused: [], custom: [], convention: [], cloud: null, legacy: [], attention: null }; + const local = renderPoliciesScreen(empty, { version: "1.0.11", cols: 104, color: false }); + expect(local.join("\n")).toMatch(/Turn on ours:/); + const managed = renderPoliciesScreen( + { ...empty, cloudDashboard: "https://be.failproof.ai" }, + { version: "1.0.11", cols: 104, color: false }, + ); + expect(managed.join("\n")).not.toMatch(/policies add/); + expect(managed.at(-1)).toBe(" Deploy from Cloud: https://be.failproof.ai"); + }); + function withTruecolor(fn: () => T): T { const before = { COLORTERM: process.env.COLORTERM, TERM: process.env.TERM, NO_COLOR: process.env.NO_COLOR }; process.env.COLORTERM = "truecolor"; diff --git a/src/hooks/config-status.ts b/src/hooks/config-status.ts index 8d01b1e0e..4b20e707b 100644 --- a/src/hooks/config-status.ts +++ b/src/hooks/config-status.ts @@ -27,7 +27,6 @@ import { readCloudCredentials } from "./cloud-enrollment"; import { CODEX_UNTRUSTED_NOTICE, codexHookTrust, type CodexHookTrust } from "./codex-system-hooks"; import { describeMachine } from "./cloud-enrollment-cli"; import { cloudBaseFor } from "./cloud-connection"; -import { listActiveCloudManagedPolicies } from "./cloud-managed-policies"; import { readIngestCredential } from "./collector-config"; import { discoverPolicyFiles } from "./custom-hooks-loader"; import { daemonSocketPresent, isDaemonConfigured } from "./daemon-client"; @@ -44,7 +43,7 @@ import { isAgentTraced, readConfig, readCredentials, readVersionFile } from "./f import { collectorHealthFile, customPoliciesDir } from "./fp-home"; import { configuredCustomPolicyPaths, findProjectConfigDir, readMergedHooksConfig } from "./hooks-config"; import { detectInstalledClis, listInstallableIds } from "./integrations"; -import { notEnforcingReason, type NotEnforcingReason } from "./manager"; +import { cloudPolicyStatus, notEnforcingReason, type NotEnforcingReason } from "./manager"; import { hasInstalledRegexPacks, readInstalledPacks } from "./pack-manifest"; import { CORE_SOURCE } from "./pack-store"; import { formatDuration, listActivePauses } from "./session-pause"; @@ -258,17 +257,12 @@ export function summarizePolicySources(cwd?: string): StatusPolicies { // An unreadable manifest is reported by `failproofai policies`. } - try { - // Every assignment, whatever agent it targets: a hook's agent scope applied - // with no agent hid each targeted policy ("None installed" beside a - // deployment that enforces), the status twin of B4. - for (const artifact of listActiveCloudManagedPolicies()) { - if (artifact.effect === "observe") summary.observing++; - else summary.cloudOn++; - } - } catch { - // No deployment, or an unreadable one: nothing comes from there. - } + // Every assignment, whatever agent it targets, JS and Cloud Jev alike: + // counting JS alone showed "None installed" beside a Jev-only deployment the + // line below it called enforcing. + const cloud = cloudPolicyStatus(); + summary.cloudOn += cloud.count; + summary.observing += cloud.observingCount; // Deduplicated by path: run from the home directory, the project's convention // folder IS the global one. @@ -434,9 +428,11 @@ export function pickStatusAttention(facts: StatusFacts): StatusAttention | null ? "failproofai config" : facts.notEnforcing === "observe-only" ? "failproofai policies" - : policies.packsInstalled > 0 - ? "failproofai policies add" - : `failproofai policies add ${CORE_SOURCE}`; + : cloud.kind === "file" && cloud.pullsPolicies + ? `https://${cloud.host}` + : policies.packsInstalled > 0 + ? "failproofai policies add" + : `failproofai policies add ${CORE_SOURCE}`; return { severity: "caution", text: "Policies are not enforcing yet.", fix }; } if (facts.codex?.kind === "untrusted") { @@ -544,6 +540,8 @@ export function renderStatusScreen(facts: StatusFacts, opts: ScreenKitOpts & { c return `${kit.on} Healthy, ${lastEvent}, ${backlog}`; }; + // Its policies are deployed from Cloud, so "install some" is the wrong advice. + const cloudManaged = cloud.kind === "env" || (cloud.kind === "file" && cloud.pullsPolicies); const policiesValue = (): string => { const clauses: string[] = []; if (policies.packOn > 0) { @@ -558,7 +556,8 @@ export function renderStatusScreen(facts: StatusFacts, opts: ScreenKitOpts & { c if (policies.observing > 0) clauses.push(`${policies.observing} observing`); if (policies.refusedPacks > 0) clauses.push(`${many(policies.refusedPacks, "pack")} will not load`); if (clauses.length > 0) return clauses.join(", "); - return policies.anyPack ? `0 on from ${policies.anyPack}` : "None installed"; + if (policies.anyPack) return `0 on from ${policies.anyPack}`; + return cloudManaged ? "None deployed from Cloud" : "None installed"; }; // Only when failproofai's Codex hooks are installed at user scope: whether diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 52cebbd05..f1ebd0f94 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -94,6 +94,9 @@ import { isHealthProbe } from "./health-probe"; import { readRuntimeAgentIdentity, runtimeAgentSettingsPath } from "./agent-roster"; import type { AgentIdentity } from "./agent-targets"; +/** Set once the legacy-shim warning has been logged in this process. */ +let legacyShimWarned = false; + /** * Canonicalize an event name to PascalCase. Codex sends snake_case event names * on stdin and as the --hook arg; Cursor sends camelCase (`preToolUse`, @@ -796,7 +799,10 @@ export async function evaluateHookEvent( // so an empty list still registers the guard — which is exactly what this // build should contribute once packs carry everything else. registerBuiltinPolicies(activePause ? [] : legacyNames); - if (legacyNames.length > 0) { + // Once per process: the warm worker evaluates every hook on the machine, + // and repeating this on each one buried the daemon log. + if (legacyNames.length > 0 && !legacyShimWarned) { + legacyShimWarned = true; hookLogWarn( `enforcing ${legacyNames.length} policies from this build because no pack is installed — ` + `run \`failproofai policies add FailproofAI/policies\` to move them into a real pack`, diff --git a/src/hooks/manager.ts b/src/hooks/manager.ts index dfbcb8443..62749889f 100644 --- a/src/hooks/manager.ts +++ b/src/hooks/manager.ts @@ -33,6 +33,7 @@ import { CliError } from "../cli-error"; import { hookLogWarn } from "./hook-logger"; import { customPoliciesDir } from "./fp-home"; import { listActiveCloudManagedPolicies, readCloudJevAssignments, readCloudJevState, type CloudJevMode } from "./cloud-managed-policies"; +import { readCloudCredentials } from "./cloud-enrollment"; import { readCloudPolicyErrors } from "./cloud-policy-errors"; import { readRosterLabels } from "./agent-roster"; import { CORE_SOURCE, addPack, setPackPolicyEnabled } from "./pack-store"; @@ -334,16 +335,23 @@ export function integrationsInstalledAt(scope: HookScope, cwd?: string): Integra */ export type NotEnforcingReason = "no-hooks" | "no-policies" | "observe-only"; -/** Machine-wide assignments, like the listing: a `both` policy counts once. */ -function cloudPolicyStatus(): { count: number; observing: boolean } { +/** + * Machine-wide assignments, like the listing: a `both` policy counts once. + * `observingCount` is what `config --status` shows beside `count`; both read + * this one function so its policies row and this line cannot disagree. + */ +export function cloudPolicyStatus(): { count: number; observing: boolean; observingCount: number } { let count = 0; let observing = false; + let observingCount = 0; const jsIds = new Set(); try { for (const artifact of listActiveCloudManagedPolicies()) { jsIds.add(artifact.id); - if (artifact.effect === "observe") observing = true; - else count++; + if (artifact.effect === "observe") { + observing = true; + observingCount++; + } else count++; } } catch { // The listing reports an unreadable JS deployment; Jev is read independently. @@ -353,14 +361,16 @@ function cloudPolicyStatus(): { count: number; observing: boolean } { if (jevMode === "enforce" || jevMode === "observe") { for (const assignment of readCloudJevAssignments() ?? []) { if (jsIds.has(assignment.id)) continue; - if (jevMode === "observe" || assignment.effect === "observe") observing = true; - else count++; + if (jevMode === "observe" || assignment.effect === "observe") { + observing = true; + observingCount++; + } else count++; } } } catch { // No readable Jev state: neither enforcement nor observation is known. } - return { count, observing }; + return { count, observing, observingCount }; } export function notEnforcingReason(cwd?: string): NotEnforcingReason | null { @@ -1284,6 +1294,21 @@ export interface PoliciesScreen { * nothing for a machine enforcing all of them. */ legacy?: Array<{ name: string; description: string }>; + /** + * The Cloud dashboard this machine pulls its policies from, when it does. + * Its policies are deployed there, so the empty state points there instead + * of at installing packs. + */ + cloudDashboard?: string; +} + +/** The dashboard a cloud-connected machine pulls policies from, or undefined. */ +function cloudDashboardUrl(): string | undefined { + try { + return readCloudCredentials()?.url || undefined; + } catch { + return undefined; + } } /** @@ -1341,7 +1366,9 @@ export function renderPoliciesScreen( const { failed, text, fix } = screen.attention; out.push(failed ? kit.fail(text, fix) : kit.caution(text, fix)); } - if (empty) { + if (empty && screen.cloudDashboard) { + out.push(`${INDENT}Deploy from Cloud: ${kit.cmd(screen.cloudDashboard)}`); + } else if (empty) { // Ours first is a convenience, not a channel: a screen that named only ours // would read as the place policies come from. out.push( @@ -1800,7 +1827,7 @@ export async function listHooks(cwd?: string, { all = false }: { all?: boolean } printBlock( process.stdout, renderPoliciesScreen( - { packs, refused, attention, custom, convention, cloud, legacy }, + { packs, refused, attention, custom, convention, cloud, legacy, cloudDashboard: cloudDashboardUrl() }, // Descriptions are shortened only for a terminal; a pipe keeps every word. { ...optsFor(process.stdout), fit: Boolean(process.stdout.isTTY), all }, ), From 6e483141b21e675dbd3a7ccfde1027946f6f9ed9 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 13:46:17 +0530 Subject: [PATCH 05/41] docs(changelog): link the customer fixes to #1023 --- CHANGELOG.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 000132103..b55d8f6e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,13 +4,13 @@ ### Fixes -- The daemon answers the previous plugin protocol, and clients re-ask an older daemon in its version, so a Hermes or OpenClaw gateway still running the plugin it loaded before an upgrade keeps getting real verdicts instead of denying every call (#PR) -- `failproofai update` restarts running Hermes and OpenClaw gateways through their own drain-aware restart (after in-flight work finishes) so they load the updated plugin; only service-managed gateways are touched, and `--no-restart` opts out (#PR) -- A batch refused with a key the machine has since replaced (the seconds after a reconnect) is left for the new key instead of being parked as a refusal, so `config --status` no longer reports "the cloud is refusing this machine's key" right after a successful connect (#PR) -- A batch the server refuses as too large (413) is split in half and re-sent until each piece fits, instead of being parked for good (#PR) -- `config --status` counts Cloud Jev-only deployments in its policies row; it showed "None installed" beside a deployment the line under it called enforcing (#PR) -- A machine that pulls policies from Cloud is pointed at Cloud, not at installing packs: `config --status` says "None deployed from Cloud" with the dashboard as its fix, and the `failproofai policies` empty state says "Deploy from Cloud" (#PR) -- The "no pack is installed" warning is logged once per process instead of on every hook call, which buried the daemon log (#PR) +- The daemon answers the previous plugin protocol, and clients re-ask an older daemon in its version, so a Hermes or OpenClaw gateway still running the plugin it loaded before an upgrade keeps getting real verdicts instead of denying every call (#1023) +- `failproofai update` restarts running Hermes and OpenClaw gateways through their own drain-aware restart (after in-flight work finishes) so they load the updated plugin; only service-managed gateways are touched, and `--no-restart` opts out (#1023) +- A batch refused with a key the machine has since replaced (the seconds after a reconnect) is left for the new key instead of being parked as a refusal, so `config --status` no longer reports "the cloud is refusing this machine's key" right after a successful connect (#1023) +- A batch the server refuses as too large (413) is split in half and re-sent until each piece fits, instead of being parked for good (#1023) +- `config --status` counts Cloud Jev-only deployments in its policies row; it showed "None installed" beside a deployment the line under it called enforcing (#1023) +- A machine that pulls policies from Cloud is pointed at Cloud, not at installing packs: `config --status` says "None deployed from Cloud" with the dashboard as its fix, and the `failproofai policies` empty state says "Deploy from Cloud" (#1023) +- The "no pack is installed" warning is logged once per process instead of on every hook call, which buried the daemon log (#1023) ## 1.0.15 — 2026-11-18 From 32e5fd5c4a554eda01a533b5b1254de0b7e412ca Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 14:14:09 +0530 Subject: [PATCH 06/41] fix(daemon): survive a Node upgrade, transient accept errors and lane panics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The service saves a stable link to Node when PATH has one. execPath is the resolved path, and Homebrew's is Cellar/node//bin/node, which `brew upgrade node` deletes while /opt/homebrew/bin/node and the global packages survive: the daemon stayed up, its worker could not start, and every hook was denied. - `failproofai update` rewrites a service whose saved Node or failproofai path is gone (nvm keeps global packages per version, so no saved path survives a version switch there) instead of "nothing to update". The daemon log names that cause and the fix when the worker exits 127. - A transient accept() error (EMFILE, ENFILE, an aborted connection) is retried instead of ending the accept loop, which exited the daemon and left every hook denied until the service manager restarted it. - The collector manager and the cloud policy lane restart after a panic. A panic on a plain thread ended only that thread: collection or policy sync stopped silently while hooks kept being answered. - A client that hung up before its verdict is logged as that, with how long the evaluation took. On macOS it was only "Invalid argument (os error 22)", from setsockopt on a socket the peer had closed — 56 of them on a customer Mac mini, each a call its client had already failed closed. --- CHANGELOG.md | 4 + __tests__/hooks/daemon-service.test.ts | 89 +++++++++++- crates/failproofaid/src/cloud_client.rs | 175 ++++++++++++------------ crates/failproofaid/src/main.rs | 72 +++++++++- crates/failproofaid/src/server.rs | 88 +++++++++++- crates/failproofaid/src/worker.rs | 32 ++++- src/hooks/daemon-service.ts | 74 +++++++++- src/hooks/shell-quote.ts | 15 ++ 8 files changed, 451 insertions(+), 98 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b55d8f6e1..6d067362d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ - `config --status` counts Cloud Jev-only deployments in its policies row; it showed "None installed" beside a deployment the line under it called enforcing (#1023) - A machine that pulls policies from Cloud is pointed at Cloud, not at installing packs: `config --status` says "None deployed from Cloud" with the dashboard as its fix, and the `failproofai policies` empty state says "Deploy from Cloud" (#1023) - The "no pack is installed" warning is logged once per process instead of on every hook call, which buried the daemon log (#1023) +- The daemon service saves a stable link to Node when PATH has one (Homebrew's `/opt/homebrew/bin/node`, not the `Cellar/` path `brew upgrade node` deletes), and `failproofai update` rewrites a service whose saved Node or failproofai path is gone instead of reporting nothing to update; the daemon log names that cause and the fix when the worker cannot start (#1023) +- The daemon no longer exits on a transient `accept()` failure (out of file descriptors, an aborted connection), which left every hook denied until the service manager restarted it (#1023) +- The collector manager and cloud policy sync restart after a panic instead of stopping silently while the daemon keeps answering hooks (#1023) +- A hook client that stopped waiting before its verdict was ready is logged as that, with how long the evaluation took, instead of macOS's bare "Invalid argument (os error 22)" (#1023) ## 1.0.15 — 2026-11-18 diff --git a/__tests__/hooks/daemon-service.test.ts b/__tests__/hooks/daemon-service.test.ts index 35d2155df..f97e0ac1a 100644 --- a/__tests__/hooks/daemon-service.test.ts +++ b/__tests__/hooks/daemon-service.test.ts @@ -278,15 +278,16 @@ describe("hooks/daemon-service", () => { setPlatform("linux"); const { resolveWorkerCommand, systemdUnitContents } = await import("../../src/hooks/daemon-service"); + const { stableExecPath } = await import("../../src/hooks/daemon-service"); const workerCmd = resolveWorkerCommand(); if (workerCmd) { - expect(workerCmd).toContain(process.execPath); + expect(workerCmd).toContain(stableExecPath()); expect(workerCmd).not.toMatch(/^node /); // Shell-quoted, because the daemon runs this through `sh -c`: an // unquoted `/Users/First Last/...` splits on its space and the worker // never starts. Ordinary on macOS, and more likely since execPath // (home-derived) replaced a bare `node`. - expect(workerCmd).toBe(`'${process.execPath}' '${resolve(process.env.FAILPROOFAI_PACKAGE_ROOT!, "dist", "worker.mjs")}'`); + expect(workerCmd).toBe(`'${stableExecPath()}' '${resolve(process.env.FAILPROOFAI_PACKAGE_ROOT!, "dist", "worker.mjs")}'`); // Environment= values containing a space must be quoted or systemd // rejects the unit — and this value always contains one. expect(systemdUnitContents("/opt/failproofaid", workerCmd)).toContain( @@ -648,6 +649,68 @@ describe("hooks/daemon-service", () => { await expect(ensureDaemonServiceCurrent()).resolves.toEqual({ outcome: "current" }); }); + it("needs a rewrite when the runtime or package its worker command names is gone", async () => { + // A Node upgrade deletes the runtime the unit names: the daemon stays up, + // its worker cannot start, and every hook is denied. `failproofai update` + // only repairs a definition this reports as needing it. + useScratchHome(); + setPlatform("linux"); + const unitDir = mkdtempSync(resolve(tmpdir(), "fpai-unit-dir-")); + const prevDir = process.env.FAILPROOFAI_SYSTEMD_DIR; + process.env.FAILPROOFAI_SYSTEMD_DIR = unitDir; + try { + const { daemonServiceNeedsUpgrade, systemdUnitContents } = await import("../../src/hooks/daemon-service"); + const { userInfo } = await import("node:os"); + const runtime = resolve(unitDir, "node"); + const script = resolve(unitDir, "worker.mjs"); + writeFileSync(runtime, ""); + writeFileSync(script, ""); + const unit = resolve(unitDir, `failproofaid@${userInfo().username}.service`); + const write = (worker: string) => + writeFileSync(unit, systemdUnitContents("/opt/failproofaid", worker, `'${runtime}' '${script}'`)); + + write(`'${runtime}' '${script}'`); + expect(daemonServiceNeedsUpgrade()).toBe(false); + write(`'${resolve(unitDir, "gone", "node")}' '${script}'`); + expect(daemonServiceNeedsUpgrade()).toBe(true); + // An operator's own command is never second-guessed. + write("node dist/worker.mjs"); + expect(daemonServiceNeedsUpgrade()).toBe(false); + } finally { + if (prevDir === undefined) delete process.env.FAILPROOFAI_SYSTEMD_DIR; + else process.env.FAILPROOFAI_SYSTEMD_DIR = prevDir; + rmSync(unitDir, { recursive: true, force: true }); + } + }); + + it("saves a stable link to the runtime when PATH has one, not a versioned path", async () => { + // Homebrew's execPath is .../Cellar/node//bin/node, which + // `brew upgrade node` deletes; /opt/homebrew/bin/node survives it. + const { stableExecPath } = await import("../../src/hooks/daemon-service"); + const { symlinkSync } = await import("node:fs"); + const root = mkdtempSync(resolve(tmpdir(), "fpai-runtime-")); + try { + const cellar = resolve(root, "Cellar", "node", "26.1.0", "bin"); + const stable = resolve(root, "bin"); + mkdirSync(cellar, { recursive: true }); + mkdirSync(stable, { recursive: true }); + writeFileSync(resolve(cellar, "node"), ""); + symlinkSync(resolve(cellar, "node"), resolve(stable, "node")); + + expect(stableExecPath(resolve(cellar, "node"), `/usr/bin:${stable}`)).toBe(resolve(stable, "node")); + // No link on PATH: execPath, as before. + expect(stableExecPath(resolve(cellar, "node"), "/usr/bin")).toBe(resolve(cellar, "node")); + // execPath itself on PATH first: kept. + expect(stableExecPath(resolve(cellar, "node"), `${cellar}:${stable}`)).toBe(resolve(cellar, "node")); + // A different file of the same name is not the same runtime. + rmSync(resolve(stable, "node")); + writeFileSync(resolve(stable, "node"), ""); + expect(stableExecPath(resolve(cellar, "node"), stable)).toBe(resolve(cellar, "node")); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + it("turns a systemd unit WITHOUT the variable into one WITH it, changing nothing else", async () => { useScratchHome(); delete process.env.FAILPROOFAI_WORKER_CMD; @@ -1288,6 +1351,28 @@ describe("refreshDaemonToCliVersion", () => { expect(installed).toBe(true); }); + it("still reinstalls a current, running daemon whose saved runtime is gone", async () => { + // A Node upgrade left the version right and the worker dead: "nothing to + // update" would leave every hook denied. + const { writeVersionFile } = await import("../../src/hooks/fp-config"); + const { version } = await import("../../package.json"); + const { installedBinaryPath } = await import("../../src/hooks/daemon-download"); + writeVersionFile({ daemon: version }); + mkdirSync(dirname(installedBinaryPath(version)), { recursive: true }); + writeFileSync(installedBinaryPath(version), "#!/bin/sh\n"); + let installed = false; + await svc.refreshDaemonToCliVersion({ + status: () => "running", + needsUpgrade: () => true, + install: async () => { + installed = true; + return { installed: true }; + }, + interactive: () => false, + }); + expect(installed).toBe(true); + }); + it("goes through the INSTALL, not a bare restart", async () => { // The property that was broken. The first version fetched the binary and then // rewrote the unit via `upgradedServiceDefinition`, which PRESERVES the diff --git a/crates/failproofaid/src/cloud_client.rs b/crates/failproofaid/src/cloud_client.rs index cf8b13f90..e7405ed69 100644 --- a/crates/failproofaid/src/cloud_client.rs +++ b/crates/failproofaid/src/cloud_client.rs @@ -1073,98 +1073,101 @@ pub fn spawn_maintenance( idle_interval: Duration, ) -> JoinHandle<()> { std::thread::spawn(move || { - let mut last_state: Option = None; - // `None` until the first successful resolution; then the identity seen - // last (itself `None` when not enrolled). - let mut last_identity: Option> = None; - // Set when the identity changed and the new one has not yet completed a - // reconcile. See below. - let mut floor_reset_pending = false; - while !shutdown.load(Ordering::Relaxed) { - if let (Ok(path), Some(home)) = (agent_roster::roster_path(), std::env::var_os("HOME")) - && let Err(err) = agent_roster::refresh(&path, Path::new(&home)) - { - eprintln!("[failproofaid] could not refresh agent inventory: {err}"); - } - let cloud = CloudClient::from_env_or_file(); - // A resolution ERROR is not a change of identity: broken - // credentials keep the last known-good deployment (see above), so - // they must neither reset the floor nor deactivate anything. - // `maintenance_tick` logs the error itself. - let identity = cloud - .as_ref() - .ok() - .map(|client| client.as_ref().map(CloudClient::identity)); - - // The rollback floor belongs to ONE cloud identity. The server - // numbers deployments per (org, machine), so after an org switch, a - // re-registration or a fresh enrolment the new identity legitimately - // answers with a lower deployment — often 0. Carrying the old floor - // across refused it ("deployment rollback from N to 0") until the - // daemon restarted, and the previous org's policies kept enforcing. - if let Some(identity) = identity - && last_identity.as_ref() != Some(&identity) - { - let first = last_identity.is_none(); - if !first { - store.reset_high_water(); - floor_reset_pending = identity.is_some(); - eprintln!( - "[failproofaid] cloud identity changed; the cloud-policy deployment floor starts again" - ); + crate::supervised("cloud policy sync", &shutdown, || { + let mut last_state: Option = None; + // `None` until the first successful resolution; then the identity seen + // last (itself `None` when not enrolled). + let mut last_identity: Option> = None; + // Set when the identity changed and the new one has not yet completed a + // reconcile. See below. + let mut floor_reset_pending = false; + while !shutdown.load(Ordering::Relaxed) { + if let (Ok(path), Some(home)) = + (agent_roster::roster_path(), std::env::var_os("HOME")) + && let Err(err) = agent_roster::refresh(&path, Path::new(&home)) + { + eprintln!("[failproofaid] could not refresh agent inventory: {err}"); } - // Enrolled → not enrolled (`--disconnect`, credentials removed): - // stop enforcing the departed org's policies. Removing only - // `active.json`, as the CLI does, is undone by the repair below, - // which rebuilds it from `desired-state.json`. - if !first && identity.is_none() { - match store.deactivate() { - Ok(true) => eprintln!( - "[failproofaid] cloud enrolment removed; cloud-managed policies deactivated" - ), - Ok(false) => {} - Err(err) => eprintln!( - "[failproofaid] could not deactivate cloud-managed policies: {err}" - ), + let cloud = CloudClient::from_env_or_file(); + // A resolution ERROR is not a change of identity: broken + // credentials keep the last known-good deployment (see above), so + // they must neither reset the floor nor deactivate anything. + // `maintenance_tick` logs the error itself. + let identity = cloud + .as_ref() + .ok() + .map(|client| client.as_ref().map(CloudClient::identity)); + + // The rollback floor belongs to ONE cloud identity. The server + // numbers deployments per (org, machine), so after an org switch, a + // re-registration or a fresh enrolment the new identity legitimately + // answers with a lower deployment — often 0. Carrying the old floor + // across refused it ("deployment rollback from N to 0") until the + // daemon restarted, and the previous org's policies kept enforcing. + if let Some(identity) = identity + && last_identity.as_ref() != Some(&identity) + { + let first = last_identity.is_none(); + if !first { + store.reset_high_water(); + floor_reset_pending = identity.is_some(); + eprintln!( + "[failproofaid] cloud identity changed; the cloud-policy deployment floor starts again" + ); + } + // Enrolled → not enrolled (`--disconnect`, credentials removed): + // stop enforcing the departed org's policies. Removing only + // `active.json`, as the CLI does, is undone by the repair below, + // which rebuilds it from `desired-state.json`. + if !first && identity.is_none() { + match store.deactivate() { + Ok(true) => eprintln!( + "[failproofaid] cloud enrolment removed; cloud-managed policies deactivated" + ), + Ok(false) => {} + Err(err) => eprintln!( + "[failproofaid] could not deactivate cloud-managed policies: {err}" + ), + } } + last_identity = Some(identity); } - last_identity = Some(identity); - } - // Log only on transition, so a disconnected machine does not print - // a line every 30 seconds forever. - let enrolled = matches!(cloud, Ok(Some(_))); - if last_state != Some(enrolled) { - eprintln!( - "[failproofaid] cloud-managed policy polling {}", - if enrolled { "enabled" } else { "disabled" } - ); - last_state = Some(enrolled); - } + // Log only on transition, so a disconnected machine does not print + // a line every 30 seconds forever. + let enrolled = matches!(cloud, Ok(Some(_))); + if last_state != Some(enrolled) { + eprintln!( + "[failproofaid] cloud-managed policy polling {}", + if enrolled { "enabled" } else { "disabled" } + ); + last_state = Some(enrolled); + } - // Re-reset until the new identity's first reconcile lands. If that - // poll fails, the repair re-applies the PREVIOUS identity's - // `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. - if maintenance_tick( - &store, - cloud, - floor_reset_pending, - &enrolment_withdrawn, - &oss_cleanup_applies, - ) { - floor_reset_pending = false; + // Re-reset until the new identity's first reconcile lands. If that + // poll fails, the repair re-applies the PREVIOUS identity's + // `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. + if maintenance_tick( + &store, + cloud, + floor_reset_pending, + &enrolment_withdrawn, + &oss_cleanup_applies, + ) { + floor_reset_pending = false; + } + wait_until_shutdown( + &shutdown, + if enrolled { + poll_interval + } else { + idle_interval + }, + ); } - wait_until_shutdown( - &shutdown, - if enrolled { - poll_interval - } else { - idle_interval - }, - ); - } + }) }) } diff --git a/crates/failproofaid/src/main.rs b/crates/failproofaid/src/main.rs index 9aa58110b..d9b9edf62 100644 --- a/crates/failproofaid/src/main.rs +++ b/crates/failproofaid/src/main.rs @@ -376,7 +376,7 @@ fn spawn_collector_manager( let interval = collector_config_poll_interval(); std::thread::Builder::new() .name("fpai-collect-mgr".to_string()) - .spawn(move || { + .spawn(move || supervised("the collector manager", &daemon_shutdown, || { // Wait until collection is enabled. A cheap config read each tick, // not the full task build, so an incomplete config waits quietly // rather than logging on every interval. @@ -618,13 +618,50 @@ fn spawn_collector_manager( if let Some(old) = draining.take() { old.join_with_flush(fpai_collect::DEFAULT_FLUSH_BUDGET); } - }) + })) .inspect_err(|err| { eprintln!("[failproofaid] could not start the collector manager: {err}; nothing is collected this run"); }) .ok() } +/// Run a long-lived lane's body until it returns, starting it again after a +/// panic. +/// +/// A panic on a plain thread ends that thread and nothing else: the daemon kept +/// answering hooks while collection or cloud policy sync had silently stopped, +/// and nothing short of a daemon restart brought it back. The panic message +/// itself is still printed by the default hook. +pub(crate) fn supervised(name: &str, shutdown: &AtomicBool, body: impl FnMut()) { + supervised_with_backoff(name, shutdown, Duration::from_secs(5), body); +} + +fn supervised_with_backoff( + name: &str, + shutdown: &AtomicBool, + backoff: Duration, + mut body: impl FnMut(), +) { + loop { + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(&mut body)) { + Ok(()) => return, + Err(_) => { + eprintln!( + "[failproofaid] {name} panicked; starting it again in {}s", + backoff.as_secs() + ); + let deadline = std::time::Instant::now() + backoff; + while std::time::Instant::now() < deadline { + if shutdown.load(Ordering::Relaxed) { + return; + } + std::thread::sleep(Duration::from_millis(20).min(backoff)); + } + } + } + } +} + /// Join a lane that may never have started. /// /// Every lane is optional by construction: when the OS refuses a thread the @@ -2162,6 +2199,37 @@ fn install_signal_handler(shutdown: Arc) { mod tests { use super::{Invocation, parse_args}; + mod supervision { + use super::super::supervised_with_backoff; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::Duration; + + #[test] + fn a_lane_that_panics_is_started_again() { + let shutdown = AtomicBool::new(false); + let mut runs = 0; + supervised_with_backoff("test lane", &shutdown, Duration::from_millis(1), || { + runs += 1; + if runs < 3 { + panic!("lane bug"); + } + }); + assert_eq!(runs, 3, "ran until it returned normally"); + } + + #[test] + fn shutdown_during_the_backoff_ends_it() { + let shutdown = AtomicBool::new(false); + let mut runs = 0; + supervised_with_backoff("test lane", &shutdown, Duration::from_secs(60), || { + runs += 1; + shutdown.store(true, Ordering::Relaxed); + panic!("lane bug"); + }); + assert_eq!(runs, 1); + } + } + fn argv(rest: &[&str]) -> Vec { std::iter::once("failproofaid".to_string()) .chain(rest.iter().map(|s| s.to_string())) diff --git a/crates/failproofaid/src/server.rs b/crates/failproofaid/src/server.rs index c72c8553f..0ff65aeae 100644 --- a/crates/failproofaid/src/server.rs +++ b/crates/failproofaid/src/server.rs @@ -245,6 +245,16 @@ impl Server { Err(err) if err.kind() == io::ErrorKind::WouldBlock => { std::thread::sleep(std::time::Duration::from_millis(20)); } + // Out of file descriptors, an aborted handshake, a signal: + // the listener is fine and the next accept can succeed. + // Returning here exited the daemon, and until the service + // manager restarted it every hook on the machine was denied. + Err(err) if is_transient_accept_error(&err) => { + log_connection_error(&io::Error::other(format!( + "accept failed, retrying: {err}" + ))); + std::thread::sleep(std::time::Duration::from_millis(100)); + } Err(err) => return Err(err), } } @@ -252,6 +262,20 @@ impl Server { } } +/// An `accept()` failure that says nothing about the listener itself. +fn is_transient_accept_error(err: &io::Error) -> bool { + matches!( + err.kind(), + io::ErrorKind::Interrupted + | io::ErrorKind::ConnectionAborted + | io::ErrorKind::ConnectionReset + | io::ErrorKind::OutOfMemory + ) || matches!( + err.raw_os_error(), + Some(libc::EMFILE | libc::ENFILE | libc::ENOBUFS | libc::ENOMEM) + ) +} + impl Drop for Server { fn drop(&mut self) { let _ = fs::remove_file(&self.socket_path); @@ -304,10 +328,36 @@ pub fn handle_connection(stream: UnixStream, worker: &Worker) -> io::Result<()> // write below gets a fresh budget for the same reason — a peer that has // waited through a slow evaluation must not then be denied its answer // because the read half used the clock up. + let started = std::time::Instant::now(); let response = dispatch(request, worker); + let took = started.elapsed(); let mut io = Deadline::new(&stream, CONNECTION_IO_TIMEOUT); - write_message(&mut io, &response) - .map_err(|e| io::Error::other(format!("failed to write response: {e}"))) + write_message(&mut io, &response).map_err(|e| { + if peer_hung_up(&e) { + // The client stopped waiting and its own fail-closed path already + // answered the call. On macOS this surfaced only as "Invalid + // argument (os error 22)": setsockopt on a socket the peer closed + // is EINVAL there. How long the evaluation took is the useful part. + io::Error::other(format!( + "the client closed the connection before its verdict was ready \ + (evaluation took {} ms)", + took.as_millis() + )) + } else { + io::Error::other(format!("failed to write response: {e}")) + } + }) +} + +/// Whether a write failed because the peer had already gone. +fn peer_hung_up(err: &fpai_ipc::FramingError) -> bool { + let fpai_ipc::FramingError::Io(io) = err else { + return false; + }; + matches!( + io.kind(), + io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset | io::ErrorKind::NotConnected + ) || io.raw_os_error() == Some(libc::EINVAL) } fn record_agent_sighting(integration: &str, settings_path: Option<&str>) { @@ -900,6 +950,40 @@ mod tests { ); } + #[test] + fn a_client_that_stopped_waiting_is_logged_as_such() { + let (mut client, server) = UnixStream::pair().unwrap(); + write_message( + &mut client, + &ClientMessage::Ping { + protocol_version: PROTOCOL_VERSION, + }, + ) + .unwrap(); + drop(client); + let worker = Worker::new(temp_socket_path("hung-up"), broken_worker_cmd()); + let err = handle_connection(server, &worker).expect_err("the peer is gone"); + assert!( + err.to_string() + .contains("closed the connection before its verdict"), + "got: {err}" + ); + } + + #[test] + fn running_out_of_descriptors_does_not_end_the_accept_loop() { + assert!(is_transient_accept_error(&io::Error::from_raw_os_error(24))); + assert!(is_transient_accept_error(&io::Error::from_raw_os_error(23))); + assert!(is_transient_accept_error(&io::Error::from( + io::ErrorKind::ConnectionAborted + ))); + // A listener that is genuinely broken still ends it. + assert!(!is_transient_accept_error(&io::Error::from_raw_os_error(9))); + assert!(!is_transient_accept_error(&io::Error::from( + io::ErrorKind::InvalidInput + ))); + } + #[test] fn versions_outside_the_supported_range_are_refused() { assert!(is_supported_protocol_version(MIN_PROTOCOL_VERSION)); diff --git a/crates/failproofaid/src/worker.rs b/crates/failproofaid/src/worker.rs index 9d001e9bd..bf4d4b4ca 100644 --- a/crates/failproofaid/src/worker.rs +++ b/crates/failproofaid/src/worker.rs @@ -76,6 +76,19 @@ pub struct PolicyEvaluation { /// in parallel by default, so multiple tests setting /// `FAILPROOFAI_WORKER_CMD` to different values would race. Tests instead /// construct a `WorkerCommand` directly via `shell`/`node`. +/// What an early exit status means when it has one obvious cause. 127 is the +/// shell's "command not found": the runtime or package saved in the service +/// definition is gone, typically after a Node upgrade, and only rewriting the +/// definition brings the worker back. +fn early_exit_hint(code: Option) -> &'static str { + match code { + Some(127) => { + "; the Node.js or failproofai path saved at install no longer exists, run `failproofai update`" + } + _ => "", + } +} + pub enum WorkerCommand { Shell(String), Node { script: PathBuf }, @@ -333,7 +346,8 @@ impl Worker { if let Ok(Some(status)) = child.try_wait() { report_spawn(reason, "exited_early", began); return Err(WorkerError::Io(io::Error::other(format!( - "worker process exited before creating its socket (status: {status})" + "worker process exited before creating its socket (status: {status}){}", + early_exit_hint(status.code()) )))); } if Instant::now() >= deadline { @@ -504,6 +518,22 @@ mod tests { /// as "a worker is listening". Before the readiness probe became a real /// `connect()`, this returned `Ok(())` immediately and every later /// request hit `ECONNREFUSED` on a dead socket. + /// A Node upgrade deletes the runtime the service names; the shell then + /// exits 127 and the error says what fixes it instead of only the status. + #[test] + fn a_worker_command_that_is_gone_names_the_fix() { + let socket_path = temp_socket_path("gone"); + let worker = Worker::new( + socket_path.clone(), + WorkerCommand::shell("'/nonexistent/fpai-test/node' '/nonexistent/worker.mjs'"), + ); + let err = worker + .call("PreToolUse", "claude", "{}", None, None) + .expect_err("a missing runtime cannot start a worker"); + assert!(err.to_string().contains("failproofai update"), "got: {err}"); + std::fs::remove_file(&socket_path).ok(); + } + #[test] fn a_stale_socket_file_is_not_mistaken_for_a_live_worker() { let socket_path = temp_socket_path("stale"); diff --git a/src/hooks/daemon-service.ts b/src/hooks/daemon-service.ts index aba926d68..e745a273e 100644 --- a/src/hooks/daemon-service.ts +++ b/src/hooks/daemon-service.ts @@ -14,6 +14,7 @@ import { mkdtempSync, readFileSync, readdirSync, + realpathSync, statSync, writeFileSync, unlinkSync, @@ -25,7 +26,7 @@ import { execFileSync } from "node:child_process"; import { hookLogWarn } from "./hook-logger"; import { downloadFailproofaidBinary, installFromNpmPackage, installedBinaryPath } from "./daemon-download"; import { logsDir } from "./fp-home"; -import { shellQuote } from "./shell-quote"; +import { shellQuote, shellQuotedWords } from "./shell-quote"; import { version } from "../../package.json"; import { readVersionFile, updateConfig, writeVersionFile } from "./fp-config"; @@ -258,7 +259,57 @@ export function resolveWorkerCommand(): string | null { // silently, on exactly the machines least likely to notice. execPath is // whatever runtime is executing this CLI right now (node for the published // bin, bun in a source checkout), absolute either way. - return `${shellQuote(process.execPath)} ${shellQuote(workerScript)}`; + return `${shellQuote(stableExecPath())} ${shellQuote(workerScript)}`; +} + +/** + * `process.execPath`, or a stable link to the same binary when one is on PATH. + * + * execPath is the RESOLVED path, and some installers version it: Homebrew's is + * `/opt/homebrew/Cellar/node//bin/node`, which `brew upgrade node` + * deletes, while `/opt/homebrew/bin/node` and the global packages under + * `/opt/homebrew/lib/node_modules` survive. A service saved with the Cellar + * path then ran nothing after the upgrade — the daemon stayed up, its worker + * could not start, and every hook was denied. A PATH entry that resolves to + * the same file is the same runtime today and still names one tomorrow. + * + * nvm has no such link (its global packages live inside each version), so + * execPath is kept there; `failproofai update` repairs a service whose saved + * path is gone (see {@link daemonServiceNeedsUpgrade}). + */ +export function stableExecPath( + execPath: string = process.execPath, + pathEnv: string = process.env.PATH ?? "", +): string { + let real: string; + try { + real = realpathSync(execPath); + } catch { + return execPath; + } + const name = execPath.split("/").pop() ?? ""; + for (const dir of pathEnv.split(":")) { + if (!dir.startsWith("/")) continue; + const candidate = resolve(dir, name); + if (candidate === execPath) return execPath; + try { + if (realpathSync(candidate) === real) return candidate; + } catch { + // Not there: try the next entry. + } + } + return execPath; +} + +/** + * Whether a saved `FAILPROOFAI_WORKER_CMD` / `FAILPROOFAI_CLI_CMD` names a + * file that no longer exists. Only a command this package wrote (quoted words) + * is judged; an operator's own command is never second-guessed. + */ +function savedCommandIsGone(command: string | null): boolean { + if (!command) return false; + const words = shellQuotedWords(command); + return words !== null && words.some((word) => word.startsWith("/") && !existsSync(word)); } /** @@ -288,7 +339,7 @@ export function resolveCliCommand(): string | null { if (!packageRoot) return null; const cliScript = resolve(packageRoot, "dist", "cli.mjs"); if (!existsSync(cliScript)) return null; - return `${shellQuote(process.execPath)} ${shellQuote(cliScript)}`; + return `${shellQuote(stableExecPath())} ${shellQuote(cliScript)}`; } @@ -1388,7 +1439,13 @@ function installedExecStart(definition: string): string | null { export function daemonServiceNeedsUpgrade(): boolean { const definition = readInstalledServiceDefinition(); if (definition === null) return false; - return !definition.includes("FAILPROOFAI_CLI_CMD"); + if (!definition.includes("FAILPROOFAI_CLI_CMD")) return true; + // A Node upgrade deleted the runtime (or package) the definition names: the + // daemon runs, its worker cannot start, and every hook is denied. + return ( + savedCommandIsGone(installedEnvValue(definition, "FAILPROOFAI_WORKER_CMD")) || + savedCommandIsGone(installedEnvValue(definition, "FAILPROOFAI_CLI_CMD")) + ); } /** @@ -1702,8 +1759,10 @@ export async function refreshDaemonToCliVersion( install?: () => Promise; prime?: () => boolean; interactive?: () => boolean; + needsUpgrade?: () => boolean; } = {}, ): Promise<{ ok: boolean; lines: string[] }> { + const needsUpgrade = deps.needsUpgrade ?? daemonServiceNeedsUpgrade; const status = deps.status ?? daemonServiceStatus; const install = deps.install ?? installDaemonService; const prime = deps.prime ?? primeElevation; @@ -1722,7 +1781,12 @@ export async function refreshDaemonToCliVersion( // `VERSION.daemon` is written only after an install succeeds, and the binary // it names must still be on disk. const recorded = readVersionFile()?.daemon; - if (current === "running" && recorded === version && existsSync(installedBinaryPath(version))) { + if ( + current === "running" && + recorded === version && + existsSync(installedBinaryPath(version)) && + !needsUpgrade() + ) { return { ok: true, lines: [`failproofaid ${version} is already installed and running; nothing to update.`] }; } diff --git a/src/hooks/shell-quote.ts b/src/hooks/shell-quote.ts index ac2fb2d24..56f6da95b 100644 --- a/src/hooks/shell-quote.ts +++ b/src/hooks/shell-quote.ts @@ -7,3 +7,18 @@ export function shellQuote(value: string): string { return `'${value.replace(/'/g, `'\\''`)}'`; } + +/** + * The words of a command built from {@link shellQuote}d parts, unquoted. Only + * that shape is understood; anything else (an operator's own + * `FAILPROOFAI_WORKER_CMD`) returns null, and callers leave it alone. + */ +export function shellQuotedWords(command: string): string[] | null { + const words: string[] = []; + const re = /\s*'((?:[^']|'\\'')*)'(?=\s|$)/y; + let match: RegExpExecArray | null; + while (re.lastIndex < command.length && (match = re.exec(command))) { + words.push(match[1].replace(/'\\''/g, "'")); + } + return words.length > 0 && command.slice(re.lastIndex).trim() === "" ? words : null; +} From 5ec52675c05ad3b7f25957755ecaa3570bd11bd0 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 14:25:28 +0530 Subject: [PATCH 07/41] feat(daemon): timestamped logs in ~/.failproofai/logs/daemon.log on every OS - The daemon's untimestamped `eprintln!("[failproofaid] ...")` lines are tracing events: one format, a timestamp, a level and a target on every line. Mixed with the tracing output in one file, half of a customer Mac mini's log could not be placed in time. Message text is unchanged, and lines a test pins verbatim keep their prefix. - Logs also go to ~/.failproofai/logs/daemon.log, size-rotated (10 MB, 3 kept), on Linux too, where they lived only in the journal. Stderr is unchanged, so journald, `systemctl status` and the e2e tests read the same lines. The log directory is created, its parents never: the run directory refuses parents it did not create. - On macOS, launchd's failproofaid.err.log, which nothing rotated, is copied and truncated in place at startup once past 10 MB (launchd holds it O_APPEND, so a rename would only move our own writes). --- CHANGELOG.md | 1 + crates/failproofaid/src/audit_lane.rs | 40 ++-- crates/failproofaid/src/cloud_client.rs | 61 +++--- crates/failproofaid/src/cloud_policies.rs | 11 +- crates/failproofaid/src/logfile.rs | 239 ++++++++++++++++++++++ crates/failproofaid/src/main.rs | 74 ++++--- crates/failproofaid/src/server.rs | 4 +- crates/failproofaid/src/telemetry.rs | 10 +- crates/failproofaid/src/worker.rs | 4 +- 9 files changed, 351 insertions(+), 93 deletions(-) create mode 100644 crates/failproofaid/src/logfile.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d067362d..e5dd9ca64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ - The daemon no longer exits on a transient `accept()` failure (out of file descriptors, an aborted connection), which left every hook denied until the service manager restarted it (#1023) - The collector manager and cloud policy sync restart after a panic instead of stopping silently while the daemon keeps answering hooks (#1023) - A hook client that stopped waiting before its verdict was ready is logged as that, with how long the evaluation took, instead of macOS's bare "Invalid argument (os error 22)" (#1023) +- failproofaid writes its log to `~/.failproofai/logs/daemon.log` on every OS (10 MB, 3 kept), as well as to stderr as before; every line carries a timestamp and level (its untimestamped `[failproofaid]` lines are now `tracing` events), and on macOS launchd's `failproofaid.err.log`, which nothing rotated, is bounded at startup (#1023) ## 1.0.15 — 2026-11-18 diff --git a/crates/failproofaid/src/audit_lane.rs b/crates/failproofaid/src/audit_lane.rs index ce66835f4..4bb94c69d 100644 --- a/crates/failproofaid/src/audit_lane.rs +++ b/crates/failproofaid/src/audit_lane.rs @@ -193,8 +193,8 @@ fn load_state(path: &Path) -> Option { match serde_json::from_str::(&text) { Ok(state) if state.schema == SCHEMA => Some(state), Ok(state) => { - eprintln!( - "[failproofaid] audit schedule {} has schema {} (expected {}); re-seeding", + tracing::info!( + "audit schedule {} has schema {} (expected {}); re-seeding", path.display(), state.schema, SCHEMA @@ -202,8 +202,8 @@ fn load_state(path: &Path) -> Option { None } Err(err) => { - eprintln!( - "[failproofaid] audit schedule {} is unreadable ({err}); re-seeding", + tracing::info!( + "audit schedule {} is unreadable ({err}); re-seeding", path.display() ); None @@ -394,13 +394,15 @@ pub fn spawn(shutdown: Arc) -> Option> { // would still say the scan is on and nothing would ever run // again. Catching it keeps the next tick alive. if std::panic::catch_unwind(AssertUnwindSafe(|| lane.tick(&shutdown))).is_err() { - eprintln!("[failproofaid] audit lane panicked; it will try again next tick"); + tracing::warn!("audit lane panicked; it will try again next tick"); } wait_until_shutdown(&shutdown, poll); } }) .inspect_err(|err| { - eprintln!("[failproofaid] could not start the audit lane: {err}; scheduled audits are off this run"); + tracing::warn!( + "could not start the audit lane: {err}; scheduled audits are off this run" + ); }) .ok() } @@ -480,8 +482,8 @@ impl Lane { // is Restart=on-failure — so any restart would launch // another full scan, and a restart loop would launch them // back to back forever. - eprintln!( - "[failproofaid] skipping the scheduled audit: could not persist the \ + tracing::warn!( + "skipping the scheduled audit: could not persist the \ schedule first ({err})" ); return; @@ -498,9 +500,7 @@ impl Lane { next.next_due_at_ms = now.saturating_add(MIN_ATTEMPT_GAP.as_millis() as i64); next.last_exit_code = Some(EXIT_LOCK_HELD); - eprintln!( - "[failproofaid] scheduled audit skipped: another audit holds the lock" - ); + tracing::warn!("scheduled audit skipped: another audit holds the lock"); } Outcome::Exited(0) => { // Read the clock again: the scan itself took real time, and @@ -511,21 +511,21 @@ impl Lane { } Outcome::Exited(code) => { next.last_exit_code = Some(code); - eprintln!("[failproofaid] scheduled audit failed (exit {code})"); + tracing::warn!("scheduled audit failed (exit {code})"); } Outcome::Signalled => { next.last_exit_code = None; - eprintln!("[failproofaid] scheduled audit was killed before it finished"); + tracing::warn!("scheduled audit was killed before it finished"); } Outcome::NotStarted(err) => { next.last_exit_code = None; - eprintln!("[failproofaid] could not start the scheduled audit: {err}"); + tracing::warn!("could not start the scheduled audit: {err}"); } } // Best effort: the schedule that matters was already persisted // above, so failing here costs a status readout, not a cadence. if let Err(err) = save_state(&path, &next) { - eprintln!("[failproofaid] could not record the audit outcome: {err}"); + tracing::warn!("could not record the audit outcome: {err}"); } } } @@ -541,7 +541,7 @@ impl Lane { return; } self.announced = Some(state); - eprintln!("[failproofaid] {message}"); + tracing::info!("{message}"); } } @@ -601,13 +601,13 @@ fn run_audit_child(cli_cmd: &str, shutdown: &AtomicBool) -> Outcome { // scan on every restart — and on macOS nothing reaps it at all, so a // scan would outlive the daemon holding the audit lock. if shutdown.load(Ordering::Relaxed) { - eprintln!("[failproofaid] stopping the scheduled audit for shutdown"); + tracing::info!("stopping the scheduled audit for shutdown"); kill_process_group(&mut child); return Outcome::Signalled; } if started.elapsed() > CHILD_TIMEOUT { - eprintln!( - "[failproofaid] scheduled audit exceeded {}s; killing it", + tracing::warn!( + "scheduled audit exceeded {}s; killing it", CHILD_TIMEOUT.as_secs() ); kill_process_group(&mut child); @@ -670,7 +670,7 @@ fn spawn_audit_child(cli_cmd: &str) -> io::Result { fn forward_child_output(label: &'static str, pipe: impl io::Read) { use std::io::BufRead; for line in io::BufReader::new(pipe).lines().map_while(Result::ok) { - eprintln!("[failproofaid] audit {label}: {line}"); + tracing::info!("audit {label}: {line}"); } } diff --git a/crates/failproofaid/src/cloud_client.rs b/crates/failproofaid/src/cloud_client.rs index e7405ed69..df68edea7 100644 --- a/crates/failproofaid/src/cloud_client.rs +++ b/crates/failproofaid/src/cloud_client.rs @@ -404,7 +404,7 @@ fn record_daemon_errors(store: &PolicyStore, errors: Vec) { return; } if let Err(err) = store.write_daemon_policy_errors(&errors) { - eprintln!("[failproofaid] could not record the cloud policy error state: {err}"); + tracing::warn!("could not record the cloud policy error state: {err}"); } } @@ -1086,7 +1086,7 @@ pub fn spawn_maintenance( (agent_roster::roster_path(), std::env::var_os("HOME")) && let Err(err) = agent_roster::refresh(&path, Path::new(&home)) { - eprintln!("[failproofaid] could not refresh agent inventory: {err}"); + tracing::warn!("could not refresh agent inventory: {err}"); } let cloud = CloudClient::from_env_or_file(); // A resolution ERROR is not a change of identity: broken @@ -1111,8 +1111,8 @@ pub fn spawn_maintenance( if !first { store.reset_high_water(); floor_reset_pending = identity.is_some(); - eprintln!( - "[failproofaid] cloud identity changed; the cloud-policy deployment floor starts again" + tracing::info!( + "cloud identity changed; the cloud-policy deployment floor starts again" ); } // Enrolled → not enrolled (`--disconnect`, credentials removed): @@ -1121,13 +1121,13 @@ pub fn spawn_maintenance( // which rebuilds it from `desired-state.json`. if !first && identity.is_none() { match store.deactivate() { - Ok(true) => eprintln!( - "[failproofaid] cloud enrolment removed; cloud-managed policies deactivated" + Ok(true) => tracing::info!( + "cloud enrolment removed; cloud-managed policies deactivated" ), Ok(false) => {} - Err(err) => eprintln!( - "[failproofaid] could not deactivate cloud-managed policies: {err}" - ), + Err(err) => { + tracing::warn!("could not deactivate cloud-managed policies: {err}") + } } } last_identity = Some(identity); @@ -1137,8 +1137,8 @@ pub fn spawn_maintenance( // a line every 30 seconds forever. let enrolled = matches!(cloud, Ok(Some(_))); if last_state != Some(enrolled) { - eprintln!( - "[failproofaid] cloud-managed policy polling {}", + tracing::info!( + "cloud-managed policy polling {}", if enrolled { "enabled" } else { "disabled" } ); last_state = Some(enrolled); @@ -1216,7 +1216,7 @@ fn maintenance_tick( reconciled } Err(err) => { - eprintln!("[failproofaid] cloud enrolment error: {err}"); + tracing::warn!("cloud enrolment error: {err}"); repair(store, &|| false); false } @@ -1224,12 +1224,12 @@ fn maintenance_tick( if back_on_oss() { match store.clear_deployment() { Ok(0) => {} - Ok(removed) => eprintln!( - "[failproofaid] this machine is disconnected from FailproofAI Cloud; \ + Ok(removed) => tracing::warn!( + "this machine is disconnected from FailproofAI Cloud; \ removed {removed} leftover cloud policy file(s)" ), - Err(err) => eprintln!( - "[failproofaid] could not remove the cloud policy files of a disconnected machine: {err}" + Err(err) => tracing::warn!( + "could not remove the cloud policy files of a disconnected machine: {err}" ), } } @@ -1240,7 +1240,7 @@ fn maintenance_tick( fn repair(store: &PolicyStore, withdrawn: &dyn Fn() -> bool) { if let Err(err) = store.repair_active_from_cache_unless(withdrawn) { - eprintln!("[failproofaid] cloud policy integrity error: {err}"); + tracing::warn!("cloud policy integrity error: {err}"); } } @@ -1259,18 +1259,18 @@ fn report_and_reclaim(cloud: &CloudClient, path: &Path, home: &Path, roster: &Ag } Ok(_) => return, Err(err) => { - eprintln!("[failproofaid] {err}"); + tracing::info!("{err}"); return; } }; match agent_roster::reclaim(path, home, &reclaimable) { Ok(next) if next.generation != roster.generation => { if let Err(err) = cloud.report_agent_roster(&next, false) { - eprintln!("[failproofaid] {err}"); + tracing::info!("{err}"); } } Ok(_) => agent_roster::capacity_stalled(path, roster.generation), - Err(err) => eprintln!("[failproofaid] could not reclaim agent roster capacity: {err}"), + Err(err) => tracing::warn!("could not reclaim agent roster capacity: {err}"), } } @@ -1295,7 +1295,7 @@ fn poll_once_guarded( let active = match store.read_active() { Ok(active) => Some(active), Err(err) => { - eprintln!("[failproofaid] could not read the active deployment to report it: {err}"); + tracing::warn!("could not read the active deployment to report it: {err}"); None } }; @@ -1328,9 +1328,11 @@ fn poll_once_guarded( ) { Ok(outcome) => { if outcome.activated || outcome.downloaded > 0 || outcome.repaired > 0 { - eprintln!( - "[failproofaid] cloud policy deployment {} active (downloaded {}, repaired {})", - outcome.deployment, outcome.downloaded, outcome.repaired + tracing::info!( + "cloud policy deployment {} active (downloaded {}, repaired {})", + outcome.deployment, + outcome.downloaded, + outcome.repaired ); } record_daemon_errors(store, Vec::new()); @@ -1340,14 +1342,14 @@ fn poll_once_guarded( // Nothing was written, and nothing is recorded either: an // error state would describe a deployment this machine no // longer has. - eprintln!( - "[failproofaid] this machine was disconnected while a poll was in flight; \ + tracing::warn!( + "this machine was disconnected while a poll was in flight; \ its result was discarded" ); false } Err(err) => { - eprintln!("[failproofaid] cloud policy reconcile error: {err}"); + tracing::warn!("cloud policy reconcile error: {err}"); if !transient_fetch_failure(&err) && !withdrawn() { record_daemon_errors( store, @@ -1363,10 +1365,7 @@ fn poll_once_guarded( } } Err(failure) => { - eprintln!( - "[failproofaid] cloud policy poll error: {}", - failure.message - ); + tracing::warn!("cloud policy poll error: {}", failure.message); // A payload this daemon refused is reported; a transport failure is // not, and leaves the recorded state as it was. if failure.reportable && !withdrawn() { diff --git a/crates/failproofaid/src/cloud_policies.rs b/crates/failproofaid/src/cloud_policies.rs index 65cad1415..ff42b5bc8 100644 --- a/crates/failproofaid/src/cloud_policies.rs +++ b/crates/failproofaid/src/cloud_policies.rs @@ -679,10 +679,11 @@ impl PolicyStore { if let Some(active) = &previous && active.deployment > desired.deployment { - eprintln!( - "[failproofaid] local active deployment {} is ahead of the server's {}; \ + tracing::warn!( + "local active deployment {} is ahead of the server's {}; \ taking the server's state (the local pointer is not authority)", - active.deployment, desired.deployment + active.deployment, + desired.deployment ); } @@ -1053,9 +1054,9 @@ pub fn spawn_integrity_monitor( match store.repair_active_from_cache() { Ok(0) => {} Ok(repaired) => { - eprintln!("[failproofaid] repaired {repaired} cloud-managed policy artifact(s)") + tracing::info!("repaired {repaired} cloud-managed policy artifact(s)") } - Err(err) => eprintln!("[failproofaid] cloud policy integrity error: {err}"), + Err(err) => tracing::warn!("cloud policy integrity error: {err}"), } let deadline = Instant::now() + interval; diff --git a/crates/failproofaid/src/logfile.rs b/crates/failproofaid/src/logfile.rs new file mode 100644 index 000000000..8982fcf4d --- /dev/null +++ b/crates/failproofaid/src/logfile.rs @@ -0,0 +1,239 @@ +//! The daemon's own log file: `~/.failproofai/logs/daemon.log`, size-rotated. +//! +//! Stderr still goes where it always has (journald on Linux, launchd's +//! `failproofaid.err.log` on macOS), unchanged, because `systemctl status`, the +//! e2e tests and every support recipe read it. This file exists so that every +//! machine has its log in ONE place under `~/.failproofai` — on Linux it +//! otherwise lived only in the journal — bounded in size, and in a form that +//! can be collected for support. +//! +//! Never fatal: a home that cannot hold a log must not stop enforcement, so +//! any failure here simply leaves logging on stderr alone. + +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +/// Rotate once the active file passes this. +pub const MAX_BYTES: u64 = 10 * 1024 * 1024; +/// Rotated files kept beside the active one: `daemon.log.1` … `.N`. +pub const KEEP: usize = 3; + +struct Inner { + path: PathBuf, + max_bytes: u64, + keep: usize, + file: Option, + size: u64, +} + +impl Inner { + fn open(&mut self) { + self.file = OpenOptions::new() + .create(true) + .append(true) + .open(&self.path) + .ok(); + self.size = fs::metadata(&self.path).map(|m| m.len()).unwrap_or(0); + } + + fn rotate(&mut self) { + self.file = None; + rotate_file(&self.path, self.keep); + self.open(); + } + + fn write(&mut self, buf: &[u8]) { + if self.size >= self.max_bytes { + self.rotate(); + } + if let Some(file) = self.file.as_mut() + && file.write_all(buf).is_ok() + { + self.size += buf.len() as u64; + } + } +} + +/// `path` → `path.1` → … → `path.`, dropping the oldest. Missing files +/// are skipped; a failed rename leaves the rest as they were. +pub fn rotate_file(path: &Path, keep: usize) { + let numbered = |n: usize| PathBuf::from(format!("{}.{n}", path.display())); + if keep == 0 { + let _ = fs::remove_file(path); + return; + } + let _ = fs::remove_file(numbered(keep)); + for n in (1..keep).rev() { + let _ = fs::rename(numbered(n), numbered(n + 1)); + } + let _ = fs::rename(path, numbered(1)); +} + +/// A cloneable, rotating append-only writer for `tracing_subscriber`. +#[derive(Clone)] +pub struct RotatingFile(Arc>); + +impl RotatingFile { + /// Creates the log's own directory, never its parents: a missing + /// failproofai home is not this module's to create (the run directory + /// checks the permissions of directories it did not make itself). + pub fn open(path: PathBuf, max_bytes: u64, keep: usize) -> Option { + let dir = path.parent()?; + if !dir.is_dir() { + fs::create_dir(dir).ok()?; + } + let mut inner = Inner { + path, + max_bytes, + keep, + file: None, + size: 0, + }; + inner.open(); + inner.file.as_ref()?; + Some(RotatingFile(Arc::new(Mutex::new(inner)))) + } +} + +impl Write for RotatingFile { + fn write(&mut self, buf: &[u8]) -> io::Result { + // Poison-tolerant: a panic mid-write elsewhere must not end logging. + let mut inner = self.0.lock().unwrap_or_else(|e| e.into_inner()); + inner.write(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + let mut inner = self.0.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(file) = inner.file.as_mut() { + file.flush()?; + } + Ok(()) + } +} + +impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for RotatingFile { + type Writer = RotatingFile; + fn make_writer(&'a self) -> Self::Writer { + self.clone() + } +} + +/// Rotate a log some other process appends to (launchd's stderr file on macOS) +/// when it has grown past `max_bytes`. Called once at startup, before this +/// process writes to it: launchd opened it `O_APPEND` for our own stderr, so a +/// rename moves our fd's writes into `.1` — which is why the old file is +/// copied and then TRUNCATED in place instead. +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +pub fn bound_inherited_log(path: &Path, max_bytes: u64, keep: usize) { + let Ok(meta) = fs::metadata(path) else { + return; + }; + if meta.len() <= max_bytes { + return; + } + let first = PathBuf::from(format!("{}.1", path.display())); + let _ = fs::remove_file(PathBuf::from(format!("{}.{keep}", path.display()))); + for n in (1..keep).rev() { + let _ = fs::rename( + PathBuf::from(format!("{}.{n}", path.display())), + PathBuf::from(format!("{}.{}", path.display(), n + 1)), + ); + } + if fs::copy(path, &first).is_ok() { + let _ = OpenOptions::new() + .write(true) + .open(path) + .and_then(|f| f.set_len(0)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "fpai-logfile-{name}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn rotates_past_the_limit_and_keeps_only_the_newest() { + let dir = temp_dir("rotate"); + let path = dir.join("daemon.log"); + let mut log = RotatingFile::open(path.clone(), 10, 2).unwrap(); + for line in [ + "aaaaaaaaaa\n", + "bbbbbbbbbb\n", + "cccccccccc\n", + "dddddddddd\n", + ] { + log.write_all(line.as_bytes()).unwrap(); + } + assert_eq!(fs::read_to_string(&path).unwrap(), "dddddddddd\n"); + assert_eq!( + fs::read_to_string(dir.join("daemon.log.1")).unwrap(), + "cccccccccc\n" + ); + assert_eq!( + fs::read_to_string(dir.join("daemon.log.2")).unwrap(), + "bbbbbbbbbb\n" + ); + assert!( + !dir.join("daemon.log.3").exists(), + "only `keep` rotations remain" + ); + fs::remove_dir_all(dir).ok(); + } + + #[test] + fn a_missing_home_is_never_created() { + let dir = temp_dir("no-home"); + let home = dir.join("home"); + assert!(RotatingFile::open(home.join("logs").join("daemon.log"), 10, 1).is_none()); + assert!(!home.exists()); + fs::remove_dir_all(dir).ok(); + } + + #[test] + fn an_unwritable_home_is_not_fatal() { + assert!(RotatingFile::open(PathBuf::from("/proc/fpai-no/daemon.log"), 10, 1).is_none()); + } + + #[test] + fn an_oversized_inherited_log_is_kept_once_and_truncated_in_place() { + let dir = temp_dir("inherited"); + let path = dir.join("failproofaid.err.log"); + fs::write(&path, "x".repeat(50)).unwrap(); + // Another process's O_APPEND handle on the same file, as launchd holds. + let mut appender = OpenOptions::new().append(true).open(&path).unwrap(); + bound_inherited_log(&path, 20, 2); + appender.write_all(b"after\n").unwrap(); + assert_eq!( + fs::read_to_string(dir.join("failproofaid.err.log.1")) + .unwrap() + .len(), + 50 + ); + assert_eq!( + fs::read_to_string(&path).unwrap(), + "after\n", + "the live handle keeps writing here" + ); + + // A small one is left alone. + bound_inherited_log(&path, 20, 2); + assert_eq!(fs::read_to_string(&path).unwrap(), "after\n"); + fs::remove_dir_all(dir).ok(); + } +} diff --git a/crates/failproofaid/src/main.rs b/crates/failproofaid/src/main.rs index d9b9edf62..0c9ed553e 100644 --- a/crates/failproofaid/src/main.rs +++ b/crates/failproofaid/src/main.rs @@ -5,6 +5,7 @@ mod backfill; mod cloud_client; pub mod cloud_policies; mod lock; +mod logfile; mod paths; mod server; mod telemetry; @@ -111,13 +112,30 @@ fn main() { /// Writes to stderr, which is where the daemon's existing `eprintln!` output /// already goes and what systemd/launchd capture. `RUST_LOG` overrides the /// default level. +/// +/// Also to `~/.failproofai/logs/daemon.log` (see `logfile.rs`), and on macOS the +/// launchd stderr file is bounded first, since nothing else ever rotates it. fn init_logging() { use tracing_subscriber::EnvFilter; + use tracing_subscriber::fmt::writer::MakeWriterExt; let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); - let _ = tracing_subscriber::fmt() - .with_env_filter(filter) - .with_writer(std::io::stderr) - .try_init(); + let logs = paths::failproofai_home().ok().map(|home| home.join("logs")); + #[cfg(target_os = "macos")] + if let Some(logs) = &logs { + logfile::bound_inherited_log( + &logs.join("failproofaid.err.log"), + logfile::MAX_BYTES, + logfile::KEEP, + ); + } + let file = logs.and_then(|logs| { + logfile::RotatingFile::open(logs.join("daemon.log"), logfile::MAX_BYTES, logfile::KEEP) + }); + let builder = tracing_subscriber::fmt().with_env_filter(filter); + let _ = match file { + Some(file) => builder.with_writer(std::io::stderr.and(file)).try_init(), + None => builder.with_writer(std::io::stderr).try_init(), + }; } fn run() -> Result<(), Box> { @@ -233,7 +251,7 @@ fn run() -> Result<(), Box> { return Err(err.into()); } }; - eprintln!("[failproofaid] listening on {}", socket_path.display()); + tracing::info!("listening on {}", socket_path.display()); let run_result = srv.run_until(shutdown); @@ -620,7 +638,7 @@ fn spawn_collector_manager( } })) .inspect_err(|err| { - eprintln!("[failproofaid] could not start the collector manager: {err}; nothing is collected this run"); + tracing::warn!("could not start the collector manager: {err}; nothing is collected this run"); }) .ok() } @@ -646,8 +664,8 @@ fn supervised_with_backoff( match std::panic::catch_unwind(std::panic::AssertUnwindSafe(&mut body)) { Ok(()) => return, Err(_) => { - eprintln!( - "[failproofaid] {name} panicked; starting it again in {}s", + tracing::warn!( + "{name} panicked; starting it again in {}s", backoff.as_secs() ); let deadline = std::time::Instant::now() + backoff; @@ -982,7 +1000,7 @@ fn collector_tasks(config: Option) -> Vec home, Err(err) => { - eprintln!("[failproofaid] collector disabled: {err}"); + tracing::warn!("collector disabled: {err}"); return Vec::new(); } }; @@ -990,7 +1008,7 @@ fn collector_tasks(config: Option) -> Vec cfg, None => { - eprintln!("[failproofaid] collector disabled: unreadable configuration"); + tracing::warn!("collector disabled: unreadable configuration"); return Vec::new(); } }; @@ -1003,9 +1021,7 @@ fn collector_tasks(config: Option) -> Vec) -> Vec std::sync::Arc::new(u), Err(err) => { - eprintln!("[failproofaid] collector disabled: {err}"); + tracing::warn!("collector disabled: {err}"); return Vec::new(); } }; @@ -1037,16 +1053,19 @@ fn collector_tasks(config: Option) -> Vec {}", - cfg.settings.sessions, cfg.settings.hooks, cfg.settings.hooks_verbosity, ingest.url, + tracing::info!( + "collector enabled: sessions={} hooks={} ({:?}) -> {}", + cfg.settings.sessions, + cfg.settings.hooks, + cfg.settings.hooks_verbosity, + ingest.url, ); // Said on every build, and OUTSIDE the `sessions` block: the selection also // scopes every backfill, so a misspelt id matters on a decisions-only // machine too, and each of these is otherwise mentioned nowhere. if let Some(line) = selection_warning(&cfg.agents) { - eprintln!("{line}"); + tracing::info!("{line}"); } // One `Delivery` shared by both tasks, so they share an upload semaphore @@ -1159,8 +1178,8 @@ fn collector_tasks(config: Option) -> Vec) -> Vec) -> Vec) -> Vec) { integration, std::path::Path::new(settings_path), ) { - eprintln!("[failproofaid] could not record an agent hook sighting: {err}"); + tracing::warn!("could not record an agent hook sighting: {err}"); } } diff --git a/crates/failproofaid/src/telemetry.rs b/crates/failproofaid/src/telemetry.rs index 85f2283db..e82782c31 100644 --- a/crates/failproofaid/src/telemetry.rs +++ b/crates/failproofaid/src/telemetry.rs @@ -201,7 +201,7 @@ impl Lane { ring.pop_front(); self.dropped.fetch_add(1, Ordering::Relaxed); if !self.warned_dropped.swap(true, Ordering::Relaxed) { - eprintln!("[failproofaid] telemetry buffer is full; dropping the oldest events"); + tracing::warn!("telemetry buffer is full; dropping the oldest events"); } } ring.push_back(event); @@ -754,15 +754,13 @@ pub fn spawn(shutdown: Arc) -> Option> { })) .is_err() { - eprintln!("[failproofaid] telemetry lane panicked; continuing next tick"); + tracing::warn!("telemetry lane panicked; continuing next tick"); } wait_until_shutdown(&shutdown, interval); } }) .inspect_err(|err| { - eprintln!( - "[failproofaid] could not start the telemetry lane: {err}; this run reports nothing" - ); + tracing::warn!("could not start the telemetry lane: {err}; this run reports nothing"); }) .ok() } @@ -883,7 +881,7 @@ fn send_pending( // One line, at the point the events are actually lost, rather than one // per failed attempt: a machine with no route to PostHog would otherwise // print a line a minute forever. - eprintln!("[failproofaid] telemetry could not be delivered; dropping this batch"); + tracing::warn!("telemetry could not be delivered; dropping this batch"); return; } lane.requeue(batch); diff --git a/crates/failproofaid/src/worker.rs b/crates/failproofaid/src/worker.rs index bf4d4b4ca..bf8243623 100644 --- a/crates/failproofaid/src/worker.rs +++ b/crates/failproofaid/src/worker.rs @@ -200,7 +200,7 @@ fn spawn_forwarder( fn forward_worker_output(label: &'static str, pipe: impl io::Read) { use std::io::BufRead; for line in io::BufReader::new(pipe).lines().map_while(Result::ok) { - eprintln!("[failproofaid] worker {label}: {line}"); + tracing::info!("worker {label}: {line}"); } } @@ -379,7 +379,7 @@ impl Worker { /// next real request anyway. pub fn warm(&self) { if let Err(err) = self.ensure_started() { - eprintln!("[failproofaid] worker warm-up failed (will retry on first request): {err}"); + tracing::warn!("worker warm-up failed (will retry on first request): {err}"); } } From ec2464c070a63995007b9e152567652a3232a1b8 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 14:28:22 +0530 Subject: [PATCH 08/41] feat(daemon): report daemon/CLI version, OS and arch on every policy poll The cloud saw a machine's failproofai version only as the ingest header X-Failproofai-Collector-Version, which it logs and does not store, so it could not say which machines run what or filter by it. The desired-state poll, which every enrolled machine makes each poll interval and which the server already turns into a per-machine check-in, now carries daemonVersion, cliVersion (from ~/.failproofai/VERSION), os and arch. They are optional query parameters: DesiredQuery is not deny_unknown_fields, so today's server ignores them until it stores them. Cloud and ingest requests also send User-Agent: failproofaid/. --- CHANGELOG.md | 1 + crates/failproofaid/src/cloud_client.rs | 42 +++++++++++++++++++++++++ crates/fpai-collect/src/uploader.rs | 1 + 3 files changed, 44 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e5dd9ca64..51bf78abf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ - The collector manager and cloud policy sync restart after a panic instead of stopping silently while the daemon keeps answering hooks (#1023) - A hook client that stopped waiting before its verdict was ready is logged as that, with how long the evaluation took, instead of macOS's bare "Invalid argument (os error 22)" (#1023) - failproofaid writes its log to `~/.failproofai/logs/daemon.log` on every OS (10 MB, 3 kept), as well as to stderr as before; every line carries a timestamp and level (its untimestamped `[failproofaid]` lines are now `tracing` events), and on macOS launchd's `failproofaid.err.log`, which nothing rotated, is bounded at startup (#1023) +- failproofaid tells FailproofAI Cloud what each machine runs: its policy poll carries `daemonVersion`, `cliVersion`, `os` and `arch` (optional parameters a server that predates them ignores), and every Cloud and ingest request sends `User-Agent: failproofaid/` (#1023) ## 1.0.15 — 2026-11-18 diff --git a/crates/failproofaid/src/cloud_client.rs b/crates/failproofaid/src/cloud_client.rs index df68edea7..b3cf2c766 100644 --- a/crates/failproofaid/src/cloud_client.rs +++ b/crates/failproofaid/src/cloud_client.rs @@ -770,6 +770,7 @@ impl CloudClient { return Err("FAILPROOFAI_MACHINE_ID cannot be empty".to_string()); } let client = Client::builder() + .user_agent(concat!("failproofaid/", env!("CARGO_PKG_VERSION"))) .connect_timeout(Duration::from_secs(5)) .timeout(Duration::from_secs(15)) .build() @@ -856,6 +857,13 @@ impl CloudClient { if let Some(errors) = policy_errors { url.query_pairs_mut().append_pair("policyErrors", errors); } + // What this machine runs, on the one call every enrolled machine makes + // every poll interval: the cloud had the version only as an ingest + // header it logged, so "which machines are behind" had no answer. + // Additive for the same reason as above. + for (key, value) in machine_facts() { + url.query_pairs_mut().append_pair(key, &value); + } self.client .get(url) .bearer_auth(&self.token) @@ -1399,6 +1407,23 @@ fn wait_until_shutdown(shutdown: &AtomicBool, interval: Duration) { } } +/// `daemonVersion`, `cliVersion` (when the home's VERSION file names one), `os` +/// and `arch`, for the desired-state poll. +fn machine_facts() -> Vec<(&'static str, String)> { + let mut facts = vec![("daemonVersion", env!("CARGO_PKG_VERSION").to_string())]; + let cli = crate::paths::failproofai_home() + .ok() + .and_then(|home| std::fs::read_to_string(crate::paths::version_file_path(&home)).ok()) + .and_then(|text| serde_json::from_str::(&text).ok()) + .and_then(|doc| doc.get("cli")?.as_str().map(str::to_string)) + .filter(|v| !v.is_empty() && v.len() <= 64); + if let Some(cli) = cli { + facts.push(("cliVersion", cli)); + } + facts.push(("os", std::env::consts::OS.to_string())); + facts.push(("arch", std::env::consts::ARCH.to_string())); + facts +} #[cfg(test)] mod tests { use super::*; @@ -1641,6 +1666,23 @@ mod tests { request.contains("machineId=machine-1"), "the existing parameter must survive: {request}" ); + // What the machine runs rides on every poll, so the cloud can say + // which machines are behind. + assert!( + request.contains(&format!("daemonVersion={}", env!("CARGO_PKG_VERSION"))), + "{request}" + ); + assert!( + request.contains(&format!("os={}", std::env::consts::OS)), + "{request}" + ); + assert!( + request.to_ascii_lowercase().contains(&format!( + "user-agent: failproofaid/{}", + env!("CARGO_PKG_VERSION") + )), + "{request}" + ); if expected { assert!( request.contains("appliedDeployment=7"), diff --git a/crates/fpai-collect/src/uploader.rs b/crates/fpai-collect/src/uploader.rs index ea4a0d15b..a1530474b 100644 --- a/crates/fpai-collect/src/uploader.rs +++ b/crates/fpai-collect/src/uploader.rs @@ -234,6 +234,7 @@ pub fn is_credential_status(status: u16) -> bool { impl Uploader { pub fn new(url: String, key: String, failed_dir: PathBuf) -> Result { let client = reqwest::Client::builder() + .user_agent(concat!("failproofaid/", env!("CARGO_PKG_VERSION"))) .connect_timeout(Duration::from_secs(10)) .read_timeout(DEFAULT_READ_TIMEOUT) // Backstop only — see the module docs. Large multiple of the read From 26057871b3bddfa2e6595dfcce60d6fe57773c1a Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 14:45:14 +0530 Subject: [PATCH 09/41] feat(collector): join hook events to their tool call; stamp hook start on arrival Cloud orders a session's events by timestamp, and hook events and transcript events come from two writers with nothing in common below the session id. A hook row was stamped when its evaluation ENDED, so the start leg sorted late by the whole evaluation, and the agent's own id for the call (`tool_use_id` in Claude's payload) was dropped when the row was written, so no hook could be tied to the tool call it governed. - Hook rows record `toolCallId` (Claude, Devin, Factory, Pi, Hermes' nested id) and `startedAt`. The Pi shim now forwards Pi's toolCallId. - The collector puts `tool_call_id` on both hook legs, at the top level like the transcript sources' tool events; the server already stores it in its own `tool_call_id` column, so hook and transcript rows join there. - `hook_triggered` is stamped at `startedAt`, never after the end leg. - Rows written before this convert byte-for-byte as before, so a backfill re-read does not change their content-hash dedup key. - The golden-equivalence helpers drop `startedAt` with the other timing fields; the frozen digests are unchanged. --- CHANGELOG.md | 1 + __tests__/hooks/handler.test.ts | 23 +++++++++ __tests__/hooks/pi-shim-shapes.test.ts | 7 +++ __tests__/hooks/two-tier-handler.test.ts | 2 +- __tests__/hooks/two-tier/corpus.ts | 2 + .../src/sources/hooks/transform.rs | 44 ++++++++++++++--- crates/fpai-collect/tests/hooks_source.rs | 49 +++++++++++++++++++ pi-extension/index.ts | 2 + src/hooks/handler.ts | 30 +++++++++++- src/hooks/hook-activity-store.ts | 5 ++ 10 files changed, 157 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 51bf78abf..57f382667 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ - A hook client that stopped waiting before its verdict was ready is logged as that, with how long the evaluation took, instead of macOS's bare "Invalid argument (os error 22)" (#1023) - failproofaid writes its log to `~/.failproofai/logs/daemon.log` on every OS (10 MB, 3 kept), as well as to stderr as before; every line carries a timestamp and level (its untimestamped `[failproofaid]` lines are now `tracing` events), and on macOS launchd's `failproofaid.err.log`, which nothing rotated, is bounded at startup (#1023) - failproofaid tells FailproofAI Cloud what each machine runs: its policy poll carries `daemonVersion`, `cliVersion`, `os` and `arch` (optional parameters a server that predates them ignores), and every Cloud and ingest request sends `User-Agent: failproofaid/` (#1023) +- Hook events carry the agent's own `tool_call_id` (Claude, Devin, Factory, Pi, Hermes), the field the transcript events already use and Cloud stores in its own column, so a hook joins the tool call it governed instead of being placed beside it by timestamp; and a hook's start is stamped when it arrived, not when its evaluation ended. Rows written before this convert exactly as before (#1023) ## 1.0.15 — 2026-11-18 diff --git a/__tests__/hooks/handler.test.ts b/__tests__/hooks/handler.test.ts index d9934a588..c105d5c4e 100644 --- a/__tests__/hooks/handler.test.ts +++ b/__tests__/hooks/handler.test.ts @@ -195,6 +195,29 @@ describe("hooks/handler", () => { ); }); + it("records when the hook arrived and the agent's id for the tool call", async () => { + // The collector stamps a hook's start leg from startedAt (the row's own + // timestamp is the END of evaluation) and joins it to the transcript's + // tool call by toolCallId. + mockStdin(JSON.stringify({ tool_name: "Bash", tool_input: { command: "ls" }, tool_use_id: "toolu_01ABC" })); + const { persistHookActivity } = await import("../../src/hooks/hook-activity-store"); + await handleHookEvent("PreToolUse"); + const entry = vi.mocked(persistHookActivity).mock.calls.at(-1)![0]; + expect(entry.toolCallId).toBe("toolu_01ABC"); + expect(entry.startedAt).toBe(entry.timestamp - (entry.durationMs ?? 0)); + }); + + it("finds the tool call id in each agent's payload shape", async () => { + const { toolCallIdOf } = await import("../../src/hooks/handler"); + expect(toolCallIdOf({ tool_use_id: "toolu_1" })).toBe("toolu_1"); // Claude, Factory, Pi + expect(toolCallIdOf({ tool_call_id: "call_1" })).toBe("call_1"); // Devin + expect(toolCallIdOf({ hermes: { tool_call_id: "call_h" } })).toBe("call_h"); // Hermes plugin + expect(toolCallIdOf({ tool_use_id: "" })).toBeUndefined(); + expect(toolCallIdOf({ tool_use_id: "x".repeat(257) })).toBeUndefined(); + expect(toolCallIdOf({ tool_use_id: 7 })).toBeUndefined(); + expect(toolCallIdOf({})).toBeUndefined(); + }); + it("normalizes Copilot's camelCase permissionRequest payload (verified 1.0.71 capture)", async () => { // Copilot's snake_case events are Claude-shaped, but permissionRequest // alone pipes camelCase with a lowercase tool name. Without normalization diff --git a/__tests__/hooks/pi-shim-shapes.test.ts b/__tests__/hooks/pi-shim-shapes.test.ts index f225010d5..074cc3c68 100644 --- a/__tests__/hooks/pi-shim-shapes.test.ts +++ b/__tests__/hooks/pi-shim-shapes.test.ts @@ -46,6 +46,13 @@ describe("pi-extension deny shapes are in the right handlers", () => { expect(h).not.toMatch(/return \{ block: true/); }); + it("tool_call and tool_result forward Pi's toolCallId as tool_use_id", () => { + // The key the handler reads, so a Pi hook joins its transcript tool call. + for (const event of ["tool_call", "tool_result"]) { + expect(handler(event)).toMatch(/tool_use_id: e\.toolCallId/); + } + }); + it("input returns InputEventResult, never a block field", () => { const h = handler("input"); expect(h).toMatch(/action: "handled"/); diff --git a/__tests__/hooks/two-tier-handler.test.ts b/__tests__/hooks/two-tier-handler.test.ts index b3529220e..7003684bd 100644 --- a/__tests__/hooks/two-tier-handler.test.ts +++ b/__tests__/hooks/two-tier-handler.test.ts @@ -343,7 +343,7 @@ describe("opt-in", () => { const deletion = () => bash("find . -name '*.sqlite' -delete"); const strip = (o: Awaited>) => ({ ...o.outcome, evaluation: { ...o.outcome.evaluation, durationMs: 0 } }); const stripRow = (row: Record) => { - const { timestamp: _t, durationMs: _d, ...rest } = row; + const { timestamp: _t, durationMs: _d, startedAt: _s, ...rest } = row; return rest; }; // Were Jev asked, both would come out differently: it clears the diff --git a/__tests__/hooks/two-tier/corpus.ts b/__tests__/hooks/two-tier/corpus.ts index 656805d78..2bbaf7eca 100644 --- a/__tests__/hooks/two-tier/corpus.ts +++ b/__tests__/hooks/two-tier/corpus.ts @@ -330,6 +330,8 @@ export function comparableHandlerOutcome( row = { ...activity }; delete row.timestamp; delete row.durationMs; + // Timing as well: `timestamp - durationMs`. + delete row.startedAt; } return { out: { exitCode: outcome.exitCode, stdout: outcome.stdout, stderr: outcome.stderr, evaluation }, diff --git a/crates/fpai-collect/src/sources/hooks/transform.rs b/crates/fpai-collect/src/sources/hooks/transform.rs index ac00a65cb..a0a24ad40 100644 --- a/crates/fpai-collect/src/sources/hooks/transform.rs +++ b/crates/fpai-collect/src/sources/hooks/transform.rs @@ -34,8 +34,16 @@ use serde_json::{Map, Value, json}; /// enumerating all of them turns each addition into unrelated breakage. #[derive(Debug, Clone, Default, Deserialize)] pub struct HookRow { - /// Epoch milliseconds. + /// Epoch milliseconds: when the row was written, the END of evaluation. pub timestamp: i64, + /// Epoch milliseconds the hook arrived. Written since 1.0.15; older rows + /// have none, and keep the exact events they always produced (the server + /// dedups on content, so a re-read must not change them). + #[serde(rename = "startedAt", default)] + pub started_at: Option, + /// The agent's own id for the tool call this hook governed. + #[serde(rename = "toolCallId", default)] + pub tool_call_id: Option, #[serde(rename = "eventType")] pub event_type: Option, /// Which agent CLI fired the hook. @@ -823,12 +831,20 @@ fn base( environment: &str, kind: &str, index: u32, +) -> Option> { + base_at(row, row.timestamp, session_id, environment, kind, index) +} + +fn base_at( + row: &HookRow, + at_ms: i64, + session_id: &str, + environment: &str, + kind: &str, + index: u32, ) -> Option> { let mut m = Map::new(); - m.insert( - "timestamp".into(), - json!(to_rfc3339_micros(row.timestamp, index)?), - ); + m.insert("timestamp".into(), json!(to_rfc3339_micros(at_ms, index)?)); m.insert("session_id".into(), json!(session_id)); m.insert("agent_id".into(), json!(agent_id(row))); m.insert("type".into(), json!(kind)); @@ -850,7 +866,16 @@ pub fn to_events(row: &HookRow, offset: u64, environment: &str) -> Vec { let event_name = row.event_type.as_deref().unwrap_or("Hook"); let hook_id = format!("{session_id}:{}:{offset}", row.timestamp); - let Some(mut start) = base(row, session_id, environment, "hook_triggered", 0) else { + // The start leg is stamped when the hook ARRIVED, where the row says: the + // row's own timestamp is the end of evaluation, which put a hook start + // after the tool call it gated whenever evaluation took longer than the + // agent's own logging. Never after the end, whatever a row claims. + let started = row + .started_at + .filter(|at| *at <= row.timestamp) + .unwrap_or(row.timestamp); + let Some(mut start) = base_at(row, started, session_id, environment, "hook_triggered", 0) + else { return Vec::new(); }; start.insert("hook_name".into(), json!(event_name)); @@ -879,6 +904,13 @@ pub fn to_events(row: &HookRow, offset: u64, environment: &str) -> Vec { let Some(mut end) = base(row, session_id, environment, "hook_completed", 1) else { return Vec::new(); }; + // The same field, at the same place, as the transcript sources' tool + // events: the server stores it in its own column, so a hook joins the + // tool call it governed instead of only sorting beside it. + if let Some(id) = row.tool_call_id.as_deref().filter(|id| !id.is_empty()) { + start.insert("tool_call_id".into(), json!(id)); + end.insert("tool_call_id".into(), json!(id)); + } end.insert("hook_name".into(), json!(event_name)); end.insert("hook_id".into(), json!(hook_id)); end.insert("outcome".into(), json!(row.decision_str())); diff --git a/crates/fpai-collect/tests/hooks_source.rs b/crates/fpai-collect/tests/hooks_source.rs index 5c94ab06e..73549686c 100644 --- a/crates/fpai-collect/tests/hooks_source.rs +++ b/crates/fpai-collect/tests/hooks_source.rs @@ -638,3 +638,52 @@ async fn an_observed_verdict_survives_the_allow_rollup() { fs::remove_dir_all(&state).ok(); fs::remove_dir_all(&spool).ok(); } + +#[test] +fn a_row_with_a_tool_call_id_and_start_time_joins_its_tool_call() { + let mut v: Value = serde_json::from_str(&deny_row()).unwrap(); + let ts = v["timestamp"].as_i64().unwrap(); + v["startedAt"] = serde_json::json!(ts - 1500); + v["toolCallId"] = serde_json::json!("toolu_01ABC"); + let events = transform::to_events(&serde_json::from_value(v).unwrap(), 0, "local"); + let (start, end) = (&events[0], &events[1]); + // The start leg is stamped when the hook arrived, 1.5 s before the end. + assert_eq!( + start["timestamp"], + transform::to_rfc3339_micros(ts - 1500, 0).unwrap() + ); + assert_eq!( + end["timestamp"], + transform::to_rfc3339_micros(ts, 1).unwrap() + ); + // The field and place the transcript sources use, on both legs. + assert_eq!(start["tool_call_id"], "toolu_01ABC"); + assert_eq!(end["tool_call_id"], "toolu_01ABC"); +} + +#[test] +fn an_older_row_converts_exactly_as_before() { + // The server dedups on content: a re-read (a backfill) of a row written + // before these fields existed must produce byte-identical events. + let row = parse(&deny_row()); + let ts = row.timestamp; + let events = transform::to_events(&row, 0, "local"); + assert_eq!( + events[0]["timestamp"], + transform::to_rfc3339_micros(ts, 0).unwrap() + ); + assert!(events[0].get("tool_call_id").is_none()); + assert!(events[1].get("tool_call_id").is_none()); +} + +#[test] +fn a_start_time_after_the_end_is_ignored() { + let mut v: Value = serde_json::from_str(&deny_row()).unwrap(); + let ts = v["timestamp"].as_i64().unwrap(); + v["startedAt"] = serde_json::json!(ts + 60_000); + let events = transform::to_events(&serde_json::from_value(v).unwrap(), 0, "local"); + assert_eq!( + events[0]["timestamp"], + transform::to_rfc3339_micros(ts, 0).unwrap() + ); +} diff --git a/pi-extension/index.ts b/pi-extension/index.ts index 8dffa1247..21b2022e0 100644 --- a/pi-extension/index.ts +++ b/pi-extension/index.ts @@ -343,6 +343,7 @@ export default function failproofaiBridge(pi: PiExtensionApi) { const decision = callPolicy("tool_call", { tool_name: canonicalTool, tool_input: canonicalizeToolInput(canonicalTool, e.input), + ...(e.toolCallId ? { tool_use_id: e.toolCallId } : {}), session_id: resolveSessionId(e.sessionId, resolveCwd(e.cwd)), cwd: resolveCwd(e.cwd), hook_event_name: "PreToolUse", @@ -449,6 +450,7 @@ export default function failproofaiBridge(pi: PiExtensionApi) { callPolicy("tool_result", { tool_name: canonicalTool, tool_input: canonicalizeToolInput(canonicalTool, e.input) ?? {}, + ...(e.toolCallId ? { tool_use_id: e.toolCallId } : {}), tool_response: { content: e.content, isError: e.isError }, session_id: resolveSessionId(e.sessionId, resolveCwd(e.cwd)), cwd: resolveCwd(e.cwd), diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index f1ebd0f94..3f6c37680 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -97,6 +97,26 @@ import type { AgentIdentity } from "./agent-targets"; /** Set once the legacy-shim warning has been logged in this process. */ let legacyShimWarned = false; +/** + * The agent's own id for the tool call a hook payload is about: Claude, Devin, + * Factory and Pi (via its shim) send `tool_use_id`, Devin also + * `tool_call_id`, Hermes nests it under `hermes.tool_call_id`. It is the id the + * agent's transcript records that call under, so a hook event that carries it + * joins the transcript events for the same call instead of being placed + * beside them by timestamp alone. + */ +export function toolCallIdOf(parsed: Record): string | undefined { + const hermes = parsed.hermes; + const nested = + hermes && typeof hermes === "object" && !Array.isArray(hermes) + ? (hermes as Record).tool_call_id + : undefined; + for (const value of [parsed.tool_use_id, parsed.tool_call_id, parsed.toolCallId, parsed.toolUseId, nested]) { + if (typeof value === "string" && value.length > 0 && value.length <= 256) return value; + } + return undefined; +} + /** * Canonicalize an event name to PascalCase. Codex sends snake_case event names * on stdin and as the --hook arg; Cursor sends camelCase (`preToolUse`, @@ -1246,8 +1266,16 @@ export async function evaluateHookEvent( const jevOrigin = result.policyName && result.twoTier?.decidedByJev ? result.twoTier.jevOrigin : undefined; // Persist activity to disk (visible in /policies activity tab) + const writtenAt = Date.now(); + const toolCallId = toolCallIdOf(parsed); const activityEntry = { - timestamp: Date.now(), + timestamp: writtenAt, + // When the hook arrived. `timestamp` is when its evaluation ENDED, so a + // hook start ordered by it sorted late by the whole evaluation. + startedAt: writtenAt - durationMs, + // The agent's own id for the tool call this hook governed, the key its + // transcript records the call under (see `toolCallIdOf`). + ...(toolCallId ? { toolCallId } : {}), eventType: canonicalEventType, integration: cli, toolName: (parsed.tool_name as string) ?? null, diff --git a/src/hooks/hook-activity-store.ts b/src/hooks/hook-activity-store.ts index 09abff028..4a15480ab 100644 --- a/src/hooks/hook-activity-store.ts +++ b/src/hooks/hook-activity-store.ts @@ -54,7 +54,12 @@ let rotateSeq = 0; // ── Types ── export interface HookActivityEntry { + /** When the row was written: the END of the hook's evaluation. */ timestamp: number; + /** When the hook arrived (`timestamp - durationMs`). Absent on older rows. */ + startedAt?: number; + /** The agent's own id for the tool call this hook governed, when it sent one. */ + toolCallId?: string; eventType: string; /** Which agent CLI fired the hook (claude | codex). */ integration?: string; From 2f7b56f09316adb3bc694ff2a7460cba14d97de8 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 16:19:39 +0530 Subject: [PATCH 10/41] fix(protocol): never answer an old client where agent-targeted policies apply Review (CodeRabbit, server.rs / daemon-client.ts): a v1 request carries no agentSettingsPath, so it is evaluated with its agent unknown, and a Cloud policy targeted at an agent does not apply to an unknown one. On a deployment with targeted policies (active.json schema 3) the compatible answer could allow a call the targeted policy denies, where before this PR the stale client failed closed. - The daemon refuses a v1 hook/policyEvaluation request when the active deployment is schema 3, or cannot be read, stamped v1 so the old client's own fail-closed path blocks it. Elsewhere compatibility is unchanged. - The CLI, Hermes and OpenClaw clients never fall back to an older daemon on such a deployment, for the same reason. - Tests point the daemon and clients at a scratch Cloud policy directory; they had been reading the developer's own. --- .../fixtures/hermes-native-plugin-check.py | 20 ++- __tests__/hooks/daemon-client.test.ts | 24 +++ __tests__/hooks/openclaw-plugin.test.ts | 20 ++- crates/failproofaid/src/server.rs | 144 ++++++++++++++++++ hermes-plugin/client.py | 29 ++++ openclaw-plugin/daemon-client.js | 36 ++++- src/hooks/daemon-client.ts | 7 +- 7 files changed, 275 insertions(+), 5 deletions(-) diff --git a/__tests__/fixtures/hermes-native-plugin-check.py b/__tests__/fixtures/hermes-native-plugin-check.py index ce4ae13e2..cf9d33b7b 100644 --- a/__tests__/fixtures/hermes-native-plugin-check.py +++ b/__tests__/fixtures/hermes-native-plugin-check.py @@ -1706,12 +1706,19 @@ class ProtocolCompatibilityTests(unittest.TestCase): """Files on disk can be newer than the daemon still running. An older daemon inside the supported range is asked again in its own version, not refused.""" - def _evaluate(self, responses: list[dict[str, object]]) -> tuple[object, list]: + def _evaluate(self, responses: list[dict[str, object]], schema: int | None = None) -> tuple[object, list]: with tempfile.TemporaryDirectory() as tmp: socket_path = Path(tmp) / "d.sock" + policies = Path(tmp) / "cloud-policies" + policies.mkdir() + if schema is not None: + (policies / "active.json").write_text( + json.dumps({"schemaVersion": schema, "deployment": 4, "policies": []}) + ) received: list = [] thread = serve_verdicts(socket_path, responses, received) - with patch.dict("os.environ", {"FAILPROOFAI_DAEMON_SOCKET": str(socket_path)}): + env = {"FAILPROOFAI_DAEMON_SOCKET": str(socket_path), "FAILPROOFAI_CLOUD_POLICY_DIR": str(policies)} + with patch.dict("os.environ", env): try: result: object = client.evaluate_policy( event="pre_tool_call", @@ -1738,6 +1745,15 @@ def test_an_older_daemon_is_asked_again_in_its_version(self) -> None: # The answer accepted is the one to a request that never claimed a profile. self.assertNotIn("agentSettingsPath", received[1]) + def test_no_fallback_where_the_deployment_targets_agents(self) -> None: + # The older daemon evaluates with the agent unknown, and an + # agent-targeted policy does not apply to an unknown agent. + result, received = self._evaluate( + [{"type": "error", "protocolVersion": 1, "message": "protocol version mismatch"}], schema=3 + ) + self.assertIsInstance(result, client.EvaluationError) + self.assertEqual(len(received), 1) + def test_no_retry_below_the_oldest_supported_version(self) -> None: result, received = self._evaluate([ {"type": "error", "protocolVersion": 0, "message": "protocol version mismatch"}, diff --git a/__tests__/hooks/daemon-client.test.ts b/__tests__/hooks/daemon-client.test.ts index 8c02653b0..7e69a5bbf 100644 --- a/__tests__/hooks/daemon-client.test.ts +++ b/__tests__/hooks/daemon-client.test.ts @@ -57,11 +57,15 @@ describe("hooks/daemon-client", () => { socketPath = join(tmpDir, "test.sock"); server = null; process.env.FAILPROOFAI_DAEMON_SOCKET = socketPath; + // The fallback to an older daemon reads the Cloud deployment; never the + // developer's own. + process.env.FAILPROOFAI_CLOUD_POLICY_DIR = join(tmpDir, "cloud-policies"); vi.resetModules(); }); afterEach(async () => { delete process.env.FAILPROOFAI_DAEMON_SOCKET; + delete process.env.FAILPROOFAI_CLOUD_POLICY_DIR; if (server) { await new Promise((r) => server!.close(() => r())); } @@ -271,6 +275,26 @@ describe("hooks/daemon-client", () => { expect(requests).toHaveLength(2); }); + it("does not fall back to an older daemon where the deployment targets agents", async () => { + // The older daemon evaluates with the agent unknown, and an agent-targeted + // policy does not apply to an unknown agent: its allow could be wrong. + mkdirSync(process.env.FAILPROOFAI_CLOUD_POLICY_DIR!, { recursive: true }); + writeFileSync( + join(process.env.FAILPROOFAI_CLOUD_POLICY_DIR!, "active.json"), + JSON.stringify({ schemaVersion: 3, deployment: 4, policies: [] }), + ); + let connections = 0; + await startServer(async (socket) => { + connections++; + await readFrame(socket); + socket.end(encodeFrame({ type: "hookResult", protocolVersion: 1, exitCode: 0, stdout: "", stderr: "" })); + }); + const { attemptDaemonHook } = await import("../../src/hooks/daemon-client"); + const attempt = await attemptDaemonHook({ hookEvent: "PreToolUse", cli: "claude", stdin: "{}" }); + expect(attempt).toEqual({ ok: false, failure: "protocol-mismatch" }); + expect(connections).toBe(1); + }); + it("does not retry below the oldest supported version", async () => { let connections = 0; await startServer(async (socket) => { diff --git a/__tests__/hooks/openclaw-plugin.test.ts b/__tests__/hooks/openclaw-plugin.test.ts index 12ca6c549..cc2164151 100644 --- a/__tests__/hooks/openclaw-plugin.test.ts +++ b/__tests__/hooks/openclaw-plugin.test.ts @@ -1,7 +1,7 @@ // @vitest-environment node import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createServer, type Server, type Socket } from "node:net"; -import { cpSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs"; +import { cpSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { pathToFileURL } from "node:url"; @@ -70,6 +70,9 @@ let socketPath: string; beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "fpoc-")); socketPath = join(dir, "d.sock"); + // The fallback to an older daemon reads the Cloud deployment; never the + // developer's own. + vi.stubEnv("FAILPROOFAI_CLOUD_POLICY_DIR", join(dir, "no-cloud")); }); afterEach(() => { @@ -268,6 +271,21 @@ describe("openclaw-plugin daemon-client: requestHookVerdict", () => { } }); + it("does not fall back to an older daemon where the deployment targets agents", async () => { + const policies = join(dir, "cloud-policies"); + mkdirSync(policies, { recursive: true }); + writeFileSync(join(policies, "active.json"), JSON.stringify({ schemaVersion: 3, deployment: 4, policies: [] })); + vi.stubEnv("FAILPROOFAI_CLOUD_POLICY_DIR", policies); + const daemon = await fakeDaemon(socketPath, () => ({ type: "error", protocolVersion: 1, message: "mismatch" })); + try { + const result = await requestHookVerdict({ event: "before_tool_call", payload: {}, socketPath }); + expect(result).toMatchObject({ ok: false, failure: "protocol-mismatch" }); + expect(daemon.requests).toHaveLength(1); + } finally { + await daemon.close(); + } + }); + it("does not retry below the oldest supported version", async () => { const daemon = await fakeDaemon(socketPath, () => ({ type: "error", protocolVersion: 0, message: "x" })); try { diff --git a/crates/failproofaid/src/server.rs b/crates/failproofaid/src/server.rs index 7a4caacd7..8bdcc1882 100644 --- a/crates/failproofaid/src/server.rs +++ b/crates/failproofaid/src/server.rs @@ -394,9 +394,52 @@ fn dispatch(request: ClientMessage, worker: &Worker) -> ServerMessage { ), }; } + if version < fpai_ipc::envelope::AGENT_SETTINGS_PATH_SINCE + && !matches!(request, ClientMessage::Ping { .. }) + && let Ok(dir) = crate::paths::cloud_managed_policy_dir() + && let Some(message) = legacy_scope_refusal(&dir) + { + return ServerMessage::Error { + protocol_version: version, + message, + }; + } evaluate(request.without_fields_newer_than_its_version(), worker).with_protocol_version(version) } +/// Why a request too old to name its agent cannot be answered here, if it +/// cannot. +/// +/// A v1 request carries no `agentSettingsPath`, so it is evaluated with its +/// agent unknown, and a Cloud policy targeted at an agent does not apply to an +/// unknown one. Where the deployment has no targeted policy that changes +/// nothing, and the stale gateway keeps working. Where it does (schema 3), an +/// answer could allow what the targeted policy denies, so the request is +/// refused and the old client's own fail-closed path blocks it, as every v1 +/// request was before compatibility. A deployment that cannot be read is +/// refused for the same reason. +fn legacy_scope_refusal(cloud_policy_dir: &Path) -> Option { + let store = crate::cloud_policies::PolicyStore::new(cloud_policy_dir.to_path_buf()); + match store.read_active() { + Ok(None) => None, + Ok(Some(active)) + if active.schema_version + < crate::cloud_policies::SCOPED_DESIRED_STATE_SCHEMA_VERSION => + { + None + } + Ok(Some(_)) => Some( + "this client predates agent-targeted Cloud policies, which this machine's \ + deployment uses: restart the agent gateway to load the current plugin" + .to_string(), + ), + Err(err) => Some(format!( + "this client predates agent-targeted Cloud policies and the deployment could \ + not be read to rule them out ({err}): restart the agent gateway" + )), + } +} + fn evaluate(request: ClientMessage, worker: &Worker) -> ServerMessage { match request { ClientMessage::Ping { .. } => ServerMessage::Pong { @@ -712,6 +755,8 @@ mod tests { ) .unwrap(); + let no_deployment = temp_socket_path("no-deployment-real"); + let _env = CloudPolicyDir::set(&no_deployment); let socket_path = temp_socket_path("hook-real-worker"); let worker_cmd = WorkerCommand::shell(format!("bun {}", worker_script.display())); let _guard = start_test_server_with_worker(socket_path.clone(), worker_cmd); @@ -872,11 +917,86 @@ mod tests { } } + /// Points the daemon's Cloud policy directory at `dir` for one test. v1 + /// requests read it (see `legacy_scope_refusal`), and the developer's real + /// one must not decide a test. + struct CloudPolicyDir { + _lock: std::sync::MutexGuard<'static, ()>, + previous: Option, + } + + impl CloudPolicyDir { + fn set(dir: &Path) -> Self { + let lock = crate::test_env::lock_env(); + let previous = std::env::var_os(crate::paths::CLOUD_POLICY_DIR_ENV); + // SAFETY: serialised by the env lock held for this value's life. + unsafe { std::env::set_var(crate::paths::CLOUD_POLICY_DIR_ENV, dir) }; + CloudPolicyDir { + _lock: lock, + previous, + } + } + } + + impl Drop for CloudPolicyDir { + fn drop(&mut self) { + // SAFETY: as above. + unsafe { + match &self.previous { + Some(v) => std::env::set_var(crate::paths::CLOUD_POLICY_DIR_ENV, v), + None => std::env::remove_var(crate::paths::CLOUD_POLICY_DIR_ENV), + } + } + } + } + + #[test] + fn an_old_client_is_refused_when_the_deployment_targets_agents() { + let dir = temp_socket_path("scoped-deployment"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("active.json"), + format!( + r#"{{"schemaVersion":{},"deployment":4,"policies":[]}}"#, + crate::cloud_policies::SCOPED_DESIRED_STATE_SCHEMA_VERSION + ), + ) + .unwrap(); + let _env = CloudPolicyDir::set(&dir); + let worker = Worker::new(temp_socket_path("scoped-worker"), broken_worker_cmd()); + let request = |protocol_version| ClientMessage::PolicyEvaluation { + protocol_version, + integration: "hermes".into(), + event: "pre_tool_call".into(), + payload: serde_json::json!({}), + cwd: None, + agent_settings_path: None, + }; + match dispatch(request(1), &worker) { + ServerMessage::Error { + protocol_version, + message, + } => { + assert_eq!(protocol_version, 1, "stamped so the old client reads it"); + assert!(message.contains("agent-targeted"), "{message}"); + } + other => panic!("a v1 request was evaluated: {other:?}"), + } + // A current client names its agent: evaluated (here, by a broken worker). + match dispatch(request(PROTOCOL_VERSION), &worker) { + ServerMessage::Error { message, .. } => assert!(!message.contains("agent-targeted")), + other => panic!("unexpected {other:?}"), + } + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn previous_protocol_is_answered_in_its_own_version() { // A gateway that loaded the previous plugin before an upgrade keeps // speaking v1 until it restarts. It must get an answer it accepts, // not a mismatch that its fail-closed path turns into a deny. + let no_deployment = temp_socket_path("no-deployment"); + let _env = CloudPolicyDir::set(&no_deployment); let socket_path = temp_socket_path("old-protocol"); let _guard = start_test_server(socket_path.clone()); @@ -950,6 +1070,30 @@ mod tests { ); } + #[test] + fn an_old_client_is_refused_only_where_agent_targeted_policies_could_apply() { + let dir = temp_socket_path("legacy-scope"); + std::fs::create_dir_all(&dir).unwrap(); + let write = |schema: u32| { + std::fs::write( + dir.join("active.json"), + format!(r#"{{"schemaVersion":{schema},"deployment":4,"policies":[]}}"#), + ) + .unwrap() + }; + // No deployment, or one without targets: the stale gateway keeps working. + assert_eq!(legacy_scope_refusal(&dir), None); + write(2); + assert_eq!(legacy_scope_refusal(&dir), None); + // Targeted: an unknown agent would skip a policy aimed at it. + write(crate::cloud_policies::SCOPED_DESIRED_STATE_SCHEMA_VERSION); + assert!(legacy_scope_refusal(&dir).is_some()); + // Unreadable: cannot rule targets out. + std::fs::write(dir.join("active.json"), "{").unwrap(); + assert!(legacy_scope_refusal(&dir).is_some()); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn a_client_that_stopped_waiting_is_logged_as_such() { let (mut client, server) = UnixStream::pair().unwrap(); diff --git a/hermes-plugin/client.py b/hermes-plugin/client.py index 70f17ffe9..7b133e711 100644 --- a/hermes-plugin/client.py +++ b/hermes-plugin/client.py @@ -16,6 +16,9 @@ # MIN_PROTOCOL_VERSION), and the first that carries agentSettingsPath. MIN_PROTOCOL_VERSION = 1 AGENT_SETTINGS_PATH_SINCE = 2 +# active.json schema that can target policies at agents (crates/failproofaid +# cloud_policies.rs SCOPED_DESIRED_STATE_SCHEMA_VERSION). +SCOPED_SCHEMA_VERSION = 3 MAX_FRAME_BYTES = 16 * 1024 * 1024 MAX_REQUEST_BYTES = 1024 * 1024 @@ -43,6 +46,31 @@ def daemon_socket_path() -> Path: return home / "run" / "failproofaid.sock" +def _agent_targeted_deployment() -> bool: + """Whether this machine's Cloud deployment targets policies at agents. + + An older daemon evaluates without naming the agent, and a targeted policy + does not apply to an unknown one, so its answer could allow what that + policy denies: such a machine is never asked in the older version. A + deployment that exists but cannot be read counts as targeted. + """ + override = os.environ.get("FAILPROOFAI_CLOUD_POLICY_DIR", "").strip() + if override: + directory = Path(override).expanduser() + else: + root = os.environ.get("FAILPROOFAI_HOME", "").strip() + home = Path(root).expanduser() if root else Path.home() / ".failproofai" + directory = home / "policies" / "cloud-policies" + active = directory / "active.json" + try: + if not active.exists(): + return False + version = json.loads(active.read_text(encoding="utf-8")).get("schemaVersion") + return not (type(version) is int and version < SCOPED_SCHEMA_VERSION) + except (OSError, ValueError, AttributeError): + return True + + def _remaining_timeout(deadline: float) -> float: remaining = deadline - time.monotonic() if remaining <= 0: @@ -141,6 +169,7 @@ def build(version: int) -> bytes: if ( type(answered) is int and MIN_PROTOCOL_VERSION <= answered < PROTOCOL_VERSION + and not _agent_targeted_deployment() ): version = answered response = _exchange(build(version), connect_timeout_ms, deadline) diff --git a/openclaw-plugin/daemon-client.js b/openclaw-plugin/daemon-client.js index 121767f5b..f0ab6ab27 100644 --- a/openclaw-plugin/daemon-client.js +++ b/openclaw-plugin/daemon-client.js @@ -15,6 +15,7 @@ * Self-contained on purpose — node built-ins only, nothing imported from * outside this directory — because the capture copies nothing else. */ +import { readFile } from "node:fs/promises"; import { createConnection } from "node:net"; import { performance } from "node:perf_hooks"; import { homedir } from "node:os"; @@ -60,6 +61,34 @@ const UNREACHABLE_MESSAGE = "failproofaid could not be reached. This machine is configured to run hooks through it " + "— check the daemon (see `failproofai config`) rather than retrying blindly."; +// active.json schema that can target policies at agents (crates/failproofaid +// cloud_policies.rs SCOPED_DESIRED_STATE_SCHEMA_VERSION). +const SCOPED_SCHEMA_VERSION = 3; + +/** + * Whether this machine's Cloud deployment targets policies at agents. An older + * daemon evaluates without naming the agent, and a targeted policy does not + * apply to an unknown one, so such a machine is never asked in the older + * version. A deployment that exists but cannot be read counts as targeted. + */ +export async function agentTargetedDeployment(env = process.env, home = homedir()) { + const dir = + env.FAILPROOFAI_CLOUD_POLICY_DIR || + resolve(env.FAILPROOFAI_HOME || resolve(home, ".failproofai"), "policies", "cloud-policies"); + let text; + try { + text = await readFile(resolve(dir, "active.json"), "utf8"); + } catch (err) { + return err?.code !== "ENOENT"; + } + try { + const version = JSON.parse(text)?.schemaVersion; + return !(Number.isInteger(version) && version < SCOPED_SCHEMA_VERSION); + } catch { + return true; + } +} + /** Mirrors `daemonSocket()` in src/hooks/fp-home.ts. */ export function daemonSocketPath(env = process.env, home = homedir()) { return ( @@ -172,7 +201,12 @@ export async function requestHookVerdict(request) { // An older daemon still inside the supported range: ask again in its version // rather than block every call until it is replaced. const older = first.ok ? undefined : first.daemonVersion; - if (!Number.isInteger(older) || older < MIN_PROTOCOL_VERSION || older >= PROTOCOL_VERSION) { + if ( + !Number.isInteger(older) || + older < MIN_PROTOCOL_VERSION || + older >= PROTOCOL_VERSION || + (await agentTargetedDeployment()) + ) { if (!first.ok) delete first.daemonVersion; return first; } diff --git a/src/hooks/daemon-client.ts b/src/hooks/daemon-client.ts index 7f29e02c2..ee5506f33 100644 --- a/src/hooks/daemon-client.ts +++ b/src/hooks/daemon-client.ts @@ -15,6 +15,7 @@ import type { IntegrationType } from "./types"; import { existsSync } from "node:fs"; import { daemonSocket as daemonSocketPath } from "./fp-home"; import { readConfig } from "./fp-config"; +import { readCloudAgentScopeRequired } from "./cloud-managed-policies"; const PROTOCOL_VERSION = 2; /** Oldest daemon version this client falls back to (crates/fpai-ipc MIN_PROTOCOL_VERSION). */ @@ -220,7 +221,11 @@ async function attemptDaemonRequest( older === undefined || !Number.isInteger(older) || older < MIN_PROTOCOL_VERSION || - older >= PROTOCOL_VERSION + older >= PROTOCOL_VERSION || + // The older daemon would evaluate without this agent, and a deployment + // with agent-targeted policies (schema 3) does not apply them to an + // unknown one: its answer could allow what they deny. + readCloudAgentScopeRequired() ) { return withoutDaemonVersion(first); } From ba8c83e4040529da76a6a7f752fa00d14ac1686c Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 16:21:23 +0530 Subject: [PATCH 11/41] fix(collector): park only a refused oversized event; re-check a replaced key Review (pr-autopilot F1, CodeRabbit): - A single event still refused with 413 inside a multi-event batch is parked on its own as -oversize.*.c413 and the rest of the batch is delivered. Parking the whole file there left every event after it unsent, though each fit. A file holding one event parks as before. - The replaced-key check runs before every attempt, so a retry waiting out a 429 cannot wake and send on a key another upload found replaced, and it re-reads the key instead of latching: a key that changes back (A -> B -> A before the manager notices) resumes uploading instead of going silent. - A malformed startedAt or toolCallId no longer drops the hook row (and its decision) at parse time; a start time that cannot be formatted falls back to the row's own timestamp. --- .../src/sources/hooks/transform.rs | 5 +- crates/fpai-collect/src/uploader.rs | 68 ++++++++++-- crates/fpai-collect/tests/hooks_source.rs | 16 +++ crates/fpai-collect/tests/uploader.rs | 103 ++++++++++++++++-- 4 files changed, 173 insertions(+), 19 deletions(-) diff --git a/crates/fpai-collect/src/sources/hooks/transform.rs b/crates/fpai-collect/src/sources/hooks/transform.rs index a0a24ad40..7d4088f2e 100644 --- a/crates/fpai-collect/src/sources/hooks/transform.rs +++ b/crates/fpai-collect/src/sources/hooks/transform.rs @@ -39,10 +39,10 @@ pub struct HookRow { /// Epoch milliseconds the hook arrived. Written since 1.0.15; older rows /// have none, and keep the exact events they always produced (the server /// dedups on content, so a re-read must not change them). - #[serde(rename = "startedAt", default)] + #[serde(rename = "startedAt", default, deserialize_with = "lenient")] pub started_at: Option, /// The agent's own id for the tool call this hook governed. - #[serde(rename = "toolCallId", default)] + #[serde(rename = "toolCallId", default, deserialize_with = "lenient")] pub tool_call_id: Option, #[serde(rename = "eventType")] pub event_type: Option, @@ -875,6 +875,7 @@ pub fn to_events(row: &HookRow, offset: u64, environment: &str) -> Vec { .filter(|at| *at <= row.timestamp) .unwrap_or(row.timestamp); let Some(mut start) = base_at(row, started, session_id, environment, "hook_triggered", 0) + .or_else(|| base(row, session_id, environment, "hook_triggered", 0)) else { return Vec::new(); }; diff --git a/crates/fpai-collect/src/uploader.rs b/crates/fpai-collect/src/uploader.rs index a1530474b..b239c5fc1 100644 --- a/crates/fpai-collect/src/uploader.rs +++ b/crates/fpai-collect/src/uploader.rs @@ -363,8 +363,11 @@ impl Uploader { // preserving the exact retained bytes for server-side deduplication. let bytes = filter_boundary(&bytes, self.since_ms, crate::org_boundary::mtime_ms(path)); let bytes = redact_batch(&bytes, self.redact); + // A file holding one event parks itself on a 413, exactly as before; + // in any other file only the refused event is set aside. + let sole_event = bytes.split_inclusive(|b| *b == b'\n').count() <= 1; for chunk in split_lines(&bytes, self.max_upload_bytes) { - self.post_splitting(path, chunk).await?; + self.post_splitting(path, chunk, sole_event).await?; } match tokio::fs::remove_file(path).await { @@ -379,22 +382,66 @@ impl Uploader { /// the batch for good, though every event in it was within its limit. /// Pieces go in their original order; a later failure leaves the whole /// batch for a byte-identical resend, which the server dedups. - async fn post_splitting(&self, path: &Path, chunk: Vec) -> Result<(), UploadError> { + /// + /// A single event the server still refuses is parked on its own (`.c413`) + /// and the rest of the batch carries on: parking the whole file there left + /// every event after it unsent, though each fit. + async fn post_splitting( + &self, + path: &Path, + chunk: Vec, + sole_event: bool, + ) -> Result<(), UploadError> { let mut pending = vec![chunk]; while let Some(piece) = pending.pop() { let lines = piece.split_inclusive(|b| *b == b'\n').count(); - match self.post_batch(path, piece.clone(), lines > 1).await { - Err(UploadError::TooLarge) => { + match self + .post_batch(path, piece.clone(), !sole_event || lines > 1) + .await + { + Err(UploadError::TooLarge) if lines > 1 => { let (first, second) = halve_lines(&piece); pending.push(second); pending.push(first); } + Err(UploadError::TooLarge) => { + self.park_event(path, &piece).await?; + } other => other?, } } Ok(()) } + /// Set one event the server refused as too large aside in `failed/`, as + /// its own definitive `.c413` file, so the batch it came from can finish. + async fn park_event(&self, path: &Path, event: &[u8]) -> Result<(), UploadError> { + tokio::fs::create_dir_all(&self.failed_dir).await?; + let name = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("batch.jsonl"); + let mut parked = ParkedName::parse(name); + parked.base = format!("{}-oversize", parked.base); + parked.attempt = 1; + parked.client_attempts = 1; + parked.client_status = Some(413); + let dest = unique_destination(&self.failed_dir, &parked.render()).await; + // Written under a dotfile and renamed, so no sweep sees half of it. + let tmp = self + .failed_dir + .join(format!(".{}.partial", new_request_id())); + tokio::fs::write(&tmp, event).await?; + tokio::fs::rename(&tmp, &dest).await?; + tracing::warn!( + file = %path.display(), + dest = %dest.display(), + bytes = event.len(), + "the server refused one event as too large; parked it alone" + ); + Ok(()) + } + /// POST one body, retrying per policy. `path` is used only for parking and /// log context — this never deletes it. `can_split` answers a 413 with /// [`UploadError::TooLarge`] instead of parking. @@ -407,11 +454,16 @@ impl Uploader { let mut attempt: u32 = 0; let batch_id = batch_id(path); - if self.superseded.load(Ordering::SeqCst) { - return Err(UploadError::KeySuperseded); - } - loop { + // Before EVERY attempt, not once: a retry waiting out a 429 must + // not wake and send on a key another upload found replaced. Re-read + // rather than latched, so a key that changes back resumes. + if self.superseded.load(Ordering::SeqCst) { + if self.key_replaced() { + return Err(UploadError::KeySuperseded); + } + self.superseded.store(false, Ordering::SeqCst); + } // New per attempt: one attempt is one server request. let request_id = new_request_id(); let result = self diff --git a/crates/fpai-collect/tests/hooks_source.rs b/crates/fpai-collect/tests/hooks_source.rs index 73549686c..f646679e9 100644 --- a/crates/fpai-collect/tests/hooks_source.rs +++ b/crates/fpai-collect/tests/hooks_source.rs @@ -687,3 +687,19 @@ fn a_start_time_after_the_end_is_ignored() { transform::to_rfc3339_micros(ts, 0).unwrap() ); } + +#[test] +fn a_malformed_start_time_or_tool_call_id_never_drops_the_decision() { + for (key, bad) in [ + ("startedAt", serde_json::json!(1785740912183.5)), + ("startedAt", serde_json::json!(i64::MIN)), + ("toolCallId", serde_json::json!(42)), + ] { + let mut v: Value = serde_json::from_str(&deny_row()).unwrap(); + v[key] = bad.clone(); + let row: HookRow = serde_json::from_value(v).unwrap_or_else(|e| panic!("{key}={bad}: {e}")); + let events = transform::to_events(&row, 0, "local"); + assert_eq!(events.len(), 2, "{key}={bad}"); + assert_eq!(events[1]["outcome"], "deny"); + } +} diff --git a/crates/fpai-collect/tests/uploader.rs b/crates/fpai-collect/tests/uploader.rs index 86758ac20..bd2b9fdd7 100644 --- a/crates/fpai-collect/tests/uploader.rs +++ b/crates/fpai-collect/tests/uploader.rs @@ -1303,7 +1303,63 @@ async fn a_413_halves_the_body_until_it_fits_and_keeps_the_order() { } #[tokio::test] -async fn a_413_on_a_single_event_is_parked_as_before() { +async fn an_oversized_event_is_parked_alone_and_the_rest_of_the_batch_is_delivered() { + use wiremock::Request; + // pr-autopilot's case: [before, oversize, after]. Parking the whole file at + // the oversized event left `after` unsent, though it fit. + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(|req: &Request| { + if String::from_utf8_lossy(&req.body).contains("OVERSIZE") { + ResponseTemplate::new(413) + } else { + let n = req + .body + .split(|b| *b == b'\n') + .filter(|l| !l.is_empty()) + .count(); + ResponseTemplate::new(200) + .set_body_json(serde_json::json!({"accepted": n, "skipped": 0})) + } + }) + .mount(&server) + .await; + let root = tmpdir("oversize-event"); + let failed = root.join("failed"); + let batch = root.join("hooks-a-1-0.jsonl"); + fs::write( + &batch, + "{\"n\":\"before\"}\n{\"n\":\"OVERSIZE\"}\n{\"n\":\"after\"}\n", + ) + .unwrap(); + + uploader(&server, &failed) + .upload_file(&batch) + .await + .unwrap(); + + assert!(!batch.exists(), "the batch finished"); + let delivered: String = server + .received_requests() + .await + .unwrap() + .into_iter() + .filter(|r| !String::from_utf8_lossy(&r.body).contains("OVERSIZE")) + .map(|r| String::from_utf8_lossy(&r.body).to_string()) + .collect(); + assert_eq!(delivered, "{\"n\":\"before\"}\n{\"n\":\"after\"}\n"); + let names = parked(&failed); + assert_eq!(names, ["hooks-a-1-0-oversize.a1.r1.c413.jsonl"]); + assert_eq!( + fs::read_to_string(failed.join(&names[0])).unwrap(), + "{\"n\":\"OVERSIZE\"}\n", + "only the refused event is set aside" + ); + fs::remove_dir_all(root).ok(); +} + +#[tokio::test] +async fn a_file_holding_one_refused_event_is_parked_as_before() { let server = MockServer::start().await; Mock::given(method("POST")) .respond_with(ResponseTemplate::new(413)) @@ -1311,21 +1367,50 @@ async fn a_413_on_a_single_event_is_parked_as_before() { .await; let root = tmpdir("single-413"); let failed = root.join("failed"); - let batch = write_batch(&root, "hooks-a-1-0.jsonl", 2); + let batch = write_batch(&root, "hooks-a-1-0.jsonl", 1); let result = uploader(&server, &failed).upload_file(&batch).await; assert!( matches!(result, Err(UploadError::Client { status: 413 })), "{result:?}" ); - // Two lines -> two single-line requests; the first single line is parked. - assert_eq!(server.received_requests().await.unwrap().len(), 2); assert_eq!(parked(&failed), ["hooks-a-1-0.a1.r1.c413.jsonl"]); - let kept = fs::read(failed.join("hooks-a-1-0.a1.r1.c413.jsonl")).unwrap(); - assert_eq!( - kept.iter().filter(|b| **b == b'\n').count(), - 2, - "the whole batch is kept" + fs::remove_dir_all(root).ok(); +} + +#[tokio::test] +async fn a_key_that_changes_back_resumes_uploading() { + // A -> B (a 401 marks this uploader's key replaced) -> A again before the + // manager rebuilt anything: the uploader must not stay silent forever. + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(401)) + .up_to_n_times(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(serde_json::json!({"accepted": 1, "skipped": 0})), + ) + .mount(&server) + .await; + let root = tmpdir("key-back"); + let (home, spool, failed) = (root.join("home"), root.join("spool"), root.join("failed")); + fs::create_dir_all(&spool).unwrap(); + write_key(&home, "other-key"); + let up = uploader(&server, &failed).with_key_source(home.clone()); + let first = write_batch(&spool, "hooks-a-1-0.jsonl", 1); + assert!(matches!( + up.upload_file(&first).await, + Err(UploadError::KeySuperseded) + )); + + write_key(&home, "test-key"); + up.upload_file(&first).await.unwrap(); + assert!( + !first.exists(), + "delivered once the key is this uploader's again" ); fs::remove_dir_all(root).ok(); } From dd44bd06c7da955108c20fd2a9116822b32c1d9d Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 16:39:13 +0530 Subject: [PATCH 12/41] fix: address PR #1023 review (pr-autopilot F2/F3, CodeRabbit) Daemon - A CollectorHandle dropped while its owner panics stops its collector within the flush budget (pr-autopilot F2): the restarted manager started a second collector over the same queues and cursors beside the abandoned one. - The cloud lane's identity state lives outside the supervised body, so a restart after a panic keeps the rollback floor's org and still notices a removed credential. - The supervisor logs through tracing (eprintln! panics on a stderr write error, outside the catch) and re-checks shutdown before restarting. - daemon.log is owner-only (0600) and reopened after a failed rotation. On macOS stderr carries WARN+ only when daemon.log is active (launchd's file is never rotated during uptime), and that file is bounded only after the singleton lock is held. - The telemetry overflow warning is logged after the ring lock is released. - Blocked-audit states, an unknown agent selection and rejected capture paths log at WARN. Two messages no longer overclaim their cause. Service definition - `failproofai config` repairs a definition whose generated command names a file that is gone (ensureDaemonServiceCurrent used the old test). - Only a package-generated command ('' '/dist/{worker,cli}.mjs') is judged or replaced; an operator's own saved FAILPROOFAI_WORKER_CMD survives a reinstall and a rewrite. - A stable runtime link is taken only from system bin directories, never any PATH entry. `%` is written `%%` in systemd Environment= values. - On macOS the plist is written before the old job is unloaded, so a failed write leaves the running daemon loaded. - shellQuotedWords no longer misreads a trailing space. update / gateways - Gateways restart only onto a running daemon service (no service or an unsupported platform is also "ok" from the refresh). - A queued restart no longer comes with "restart running Hermes gateways". - Status probes are hard-killed at their deadline. Each OpenClaw row runs with only its own profile selector, not the caller's OPENCLAW_* env. Status (pr-autopilot F3) - The "not enforcing" fix is the dashboard URL as configured (path and scheme kept), and a machine connected through FAILPROOFAI_CLOUD_URL is pointed at Cloud too. Hooks - startedAt is the wall clock at arrival, not end minus a duration that was measured before later work. Tests: fixtures that read the developer's real service definition, PATH or a single TCP read no longer decide results. --- CHANGELOG.md | 6 +- __tests__/hooks/config-status.test.ts | 8 +++ __tests__/hooks/daemon-service.test.ts | 30 +++++++--- __tests__/hooks/gateway-restart.test.ts | 31 ++++++++++ __tests__/hooks/handler.test.ts | 4 +- __tests__/hooks/hermes-update.test.ts | 3 + __tests__/hooks/policies-listing.test.ts | 12 ++++ bin/failproofai.mjs | 10 +++- crates/PROTOCOL.md | 12 +++- crates/failproofaid/src/audit_lane.rs | 7 ++- crates/failproofaid/src/cloud_client.rs | 38 ++++++++---- crates/failproofaid/src/logfile.rs | 34 +++++++++++ crates/failproofaid/src/main.rs | 54 ++++++++++++----- crates/failproofaid/src/server.rs | 4 +- crates/failproofaid/src/telemetry.rs | 11 +++- crates/failproofaid/src/worker.rs | 4 +- crates/fpai-collect/src/supervisor.rs | 24 ++++++++ crates/fpai-collect/tests/supervisor.rs | 38 ++++++++++++ src/hooks/config-status.ts | 9 ++- src/hooks/daemon-service.ts | 74 +++++++++++++++++++----- src/hooks/gateway-restart.ts | 27 ++++++++- src/hooks/handler.ts | 5 +- src/hooks/hermes-update.ts | 11 +++- src/hooks/manager.ts | 7 +++ src/hooks/shell-quote.ts | 8 ++- 25 files changed, 397 insertions(+), 74 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57f382667..405130e8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,10 +4,10 @@ ### Fixes -- The daemon answers the previous plugin protocol, and clients re-ask an older daemon in its version, so a Hermes or OpenClaw gateway still running the plugin it loaded before an upgrade keeps getting real verdicts instead of denying every call (#1023) +- The daemon answers the previous plugin protocol, and clients re-ask an older daemon in its version, so a Hermes or OpenClaw gateway still running the plugin it loaded before an upgrade keeps getting real verdicts instead of denying every call; where the Cloud deployment targets policies at agents, which a request naming no agent would escape, it still fails closed (#1023) - `failproofai update` restarts running Hermes and OpenClaw gateways through their own drain-aware restart (after in-flight work finishes) so they load the updated plugin; only service-managed gateways are touched, and `--no-restart` opts out (#1023) - A batch refused with a key the machine has since replaced (the seconds after a reconnect) is left for the new key instead of being parked as a refusal, so `config --status` no longer reports "the cloud is refusing this machine's key" right after a successful connect (#1023) -- A batch the server refuses as too large (413) is split in half and re-sent until each piece fits, instead of being parked for good (#1023) +- A batch the server refuses as too large (413) is split in half and re-sent until each piece fits, instead of being parked for good; a single event still refused is parked on its own and the rest of the batch is delivered (#1023) - `config --status` counts Cloud Jev-only deployments in its policies row; it showed "None installed" beside a deployment the line under it called enforcing (#1023) - A machine that pulls policies from Cloud is pointed at Cloud, not at installing packs: `config --status` says "None deployed from Cloud" with the dashboard as its fix, and the `failproofai policies` empty state says "Deploy from Cloud" (#1023) - The "no pack is installed" warning is logged once per process instead of on every hook call, which buried the daemon log (#1023) @@ -15,7 +15,7 @@ - The daemon no longer exits on a transient `accept()` failure (out of file descriptors, an aborted connection), which left every hook denied until the service manager restarted it (#1023) - The collector manager and cloud policy sync restart after a panic instead of stopping silently while the daemon keeps answering hooks (#1023) - A hook client that stopped waiting before its verdict was ready is logged as that, with how long the evaluation took, instead of macOS's bare "Invalid argument (os error 22)" (#1023) -- failproofaid writes its log to `~/.failproofai/logs/daemon.log` on every OS (10 MB, 3 kept), as well as to stderr as before; every line carries a timestamp and level (its untimestamped `[failproofaid]` lines are now `tracing` events), and on macOS launchd's `failproofaid.err.log`, which nothing rotated, is bounded at startup (#1023) +- failproofaid writes its log to `~/.failproofai/logs/daemon.log` on every OS (owner-only, 10 MB, 3 kept), as well as to stderr as before (on macOS stderr keeps only warnings and errors, since launchd's file is never rotated); every line carries a timestamp and level (its untimestamped `[failproofaid]` lines are now `tracing` events), and on macOS launchd's `failproofaid.err.log`, which nothing rotated, is bounded at startup (#1023) - failproofaid tells FailproofAI Cloud what each machine runs: its policy poll carries `daemonVersion`, `cliVersion`, `os` and `arch` (optional parameters a server that predates them ignores), and every Cloud and ingest request sends `User-Agent: failproofaid/` (#1023) - Hook events carry the agent's own `tool_call_id` (Claude, Devin, Factory, Pi, Hermes), the field the transcript events already use and Cloud stores in its own column, so a hook joins the tool call it governed instead of being placed beside it by timestamp; and a hook's start is stamped when it arrived, not when its evaluation ended. Rows written before this convert exactly as before (#1023) diff --git a/__tests__/hooks/config-status.test.ts b/__tests__/hooks/config-status.test.ts index b080b1e8d..261f5aaf4 100644 --- a/__tests__/hooks/config-status.test.ts +++ b/__tests__/hooks/config-status.test.ts @@ -67,6 +67,7 @@ function facts(over: Partial = {}): StatusFacts { cloud: { kind: "file", host: "be.failproof.ai", + url: "https://be.failproof.ai", org: "chetanraghuvanshi85", machine: "chetan-pc (dde01f39)", pullsPolicies: true, @@ -470,6 +471,11 @@ describe("config --status — the attention line", () => { expect(fixFor("no-policies", 0)).toBe("failproofai policies add FailproofAI/policies"); // Policies for a machine that pulls from Cloud are deployed there. expect(fixFor("no-policies", 0, facts().cloud)).toBe("https://be.failproof.ai"); + // The dashboard as configured, path and scheme kept. + const tenant = { ...facts().cloud, url: "http://cloud.internal:8080/tenant" } as StatusFacts["cloud"]; + expect(fixFor("no-policies", 0, tenant)).toBe("http://cloud.internal:8080/tenant"); + // Connected through FAILPROOFAI_CLOUD_URL: pulls from Cloud just the same. + expect(fixFor("no-policies", 0, { kind: "env", url: "https://staging.example/org" })).toBe("https://staging.example/org"); }); it("never calls a machine with a refused pack 'not enforcing': it is denying", () => { @@ -609,6 +615,8 @@ describe("gatherStatusFacts", () => { expect(f.cloud).toEqual({ kind: "file", host: "be.failproof.ai", + // As configured: the attention fix links here, path and scheme intact. + url: "https://be.failproof.ai", org: "FailproofAI (failproofai)", machine: "chetan-pc (dde01f39)", pullsPolicies: true, diff --git a/__tests__/hooks/daemon-service.test.ts b/__tests__/hooks/daemon-service.test.ts index f97e0ac1a..03b8ea3a1 100644 --- a/__tests__/hooks/daemon-service.test.ts +++ b/__tests__/hooks/daemon-service.test.ts @@ -315,7 +315,7 @@ describe("hooks/daemon-service", () => { if (!cliCmd) return; expect(cliCmd).toBe( - `'${process.execPath}' '${resolve(process.env.FAILPROOFAI_PACKAGE_ROOT, "dist", "cli.mjs")}'`, + `'${svc.stableExecPath()}' '${resolve(process.env.FAILPROOFAI_PACKAGE_ROOT, "dist", "cli.mjs")}'`, ); expect(cliCmd).not.toMatch(/^node /); // Through `sh -c`, exactly as the daemon will invoke it — which is also @@ -662,7 +662,8 @@ describe("hooks/daemon-service", () => { const { daemonServiceNeedsUpgrade, systemdUnitContents } = await import("../../src/hooks/daemon-service"); const { userInfo } = await import("node:os"); const runtime = resolve(unitDir, "node"); - const script = resolve(unitDir, "worker.mjs"); + const script = resolve(unitDir, "dist", "worker.mjs"); + mkdirSync(dirname(script), { recursive: true }); writeFileSync(runtime, ""); writeFileSync(script, ""); const unit = resolve(unitDir, `failproofaid@${userInfo().username}.service`); @@ -673,9 +674,11 @@ describe("hooks/daemon-service", () => { expect(daemonServiceNeedsUpgrade()).toBe(false); write(`'${resolve(unitDir, "gone", "node")}' '${script}'`); expect(daemonServiceNeedsUpgrade()).toBe(true); - // An operator's own command is never second-guessed. + // An operator's own command is never second-guessed, quoted or not. write("node dist/worker.mjs"); expect(daemonServiceNeedsUpgrade()).toBe(false); + write(`'${resolve(unitDir, "gone", "node")}' '/opt/team/wrapper.mjs'`); + expect(daemonServiceNeedsUpgrade()).toBe(false); } finally { if (prevDir === undefined) delete process.env.FAILPROOFAI_SYSTEMD_DIR; else process.env.FAILPROOFAI_SYSTEMD_DIR = prevDir; @@ -683,6 +686,13 @@ describe("hooks/daemon-service", () => { } }); + it("writes a literal % in a command as %% so systemd does not expand it", async () => { + setPlatform("linux"); + const { systemdUnitContents } = await import("../../src/hooks/daemon-service"); + const unit = systemdUnitContents("/opt/failproofaid", "'/home/a/bin%n/node' '/pkg/dist/worker.mjs'"); + expect(unit).toContain(`Environment="FAILPROOFAI_WORKER_CMD='/home/a/bin%%n/node' '/pkg/dist/worker.mjs'"`); + }); + it("saves a stable link to the runtime when PATH has one, not a versioned path", async () => { // Homebrew's execPath is .../Cellar/node//bin/node, which // `brew upgrade node` deletes; /opt/homebrew/bin/node survives it. @@ -697,15 +707,17 @@ describe("hooks/daemon-service", () => { writeFileSync(resolve(cellar, "node"), ""); symlinkSync(resolve(cellar, "node"), resolve(stable, "node")); - expect(stableExecPath(resolve(cellar, "node"), `/usr/bin:${stable}`)).toBe(resolve(stable, "node")); + const allowed = [stable]; + expect(stableExecPath(resolve(cellar, "node"), `/usr/bin:${stable}`, allowed)).toBe(resolve(stable, "node")); // No link on PATH: execPath, as before. - expect(stableExecPath(resolve(cellar, "node"), "/usr/bin")).toBe(resolve(cellar, "node")); - // execPath itself on PATH first: kept. - expect(stableExecPath(resolve(cellar, "node"), `${cellar}:${stable}`)).toBe(resolve(cellar, "node")); + expect(stableExecPath(resolve(cellar, "node"), "/usr/bin", allowed)).toBe(resolve(cellar, "node")); + // A link in a directory that is not a system bin dir (a temporary one + // could vanish after setup) is never saved. + expect(stableExecPath(resolve(cellar, "node"), stable, [])).toBe(resolve(cellar, "node")); // A different file of the same name is not the same runtime. rmSync(resolve(stable, "node")); writeFileSync(resolve(stable, "node"), ""); - expect(stableExecPath(resolve(cellar, "node"), stable)).toBe(resolve(cellar, "node")); + expect(stableExecPath(resolve(cellar, "node"), stable, allowed)).toBe(resolve(cellar, "node")); } finally { rmSync(root, { recursive: true, force: true }); } @@ -1316,6 +1328,8 @@ describe("refreshDaemonToCliVersion", () => { let primed = false; const result = await svc.refreshDaemonToCliVersion({ status: () => "running", + // This machine's own service definition must not decide the test. + needsUpgrade: () => false, install: async () => { installed = true; return { installed: true }; diff --git a/__tests__/hooks/gateway-restart.test.ts b/__tests__/hooks/gateway-restart.test.ts index e855a11c0..a716479a6 100644 --- a/__tests__/hooks/gateway-restart.test.ts +++ b/__tests__/hooks/gateway-restart.test.ts @@ -10,6 +10,7 @@ import { restartHermesGateway, restartOpenClawGateway, restartOpenClawGateways, + openclawProfileEnv, type CommandResult, } from "../../src/hooks/gateway-restart"; @@ -136,3 +137,33 @@ describe("update's OpenClaw rows", () => { ]); }); }); + +describe("OpenClaw profile selection", () => { + it("drops every selector the caller's shell set, so a row acts on its own profile", () => { + const shell = { OPENCLAW_PROFILE: "ops", OPENCLAW_STATE_DIR: "/h/.openclaw-ops", OPENCLAW_CONFIG_PATH: "/x.json", PATH: "/bin" } as unknown as NodeJS.ProcessEnv; + const env = openclawProfileEnv({ name: "default", home: "/h/.openclaw" }, shell); + expect(env).toEqual({ PATH: "/bin" }); + // A default profile at a non-standard location is named by its directory. + expect(openclawProfileEnv({ name: "default", home: "/srv/claw" }, shell).OPENCLAW_STATE_DIR).toBe("/srv/claw"); + // A named one is selected by --profile, never by the inherited env. + expect(openclawProfileEnv({ name: "ops", home: "/h/.openclaw-ops" }, shell).OPENCLAW_PROFILE).toBeUndefined(); + }); + + it("probes and restarts the default profile with no inherited selector", () => { + const prev = process.env.OPENCLAW_PROFILE; + process.env.OPENCLAW_PROFILE = "ops"; + try { + const d = deps({ + "openclaw gateway status --json": ok(RUNNING), + "openclaw gateway restart --help": SAFE_HELP, + }); + restartOpenClawGateway({ name: "default", home: "/h/.openclaw" }, d); + for (const call of [...d.run.mock.calls, ...d.spawnDetached.mock.calls]) { + expect(call[2].OPENCLAW_PROFILE).toBeUndefined(); + } + } finally { + if (prev === undefined) delete process.env.OPENCLAW_PROFILE; + else process.env.OPENCLAW_PROFILE = prev; + } + }); +}); diff --git a/__tests__/hooks/handler.test.ts b/__tests__/hooks/handler.test.ts index c105d5c4e..ca426c8d3 100644 --- a/__tests__/hooks/handler.test.ts +++ b/__tests__/hooks/handler.test.ts @@ -204,7 +204,9 @@ describe("hooks/handler", () => { await handleHookEvent("PreToolUse"); const entry = vi.mocked(persistHookActivity).mock.calls.at(-1)![0]; expect(entry.toolCallId).toBe("toolu_01ABC"); - expect(entry.startedAt).toBe(entry.timestamp - (entry.durationMs ?? 0)); + expect(entry.startedAt).toBeLessThanOrEqual(entry.timestamp); + // Two clocks (wall and monotonic), each rounded: within a millisecond. + expect(entry.timestamp - entry.startedAt!).toBeGreaterThanOrEqual((entry.durationMs ?? 0) - 1); }); it("finds the tool call id in each agent's payload shape", async () => { diff --git a/__tests__/hooks/hermes-update.test.ts b/__tests__/hooks/hermes-update.test.ts index 02840ef95..75c7cd94f 100644 --- a/__tests__/hooks/hermes-update.test.ts +++ b/__tests__/hooks/hermes-update.test.ts @@ -301,6 +301,9 @@ describe("failproofai update → Hermes migration", () => { expect(restartGateway).toHaveBeenCalledTimes(1); expect(restartGateway.mock.calls[0][0]).toMatchObject({ name: "default", home: home() }); expect(result.lines.join("\n")).toMatch(/hermes\/default\s+migrated — shell hooks → linked plugin, gateway restarting/); + // Never also told to restart the gateway by hand: that interrupts its drain. + expect(result.lines.join("\n")).toMatch(/restart running Hermes sessions to load it there/); + expect(result.lines.join("\n")).not.toMatch(/restart running Hermes gateways/); }); it("without a restarter (update --no-restart) the rows are unchanged", async () => { diff --git a/__tests__/hooks/policies-listing.test.ts b/__tests__/hooks/policies-listing.test.ts index a5ef14b46..ee5d6a42f 100644 --- a/__tests__/hooks/policies-listing.test.ts +++ b/__tests__/hooks/policies-listing.test.ts @@ -473,6 +473,18 @@ describe("renderPoliciesScreen", () => { expect(managed.at(-1)).toBe(" Deploy from Cloud: https://be.failproof.ai"); }); + it("treats a machine connected through FAILPROOFAI_CLOUD_URL as pulling from Cloud", async () => { + const { cloudDashboardUrlForTest } = await import("@/src/hooks/manager"); + const prev = process.env.FAILPROOFAI_CLOUD_URL; + process.env.FAILPROOFAI_CLOUD_URL = "https://staging.example/org"; + try { + expect(cloudDashboardUrlForTest()).toBe("https://staging.example/org"); + } finally { + if (prev === undefined) delete process.env.FAILPROOFAI_CLOUD_URL; + else process.env.FAILPROOFAI_CLOUD_URL = prev; + } + }); + function withTruecolor(fn: () => T): T { const before = { COLORTERM: process.env.COLORTERM, TERM: process.env.TERM, NO_COLOR: process.env.NO_COLOR }; process.env.COLORTERM = "truecolor"; diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index ec85354ad..f9e888984 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -1236,8 +1236,14 @@ async function runCli() { // now running can do: the native plugin needs `policyEvaluation`, which // ≤1.0.5 daemons lack, so when the swap above could not happen (a sudo // system service with no sudo) the shell hooks stay and this fails loudly. - // Gateways are restarted only onto a daemon this run left current. - const restartsGateways = daemonOk && !subArgs.includes("--no-daemon") && !subArgs.includes("--no-restart"); + // Gateways are restarted only onto a daemon this run left current AND that + // is running: "nothing to update" on a machine with no service, or an + // unsupported platform, is also `daemonOk`. + let restartsGateways = daemonOk && !subArgs.includes("--no-daemon") && !subArgs.includes("--no-restart"); + if (restartsGateways) { + const svc = await import("../src/hooks/daemon-service"); + restartsGateways = svc.isDaemonSupportedPlatform() && svc.daemonServiceStatus() === "running"; + } let hermesOk = true; let hermesMigrated = 0; try { diff --git a/crates/PROTOCOL.md b/crates/PROTOCOL.md index d9ad9d8e0..6c009f751 100644 --- a/crates/PROTOCOL.md +++ b/crates/PROTOCOL.md @@ -76,8 +76,10 @@ Protocol v2 carries the originating agent's settings path for both `hook` and native `policyEvaluation` requests. A missing path is unresolved, never inferred from the long-lived daemon's environment. A v1 daemon cannot be trusted with a v2 scoped request: it may discard this field and evaluate for -the wrong profile. The v2 client rejects every v1 response and tells the -operator to reinstall/restart the daemon before evaluation resumes. +the wrong profile. So a v2 client never uses a v1 daemon's answer to a v2 +request; it asks again in v1, without the field (see "Protocol versioning"), +except where the machine's Cloud deployment targets policies at agents, which +an unnamed agent would escape: there it fails closed. ### Daemon → client (`ServerMessage`) @@ -113,6 +115,12 @@ asks once more in that version, without the fields that version predates. The answer to the original request is never used. Anything outside the range gets an explicit `error`, and a daemon-configured client fails closed on it. +Neither fallback runs where the active Cloud deployment targets policies at +agents (`active.json` schema 3), or cannot be read: an older request names no +agent, and a targeted policy does not apply to an unknown one. There the daemon +refuses a v1 request (stamped v1, so the old client's own fail-closed path +blocks it) and a current client does not re-ask an older daemon. + This exists because a long-lived host (a Hermes or OpenClaw gateway) keeps the plugin it loaded at start: after an upgrade it speaks the previous version until it restarts, and refusing it denied every call it made. Versions only add diff --git a/crates/failproofaid/src/audit_lane.rs b/crates/failproofaid/src/audit_lane.rs index 4bb94c69d..0b37f68f1 100644 --- a/crates/failproofaid/src/audit_lane.rs +++ b/crates/failproofaid/src/audit_lane.rs @@ -541,7 +541,12 @@ impl Lane { return; } self.announced = Some(state); - tracing::info!("{message}"); + // A lane that cannot run says why at WARN, where a quiet log still + // shows it; an ordinary on/off change is INFO. + match state { + Announced::NoCliCommand | Announced::NoSchedule => tracing::warn!("{message}"), + Announced::Off | Announced::Scheduled => tracing::info!("{message}"), + } } } diff --git a/crates/failproofaid/src/cloud_client.rs b/crates/failproofaid/src/cloud_client.rs index b3cf2c766..e4957c252 100644 --- a/crates/failproofaid/src/cloud_client.rs +++ b/crates/failproofaid/src/cloud_client.rs @@ -1081,14 +1081,19 @@ pub fn spawn_maintenance( idle_interval: Duration, ) -> JoinHandle<()> { std::thread::spawn(move || { + // Outside the supervised body on purpose: a restart after a panic must + // remember the identity it last saw. Forgetting it made an org switch + // during the backoff read as a first identity (whose deployment 0 the + // rollback floor then refused) and a removed credential read as never + // enrolled (so nothing was deactivated). + let mut last_state: Option = None; + // `None` until the first successful resolution; then the identity seen + // last (itself `None` when not enrolled). + let mut last_identity: Option> = None; + // Set when the identity changed and the new one has not yet completed a + // reconcile. See below. + let mut floor_reset_pending = false; crate::supervised("cloud policy sync", &shutdown, || { - let mut last_state: Option = None; - // `None` until the first successful resolution; then the identity seen - // last (itself `None` when not enrolled). - let mut last_identity: Option> = None; - // Set when the identity changed and the new one has not yet completed a - // reconcile. See below. - let mut floor_reset_pending = false; while !shutdown.load(Ordering::Relaxed) { if let (Ok(path), Some(home)) = (agent_roster::roster_path(), std::env::var_os("HOME")) @@ -1639,9 +1644,22 @@ mod tests { let sink = captured.clone(); let server = std::thread::spawn(move || { let (mut stream, _) = listener.accept().unwrap(); - let mut request = [0_u8; 4096]; - let read = stream.read(&mut request).unwrap(); - *sink.lock().unwrap() = String::from_utf8_lossy(&request[..read]).to_string(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + // Through the end of the headers, not one read: a read that + // returned after the request line made the User-Agent + // assertion below fail on a client that sent it. + let mut request = Vec::new(); + let mut chunk = [0_u8; 4096]; + while !request.windows(4).any(|w| w == b"\r\n\r\n") && request.len() < 65_536 { + let read = stream.read(&mut chunk).unwrap(); + if read == 0 { + break; + } + request.extend_from_slice(&chunk[..read]); + } + *sink.lock().unwrap() = String::from_utf8_lossy(&request).to_string(); let body = br#"{"schemaVersion":2,"deployment":7,"policies":[]}"#; write!( stream, diff --git a/crates/failproofaid/src/logfile.rs b/crates/failproofaid/src/logfile.rs index 8982fcf4d..b8b90591e 100644 --- a/crates/failproofaid/src/logfile.rs +++ b/crates/failproofaid/src/logfile.rs @@ -29,12 +29,20 @@ struct Inner { } impl Inner { + /// Owner-only, created that way and tightened if an older file is not: + /// the log carries machine ids and policy diagnostics, and a home another + /// account can traverse must not make it readable to them. fn open(&mut self) { + use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; self.file = OpenOptions::new() .create(true) .append(true) + .mode(0o600) .open(&self.path) .ok(); + if self.file.is_some() { + let _ = fs::set_permissions(&self.path, fs::Permissions::from_mode(0o600)); + } self.size = fs::metadata(&self.path).map(|m| m.len()).unwrap_or(0); } @@ -47,6 +55,10 @@ impl Inner { fn write(&mut self, buf: &[u8]) { if self.size >= self.max_bytes { self.rotate(); + } else if self.file.is_none() { + // A rotation whose new file could not be created (a full disk, + // say): try again rather than stay silent until a restart. + self.open(); } if let Some(file) = self.file.as_mut() && file.write_all(buf).is_ok() @@ -196,6 +208,28 @@ mod tests { fs::remove_dir_all(dir).ok(); } + #[test] + fn the_log_is_owner_only() { + use std::os::unix::fs::PermissionsExt; + let dir = temp_dir("mode"); + let path = dir.join("daemon.log"); + fs::write(&path, "older\n").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + let mut log = RotatingFile::open(path.clone(), 10, 1).unwrap(); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + log.write_all(b"0123456789ab\n").unwrap(); + log.write_all(b"x\n").unwrap(); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600, + "after rotation" + ); + fs::remove_dir_all(dir).ok(); + } + #[test] fn a_missing_home_is_never_created() { let dir = temp_dir("no-home"); diff --git a/crates/failproofaid/src/main.rs b/crates/failproofaid/src/main.rs index 0c9ed553e..76755c04b 100644 --- a/crates/failproofaid/src/main.rs +++ b/crates/failproofaid/src/main.rs @@ -113,28 +113,33 @@ fn main() { /// already goes and what systemd/launchd capture. `RUST_LOG` overrides the /// default level. /// -/// Also to `~/.failproofai/logs/daemon.log` (see `logfile.rs`), and on macOS the -/// launchd stderr file is bounded first, since nothing else ever rotates it. +/// Also to `~/.failproofai/logs/daemon.log` (see `logfile.rs`). On macOS that +/// file then carries everything and stderr only WARN and above: launchd's +/// `failproofaid.err.log` is a file nothing rotates during uptime, and a copy +/// of every INFO line grew it without bound. fn init_logging() { use tracing_subscriber::EnvFilter; use tracing_subscriber::fmt::writer::MakeWriterExt; let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); - let logs = paths::failproofai_home().ok().map(|home| home.join("logs")); - #[cfg(target_os = "macos")] - if let Some(logs) = &logs { - logfile::bound_inherited_log( - &logs.join("failproofaid.err.log"), + let file = paths::failproofai_home().ok().and_then(|home| { + logfile::RotatingFile::open( + home.join("logs").join("daemon.log"), logfile::MAX_BYTES, logfile::KEEP, - ); - } - let file = logs.and_then(|logs| { - logfile::RotatingFile::open(logs.join("daemon.log"), logfile::MAX_BYTES, logfile::KEEP) + ) }); let builder = tracing_subscriber::fmt().with_env_filter(filter); + #[cfg(target_os = "macos")] + let stderr = std::io::stderr.with_max_level(if file.is_some() { + tracing::Level::WARN + } else { + tracing::Level::TRACE + }); + #[cfg(not(target_os = "macos"))] + let stderr = std::io::stderr; let _ = match file { - Some(file) => builder.with_writer(std::io::stderr.and(file)).try_init(), - None => builder.with_writer(std::io::stderr).try_init(), + Some(file) => builder.with_writer(stderr.and(file)).try_init(), + None => builder.with_writer(stderr).try_init(), }; } @@ -144,6 +149,17 @@ fn run() -> Result<(), Box> { let lock_path = paths::lock_path()?; paths::ensure_run_dir()?; let _singleton = lock::acquire(&lock_path)?; + // Only the instance holding the lock may rotate the log launchd gives the + // running service: a second invocation copying and truncating it could + // cut out lines the live daemon appended in between. + #[cfg(target_os = "macos")] + if let Ok(home) = paths::failproofai_home() { + logfile::bound_inherited_log( + &home.join("logs").join("failproofaid.err.log"), + logfile::MAX_BYTES, + logfile::KEEP, + ); + } // The shutdown flag and its signal handler are installed BEFORE anything // long-running starts, so every lane below observes the same flag the socket @@ -664,7 +680,9 @@ fn supervised_with_backoff( match std::panic::catch_unwind(std::panic::AssertUnwindSafe(&mut body)) { Ok(()) => return, Err(_) => { - tracing::warn!( + // Not `eprintln!`, which panics when stderr cannot be written, + // outside the catch: that ended the very loop meant to survive. + tracing::error!( "{name} panicked; starting it again in {}s", backoff.as_secs() ); @@ -675,6 +693,10 @@ fn supervised_with_backoff( } std::thread::sleep(Duration::from_millis(20).min(backoff)); } + // A shutdown during the last sleep must not start the lane again. + if shutdown.load(Ordering::Relaxed) { + return; + } } } } @@ -1065,7 +1087,7 @@ fn collector_tasks(config: Option) -> Vec) -> Vec io::Result<()> // argument (os error 22)": setsockopt on a socket the peer closed // is EINVAL there. How long the evaluation took is the useful part. io::Error::other(format!( - "the client closed the connection before its verdict was ready \ + "the client had closed the connection when its verdict was written \ (evaluation took {} ms)", took.as_millis() )) @@ -1109,7 +1109,7 @@ mod tests { let err = handle_connection(server, &worker).expect_err("the peer is gone"); assert!( err.to_string() - .contains("closed the connection before its verdict"), + .contains("had closed the connection when its verdict was written"), "got: {err}" ); } diff --git a/crates/failproofaid/src/telemetry.rs b/crates/failproofaid/src/telemetry.rs index e82782c31..70699c646 100644 --- a/crates/failproofaid/src/telemetry.rs +++ b/crates/failproofaid/src/telemetry.rs @@ -194,17 +194,22 @@ impl Lane { // impossible, but this is reached from the hook path and a panic here // would deny a tool call over a telemetry event. let mut ring = self.ring.lock().unwrap_or_else(|e| e.into_inner()); + let mut warn = false; if ring.len() >= RING_CAPACITY { // Oldest out, not newest refused: the interesting events in an // overflow are the recent ones, and the head is what a failing send // is stuck on. ring.pop_front(); self.dropped.fetch_add(1, Ordering::Relaxed); - if !self.warned_dropped.swap(true, Ordering::Relaxed) { - tracing::warn!("telemetry buffer is full; dropping the oldest events"); - } + warn = !self.warned_dropped.swap(true, Ordering::Relaxed); } ring.push_back(event); + drop(ring); + // After the lock: the log now also writes a file, and a stalled write + // must neither hold up this hook call's push nor the drain behind it. + if warn { + tracing::warn!("telemetry buffer is full; dropping the oldest events"); + } } /// Take everything currently buffered. The lock is released before the diff --git a/crates/failproofaid/src/worker.rs b/crates/failproofaid/src/worker.rs index bf8243623..1eb03a94c 100644 --- a/crates/failproofaid/src/worker.rs +++ b/crates/failproofaid/src/worker.rs @@ -83,7 +83,9 @@ pub struct PolicyEvaluation { fn early_exit_hint(code: Option) -> &'static str { match code { Some(127) => { - "; the Node.js or failproofai path saved at install no longer exists, run `failproofai update`" + "; a command it runs was not found: if this is the installed service, the Node.js \ + or failproofai path saved at install may be gone (run `failproofai update`); \ + otherwise check FAILPROOFAI_WORKER_CMD" } _ => "", } diff --git a/crates/fpai-collect/src/supervisor.rs b/crates/fpai-collect/src/supervisor.rs index bc7f2c0f0..d0bdba458 100644 --- a/crates/fpai-collect/src/supervisor.rs +++ b/crates/fpai-collect/src/supervisor.rs @@ -259,6 +259,30 @@ impl CollectorHandle { } } +/// A handle dropped while its owner panics stops its collector instead of +/// abandoning it running. +/// +/// The daemon's collector manager is restarted after a panic. Unwinding drops +/// the handles it held, and a handle that only detached left that collector +/// running: the restarted manager then started a second one over the same +/// queues and cursors. Bounded by the flush budget, like process exit, so a +/// wedged collector cannot hang the unwind. An ordinary drop is unchanged. +impl Drop for CollectorHandle { + fn drop(&mut self) { + if !std::thread::panicking() || self.thread.is_none() { + return; + } + let handle = CollectorHandle { + thread: self.thread.take(), + stop: self.stop.clone(), + metrics: self.metrics.clone(), + }; + if handle.stop_within(crate::DEFAULT_FLUSH_BUDGET).is_err() { + tracing::warn!("a collector abandoned by a panic did not stop within its flush budget"); + } + } +} + /// Start the collector on its own thread with its own Tokio runtime. /// /// `shutdown` is the daemon's existing flag, observed rather than owned, so a diff --git a/crates/fpai-collect/tests/supervisor.rs b/crates/fpai-collect/tests/supervisor.rs index 68ca43f5d..05bcbafe3 100644 --- a/crates/fpai-collect/tests/supervisor.rs +++ b/crates/fpai-collect/tests/supervisor.rs @@ -322,3 +322,41 @@ fn a_slow_stop_hands_the_handle_back_and_a_later_wait_completes_it() { assert!(handle.stop_within(Duration::from_secs(2)).is_ok()); assert!(finished.load(Ordering::SeqCst)); } + +#[test] +fn a_handle_dropped_by_a_panic_stops_its_collector() { + // The daemon restarts a panicked collector manager; a handle that only + // detached left the old collector running beside the new one. + let shutdown = Arc::new(AtomicBool::new(false)); + let running = Arc::new(AtomicUsize::new(0)); + let alive = running.clone(); + let handle = spawn_supervised( + vec![TaskSpec::new("source", move |sd| { + let alive = alive.clone(); + async move { + alive.fetch_add(1, Ordering::SeqCst); + while !sd.is_set() { + sd.sleep(Duration::from_millis(10)).await; + } + alive.fetch_sub(1, Ordering::SeqCst); + Ok(()) + } + })], + shutdown.clone(), + ) + .expect("supervisor should start"); + assert!(wait_until(Duration::from_secs(5), || running + .load(Ordering::SeqCst) + == 1)); + + let owner = std::thread::spawn(move || { + let _held = handle; + panic!("collector manager bug"); + }); + assert!(owner.join().is_err()); + assert_eq!( + running.load(Ordering::SeqCst), + 0, + "the unwind stopped the collector" + ); +} diff --git a/src/hooks/config-status.ts b/src/hooks/config-status.ts index 4b20e707b..e24a69387 100644 --- a/src/hooks/config-status.ts +++ b/src/hooks/config-status.ts @@ -83,6 +83,8 @@ export type StatusCloud = | { kind: "file"; host: string; + /** The dashboard as configured, path included. */ + url?: string; /** The org as the server named it at connect time, when it did. */ org?: string; machine?: string; @@ -317,6 +319,7 @@ export async function gatherStatusFacts(deps: StatusDeps = {}): Promise 0 ? "failproofai policies add" : `failproofai policies add ${CORE_SOURCE}`; diff --git a/src/hooks/daemon-service.ts b/src/hooks/daemon-service.ts index e745a273e..422dc2635 100644 --- a/src/hooks/daemon-service.ts +++ b/src/hooks/daemon-service.ts @@ -280,6 +280,7 @@ export function resolveWorkerCommand(): string | null { export function stableExecPath( execPath: string = process.execPath, pathEnv: string = process.env.PATH ?? "", + stableDirs: readonly string[] = STABLE_BIN_DIRS, ): string { let real: string; try { @@ -289,7 +290,10 @@ export function stableExecPath( } const name = execPath.split("/").pop() ?? ""; for (const dir of pathEnv.split(":")) { - if (!dir.startsWith("/")) continue; + // Only a system bin directory a package manager owns: any PATH entry would + // let a temporary one (a dev shell, a CI step) be saved into the service + // and vanish after setup, taking the worker's runtime with it. + if (!dir.startsWith("/") || !stableDirs.includes(dir.replace(/\/+$/, ""))) continue; const candidate = resolve(dir, name); if (candidate === execPath) return execPath; try { @@ -301,15 +305,32 @@ export function stableExecPath( return execPath; } +/** Where Homebrew, Linuxbrew and the distributions keep a stable `node` link. */ +const STABLE_BIN_DIRS: readonly string[] = [ + "/opt/homebrew/bin", + "/usr/local/bin", + "/usr/bin", + "/home/linuxbrew/.linuxbrew/bin", +]; + /** - * Whether a saved `FAILPROOFAI_WORKER_CMD` / `FAILPROOFAI_CLI_CMD` names a - * file that no longer exists. Only a command this package wrote (quoted words) - * is judged; an operator's own command is never second-guessed. + * Whether a saved `FAILPROOFAI_WORKER_CMD` / `FAILPROOFAI_CLI_CMD` is one this + * package generated: `'' '/dist/worker.mjs'` (or `cli.mjs`). + * Quoting alone does not say so, since an operator can quote their own. + */ +function isPackageCommand(command: string | null): boolean { + const words = command ? shellQuotedWords(command) : null; + const script = words?.at(-1); + return words?.length === 2 && script !== undefined && /\/dist\/(worker|cli)\.mjs$/.test(script); +} + +/** + * Whether a saved command this package generated names a file that no longer + * exists. An operator's own command is never second-guessed. */ function savedCommandIsGone(command: string | null): boolean { - if (!command) return false; - const words = shellQuotedWords(command); - return words !== null && words.some((word) => word.startsWith("/") && !existsSync(word)); + if (!isPackageCommand(command)) return false; + return shellQuotedWords(command!)!.some((word) => !existsSync(word)); } /** @@ -828,7 +849,9 @@ export function systemdUnitContents( // Quoted because every value here contains a space or a path — systemd's // Environment= requires quoting whenever the value does. const envLines = serviceEnvironment(workerCmd, cliCmd) - .map(([key, value]) => `Environment="${key}=${assertUnitSafe(value, key)}"\n`) + // `%` is a specifier inside a unit (`%n` is the unit name, `%h` a home), + // so a literal one is written `%%` or the path silently changes. + .map(([key, value]) => `Environment="${key}=${assertUnitSafe(value, key).replace(/%/g, "%%")}"\n`) .join(""); const user = assertUnitSafe(serviceUser(), "User"); assertUnitSafe(binaryPath, "ExecStart"); @@ -1036,7 +1059,14 @@ export async function installDaemonService(): Promise { // and threading it through as an absolute path in the service's // environment is what makes a *service-managed* daemon actually find its // worker regardless of what cwd the service manager starts it from. - const workerCmd = resolveWorkerCommand(); + // An operator's own worker command saved in the service survives a + // reinstall (one an expired audit path forces, say) when the shell running + // it no longer exports FAILPROOFAI_WORKER_CMD; only a generated one is + // re-resolved. + const savedWorker = process.env.FAILPROOFAI_WORKER_CMD + ? null + : installedEnvValue(readInstalledServiceDefinition() ?? "", "FAILPROOFAI_WORKER_CMD"); + const workerCmd = savedWorker && !isPackageCommand(savedWorker) ? savedWorker : resolveWorkerCommand(); // Same best-effort footing as the worker command, and null is survivable in // the same way — the daemon just has no way to run an audit. Unlike the // worker, there is no relative-path fallback to degrade to, which is exactly @@ -1100,15 +1130,19 @@ export async function installDaemonService(): Promise { const plistPath = launchdPlistPath(); const logDir = logsDir(); mkdirSync(logDir, { recursive: true }); - // Unload any previously-loaded copy first — reloading with a changed - // binary path (e.g. after an upgrade) is a no-op under plain `load` - // if launchd thinks the label is already loaded. + // Written BEFORE the unload: a write that fails then leaves the running + // daemon loaded and untouched, where unloading first left a healthy + // machine with no daemon (every hook denied) over a failed rewrite. + // `unload` finds the job by its label, which the new plist keeps. + writePrivilegedFile(plistPath, launchdPlistContents(binaryPath, logDir, workerCmd, cliCmd)); + // Unload any previously-loaded copy — reloading with a changed binary + // path (e.g. after an upgrade) is a no-op under plain `load` if launchd + // thinks the label is already loaded. try { runPrivileged("launchctl", ["unload", plistPath]); } catch { // Wasn't loaded — fine, this is the common case on a fresh install. } - writePrivilegedFile(plistPath, launchdPlistContents(binaryPath, logDir, workerCmd, cliCmd)); runPrivileged("launchctl", ["load", "-w", plistPath]); } } catch (err) { @@ -1397,7 +1431,7 @@ function readInstalledServiceDefinition(): string | null { function installedEnvValue(definition: string, name: string): string | null { if (process.platform === "linux") { const m = new RegExp(`^Environment="${name}=(.*)"$`, "m").exec(definition); - return m ? m[1] : null; + return m ? m[1].replace(/%%/g, "%") : null; } const m = new RegExp(`${name}\\s*([^<]*)`).exec(definition); return m ? unescapeXml(m[1]) : null; @@ -1469,7 +1503,13 @@ export function upgradedServiceDefinition( ): string | null { const binaryPath = installedExecStart(definition); if (!binaryPath) return null; - const workerCmd = resolveWorkerCommand() ?? installedEnvValue(definition, "FAILPROOFAI_WORKER_CMD"); + const saved = installedEnvValue(definition, "FAILPROOFAI_WORKER_CMD"); + // An operator's own saved command is carried over, never replaced by the + // package default (only a generated one is re-resolved). + const workerCmd = + !process.env.FAILPROOFAI_WORKER_CMD && saved && !isPackageCommand(saved) + ? saved + : (resolveWorkerCommand() ?? saved); try { return process.platform === "linux" ? systemdUnitContents(binaryPath, workerCmd, cliCmd) @@ -1623,7 +1663,9 @@ async function refreshFailed(message: string, previous: string | null): Promise< */ export async function ensureDaemonServiceCurrent(): Promise { const definition = readInstalledServiceDefinition(); - if (definition === null || definition.includes("FAILPROOFAI_CLI_CMD")) { + // The same test `update` uses: a definition carrying FAILPROOFAI_CLI_CMD is + // still stale when a generated command in it names a file that is gone. + if (definition === null || !daemonServiceNeedsUpgrade()) { return { outcome: "current" }; } diff --git a/src/hooks/gateway-restart.ts b/src/hooks/gateway-restart.ts index e9d5b43d6..61ada9df9 100644 --- a/src/hooks/gateway-restart.ts +++ b/src/hooks/gateway-restart.ts @@ -23,7 +23,7 @@ */ import { spawn, spawnSync } from "node:child_process"; import { closeSync, mkdirSync, openSync, readFileSync } from "node:fs"; -import { dirname, join } from "node:path"; +import { basename, dirname, join } from "node:path"; import { listOpenClawProfiles, OPENCLAW_DEFAULT_PROFILE } from "../../lib/openclaw-profiles"; import { logsDir } from "./fp-home"; @@ -57,6 +57,9 @@ function defaultRun(cmd: string, args: string[], env: NodeJS.ProcessEnv): Comman env, encoding: "utf8", timeout: STATUS_TIMEOUT_MS, + // SIGTERM is the default, and a status command that handles it and stays + // stuck kept `update` from ever printing its report. + killSignal: "SIGKILL", stdio: ["ignore", "pipe", "pipe"], }); return { status: out.error ? null : out.status, stdout: `${out.stdout ?? ""}${out.stderr ?? ""}` }; @@ -145,7 +148,7 @@ function restartOpenClawGatewayUnsafe( const run = deps.run ?? defaultRun; const spawnDetached = deps.spawnDetached ?? defaultSpawnDetached; const profileArgs = profile.name === OPENCLAW_DEFAULT_PROFILE ? [] : ["--profile", profile.name]; - const env = { ...process.env }; + const env = openclawProfileEnv(profile); const result = (status: GatewayRestartStatus): GatewayRestart => ({ host: "openclaw", profile: profile.name, status }); const out = run("openclaw", [...profileArgs, "gateway", "status", "--json"], env); @@ -169,6 +172,26 @@ function restartOpenClawGatewayUnsafe( ); } +/** + * The environment that selects exactly `profile`, and no other. Every OpenClaw + * profile selector inherited from the caller's shell is dropped: left in, the + * default row inherited an `OPENCLAW_PROFILE=ops` and acted on `ops`. A default + * profile living somewhere non-standard is named by its state directory. + */ +export function openclawProfileEnv( + profile: { name: string; home: string }, + base: NodeJS.ProcessEnv = process.env, +): NodeJS.ProcessEnv { + const env = { ...base }; + for (const key of ["OPENCLAW_PROFILE", "OPENCLAW_STATE_DIR", "OPENCLAW_HOME", "OPENCLAW_CONFIG_PATH"]) { + delete env[key]; + } + if (profile.name === OPENCLAW_DEFAULT_PROFILE && basename(profile.home) !== ".openclaw") { + env.OPENCLAW_STATE_DIR = profile.home; + } + return env; +} + /** Profiles whose openclaw.json loads our plugin; only their gateways run it. */ function openclawProfilesUsingFailproofai(): Array<{ name: string; home: string }> { return listOpenClawProfiles().filter((profile) => { diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 3f6c37680..3ca7992ef 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -671,6 +671,9 @@ export async function evaluateHookEvent( opts?: EvaluateHookEventOptions, ): Promise { const startTime = performance.now(); + // Wall clock at arrival, for the activity row's `startedAt`. Taken here, not + // derived from `durationMs`, which is measured before the work after it. + const arrivedAt = Date.now(); // A home from another layout resolves to no global config, so every builtin // silently stops firing — the machine looks protected and is not. Say so on // every call rather than deleting anything (a hook is unattended) or denying @@ -1272,7 +1275,7 @@ export async function evaluateHookEvent( timestamp: writtenAt, // When the hook arrived. `timestamp` is when its evaluation ENDED, so a // hook start ordered by it sorted late by the whole evaluation. - startedAt: writtenAt - durationMs, + startedAt: Math.min(arrivedAt, writtenAt), // The agent's own id for the tool call this hook governed, the key its // transcript records the call under (see `toolCallIdOf`). ...(toolCallId ? { toolCallId } : {}), diff --git a/src/hooks/hermes-update.ts b/src/hooks/hermes-update.ts index 575ae662e..cafe47715 100644 --- a/src/hooks/hermes-update.ts +++ b/src/hooks/hermes-update.ts @@ -47,12 +47,15 @@ export async function runHermesUpdateMigration(deps: { const width = Math.max(...profiles.map((p) => ("hermes/" + p.name).length)); const lines = ["Hermes:"]; + let restarting = false; for (const p of profiles) { const label = ("hermes/" + p.name).padEnd(width); const detail = p.status === "current" ? "" : ` — ${p.detail}`; // Only a profile now on the linked plugin has new code for its gateway. const loaded = p.status === "migrated" || p.status === "current"; - const gateway = loaded && deps.restartGateway ? GATEWAY_STATUS_LABEL[deps.restartGateway(p).status] : ""; + const restart = loaded && deps.restartGateway ? deps.restartGateway(p).status : null; + if (restart === "restarting") restarting = true; + const gateway = restart ? GATEWAY_STATUS_LABEL[restart] : ""; lines.push(` ${label} ${STATUS_LABEL[p.status]}${detail}${gateway ? `, ${gateway}` : ""}`); } @@ -60,7 +63,11 @@ export async function runHermesUpdateMigration(deps: { const failed = profiles.filter((p) => p.status === "failed"); if (profiles.some((p) => p.status === "migrated")) { lines.push( - " Cron jobs load the plugin on their next run; restart running Hermes gateways and sessions to load it there.", + // A gateway already queued for restart must not also be restarted by + // hand: that interrupts its drain. + restarting + ? " Cron jobs load the plugin on their next run; restart running Hermes sessions to load it there." + : " Cron jobs load the plugin on their next run; restart running Hermes gateways and sessions to load it there.", ); } if (blocked.length > 0) { diff --git a/src/hooks/manager.ts b/src/hooks/manager.ts index 62749889f..1c7379b9b 100644 --- a/src/hooks/manager.ts +++ b/src/hooks/manager.ts @@ -1304,6 +1304,10 @@ export interface PoliciesScreen { /** The dashboard a cloud-connected machine pulls policies from, or undefined. */ function cloudDashboardUrl(): string | undefined { + // FAILPROOFAI_CLOUD_URL wins over the credential file in the daemon, so a + // machine connected that way pulls from Cloud too. + const fromEnv = process.env.FAILPROOFAI_CLOUD_URL?.trim(); + if (fromEnv) return fromEnv; try { return readCloudCredentials()?.url || undefined; } catch { @@ -1311,6 +1315,9 @@ function cloudDashboardUrl(): string | undefined { } } +/** @internal */ +export const cloudDashboardUrlForTest = cloudDashboardUrl; + /** * The policies screen (decision D14: "the policies list exactly as designed"). * diff --git a/src/hooks/shell-quote.ts b/src/hooks/shell-quote.ts index 56f6da95b..9187e3ade 100644 --- a/src/hooks/shell-quote.ts +++ b/src/hooks/shell-quote.ts @@ -16,9 +16,13 @@ export function shellQuote(value: string): string { export function shellQuotedWords(command: string): string[] | null { const words: string[] = []; const re = /\s*'((?:[^']|'\\'')*)'(?=\s|$)/y; + // Kept apart from `re.lastIndex`, which a failed sticky match resets to 0: + // a trailing space after the last word then read as "nothing matched". + let end = 0; let match: RegExpExecArray | null; - while (re.lastIndex < command.length && (match = re.exec(command))) { + while (end < command.length && (match = re.exec(command))) { words.push(match[1].replace(/'\\''/g, "'")); + end = re.lastIndex; } - return words.length > 0 && command.slice(re.lastIndex).trim() === "" ? words : null; + return words.length > 0 && command.slice(end).trim() === "" ? words : null; } From 1d71e7ac8e354967375dc5b0c5e338f439f07a8c Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 17:10:52 +0530 Subject: [PATCH 13/41] fix: second review round on #1023 (CI isolation, CodeRabbit) CI - daemon-client tests point FAILPROOFAI_HOME at a scratch home: a runner whose config.json is in `oss` mode hides every deployment, so the agent-targeted-deployment test saw none and failed in all three unit jobs. Fail-closed fallbacks - The TS client uses cloudDeploymentMayTargetAgents(): true unless the deployment is KNOWN untargeted, so an unreadable manifest no longer permits the v1 retry. The Hermes client reads active.json directly (Path.exists() reads a permission error as absent). The daemon treats anything but NotFound on active.json as unreadable, and re-checks after evaluation, so a deployment that became targeted mid-request withholds the answer. Daemon - A collector abandoned by a panic that does not stop in time is detached rather than dropped again inside Drop, which waited for ever. - An event parked alone is fsynced, and its directory, before the source batch is deleted: the server refused it, so the file is its only copy. - daemon.log is opened O_NONBLOCK|O_NOFOLLOW and used only if it is a regular file (a FIFO stalled startup), permissions set on the descriptor. Rotated names keep the path's own bytes. - macOS stderr is WARN-only only under launchd; the inherited log is bounded on a background thread so a large copy cannot delay the socket bind. - The VERSION read on each poll is bounded. Service definition - `%` is escaped only in commands this package generated; an operator's saved command keeps its systemd specifiers, its audit command survives a reinstall too, and the package worker condition is omitted when the operator's own worker runs. Conditions escape `%` as well. - ensureDaemonServiceCurrent refuses a rewrite that would still name a missing file instead of reporting "rewritten". - Unit and plist files are installed beside the destination and renamed over it: `install` onto the target unlinks it first. Gateways - A default OpenClaw profile relocated to a directory also named .openclaw is selected by its state directory, not mistaken for ~/.openclaw. --- .../fixtures/hermes-native-plugin-check.py | 13 ++++- __tests__/hooks/daemon-client.test.ts | 22 ++++++++ __tests__/hooks/daemon-service.test.ts | 11 ++++ __tests__/hooks/gateway-restart.test.ts | 6 +- crates/failproofaid/src/cloud_client.rs | 15 ++++- crates/failproofaid/src/logfile.rs | 55 ++++++++++++++---- crates/failproofaid/src/main.rs | 30 ++++++---- crates/failproofaid/src/server.rs | 28 +++++++++- crates/fpai-collect/src/supervisor.rs | 7 ++- crates/fpai-collect/src/uploader.rs | 13 ++++- hermes-plugin/client.py | 17 ++++-- src/hooks/cloud-managed-policies.ts | 22 ++++++++ src/hooks/daemon-client.ts | 7 ++- src/hooks/daemon-service.ts | 56 ++++++++++++++++--- src/hooks/gateway-restart.ts | 7 ++- 15 files changed, 262 insertions(+), 47 deletions(-) diff --git a/__tests__/fixtures/hermes-native-plugin-check.py b/__tests__/fixtures/hermes-native-plugin-check.py index cf9d33b7b..130bd16c8 100644 --- a/__tests__/fixtures/hermes-native-plugin-check.py +++ b/__tests__/fixtures/hermes-native-plugin-check.py @@ -1706,7 +1706,9 @@ class ProtocolCompatibilityTests(unittest.TestCase): """Files on disk can be newer than the daemon still running. An older daemon inside the supported range is asked again in its own version, not refused.""" - def _evaluate(self, responses: list[dict[str, object]], schema: int | None = None) -> tuple[object, list]: + def _evaluate( + self, responses: list[dict[str, object]], schema: int | None = None, raw: str | None = None + ) -> tuple[object, list]: with tempfile.TemporaryDirectory() as tmp: socket_path = Path(tmp) / "d.sock" policies = Path(tmp) / "cloud-policies" @@ -1715,6 +1717,8 @@ def _evaluate(self, responses: list[dict[str, object]], schema: int | None = Non (policies / "active.json").write_text( json.dumps({"schemaVersion": schema, "deployment": 4, "policies": []}) ) + if raw is not None: + (policies / "active.json").write_text(raw) received: list = [] thread = serve_verdicts(socket_path, responses, received) env = {"FAILPROOFAI_DAEMON_SOCKET": str(socket_path), "FAILPROOFAI_CLOUD_POLICY_DIR": str(policies)} @@ -1754,6 +1758,13 @@ def test_no_fallback_where_the_deployment_targets_agents(self) -> None: self.assertIsInstance(result, client.EvaluationError) self.assertEqual(len(received), 1) + def test_no_fallback_where_the_deployment_cannot_be_read(self) -> None: + result, received = self._evaluate( + [{"type": "error", "protocolVersion": 1, "message": "protocol version mismatch"}], raw="{" + ) + self.assertIsInstance(result, client.EvaluationError) + self.assertEqual(len(received), 1) + def test_no_retry_below_the_oldest_supported_version(self) -> None: result, received = self._evaluate([ {"type": "error", "protocolVersion": 0, "message": "protocol version mismatch"}, diff --git a/__tests__/hooks/daemon-client.test.ts b/__tests__/hooks/daemon-client.test.ts index 7e69a5bbf..1baf274a1 100644 --- a/__tests__/hooks/daemon-client.test.ts +++ b/__tests__/hooks/daemon-client.test.ts @@ -51,6 +51,7 @@ describe("hooks/daemon-client", () => { let tmpDir: string; let socketPath: string; let server: Server | null; + let prevHome: string | undefined; beforeEach(() => { tmpDir = mkdtempSync(join(tmpdir(), "fpai-daemon-client-test-")); @@ -60,12 +61,18 @@ describe("hooks/daemon-client", () => { // The fallback to an older daemon reads the Cloud deployment; never the // developer's own. process.env.FAILPROOFAI_CLOUD_POLICY_DIR = join(tmpDir, "cloud-policies"); + // And its config: one in `oss` mode (a CI runner's, say) hides any + // deployment, so the runner's own home must not decide these tests. + prevHome = process.env.FAILPROOFAI_HOME; + process.env.FAILPROOFAI_HOME = join(tmpDir, "home"); vi.resetModules(); }); afterEach(async () => { delete process.env.FAILPROOFAI_DAEMON_SOCKET; delete process.env.FAILPROOFAI_CLOUD_POLICY_DIR; + if (prevHome === undefined) delete process.env.FAILPROOFAI_HOME; + else process.env.FAILPROOFAI_HOME = prevHome; if (server) { await new Promise((r) => server!.close(() => r())); } @@ -295,6 +302,21 @@ describe("hooks/daemon-client", () => { expect(connections).toBe(1); }); + it("does not fall back where the deployment cannot be read to rule targets out", async () => { + mkdirSync(process.env.FAILPROOFAI_CLOUD_POLICY_DIR!, { recursive: true }); + writeFileSync(join(process.env.FAILPROOFAI_CLOUD_POLICY_DIR!, "active.json"), "{"); + let connections = 0; + await startServer(async (socket) => { + connections++; + await readFrame(socket); + socket.end(encodeFrame({ type: "hookResult", protocolVersion: 1, exitCode: 0, stdout: "", stderr: "" })); + }); + const { attemptDaemonHook } = await import("../../src/hooks/daemon-client"); + expect(await attemptDaemonHook({ hookEvent: "PreToolUse", cli: "claude", stdin: "{}" })) + .toEqual({ ok: false, failure: "protocol-mismatch" }); + expect(connections).toBe(1); + }); + it("does not retry below the oldest supported version", async () => { let connections = 0; await startServer(async (socket) => { diff --git a/__tests__/hooks/daemon-service.test.ts b/__tests__/hooks/daemon-service.test.ts index 03b8ea3a1..6dd7c5967 100644 --- a/__tests__/hooks/daemon-service.test.ts +++ b/__tests__/hooks/daemon-service.test.ts @@ -693,6 +693,17 @@ describe("hooks/daemon-service", () => { expect(unit).toContain(`Environment="FAILPROOFAI_WORKER_CMD='/home/a/bin%%n/node' '/pkg/dist/worker.mjs'"`); }); + it("writes an operator's own command as saved, specifiers and all, and does not gate on our worker", async () => { + useScratchHome(); + setPlatform("linux"); + process.env.FAILPROOFAI_PACKAGE_ROOT = resolve(__dirname, "..", ".."); + const { systemdUnitContents, workerScriptPath } = await import("../../src/hooks/daemon-service"); + const unit = systemdUnitContents("/opt/failproofaid", "/opt/team/%i/worker-wrapper"); + expect(unit).toContain(`Environment="FAILPROOFAI_WORKER_CMD=/opt/team/%i/worker-wrapper"`); + const script = workerScriptPath(); + if (script) expect(unit).not.toContain(`ConditionPathExists=${script}`); + }); + it("saves a stable link to the runtime when PATH has one, not a versioned path", async () => { // Homebrew's execPath is .../Cellar/node//bin/node, which // `brew upgrade node` deletes; /opt/homebrew/bin/node survives it. diff --git a/__tests__/hooks/gateway-restart.test.ts b/__tests__/hooks/gateway-restart.test.ts index a716479a6..8504619ed 100644 --- a/__tests__/hooks/gateway-restart.test.ts +++ b/__tests__/hooks/gateway-restart.test.ts @@ -141,10 +141,14 @@ describe("update's OpenClaw rows", () => { describe("OpenClaw profile selection", () => { it("drops every selector the caller's shell set, so a row acts on its own profile", () => { const shell = { OPENCLAW_PROFILE: "ops", OPENCLAW_STATE_DIR: "/h/.openclaw-ops", OPENCLAW_CONFIG_PATH: "/x.json", PATH: "/bin" } as unknown as NodeJS.ProcessEnv; - const env = openclawProfileEnv({ name: "default", home: "/h/.openclaw" }, shell); + const { homedir } = require("node:os") as typeof import("node:os"); + const env = openclawProfileEnv({ name: "default", home: `${homedir()}/.openclaw` }, shell); expect(env).toEqual({ PATH: "/bin" }); // A default profile at a non-standard location is named by its directory. expect(openclawProfileEnv({ name: "default", home: "/srv/claw" }, shell).OPENCLAW_STATE_DIR).toBe("/srv/claw"); + // Relocated, even when the directory is itself named `.openclaw`. + expect(openclawProfileEnv({ name: "default", home: "/srv/claw/.openclaw" }, shell).OPENCLAW_STATE_DIR) + .toBe("/srv/claw/.openclaw"); // A named one is selected by --profile, never by the inherited env. expect(openclawProfileEnv({ name: "ops", home: "/h/.openclaw-ops" }, shell).OPENCLAW_PROFILE).toBeUndefined(); }); diff --git a/crates/failproofaid/src/cloud_client.rs b/crates/failproofaid/src/cloud_client.rs index e4957c252..ce07e3d78 100644 --- a/crates/failproofaid/src/cloud_client.rs +++ b/crates/failproofaid/src/cloud_client.rs @@ -1412,13 +1412,26 @@ fn wait_until_shutdown(shutdown: &AtomicBool, interval: Duration) { } } +/// A file of at most 4 KiB, as text: the VERSION file is a few dozen bytes, +/// and this runs on every poll, so a file that grew is not read whole. +fn read_small(path: &Path) -> Option { + use std::io::Read; + let mut text = String::new(); + std::fs::File::open(path) + .ok()? + .take(4096) + .read_to_string(&mut text) + .ok()?; + Some(text) +} + /// `daemonVersion`, `cliVersion` (when the home's VERSION file names one), `os` /// and `arch`, for the desired-state poll. fn machine_facts() -> Vec<(&'static str, String)> { let mut facts = vec![("daemonVersion", env!("CARGO_PKG_VERSION").to_string())]; let cli = crate::paths::failproofai_home() .ok() - .and_then(|home| std::fs::read_to_string(crate::paths::version_file_path(&home)).ok()) + .and_then(|home| read_small(&crate::paths::version_file_path(&home))) .and_then(|text| serde_json::from_str::(&text).ok()) .and_then(|doc| doc.get("cli")?.as_str().map(str::to_string)) .filter(|v| !v.is_empty() && v.len() <= 64); diff --git a/crates/failproofaid/src/logfile.rs b/crates/failproofaid/src/logfile.rs index b8b90591e..fe1f050a1 100644 --- a/crates/failproofaid/src/logfile.rs +++ b/crates/failproofaid/src/logfile.rs @@ -32,18 +32,28 @@ impl Inner { /// Owner-only, created that way and tightened if an older file is not: /// the log carries machine ids and policy diagnostics, and a home another /// account can traverse must not make it readable to them. + /// + /// Only a regular file is used. Opened non-blocking and without following + /// a link, so a FIFO placed there (whose open waits for a reader) cannot + /// stall startup, which runs before the socket is bound, and a symlink + /// cannot point the log somewhere else. fn open(&mut self) { use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; self.file = OpenOptions::new() .create(true) .append(true) .mode(0o600) + .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW) .open(&self.path) - .ok(); - if self.file.is_some() { - let _ = fs::set_permissions(&self.path, fs::Permissions::from_mode(0o600)); - } - self.size = fs::metadata(&self.path).map(|m| m.len()).unwrap_or(0); + .ok() + .filter(|file| file.metadata().is_ok_and(|m| m.is_file())); + self.size = match &self.file { + Some(file) => { + let _ = file.set_permissions(fs::Permissions::from_mode(0o600)); + file.metadata().map(|m| m.len()).unwrap_or(0) + } + None => 0, + }; } fn rotate(&mut self) { @@ -70,8 +80,16 @@ impl Inner { /// `path` → `path.1` → … → `path.`, dropping the oldest. Missing files /// are skipped; a failed rename leaves the rest as they were. +/// `.`, built from the path's own bytes rather than its display +/// form, which replaces anything that is not UTF-8. +fn numbered(path: &Path, n: usize) -> PathBuf { + let mut name = path.as_os_str().to_owned(); + name.push(format!(".{n}")); + PathBuf::from(name) +} + pub fn rotate_file(path: &Path, keep: usize) { - let numbered = |n: usize| PathBuf::from(format!("{}.{n}", path.display())); + let numbered = |n: usize| numbered(path, n); if keep == 0 { let _ = fs::remove_file(path); return; @@ -146,13 +164,10 @@ pub fn bound_inherited_log(path: &Path, max_bytes: u64, keep: usize) { if meta.len() <= max_bytes { return; } - let first = PathBuf::from(format!("{}.1", path.display())); - let _ = fs::remove_file(PathBuf::from(format!("{}.{keep}", path.display()))); + let first = numbered(path, 1); + let _ = fs::remove_file(numbered(path, keep)); for n in (1..keep).rev() { - let _ = fs::rename( - PathBuf::from(format!("{}.{n}", path.display())), - PathBuf::from(format!("{}.{}", path.display(), n + 1)), - ); + let _ = fs::rename(numbered(path, n), numbered(path, n + 1)); } if fs::copy(path, &first).is_ok() { let _ = OpenOptions::new() @@ -230,6 +245,22 @@ mod tests { fs::remove_dir_all(dir).ok(); } + #[test] + fn a_fifo_in_place_of_the_log_neither_blocks_nor_is_used() { + let dir = temp_dir("fifo"); + let path = dir.join("daemon.log"); + let c = std::ffi::CString::new(path.to_str().unwrap()).unwrap(); + // SAFETY: a valid NUL-terminated path. + assert_eq!(unsafe { libc::mkfifo(c.as_ptr(), 0o600) }, 0); + let started = std::time::Instant::now(); + assert!(RotatingFile::open(path, 10, 1).is_none()); + assert!( + started.elapsed() < std::time::Duration::from_secs(1), + "the open did not wait for a reader" + ); + fs::remove_dir_all(dir).ok(); + } + #[test] fn a_missing_home_is_never_created() { let dir = temp_dir("no-home"); diff --git a/crates/failproofaid/src/main.rs b/crates/failproofaid/src/main.rs index 76755c04b..37205ee7c 100644 --- a/crates/failproofaid/src/main.rs +++ b/crates/failproofaid/src/main.rs @@ -129,12 +129,16 @@ fn init_logging() { ) }); let builder = tracing_subscriber::fmt().with_env_filter(filter); + // Only under launchd (which sets XPC_SERVICE_NAME): a hand-run daemon or a + // test reading stderr keeps every line. #[cfg(target_os = "macos")] - let stderr = std::io::stderr.with_max_level(if file.is_some() { - tracing::Level::WARN - } else { - tracing::Level::TRACE - }); + let stderr = std::io::stderr.with_max_level( + if file.is_some() && std::env::var_os("XPC_SERVICE_NAME").is_some() { + tracing::Level::WARN + } else { + tracing::Level::TRACE + }, + ); #[cfg(not(target_os = "macos"))] let stderr = std::io::stderr; let _ = match file { @@ -152,13 +156,19 @@ fn run() -> Result<(), Box> { // Only the instance holding the lock may rotate the log launchd gives the // running service: a second invocation copying and truncating it could // cut out lines the live daemon appended in between. + // Off the startup path: copying a log that grew large must not delay the + // socket bind, before which every hook call on the machine is denied. #[cfg(target_os = "macos")] if let Ok(home) = paths::failproofai_home() { - logfile::bound_inherited_log( - &home.join("logs").join("failproofaid.err.log"), - logfile::MAX_BYTES, - logfile::KEEP, - ); + let _ = std::thread::Builder::new() + .name("fpai-log-bound".to_string()) + .spawn(move || { + logfile::bound_inherited_log( + &home.join("logs").join("failproofaid.err.log"), + logfile::MAX_BYTES, + logfile::KEEP, + ) + }); } // The shutdown flag and its signal handler are installed BEFORE anything diff --git a/crates/failproofaid/src/server.rs b/crates/failproofaid/src/server.rs index 5c4cb4966..72cb9eb61 100644 --- a/crates/failproofaid/src/server.rs +++ b/crates/failproofaid/src/server.rs @@ -404,7 +404,21 @@ fn dispatch(request: ClientMessage, worker: &Worker) -> ServerMessage { message, }; } - evaluate(request.without_fields_newer_than_its_version(), worker).with_protocol_version(version) + let response = evaluate(request.without_fields_newer_than_its_version(), worker) + .with_protocol_version(version); + // Checked again after: a deployment that became targeted while the worker + // evaluated (Cloud maintenance runs beside it) may have been applied with + // no agent, so the answer is withheld for the same reason as above. + if version < fpai_ipc::envelope::AGENT_SETTINGS_PATH_SINCE + && let Ok(dir) = crate::paths::cloud_managed_policy_dir() + && let Some(message) = legacy_scope_refusal(&dir) + { + return ServerMessage::Error { + protocol_version: version, + message, + }; + } + response } /// Why a request too old to name its agent cannot be answered here, if it @@ -419,6 +433,18 @@ fn dispatch(request: ClientMessage, worker: &Worker) -> ServerMessage { /// request was before compatibility. A deployment that cannot be read is /// refused for the same reason. fn legacy_scope_refusal(cloud_policy_dir: &Path) -> Option { + // Only a manifest that is NOT THERE means no deployment. `read_active` + // asks `exists()`, which reads a permission error as absent too. + match fs::metadata(cloud_policy_dir.join("active.json")) { + Err(err) if err.kind() == io::ErrorKind::NotFound => return None, + Err(err) => { + return Some(format!( + "this client predates agent-targeted Cloud policies and the deployment could \ + not be read to rule them out ({err}): restart the agent gateway" + )); + } + Ok(_) => {} + } let store = crate::cloud_policies::PolicyStore::new(cloud_policy_dir.to_path_buf()); match store.read_active() { Ok(None) => None, diff --git a/crates/fpai-collect/src/supervisor.rs b/crates/fpai-collect/src/supervisor.rs index d0bdba458..ca6999020 100644 --- a/crates/fpai-collect/src/supervisor.rs +++ b/crates/fpai-collect/src/supervisor.rs @@ -277,7 +277,12 @@ impl Drop for CollectorHandle { stop: self.stop.clone(), metrics: self.metrics.clone(), }; - if handle.stop_within(crate::DEFAULT_FLUSH_BUDGET).is_err() { + if let Err(mut wedged) = handle.stop_within(crate::DEFAULT_FLUSH_BUDGET) { + // Detach before it drops: dropping it as-is would re-enter this + // `drop` (still panicking, thread still attached) and wait again, + // for ever on a wedged collector, so the unwind never ended. + // Asked to stop, it still exits on its own. + drop(wedged.thread.take()); tracing::warn!("a collector abandoned by a panic did not stop within its flush budget"); } } diff --git a/crates/fpai-collect/src/uploader.rs b/crates/fpai-collect/src/uploader.rs index b239c5fc1..3da9d8675 100644 --- a/crates/fpai-collect/src/uploader.rs +++ b/crates/fpai-collect/src/uploader.rs @@ -427,12 +427,21 @@ impl Uploader { parked.client_attempts = 1; parked.client_status = Some(413); let dest = unique_destination(&self.failed_dir, &parked.render()).await; - // Written under a dotfile and renamed, so no sweep sees half of it. + // Written under a dotfile and renamed, so no sweep sees half of it, and + // durable before returning: the caller then deletes the source batch, + // and the server has already refused this event, so this file is its + // only copy. let tmp = self .failed_dir .join(format!(".{}.partial", new_request_id())); - tokio::fs::write(&tmp, event).await?; + { + use tokio::io::AsyncWriteExt; + let mut file = tokio::fs::File::create(&tmp).await?; + file.write_all(event).await?; + file.sync_all().await?; + } tokio::fs::rename(&tmp, &dest).await?; + sync_dir(&self.failed_dir).await?; tracing::warn!( file = %path.display(), dest = %dest.display(), diff --git a/hermes-plugin/client.py b/hermes-plugin/client.py index 7b133e711..68df84eb4 100644 --- a/hermes-plugin/client.py +++ b/hermes-plugin/client.py @@ -61,14 +61,19 @@ def _agent_targeted_deployment() -> bool: root = os.environ.get("FAILPROOFAI_HOME", "").strip() home = Path(root).expanduser() if root else Path.home() / ".failproofai" directory = home / "policies" / "cloud-policies" - active = directory / "active.json" + # Read directly: `Path.exists()` reports a permission error as absent, and + # only a manifest that is NOT THERE means no deployment. try: - if not active.exists(): - return False - version = json.loads(active.read_text(encoding="utf-8")).get("schemaVersion") - return not (type(version) is int and version < SCOPED_SCHEMA_VERSION) - except (OSError, ValueError, AttributeError): + text = (directory / "active.json").read_text(encoding="utf-8") + except FileNotFoundError: + return False + except OSError: return True + try: + version = json.loads(text).get("schemaVersion") + except (ValueError, AttributeError): + return True + return not (type(version) is int and version < SCOPED_SCHEMA_VERSION) def _remaining_timeout(deadline: float) -> float: diff --git a/src/hooks/cloud-managed-policies.ts b/src/hooks/cloud-managed-policies.ts index 583b578c5..aed684af9 100644 --- a/src/hooks/cloud-managed-policies.ts +++ b/src/hooks/cloud-managed-policies.ts @@ -362,6 +362,28 @@ export function readCloudAgentScopeRequired(): boolean { } } +/** + * {@link readCloudAgentScopeRequired}, failing the other way: true unless the + * deployment is KNOWN not to target agents. For deciding whether an answer + * that names no agent may be used, where a manifest that exists but cannot be + * read must count as targeted. A machine in `oss` mode enforces no deployment. + */ +export function cloudDeploymentMayTargetAgents(): boolean { + if (disconnectedByConfig()) return false; + let text: string; + try { + text = readFileSync(resolve(cloudManagedPolicyRoot(), "active.json"), "utf8"); + } catch (err) { + return (err as NodeJS.ErrnoException).code !== "ENOENT"; + } + try { + const version = (JSON.parse(text) as { schemaVersion?: unknown })?.schemaVersion; + return !(typeof version === "number" && Number.isInteger(version) && version < 3); + } catch { + return true; + } +} + /** * Cloud's Jev mode from `active.json`, or null — no deployment, no mode, or a * file that cannot be read (which is then simply not a mode: the local diff --git a/src/hooks/daemon-client.ts b/src/hooks/daemon-client.ts index ee5506f33..825143dde 100644 --- a/src/hooks/daemon-client.ts +++ b/src/hooks/daemon-client.ts @@ -15,7 +15,7 @@ import type { IntegrationType } from "./types"; import { existsSync } from "node:fs"; import { daemonSocket as daemonSocketPath } from "./fp-home"; import { readConfig } from "./fp-config"; -import { readCloudAgentScopeRequired } from "./cloud-managed-policies"; +import { cloudDeploymentMayTargetAgents } from "./cloud-managed-policies"; const PROTOCOL_VERSION = 2; /** Oldest daemon version this client falls back to (crates/fpai-ipc MIN_PROTOCOL_VERSION). */ @@ -224,8 +224,9 @@ async function attemptDaemonRequest( older >= PROTOCOL_VERSION || // The older daemon would evaluate without this agent, and a deployment // with agent-targeted policies (schema 3) does not apply them to an - // unknown one: its answer could allow what they deny. - readCloudAgentScopeRequired() + // unknown one: its answer could allow what they deny. One that cannot be + // read cannot be ruled out. + cloudDeploymentMayTargetAgents() ) { return withoutDaemonVersion(first); } diff --git a/src/hooks/daemon-service.ts b/src/hooks/daemon-service.ts index 422dc2635..d977676a5 100644 --- a/src/hooks/daemon-service.ts +++ b/src/hooks/daemon-service.ts @@ -420,6 +420,11 @@ export function workerScriptPath(): string | null { */ const UNIT_UNSAFE_RE = /["\\\r\n]/; +/** A literal `%` in a unit value, written so systemd does not expand it. */ +function escapeUnitPercent(value: string): string { + return value.replace(/%/g, "%%"); +} + /** Throws when a value cannot be safely interpolated into a unit file. */ function assertUnitSafe(value: string, field: string): string { if (UNIT_UNSAFE_RE.test(value)) { @@ -777,7 +782,13 @@ export function writePrivilegedFile(destination: string, contents: string, mode const staging = resolve(stagingDir, "service-definition"); try { writeFileSync(staging, contents, "utf8"); - runPrivileged("install", ["-m", mode, staging, destination]); + // Installed beside the destination and renamed over it: `install` onto + // the destination unlinks the old file before copying, so a copy that + // failed part-way left no definition (launchd then cannot load the job + // at boot). A rename within one directory is atomic. + const sibling = `${destination}.failproofai-new`; + runPrivileged("install", ["-m", mode, staging, sibling]); + runPrivileged("mv", ["-f", sibling, destination]); } finally { rmSync(stagingDir, { recursive: true, force: true }); } @@ -850,8 +861,13 @@ export function systemdUnitContents( // Environment= requires quoting whenever the value does. const envLines = serviceEnvironment(workerCmd, cliCmd) // `%` is a specifier inside a unit (`%n` is the unit name, `%h` a home), - // so a literal one is written `%%` or the path silently changes. - .map(([key, value]) => `Environment="${key}=${assertUnitSafe(value, key).replace(/%/g, "%%")}"\n`) + // so in a command this package generated a literal one is written `%%`, or + // the path silently changes. An operator's own command is written as they + // saved it: its specifiers (`%i`, say) are meant. + .map(([key, value]) => { + const safe = assertUnitSafe(value, key); + return `Environment="${key}=${isPackageCommand(safe) ? escapeUnitPercent(safe) : safe}"\n`; + }) .join(""); const user = assertUnitSafe(serviceUser(), "User"); assertUnitSafe(binaryPath, "ExecStart"); @@ -897,11 +913,15 @@ export function systemdUnitContents( // a command-with-arguments is not. Same rule the worker script already // follows — never gate on a path that is not there, or the freshly installed // unit skips on its very first start. - const conditionPaths = [binaryPath, workerScriptPath()].filter( + // The package's worker script only when the unit runs it: an operator's own + // worker command does not need it, and gating on it skipped a service whose + // wrapper was intact once the unused script was removed. + const workerScript = workerCmd === null || isPackageCommand(workerCmd) ? workerScriptPath() : null; + const conditionPaths = [binaryPath, workerScript].filter( (p): p is string => typeof p === "string" && existsSync(p), ); const conditionLines = conditionPaths - .map((p) => `ConditionPathExists=${assertUnitSafe(p, "ConditionPathExists")}\n`) + .map((p) => `ConditionPathExists=${escapeUnitPercent(assertUnitSafe(p, "ConditionPathExists"))}\n`) .join(""); return `[Unit] @@ -1067,11 +1087,15 @@ export async function installDaemonService(): Promise { ? null : installedEnvValue(readInstalledServiceDefinition() ?? "", "FAILPROOFAI_WORKER_CMD"); const workerCmd = savedWorker && !isPackageCommand(savedWorker) ? savedWorker : resolveWorkerCommand(); + // And the operator's own audit command, the same way. + const savedCli = process.env.FAILPROOFAI_CLI_CMD + ? null + : installedEnvValue(readInstalledServiceDefinition() ?? "", "FAILPROOFAI_CLI_CMD"); // Same best-effort footing as the worker command, and null is survivable in // the same way — the daemon just has no way to run an audit. Unlike the // worker, there is no relative-path fallback to degrade to, which is exactly // why it is resolved here where FAILPROOFAI_PACKAGE_ROOT is reliably set. - const cliCmd = resolveCliCommand(); + const cliCmd = savedCli && !isPackageCommand(savedCli) ? savedCli : resolveCliCommand(); // The service is installed system-wide, which needs root. Check before // writing anything, so a machine that cannot elevate gets the exact @@ -1669,7 +1693,9 @@ export async function ensureDaemonServiceCurrent(): Promise return { outcome: "current" }; } - const cliCmd = resolveCliCommand(); + const savedCli = installedEnvValue(definition, "FAILPROOFAI_CLI_CMD"); + const cliCmd = + !process.env.FAILPROOFAI_CLI_CMD && savedCli && !isPackageCommand(savedCli) ? savedCli : resolveCliCommand(); if (!cliCmd) { return { outcome: "failed", @@ -1681,6 +1707,22 @@ export async function ensureDaemonServiceCurrent(): Promise const logDir = logsDir(); const upgraded = upgradedServiceDefinition(definition, cliCmd, logDir); + // A rewrite that would still name a missing file repairs nothing, and then + // reported "rewritten" while the next check flagged the same path. The + // install it would point at is incomplete; say that instead. + if ( + upgraded && + (savedCommandIsGone(installedEnvValue(upgraded, "FAILPROOFAI_WORKER_CMD")) || + savedCommandIsGone(installedEnvValue(upgraded, "FAILPROOFAI_CLI_CMD"))) + ) { + return { + outcome: "failed", + reason: + "the failproofai install the service would run is incomplete (its Node.js or dist/ files are missing). " + + "Reinstall the package, then run `failproofai update`.", + daemonRunning: daemonServiceStatus() === "running", + }; + } if (!upgraded) { return { outcome: "failed", diff --git a/src/hooks/gateway-restart.ts b/src/hooks/gateway-restart.ts index 61ada9df9..b7afa1f60 100644 --- a/src/hooks/gateway-restart.ts +++ b/src/hooks/gateway-restart.ts @@ -23,7 +23,8 @@ */ import { spawn, spawnSync } from "node:child_process"; import { closeSync, mkdirSync, openSync, readFileSync } from "node:fs"; -import { basename, dirname, join } from "node:path"; +import { dirname, join, resolve } from "node:path"; +import { homedir } from "node:os"; import { listOpenClawProfiles, OPENCLAW_DEFAULT_PROFILE } from "../../lib/openclaw-profiles"; import { logsDir } from "./fp-home"; @@ -186,7 +187,9 @@ export function openclawProfileEnv( for (const key of ["OPENCLAW_PROFILE", "OPENCLAW_STATE_DIR", "OPENCLAW_HOME", "OPENCLAW_CONFIG_PATH"]) { delete env[key]; } - if (profile.name === OPENCLAW_DEFAULT_PROFILE && basename(profile.home) !== ".openclaw") { + // The account default is ~/.openclaw itself; a default profile anywhere else + // (a relocated `/srv/claw/.openclaw` included) is named by its directory. + if (profile.name === OPENCLAW_DEFAULT_PROFILE && resolve(profile.home) !== resolve(homedir(), ".openclaw")) { env.OPENCLAW_STATE_DIR = profile.home; } return env; From 298756b4acd07d863d4f87c47f00c9bb7a70ae46 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 21:08:28 +0530 Subject: [PATCH 14/41] feat(daemon): send the daemon log to Cloud only when something is wrong A healthy daemon's log stays on the machine (~/.failproofai/logs/daemon.log). Cloud gets, on the maintenance lane after each poll, at most one body: - errors: one entry per distinct warning/error (digits folded), counted, at most every 5 minutes and only when there is one; - incident: the last 5 minutes of INFO-and-up lines around an ERROR (a lane panic, a crashed worker), or the previous run's log tail when it ended without a clean shutdown (logs/daemon.running left behind); at most one per 15 minutes, stamped on disk so a crash loop does not resend; - requested: the daemon.log tail, answering logRequest on desired-state. POST /enforcement/v1/machine-logs with the machine key. The home directory and the token are scrubbed; 404 pauses uploads for a day, 429 honours Retry-After. Capture is a third log writer feeding a bounded ring, so nothing new runs on the hook path, and shipping is off until main() turns it on. FAILPROOFAI_NO_LOG_UPLOAD=1 turns it off. --- CHANGELOG.md | 1 + crates/PROTOCOL.md | 21 + crates/failproofaid/src/cloud_client.rs | 134 ++++ crates/failproofaid/src/logship.rs | 945 ++++++++++++++++++++++++ crates/failproofaid/src/main.rs | 25 +- 5 files changed, 1124 insertions(+), 2 deletions(-) create mode 100644 crates/failproofaid/src/logship.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 405130e8d..ec46ec4ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ - failproofaid writes its log to `~/.failproofai/logs/daemon.log` on every OS (owner-only, 10 MB, 3 kept), as well as to stderr as before (on macOS stderr keeps only warnings and errors, since launchd's file is never rotated); every line carries a timestamp and level (its untimestamped `[failproofaid]` lines are now `tracing` events), and on macOS launchd's `failproofaid.err.log`, which nothing rotated, is bounded at startup (#1023) - failproofaid tells FailproofAI Cloud what each machine runs: its policy poll carries `daemonVersion`, `cliVersion`, `os` and `arch` (optional parameters a server that predates them ignores), and every Cloud and ingest request sends `User-Agent: failproofaid/` (#1023) - Hook events carry the agent's own `tool_call_id` (Claude, Devin, Factory, Pi, Hermes), the field the transcript events already use and Cloud stores in its own column, so a hook joins the tool call it governed instead of being placed beside it by timestamp; and a hook's start is stamped when it arrived, not when its evaluation ended. Rows written before this convert exactly as before (#1023) +- failproofaid sends its log to FailproofAI Cloud only when something is wrong: one roll-up of distinct warnings and errors (repeats counted, at most every 5 minutes), the last 5 minutes of log around an error or after a run that ended without a clean shutdown (at most one per 15 minutes), and the log tail when an operator asks for it from Cloud; the home directory and the machine token are scrubbed, a server without the route is left alone for a day, and `FAILPROOFAI_NO_LOG_UPLOAD=1` turns it off (#1023) ## 1.0.15 — 2026-11-18 diff --git a/crates/PROTOCOL.md b/crates/PROTOCOL.md index 6c009f751..c07b936cc 100644 --- a/crates/PROTOCOL.md +++ b/crates/PROTOCOL.md @@ -145,3 +145,24 @@ there. None of these crash the daemon or the connection-handling thread — a bad frame from one connection has no effect on any other connection. + +## Machine logs (HTTP, not this socket) + +Not part of the socket protocol: the daemon's cloud maintenance lane sends its +own log to FailproofAI Cloud, only when something is wrong +(`crates/failproofaid/src/logship.rs`). `POST /enforcement/v1/machine-logs`, +bearer = the machine key, body ≤ 256 KiB: + +```json +{ "machineId": "…", "daemonVersion": "1.0.16-beta.0", + "kind": "errors | incident | requested", + "trigger": "incident only, ≤ 200 chars", "requestId": "requested only", + "entries": [{ "ts": "…", "level": "ERROR|WARN|INFO|DEBUG", "target": "…", + "message": "≤ 2 KiB", "count": 1, "lastTs": "errors only" }] } +``` + +- `errors`: distinct warnings/errors (digits folded), counted; ≤ every 5 min, only when there is one. +- `incident`: the last 5 min of INFO-and-up lines around an ERROR, or the previous run's log tail when it ended without a clean shutdown (`logs/daemon.running` still present at start); ≤ 1 per 15 min (stamped in `logs/.incident-sent`, so a crash loop does not resend), ≤ 10 per day. +- `requested`: the `daemon.log` tail, answering `logRequest: {id}` on the desired-state response. +- One body per poll. `2xx` stored; `404` → no uploads for 24 h; `429` → wait `Retry-After`; other `4xx` → dropped; network/`5xx` → kept for the next poll. +- Home directory → `~`, machine token → `[redacted]`. `FAILPROOFAI_NO_LOG_UPLOAD=1` turns uploads off. diff --git a/crates/failproofaid/src/cloud_client.rs b/crates/failproofaid/src/cloud_client.rs index ce07e3d78..755c5307a 100644 --- a/crates/failproofaid/src/cloud_client.rs +++ b/crates/failproofaid/src/cloud_client.rs @@ -891,6 +891,14 @@ impl CloudClient { // payload instead of a stale server. Reading the version off an // untyped value first means the error names both halves and says // which to upgrade. + // An operator asked for this machine's logs (logship.rs). + if let Some(id) = raw + .get("logRequest") + .and_then(|r| r.get("id")) + .and_then(serde_json::Value::as_str) + { + crate::logship::note_request(id); + } let version = raw.get("schemaVersion").and_then(serde_json::Value::as_u64); match version { Some(v) if v == u64::from(DESIRED_STATE_SCHEMA_VERSION) @@ -913,6 +921,59 @@ impl CloudClient { }) } + /// One `machine-logs` upload (logship.rs). Never logs above debug: a + /// failure here must not become the next thing it uploads. + fn post_machine_logs(&self, body: &serde_json::Value) -> crate::logship::PostOutcome { + use crate::logship::PostOutcome; + let Ok(url) = self.base_url.join("enforcement/v1/machine-logs") else { + return PostOutcome::Refused; + }; + match self + .client + .post(url) + .bearer_auth(&self.token) + .json(body) + .send() + { + Ok(response) => { + let status = response.status(); + match status.as_u16() { + 200..=299 => PostOutcome::Stored, + 404 => PostOutcome::Gone, + 429 => PostOutcome::RetryAfter(Duration::from_secs( + response + .headers() + .get(reqwest::header::RETRY_AFTER) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(3600), + )), + 400..=499 => { + tracing::debug!("machine log upload refused: {status}"); + PostOutcome::Refused + } + _ => PostOutcome::Failed, + } + } + Err(err) => { + tracing::debug!( + "machine log upload failed: {}", + fpai_collect::error_chain(&err) + ); + PostOutcome::Failed + } + } + } + + /// Upload whatever logship has queued, one body per tick. + fn ship_logs(&self) { + let scrub = + crate::logship::Scrub::new(std::env::var("HOME").ok(), Some(self.token.clone())); + crate::logship::ship(&self.machine_id, &scrub, &|body| { + self.post_machine_logs(body) + }); + } + /// The roster is a full snapshot, independent of policy reconciliation. /// A failed upload never discards the already-active assignment. /// @@ -1225,6 +1286,7 @@ fn maintenance_tick( let reconciled = poll_once_guarded(store, &cloud, withdrawn); if !withdrawn() { repair(store, withdrawn); + cloud.ship_logs(); } reconciled } @@ -1611,6 +1673,78 @@ mod tests { /// half, so this path took a v1 response. The disk half is now handled by a /// dedicated legacy type in `cloud_policies.rs`, which is what lets this end be /// strict without costing an upgraded machine its persisted state. + /// One request in, one canned status out; returns the request head. + fn answer_once( + status_line: &'static str, + extra: &'static str, + ) -> (String, std::thread::JoinHandle) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut request = Vec::new(); + let mut chunk = [0u8; 4096]; + // Head, then the body its Content-Length names. + loop { + let n = stream.read(&mut chunk).unwrap(); + request.extend_from_slice(&chunk[..n]); + let text = String::from_utf8_lossy(&request).to_string(); + if let Some(head_end) = text.find("\r\n\r\n") { + let len = text[..head_end] + .lines() + .find_map(|l| { + l.to_ascii_lowercase() + .strip_prefix("content-length:") + .map(|v| v.trim().parse::().unwrap_or(0)) + }) + .unwrap_or(0); + if request.len() >= head_end + 4 + len || n == 0 { + break; + } + } + if n == 0 { + break; + } + } + let response = format!("HTTP/1.1 {status_line}\r\n{extra}Content-Length: 0\r\n\r\n"); + stream.write_all(response.as_bytes()).unwrap(); + String::from_utf8_lossy(&request).to_string() + }); + (format!("http://{address}"), server) + } + + #[test] + fn machine_log_uploads_map_the_server_answer() { + use crate::logship::PostOutcome; + let body = serde_json::json!({"machineId": "machine", "kind": "errors", "entries": []}); + for (status, extra, want) in [ + ("202 Accepted", "", PostOutcome::Stored), + ("404 Not Found", "", PostOutcome::Gone), + ( + "429 Too Many Requests", + "Retry-After: 120\r\n", + PostOutcome::RetryAfter(Duration::from_secs(120)), + ), + ("413 Payload Too Large", "", PostOutcome::Refused), + ("503 Service Unavailable", "", PostOutcome::Failed), + ] { + let (url, server) = answer_once(status, extra); + let client = CloudClient::new(&url, "token-abcdefgh".into(), "machine".into()).unwrap(); + assert_eq!(client.post_machine_logs(&body), want, "{status}"); + let request = server.join().unwrap(); + assert!( + request.starts_with("POST /enforcement/v1/machine-logs "), + "{request}" + ); + assert!( + request + .to_ascii_lowercase() + .contains("authorization: bearer token-abcdefgh") + ); + assert!(request.contains(r#""kind":"errors""#)); + } + } + #[test] fn refuses_a_desired_state_response_at_an_older_schema_version() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/crates/failproofaid/src/logship.rs b/crates/failproofaid/src/logship.rs new file mode 100644 index 000000000..ae5012a99 --- /dev/null +++ b/crates/failproofaid/src/logship.rs @@ -0,0 +1,945 @@ +//! Daemon log upload to FailproofAI Cloud — only when something is wrong. +//! +//! A healthy daemon logs a line for almost every hook, so its log is shipped +//! nowhere: `~/.failproofai/logs/daemon.log` keeps all of it, on the machine. +//! Cloud gets three things, each bounded (crates/PROTOCOL.md, "Machine logs"): +//! +//! - **errors** — one entry per DISTINCT warning or error (digits folded, so a +//! loop of the same failure is one entry with a count), at most every +//! [`ERRORS_EVERY`], only when there is one. +//! - **incident** — the last [`INCIDENT_WINDOW`] of INFO-and-up lines around an +//! ERROR (a lane panic, a crashed worker, refused uploads), or the tail of the +//! previous run's log when that run ended without a clean shutdown (a power +//! loss, a kernel panic, a crash loop). At most one per [`INCIDENT_GAP`]. +//! - **requested** — the tail of `daemon.log`, when an operator asked Cloud for +//! this machine's logs (`logRequest` on the desired-state poll). +//! +//! Capture is a third writer on the log subscriber ([`Capture`]), so nothing +//! here sits on the hook path: a line is parsed into a bounded ring, and every +//! request happens later on the cloud maintenance lane. Shipping is OFF until +//! [`init`] runs, which only `main` does — tests that log never upload. +//! +//! Nothing a hook evaluates is logged by the daemon, and the upload scrubs the +//! home directory to `~` and the machine token to `[redacted]` regardless. +//! `FAILPROOFAI_NO_LOG_UPLOAD=1` turns uploading off. + +use std::collections::{HashMap, VecDeque}; +use std::fs::{self, File}; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::sync::{LazyLock, Mutex, MutexGuard}; +use std::time::{Duration, Instant, SystemTime}; + +use serde_json::{Value, json}; +use tracing::{Level, Metadata}; +use tracing_subscriber::fmt::MakeWriter; + +/// Lines older than this leave the ring. +pub const INCIDENT_WINDOW: Duration = Duration::from_secs(5 * 60); +/// Minimum gap between two incident uploads, across restarts too. +pub const INCIDENT_GAP: Duration = Duration::from_secs(15 * 60); +/// Incidents per rolling day, per process. +const INCIDENTS_PER_DAY: usize = 10; +/// How long an incident waits before it is sent, so the lines that follow the +/// error (the restart, the retry) are in it. +const INCIDENT_SETTLE: Duration = Duration::from_secs(10); +/// An incident that could not be delivered for this long is dropped. +const INCIDENT_GIVE_UP: Duration = Duration::from_secs(30 * 60); +pub const ERRORS_EVERY: Duration = Duration::from_secs(5 * 60); +/// When Cloud answers 404 (a server without the route), ask again after this. +const GONE_FOR: Duration = Duration::from_secs(24 * 60 * 60); + +const RING_MAX: usize = 2000; +const DISTINCT_ERRORS_MAX: usize = 500; +pub const MAX_ENTRIES: usize = 2000; +pub const MAX_MESSAGE_BYTES: usize = 2048; +const MAX_TRIGGER_BYTES: usize = 200; +/// Under the server's 256 KiB body limit, with room for the envelope. +pub const MAX_BODY_BYTES: usize = 240 * 1024; +/// How much of `daemon.log` a requested or unclean-restart upload reads. +const TAIL_BYTES: u64 = 192 * 1024; + +const MARKER: &str = "daemon.running"; +const INCIDENT_STAMP: &str = ".incident-sent"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + pub ts: String, + pub level: String, + pub target: String, + pub message: String, + pub count: u64, + pub last_ts: Option, +} + +impl Entry { + fn to_json(&self, scrub: &Scrub) -> Value { + let mut v = json!({ + "ts": self.ts, + "level": self.level, + "target": self.target, + "message": scrub.apply(&self.message), + "count": self.count, + }); + if let Some(last) = &self.last_ts { + v["lastTs"] = json!(last); + } + v + } +} + +struct Captured { + entry: Entry, + at: Instant, +} + +struct Incident { + trigger: String, + at: Instant, + /// Set when the entries come from somewhere other than the ring (the + /// previous run's log); the ring is read at send time otherwise. + entries: Option>, +} + +#[derive(Default)] +struct State { + enabled: bool, + log_path: Option, + stamp_path: Option, + ring: VecDeque, + errors: HashMap, + /// Insertion order of `errors`, so the oldest distinct error is reported + /// first and the map's iteration order never decides what is cut. + error_order: Vec, + errors_overflow: u64, + last_errors_sent: Option, + incident: Option, + incidents_sent: VecDeque, + last_incident: Option, + requested: Option, + answered: Option, + paused_until: Option, +} + +static STATE: LazyLock> = LazyLock::new(|| Mutex::new(State::default())); + +fn state() -> MutexGuard<'static, State> { + // A panic while the lock was held must not stop logging. + STATE + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +/// The log writer that feeds the ring. Add it to the subscriber's writer with +/// `MakeWriterExt::and`; it keeps INFO and up. +#[derive(Clone, Copy, Default)] +pub struct Capture; + +pub struct LineSink { + level: Option, + target: String, + buf: Vec, +} + +impl Write for LineSink { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + if self.level.is_some() && self.buf.len() < 64 * 1024 { + self.buf.extend_from_slice(bytes); + } + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl Drop for LineSink { + fn drop(&mut self) { + if let Some(level) = self.level + && !self.buf.is_empty() + { + let line = String::from_utf8_lossy(&self.buf); + record(level, &self.target, &line, Instant::now()); + } + } +} + +impl<'a> MakeWriter<'a> for Capture { + type Writer = LineSink; + fn make_writer(&'a self) -> LineSink { + LineSink { + level: None, + target: String::new(), + buf: Vec::new(), + } + } + fn make_writer_for(&'a self, meta: &Metadata<'_>) -> LineSink { + // tracing orders verbosity upward: ERROR < WARN < INFO < DEBUG. + let keep = *meta.level() <= Level::INFO; + LineSink { + level: keep.then(|| *meta.level()), + target: meta.target().to_string(), + buf: Vec::new(), + } + } +} + +/// One formatted line → an entry. The default fmt layout is +/// ` [spans: ]: `; anything else is kept whole. +pub fn parse_line(line: &str, level: Option<&str>, target: Option<&str>) -> Entry { + let line = line.trim_end_matches(['\n', '\r']); + let mut rest = line; + let mut ts = String::new(); + let mut parsed_level = None; + if let Some((first, after)) = line.split_once(' ') + && first.len() >= 20 + && first.as_bytes()[4] == b'-' + && first.contains('T') + { + ts = first.to_string(); + let after = after.trim_start(); + if let Some((lvl, tail)) = after.split_once(' ') + && matches!(lvl, "ERROR" | "WARN" | "INFO" | "DEBUG" | "TRACE") + { + parsed_level = Some(lvl.to_string()); + rest = tail.trim_start(); + } else { + rest = after; + } + } + let mut found_target = target.map(str::to_string).unwrap_or_default(); + let message = match target { + Some(t) => match rest.find(&format!("{t}: ")) { + Some(at) => &rest[at + t.len() + 2..], + None => rest, + }, + // A line read back from a file: `target: message` when the head looks + // like a module path. + None => match rest.split_once(": ") { + Some((head, tail)) + if !head.is_empty() + && head + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | ':')) => + { + found_target = head.to_string(); + tail + } + _ => rest, + }, + }; + Entry { + ts, + level: level + .map(str::to_string) + .or(parsed_level) + .unwrap_or_else(|| "INFO".to_string()), + target: found_target, + message: truncate(message, MAX_MESSAGE_BYTES).to_string(), + count: 1, + last_ts: None, + } +} + +fn truncate(text: &str, max: usize) -> &str { + if text.len() <= max { + return text; + } + let mut end = max; + while !text.is_char_boundary(end) { + end -= 1; + } + &text[..end] +} + +/// Same failure, different numbers → same fingerprint. +pub fn fingerprint(target: &str, message: &str) -> String { + let mut out = String::with_capacity(target.len() + message.len() + 1); + out.push_str(target); + out.push('|'); + let mut last_hash = false; + for c in message.chars() { + if c.is_ascii_digit() { + if !last_hash { + out.push('#'); + } + last_hash = true; + } else { + out.push(c); + last_hash = false; + } + } + out +} + +fn record(level: Level, target: &str, line: &str, now: Instant) { + let entry = parse_line(line, Some(level.as_str()), Some(target)); + // This module's own failures never trigger an upload of themselves. + let own = target.starts_with(module_path!()); + let mut st = state(); + while st.ring.len() >= RING_MAX + || st + .ring + .front() + .is_some_and(|c| now.duration_since(c.at) > INCIDENT_WINDOW) + { + st.ring.pop_front(); + } + if level <= Level::WARN && !own { + let key = fingerprint(&entry.target, &entry.message); + if let Some(existing) = st.errors.get_mut(&key) { + existing.count += 1; + existing.last_ts = Some(entry.ts.clone()); + } else if st.errors.len() < DISTINCT_ERRORS_MAX { + st.error_order.push(key.clone()); + st.errors.insert(key, entry.clone()); + } else { + st.errors_overflow += 1; + } + } + if level == Level::ERROR && !own { + let trigger = truncate(&entry.message, MAX_TRIGGER_BYTES).to_string(); + maybe_open_incident(&mut st, trigger, None, now); + } + st.ring.push_back(Captured { entry, at: now }); +} + +fn maybe_open_incident(st: &mut State, trigger: String, entries: Option>, now: Instant) { + if st.incident.is_some() { + return; + } + if st + .last_incident + .is_some_and(|at| now.duration_since(at) < INCIDENT_GAP) + { + return; + } + while st + .incidents_sent + .front() + .is_some_and(|at| now.duration_since(*at) > Duration::from_secs(24 * 60 * 60)) + { + st.incidents_sent.pop_front(); + } + if st.incidents_sent.len() >= INCIDENTS_PER_DAY { + return; + } + if st + .stamp_path + .as_deref() + .and_then(|p| fs::metadata(p).ok()) + .and_then(|m| m.modified().ok()) + .and_then(|at| SystemTime::now().duration_since(at).ok()) + .is_some_and(|age| age < INCIDENT_GAP) + { + return; + } + st.incident = Some(Incident { + trigger, + at: now, + entries, + }); +} + +/// Read the last `max` bytes of a file, from its first complete line. +fn tail(path: &Path, end: Option, max: u64) -> Option { + let mut file = File::open(path).ok()?; + let len = file.metadata().ok()?.len(); + let end = end.map_or(len, |e| e.min(len)); + let start = end.saturating_sub(max); + file.seek(SeekFrom::Start(start)).ok()?; + let mut buf = vec![0u8; usize::try_from(end - start).ok()?]; + file.read_exact(&mut buf).ok()?; + let text = String::from_utf8_lossy(&buf).into_owned(); + Some(if start > 0 { + text.split_once('\n') + .map(|(_, r)| r.to_string()) + .unwrap_or_default() + } else { + text + }) +} + +fn entries_from_text(text: &str) -> Vec { + let mut out: Vec = text + .lines() + .filter(|l| !l.trim().is_empty()) + .map(|l| parse_line(l, None, None)) + .collect(); + if out.len() > MAX_ENTRIES { + out.drain(..out.len() - MAX_ENTRIES); + } + out +} + +/// Size of `daemon.log` before this process writes to it. Call before the log +/// subscriber is installed; pass the result to [`init`]. +pub fn log_len_before_start(log_path: &Path) -> Option { + fs::metadata(log_path).ok().map(|m| m.len()) +} + +/// Turn shipping on. Called once by `main`, AFTER the singleton lock is held: +/// only the daemon that owns the machine may read the run marker, or a second +/// invocation would read the live daemon's marker as an unclean exit. +/// +/// `prior_len` is [`log_len_before_start`]: the previous run's lines end there. +pub fn init(logs_dir: &Path, prior_len: Option) { + let log_path = logs_dir.join("daemon.log"); + let marker = logs_dir.join(MARKER); + let stamp = logs_dir.join(INCIDENT_STAMP); + let unclean = marker.exists(); + { + let mut st = state(); + st.enabled = + std::env::var_os("FAILPROOFAI_NO_LOG_UPLOAD").is_none_or(|v| v.is_empty() || v == "0"); + st.log_path = Some(log_path.clone()); + st.stamp_path = Some(stamp); + } + if unclean { + // The previous run's lines: daemon.log up to where it was before this + // start, or the rotated file when opening rotated it away. + let text = match prior_len { + Some(len) if fs::metadata(&log_path).is_ok_and(|m| m.len() >= len) => { + tail(&log_path, Some(len), TAIL_BYTES) + } + _ => tail(&logs_dir.join("daemon.log.1"), None, TAIL_BYTES), + }; + let entries = text.as_deref().map(entries_from_text).unwrap_or_default(); + let mut st = state(); + maybe_open_incident( + &mut st, + "the previous daemon run ended without a clean shutdown".to_string(), + Some(entries), + Instant::now(), + ); + } + let _ = fs::write(&marker, std::process::id().to_string()); +} + +/// The daemon stopped on purpose (a signal): the next start is not an incident. +pub fn mark_clean_shutdown(logs_dir: &Path) { + let _ = fs::remove_file(logs_dir.join(MARKER)); +} + +/// The desired-state poll carried `logRequest.id`. +pub fn note_request(id: &str) { + let id = truncate(id, 128); + if id.is_empty() { + return; + } + let mut st = state(); + if st.answered.as_deref() != Some(id) && st.requested.as_deref() != Some(id) { + st.requested = Some(id.to_string()); + } +} + +/// What a POST to `machine-logs` came back with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PostOutcome { + Stored, + /// 429: wait before the next upload. + RetryAfter(Duration), + /// 404: this server has no such route. + Gone, + /// 413 / 422 / other 4xx: this body will never be accepted. + Refused, + /// Network or 5xx: try again next tick. + Failed, +} + +/// Replaces the home directory and the token in uploaded text. +pub struct Scrub { + home: Option, + token: Option, +} + +impl Scrub { + pub fn new(home: Option, token: Option) -> Self { + Self { + home: home.filter(|h| h.len() > 1), + token: token.filter(|t| t.len() >= 8), + } + } + fn apply(&self, text: &str) -> String { + let mut out = text.to_string(); + if let Some(t) = &self.token { + out = out.replace(t.as_str(), "[redacted]"); + } + if let Some(h) = &self.home { + out = out.replace(h.as_str(), "~"); + } + out + } +} + +enum Kind { + Requested(String), + Incident, + Errors, +} + +/// Build the body, keeping the NEWEST entries that fit. +pub fn body( + machine_id: &str, + kind: &str, + trigger: Option<&str>, + request_id: Option<&str>, + entries: &[Entry], + scrub: &Scrub, +) -> Value { + let mut start = entries.len().saturating_sub(MAX_ENTRIES); + loop { + let mut v = json!({ + "machineId": machine_id, + "daemonVersion": env!("CARGO_PKG_VERSION"), + "kind": kind, + "entries": entries[start..].iter().map(|e| e.to_json(scrub)).collect::>(), + }); + if let Some(t) = trigger { + v["trigger"] = json!(scrub.apply(t)); + } + if let Some(r) = request_id { + v["requestId"] = json!(r); + } + let size = serde_json::to_vec(&v).map_or(usize::MAX, |b| b.len()); + if size <= MAX_BODY_BYTES || start >= entries.len() { + return v; + } + // Drop the oldest quarter of what is left, at least one entry. + start += ((entries.len() - start) / 4).max(1); + } +} + +/// One upload per call, the most useful first: an operator's request, then an +/// incident, then the error roll-up. Called by the cloud maintenance lane after +/// its poll; `post` sends one body. +pub fn ship(machine_id: &str, scrub: &Scrub, post: &dyn Fn(&Value) -> PostOutcome) { + ship_at(machine_id, scrub, post, Instant::now()); +} + +fn ship_at(machine_id: &str, scrub: &Scrub, post: &dyn Fn(&Value) -> PostOutcome, now: Instant) { + let (kind, value) = { + let mut st = state(); + if !st.enabled || st.paused_until.is_some_and(|until| now < until) { + return; + } + st.paused_until = None; + if st + .incident + .as_ref() + .is_some_and(|i| now.duration_since(i.at) > INCIDENT_GIVE_UP) + { + st.incident = None; + } + if let Some(id) = st.requested.clone() { + let text = st + .log_path + .as_deref() + .and_then(|p| tail(p, None, TAIL_BYTES)); + let entries = match text { + Some(t) => entries_from_text(&t), + None => st.ring.iter().map(|c| c.entry.clone()).collect(), + }; + let v = body(machine_id, "requested", None, Some(&id), &entries, scrub); + (Kind::Requested(id), v) + } else if let Some(incident) = st + .incident + .as_ref() + .filter(|i| i.entries.is_some() || now.duration_since(i.at) >= INCIDENT_SETTLE) + { + let entries: Vec = match &incident.entries { + Some(e) => e.clone(), + None => st.ring.iter().map(|c| c.entry.clone()).collect(), + }; + let v = body( + machine_id, + "incident", + Some(&incident.trigger), + None, + &entries, + scrub, + ); + (Kind::Incident, v) + } else if (!st.errors.is_empty() || st.errors_overflow > 0) + && st + .last_errors_sent + .is_none_or(|at| now.duration_since(at) >= ERRORS_EVERY) + { + let mut entries: Vec = st + .error_order + .iter() + .filter_map(|k| st.errors.get(k).cloned()) + .collect(); + if st.errors_overflow > 0 { + entries.push(Entry { + ts: entries.last().map(|e| e.ts.clone()).unwrap_or_default(), + level: "WARN".to_string(), + target: module_path!().to_string(), + message: format!( + "{} more warnings or errors were not itemised (over {DISTINCT_ERRORS_MAX} distinct)", + st.errors_overflow + ), + count: st.errors_overflow, + last_ts: None, + }); + } + ( + Kind::Errors, + body(machine_id, "errors", None, None, &entries, scrub), + ) + } else { + return; + } + }; + + // The lock is NOT held across the request: logging must never wait on it. + let outcome = post(&value); + let mut st = state(); + let done = match outcome { + PostOutcome::Stored | PostOutcome::Refused => true, + PostOutcome::RetryAfter(wait) => { + st.paused_until = Some(now + wait.min(GONE_FOR)); + false + } + PostOutcome::Gone => { + st.paused_until = Some(now + GONE_FOR); + false + } + PostOutcome::Failed => false, + }; + if !done { + return; + } + match kind { + Kind::Requested(id) => { + st.requested = None; + st.answered = Some(id); + } + Kind::Incident => { + st.incident = None; + st.last_incident = Some(now); + st.incidents_sent.push_back(now); + if let Some(stamp) = st.stamp_path.clone() { + let _ = fs::write(stamp, b""); + } + } + Kind::Errors => { + st.errors.clear(); + st.error_order.clear(); + st.errors_overflow = 0; + st.last_errors_sent = Some(now); + } + } +} + +#[cfg(test)] +pub(crate) fn reset_for_test(enabled: bool) { + let mut st = state(); + *st = State::default(); + st.enabled = enabled; +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + + // The module keeps one process-wide state; serialise the tests that use it. + static LOCK: Mutex<()> = Mutex::new(()); + + fn line(level: &str, target: &str, msg: &str) -> String { + format!("2026-11-18T13:18:37.676211Z {level:>5} {target}: {msg}\n") + } + + fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "fpai-logship-{name}-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&dir).unwrap(); + dir + } + + fn scrub() -> Scrub { + Scrub::new(Some("/home/alice".into()), Some("secret-token-123".into())) + } + + fn collect(at: Instant) -> Vec { + let sent = RefCell::new(Vec::new()); + ship_at( + "m-1", + &scrub(), + &|v| { + sent.borrow_mut().push(v.clone()); + PostOutcome::Stored + }, + at, + ); + sent.into_inner() + } + + #[test] + fn parses_the_fmt_layout() { + let e = parse_line( + "2026-11-18T13:18:37.676211Z WARN fpai_collect::sources::openclaw::sqlite: could not process db=x\n", + None, + None, + ); + assert_eq!(e.ts, "2026-11-18T13:18:37.676211Z"); + assert_eq!(e.level, "WARN"); + assert_eq!(e.target, "fpai_collect::sources::openclaw::sqlite"); + assert_eq!(e.message, "could not process db=x"); + + let raw = parse_line("[failproofaid] worker stderr: boom", None, None); + assert_eq!(raw.level, "INFO"); + assert_eq!(raw.message, "[failproofaid] worker stderr: boom"); + } + + #[test] + fn repeated_errors_fold_into_one_entry_with_a_count() { + let _g = LOCK.lock().unwrap(); + reset_for_test(true); + let t0 = Instant::now(); + for n in 0..50 { + record( + Level::WARN, + "fpai_collect::uploader", + &line( + "WARN", + "fpai_collect::uploader", + &format!("upload failed after {n} ms"), + ), + t0, + ); + } + record(Level::WARN, "x", &line("WARN", "x", "other"), t0); + let sent = collect(t0); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0]["kind"], "errors"); + let entries = sent[0]["entries"].as_array().unwrap(); + assert_eq!(entries.len(), 2); + assert_eq!(entries[0]["count"], 50); + assert_eq!(entries[1]["message"], "other"); + // Nothing new: nothing sent, and the roll-up waits its interval. + assert!(collect(t0 + Duration::from_secs(1)).is_empty()); + record(Level::WARN, "x", &line("WARN", "x", "again"), t0); + assert!(collect(t0 + Duration::from_secs(60)).is_empty()); + assert_eq!(collect(t0 + ERRORS_EVERY).len(), 1); + } + + #[test] + fn info_alone_never_uploads() { + let _g = LOCK.lock().unwrap(); + reset_for_test(true); + let t0 = Instant::now(); + for _ in 0..100 { + record(Level::INFO, "a", &line("INFO", "a", "hook ok"), t0); + } + assert!(collect(t0 + Duration::from_secs(3600)).is_empty()); + } + + #[test] + fn an_error_sends_one_incident_with_context_after_it_settles() { + let _g = LOCK.lock().unwrap(); + reset_for_test(true); + let t0 = Instant::now(); + record(Level::INFO, "a", &line("INFO", "a", "before"), t0); + record( + Level::ERROR, + "failproofaid", + &line( + "ERROR", + "failproofaid", + "cloud policy sync panicked; starting it again in 5s", + ), + t0, + ); + // Not before it settles; the error roll-up goes first meanwhile. + let early = collect(t0); + assert_eq!(early.len(), 1); + assert_eq!(early[0]["kind"], "errors"); + record( + Level::INFO, + "a", + &line("INFO", "a", "after"), + t0 + Duration::from_secs(2), + ); + let sent = collect(t0 + INCIDENT_SETTLE); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0]["kind"], "incident"); + assert_eq!( + sent[0]["trigger"], + "cloud policy sync panicked; starting it again in 5s" + ); + let msgs: Vec<_> = sent[0]["entries"] + .as_array() + .unwrap() + .iter() + .map(|e| e["message"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(msgs.first().map(String::as_str), Some("before")); + assert_eq!(msgs.last().map(String::as_str), Some("after")); + // A second error inside the gap opens no second incident. + record( + Level::ERROR, + "failproofaid", + &line("ERROR", "failproofaid", "again"), + t0 + Duration::from_secs(20), + ); + let later = collect(t0 + Duration::from_secs(60)); + assert!(later.iter().all(|v| v["kind"] != "incident")); + } + + #[test] + fn scrubs_home_and_token() { + let _g = LOCK.lock().unwrap(); + reset_for_test(true); + let t0 = Instant::now(); + record( + Level::WARN, + "a", + &line( + "WARN", + "a", + "bad /home/alice/.failproofai key secret-token-123", + ), + t0, + ); + let sent = collect(t0); + assert_eq!( + sent[0]["entries"][0]["message"], + "bad ~/.failproofai key [redacted]" + ); + } + + #[test] + fn refused_and_gone_and_retry() { + let _g = LOCK.lock().unwrap(); + reset_for_test(true); + let t0 = Instant::now(); + record(Level::WARN, "a", &line("WARN", "a", "w"), t0); + ship_at("m", &scrub(), &|_| PostOutcome::Gone, t0); + let calls = RefCell::new(0); + ship_at( + "m", + &scrub(), + &|_| { + *calls.borrow_mut() += 1; + PostOutcome::Stored + }, + t0 + Duration::from_secs(3600), + ); + assert_eq!(*calls.borrow(), 0, "a 404 pauses uploads for a day"); + ship_at("m", &scrub(), &|_| PostOutcome::Failed, t0 + GONE_FOR); + // A failed send keeps the roll-up for the next tick. + assert_eq!(collect(t0 + GONE_FOR + Duration::from_secs(30)).len(), 1); + } + + #[test] + fn disabled_never_posts() { + let _g = LOCK.lock().unwrap(); + reset_for_test(false); + let t0 = Instant::now(); + record(Level::ERROR, "a", &line("ERROR", "a", "e"), t0); + assert!(collect(t0 + Duration::from_secs(3600)).is_empty()); + } + + #[test] + fn a_request_sends_the_log_tail_once() { + let _g = LOCK.lock().unwrap(); + reset_for_test(true); + let dir = temp_dir("request"); + let log = dir.join("daemon.log"); + fs::write(&log, line("INFO", "a", "one") + &line("WARN", "b", "two")).unwrap(); + state().log_path = Some(log); + note_request("req-1"); + let sent = collect(Instant::now()); + assert_eq!(sent[0]["kind"], "requested"); + assert_eq!(sent[0]["requestId"], "req-1"); + assert_eq!(sent[0]["entries"].as_array().unwrap().len(), 2); + // The same id again (the next poll, before Cloud marked it) is not resent. + note_request("req-1"); + assert!( + collect(Instant::now()) + .iter() + .all(|v| v["kind"] != "requested") + ); + } + + #[test] + fn an_unclean_previous_run_is_an_incident_from_its_own_log() { + let _g = LOCK.lock().unwrap(); + reset_for_test(true); + let dir = temp_dir("unclean"); + let prev = line("INFO", "a", "old run") + &line("ERROR", "a", "last words"); + fs::write(dir.as_path().join("daemon.log"), &prev).unwrap(); + fs::write(dir.as_path().join(MARKER), "1").unwrap(); + let prior = log_len_before_start(&dir.as_path().join("daemon.log")); + // This run's first line lands after the previous run's end. + let mut f = fs::OpenOptions::new() + .append(true) + .open(dir.as_path().join("daemon.log")) + .unwrap(); + f.write_all(line("INFO", "a", "new run").as_bytes()) + .unwrap(); + init(dir.as_path(), prior); + assert!(dir.as_path().join(MARKER).exists()); + let sent = collect(Instant::now()); + assert_eq!(sent[0]["kind"], "incident"); + let msgs: Vec<_> = sent[0]["entries"] + .as_array() + .unwrap() + .iter() + .map(|e| e["message"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(msgs, ["old run", "last words"]); + // Sent: the stamp stops a crash loop from re-sending on every start. + assert!(dir.as_path().join(INCIDENT_STAMP).exists()); + mark_clean_shutdown(dir.as_path()); + assert!(!dir.as_path().join(MARKER).exists()); + + // A clean previous run is no incident. + reset_for_test(true); + init(dir.as_path(), prior); + assert!( + collect(Instant::now()) + .iter() + .all(|v| v["kind"] != "incident") + ); + } + + #[test] + fn body_stays_under_the_limit() { + let big = "x".repeat(MAX_MESSAGE_BYTES); + let entries: Vec = (0..1000) + .map(|n| Entry { + ts: n.to_string(), + level: "INFO".into(), + target: "t".into(), + message: big.clone(), + count: 1, + last_ts: None, + }) + .collect(); + let v = body("m", "incident", Some("t"), None, &entries, &scrub()); + assert!(serde_json::to_vec(&v).unwrap().len() <= MAX_BODY_BYTES); + // The newest entries are the ones kept. + assert_eq!( + v["entries"].as_array().unwrap().last().unwrap()["ts"], + "999" + ); + } + + #[test] + fn fingerprint_folds_numbers() { + assert_eq!( + fingerprint("t", "took 123 ms, 4 tries"), + fingerprint("t", "took 9 ms, 77 tries") + ); + assert_ne!(fingerprint("t", "a"), fingerprint("u", "a")); + } +} diff --git a/crates/failproofaid/src/main.rs b/crates/failproofaid/src/main.rs index 37205ee7c..3a5756305 100644 --- a/crates/failproofaid/src/main.rs +++ b/crates/failproofaid/src/main.rs @@ -6,6 +6,7 @@ mod cloud_client; pub mod cloud_policies; mod lock; mod logfile; +mod logship; mod paths; mod server; mod telemetry; @@ -141,18 +142,31 @@ fn init_logging() { ); #[cfg(not(target_os = "macos"))] let stderr = std::io::stderr; + // `logship::Capture` keeps a bounded in-memory copy for the upload that + // happens only when something goes wrong (see logship.rs). let _ = match file { - Some(file) => builder.with_writer(stderr.and(file)).try_init(), - None => builder.with_writer(stderr).try_init(), + Some(file) => builder + .with_writer(stderr.and(file).and(logship::Capture)) + .try_init(), + None => builder.with_writer(stderr.and(logship::Capture)).try_init(), }; } fn run() -> Result<(), Box> { + let logs_dir = paths::failproofai_home().ok().map(|home| home.join("logs")); + // Where the previous run's lines end, read before this run appends any. + let prior_log_len = logs_dir + .as_deref() + .and_then(|dir| logship::log_len_before_start(&dir.join("daemon.log"))); init_logging(); refuse_foreign_layout()?; let lock_path = paths::lock_path()?; paths::ensure_run_dir()?; let _singleton = lock::acquire(&lock_path)?; + // After the lock: the run marker belongs to the daemon that owns the machine. + if let Some(dir) = logs_dir.as_deref().filter(|dir| dir.is_dir()) { + logship::init(dir, prior_log_len); + } // Only the instance holding the lock may rotate the log launchd gives the // running service: a second invocation copying and truncating it could // cut out lines the live daemon appended in between. @@ -316,6 +330,13 @@ fn run() -> Result<(), Box> { ); telemetry::shutdown_flush(); + // A signal is a clean stop; a server error leaves the marker, so the next + // start reports this run's last lines (logship.rs). + if run_result.is_ok() + && let Some(dir) = logs_dir.as_deref() + { + logship::mark_clean_shutdown(dir); + } run_result?; Ok(()) } From 5a8c5b379940dc52d4961489e96477637641315a Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 18 Nov 2026 22:54:47 +0530 Subject: [PATCH 15/41] fix(daemon): make every uploaded log entry valid on the wire Cloud refuses a whole machine-logs upload over one bad entry. A line read back from daemon.log can lack a timestamp (worker stderr, a stack trace) or a module-path target, and scrubbing the token can lengthen a message past 2 KiB. Each entry now takes the previous line's time, a sanitised target (failproofaid when none), a wire level (TRACE -> DEBUG), a count of at least 1 and a message cut after scrubbing. Checked against the server's own validator with bodies of all three kinds. --- crates/failproofaid/src/logship.rs | 129 ++++++++++++++++++++++++++--- 1 file changed, 119 insertions(+), 10 deletions(-) diff --git a/crates/failproofaid/src/logship.rs b/crates/failproofaid/src/logship.rs index ae5012a99..3a6093982 100644 --- a/crates/failproofaid/src/logship.rs +++ b/crates/failproofaid/src/logship.rs @@ -73,21 +73,73 @@ pub struct Entry { } impl Entry { - fn to_json(&self, scrub: &Scrub) -> Value { + /// The wire form. Cloud refuses a whole upload over one bad entry, so every + /// field is made valid here rather than trusted: a line read back from a + /// file may have no timestamp (`fallback_ts`, the previous line's) and no + /// module path for a target. + fn to_json(&self, scrub: &Scrub, fallback_ts: &str) -> Value { + let ts = if looks_like_rfc3339(&self.ts) { + self.ts.as_str() + } else { + fallback_ts + }; + let message = scrub.apply(&self.message); let mut v = json!({ - "ts": self.ts, - "level": self.level, - "target": self.target, - "message": scrub.apply(&self.message), - "count": self.count, + "ts": ts, + "level": wire_level(&self.level), + "target": wire_target(&self.target), + "message": truncate(&message, MAX_MESSAGE_BYTES), + "count": self.count.max(1), }); - if let Some(last) = &self.last_ts { + if let Some(last) = self + .last_ts + .as_deref() + .filter(|l| looks_like_rfc3339(l) && *l >= ts) + { v["lastTs"] = json!(last); } v } } +fn looks_like_rfc3339(ts: &str) -> bool { + let b = ts.as_bytes(); + b.len() >= 20 + && b[4] == b'-' + && b[7] == b'-' + && b[10] == b'T' + && b[..4].iter().all(u8::is_ascii_digit) +} + +fn wire_level(level: &str) -> &'static str { + match level { + "ERROR" => "ERROR", + "WARN" => "WARN", + "INFO" => "INFO", + _ => "DEBUG", + } +} + +/// `[A-Za-z0-9_:./-]`, 1–256 chars (the server's rule). +fn wire_target(target: &str) -> String { + let clean: String = target + .chars() + .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | ':' | '.' | '-' | '/')) + .take(256) + .collect(); + if clean.is_empty() { + "failproofaid".to_string() + } else { + clean + } +} + +fn now_rfc3339() -> String { + time::OffsetDateTime::now_utc() + .format(&time::format_description::well_known::Rfc3339) + .unwrap_or_else(|_| "1970-01-01T00:00:00Z".to_string()) +} + struct Captured { entry: Entry, at: Instant, @@ -478,6 +530,25 @@ enum Kind { Errors, } +fn wire_entries(entries: &[Entry], scrub: &Scrub) -> Vec { + // An undated first line takes the first dated one's time, else now. + let mut last = entries + .iter() + .map(|e| e.ts.as_str()) + .find(|ts| looks_like_rfc3339(ts)) + .map_or_else(now_rfc3339, str::to_string); + entries + .iter() + .map(|e| { + let v = e.to_json(scrub, &last); + if let Some(ts) = v["ts"].as_str() { + last = ts.to_string(); + } + v + }) + .collect() +} + /// Build the body, keeping the NEWEST entries that fit. pub fn body( machine_id: &str, @@ -493,7 +564,7 @@ pub fn body( "machineId": machine_id, "daemonVersion": env!("CARGO_PKG_VERSION"), "kind": kind, - "entries": entries[start..].iter().map(|e| e.to_json(scrub)).collect::>(), + "entries": wire_entries(&entries[start..], scrub), }); if let Some(t) = trigger { v["trigger"] = json!(scrub.apply(t)); @@ -917,7 +988,7 @@ mod tests { let big = "x".repeat(MAX_MESSAGE_BYTES); let entries: Vec = (0..1000) .map(|n| Entry { - ts: n.to_string(), + ts: format!("2026-11-18T13:{:02}:{:02}.000000Z", n / 60 % 60, n % 60), level: "INFO".into(), target: "t".into(), message: big.clone(), @@ -930,10 +1001,48 @@ mod tests { // The newest entries are the ones kept. assert_eq!( v["entries"].as_array().unwrap().last().unwrap()["ts"], - "999" + "2026-11-18T13:16:39.000000Z" ); } + #[test] + fn every_entry_is_valid_on_the_wire() { + let text = "[failproofaid] worker stderr: boom\n".to_string() + + &line("INFO", "a::b", "dated") + + " at Module._load (node:internal)\n" + + "2026-11-18T13:18:40.000000Z TRACE x: verbose\n"; + let entries = entries_from_text(&text); + let long = Scrub::new(None, Some("tok12345".into())); + let mut e = entries.clone(); + e.push(Entry { + ts: "".into(), + level: "WARN".into(), + target: "bad target!".into(), + message: "tok12345".repeat(300), + count: 0, + last_ts: Some("x".into()), + }); + let v = body("m", "requested", None, Some("r"), &e, &long); + for entry in v["entries"].as_array().unwrap() { + let ts = entry["ts"].as_str().unwrap(); + assert!(looks_like_rfc3339(ts), "{entry}"); + let target = entry["target"].as_str().unwrap(); + assert!( + !target.is_empty() + && target + .chars() + .all(|c| c.is_ascii_alphanumeric() || "_:./-".contains(c)), + "{entry}" + ); + assert!(["ERROR", "WARN", "INFO", "DEBUG"].contains(&entry["level"].as_str().unwrap())); + assert!(entry["message"].as_str().unwrap().len() <= MAX_MESSAGE_BYTES); + assert!(entry["count"].as_u64().unwrap() >= 1); + assert!(entry.get("lastTs").is_none()); + } + // The undated first line borrows the first dated line's time. + assert_eq!(v["entries"][0]["ts"], "2026-11-18T13:18:37.676211Z"); + } + #[test] fn fingerprint_folds_numbers() { assert_eq!( From e7022e75a25c66d06c985ae9bbcc2b9dd5a8dd48 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 19 Nov 2026 00:02:07 +0530 Subject: [PATCH 16/41] fix: what a live end-to-end run found (outage retries, roll-up time, log fold) Found by installing the packed CLI in a systemd container against a local FailproofAI Cloud and driving it with a real Claude Code session. - Batches an outage parked waited for the hourly pass (and 5 minutes of age) after the server was back, while `config --status` said "nothing queued". An accepted delivery after a failed one now retries them at once (at most every 5 minutes), and status counts them as queued. - Allow roll-ups (the default verbosity) were stamped at the top of their minute, ahead of every tool call they covered. They are stamped when their first hook arrived and list the tool_call_ids they cover; a roll-up of one call carries that call's tool_call_id. - The machine-log roll-up folds every word holding a digit, so a retry warning with a fresh request id is one entry with a count, not one each. - The run marker and incident stamp are owner-only, and the stamp's content changes on every write so the 15-minute gap is measured from the last send. - Setup's summary pointed a Cloud-managed machine at installing a pack; it now says "Deploy from Cloud: ", as the policies screen does. --- __tests__/hooks/config-status.test.ts | 5 + __tests__/hooks/configure-wizard.test.ts | 15 +++ __tests__/hooks/delivery-health.test.ts | 10 ++ crates/failproofaid/src/logship.rs | 64 ++++++++-- crates/fpai-collect/src/delivery.rs | 105 ++++++++++++++++- crates/fpai-collect/src/sources/hooks/mod.rs | 2 + .../src/sources/hooks/transform.rs | 43 ++++++- crates/fpai-collect/tests/hooks_source.rs | 111 ++++++++++++++++++ src/hooks/config-status.ts | 3 +- src/hooks/configure-wizard.ts | 19 ++- src/hooks/delivery-health.ts | 10 ++ src/hooks/manager.ts | 2 +- 12 files changed, 363 insertions(+), 26 deletions(-) diff --git a/__tests__/hooks/config-status.test.ts b/__tests__/hooks/config-status.test.ts index 261f5aaf4..1079cd08d 100644 --- a/__tests__/hooks/config-status.test.ts +++ b/__tests__/hooks/config-status.test.ts @@ -296,6 +296,11 @@ describe("config --status — delivery", () => { ); }); + it("counts batches an outage parked as queued, since the daemon retries them", () => { + const parked = { ...facts().delivery!.refused, retrying: 2 }; + expect(deliveryRow({ refused: parked })).toBe("● Healthy, last event 12s ago, 2 batches queued"); + }); + it("puts refused batches in the row, with their status and age", () => { const refused = { total: 26, rejected: 26, credentialRejected: 26, resending: 0, byStatus: { 401: 26 }, oldestAgeMs: 134 * 60_000 }; expect(deliveryRow({ refused })).toBe("▲ 26 batches refused (401), oldest 2h14m"); diff --git a/__tests__/hooks/configure-wizard.test.ts b/__tests__/hooks/configure-wizard.test.ts index a883664b3..0b5bbfb20 100644 --- a/__tests__/hooks/configure-wizard.test.ts +++ b/__tests__/hooks/configure-wizard.test.ts @@ -33,6 +33,7 @@ vi.mock("../../src/hooks/manager", () => ({ installHooks: vi.fn(async () => {}), notEnforcingReason: vi.fn(() => "no-policies"), enforcingPolicyCount: vi.fn(() => ({ count: 0, custom: false })), + cloudDashboardUrl: vi.fn(() => undefined), })); // The apply path resolves project-scoped config from `process.cwd()` — this // repository, under test. A run that wrote there once committed custom policies @@ -525,6 +526,20 @@ describe("doneLines", () => { expect(lines).toContain(" Connect to cloud any time: failproofai config"); }); + it("points a Cloud-managed machine at Cloud, not at installing a pack", () => { + const lines = doneLines(kit, { + elapsedMs: 1, + done: [], + cwd: "/tmp/x", + agents: 1, + connected: true, + cloudDashboard: "https://app.example", + }); + expect(lines).toContain("▲ Policies are not enforcing yet."); + expect(lines).toContain(" Deploy from Cloud: https://app.example"); + expect(lines.join("\n")).not.toContain("policies add"); + }); + it("counts what enforces, on how many agents", () => { vi.mocked(notEnforcingReason).mockReturnValue(null); vi.mocked(enforcingPolicyCount).mockReturnValue({ count: 10, custom: false }); diff --git a/__tests__/hooks/delivery-health.test.ts b/__tests__/hooks/delivery-health.test.ts index f38b55512..43ec521ce 100644 --- a/__tests__/hooks/delivery-health.test.ts +++ b/__tests__/hooks/delivery-health.test.ts @@ -169,6 +169,16 @@ describe("hooks/delivery-health — refusals the current key has outlived", () = }); describe("hooks/delivery-health deliveryHealthLine", () => { + it("counts batches an outage parked as retrying, not refused", () => { + park("a-0.a1.jsonl"); + park("a-1.a4.jsonl"); + park("a-2.a1.c422.jsonl"); + park("a-3.a1.jsonl.poison"); + const health = deliveryHealth(home); + expect(health.retrying).toBe(2); + expect(health.rejected).toBe(1); + }); + it("says nothing when only transient parks exist", () => { // The retry pass will pick these up. Reporting them would cry wolf over a // blip the daemon is already handling. diff --git a/crates/failproofaid/src/logship.rs b/crates/failproofaid/src/logship.rs index 3a6093982..6fe751b15 100644 --- a/crates/failproofaid/src/logship.rs +++ b/crates/failproofaid/src/logship.rs @@ -304,23 +304,31 @@ fn truncate(text: &str, max: usize) -> &str { &text[..end] } -/// Same failure, different numbers → same fingerprint. +/// Same failure, different numbers → same fingerprint. Every word holding a +/// digit folds to `#`, so hex request ids, batch file names and durations do +/// not make one repeated failure look like many. pub fn fingerprint(target: &str, message: &str) -> String { let mut out = String::with_capacity(target.len() + message.len() + 1); out.push_str(target); out.push('|'); - let mut last_hash = false; + let mut word = String::new(); + let flush = |word: &mut String, out: &mut String| { + if word.chars().any(|c| c.is_ascii_digit()) { + out.push('#'); + } else { + out.push_str(word); + } + word.clear(); + }; for c in message.chars() { - if c.is_ascii_digit() { - if !last_hash { - out.push('#'); - } - last_hash = true; + if c.is_alphanumeric() || matches!(c, '_' | '-') { + word.push(c); } else { + flush(&mut word, &mut out); out.push(c); - last_hash = false; } } + flush(&mut word, &mut out); out } @@ -424,6 +432,22 @@ fn entries_from_text(text: &str) -> Vec { out } +/// Owner-only, like `daemon.log` beside it. +fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + use std::os::unix::fs::OpenOptionsExt; + let mut file = fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(path)?; + file.write_all(bytes)?; + // A file an older build left at 0644 keeps its mode on open. + use std::os::unix::fs::PermissionsExt; + file.set_permissions(fs::Permissions::from_mode(0o600)) +} + /// Size of `daemon.log` before this process writes to it. Call before the log /// subscriber is installed; pass the result to [`init`]. pub fn log_len_before_start(log_path: &Path) -> Option { @@ -465,7 +489,7 @@ pub fn init(logs_dir: &Path, prior_len: Option) { Instant::now(), ); } - let _ = fs::write(&marker, std::process::id().to_string()); + let _ = write_private(&marker, std::process::id().to_string().as_bytes()); } /// The daemon stopped on purpose (a signal): the next start is not an incident. @@ -691,7 +715,12 @@ fn ship_at(machine_id: &str, scrub: &Scrub, post: &dyn Fn(&Value) -> PostOutcome st.last_incident = Some(now); st.incidents_sent.push_back(now); if let Some(stamp) = st.stamp_path.clone() { - let _ = fs::write(stamp, b""); + // Content that changes each time, so the mtime the gap is + // measured from always moves (an empty rewrite may not). + let sent = SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let _ = write_private(&stamp, sent.to_string().as_bytes()); } } Kind::Errors => { @@ -1050,5 +1079,20 @@ mod tests { fingerprint("t", "took 9 ms, 77 tries") ); assert_ne!(fingerprint("t", "a"), fingerprint("u", "a")); + // Seen live: one retry warning per attempt, each with its own ids. + assert_eq!( + fingerprint( + "u", + "upload attempt failed; retrying file=~/s/hooks-activity-1795026411334556154-0.jsonl request_id=607541f010e04a7b8b9fed" + ), + fingerprint( + "u", + "upload attempt failed; retrying file=~/s/claude-03d689e9-35ed-48-1795026415345336098-0.jsonl request_id=6c47e6ba69784" + ) + ); + assert_ne!( + fingerprint("u", "upload failed"), + fingerprint("u", "parking a batch") + ); } } diff --git a/crates/fpai-collect/src/delivery.rs b/crates/fpai-collect/src/delivery.rs index 69ed7d974..ce43e47bb 100644 --- a/crates/fpai-collect/src/delivery.rs +++ b/crates/fpai-collect/src/delivery.rs @@ -72,6 +72,9 @@ const FAILED_RETRY_INTERVAL: Duration = Duration::from_secs(3600); const FAILED_RETRY_MIN_AGE: Duration = Duration::from_secs(300); /// Parked batches per retry pass. const FAILED_RETRY_MAX_FILES: usize = 16; +/// Minimum gap between two "the server is back" retries of parked batches, so +/// a flapping connection cannot turn every accepted upload into a pass. +const RECOVERY_RETRY_GAP: Duration = Duration::from_secs(300); /// At most one refused batch after a fresh delivery, so the serial watcher /// and sweeper return to fresh work instead of draining a credential backlog. const REFUSED_REDRIVE_MAX_FILES: usize = 1; @@ -90,6 +93,12 @@ pub struct Delivery { in_flight: Arc>>, replay_gate: Arc, replay_ready: std::sync::atomic::AtomicBool, + /// A delivery failed since the last one the server accepted. Starts true, + /// so the first accepted delivery after a start also looks at `failed/`. + failing: std::sync::atomic::AtomicBool, + /// An accepted delivery followed a failure: the server is reachable again, + /// so what an outage parked can go now rather than at the hourly pass. + recovered: std::sync::atomic::AtomicBool, } /// Cancellation must leave another pass scheduled and release the global gate. @@ -131,9 +140,16 @@ impl Delivery { in_flight: Arc::new(Mutex::new(HashSet::new())), replay_gate: Arc::new(Semaphore::new(1)), replay_ready: std::sync::atomic::AtomicBool::new(false), + failing: std::sync::atomic::AtomicBool::new(true), + recovered: std::sync::atomic::AtomicBool::new(false), } } + /// Whether the server came back since the last call (see `recovered`). + fn take_recovered(&self) -> bool { + self.recovered.swap(false, Ordering::SeqCst) + } + /// Claim `path` for delivery, or `None` if another task already has it. /// /// Claiming and releasing are a guard rather than a pair of calls so an @@ -186,15 +202,21 @@ impl Delivery { // The owning watcher/sweeper schedules replay separately. // Never await background retries on the fresh-delivery path. self.replay_ready.store(true, Ordering::SeqCst); + if self.failing.swap(false, Ordering::SeqCst) { + self.recovered.store(true, Ordering::SeqCst); + } } // The batch id ties this to the attempt and park lines, which // carry the request ids. - Err(err) => tracing::warn!( - file = %path.display(), - batch_id = %batch_id(&path), - %err, - "upload failed" - ), + Err(err) => { + self.failing.store(true, Ordering::SeqCst); + tracing::warn!( + file = %path.display(), + batch_id = %batch_id(&path), + %err, + "upload failed" + ) + } } } @@ -404,6 +426,7 @@ pub async fn sweep( // event for those files is never coming — they were published while // nothing was listening. let mut next_failed_pass = SystemTime::now(); + let mut next_recovery_pass = SystemTime::now(); let mut replays = tokio::task::JoinSet::new(); loop { @@ -449,6 +472,14 @@ pub async fn sweep( delivery.schedule_refused(&mut replays, &sd); break; } + // The server accepted a batch after an outage: retry what the + // outage parked now, not at the next hourly pass, with no minimum + // age (the failure that parked them is over). + if SystemTime::now() >= next_recovery_pass && delivery.take_recovered() { + retry_parked(&delivery, &failed_dir, &sd, Duration::ZERO).await; + delivery.schedule_refused(&mut replays, &sd); + next_recovery_pass = SystemTime::now() + RECOVERY_RETRY_GAP; + } if SystemTime::now() >= deadline { break; } @@ -609,6 +640,68 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + /// What an outage parked goes as soon as the server accepts a batch again, + /// not at the hourly pass and not only once it is five minutes old. + #[tokio::test(flavor = "multi_thread")] + async fn an_accepted_delivery_after_an_outage_retries_parked_batches_now() { + use wiremock::matchers::method; + use wiremock::{Mock, MockServer, ResponseTemplate}; + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(serde_json::json!({"accepted": 1, "skipped": 0})), + ) + .mount(&server) + .await; + let failed = tmpdir("recovery-failed"); + let spool = tmpdir("recovery-spool"); + // Parked by the outage a moment ago: younger than FAILED_RETRY_MIN_AGE. + let parked = failed.join("hooks-activity-1-0.a1.jsonl"); + std::fs::write(&parked, "{}\n").unwrap(); + // A refusal is not an outage: it stays for the credential redrive. + let refused = failed.join("other-1-0.a1.c422.jsonl"); + std::fs::write(&refused, "{}\n").unwrap(); + + let delivery = Arc::new(Delivery::new(Arc::new( + Uploader::new(server.uri(), "k".into(), failed.clone()).unwrap(), + ))); + let flag = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let sd = Shutdown::for_test(flag.clone()); + let sweeper = tokio::spawn(sweep( + delivery.clone(), + vec![spool.clone()], + failed.clone(), + sd, + Arc::new(std::sync::atomic::AtomicBool::new(false)), + )); + // The cold-start pass keeps the age gate: the young park stays. + tokio::time::sleep(Duration::from_millis(1500)).await; + assert!(parked.exists(), "no recovery has been seen yet"); + + // A fresh batch the server accepts: it is back. + let fresh = spool.join("hooks-activity-2-0.jsonl"); + std::fs::write(&fresh, "{}\n").unwrap(); + delivery.deliver(fresh.clone()).await; + let deadline = std::time::Instant::now() + Duration::from_secs(10); + while parked.exists() && std::time::Instant::now() < deadline { + tokio::time::sleep(Duration::from_millis(100)).await; + } + assert!( + !parked.exists(), + "the parked batch must go once the server is back" + ); + assert!( + refused.exists(), + "a 422 refusal is not retried as an outage" + ); + + flag.store(true, Ordering::SeqCst); + let _ = tokio::time::timeout(Duration::from_secs(5), sweeper).await; + std::fs::remove_dir_all(failed).ok(); + std::fs::remove_dir_all(spool).ok(); + } + #[tokio::test] async fn a_refusal_the_current_key_repeats_is_reparked_and_others_are_kept() { use wiremock::matchers::{body_string, method}; diff --git a/crates/fpai-collect/src/sources/hooks/mod.rs b/crates/fpai-collect/src/sources/hooks/mod.rs index 31ef478a7..0356133bd 100644 --- a/crates/fpai-collect/src/sources/hooks/mod.rs +++ b/crates/fpai-collect/src/sources/hooks/mod.rs @@ -260,6 +260,8 @@ async fn poll_once( event_name: key.1.clone(), tool_name: key.2.clone(), minute_ms: key.3, + first_ms: i64::MAX, + tool_call_ids: Vec::new(), count: 0, total_duration_ms: 0.0, max_duration_ms: 0.0, diff --git a/crates/fpai-collect/src/sources/hooks/transform.rs b/crates/fpai-collect/src/sources/hooks/transform.rs index 7d4088f2e..2afd9741f 100644 --- a/crates/fpai-collect/src/sources/hooks/transform.rs +++ b/crates/fpai-collect/src/sources/hooks/transform.rs @@ -980,8 +980,15 @@ pub struct AllowBucket { pub agent_id: String, pub event_name: String, pub tool_name: Option, - /// Truncated to the minute; also the bucket's emitted timestamp. + /// Truncated to the minute: the bucket's KEY (and its `hook_id`). pub minute_ms: i64, + /// When the bucket's first hook arrived (its `startedAt`, else its end): + /// the emitted timestamp. Stamping the minute instead put every roll-up + /// before the tool calls it covered. `i64::MAX` until a row is added. + pub first_ms: i64, + /// The agent's tool-call ids the bucket covers, in arrival order, at most + /// [`MAX_BUCKET_TOOL_CALL_IDS`], so Cloud can join a roll-up to its calls. + pub tool_call_ids: Vec, pub count: u64, pub total_duration_ms: f64, pub max_duration_ms: f64, @@ -1019,9 +1026,23 @@ pub fn bucket_key(row: &HookRow) -> Option { )) } +/// Bound on `AllowBucket::tool_call_ids`: a busy minute stays one small event. +pub const MAX_BUCKET_TOOL_CALL_IDS: usize = 64; + impl AllowBucket { pub fn add(&mut self, row: &HookRow) { self.count += 1; + let arrived = row + .started_at + .filter(|at| *at <= row.timestamp) + .unwrap_or(row.timestamp); + self.first_ms = self.first_ms.min(arrived); + if let Some(id) = row.tool_call_id.as_deref().filter(|id| !id.is_empty()) + && self.tool_call_ids.len() < MAX_BUCKET_TOOL_CALL_IDS + && !self.tool_call_ids.iter().any(|known| known == id) + { + self.tool_call_ids.push(id.to_string()); + } let d = row.duration_ms.unwrap_or(0.0); self.total_duration_ms += d; if d > self.max_duration_ms { @@ -1043,10 +1064,12 @@ impl AllowBucket { /// report a duration that belongs to no real hook call. pub fn to_event(&self, environment: &str) -> Option { let mut m = Map::new(); - m.insert( - "timestamp".into(), - json!(to_rfc3339_micros(self.minute_ms, 0)?), - ); + let at = if self.first_ms == i64::MAX { + self.minute_ms + } else { + self.first_ms + }; + m.insert("timestamp".into(), json!(to_rfc3339_micros(at, 0)?)); m.insert("session_id".into(), json!(self.session_id)); m.insert("agent_id".into(), json!(self.agent_id)); m.insert("type".into(), json!("hook_completed")); @@ -1116,6 +1139,16 @@ impl AllowBucket { if let Some(t) = &self.tool_name { m.insert("tool_name".into(), json!(t)); } + if !self.tool_call_ids.is_empty() { + m.insert("tool_call_ids".into(), json!(self.tool_call_ids)); + } + // A bucket of exactly one call IS that call's hook: the same field the + // per-row legs carry, so it joins its tool call like they do. + if self.count == 1 + && let [only] = self.tool_call_ids.as_slice() + { + m.insert("tool_call_id".into(), json!(only)); + } // Honest by construction: every row in this bucket was grouped BY this // attribution, so it describes all of them. self.attribution.apply(&mut m); diff --git a/crates/fpai-collect/tests/hooks_source.rs b/crates/fpai-collect/tests/hooks_source.rs index f646679e9..7454ef90f 100644 --- a/crates/fpai-collect/tests/hooks_source.rs +++ b/crates/fpai-collect/tests/hooks_source.rs @@ -259,6 +259,117 @@ async fn decisions_verbosity_keeps_denies_exact_and_rolls_up_allows() { fs::remove_dir_all(&spool).ok(); } +fn allow_row_with(ts: i64, started: i64, tool: &str, event: &str, id: Option<&str>) -> String { + let mut v: Value = serde_json::from_str(&allow_row(ts, tool)).unwrap(); + v["startedAt"] = serde_json::json!(started); + v["eventType"] = serde_json::json!(event); + if let Some(id) = id { + v["toolCallId"] = serde_json::json!(id); + } + v.to_string() +} + +/// A roll-up is stamped where its first hook ARRIVED, not at the top of the +/// minute: the minute stamp put every allow bucket before the tool calls it +/// covered on the session timeline. It names the calls it covers, and a +/// bucket of one call carries that call's id like a per-row leg does. +#[tokio::test(flavor = "multi_thread")] +async fn an_allow_rollup_is_stamped_at_its_first_hook_and_names_its_calls() { + let store = tmpdir("agg-ids-store"); + let state = tmpdir("agg-ids-state"); + let spool = tmpdir("agg-ids-spool"); + let minute = 1785740940000; // a minute boundary + let mut lines = vec![ + // Arrived 2.1 s into the minute; ended at 2.3 s. + allow_row_with( + minute + 2300, + minute + 2100, + "Bash", + "PreToolUse", + Some("toolu_a"), + ), + allow_row_with( + minute + 5000, + minute + 4900, + "Bash", + "PreToolUse", + Some("toolu_b"), + ), + // The same call again (a retry) is listed once. + allow_row_with( + minute + 6000, + minute + 5900, + "Bash", + "PreToolUse", + Some("toolu_b"), + ), + // A startedAt after its own end is not believed. + allow_row_with( + minute + 7000, + minute + 9000, + "Read", + "PreToolUse", + Some("toolu_c"), + ), + ]; + // 70 more calls in another bucket: the list is capped. + for i in 0..70 { + lines.push(allow_row_with( + minute + 10_000 + i, + minute + 10_000 + i, + "Edit", + "PostToolUse", + Some(&format!("toolu_e{i}")), + )); + } + fs::write(store.join("current.jsonl"), lines.join("\n") + "\n").unwrap(); + + run_once(&store, &state, &spool, HooksVerbosity::Decisions).await; + let events = spooled(&spool); + let bucket = |tool: &str| { + events + .iter() + .find(|e| e["tool_name"] == tool && e["outcome"] == "allow") + .unwrap_or_else(|| panic!("no {tool} bucket in {events:?}")) + .clone() + }; + + let bash = bucket("Bash"); + assert_eq!(bash["failproofai_allow_count"], 3); + assert_eq!(bash["timestamp"], "2026-08-03T07:09:02.100000Z"); + assert_eq!( + bash["tool_call_ids"], + serde_json::json!(["toolu_a", "toolu_b"]) + ); + assert!( + bash.get("tool_call_id").is_none(), + "a bucket of several calls is no single call's hook" + ); + // The id still names the minute, so it is unchanged from earlier builds. + assert!( + bash["hook_id"] + .as_str() + .unwrap() + .contains(&format!(":{minute}:")) + ); + + let read = bucket("Read"); + assert_eq!(read["timestamp"], "2026-08-03T07:09:07.000000Z"); + assert_eq!(read["tool_call_id"], "toolu_c"); + assert_eq!(read["tool_call_ids"], serde_json::json!(["toolu_c"])); + + let edit = bucket("Edit"); + assert_eq!(edit["failproofai_allow_count"], 70); + assert_eq!( + edit["tool_call_ids"].as_array().unwrap().len(), + transform::MAX_BUCKET_TOOL_CALL_IDS + ); + + fs::remove_dir_all(&store).ok(); + fs::remove_dir_all(&state).ok(); + fs::remove_dir_all(&spool).ok(); +} + #[tokio::test(flavor = "multi_thread")] async fn all_verbosity_emits_a_pair_for_every_row() { let store = tmpdir("all-store"); diff --git a/src/hooks/config-status.ts b/src/hooks/config-status.ts index e24a69387..2e129b102 100644 --- a/src/hooks/config-status.ts +++ b/src/hooks/config-status.ts @@ -531,7 +531,8 @@ export function renderStatusScreen(facts: StatusFacts, opts: ScreenKitOpts & { c if (!health.delivering) return `${kit.off} Not delivering, failproofaid has no key`; // Batches an earlier key had refused wait for the daemon to re-send them // with the key that works now: queued, not refused. - const pending = queued + (refused.resending ?? 0); + // So do batches an outage parked: the daemon retries them itself. + const pending = queued + (refused.resending ?? 0) + (refused.retrying ?? 0); const backlog = pending === 0 ? "nothing queued" : `${many(pending, "batch", "batches")} queued`; const stuck = queued > 0 && diff --git a/src/hooks/configure-wizard.ts b/src/hooks/configure-wizard.ts index 5c01de189..2bdcd6578 100644 --- a/src/hooks/configure-wizard.ts +++ b/src/hooks/configure-wizard.ts @@ -61,7 +61,7 @@ import { settingsPathsFor, } from "./integrations"; import { INTEGRATION_TYPES, type IntegrationType, type HookScope } from "./types"; -import { enforcingPolicyCount, installHooks, notEnforcingReason } from "./manager"; +import { cloudDashboardUrl, enforcingPolicyCount, installHooks, notEnforcingReason } from "./manager"; import { installAgentSkill } from "./agent-skill"; import { CODEX_UNTRUSTED_NOTICE, @@ -1613,6 +1613,7 @@ export async function runConfigureWizard( agents: selected.length, connected: cloudAfter, codexTrust, + cloudDashboard: cloudAfter ? cloudDashboardUrl() : undefined, }), ); @@ -1840,7 +1841,16 @@ function failClosedPacks(): Array<{ id: string | null }> { */ export function doneLines( kit: ReturnType, - state: { elapsedMs: number; done: string[]; cwd: string; agents: number; connected: boolean; codexTrust?: CodexHookTrust }, + state: { + elapsedMs: number; + done: string[]; + cwd: string; + agents: number; + connected: boolean; + codexTrust?: CodexHookTrust; + /** Set when this machine pulls its policies from Cloud: point there, not at packs. */ + cloudDashboard?: string; + }, ): string[] { const lines = [kit.head("Done", `in ${(state.elapsedMs / 1000).toFixed(1)}s`), ...state.done]; // Codex with untrusted hooks runs none of them: it is not an agent anything @@ -1851,7 +1861,10 @@ export function doneLines( if (notEnforcingReason(state.cwd)) { lines.push( kit.caution("Policies are not enforcing yet."), - ` Turn on ours: ${kit.cmd(`failproofai policies add ${CORE_SOURCE}`)}`, + // The same line the policies screen's empty state uses for such a machine. + state.cloudDashboard + ? ` Deploy from Cloud: ${kit.cmd(state.cloudDashboard)}` + : ` Turn on ours: ${kit.cmd(`failproofai policies add ${CORE_SOURCE}`)}`, ); } else { const { count, custom } = enforcingPolicyCount(state.cwd); diff --git a/src/hooks/delivery-health.ts b/src/hooks/delivery-health.ts index 77f78b724..89a00cccf 100644 --- a/src/hooks/delivery-health.ts +++ b/src/hooks/delivery-health.ts @@ -132,6 +132,12 @@ export interface DeliveryHealth { * and drops one only if the current key refuses it too. */ resending: number; + /** + * Parked by a failure that was not a refusal (an outage, a timeout): the + * daemon retries these itself, and right away once the server accepts a + * batch again. Queued, not lost. Absent when there are none. + */ + retrying?: number; /** Age of the oldest parked batch, in ms. Undefined when none are parked. */ oldestAgeMs?: number; } @@ -187,6 +193,7 @@ export function deliveryHealth( let rejected = 0; let credentialRejected = 0; let resending = 0; + let retrying = 0; let oldestMtime: number | undefined; for (const name of entries) { @@ -221,6 +228,8 @@ export function deliveryHealth( rejected += 1; byStatus[parsed.clientStatus] = (byStatus[parsed.clientStatus] ?? 0) + 1; if (CREDENTIAL_STATUSES.has(parsed.clientStatus)) credentialRejected += 1; + } else if (!parsed.poison) { + retrying += 1; } if (oldestMtime === undefined || mtime < oldestMtime) oldestMtime = mtime; @@ -232,6 +241,7 @@ export function deliveryHealth( credentialRejected, byStatus, resending, + ...(retrying > 0 ? { retrying } : {}), ...(oldestMtime !== undefined ? { oldestAgeMs: Math.max(0, now - oldestMtime) } : {}), }; } diff --git a/src/hooks/manager.ts b/src/hooks/manager.ts index 1c7379b9b..f147f3df5 100644 --- a/src/hooks/manager.ts +++ b/src/hooks/manager.ts @@ -1303,7 +1303,7 @@ export interface PoliciesScreen { } /** The dashboard a cloud-connected machine pulls policies from, or undefined. */ -function cloudDashboardUrl(): string | undefined { +export function cloudDashboardUrl(): string | undefined { // FAILPROOFAI_CLOUD_URL wins over the credential file in the daemon, so a // machine connected that way pulls from Cloud too. const fromEnv = process.env.FAILPROOFAI_CLOUD_URL?.trim(); From 041ea544289694df383d12a422f47e4ed501d068 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 19 Nov 2026 00:23:44 +0530 Subject: [PATCH 17/41] fix(collector): retry what an outage parked on an idle machine too An accepted delivery was the only recovery signal, so a machine with nothing new to send left its parked batches for the hourly pass. While the last delivery failed, one parked batch goes as a probe every 5 minutes; its success is the recovery that sends the rest. Verified live: with no new events, the batches an outage parked arrived within one probe of the server coming back. --- crates/fpai-collect/src/delivery.rs | 50 ++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 16 deletions(-) diff --git a/crates/fpai-collect/src/delivery.rs b/crates/fpai-collect/src/delivery.rs index ce43e47bb..66bd599a4 100644 --- a/crates/fpai-collect/src/delivery.rs +++ b/crates/fpai-collect/src/delivery.rs @@ -427,6 +427,7 @@ pub async fn sweep( // nothing was listening. let mut next_failed_pass = SystemTime::now(); let mut next_recovery_pass = SystemTime::now(); + let mut next_probe = SystemTime::now(); let mut replays = tokio::task::JoinSet::new(); loop { @@ -480,6 +481,13 @@ pub async fn sweep( delivery.schedule_refused(&mut replays, &sd); next_recovery_pass = SystemTime::now() + RECOVERY_RETRY_GAP; } + // An idle machine sends nothing fresh to notice the server is back: + // while the last delivery failed, one parked batch goes as a probe + // each gap, and its success is the recovery above. + if SystemTime::now() >= next_probe && delivery.failing.load(Ordering::SeqCst) { + retry_parked_up_to(&delivery, &failed_dir, &sd, Duration::ZERO, 1).await; + next_probe = SystemTime::now() + RECOVERY_RETRY_GAP; + } if SystemTime::now() >= deadline { break; } @@ -543,6 +551,16 @@ fn sweepable(name: &str) -> bool { } async fn retry_parked(delivery: &Delivery, failed_dir: &Path, sd: &Shutdown, min_age: Duration) { + retry_parked_up_to(delivery, failed_dir, sd, min_age, FAILED_RETRY_MAX_FILES).await; +} + +async fn retry_parked_up_to( + delivery: &Delivery, + failed_dir: &Path, + sd: &Shutdown, + min_age: Duration, + max: usize, +) { let Ok(mut rd) = tokio::fs::read_dir(failed_dir).await else { return; }; @@ -573,12 +591,9 @@ async fn retry_parked(delivery: &Delivery, failed_dir: &Path, sd: &Shutdown, min return; } found.sort_by_key(|(t, _)| *t); - tracing::info!( - count = found.len().min(FAILED_RETRY_MAX_FILES), - "retrying parked batches" - ); + tracing::info!(count = found.len().min(max), "retrying parked batches"); - for (_, path) in found.into_iter().take(FAILED_RETRY_MAX_FILES) { + for (_, path) in found.into_iter().take(max) { if sd.is_set() { return; } @@ -641,7 +656,8 @@ mod tests { } /// What an outage parked goes as soon as the server accepts a batch again, - /// not at the hourly pass and not only once it is five minutes old. + /// not at the hourly pass and not only once it is five minutes old — even + /// on an idle machine, through a one-batch probe. #[tokio::test(flavor = "multi_thread")] async fn an_accepted_delivery_after_an_outage_retries_parked_batches_now() { use wiremock::matchers::method; @@ -657,6 +673,9 @@ mod tests { let failed = tmpdir("recovery-failed"); let spool = tmpdir("recovery-spool"); // Parked by the outage a moment ago: younger than FAILED_RETRY_MIN_AGE. + let probe_first = failed.join("hooks-activity-0-0.a1.jsonl"); + std::fs::write(&probe_first, "{}\n").unwrap(); + std::thread::sleep(Duration::from_millis(20)); let parked = failed.join("hooks-activity-1-0.a1.jsonl"); std::fs::write(&parked, "{}\n").unwrap(); // A refusal is not an outage: it stays for the credential redrive. @@ -675,22 +694,21 @@ mod tests { sd, Arc::new(std::sync::atomic::AtomicBool::new(false)), )); - // The cold-start pass keeps the age gate: the young park stays. - tokio::time::sleep(Duration::from_millis(1500)).await; - assert!(parked.exists(), "no recovery has been seen yet"); - - // A fresh batch the server accepts: it is back. - let fresh = spool.join("hooks-activity-2-0.jsonl"); - std::fs::write(&fresh, "{}\n").unwrap(); - delivery.deliver(fresh.clone()).await; + // Nothing fresh to send: the first parked batch goes as a probe, and + // its success lets the rest follow (an idle machine recovers too). let deadline = std::time::Instant::now() + Duration::from_secs(10); - while parked.exists() && std::time::Instant::now() < deadline { + while (probe_first.exists() || parked.exists()) && std::time::Instant::now() < deadline { tokio::time::sleep(Duration::from_millis(100)).await; } + assert!( + !probe_first.exists(), + "the oldest parked batch is the probe" + ); assert!( !parked.exists(), - "the parked batch must go once the server is back" + "an accepted probe lets the rest of the outage's batches go" ); + assert!( refused.exists(), "a 422 refusal is not retried as an outage" From b3e4dd26b0b2160cfaf3934ab8021008fe21b7cd Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 19 Nov 2026 00:44:28 +0530 Subject: [PATCH 18/41] fix: review round 4 on #1023 (F2, F4, F5, F6) - F6: a line the daemon relays from a child process (worker or scheduled audit stdout/stderr) is never part of an automatic upload: it opens no incident, joins no errors roll-up and is dropped from an unclean-restart tail. Only an operator's request includes it. Every uploaded message now goes through the collector's secret redaction (`redact::scrub_str`) as well as the home/token scrub. - F5: the log tail opens with O_NONBLOCK | O_NOFOLLOW and reads regular files only, so a FIFO or link at daemon.log cannot stall startup before the socket is bound; with uploads off the previous run's log is not read at all. Regression: a real daemon with a FIFO log and a leftover run marker binds its socket and answers ping, uploads on and off (fails on the old open). - F4: all three clients (CLI, Hermes, OpenClaw) re-check the deployment after the older-version retry returns and discard its answer if targeting can no longer be ruled out. Regression in each: schema 3 installed while the v1 daemon evaluates. - F2: the collector manager's handles live outside its supervised body, so a restart after a panic still owns the deployment the last run started and waits until it has stopped (however long its upload takes) before starting another over the same queues. --- .../fixtures/hermes-native-plugin-check.py | 23 +++ __tests__/hooks/daemon-client.test.ts | 24 +++ __tests__/hooks/openclaw-plugin.test.ts | 19 ++ crates/failproofaid/src/logship.rs | 163 +++++++++++++++++- crates/failproofaid/src/main.rs | 131 ++++++++++++-- crates/failproofaid/tests/daemon_e2e.rs | 59 +++++++ hermes-plugin/client.py | 4 + openclaw-plugin/daemon-client.js | 6 + src/hooks/daemon-client.ts | 7 +- 9 files changed, 414 insertions(+), 22 deletions(-) diff --git a/__tests__/fixtures/hermes-native-plugin-check.py b/__tests__/fixtures/hermes-native-plugin-check.py index 130bd16c8..e80aad162 100644 --- a/__tests__/fixtures/hermes-native-plugin-check.py +++ b/__tests__/fixtures/hermes-native-plugin-check.py @@ -3,6 +3,7 @@ import contextvars import importlib.util import json +import os import socket import struct import sys @@ -110,6 +111,11 @@ def server() -> None: deadline = time.monotonic() + 2 length = struct.unpack(">I", client._read_exact(connection, 4, deadline))[0] received.append(json.loads(client._read_exact(connection, length, deadline))) + # A response may run a side effect before it is sent (a + # deployment changing while the daemon evaluates). + before = response.pop("_before_reply", None) if isinstance(response, dict) else None + if callable(before): + before() body = json.dumps({"type": "policyResult", "protocolVersion": client.PROTOCOL_VERSION, **response}).encode() connection.sendall(struct.pack(">I", len(body)) + body) @@ -1758,6 +1764,23 @@ def test_no_fallback_where_the_deployment_targets_agents(self) -> None: self.assertIsInstance(result, client.EvaluationError) self.assertEqual(len(received), 1) + def test_a_targeted_deployment_during_the_retry_discards_its_answer(self) -> None: + # Cloud activated agent-targeted policies while the v1 daemon was + # evaluating: its allow was made without this agent. + def install_schema_3() -> None: + policy_dir = Path(os.environ["FAILPROOFAI_CLOUD_POLICY_DIR"]) + (policy_dir / "active.json").write_text( + json.dumps({"schemaVersion": 3, "deployment": 5, "policies": []}) + ) + + result, received = self._evaluate([ + {"type": "error", "protocolVersion": 1, "message": "protocol version mismatch"}, + {"protocolVersion": 1, "decision": "allow", "policyNames": [], "reason": None, + "matchedPolicies": [], "durationMs": 1, "toolName": "Bash", "_before_reply": install_schema_3}, + ]) + self.assertIsInstance(result, client.EvaluationError) + self.assertEqual([r["protocolVersion"] for r in received], [2, 1]) + def test_no_fallback_where_the_deployment_cannot_be_read(self) -> None: result, received = self._evaluate( [{"type": "error", "protocolVersion": 1, "message": "protocol version mismatch"}], raw="{" diff --git a/__tests__/hooks/daemon-client.test.ts b/__tests__/hooks/daemon-client.test.ts index 1baf274a1..c8abcb6ef 100644 --- a/__tests__/hooks/daemon-client.test.ts +++ b/__tests__/hooks/daemon-client.test.ts @@ -302,6 +302,30 @@ describe("hooks/daemon-client", () => { expect(connections).toBe(1); }); + it("discards the older daemon's answer when a targeted deployment arrives during the retry", async () => { + // Cloud activated agent-targeted policies while the v1 daemon evaluated: + // its allow was made without this agent and is no safer than before. + const requests: number[] = []; + await startServer(async (socket) => { + const request = (await readFrame(socket)) as Record; + requests.push(request.protocolVersion as number); + if (request.protocolVersion === 1) { + mkdirSync(process.env.FAILPROOFAI_CLOUD_POLICY_DIR!, { recursive: true }); + writeFileSync( + join(process.env.FAILPROOFAI_CLOUD_POLICY_DIR!, "active.json"), + JSON.stringify({ schemaVersion: 3, deployment: 5, policies: [] }), + ); + socket.end(encodeFrame({ type: "hookResult", protocolVersion: 1, exitCode: 0, stdout: "", stderr: "" })); + } else { + socket.end(encodeFrame({ type: "error", protocolVersion: 1, message: "protocol version mismatch" })); + } + }); + const { attemptDaemonHook } = await import("../../src/hooks/daemon-client"); + const attempt = await attemptDaemonHook({ hookEvent: "PreToolUse", cli: "claude", stdin: "{}" }); + expect(requests).toEqual([2, 1]); + expect(attempt).toEqual({ ok: false, failure: "protocol-mismatch" }); + }); + it("does not fall back where the deployment cannot be read to rule targets out", async () => { mkdirSync(process.env.FAILPROOFAI_CLOUD_POLICY_DIR!, { recursive: true }); writeFileSync(join(process.env.FAILPROOFAI_CLOUD_POLICY_DIR!, "active.json"), "{"); diff --git a/__tests__/hooks/openclaw-plugin.test.ts b/__tests__/hooks/openclaw-plugin.test.ts index cc2164151..59c0cf3fe 100644 --- a/__tests__/hooks/openclaw-plugin.test.ts +++ b/__tests__/hooks/openclaw-plugin.test.ts @@ -286,6 +286,25 @@ describe("openclaw-plugin daemon-client: requestHookVerdict", () => { } }); + it("discards the older daemon's answer when a targeted deployment arrives during the retry", async () => { + const policies = join(dir, "cloud-policies-inflight"); + mkdirSync(policies, { recursive: true }); + vi.stubEnv("FAILPROOFAI_CLOUD_POLICY_DIR", policies); + const daemon = await fakeDaemon(socketPath, (request) => { + if (request.protocolVersion !== 1) return { type: "error", protocolVersion: 1, message: "mismatch" }; + writeFileSync(join(policies, "active.json"), JSON.stringify({ schemaVersion: 3, deployment: 5, policies: [] })); + return { type: "hookResult", protocolVersion: 1, exitCode: 0, stdout: "", stderr: "" }; + }); + try { + const result = await requestHookVerdict({ event: "before_tool_call", payload: {}, socketPath }); + expect(daemon.requests.map((r) => r.protocolVersion)).toEqual([2, 1]); + expect(result).toMatchObject({ ok: false, failure: "protocol-mismatch" }); + expect(result).not.toHaveProperty("daemonVersion"); + } finally { + await daemon.close(); + } + }); + it("does not retry below the oldest supported version", async () => { const daemon = await fakeDaemon(socketPath, () => ({ type: "error", protocolVersion: 0, message: "x" })); try { diff --git a/crates/failproofaid/src/logship.rs b/crates/failproofaid/src/logship.rs index 6fe751b15..63bd736bb 100644 --- a/crates/failproofaid/src/logship.rs +++ b/crates/failproofaid/src/logship.rs @@ -24,7 +24,7 @@ //! `FAILPROOFAI_NO_LOG_UPLOAD=1` turns uploading off. use std::collections::{HashMap, VecDeque}; -use std::fs::{self, File}; +use std::fs; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use std::sync::{LazyLock, Mutex, MutexGuard}; @@ -334,6 +334,10 @@ pub fn fingerprint(target: &str, message: &str) -> String { fn record(level: Level, target: &str, line: &str, now: Instant) { let entry = parse_line(line, Some(level.as_str()), Some(target)); + // Child output stays in daemon.log only (see `is_child_output`). + if is_child_output(&entry.message) { + return; + } // This module's own failures never trigger an upload of themselves. let own = target.starts_with(module_path!()); let mut st = state(); @@ -403,8 +407,20 @@ fn maybe_open_incident(st: &mut State, trigger: String, entries: Option, max: u64) -> Option { - let mut file = File::open(path).ok()?; - let len = file.metadata().ok()?.len(); + use std::os::unix::fs::OpenOptionsExt; + // Never blocks and never follows a link: a FIFO or a symlink planted at + // the log path must not stall startup (this runs before the socket is + // bound, and every hook is denied until it is) or read another file. + let mut file = fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW) + .open(path) + .ok()?; + let meta = file.metadata().ok()?; + if !meta.file_type().is_file() { + return None; + } + let len = meta.len(); let end = end.map_or(len, |e| e.min(len)); let start = end.saturating_sub(max); file.seek(SeekFrom::Start(start)).ok()?; @@ -420,11 +436,27 @@ fn tail(path: &Path, end: Option, max: u64) -> Option { }) } -fn entries_from_text(text: &str) -> Vec { +/// A line the daemon relays from a child process (the worker, the scheduled +/// audit). Its text is whatever that process printed — a custom policy's own +/// diagnostics, a tool command — so it never goes up automatically: only an +/// operator's request includes it, and then redacted like every line. +fn is_child_output(message: &str) -> bool { + [ + "worker stdout:", + "worker stderr:", + "audit stdout:", + "audit stderr:", + ] + .iter() + .any(|prefix| message.starts_with(prefix)) +} + +fn entries_from_text(text: &str, with_child_output: bool) -> Vec { let mut out: Vec = text .lines() .filter(|l| !l.trim().is_empty()) .map(|l| parse_line(l, None, None)) + .filter(|e| with_child_output || !is_child_output(&e.message)) .collect(); if out.len() > MAX_ENTRIES { out.drain(..out.len() - MAX_ENTRIES); @@ -471,7 +503,9 @@ pub fn init(logs_dir: &Path, prior_len: Option) { st.log_path = Some(log_path.clone()); st.stamp_path = Some(stamp); } - if unclean { + // Nothing is read when uploads are off: the previous run's lines would + // only ever be read to send them. + if unclean && state().enabled { // The previous run's lines: daemon.log up to where it was before this // start, or the rotated file when opening rotated it away. let text = match prior_len { @@ -480,7 +514,10 @@ pub fn init(logs_dir: &Path, prior_len: Option) { } _ => tail(&logs_dir.join("daemon.log.1"), None, TAIL_BYTES), }; - let entries = text.as_deref().map(entries_from_text).unwrap_or_default(); + let entries = text + .as_deref() + .map(|t| entries_from_text(t, false)) + .unwrap_or_default(); let mut st = state(); maybe_open_incident( &mut st, @@ -537,7 +574,11 @@ impl Scrub { } } fn apply(&self, text: &str) -> String { - let mut out = text.to_string(); + // The collector's secret patterns first (keys, bearer headers, env + // assignments), the same rules session events get, then the machine's + // own token and home directory. + let mut out = fpai_collect::redact::scrub_str(text) + .map_or_else(|| text.to_string(), |(scrubbed, _)| scrubbed); if let Some(t) = &self.token { out = out.replace(t.as_str(), "[redacted]"); } @@ -632,7 +673,7 @@ fn ship_at(machine_id: &str, scrub: &Scrub, post: &dyn Fn(&Value) -> PostOutcome .as_deref() .and_then(|p| tail(p, None, TAIL_BYTES)); let entries = match text { - Some(t) => entries_from_text(&t), + Some(t) => entries_from_text(&t, true), None => st.ring.iter().map(|c| c.entry.clone()).collect(), }; let v = body(machine_id, "requested", None, Some(&id), &entries, scrub); @@ -1040,7 +1081,7 @@ mod tests { + &line("INFO", "a::b", "dated") + " at Module._load (node:internal)\n" + "2026-11-18T13:18:40.000000Z TRACE x: verbose\n"; - let entries = entries_from_text(&text); + let entries = entries_from_text(&text, true); let long = Scrub::new(None, Some("tok12345".into())); let mut e = entries.clone(); e.push(Entry { @@ -1072,6 +1113,110 @@ mod tests { assert_eq!(v["entries"][0]["ts"], "2026-11-18T13:18:37.676211Z"); } + /// A custom policy printed a tool command holding a credential: it must + /// never ride an automatic upload, and a requested one gets it redacted. + #[test] + fn child_output_stays_out_of_automatic_uploads_and_secrets_are_redacted() { + let _g = LOCK.lock().unwrap(); + reset_for_test(true); + let t0 = Instant::now(); + let secret = "curl -H 'Authorization: Bearer sk-live-0123456789abcdefABCDEF' https://x"; + record( + Level::WARN, + "failproofaid::worker", + &line( + "WARN", + "failproofaid::worker", + &format!("worker stderr: {secret}"), + ), + t0, + ); + record( + Level::ERROR, + "failproofaid::audit_lane", + &line( + "ERROR", + "failproofaid::audit_lane", + &format!("audit stdout: {secret}"), + ), + t0, + ); + record( + Level::WARN, + "a", + &line("WARN", "a", &format!("daemon saw {secret}")), + t0, + ); + let sent = collect(t0 + INCIDENT_SETTLE); + let all = serde_json::to_string(&sent).unwrap(); + assert!(!all.contains("sk-live-0123456789abcdefABCDEF"), "{all}"); + assert!( + !all.contains("worker stderr"), + "child output is not uploaded automatically: {all}" + ); + assert!( + sent.iter().all(|v| v["kind"] != "incident"), + "a child's ERROR line opens no incident" + ); + assert_eq!(sent[0]["entries"].as_array().unwrap().len(), 1); + + // Requested: the operator asked, so child output is included, redacted. + let dir = temp_dir("child"); + let log = dir.join("daemon.log"); + fs::write( + &log, + line( + "INFO", + "failproofaid::worker", + &format!("worker stderr: {secret}"), + ), + ) + .unwrap(); + state().log_path = Some(log); + note_request("req-child"); + let sent = collect(Instant::now()); + let req = sent.iter().find(|v| v["kind"] == "requested").unwrap(); + let msg = req["entries"][0]["message"].as_str().unwrap(); + assert!(msg.starts_with("worker stderr: "), "{msg}"); + assert!(!msg.contains("sk-live-0123456789abcdefABCDEF"), "{msg}"); + } + + /// A FIFO at daemon.log after an unclean exit must not stall startup, + /// with uploads on or off. + #[test] + fn a_fifo_at_the_log_path_never_blocks_init() { + let _g = LOCK.lock().unwrap(); + for disabled in [false, true] { + reset_for_test(true); + let dir = temp_dir(if disabled { "fifo-off" } else { "fifo-on" }); + let log = dir.join("daemon.log"); + let c = std::ffi::CString::new(log.as_os_str().as_encoded_bytes()).unwrap(); + assert_eq!(unsafe { libc::mkfifo(c.as_ptr(), 0o600) }, 0); + fs::write(dir.join(MARKER), "1").unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + let d = dir.clone(); + std::thread::spawn(move || { + // SAFETY: test-only; the env is read once inside `init`. + if disabled { + unsafe { std::env::set_var("FAILPROOFAI_NO_LOG_UPLOAD", "1") }; + } + init(&d, Some(10)); + if disabled { + unsafe { std::env::remove_var("FAILPROOFAI_NO_LOG_UPLOAD") }; + } + let _ = tx.send(()); + }); + assert!( + rx.recv_timeout(Duration::from_secs(3)).is_ok(), + "init blocked on a FIFO (uploads disabled: {disabled})" + ); + assert!( + tail(&log, None, TAIL_BYTES).is_none(), + "a FIFO is not a log" + ); + } + } + #[test] fn fingerprint_folds_numbers() { assert_eq!( diff --git a/crates/failproofaid/src/main.rs b/crates/failproofaid/src/main.rs index 3a5756305..8f24c841e 100644 --- a/crates/failproofaid/src/main.rs +++ b/crates/failproofaid/src/main.rs @@ -441,7 +441,24 @@ fn spawn_collector_manager( let interval = collector_config_poll_interval(); std::thread::Builder::new() .name("fpai-collect-mgr".to_string()) - .spawn(move || supervised("the collector manager", &daemon_shutdown, || { + .spawn(move || { + // Held OUTSIDE the supervised body, like the cloud lane's state: a + // panic unwinds the body, not these, so a restart still owns the + // deployments the last run started and stops them before anything new + // runs over the same queues and cursors. Dropped by the unwind, a + // handle mid-upload outlived its flush budget, detached, and kept + // running beside its replacement. + let mut collector_slot: Option = None; + let mut draining_slot: Option = None; + supervised("the collector manager", &daemon_shutdown, || { + let collector = &mut collector_slot; + let draining = &mut draining_slot; + let stop_budget = collector_stop_budget(); + // What a run before a panic left running. Waited for, however long + // its in-flight upload takes: nothing starts beside it. + if !stop_inherited_collectors(collector, draining, stop_budget, &daemon_shutdown) { + return; + } // Wait until collection is enabled. A cheap config read each tick, // not the full task build, so an incomplete config waits quietly // rather than logging on every interval. @@ -481,7 +498,7 @@ fn spawn_collector_manager( // flipped back to disabled between the check and the build, or the // runtime failed to start. let mut running_cfg = current_collector_config(); - let Some(collector) = + let Some(first) = fpai_collect::spawn_supervised(collector_tasks(running_cfg.clone()), daemon_shutdown.clone()) else { return; @@ -492,11 +509,11 @@ fn spawn_collector_manager( // no telemetry code enters `fpai-collect`, and a task quietly // restarting in a loop stops being invisible from outside the // machine. - telemetry::set_collector_metrics(collector.metrics()); + telemetry::set_collector_metrics(first.metrics()); // `Option` because `join_with_flush` CONSUMES the handle: the loop // has to be able to give a deployment away and hold nothing until it // has a replacement. - let mut collector = Some(collector); + *collector = Some(first); // The config this deployment was built from. Comparing the whole // `CollectorConfig` rather than just the credential is deliberate: // it also covers a stream being switched off, a verbosity change and @@ -508,11 +525,9 @@ fn spawn_collector_manager( // new starts over its queues, and no cursor is rewound under it, // until it has stopped. Giving up here used to end this thread and // with it all collection until the daemon restarted. - let mut draining: Option = None; // A backfill request already taken off disk while a deployment was // still draining. Applied once it has stopped, never dropped. let mut pending_backfill: Option = None; - let stop_budget = collector_stop_budget(); loop { if daemon_shutdown.load(Ordering::Relaxed) { @@ -533,7 +548,7 @@ fn spawn_collector_manager( match old.stop_within(Duration::from_millis(200)) { Ok(()) => tracing::info!("previous collector stopped; starting its replacement"), Err(still) => { - draining = Some(still); + *draining = Some(still); continue; } } @@ -550,7 +565,7 @@ fn spawn_collector_manager( && let Err(still) = running.stop_within(stop_budget) { tracing::warn!("previous collector is still draining; the new one starts once it stops"); - draining = Some(still); + *draining = Some(still); pending_backfill = Some(request); continue; } @@ -571,7 +586,7 @@ fn spawn_collector_manager( { Some(next_collector) => { telemetry::set_collector_metrics(next_collector.metrics()); - collector = Some(next_collector); + *collector = Some(next_collector); } None => tracing::warn!( "backfill rewound cursors but the collector could not be restarted" @@ -619,7 +634,7 @@ fn spawn_collector_manager( // Next ticks keep waiting for it; once it stops, the // compare above sees no collector and starts this config. tracing::warn!("previous collector is still draining; the new one starts once it stops"); - draining = Some(still); + *draining = Some(still); continue; } @@ -668,7 +683,7 @@ fn spawn_collector_manager( // slot left telemetry polling a collector that had been joined, // reporting a dead deployment's totals as current. telemetry::set_collector_metrics(next_collector.metrics()); - collector = Some(next_collector); + *collector = Some(next_collector); // What was BUILT FROM, not a fresh read. Re-reading here loses // any edit that landed between the spawn and this line: it would // be recorded as the running config and therefore never seen as @@ -683,13 +698,45 @@ fn spawn_collector_manager( if let Some(old) = draining.take() { old.join_with_flush(fpai_collect::DEFAULT_FLUSH_BUDGET); } - })) + }); + // Shut down while waiting on an inherited deployment: give it the same + // flush budget the normal exit path gives a running one. + for handle in [collector_slot.take(), draining_slot.take()].into_iter().flatten() { + handle.join_with_flush(fpai_collect::DEFAULT_FLUSH_BUDGET); + } + }) .inspect_err(|err| { tracing::warn!("could not start the collector manager: {err}; nothing is collected this run"); }) .ok() } +/// Stop the deployments a collector-manager run left behind when it panicked, +/// and wait until they HAVE stopped: a replacement started beside one that is +/// still uploading would claim the same spooled batches and rewrite the same +/// cursors. `false` when shutdown came first; the handle stays in `draining` +/// for the exit path to flush. +fn stop_inherited_collectors( + collector: &mut Option, + draining: &mut Option, + budget: Duration, + shutdown: &AtomicBool, +) -> bool { + while let Some(old) = collector.take().or_else(|| draining.take()) { + match old.stop_within(budget) { + Ok(()) => tracing::info!("the collector a restarted manager inherited has stopped"), + Err(still) => { + *draining = Some(still); + if shutdown.load(Ordering::Relaxed) { + return false; + } + std::thread::sleep(Duration::from_millis(200)); + } + } + } + true +} + /// Run a long-lived lane's body until it returns, starting it again after a /// panic. /// @@ -2301,6 +2348,66 @@ mod tests { }); assert_eq!(runs, 1); } + + /// F2: a manager that panics while its collector is mid-upload. The + /// handle lives outside the supervised body, so the restart owns it + /// and starts nothing until the old collector has really stopped. + #[test] + fn a_restart_waits_for_the_collector_a_panicked_run_left_uploading() { + use super::super::stop_inherited_collectors; + use fpai_collect::{CollectorHandle, TaskSpec, spawn_supervised}; + use std::sync::Arc; + + let daemon_shutdown = Arc::new(AtomicBool::new(false)); + let finished = Arc::new(AtomicBool::new(false)); + let mut collector: Option = None; + let mut draining: Option = None; + let mut runs = 0; + let mut old_was_done_at_restart = None; + supervised_with_backoff( + "collector manager", + &daemon_shutdown, + Duration::from_millis(1), + || { + runs += 1; + if runs == 1 { + let done = finished.clone(); + collector = spawn_supervised( + vec![TaskSpec::new("uploading", move |sd| { + let done = done.clone(); + async move { + while !sd.is_set() { + sd.sleep(Duration::from_millis(10)).await; + } + // An upload in flight outlasts the stop budget. + tokio::time::sleep(Duration::from_millis(600)).await; + done.store(true, Ordering::SeqCst); + Ok(()) + } + })], + daemon_shutdown.clone(), + ); + assert!(collector.is_some()); + std::thread::sleep(Duration::from_millis(50)); + panic!("manager bug after the collector started"); + } + assert!(stop_inherited_collectors( + &mut collector, + &mut draining, + Duration::from_millis(50), + &daemon_shutdown, + )); + old_was_done_at_restart = Some(finished.load(Ordering::SeqCst)); + assert!(collector.is_none() && draining.is_none()); + }, + ); + assert_eq!(runs, 2); + assert_eq!( + old_was_done_at_restart, + Some(true), + "the replacement may start only once the old collector has stopped" + ); + } } fn argv(rest: &[&str]) -> Vec { diff --git a/crates/failproofaid/tests/daemon_e2e.rs b/crates/failproofaid/tests/daemon_e2e.rs index b1648d691..2f0e95c17 100644 --- a/crates/failproofaid/tests/daemon_e2e.rs +++ b/crates/failproofaid/tests/daemon_e2e.rs @@ -383,3 +383,62 @@ fn real_binary_starts_against_a_home_with_no_marker() { drop(stream); daemon.terminate(); } + +/// An unclean previous exit (`logs/daemon.running` left behind) plus a FIFO +/// where `daemon.log` belongs: the daemon must still bind its socket, with +/// log uploads on or off. Reading the previous run's log opened that path +/// blocking and waited for a writer that never came, before the socket was +/// bound — every hook on the machine then went without a verdict. +#[test] +fn a_fifo_log_after_an_unclean_exit_does_not_stall_startup() { + use std::os::unix::fs::DirBuilderExt; + for disabled in [false, true] { + let socket_path = unique_socket_path(if disabled { "fifo-off" } else { "fifo-on" }); + let run_dir = socket_path.parent().unwrap(); + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(run_dir) + .unwrap(); + let logs = scratch_home(&socket_path).join("logs"); + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(&logs) + .unwrap(); + std::fs::write(logs.join("daemon.running"), "1").unwrap(); + let fifo = std::ffi::CString::new( + logs.join("daemon.log") + .into_os_string() + .into_encoded_bytes(), + ) + .unwrap(); + assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o600) }, 0); + + // `spawn_daemon` panics with the daemon's stderr if no socket appears. + // SAFETY: the variable is read by the child only. + if disabled { + unsafe { std::env::set_var("FAILPROOFAI_NO_LOG_UPLOAD", "1") }; + } + let mut daemon = spawn_daemon(&socket_path); + if disabled { + unsafe { std::env::remove_var("FAILPROOFAI_NO_LOG_UPLOAD") }; + } + let mut stream = UnixStream::connect(&socket_path).expect("connect"); + write_message( + &mut stream, + &ClientMessage::Ping { + protocol_version: PROTOCOL_VERSION, + }, + ) + .unwrap(); + let response: ServerMessage = read_message(&mut stream).unwrap(); + assert_eq!( + response, + ServerMessage::Pong { + protocol_version: PROTOCOL_VERSION + } + ); + assert!(daemon.terminate().success()); + } +} diff --git a/hermes-plugin/client.py b/hermes-plugin/client.py index 68df84eb4..90b781ab6 100644 --- a/hermes-plugin/client.py +++ b/hermes-plugin/client.py @@ -178,6 +178,10 @@ def build(version: int) -> bytes: ): version = answered response = _exchange(build(version), connect_timeout_ms, deadline) + # Asked again after the answer: a targeted deployment activated while + # the older daemon was evaluating makes its answer unsafe too. + if _agent_targeted_deployment(): + raise EvaluationError("failproofai protocol version mismatch") if not isinstance(response, dict): raise EvaluationError("failproofaid returned a non-object response") diff --git a/openclaw-plugin/daemon-client.js b/openclaw-plugin/daemon-client.js index f0ab6ab27..2b0d54d71 100644 --- a/openclaw-plugin/daemon-client.js +++ b/openclaw-plugin/daemon-client.js @@ -211,6 +211,12 @@ export async function requestHookVerdict(request) { return first; } const retried = await requestWithRetry(older, request, clock); + // Asked again after the answer: a targeted deployment activated while the + // older daemon was evaluating makes its answer unsafe too. + if (await agentTargetedDeployment()) { + delete first.daemonVersion; + return first; + } if (!retried.ok) delete retried.daemonVersion; return retried; } diff --git a/src/hooks/daemon-client.ts b/src/hooks/daemon-client.ts index 825143dde..ac2c80365 100644 --- a/src/hooks/daemon-client.ts +++ b/src/hooks/daemon-client.ts @@ -230,7 +230,12 @@ async function attemptDaemonRequest( ) { return withoutDaemonVersion(first); } - return withoutDaemonVersion(await attemptDaemonRequestAt(older, build, opts)); + const retried = await attemptDaemonRequestAt(older, build, opts); + // Asked again AFTER the answer: Cloud may have activated a targeted + // deployment while the older daemon was evaluating, and then its answer + // (made without this agent) is no safer than if it had been asked then. + if (cloudDeploymentMayTargetAgents()) return withoutDaemonVersion(first); + return withoutDaemonVersion(retried); } function withoutDaemonVersion(attempt: DaemonWireAttempt): DaemonWireAttempt { From 7822d6c6e17fda41ffc93f36912306661935084b Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 19 Nov 2026 00:44:40 +0530 Subject: [PATCH 19/41] docs(changelog): the end-to-end and review-round-4 fixes on #1023 --- CHANGELOG.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ec46ec4ec..9a6ba48f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,10 @@ - failproofaid writes its log to `~/.failproofai/logs/daemon.log` on every OS (owner-only, 10 MB, 3 kept), as well as to stderr as before (on macOS stderr keeps only warnings and errors, since launchd's file is never rotated); every line carries a timestamp and level (its untimestamped `[failproofaid]` lines are now `tracing` events), and on macOS launchd's `failproofaid.err.log`, which nothing rotated, is bounded at startup (#1023) - failproofaid tells FailproofAI Cloud what each machine runs: its policy poll carries `daemonVersion`, `cliVersion`, `os` and `arch` (optional parameters a server that predates them ignores), and every Cloud and ingest request sends `User-Agent: failproofaid/` (#1023) - Hook events carry the agent's own `tool_call_id` (Claude, Devin, Factory, Pi, Hermes), the field the transcript events already use and Cloud stores in its own column, so a hook joins the tool call it governed instead of being placed beside it by timestamp; and a hook's start is stamped when it arrived, not when its evaluation ended. Rows written before this convert exactly as before (#1023) -- failproofaid sends its log to FailproofAI Cloud only when something is wrong: one roll-up of distinct warnings and errors (repeats counted, at most every 5 minutes), the last 5 minutes of log around an error or after a run that ended without a clean shutdown (at most one per 15 minutes), and the log tail when an operator asks for it from Cloud; the home directory and the machine token are scrubbed, a server without the route is left alone for a day, and `FAILPROOFAI_NO_LOG_UPLOAD=1` turns it off (#1023) +- failproofaid sends its log to FailproofAI Cloud only when something is wrong: one roll-up of distinct warnings and errors (repeats counted, at most every 5 minutes), the last 5 minutes of log around an error or after a run that ended without a clean shutdown (at most one per 15 minutes), and the log tail when an operator asks for it from Cloud; secrets are redacted with the collector's rules and the home directory and machine token scrubbed, worker and audit output is sent only when an operator asks, a server without the route is left alone for a day, and `FAILPROOFAI_NO_LOG_UPLOAD=1` turns it off (#1023) +- Batches an outage parked are retried as soon as the server accepts a batch again (or, on an idle machine, within one 5-minute probe) instead of at the hourly pass, and `config --status` counts them as queued rather than "nothing queued" (#1023) +- Allow roll-ups (the default `decisions` verbosity) are stamped when their first hook arrived instead of at the top of their minute, which put them before the tool calls they covered, and name the `tool_call_ids` they cover (#1023) +- Setup's summary on a Cloud-managed machine says "Deploy from Cloud" instead of pointing at installing a pack (#1023) ## 1.0.15 — 2026-11-18 From 9d98cec9b162241ce9ae373c873a88bfd2753fb6 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 19 Nov 2026 02:33:40 +0530 Subject: [PATCH 20/41] fix: review round 5 on #1023 (FIFO marker, legacy roll-ups, backlog drain) - The run marker and incident stamp are written to a fresh temporary file and renamed over the path, so a FIFO (or link) at logs/daemon.running can no longer block startup before the socket is bound. The real-daemon regression now covers a FIFO at the marker as well as at daemon.log, uploads on and off. - An allow roll-up holding any row written before `startedAt` existed keeps the minute stamp it always had, so re-reading old rows (a backfill, a lost cursor) reproduces the shipped bytes and the server's dedup collapses them. Only roll-ups of new-format rows take the first arrival. - A backlog larger than one capped recovery pass keeps draining, one pass every 10 s while deliveries succeed, instead of leaving the rest for the hourly pass. --- crates/failproofaid/src/logship.rs | 38 +++++--- crates/failproofaid/tests/daemon_e2e.rs | 31 ++++--- crates/fpai-collect/src/delivery.rs | 90 +++++++++++++++++-- crates/fpai-collect/src/sources/hooks/mod.rs | 1 + .../src/sources/hooks/transform.rs | 9 +- crates/fpai-collect/tests/hooks_source.rs | 36 ++++++++ 6 files changed, 174 insertions(+), 31 deletions(-) diff --git a/crates/failproofaid/src/logship.rs b/crates/failproofaid/src/logship.rs index 63bd736bb..e2c1d92db 100644 --- a/crates/failproofaid/src/logship.rs +++ b/crates/failproofaid/src/logship.rs @@ -464,20 +464,34 @@ fn entries_from_text(text: &str, with_child_output: bool) -> Vec { out } -/// Owner-only, like `daemon.log` beside it. +/// Owner-only, like `daemon.log` beside it, and never through whatever is +/// at `path` now: written to a fresh temporary file and renamed over it. A +/// FIFO there would block an open for writing (before the socket is bound, +/// so every hook goes without a verdict), and a symlink would redirect it. fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> { use std::os::unix::fs::OpenOptionsExt; - let mut file = fs::OpenOptions::new() - .write(true) - .create(true) - .truncate(true) - .mode(0o600) - .custom_flags(libc::O_NOFOLLOW) - .open(path)?; - file.write_all(bytes)?; - // A file an older build left at 0644 keeps its mode on open. - use std::os::unix::fs::PermissionsExt; - file.set_permissions(fs::Permissions::from_mode(0o600)) + let Some(name) = path.file_name() else { + return Err(std::io::Error::other("no file name")); + }; + let mut tmp_name = std::ffi::OsString::from("."); + tmp_name.push(name); + tmp_name.push(format!(".{}.tmp", std::process::id())); + let tmp = path.with_file_name(tmp_name); + let _ = fs::remove_file(&tmp); + let written = (|| { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(&tmp)?; + file.write_all(bytes)?; + fs::rename(&tmp, path) + })(); + if written.is_err() { + let _ = fs::remove_file(&tmp); + } + written } /// Size of `daemon.log` before this process writes to it. Call before the log diff --git a/crates/failproofaid/tests/daemon_e2e.rs b/crates/failproofaid/tests/daemon_e2e.rs index 2f0e95c17..67eba1017 100644 --- a/crates/failproofaid/tests/daemon_e2e.rs +++ b/crates/failproofaid/tests/daemon_e2e.rs @@ -385,15 +385,25 @@ fn real_binary_starts_against_a_home_with_no_marker() { } /// An unclean previous exit (`logs/daemon.running` left behind) plus a FIFO -/// where `daemon.log` belongs: the daemon must still bind its socket, with -/// log uploads on or off. Reading the previous run's log opened that path +/// where `daemon.log` belongs, or a FIFO at the run marker itself: the daemon +/// must still bind its socket, with log uploads on or off. Reading the previous run's log opened that path /// blocking and waited for a writer that never came, before the socket was /// bound — every hook on the machine then went without a verdict. #[test] fn a_fifo_log_after_an_unclean_exit_does_not_stall_startup() { use std::os::unix::fs::DirBuilderExt; - for disabled in [false, true] { - let socket_path = unique_socket_path(if disabled { "fifo-off" } else { "fifo-on" }); + // The FIFO at the log path, then at the run marker itself. + for (fifo_name, disabled) in [ + ("daemon.log", false), + ("daemon.log", true), + ("daemon.running", false), + ("daemon.running", true), + ] { + let socket_path = unique_socket_path(&format!( + "fifo-{}-{}", + fifo_name.replace('.', "-"), + if disabled { "off" } else { "on" } + )); let run_dir = socket_path.parent().unwrap(); std::fs::DirBuilder::new() .recursive(true) @@ -406,13 +416,12 @@ fn a_fifo_log_after_an_unclean_exit_does_not_stall_startup() { .mode(0o700) .create(&logs) .unwrap(); - std::fs::write(logs.join("daemon.running"), "1").unwrap(); - let fifo = std::ffi::CString::new( - logs.join("daemon.log") - .into_os_string() - .into_encoded_bytes(), - ) - .unwrap(); + if fifo_name != "daemon.running" { + std::fs::write(logs.join("daemon.running"), "1").unwrap(); + } + let fifo = + std::ffi::CString::new(logs.join(fifo_name).into_os_string().into_encoded_bytes()) + .unwrap(); assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o600) }, 0); // `spawn_daemon` panics with the daemon's stderr if no socket appears. diff --git a/crates/fpai-collect/src/delivery.rs b/crates/fpai-collect/src/delivery.rs index 66bd599a4..20324eb73 100644 --- a/crates/fpai-collect/src/delivery.rs +++ b/crates/fpai-collect/src/delivery.rs @@ -75,6 +75,10 @@ const FAILED_RETRY_MAX_FILES: usize = 16; /// Minimum gap between two "the server is back" retries of parked batches, so /// a flapping connection cannot turn every accepted upload into a pass. const RECOVERY_RETRY_GAP: Duration = Duration::from_secs(300); +/// Between two recovery passes while a backlog remains: each pass is capped at +/// FAILED_RETRY_MAX_FILES, and a larger backlog drains in steps rather than +/// waiting for the hourly pass, without one long burst starving fresh events. +const RECOVERY_BACKLOG_GAP: Duration = Duration::from_secs(10); /// At most one refused batch after a fresh delivery, so the serial watcher /// and sweeper return to fresh work instead of draining a credential backlog. const REFUSED_REDRIVE_MAX_FILES: usize = 1; @@ -428,6 +432,7 @@ pub async fn sweep( let mut next_failed_pass = SystemTime::now(); let mut next_recovery_pass = SystemTime::now(); let mut next_probe = SystemTime::now(); + let mut backlog = false; let mut replays = tokio::task::JoinSet::new(); loop { @@ -476,10 +481,26 @@ pub async fn sweep( // The server accepted a batch after an outage: retry what the // outage parked now, not at the next hourly pass, with no minimum // age (the failure that parked them is over). - if SystemTime::now() >= next_recovery_pass && delivery.take_recovered() { - retry_parked(&delivery, &failed_dir, &sd, Duration::ZERO).await; + // + // A backlog larger than one pass keeps draining, one capped pass + // every RECOVERY_BACKLOG_GAP, for as long as deliveries succeed. + if SystemTime::now() >= next_recovery_pass && (backlog || delivery.take_recovered()) { + let left = retry_parked_up_to( + &delivery, + &failed_dir, + &sd, + Duration::ZERO, + FAILED_RETRY_MAX_FILES, + ) + .await; delivery.schedule_refused(&mut replays, &sd); - next_recovery_pass = SystemTime::now() + RECOVERY_RETRY_GAP; + backlog = left > 0 && !delivery.failing.load(Ordering::SeqCst); + next_recovery_pass = SystemTime::now() + + if backlog { + RECOVERY_BACKLOG_GAP + } else { + RECOVERY_RETRY_GAP + }; } // An idle machine sends nothing fresh to notice the server is back: // while the last delivery failed, one parked batch goes as a probe @@ -554,15 +575,17 @@ async fn retry_parked(delivery: &Delivery, failed_dir: &Path, sd: &Shutdown, min retry_parked_up_to(delivery, failed_dir, sd, min_age, FAILED_RETRY_MAX_FILES).await; } +/// Retry up to `max` parked batches, oldest first. Returns how many eligible +/// batches were left untried. async fn retry_parked_up_to( delivery: &Delivery, failed_dir: &Path, sd: &Shutdown, min_age: Duration, max: usize, -) { +) -> usize { let Ok(mut rd) = tokio::fs::read_dir(failed_dir).await else { - return; + return 0; }; let now = SystemTime::now(); let mut found: Vec<(SystemTime, PathBuf)> = Vec::new(); @@ -588,17 +611,19 @@ async fn retry_parked_up_to( } if found.is_empty() { - return; + return 0; } found.sort_by_key(|(t, _)| *t); tracing::info!(count = found.len().min(max), "retrying parked batches"); + let left = found.len().saturating_sub(max); for (_, path) in found.into_iter().take(max) { if sd.is_set() { - return; + return left; } delivery.deliver(path).await; } + left } /// Resolves once shutdown is requested. A `select!` arm needs a future, and @@ -720,6 +745,57 @@ mod tests { std::fs::remove_dir_all(spool).ok(); } + /// More parked than one capped pass: the rest keep draining while + /// deliveries succeed, instead of waiting for the hourly pass. + #[tokio::test(flavor = "multi_thread")] + async fn a_backlog_larger_than_one_pass_drains_after_recovery() { + use wiremock::matchers::method; + use wiremock::{Mock, MockServer, ResponseTemplate}; + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(serde_json::json!({"accepted": 1, "skipped": 0})), + ) + .mount(&server) + .await; + let failed = tmpdir("backlog-failed"); + let spool = tmpdir("backlog-spool"); + let total = FAILED_RETRY_MAX_FILES + 9; + for i in 0..total { + std::fs::write( + failed.join(format!("hooks-activity-{i}-0.a1.jsonl")), + "{}\n", + ) + .unwrap(); + } + let delivery = Arc::new(Delivery::new(Arc::new( + Uploader::new(server.uri(), "k".into(), failed.clone()).unwrap(), + ))); + let flag = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let sweeper = tokio::spawn(sweep( + delivery.clone(), + vec![spool.clone()], + failed.clone(), + Shutdown::for_test(flag.clone()), + Arc::new(std::sync::atomic::AtomicBool::new(false)), + )); + let left = || std::fs::read_dir(&failed).map(|d| d.count()).unwrap_or(0); + let deadline = std::time::Instant::now() + RECOVERY_BACKLOG_GAP * 3; + while left() > 0 && std::time::Instant::now() < deadline { + tokio::time::sleep(Duration::from_millis(200)).await; + } + assert_eq!( + left(), + 0, + "the whole backlog drains once the server is back" + ); + flag.store(true, Ordering::SeqCst); + let _ = tokio::time::timeout(Duration::from_secs(5), sweeper).await; + std::fs::remove_dir_all(failed).ok(); + std::fs::remove_dir_all(spool).ok(); + } + #[tokio::test] async fn a_refusal_the_current_key_repeats_is_reparked_and_others_are_kept() { use wiremock::matchers::{body_string, method}; diff --git a/crates/fpai-collect/src/sources/hooks/mod.rs b/crates/fpai-collect/src/sources/hooks/mod.rs index 0356133bd..8761513ef 100644 --- a/crates/fpai-collect/src/sources/hooks/mod.rs +++ b/crates/fpai-collect/src/sources/hooks/mod.rs @@ -261,6 +261,7 @@ async fn poll_once( tool_name: key.2.clone(), minute_ms: key.3, first_ms: i64::MAX, + all_started: true, tool_call_ids: Vec::new(), count: 0, total_duration_ms: 0.0, diff --git a/crates/fpai-collect/src/sources/hooks/transform.rs b/crates/fpai-collect/src/sources/hooks/transform.rs index 2afd9741f..357764b97 100644 --- a/crates/fpai-collect/src/sources/hooks/transform.rs +++ b/crates/fpai-collect/src/sources/hooks/transform.rs @@ -986,6 +986,12 @@ pub struct AllowBucket { /// the emitted timestamp. Stamping the minute instead put every roll-up /// before the tool calls it covered. `i64::MAX` until a row is added. pub first_ms: i64, + /// Every row so far recorded `startedAt` (written by a CLI that knows it). + /// Only then is the bucket stamped at `first_ms`: a bucket holding a row + /// from before keeps the minute stamp it always had, so re-reading old + /// rows (a backfill, a lost cursor) produces the bytes already shipped + /// and the server's dedup still collapses them. + pub all_started: bool, /// The agent's tool-call ids the bucket covers, in arrival order, at most /// [`MAX_BUCKET_TOOL_CALL_IDS`], so Cloud can join a roll-up to its calls. pub tool_call_ids: Vec, @@ -1032,6 +1038,7 @@ pub const MAX_BUCKET_TOOL_CALL_IDS: usize = 64; impl AllowBucket { pub fn add(&mut self, row: &HookRow) { self.count += 1; + self.all_started &= row.started_at.is_some(); let arrived = row .started_at .filter(|at| *at <= row.timestamp) @@ -1064,7 +1071,7 @@ impl AllowBucket { /// report a duration that belongs to no real hook call. pub fn to_event(&self, environment: &str) -> Option { let mut m = Map::new(); - let at = if self.first_ms == i64::MAX { + let at = if self.first_ms == i64::MAX || !self.all_started { self.minute_ms } else { self.first_ms diff --git a/crates/fpai-collect/tests/hooks_source.rs b/crates/fpai-collect/tests/hooks_source.rs index 7454ef90f..f33638863 100644 --- a/crates/fpai-collect/tests/hooks_source.rs +++ b/crates/fpai-collect/tests/hooks_source.rs @@ -370,6 +370,42 @@ async fn an_allow_rollup_is_stamped_at_its_first_hook_and_names_its_calls() { fs::remove_dir_all(&spool).ok(); } +/// Rows written before `startedAt` existed roll up exactly as they always +/// did: stamped at the top of their minute, byte for byte. A backfill or a +/// lost cursor re-reads them, and the server dedups on what was shipped. +#[tokio::test(flavor = "multi_thread")] +async fn a_legacy_allow_rollup_keeps_its_minute_stamp() { + let store = tmpdir("agg-legacy-store"); + let state = tmpdir("agg-legacy-state"); + let spool = tmpdir("agg-legacy-spool"); + let minute = 1785740940000; + let mut lines: Vec = (0..3) + .map(|i| allow_row(minute + 2000 + i * 100, "Bash")) + .collect(); + // One new-format row in the same bucket does not restamp the old ones. + lines.push(allow_row_with( + minute + 9000, + minute + 8900, + "Bash", + "PreToolUse", + Some("toolu_new"), + )); + fs::write(store.join("current.jsonl"), lines.join("\n") + "\n").unwrap(); + + run_once(&store, &state, &spool, HooksVerbosity::Decisions).await; + let events = spooled(&spool); + let agg = events + .iter() + .find(|e| e["outcome"] == "allow") + .expect("a roll-up"); + assert_eq!(agg["failproofai_allow_count"], 4); + assert_eq!(agg["timestamp"], "2026-08-03T07:09:00.000000Z"); + + fs::remove_dir_all(&store).ok(); + fs::remove_dir_all(&state).ok(); + fs::remove_dir_all(&spool).ok(); +} + #[tokio::test(flavor = "multi_thread")] async fn all_verbosity_emits_a_pair_for_every_row() { let store = tmpdir("all-store"); From 3a117fb8cae744b2651dbe68439df829a608cb03 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 19 Nov 2026 11:43:52 +0530 Subject: [PATCH 21/41] fix: OpenClaw hooks name their tool call; a long outage reads as stuck Found driving a real install (Hermes + OpenClaw gateways against a local Cloud): - The OpenClaw plugin never forwarded OpenClaw's toolCallId (on the before/after_tool_call event and the tool context), so every OpenClaw check reached Cloud with no tool_call_id and could only be placed by timestamp. It now sends it as tool_use_id, which the handler already reads. Verified live: each check carries its call's id, the deny too. - config --status counted outage-parked batches as queued but its stuck check looked at the spool only. An outage moves the spool into failed/ batch by batch, so the spool always looked young and a multi-hour outage read "Healthy, N batches queued". Parked batches' age now counts. --- CHANGELOG.md | 4 ++-- __tests__/hooks/config-status.test.ts | 14 ++++++++++++++ __tests__/hooks/openclaw-plugin.test.ts | 11 +++++++++++ openclaw-plugin/hooks.js | 12 ++++++++++++ src/hooks/config-status.ts | 16 ++++++++++++---- 5 files changed, 51 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a6ba48f0..3d564cd0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,9 +17,9 @@ - A hook client that stopped waiting before its verdict was ready is logged as that, with how long the evaluation took, instead of macOS's bare "Invalid argument (os error 22)" (#1023) - failproofaid writes its log to `~/.failproofai/logs/daemon.log` on every OS (owner-only, 10 MB, 3 kept), as well as to stderr as before (on macOS stderr keeps only warnings and errors, since launchd's file is never rotated); every line carries a timestamp and level (its untimestamped `[failproofaid]` lines are now `tracing` events), and on macOS launchd's `failproofaid.err.log`, which nothing rotated, is bounded at startup (#1023) - failproofaid tells FailproofAI Cloud what each machine runs: its policy poll carries `daemonVersion`, `cliVersion`, `os` and `arch` (optional parameters a server that predates them ignores), and every Cloud and ingest request sends `User-Agent: failproofaid/` (#1023) -- Hook events carry the agent's own `tool_call_id` (Claude, Devin, Factory, Pi, Hermes), the field the transcript events already use and Cloud stores in its own column, so a hook joins the tool call it governed instead of being placed beside it by timestamp; and a hook's start is stamped when it arrived, not when its evaluation ended. Rows written before this convert exactly as before (#1023) +- Hook events carry the agent's own `tool_call_id` (Claude, Devin, Factory, Pi, Hermes, OpenClaw), the field the transcript events already use and Cloud stores in its own column, so a hook joins the tool call it governed instead of being placed beside it by timestamp; and a hook's start is stamped when it arrived, not when its evaluation ended. Rows written before this convert exactly as before (#1023) - failproofaid sends its log to FailproofAI Cloud only when something is wrong: one roll-up of distinct warnings and errors (repeats counted, at most every 5 minutes), the last 5 minutes of log around an error or after a run that ended without a clean shutdown (at most one per 15 minutes), and the log tail when an operator asks for it from Cloud; secrets are redacted with the collector's rules and the home directory and machine token scrubbed, worker and audit output is sent only when an operator asks, a server without the route is left alone for a day, and `FAILPROOFAI_NO_LOG_UPLOAD=1` turns it off (#1023) -- Batches an outage parked are retried as soon as the server accepts a batch again (or, on an idle machine, within one 5-minute probe) instead of at the hourly pass, and `config --status` counts them as queued rather than "nothing queued" (#1023) +- Batches an outage parked are retried as soon as the server accepts a batch again (or, on an idle machine, within one 5-minute probe) instead of at the hourly pass, and `config --status` counts them as queued rather than "nothing queued" ; a long outage reads as stuck ("N batches queued, oldest …, last delivered …") instead of "Healthy", since its batches sit in the parked queue rather than the spool (#1023) - Allow roll-ups (the default `decisions` verbosity) are stamped when their first hook arrived instead of at the top of their minute, which put them before the tool calls they covered, and name the `tool_call_ids` they cover (#1023) - Setup's summary on a Cloud-managed machine says "Deploy from Cloud" instead of pointing at installing a pack (#1023) diff --git a/__tests__/hooks/config-status.test.ts b/__tests__/hooks/config-status.test.ts index 1079cd08d..ad03ef6dc 100644 --- a/__tests__/hooks/config-status.test.ts +++ b/__tests__/hooks/config-status.test.ts @@ -301,6 +301,20 @@ describe("config --status — delivery", () => { expect(deliveryRow({ refused: parked })).toBe("● Healthy, last event 12s ago, 2 batches queued"); }); + it("calls a long outage stuck even when the spool keeps moving into failed/", () => { + // Every spool batch is young (just written, then parked), but the parked + // ones are 2h old and nothing has been accepted since. + const parked = { ...facts().delivery!.refused, total: 40, retrying: 40, oldestAgeMs: 2 * 3_600_000 }; + const down = { ...health, lastOkAt: NOW - 2 * 3_600_000 }; + expect(deliveryRow({ queued: 3, oldestQueuedMs: 10_000, refused: parked, health: down })).toBe( + "▲ 43 batches queued, oldest 2h, last delivered 2h ago", + ); + // The same backlog while uploads succeed is draining, not stuck. + expect(deliveryRow({ queued: 3, oldestQueuedMs: 10_000, refused: parked })).toBe( + "● Healthy, last event 12s ago, 43 batches queued", + ); + }); + it("puts refused batches in the row, with their status and age", () => { const refused = { total: 26, rejected: 26, credentialRejected: 26, resending: 0, byStatus: { 401: 26 }, oldestAgeMs: 134 * 60_000 }; expect(deliveryRow({ refused })).toBe("▲ 26 batches refused (401), oldest 2h14m"); diff --git a/__tests__/hooks/openclaw-plugin.test.ts b/__tests__/hooks/openclaw-plugin.test.ts index 59c0cf3fe..ef04f99df 100644 --- a/__tests__/hooks/openclaw-plugin.test.ts +++ b/__tests__/hooks/openclaw-plugin.test.ts @@ -531,6 +531,17 @@ describe("openclaw-plugin hooks", () => { ); }); + it("names the tool call it checks, from the event or the tool context", async () => { + const { api, handlers } = fakeApi(); + const evaluate = vi.fn(async () => ({ ok: true, verdict: { permission: "allow" } })); + registerFailproofaiHooks(api, { evaluate }); + await handlers.get("before_tool_call")!({ ...toolCall, toolCallId: "call_evt" }, { ...ctx, toolCallId: "call_ctx" }); + await handlers.get("after_tool_call")!({ ...toolCall, result: "ok" }, { ...ctx, toolCallId: "call_ctx" }); + await handlers.get("before_tool_call")!(toolCall, ctx); + const sent = evaluate.mock.calls.map((call) => (call as unknown as [string, Record])[1].tool_use_id); + expect(sent).toEqual(["call_evt", "call_ctx", undefined]); + }); + it("maps a deny to each gate's native shape", async () => { const { api, handlers } = fakeApi(); registerFailproofaiHooks(api, { diff --git a/openclaw-plugin/hooks.js b/openclaw-plugin/hooks.js index 8330b0b92..f4aa23dc4 100644 --- a/openclaw-plugin/hooks.js +++ b/openclaw-plugin/hooks.js @@ -34,6 +34,17 @@ const OBSERVATION_EVENTS = [ const HOOK_OPTIONS = { priority: 100, timeoutMs: 60_000 }; +/** OpenClaw's id for the tool call a hook is about (on the event and the tool + * context of before/after_tool_call), the id its transcript records the call + * under. Sent as `tool_use_id` so the check joins that call in Cloud instead + * of sitting beside it by timestamp alone. */ +function toolCallIdOf(p, c) { + for (const id of [p.toolCallId, c.toolCallId]) { + if (typeof id === "string" && id.length > 0) return id; + } + return undefined; +} + /** Claude-shaped stdin base. Extra keys are ignored by the evaluator's payload * parser; they're forwarded for activity attribution. */ function baseMeta(payload, ctx, config, workspace) { @@ -41,6 +52,7 @@ function baseMeta(payload, ctx, config, workspace) { const c = ctx || {}; return { session_id: c.sessionId ?? p.sessionId ?? c.sessionKey ?? p.sessionKey, + tool_use_id: toolCallIdOf(p, c), cwd: workspace.resolveWorkspace(p, c, config) ?? process.cwd(), transcript_path: p.transcriptPath, stop_hook_active: p.stopHookActive === true, diff --git a/src/hooks/config-status.ts b/src/hooks/config-status.ts index 2e129b102..c5f4621b6 100644 --- a/src/hooks/config-status.ts +++ b/src/hooks/config-status.ts @@ -532,15 +532,23 @@ export function renderStatusScreen(facts: StatusFacts, opts: ScreenKitOpts & { c // Batches an earlier key had refused wait for the daemon to re-send them // with the key that works now: queued, not refused. // So do batches an outage parked: the daemon retries them itself. - const pending = queued + (refused.resending ?? 0) + (refused.retrying ?? 0); + const retrying = refused.retrying ?? 0; + const pending = queued + (refused.resending ?? 0) + retrying; const backlog = pending === 0 ? "nothing queued" : `${many(pending, "batch", "batches")} queued`; + // A long outage moves the spool into `failed/` batch by batch, so the spool + // alone always looks young: the parked batches' age counts too. + const waiting = queued + retrying; + const oldestWaitingMs = Math.max( + queued > 0 ? (oldestQueuedMs ?? 0) : 0, + retrying > 0 ? (refused.oldestAgeMs ?? 0) : 0, + ); const stuck = - queued > 0 && - (oldestQueuedMs ?? 0) > STATUS_QUEUE_STUCK_MS && + waiting > 0 && + oldestWaitingMs > STATUS_QUEUE_STUCK_MS && (health.lastOkAt === undefined || now - health.lastOkAt > STATUS_QUEUE_STUCK_MS); if (stuck) { const last = health.lastOkAt !== undefined ? `last delivered ${ago(health.lastOkAt)}` : "nothing delivered since failproofaid started"; - return kit.caution(`${many(queued, "batch", "batches")} queued, oldest ${formatDuration(oldestQueuedMs ?? 0)}, ${last}`); + return kit.caution(`${many(waiting, "batch", "batches")} queued, oldest ${formatDuration(oldestWaitingMs)}, ${last}`); } const lastEvent = health.lastEventAt !== undefined ? `last event ${ago(health.lastEventAt)}` : "no events since failproofaid started"; return `${kit.on} Healthy, ${lastEvent}, ${backlog}`; From f5e0844f64d4a100a76536d980d858817ed41be9 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 19 Nov 2026 12:10:43 +0530 Subject: [PATCH 22/41] feat(config): the first setup on a new version finishes the upgrade `failproofai update` migrated Hermes profiles and restarted running, service-managed Hermes and OpenClaw gateways so they load the plugin now on disk; `failproofai config` did neither. A gateway already running when setup enabled the plugin (fresh install) or after `npm i -g` (upgrade) kept the plugin it had loaded, or none, until someone ran `update`. update's steps move to src/hooks/update-run.ts. `config`, after a setup that applied, runs them when this CLI version has not finished them here yet (state/updated-version, written by both commands): no layout step (the CLI entry already migrated) and no daemon step (setup already brought it to this version). A repeat `config` on the same version touches nothing. Verified on a real machine: first config after installing a new build restarted both gateways and printed the same rows update does; a second config left them alone; both agents still enforce afterwards. --- CHANGELOG.md | 1 + __tests__/hooks/update-run.test.ts | 126 +++++++++++++++++++ bin/failproofai.mjs | 144 ++++++--------------- src/hooks/fp-home.ts | 8 ++ src/hooks/update-run.ts | 196 +++++++++++++++++++++++++++++ 5 files changed, 368 insertions(+), 107 deletions(-) create mode 100644 __tests__/hooks/update-run.test.ts create mode 100644 src/hooks/update-run.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d564cd0f..462d6bb92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ - Batches an outage parked are retried as soon as the server accepts a batch again (or, on an idle machine, within one 5-minute probe) instead of at the hourly pass, and `config --status` counts them as queued rather than "nothing queued" ; a long outage reads as stuck ("N batches queued, oldest …, last delivered …") instead of "Healthy", since its batches sit in the parked queue rather than the spool (#1023) - Allow roll-ups (the default `decisions` verbosity) are stamped when their first hook arrived instead of at the top of their minute, which put them before the tool calls they covered, and name the `tool_call_ids` they cover (#1023) - Setup's summary on a Cloud-managed machine says "Deploy from Cloud" instead of pointing at installing a pack (#1023) +- The first `failproofai config` on a new version (a fresh install, or the first after `npm i -g failproofai`) finishes the upgrade the way `failproofai update` does: it migrates Hermes profiles and restarts running, service-managed Hermes and OpenClaw gateways so they load the plugin now on disk. Setup used to leave a gateway that was already running on the plugin it loaded before, or with none, until someone ran `update` (#1023) ## 1.0.15 — 2026-11-18 diff --git a/__tests__/hooks/update-run.test.ts b/__tests__/hooks/update-run.test.ts new file mode 100644 index 000000000..6e219a1e1 --- /dev/null +++ b/__tests__/hooks/update-run.test.ts @@ -0,0 +1,126 @@ +/** + * The upgrade steps `update` runs, shared with `config`: the first setup on a + * new version restarts running gateways so they load the plugin now on disk, + * 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 { tmpdir } from "node:os"; +import { join } from "node:path"; + +const svc = vi.hoisted(() => ({ + isDaemonSupportedPlatform: vi.fn(() => true), + daemonServiceStatus: vi.fn(() => "running"), + refreshDaemonToCliVersion: vi.fn(async () => ({ ok: true, lines: ["failproofaid 1.0.0 is already installed and running; nothing to update."] })), + probeDaemonPolicyEvaluation: vi.fn(async () => true), +})); +const hermes = vi.hoisted(() => ({ runHermesUpdateMigration: vi.fn() })); +const gateways = vi.hoisted(() => ({ + restartHermesGateway: vi.fn(() => ({ host: "hermes", profile: "default", status: "restarting" })), + restartOpenClawGateways: vi.fn(() => [] as unknown[]), + openclawRestartLines: vi.fn((r: unknown[]) => (r.length > 0 ? ["OpenClaw:", " openclaw/default gateway restarting"] : [])), +})); +vi.mock("../../src/hooks/daemon-service", () => svc); +vi.mock("../../src/hooks/hermes-update", () => hermes); +vi.mock("../../src/hooks/gateway-restart", () => gateways); + +import { markUpdated, readUpdatedVersion, runUpdateSteps, setupNeedsUpdateSteps } from "../../src/hooks/update-run"; + +/** Hermes as `runHermesUpdateMigration` reports it, calling the restart it was handed. */ +function hermesWith(status: "current" | "migrated" | "untouched") { + hermes.runHermesUpdateMigration.mockImplementation(async (deps: { restartGateway?: (p: unknown) => { status: string } }) => { + if (status === "untouched") return { ok: true, lines: [], profiles: [{ name: "default", status }] }; + const restart = deps.restartGateway?.({ name: "default", home: "/h" }); + const gw = restart?.status === "restarting" ? ", gateway restarting" : ""; + const label = status === "current" ? "already current" : "migrated — linked"; + return { ok: true, lines: ["Hermes:", ` hermes/default ${label}${gw}`], profiles: [{ name: "default", status }] }; + }); +} + +let home: string; +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "fp-update-run-")); + vi.stubEnv("HOME", home); + vi.stubEnv("FAILPROOFAI_HOME", join(home, ".failproofai")); + svc.daemonServiceStatus.mockReturnValue("running"); + gateways.restartOpenClawGateways.mockReturnValue([]); + vi.clearAllMocks(); +}); +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(home, { recursive: true, force: true }); +}); + +describe("the version marker", () => { + it("asks for the steps until this version has finished them, then stops asking", () => { + const fp = home; + expect(readUpdatedVersion(fp)).toBeNull(); + expect(setupNeedsUpdateSteps("1.0.16", fp)).toBe(true); + markUpdated("1.0.16", fp); + expect(readUpdatedVersion(fp)).toBe("1.0.16"); + expect(setupNeedsUpdateSteps("1.0.16", fp)).toBe(false); + // The next npm upgrade asks again. + expect(setupNeedsUpdateSteps("1.0.17", fp)).toBe(true); + const file = join(home, ".failproofai", "state", "updated-version"); + expect(readFileSync(file, "utf8")).toBe("1.0.16\n"); + expect(statSync(file).mode & 0o777).toBe(0o600); + }); +}); + +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 () => { + hermesWith("current"); + gateways.restartOpenClawGateways.mockReturnValue([{ host: "openclaw", profile: "default", status: "restarting" }]); + const run = await runUpdateSteps(AS_CONFIG); + expect(run.ok).toBe(true); + 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"); + // Setup already brought the daemon to this version. + expect(svc.refreshDaemonToCliVersion).not.toHaveBeenCalled(); + }); + + it("touches no gateway when the daemon is not running", async () => { + hermesWith("current"); + svc.daemonServiceStatus.mockReturnValue("stopped"); + const run = await runUpdateSteps(AS_CONFIG); + expect(gateways.restartHermesGateway).not.toHaveBeenCalled(); + expect(gateways.restartOpenClawGateways).not.toHaveBeenCalled(); + // "already current" with nothing restarted is not worth a report. + expect(run.changed).toBe(false); + }); + + it("is silent on a machine without Hermes or OpenClaw", async () => { + hermesWith("untouched"); + const run = await runUpdateSteps(AS_CONFIG); + expect(run).toMatchObject({ ok: true, changed: false, lines: [] }); + }); +}); + +describe("runUpdateSteps as update runs it", () => { + it("refreshes the daemon, and --no-daemon also leaves gateways alone", async () => { + hermesWith("current"); + await runUpdateSteps({ layout: false, daemon: true, restart: true }); + expect(svc.refreshDaemonToCliVersion).toHaveBeenCalledTimes(1); + + vi.clearAllMocks(); + hermesWith("current"); + const skipped = await runUpdateSteps({ layout: false, daemon: false, restart: false, noteSkippedDaemon: true }); + expect(svc.refreshDaemonToCliVersion).not.toHaveBeenCalled(); + expect(gateways.restartHermesGateway).not.toHaveBeenCalled(); + expect(skipped.lines).toContain("Skipped the daemon (--no-daemon). Its version may not match this CLI."); + }); + + it("does not restart gateways onto a daemon that failed to update", async () => { + hermesWith("current"); + svc.refreshDaemonToCliVersion.mockResolvedValueOnce({ ok: false, lines: ["✕ failproofaid could not be updated"] }); + const run = await runUpdateSteps({ layout: false, daemon: true, restart: true }); + expect(run.ok).toBe(false); + expect(gateways.restartHermesGateway).not.toHaveBeenCalled(); + expect(gateways.restartOpenClawGateways).not.toHaveBeenCalled(); + }); +}); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index f9e888984..1e2f879d6 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -1165,127 +1165,43 @@ async function runCli() { // this file, which this command is exempt from. Reading the ledger and // inferring "the top-level check must have done it" was the first version, and // it is the kind of indirection that reads fine and reports the wrong thing - // the moment either half moves. - const { detectLayout } = await import("../src/hooks/fp-config"); - const { LAYOUT_VERSION } = await import("../src/hooks/fp-home"); - const { runMigrations } = await import("../src/hooks/migrations"); - const state = detectLayout(); + // the moment either half moves. The steps are shared with `config`, which + // runs them after the first setup on a new version (src/hooks/update-run.ts). + const { runUpdateSteps, markUpdated } = await import("../src/hooks/update-run"); + const noDaemon = subArgs.includes("--no-daemon"); + const run = await runUpdateSteps({ + layout: true, + daemon: !noDaemon, + // A daemon left as it is may not serve the new plugin, so --no-daemon + // leaves the gateways alone too. + restart: !noDaemon && !subArgs.includes("--no-restart"), + noteSkippedDaemon: noDaemon, + }); - if (state.kind === "future") { + if (run.futureLayout) { await printReport("update", [ `This machine's failproofai directory was written by a NEWER version ` + - `(layout ${state.found}; this build speaks ${LAYOUT_VERSION}). This CLI is the stale half:`, + `(layout ${run.futureLayout.found}; this build speaks ${run.futureLayout.speaks}). This CLI is the stale half:`, "", " npm install -g failproofai@latest", - ], { ok: false, meta: `layout ${state.found}` }); + ], { ok: false, meta: `layout ${run.futureLayout.found}` }); await track("cli_update", { ok: false, reason: "future_layout" }); lastSubcommand = null; await exitAfterFlush(1); return; } - // Collected rather than printed as it goes, so `update` closes with ONE - // report — heading, then both halves of the upgrade under it — instead of - // a run of bare sentences at column zero. - const report = []; - let migrationsRan = 0; - let migrationFailed = false; - if (state.kind === "stale") { - const run = runMigrations(state.found); - migrationsRan = run.steps.length; - migrationFailed = Boolean(run.failed); - for (const step of run.steps) { - report.push(` ${step.ok ? "migrated" : "FAILED "} layout ${step.from} → ${step.to}`); - } - if (run.backedUp.length > 0) report.push("", `Saved first: ${run.backedUp.join(", ")}`); - // Each failing half marks its own line (the daemon's lines arrive with - // their ✕ already): the report opens on whatever ran first, often a - // success, and printReport's guess would put the ✕ there. - if (run.failed) { - report.push( - "", - `✕ Step ${run.failed.from} → ${run.failed.to} did not finish: ${run.failed.error}`, - ` The home is still marked layout ${state.found} and will be retried.`, - ); - } - } else { - report.push(`Home is at layout ${LAYOUT_VERSION}; no migration was needed.`); - } - - // The daemon is refreshed even when a step failed, and deliberately: the - // binary and the layout are independent halves, and leaving a version-skewed - // daemon behind on top of a failed migration is strictly worse than fixing - // the half that can be fixed. The exit code still reports the failure. - let daemonOk = true; - if (subArgs.includes("--no-daemon")) { - report.push("", "Skipped the daemon (--no-daemon). Its version may not match this CLI."); - } else { - const svc = await import("../src/hooks/daemon-service"); - if (!svc.isDaemonSupportedPlatform()) { - report.push("", `failproofaid does not run on ${process.platform}; nothing to update.`); - } else { - // `refreshDaemonToCliVersion` answers "is there a service at all" itself, - // so there is no separate installed check to get out of step with it. - const result = await svc.refreshDaemonToCliVersion(); - report.push("", ...result.lines); - daemonOk = result.ok; - } - } - - // Hermes is migrated AFTER the daemon, and gated on what the daemon that is - // now running can do: the native plugin needs `policyEvaluation`, which - // ≤1.0.5 daemons lack, so when the swap above could not happen (a sudo - // system service with no sudo) the shell hooks stay and this fails loudly. - // Gateways are restarted only onto a daemon this run left current AND that - // is running: "nothing to update" on a machine with no service, or an - // unsupported platform, is also `daemonOk`. - let restartsGateways = daemonOk && !subArgs.includes("--no-daemon") && !subArgs.includes("--no-restart"); - if (restartsGateways) { - const svc = await import("../src/hooks/daemon-service"); - restartsGateways = svc.isDaemonSupportedPlatform() && svc.daemonServiceStatus() === "running"; - } - let hermesOk = true; - let hermesMigrated = 0; - try { - const { runHermesUpdateMigration } = await import("../src/hooks/hermes-update"); - const svc = await import("../src/hooks/daemon-service"); - const restart = await import("../src/hooks/gateway-restart"); - const hermesResult = await runHermesUpdateMigration({ - daemonSupportsPolicyEvaluation: () => svc.probeDaemonPolicyEvaluation(), - restartGateway: restartsGateways ? (p) => restart.restartHermesGateway(p) : undefined, - }); - 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. - const [heading, ...rest] = hermesResult.lines; - report.push("", hermesResult.ok ? heading : `✕ ${heading}`, ...rest); - } - hermesOk = hermesResult.ok; - hermesMigrated = hermesResult.profiles.filter((p) => p.status === "migrated").length; - } catch (err) { - report.push("", `✕ Hermes migration failed: ${err instanceof Error ? err.message : String(err)}`); - hermesOk = false; - } - - if (restartsGateways) { - try { - const restart = await import("../src/hooks/gateway-restart"); - const lines = restart.openclawRestartLines(restart.restartOpenClawGateways()); - if (lines.length > 0) report.push("", ...lines); - } catch { - // Restarting is a convenience; the update itself already succeeded. - } - } - - const updateOk = daemonOk && !migrationFailed && hermesOk; + const report = run.lines; + const updateOk = run.ok; + if (updateOk && !noDaemon) markUpdated(version); // No `v${version}` meta: the header already names the version. await printReport("update", report, { ok: updateOk }); await track("cli_update", { ok: updateOk, - migrations: migrationsRan, - migration_failed: migrationFailed, - hermes_ok: hermesOk, - hermes_migrated: hermesMigrated, + migrations: run.migrationsRan, + migration_failed: run.migrationFailed, + hermes_ok: run.hermesOk, + hermes_migrated: run.hermesMigrated, }); lastSubcommand = null; await exitAfterFlush(updateOk ? 0 : 1); @@ -2120,6 +2036,20 @@ async function runCli() { labelExit = renamed.exitCode; } } + // The first setup on a new version finishes the upgrade too: without this a + // 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. + let updateExit = 0; + if (result.applied) { + const { runUpdateSteps, markUpdated, setupNeedsUpdateSteps } = await import("../src/hooks/update-run"); + if (setupNeedsUpdateSteps(version)) { + const run = await runUpdateSteps({ layout: false, daemon: false, restart: true }); + if (run.changed) await printReport("update", run.lines.filter((l, i) => i > 0 || l !== ""), { ok: run.ok }); + if (run.ok) markUpdated(version); + else updateExit = 1; + } + } await warnTokenOnArgv(); await track("cli_configure_invoked", { applied: result.applied, @@ -2138,7 +2068,7 @@ async function runCli() { // regardless discarded it: a fleet script could not tell "the user pressed // Esc" from "this machine could not install the required daemon and is // unconfigured". Cancelling is not a failure; the other two are. - await exitAfterFlush(!result.applied && result.abort && result.abort !== "cancelled" ? 1 : labelExit); + await exitAfterFlush(!result.applied && result.abort && result.abort !== "cancelled" ? 1 : labelExit || updateExit); return; } diff --git a/src/hooks/fp-home.ts b/src/hooks/fp-home.ts index 68cd6f17a..50921ff98 100644 --- a/src/hooks/fp-home.ts +++ b/src/hooks/fp-home.ts @@ -474,6 +474,13 @@ export const onboardingAttemptFile = (home?: string) => * "failproofai reorganised … Removed 1 item(s) from the old layout." */ export const lastVersionFile = (home?: string) => resolve(stateDir(home), "last-version"); +/** + * The CLI version whose upgrade steps (`failproofai update`: Hermes profiles, + * gateway restarts) last finished on this machine. `config` runs them when it + * differs, so the first setup after an `npm i -g` leaves no gateway on the plugin + * it loaded before. Separate from `last-version`, which any first command writes. + */ +export const updatedVersionFile = (home?: string) => resolve(stateDir(home), "updated-version"); export const onboardingLockFile = (home?: string) => resolve(stateDir(home), "onboarding.lock"); export const codexSessionPathsFile = (home?: string) => resolve(stateDir(home), "codex-session-paths.json"); @@ -684,6 +691,7 @@ export const HOME_CLASSES: readonly { path: (home?: string) => string; class: Da { path: semanticDir, class: "derived" }, { path: logsDir, class: "derived" }, { path: lastVersionFile, class: "derived" }, + { path: updatedVersionFile, class: "derived" }, { path: launcherMarker, class: "derived" }, { path: onboardingLockFile, class: "derived" }, { path: onboardingAttemptFile, class: "derived" }, diff --git a/src/hooks/update-run.ts b/src/hooks/update-run.ts new file mode 100644 index 000000000..c09fc0444 --- /dev/null +++ b/src/hooks/update-run.ts @@ -0,0 +1,196 @@ +/** + * The steps that finish an npm upgrade on this machine, shared by + * `failproofai update` and by `failproofai config`. + * + * `update` runs all of them. `config` runs them after a setup that applied, + * when this CLI version has not finished them here yet (`updatedVersionFile`): + * the first setup after `npm i -g failproofai` (or on a fresh machine) would + * otherwise leave a running Hermes or OpenClaw gateway on the plugin it loaded + * before, or with no plugin at all, until someone thought to run `update`. + * Setup has already brought the daemon to this version and the CLI entry has + * already migrated the home, so `config` skips those two. + */ +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname } from "node:path"; +import { updatedVersionFile } from "./fp-home"; + +export interface UpdateStepsOptions { + /** Migrate the home layout (`update`); `config` relies on the CLI entry's. */ + layout: boolean; + /** Bring the daemon to this CLI's version (`update` without --no-daemon). */ + daemon: boolean; + /** Restart running, service-managed Hermes and OpenClaw gateways. */ + restart: boolean; + /** Say the daemon was skipped on purpose (`update --no-daemon`). */ + noteSkippedDaemon?: boolean; +} + +export interface UpdateStepsResult { + /** Report lines, grouped by step with blank lines between. */ + lines: string[]; + ok: boolean; + /** True when the layout is NEWER than this CLI: nothing else ran. */ + futureLayout?: { found: number; speaks: number }; + migrationsRan: number; + migrationFailed: boolean; + hermesOk: boolean; + hermesMigrated: number; + /** Something a person should see: a migration, a daemon change, a restart. */ + changed: boolean; +} + +export async function runUpdateSteps(opts: UpdateStepsOptions): Promise { + const lines: string[] = []; + let migrationsRan = 0; + let migrationFailed = false; + let changed = false; + + if (opts.layout) { + const { detectLayout } = await import("./fp-config"); + const { LAYOUT_VERSION } = await import("./fp-home"); + const { runMigrations } = await import("./migrations"); + const state = detectLayout(); + if (state.kind === "future") { + return { + lines: [], + ok: false, + futureLayout: { found: state.found, speaks: LAYOUT_VERSION }, + migrationsRan: 0, + migrationFailed: false, + hermesOk: true, + hermesMigrated: 0, + changed: false, + }; + } + if (state.kind === "stale") { + const run = runMigrations(state.found); + migrationsRan = run.steps.length; + migrationFailed = Boolean(run.failed); + changed = changed || migrationsRan > 0; + for (const step of run.steps) { + lines.push(` ${step.ok ? "migrated" : "FAILED "} layout ${step.from} → ${step.to}`); + } + if (run.backedUp.length > 0) lines.push("", `Saved first: ${run.backedUp.join(", ")}`); + // Each failing half marks its own line (the daemon's lines arrive with + // their ✕ already): the report opens on whatever ran first, often a + // success, and printReport's guess would put the ✕ there. + if (run.failed) { + lines.push( + "", + `✕ Step ${run.failed.from} → ${run.failed.to} did not finish: ${run.failed.error}`, + ` The home is still marked layout ${state.found} and will be retried.`, + ); + } + } else { + lines.push(`Home is at layout ${LAYOUT_VERSION}; no migration was needed.`); + } + } + + // The daemon is refreshed even when a step failed, and deliberately: the + // binary and the layout are independent halves, and leaving a version-skewed + // daemon behind on top of a failed migration is strictly worse than fixing + // the half that can be fixed. The exit code still reports the failure. + let daemonOk = true; + const svc = await import("./daemon-service"); + if (opts.noteSkippedDaemon) { + lines.push("", "Skipped the daemon (--no-daemon). Its version may not match this CLI."); + } else if (opts.daemon) { + if (!svc.isDaemonSupportedPlatform()) { + lines.push("", `failproofaid does not run on ${process.platform}; nothing to update.`); + } else { + // `refreshDaemonToCliVersion` answers "is there a service at all" itself, + // so there is no separate installed check to get out of step with it. + const result = await svc.refreshDaemonToCliVersion(); + lines.push("", ...result.lines); + daemonOk = result.ok; + changed = changed || !result.lines.some((l) => /nothing to update/.test(l)); + } + } + + // Hermes is migrated AFTER the daemon, and gated on what the daemon that is + // now running can do: the native plugin needs `policyEvaluation`, which + // ≤1.0.5 daemons lack, so when the swap above could not happen (a sudo + // system service with no sudo) the shell hooks stay and this fails loudly. + // Gateways are restarted only onto a daemon that is current AND running: + // "nothing to update" on a machine with no service, or an unsupported + // platform, is also `daemonOk`. + const restarts = + opts.restart && daemonOk && svc.isDaemonSupportedPlatform() && svc.daemonServiceStatus() === "running"; + let hermesOk = true; + let hermesMigrated = 0; + try { + const { runHermesUpdateMigration } = await import("./hermes-update"); + const restart = await import("./gateway-restart"); + const hermesResult = await runHermesUpdateMigration({ + daemonSupportsPolicyEvaluation: () => svc.probeDaemonPolicyEvaluation(), + restartGateway: restarts ? (p) => restart.restartHermesGateway(p) : undefined, + }); + 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. + const [heading, ...rest] = hermesResult.lines; + lines.push("", hermesResult.ok ? heading : `✕ ${heading}`, ...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); + } catch (err) { + lines.push("", `✕ Hermes migration failed: ${err instanceof Error ? err.message : String(err)}`); + hermesOk = false; + } + + if (restarts) { + try { + const restart = await import("./gateway-restart"); + const restartLines = restart.openclawRestartLines(restart.restartOpenClawGateways()); + if (restartLines.length > 0) { + lines.push("", ...restartLines); + changed = true; + } + } catch { + // Restarting is a convenience; the update itself already succeeded. + } + } + + return { + lines, + ok: daemonOk && !migrationFailed && hermesOk, + migrationsRan, + migrationFailed, + hermesOk, + hermesMigrated, + changed, + }; +} + +function mentionsGateway(lines: string[]): boolean { + return lines.some((l) => /gateway/.test(l)); +} + +/** The CLI version whose upgrade steps last finished here, or null. */ +export function readUpdatedVersion(home?: string): string | null { + try { + const v = readFileSync(updatedVersionFile(home), "utf8").trim(); + return v.length > 0 ? v : null; + } catch { + return null; + } +} + +/** Record that this version's upgrade steps finished. Best effort. */ +export function markUpdated(version: string, home?: string): void { + try { + const file = updatedVersionFile(home); + if (!existsSync(dirname(file))) mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); + writeFileSync(file, `${version}\n`, { mode: 0o600 }); + } catch { + // A missing marker only means the next setup runs these steps again. + } +} + +/** Whether `config` should run the upgrade steps after a setup that applied. */ +export function setupNeedsUpdateSteps(version: string, home?: string): boolean { + return readUpdatedVersion(home) !== version; +} From a3682cbdf7ae79b89f3c71eac65327a37cc7dd3a Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 19 Nov 2026 12:48:15 +0530 Subject: [PATCH 23/41] fix(config): one line, in update's words, instead of a second report MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first setup on a new version printed update's whole report under it: a second "Update" header and a Hermes/OpenClaw block. Setup now prints at most one line, built from update's own row words: ✓ hermes/default, openclaw/default: gateway restarting ▲ openclaw/lab: restart the gateway and nothing when no gateway runs. A Hermes migration failure keeps its existing ✕ line. Verified with two profiles per agent (a throwaway Hermes profile and a named OpenClaw profile, each with its own gateway service): config enabled the plugin in both, restarted all four gateways, and each new gateway process loaded the plugin. --- __tests__/hooks/update-run.test.ts | 35 ++++++++++++++++++++++++++++- bin/failproofai.mjs | 13 +++++++++-- src/hooks/update-run.ts | 36 ++++++++++++++++++++++++++---- 3 files changed, 77 insertions(+), 7 deletions(-) diff --git a/__tests__/hooks/update-run.test.ts b/__tests__/hooks/update-run.test.ts index 6e219a1e1..0bfe7bfdf 100644 --- a/__tests__/hooks/update-run.test.ts +++ b/__tests__/hooks/update-run.test.ts @@ -24,7 +24,7 @@ vi.mock("../../src/hooks/daemon-service", () => svc); vi.mock("../../src/hooks/hermes-update", () => hermes); vi.mock("../../src/hooks/gateway-restart", () => gateways); -import { markUpdated, readUpdatedVersion, runUpdateSteps, setupNeedsUpdateSteps } from "../../src/hooks/update-run"; +import { markUpdated, readUpdatedVersion, runUpdateSteps, setupGatewayLine, setupNeedsUpdateSteps } from "../../src/hooks/update-run"; /** Hermes as `runHermesUpdateMigration` reports it, calling the restart it was handed. */ function hermesWith(status: "current" | "migrated" | "untouched") { @@ -124,3 +124,36 @@ describe("runUpdateSteps as update runs it", () => { expect(gateways.restartOpenClawGateways).not.toHaveBeenCalled(); }); }); + +describe("what config prints about it", () => { + const r = (host: "hermes" | "openclaw", profile: string, status: string) => ({ host, profile, status }) as never; + + it("is one line, in update's own words, naming every profile", () => { + expect(setupGatewayLine([r("hermes", "default", "restarting"), r("hermes", "work", "restarting"), r("openclaw", "ops", "restarting")])).toEqual({ + ok: true, + text: "hermes/default, hermes/work, openclaw/ops: gateway restarting", + }); + }); + + it("asks for a manual restart first when a gateway could not be restarted", () => { + expect(setupGatewayLine([r("hermes", "default", "restarting"), r("openclaw", "lab", "not-supervised")])).toEqual({ + ok: false, + text: "openclaw/lab: restart the gateway", + }); + }); + + it("says nothing when no gateway runs", () => { + expect(setupGatewayLine([r("hermes", "default", "not-running")])).toBeNull(); + expect(setupGatewayLine([])).toBeNull(); + }); + + it("collects each profile's restart, Hermes and OpenClaw", async () => { + hermesWith("current"); + gateways.restartOpenClawGateways.mockReturnValue([{ host: "openclaw", profile: "ops", status: "restarting" }]); + const run = await runUpdateSteps({ layout: false, daemon: false, restart: true }); + expect(run.restarts.map((x) => `${x.host}/${x.profile}:${x.status}`)).toEqual([ + "hermes/default:restarting", + "openclaw/ops:restarting", + ]); + }); +}); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index 1e2f879d6..2d9431c58 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -2042,10 +2042,19 @@ async function runCli() { // the daemon to this version and the entry check migrated the home. let updateExit = 0; if (result.applied) { - const { runUpdateSteps, markUpdated, setupNeedsUpdateSteps } = await import("../src/hooks/update-run"); + const { runUpdateSteps, markUpdated, setupNeedsUpdateSteps, setupGatewayLine } = await import("../src/hooks/update-run"); if (setupNeedsUpdateSteps(version)) { const run = await runUpdateSteps({ layout: false, daemon: false, restart: true }); - if (run.changed) await printReport("update", run.lines.filter((l, i) => i > 0 || l !== ""), { ok: run.ok }); + // One line at most, in update's own words; a Hermes failure keeps its + // existing ✕ line so it is not lost. + const { screenKit, colorsEnabled } = await import("../src/hooks/tui"); + const kit = screenKit({ color: colorsEnabled(process.stdout) }); + 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; } diff --git a/src/hooks/update-run.ts b/src/hooks/update-run.ts index c09fc0444..973ef7f78 100644 --- a/src/hooks/update-run.ts +++ b/src/hooks/update-run.ts @@ -13,6 +13,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname } from "node:path"; import { updatedVersionFile } from "./fp-home"; +import type { GatewayRestart } from "./gateway-restart"; export interface UpdateStepsOptions { /** Migrate the home layout (`update`); `config` relies on the CLI entry's. */ @@ -37,6 +38,8 @@ export interface UpdateStepsResult { hermesMigrated: number; /** Something a person should see: a migration, a daemon change, a restart. */ changed: boolean; + /** Every gateway restart attempted, Hermes and OpenClaw, in report order. */ + restarts: GatewayRestart[]; } export async function runUpdateSteps(opts: UpdateStepsOptions): Promise { @@ -60,6 +63,7 @@ export async function runUpdateSteps(opts: UpdateStepsOptions): Promise svc.probeDaemonPolicyEvaluation(), - restartGateway: restarts ? (p) => restart.restartHermesGateway(p) : undefined, + restartGateway: restartsGateways + ? (p) => { + const r = restart.restartHermesGateway(p); + restarts.push(r); + return r; + } + : undefined, }); if (hermesResult.lines.length > 0) { // Its lines open on a "Hermes:" heading over one row per profile; on a @@ -141,10 +152,12 @@ export async function runUpdateSteps(opts: UpdateStepsOptions): Promise 0) { lines.push("", ...restartLines); changed = true; @@ -162,9 +175,24 @@ export async function runUpdateSteps(opts: UpdateStepsOptions): Promise `${r.host}/${r.profile}`; + const manual = restarts.filter((r) => r.status === "not-supervised" || r.status === "failed").map(named); + if (manual.length > 0) return { ok: false, text: `${manual.join(", ")}: restart the gateway` }; + const restarting = restarts.filter((r) => r.status === "restarting").map(named); + if (restarting.length > 0) return { ok: true, text: `${restarting.join(", ")}: gateway restarting` }; + return null; +} + function mentionsGateway(lines: string[]): boolean { return lines.some((l) => /gateway/.test(l)); } From 107881c7d37737c0295f2a3c8f7471e895034f0b Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 19 Nov 2026 13:26:34 +0530 Subject: [PATCH 24/41] fix(config): setup no longer tells you to run update before it updates the daemon MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After `npm i -g`, the first `failproofai config` opened with "failproofaid does not match this CLI … Bring it from X to Y: failproofai update", then updated the daemon itself two lines later. Setup runs skip that hint; its other modes (--status, --pause, --resume, --connect, --disconnect, a bare --machine-label rename) still show it, since they leave the daemon as is. Found in a clean-container upgrade run (1.0.15 → 1.0.16-test.0); verified with a 1.0.16-test.1 build: `config --status` still warns, `config` does not and updates the daemon. --- __tests__/hooks/fp-reset.test.ts | 10 ++++++++++ bin/failproofai.mjs | 8 +++++++- src/hooks/fp-reset.ts | 10 ++++++++-- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/__tests__/hooks/fp-reset.test.ts b/__tests__/hooks/fp-reset.test.ts index 00b4eca2b..a397520cc 100644 --- a/__tests__/hooks/fp-reset.test.ts +++ b/__tests__/hooks/fp-reset.test.ts @@ -1366,6 +1366,16 @@ describe("the banners printed before a command", () => { ]); }); + it("says nothing about the daemon to setup, which updates it itself", async () => { + installedDaemon("0.0.1-old"); + writeVersionFile({ daemon: "0.0.1-old" }); + updateConfig({ daemon: { configured: true } }); + + const { lines } = await checkLayoutForCli({ daemonStatus: () => "stopped" as const, daemonUpdatedByCommand: true }); + expect(lines.join("\n")).not.toContain("does not match this CLI"); + expect(lines.join("\n")).not.toContain("failproofai update"); + }); + it("the self-heal: what was repaired, with the phrase on one line, then how to reinstall", async () => { writeVersionFile(); updateConfig({ daemon: { configured: true } }); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index 2d9431c58..e08ad0a25 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -669,7 +669,13 @@ async function runCli() { // test on a seeded layout-2 home, not by a unit test: nothing below the CLI // entry point can see this ordering. const { checkLayoutForCli } = await import("../src/hooks/fp-reset"); - const check = await checkLayoutForCli(); + // Setup brings the daemon to this version itself, so it is not told to + // run `update` first; its other modes (--status, --pause, …) still are. + const setupRun = + args[0] === "config" && + !["--status", "--pause", "--resume", "--connect", "--disconnect"].some((f) => args.includes(f)) && + !(args.includes("--machine-label") && !["--token", "--oss", "--agents"].some((f) => args.includes(f))); + const check = await checkLayoutForCli({ daemonUpdatedByCommand: setupRun }); // Written rather than `console.error`, which Bun paints red on a terminal. if (check.lines.length > 0) process.stderr.write(`${check.lines.join("\n")}\n`); if (check.fatal) await exitAfterFlush(1); diff --git a/src/hooks/fp-reset.ts b/src/hooks/fp-reset.ts index 4dff4c18b..aca6ae70b 100644 --- a/src/hooks/fp-reset.ts +++ b/src/hooks/fp-reset.ts @@ -1117,6 +1117,12 @@ export interface LayoutCheckDeps { daemonStatus?: () => DaemonServiceStatus; /** How to draw the banners. Defaults to what stderr can show, where they print. */ render?: RenderOpts; + /** + * The command is setup (`failproofai config` without --status, --pause and + * the like), which brings the daemon to this version itself: telling the + * person to run `failproofai update` first would be wrong advice. + */ + daemonUpdatedByCommand?: boolean; } /** @@ -1164,7 +1170,7 @@ export async function checkLayoutForCli(deps: LayoutCheckDeps = {}): Promise Date: Thu, 19 Nov 2026 13:32:44 +0530 Subject: [PATCH 25/41] fix(daemon): a policy stuck in a loop no longer wedges every tool call Found driving a real machine: a Cloud policy that spins (`for (;;) {}`) blocks the worker's one event loop, so its 10 s per-policy limit cannot fire. The daemon gave up on that request after 30 s but kept the worker, so every later tool call on the machine, from every agent, waited 30 s and was denied as "failproofaid could not be reached", until someone restarted the daemon. - A read or write timeout on the worker now kills its process group, so the next request starts a fresh worker. The timed-out request, and any queued behind it on the dead worker, still fail closed. - Respawning after the tracked child died now kills what is left of its group first. The worker runs under `sh -c`; with the shell gone, a still spinning `node` child was left running as an orphan. Verified with the release binary and the real worker against a spinning custom policy: the spinning call is denied at 30 s, the daemon logs the restart, the next calls answer allow in ~130 ms, no worker left spinning. --- CHANGELOG.md | 1 + crates/failproofaid/src/worker.rs | 163 +++++++++++++++++++++++++++++- 2 files changed, 159 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 462d6bb92..983ed0d90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - A machine that pulls policies from Cloud is pointed at Cloud, not at installing packs: `config --status` says "None deployed from Cloud" with the dashboard as its fix, and the `failproofai policies` empty state says "Deploy from Cloud" (#1023) - The "no pack is installed" warning is logged once per process instead of on every hook call, which buried the daemon log (#1023) - The daemon service saves a stable link to Node when PATH has one (Homebrew's `/opt/homebrew/bin/node`, not the `Cellar/` path `brew upgrade node` deletes), and `failproofai update` rewrites a service whose saved Node or failproofai path is gone instead of reporting nothing to update; the daemon log names that cause and the fix when the worker cannot start (#1023) +- A policy stuck in a loop no longer leaves every tool call on the machine waiting 30 s and then denied until the daemon restarts: the daemon replaces a worker that let a request time out, and reaps what a dead worker left in its process group (#1023) - The daemon no longer exits on a transient `accept()` failure (out of file descriptors, an aborted connection), which left every hook denied until the service manager restarted it (#1023) - The collector manager and cloud policy sync restart after a panic instead of stopping silently while the daemon keeps answering hooks (#1023) - A hook client that stopped waiting before its verdict was ready is logged as that, with how long the evaluation took, instead of macOS's bare "Invalid argument (os error 22)" (#1023) diff --git a/crates/failproofaid/src/worker.rs b/crates/failproofaid/src/worker.rs index 1eb03a94c..074e7f9d4 100644 --- a/crates/failproofaid/src/worker.rs +++ b/crates/failproofaid/src/worker.rs @@ -10,7 +10,7 @@ //! since that one crosses a real compatibility boundary against whatever //! `failproofai` CLI version happens to be installed). -use fpai_ipc::framing::{read_message, write_message}; +use fpai_ipc::framing::{FramingError, read_message, write_message}; use serde::Deserialize; use serde_json::json; use std::io; @@ -245,6 +245,8 @@ pub struct Worker { /// Set once shutdown begins, so no thread can spawn a worker after the /// process has decided to stop. See [`Worker::shutdown`]. stopping: AtomicBool, + /// How long one request may wait on the worker before it counts as wedged. + request_timeout: Duration, } impl Worker { @@ -254,6 +256,7 @@ impl Worker { cmd, child: Mutex::new(None), stopping: AtomicBool::new(false), + request_timeout: Duration::from_secs(30), } } @@ -325,6 +328,12 @@ impl Worker { None => true, }; if needs_spawn { + // The child we tracked may be gone while its group lives on: the + // `sh -c` wrapper dead, the `node` it forked still running (and, + // after a stuck policy, still spinning). Reap the group first. + if let Some(mut old) = guard.take() { + kill_process_group(&mut old); + } let reason = if previous_child { "restart" } else { "initial" }; let began = Instant::now(); let _ = std::fs::remove_file(&self.socket_path); @@ -403,7 +412,7 @@ impl Worker { let mut stream = UnixStream::connect(&self.socket_path).map_err(WorkerError::Io)?; stream - .set_read_timeout(Some(Duration::from_secs(30))) + .set_read_timeout(Some(self.request_timeout)) .map_err(WorkerError::Io)?; // Symmetric with the read timeout, and not optional. `write_message` // does a blocking `write_all`: if the worker's single-threaded event @@ -415,7 +424,7 @@ impl Worker { // stops answering entirely — the opposite of the fail-fast behaviour // the rest of this file is built around. stream - .set_write_timeout(Some(Duration::from_secs(30))) + .set_write_timeout(Some(self.request_timeout)) .map_err(WorkerError::Io)?; let request = json!({ @@ -426,10 +435,10 @@ impl Worker { "cwd": cwd, "agentSettingsPath": agent_settings_path, }); - write_message(&mut stream, &request).map_err(|e| WorkerError::Io(io::Error::other(e)))?; + write_message(&mut stream, &request).map_err(|e| self.after_io_failure(e))?; let response: serde_json::Value = - read_message(&mut stream).map_err(|e| WorkerError::Io(io::Error::other(e)))?; + read_message(&mut stream).map_err(|e| self.after_io_failure(e))?; match response.get("type").and_then(|t| t.as_str()) { Some("hookResult") => { @@ -476,6 +485,32 @@ impl Worker { } } +impl Worker { + /// A worker that let a request time out is wedged (a policy stuck in a + /// loop blocks its single event loop): its own 10 s per-policy limit could + /// not fire. Left in place it timed out every later request too, so every + /// tool call on the machine waited 30 s and was then denied, for good. + /// Kill its group so the next request starts a fresh worker. This request + /// still fails (and the caller fails closed). + fn after_io_failure(&self, err: FramingError) -> WorkerError { + let timed_out = matches!( + &err, + FramingError::Io(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) + ); + if timed_out { + tracing::warn!( + "worker did not answer within {}s; restarting it", + self.request_timeout.as_secs() + ); + let mut guard = self.child.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(mut child) = guard.take() { + kill_process_group(&mut child); + } + } + WorkerError::Io(io::Error::other(err)) + } +} + impl Drop for Worker { /// Backstop for the paths that do not call [`Worker::shutdown`] explicitly /// (tests, and any early return). Idempotent: `take()` yields `None` once @@ -536,6 +571,124 @@ mod tests { std::fs::remove_file(&socket_path).ok(); } + /// A fake worker that binds the socket, takes requests and never answers: + /// a policy stuck in a loop, from the daemon's side. It writes its pid. + fn wedged_worker_script(pid_file: &Path) -> String { + format!( + "import os, socket, time\n\ + s = socket.socket(socket.AF_UNIX)\n\ + s.bind(os.environ['FAILPROOFAI_WORKER_SOCKET'])\n\ + s.listen(8)\n\ + open('{}', 'w').write(str(os.getpid()))\n\ + held = []\n\ + while True:\n c, _ = s.accept()\n held.append(c)\n", + pid_file.display() + ) + } + + fn alive(pid: i32) -> bool { + // Signal 0 checks existence; a zombie still counts, so reap-or-gone is + // what the kill must achieve within the wait below. + let exists = unsafe { libc::kill(pid, 0) == 0 }; + exists + && !std::fs::read_to_string(format!("/proc/{pid}/stat")) + .map(|s| s.contains(") Z ")) + .unwrap_or(true) + } + + fn read_pid(path: &Path) -> i32 { + for _ in 0..100 { + if let Ok(s) = std::fs::read_to_string(path) + && let Ok(pid) = s.trim().parse() + { + return pid; + } + std::thread::sleep(Duration::from_millis(50)); + } + panic!("the fake worker never wrote its pid"); + } + + /// The regression, found driving a real machine: a Cloud policy stuck in a + /// loop wedged the worker, and every later tool call on the machine waited + /// out the read timeout and was denied, until someone restarted the daemon. + #[test] + fn a_worker_that_times_out_is_replaced_for_the_next_request() { + let socket_path = temp_socket_path("wedged"); + let pid_file = temp_socket_path("wedged-pid"); + let script = temp_socket_path("wedged-py"); + std::fs::write(&script, wedged_worker_script(&pid_file)).unwrap(); + let mut worker = Worker::new( + socket_path.clone(), + WorkerCommand::shell(format!("python3 {}", script.display())), + ); + worker.request_timeout = Duration::from_millis(500); + + worker + .call("PreToolUse", "claude", "{}", None, None) + .expect_err("a worker that never answers fails this request"); + let first = read_pid(&pid_file); + std::fs::remove_file(&pid_file).ok(); + let deadline = Instant::now() + Duration::from_secs(5); + while alive(first) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + assert!( + !alive(first), + "the wedged worker must be killed, not left holding every request" + ); + + // The next request gets a fresh worker rather than the wedged one. + worker.call("PreToolUse", "claude", "{}", None, None).ok(); + let second = read_pid(&pid_file); + assert_ne!(first, second, "a new worker serves the next request"); + + drop(worker); + for p in [&pid_file, &script] { + std::fs::remove_file(p).ok(); + } + } + + /// The worker runs under `sh -c`. With the shell gone but its `node` child + /// alive (still spinning), a respawn left that child running, orphaned. + #[test] + fn a_respawn_reaps_what_the_dead_worker_left_in_its_group() { + let socket_path = temp_socket_path("orphan"); + let pid_file = temp_socket_path("orphan-pid"); + let script = temp_socket_path("orphan-py"); + std::fs::write(&script, wedged_worker_script(&pid_file)).unwrap(); + // `& wait` keeps the shell as the tracked child and python as its child. + let worker = Worker::new( + socket_path.clone(), + WorkerCommand::shell(format!("python3 {} & wait", script.display())), + ); + worker.ensure_started().expect("the fake worker starts"); + let grandchild = read_pid(&pid_file); + std::fs::remove_file(&pid_file).ok(); + { + // Kill only the shell, as a stray `kill ` would. + let mut guard = worker.child.lock().unwrap(); + let child = guard.as_mut().unwrap(); + child.kill().unwrap(); + child.wait().unwrap(); + } + assert!(alive(grandchild), "premise: the shell's child outlives it"); + + worker.ensure_started().expect("a new worker starts"); + let deadline = Instant::now() + Duration::from_secs(5); + while alive(grandchild) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + assert!( + !alive(grandchild), + "the old group's leftover must be reaped on respawn" + ); + + drop(worker); + for p in [&pid_file, &script] { + std::fs::remove_file(p).ok(); + } + } + #[test] fn a_stale_socket_file_is_not_mistaken_for_a_live_worker() { let socket_path = temp_socket_path("stale"); From 3ace0d698eded1b3b135e5b421b275fafb691eea Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 19 Nov 2026 20:22:34 +0530 Subject: [PATCH 26/41] fix(daemon): a warning logged during a log upload is kept for the next one The roll-up cleared every warning once Cloud stored it, including ones recorded while the request was in flight (the lock is not held across it). Acknowledge only the counts the upload carried. --- CHANGELOG.md | 2 +- crates/failproofaid/src/logship.rs | 80 +++++++++++++++++++++++++++--- 2 files changed, 75 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 983ed0d90..1c84fe4b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,7 @@ - failproofaid tells FailproofAI Cloud what each machine runs: its policy poll carries `daemonVersion`, `cliVersion`, `os` and `arch` (optional parameters a server that predates them ignores), and every Cloud and ingest request sends `User-Agent: failproofaid/` (#1023) - Hook events carry the agent's own `tool_call_id` (Claude, Devin, Factory, Pi, Hermes, OpenClaw), the field the transcript events already use and Cloud stores in its own column, so a hook joins the tool call it governed instead of being placed beside it by timestamp; and a hook's start is stamped when it arrived, not when its evaluation ended. Rows written before this convert exactly as before (#1023) - failproofaid sends its log to FailproofAI Cloud only when something is wrong: one roll-up of distinct warnings and errors (repeats counted, at most every 5 minutes), the last 5 minutes of log around an error or after a run that ended without a clean shutdown (at most one per 15 minutes), and the log tail when an operator asks for it from Cloud; secrets are redacted with the collector's rules and the home directory and machine token scrubbed, worker and audit output is sent only when an operator asks, a server without the route is left alone for a day, and `FAILPROOFAI_NO_LOG_UPLOAD=1` turns it off (#1023) -- Batches an outage parked are retried as soon as the server accepts a batch again (or, on an idle machine, within one 5-minute probe) instead of at the hourly pass, and `config --status` counts them as queued rather than "nothing queued" ; a long outage reads as stuck ("N batches queued, oldest …, last delivered …") instead of "Healthy", since its batches sit in the parked queue rather than the spool (#1023) +- Batches an outage parked are retried as soon as the server accepts a batch again (or, on an idle machine, within one 5-minute probe) instead of at the hourly pass, and `config --status` counts them as queued rather than "nothing queued"; a long outage reads as stuck ("N batches queued, oldest …, last delivered …") instead of "Healthy", since its batches sit in the parked queue rather than the spool (#1023) - Allow roll-ups (the default `decisions` verbosity) are stamped when their first hook arrived instead of at the top of their minute, which put them before the tool calls they covered, and name the `tool_call_ids` they cover (#1023) - Setup's summary on a Cloud-managed machine says "Deploy from Cloud" instead of pointing at installing a pack (#1023) - The first `failproofai config` on a new version (a fresh install, or the first after `npm i -g failproofai`) finishes the upgrade the way `failproofai update` does: it migrates Hermes profiles and restarts running, service-managed Hermes and OpenClaw gateways so they load the plugin now on disk. Setup used to leave a gateway that was already running on the plugin it loaded before, or with none, until someone ran `update` (#1023) diff --git a/crates/failproofaid/src/logship.rs b/crates/failproofaid/src/logship.rs index e2c1d92db..fd7c6564a 100644 --- a/crates/failproofaid/src/logship.rs +++ b/crates/failproofaid/src/logship.rs @@ -606,7 +606,10 @@ impl Scrub { enum Kind { Requested(String), Incident, - Errors, + /// What the roll-up carried: each entry's count, and the overflow count. + /// Only that is acknowledged, so a warning logged while the upload was in + /// flight stays for the next one. + Errors(Vec<(String, u64)>, u64), } fn wire_entries(entries: &[Entry], scrub: &Scrub) -> Vec { @@ -733,8 +736,13 @@ fn ship_at(machine_id: &str, scrub: &Scrub, post: &dyn Fn(&Value) -> PostOutcome last_ts: None, }); } + let sent: Vec<(String, u64)> = st + .error_order + .iter() + .filter_map(|k| st.errors.get(k).map(|e| (k.clone(), e.count))) + .collect(); ( - Kind::Errors, + Kind::Errors(sent, st.errors_overflow), body(machine_id, "errors", None, None, &entries, scrub), ) } else { @@ -778,10 +786,23 @@ fn ship_at(machine_id: &str, scrub: &Scrub, post: &dyn Fn(&Value) -> PostOutcome let _ = write_private(&stamp, sent.to_string().as_bytes()); } } - Kind::Errors => { - st.errors.clear(); - st.error_order.clear(); - st.errors_overflow = 0; + Kind::Errors(sent, overflow) => { + for (key, count) in sent { + let left = st.errors.get_mut(&key).map(|e| { + e.count = e.count.saturating_sub(count); + e.count + }); + if left == Some(0) { + st.errors.remove(&key); + } + } + let State { + errors, + error_order, + .. + } = &mut *st; + error_order.retain(|k| errors.contains_key(k)); + st.errors_overflow = st.errors_overflow.saturating_sub(overflow); st.last_errors_sent = Some(now); } } @@ -886,6 +907,53 @@ mod tests { assert_eq!(collect(t0 + ERRORS_EVERY).len(), 1); } + #[test] + fn a_warning_logged_during_the_upload_is_kept_for_the_next_one() { + let _g = LOCK.lock().unwrap(); + reset_for_test(true); + let t0 = Instant::now(); + record(Level::WARN, "x", &line("WARN", "x", "retry 1"), t0); + record(Level::WARN, "x", &line("WARN", "x", "seen once"), t0); + let sent = RefCell::new(Vec::new()); + ship_at( + "m-1", + &scrub(), + &|v| { + sent.borrow_mut().push(v.clone()); + // Logged while the request is in flight (the lock is free): + // the same warning again, and new ones. + for _ in 0..5 { + record(Level::WARN, "x", &line("WARN", "x", "retry 2"), t0); + } + record(Level::WARN, "x", &line("WARN", "x", "brand new"), t0); + PostOutcome::Stored + }, + t0, + ); + let first = sent.into_inner(); + assert_eq!(first.len(), 1); + assert_eq!(first[0]["entries"].as_array().unwrap().len(), 2); + let next = collect(t0 + ERRORS_EVERY); + assert_eq!(next.len(), 1); + let entries = next[0]["entries"].as_array().unwrap(); + let by_msg: Vec<(String, u64)> = entries + .iter() + .map(|e| { + ( + e["message"].as_str().unwrap().to_string(), + e["count"].as_u64().unwrap(), + ) + }) + .collect(); + // "retry N" folds to one fingerprint: 1 was sent, 5 arrived after. + assert_eq!( + by_msg, + vec![("retry 1".to_string(), 5), ("brand new".to_string(), 1)] + ); + // Everything acknowledged now. + assert!(collect(t0 + ERRORS_EVERY * 2).is_empty()); + } + #[test] fn info_alone_never_uploads() { let _g = LOCK.lock().unwrap(); From 783817a20676e9e6579a9a182f17949b3cb8f6b7 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 19 Nov 2026 22:46:43 +0530 Subject: [PATCH 27/41] fix(update): the gateway restart log is owner-only It was created with the default umask (0664), unlike daemon.log. Open it 0600 and tighten an existing one. --- __tests__/hooks/gateway-restart.test.ts | 24 ++++++++++++++++++++++++ src/hooks/gateway-restart.ts | 19 +++++++++++++++---- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/__tests__/hooks/gateway-restart.test.ts b/__tests__/hooks/gateway-restart.test.ts index 8504619ed..cc6bbaa0f 100644 --- a/__tests__/hooks/gateway-restart.test.ts +++ b/__tests__/hooks/gateway-restart.test.ts @@ -5,7 +5,11 @@ * `hermes gateway restart` runs the new gateway in the caller's foreground. */ import { describe, it, expect, vi } from "vitest"; +import { chmodSync, closeSync, mkdtempSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { + openRestartLog, openclawRestartLines, restartHermesGateway, restartOpenClawGateway, @@ -171,3 +175,23 @@ describe("OpenClaw profile selection", () => { } }); }); + +describe("the gateway restart log", () => { + it("is owner-only, and tightens one left world-readable", () => { + const home = mkdtempSync(join(tmpdir(), "fp-restart-log-")); + const prev = process.env.FAILPROOFAI_HOME; + process.env.FAILPROOFAI_HOME = home; + try { + closeSync(openRestartLog()); + const log = join(home, "logs", "gateway-restart.log"); + expect(statSync(log).mode & 0o777).toBe(0o600); + chmodSync(log, 0o664); + closeSync(openRestartLog()); + expect(statSync(log).mode & 0o777).toBe(0o600); + } finally { + if (prev === undefined) delete process.env.FAILPROOFAI_HOME; + else process.env.FAILPROOFAI_HOME = prev; + rmSync(home, { recursive: true, force: true }); + } + }); +}); diff --git a/src/hooks/gateway-restart.ts b/src/hooks/gateway-restart.ts index b7afa1f60..2473aa7c8 100644 --- a/src/hooks/gateway-restart.ts +++ b/src/hooks/gateway-restart.ts @@ -22,7 +22,7 @@ * host waits out its drain. */ import { spawn, spawnSync } from "node:child_process"; -import { closeSync, mkdirSync, openSync, readFileSync } from "node:fs"; +import { chmodSync, closeSync, mkdirSync, openSync, readFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { homedir } from "node:os"; import { listOpenClawProfiles, OPENCLAW_DEFAULT_PROFILE } from "../../lib/openclaw-profiles"; @@ -70,12 +70,23 @@ function restartLogPath(): string { return `${logsDir()}/gateway-restart.log`; } +/** + * The gateways' restart output, owner-only like daemon.log. An existing file + * from before this was set is tightened too. + * @internal exported for tests + */ +export function openRestartLog(): number { + const log = restartLogPath(); + mkdirSync(dirname(log), { recursive: true, mode: 0o700 }); + const fd = openSync(log, "a", 0o600); + chmodSync(log, 0o600); + return fd; +} + function defaultSpawnDetached(cmd: string, args: string[], env: NodeJS.ProcessEnv): boolean { let fd: number | undefined; try { - const log = restartLogPath(); - mkdirSync(dirname(log), { recursive: true }); - fd = openSync(log, "a"); + fd = openRestartLog(); const child = spawn(cmd, args, { env, detached: true, stdio: ["ignore", fd, fd] }); child.on("error", () => {}); child.unref(); From c4f82903a3c0aedc4c56cce14221d4ccd2968321 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 19 Nov 2026 23:44:13 +0530 Subject: [PATCH 28/41] fix(config): a profile added after setup has its gateway restarted Setup ran update's gateway restarts only on a version's first setup. A Hermes or OpenClaw profile created later got the plugin on disk from the next setup, but its gateway was already running and went on without it, unchecked, while status read healthy (found driving a real work profile). Setup now notes which profiles load the plugin before it runs and restarts the running gateways of the ones it plugged in, reported with the existing line: "hermes/work, openclaw/work: gateway restarting". --- CHANGELOG.md | 2 +- __tests__/hooks/update-run.test.ts | 59 +++++++++++++++++++++++++++++- bin/failproofai.mjs | 16 ++++++-- src/hooks/gateway-restart.ts | 2 +- src/hooks/update-run.ts | 52 ++++++++++++++++++++++++++ 5 files changed, 124 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c84fe4b1..ab8bcd32d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,7 +23,7 @@ - Batches an outage parked are retried as soon as the server accepts a batch again (or, on an idle machine, within one 5-minute probe) instead of at the hourly pass, and `config --status` counts them as queued rather than "nothing queued"; a long outage reads as stuck ("N batches queued, oldest …, last delivered …") instead of "Healthy", since its batches sit in the parked queue rather than the spool (#1023) - Allow roll-ups (the default `decisions` verbosity) are stamped when their first hook arrived instead of at the top of their minute, which put them before the tool calls they covered, and name the `tool_call_ids` they cover (#1023) - Setup's summary on a Cloud-managed machine says "Deploy from Cloud" instead of pointing at installing a pack (#1023) -- The first `failproofai config` on a new version (a fresh install, or the first after `npm i -g failproofai`) finishes the upgrade the way `failproofai update` does: it migrates Hermes profiles and restarts running, service-managed Hermes and OpenClaw gateways so they load the plugin now on disk. Setup used to leave a gateway that was already running on the plugin it loaded before, or with none, until someone ran `update` (#1023) +- The first `failproofai config` on a new version (a fresh install, or the first after `npm i -g failproofai`) finishes the upgrade the way `failproofai update` does: it migrates Hermes profiles and restarts running, service-managed Hermes and OpenClaw gateways so they load the plugin now on disk. A later setup that plugs in a profile created since restarts that profile's gateway. Setup used to leave a gateway that was already running on the plugin it loaded before, or with none, until someone ran `update` (#1023) ## 1.0.15 — 2026-11-18 diff --git a/__tests__/hooks/update-run.test.ts b/__tests__/hooks/update-run.test.ts index 0bfe7bfdf..744d6121d 100644 --- a/__tests__/hooks/update-run.test.ts +++ b/__tests__/hooks/update-run.test.ts @@ -24,7 +24,16 @@ vi.mock("../../src/hooks/daemon-service", () => svc); vi.mock("../../src/hooks/hermes-update", () => hermes); vi.mock("../../src/hooks/gateway-restart", () => gateways); -import { markUpdated, readUpdatedVersion, runUpdateSteps, setupGatewayLine, setupNeedsUpdateSteps } from "../../src/hooks/update-run"; +import { + markUpdated, + readUpdatedVersion, + restartNewlyPlugged, + runUpdateSteps, + setupGatewayLine, + setupNeedsUpdateSteps, + type PluggedProfile, +} from "../../src/hooks/update-run"; +import type { GatewayRestart } from "../../src/hooks/gateway-restart"; /** Hermes as `runHermesUpdateMigration` reports it, calling the restart it was handed. */ function hermesWith(status: "current" | "migrated" | "untouched") { @@ -157,3 +166,51 @@ describe("what config prints about it", () => { ]); }); }); + +describe("a setup that plugs in a profile created after the version's first setup", () => { + const p = (host: "hermes" | "openclaw", name: string): PluggedProfile => ({ host, name, home: `/h/${host}-${name}` }); + const before = [p("hermes", "default"), p("openclaw", "default")]; + const restarted = + (host: "hermes" | "openclaw") => + (q: { name: string; home: string }): GatewayRestart => ({ host, profile: q.name, status: "restarting" }); + + it("restarts only the gateways of the profiles it plugged in", async () => { + const restartHermes = vi.fn(restarted("hermes")); + const restartOpenClaw = vi.fn(restarted("openclaw")); + const restarts = await restartNewlyPlugged(before, { + plugged: async () => [...before, p("hermes", "work"), p("openclaw", "work")], + daemonRunning: async () => true, + restartHermes, + restartOpenClaw, + }); + expect(restartHermes).toHaveBeenCalledTimes(1); + expect(restartHermes.mock.calls[0][0]).toMatchObject({ name: "work", home: "/h/hermes-work" }); + expect(restartOpenClaw).toHaveBeenCalledTimes(1); + expect(setupGatewayLine(restarts)).toEqual({ ok: true, text: "hermes/work, openclaw/work: gateway restarting" }); + }); + + it("restarts nothing when every plugged profile already was", async () => { + const restartHermes = vi.fn(restarted("hermes")); + const restarts = await restartNewlyPlugged(before, { + plugged: async () => before, + daemonRunning: async () => true, + restartHermes, + restartOpenClaw: restartHermes, + }); + expect(restarts).toEqual([]); + expect(restartHermes).not.toHaveBeenCalled(); + expect(setupGatewayLine(restarts)).toBeNull(); + }); + + it("restarts nothing onto a daemon that is not running", async () => { + const restartHermes = vi.fn(restarted("hermes")); + const restarts = await restartNewlyPlugged([], { + plugged: async () => [p("hermes", "work")], + daemonRunning: async () => false, + restartHermes, + restartOpenClaw: restartHermes, + }); + expect(restarts).toEqual([]); + expect(restartHermes).not.toHaveBeenCalled(); + }); +}); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index e08ad0a25..e79a804d7 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -2019,6 +2019,8 @@ async function runCli() { if (refusal) throw new CliError(refusal); } const { runConfigureWizard } = await import("../src/hooks/configure-wizard"); + const { pluggedProfiles } = await import("../src/hooks/update-run"); + const pluggedBefore = await pluggedProfiles().catch(() => []); const result = await runConfigureWizard( {}, { @@ -2048,13 +2050,19 @@ async function runCli() { // the daemon to this version and the entry check migrated the home. let updateExit = 0; if (result.applied) { - const { runUpdateSteps, markUpdated, setupNeedsUpdateSteps, setupGatewayLine } = await import("../src/hooks/update-run"); - if (setupNeedsUpdateSteps(version)) { + 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 { screenKit, colorsEnabled } = await import("../src/hooks/tui"); - const kit = screenKit({ color: colorsEnabled(process.stdout) }); const gateway = setupGatewayLine(run.restarts); const out = [ ...run.lines.filter((l) => l.startsWith("✕")), diff --git a/src/hooks/gateway-restart.ts b/src/hooks/gateway-restart.ts index 2473aa7c8..6691648f4 100644 --- a/src/hooks/gateway-restart.ts +++ b/src/hooks/gateway-restart.ts @@ -207,7 +207,7 @@ export function openclawProfileEnv( } /** Profiles whose openclaw.json loads our plugin; only their gateways run it. */ -function openclawProfilesUsingFailproofai(): Array<{ name: string; home: string }> { +export function openclawProfilesUsingFailproofai(): Array<{ name: string; home: string }> { return listOpenClawProfiles().filter((profile) => { try { const settings = JSON.parse(readFileSync(join(profile.home, "openclaw.json"), "utf8")) as { diff --git a/src/hooks/update-run.ts b/src/hooks/update-run.ts index 973ef7f78..de6daa7a7 100644 --- a/src/hooks/update-run.ts +++ b/src/hooks/update-run.ts @@ -193,6 +193,58 @@ export function setupGatewayLine(restarts: GatewayRestart[]): { ok: boolean; tex return null; } +/** A Hermes or OpenClaw profile whose gateway loads FailproofAI's plugin when it starts. */ +export interface PluggedProfile { + host: "hermes" | "openclaw"; + name: string; + home: string; +} + +export async function pluggedProfiles(): Promise { + const { hermesProfileHealth } = await import("./integrations"); + const { openclawProfilesUsingFailproofai } = await import("./gateway-restart"); + return [ + ...hermesProfileHealth() + .filter((p) => p.pluginInstalled && p.pluginEnabled && !p.pluginDisabled) + .map((p): PluggedProfile => ({ host: "hermes", name: p.name, home: p.home })), + ...openclawProfilesUsingFailproofai().map((p): PluggedProfile => ({ host: "openclaw", ...p })), + ]; +} + +export interface NewlyPluggedDeps { + plugged?: () => Promise; + daemonRunning?: () => Promise; + restartHermes?: (p: { name: string; home: string }) => GatewayRestart; + restartOpenClaw?: (p: { name: string; home: string }) => GatewayRestart; +} + +/** + * Restart the gateways of profiles this setup run plugged in, given + * `pluggedProfiles()` from before it. A profile created after the version's + * first setup gets the plugin on disk, but its gateway is already running and + * would go on without it, unchecked, until something restarted it. + */ +export async function restartNewlyPlugged( + before: PluggedProfile[], + deps: NewlyPluggedDeps = {}, +): Promise { + const key = (p: PluggedProfile) => `${p.host}/${p.name}`; + const had = new Set(before.map(key)); + const fresh = (await (deps.plugged ?? pluggedProfiles)()).filter((p) => !had.has(key(p))); + if (fresh.length === 0) return []; + const daemonRunning = + deps.daemonRunning ?? + (async () => { + const svc = await import("./daemon-service"); + return svc.isDaemonSupportedPlatform() && svc.daemonServiceStatus() === "running"; + }); + if (!(await daemonRunning())) return []; + const restart = await import("./gateway-restart"); + const hermes = deps.restartHermes ?? ((p) => restart.restartHermesGateway(p)); + const openclaw = deps.restartOpenClaw ?? ((p) => restart.restartOpenClawGateway(p)); + return fresh.map((p) => (p.host === "hermes" ? hermes(p) : openclaw(p))); +} + function mentionsGateway(lines: string[]): boolean { return lines.some((l) => /gateway/.test(l)); } From bfe6b7b6c7b5eae5fbb81ce2cd6918ee4aaff31b Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Fri, 20 Nov 2026 00:49:33 +0530 Subject: [PATCH 29/41] chore: bump to 1.0.16-beta.1 1.0.16-beta.0 was published from this branch to the next dist-tag, so main's next beta needs a version npm has not taken. --- 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 ab8bcd32d..941374e00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## 1.0.16-beta.0 — 2026-11-18 +## 1.0.16-beta.1 — 2026-11-20 ### Fixes diff --git a/Cargo.lock b/Cargo.lock index 81ddbaa1e..dbabc1aad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -298,7 +298,7 @@ dependencies = [ [[package]] name = "failproofaid" -version = "1.0.16-beta.0" +version = "1.0.16-beta.1" dependencies = [ "fpai-collect", "fpai-ipc", @@ -361,7 +361,7 @@ dependencies = [ [[package]] name = "fpai-collect" -version = "1.0.16-beta.0" +version = "1.0.16-beta.1" dependencies = [ "axum", "getrandom 0.4.3", @@ -382,7 +382,7 @@ dependencies = [ [[package]] name = "fpai-ipc" -version = "1.0.16-beta.0" +version = "1.0.16-beta.1" dependencies = [ "libc", "proptest", diff --git a/Cargo.toml b/Cargo.toml index bd702a497..f7105cdae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "1.0.16-beta.0" +version = "1.0.16-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 b675e9010..81a13e183 100644 --- a/hermes-plugin/plugin.yaml +++ b/hermes-plugin/plugin.yaml @@ -1,5 +1,5 @@ name: failproofai -version: 1.0.16-beta.0 +version: 1.0.16-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 eb2b6d694..c5b5f3921 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "failproofai", - "version": "1.0.16-beta.0", + "version": "1.0.16-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 ce9211749b5ff948bdca3b3663f873444cf21e6d Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Fri, 20 Nov 2026 16:43:59 +0530 Subject: [PATCH 30/41] fix(policies): a policy written with require() loads under Node Every policy file's temporary copy was written as .mjs. Node defines no require, module or exports in an ES module, so a CommonJS policy, or an ES module policy importing a module.exports helper, failed to load, and the calls it should have denied were allowed. The e2e suite runs the CLI under Bun, which defines require in ES modules, so nothing caught it. A file with no import/export or import.meta that uses require, module.exports or exports.x now gets a .cjs copy, and the specifiers pointing at it are rewritten to match. A new e2e test bundles the CLI and runs it with node. The collector reload e2e test now gives its daemon the scratch HOME as well: it read the developer's real ~/.claude/projects, and on a machine with a big history the backfill held the reload past the test's 20s window. --- CHANGELOG.md | 1 + .../hooks/commonjs-policy-node.e2e.test.ts | 78 +++++++++++++++++++ .../custom-hooks-loader.integration.test.ts | 32 +++++++- __tests__/hooks/loader-utils.test.ts | 28 +++++++ .../tests/collector_reload_e2e.rs | 4 + src/hooks/custom-hooks-loader.ts | 13 +++- src/hooks/loader-utils.ts | 46 ++++++++++- 7 files changed, 196 insertions(+), 6 deletions(-) create mode 100644 __tests__/e2e/hooks/commonjs-policy-node.e2e.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 941374e00..2ad4e857c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Fixes +- A policy file written with `require()` loads and enforces under Node. Every policy's temporary copy was written as `.mjs`, where Node defines no `require`, `module` or `exports`, so a CommonJS policy (or an ES module policy importing a `module.exports` helper) failed to load and the calls it should have denied were allowed. A CommonJS file's copy is now `.cjs`. A new e2e test runs the bundled CLI under `node`; the rest of the suite runs under Bun, which hid this (#1023) - The daemon answers the previous plugin protocol, and clients re-ask an older daemon in its version, so a Hermes or OpenClaw gateway still running the plugin it loaded before an upgrade keeps getting real verdicts instead of denying every call; where the Cloud deployment targets policies at agents, which a request naming no agent would escape, it still fails closed (#1023) - `failproofai update` restarts running Hermes and OpenClaw gateways through their own drain-aware restart (after in-flight work finishes) so they load the updated plugin; only service-managed gateways are touched, and `--no-restart` opts out (#1023) - A batch refused with a key the machine has since replaced (the seconds after a reconnect) is left for the new key instead of being parked as a refusal, so `config --status` no longer reports "the cloud is refusing this machine's key" right after a successful connect (#1023) diff --git a/__tests__/e2e/hooks/commonjs-policy-node.e2e.test.ts b/__tests__/e2e/hooks/commonjs-policy-node.e2e.test.ts new file mode 100644 index 000000000..1890f40e7 --- /dev/null +++ b/__tests__/e2e/hooks/commonjs-policy-node.e2e.test.ts @@ -0,0 +1,78 @@ +// @vitest-environment node +/** + * A CommonJS policy, run by Node. + * + * Every policy's temporary copy used to be `.mjs`, and Node gives an ES module + * no `require`, `module` or `exports`: a policy written with `require()` (or an + * ES module policy importing a `module.exports` helper) threw at load, was + * skipped, and the call it should have denied was allowed. The rest of the e2e + * suite runs the CLI under Bun, which defines `require` in ES modules, so it + * never saw this. Here the CLI is bundled and run by `node`, as an install is. + */ +import { afterAll, describe, expect, it } from "vitest"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; + +const root = mkdtempSync(join(tmpdir(), "fpai-cjs-policy-")); +const home = join(root, "home"); +const dist = join(root, "dist"); +const policies = join(root, "policies"); +const proj = join(root, "proj"); +const repo = resolve(__dirname, "../../.."); +symlinkSync(join(repo, "node_modules"), join(root, "node_modules"), "dir"); +for (const dir of [join(home, ".failproofai"), dist, policies, proj]) mkdirSync(dir, { recursive: true }); + +const builds = [ + ["build", "--target=node", "--format=esm", `--outfile=${join(dist, "cli.mjs")}`, "bin/failproofai.mjs", + "--external", "posthog-node", "--external", "sql.js"], + ["build", "--target=node", "--format=cjs", `--outfile=${join(dist, "index.js")}`, "src/index.ts"], +].map((args) => spawnSync("bun", args, { cwd: repo, encoding: "utf8", timeout: 60000 })); +afterAll(() => rmSync(root, { recursive: true, force: true })); + +writeFileSync(join(policies, "util.js"), `module.exports = { isCurl: (c) => c.includes("curl") };\n`); +writeFileSync(join(policies, "cjs.js"), [ + `const { customPolicies, deny, allow } = require("failproofai");`, + `const { isCurl } = require("./util.js");`, + `customPolicies.add({ name: "cjs-no-curl", match: { events: ["PreToolUse"] },`, + ` fn: async (ctx) => isCurl(String(ctx.toolInput?.command ?? "")) ? deny("cjs says no curl") : allow() });`, +].join("\n")); +writeFileSync(join(policies, "mixed.mjs"), [ + `import { customPolicies, deny, allow } from "failproofai";`, + `import util from "./util.js";`, + `customPolicies.add({ name: "mixed-no-curl", match: { events: ["PreToolUse"] },`, + ` fn: async (ctx) => util.isCurl(String(ctx.toolInput?.command ?? "")) ? deny("mixed says no curl") : allow() });`, +].join("\n")); + +function hook(policyFile: string, command: string) { + writeFileSync(join(home, ".failproofai/policies-config.json"), + JSON.stringify({ enabledPolicies: [], customPoliciesPath: join(policies, policyFile) })); + const stdin = JSON.stringify({ session_id: "s", hook_event_name: "PreToolUse", tool_name: "Bash", + tool_input: { command }, cwd: proj }); + return spawnSync("node", [join(dist, "cli.mjs"), "--hook", "PreToolUse", "--cli", "claude"], { + input: stdin, encoding: "utf8", timeout: 20000, + env: { ...process.env, HOME: home, USERPROFILE: home, FAILPROOFAI_HOME: join(home, ".failproofai"), + FAILPROOFAI_DIST_PATH: dist, FAILPROOFAI_TELEMETRY_DISABLED: "1" }, + }); +} + +describe("a CommonJS policy run by node", () => { + it("builds", () => { + for (const b of builds) expect(b.status, b.stderr).toBe(0); + }); + + it("require('failproofai') and a required module.exports helper load and deny", () => { + const denied = hook("cjs.js", "curl example.com"); + expect(denied.stdout, denied.stderr).toContain("cjs says no curl"); + expect(denied.stderr).not.toContain("require is not defined"); + const allowed = hook("cjs.js", "ls"); + expect(allowed.status).toBe(0); + expect(allowed.stdout).not.toContain("deny"); + }); + + it("an ES module policy importing a module.exports helper loads and denies", () => { + const denied = hook("mixed.mjs", "curl example.com"); + expect(denied.stdout, denied.stderr).toContain("mixed says no curl"); + }); +}); diff --git a/__tests__/hooks/custom-hooks-loader.integration.test.ts b/__tests__/hooks/custom-hooks-loader.integration.test.ts index ddd724409..198b30299 100644 --- a/__tests__/hooks/custom-hooks-loader.integration.test.ts +++ b/__tests__/hooks/custom-hooks-loader.integration.test.ts @@ -7,7 +7,7 @@ * The fixture avoids 'failproofai' imports so ESM rewriting is a no-op. */ import { describe, it, expect, afterEach } from "vitest"; -import { writeFileSync, unlinkSync, existsSync } from "node:fs"; +import { writeFileSync, unlinkSync, existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { loadCustomHooks } from "../../src/hooks/custom-hooks-loader"; @@ -51,4 +51,34 @@ describe("custom-hooks-loader (integration)", () => { expect(result[0].name).toBe("integration-hook"); expect(typeof result[0].fn).toBe("function"); }); + + // Node gives an ES module no `require`. Every policy copy used to be `.mjs`, + // so a CommonJS policy threw at load, was skipped, and its calls were allowed. + // (Bun defines `require` in ES modules, which is why the bun-run e2e passed.) + it("loads a CommonJS policy that requires a CommonJS helper", async () => { + const dir = mkdtempSync(join(tmpdir(), "failproofai-cjs-")); + try { + writeFileSync(join(dir, "helper.js"), `module.exports = { policyName: "cjs-hook" };\n`, "utf8"); + writeFileSync( + join(dir, "policies.js"), + [ + `// import { nothing } from "here" — a comment does not make this ESM`, + `const { policyName } = require("./helper.js");`, + `const KEY = "__failproofai_custom_hooks__";`, + `if (!Array.isArray(globalThis[KEY])) globalThis[KEY] = [];`, + `globalThis[KEY].push({ name: policyName, fn: async () => ({ decision: "allow" }) });`, + ].join("\n"), + "utf8", + ); + clearRegistry(); + + const result = await loadCustomHooks(join(dir, "policies.js")); + + expect(result.map((h) => h.name)).toEqual(["cjs-hook"]); + // The temporary copies are cleaned up, `.cjs` ones included. + expect(readdirSync(dir).filter((f) => f.includes("__failproofai_tmp__"))).toEqual([]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); }); diff --git a/__tests__/hooks/loader-utils.test.ts b/__tests__/hooks/loader-utils.test.ts index b6f3b2da2..01f8604d1 100644 --- a/__tests__/hooks/loader-utils.test.ts +++ b/__tests__/hooks/loader-utils.test.ts @@ -74,3 +74,31 @@ describe("hooks/loader-utils - findDistIndex", () => { expect(result).toBeNull(); }); }); + +describe("hooks/loader-utils - isCommonJsSource", () => { + it("is CommonJS with require or module.exports and no import/export", async () => { + const { isCommonJsSource } = await import("../../src/hooks/loader-utils"); + expect(isCommonJsSource(`const { deny } = require("failproofai");`)).toBe(true); + expect(isCommonJsSource(`module.exports = { a: 1 };`)).toBe(true); + expect(isCommonJsSource(`exports.a = 1;`)).toBe(true); + // Dynamic import() is allowed in CommonJS. + expect(isCommonJsSource(`const m = require("x");\nconst later = import("y");`)).toBe(true); + }); + + it("is not CommonJS once a real import, export or import.meta appears", async () => { + const { isCommonJsSource } = await import("../../src/hooks/loader-utils"); + expect(isCommonJsSource(`import { deny } from "failproofai";`)).toBe(false); + expect(isCommonJsSource(`export const a = 1;\nconst b = require("x");`)).toBe(false); + expect(isCommonJsSource(`const r = createRequire(import.meta.url);\nr("x");`)).toBe(false); + // Neither kind of marker: left as an ES module, as before. + expect(isCommonJsSource(`globalThis.x = 1;`)).toBe(false); + }); + + it("ignores import and require that only appear in comments", async () => { + const { isCommonJsSource } = await import("../../src/hooks/loader-utils"); + expect(isCommonJsSource(`// import x from "y"\nconst a = require("a");`)).toBe(true); + expect(isCommonJsSource(`/* require("a") */\nglobalThis.x = 1;`)).toBe(false); + // A URL's "//" is not a comment start. + expect(isCommonJsSource(`const u = "http://x";\nmodule.exports = u;`)).toBe(true); + }); +}); diff --git a/crates/failproofaid/tests/collector_reload_e2e.rs b/crates/failproofaid/tests/collector_reload_e2e.rs index badadc7cf..97503fb42 100644 --- a/crates/failproofaid/tests/collector_reload_e2e.rs +++ b/crates/failproofaid/tests/collector_reload_e2e.rs @@ -124,6 +124,10 @@ fn spawn_daemon_with(home: &Path, env: &[(&str, &str)]) -> DaemonGuard { let mut child = Command::new(binary_path()) .envs(env.iter().copied()) .env("FAILPROOFAI_HOME", home) + // The agents' own folders resolve from HOME. Left as the developer's, the + // daemon backfilled their real Claude sessions, and on a machine with a + // big history the reload these tests wait for missed its window. + .env("HOME", home) .env( "FAILPROOFAI_DAEMON_SOCKET", home.join("run/failproofaid.sock"), diff --git a/src/hooks/custom-hooks-loader.ts b/src/hooks/custom-hooks-loader.ts index 99e064a93..0d8af028e 100644 --- a/src/hooks/custom-hooks-loader.ts +++ b/src/hooks/custom-hooks-loader.ts @@ -22,6 +22,7 @@ import { findDistIndex, rewriteFileTree, TMP_SUFFIX, + commonJsTmpSuffix, cleanupTmpFiles, isTmpArtifact, sweepStaleTmpArtifacts, @@ -227,7 +228,9 @@ async function loadSingleFile( return null; } - const entryTmp = absPath + tmpSuffix; + // `.cjs` when the policy is CommonJS (see `isCommonJsSource`). + const entryTmp = + tmpFiles.find((f) => f === absPath + commonJsTmpSuffix(tmpSuffix)) ?? absPath + tmpSuffix; const fileUrl = pathToFileURL(entryTmp).href; const hooksBefore = getCustomHooks().length; const semanticBefore = getSemanticRegistrations().length; @@ -282,9 +285,13 @@ async function fingerprintTemporaryTree(tmpFiles: string[], tmpSuffix: string): for (const tmpFile of [...tmpFiles].sort()) { // The generated filenames change per load. Normalize both the logical path // and rewritten import specifiers so identical source graphs hash equally. - hash.update(tmpFile.replaceAll(tmpSuffix, TMP_SUFFIX)); + // A CommonJS source's copy ends `.cjs` (see `isCommonJsSource`). + const cjsSuffix = commonJsTmpSuffix(tmpSuffix); + const normalize = (text: string) => + text.replaceAll(tmpSuffix, TMP_SUFFIX).replaceAll(cjsSuffix, commonJsTmpSuffix(TMP_SUFFIX)); + hash.update(normalize(tmpFile)); const contents = await readFile(tmpFile, "utf8"); - hash.update(contents.replaceAll(tmpSuffix, TMP_SUFFIX)); + hash.update(normalize(contents)); } return hash.digest("hex"); } diff --git a/src/hooks/loader-utils.ts b/src/hooks/loader-utils.ts index 52eaa7b23..772677a5c 100644 --- a/src/hooks/loader-utils.ts +++ b/src/hooks/loader-utils.ts @@ -80,6 +80,33 @@ export async function sweepStaleTmpArtifacts(dir: string, now = Date.now()): Pro return removed; } +/** + * Whether a policy source is CommonJS: no `import` / `export` statement and no + * `import.meta`, but a `require(...)`, `module.exports` or `exports.x`. + * + * Its temporary copy must then be `.cjs`, not `.mjs`. Node gives an ES module + * no `require`, `module` or `exports`, so a CommonJS policy written as `.mjs` + * threw "require is not defined in ES module scope" at load, was skipped, and + * every call it was meant to check was allowed. Bun, which the test suite runs + * under, defines `require` in ES modules too, which is why nothing caught it. + * Comments are ignored, so a commented-out `import` does not decide it. + */ +export function isCommonJsSource(code: string): boolean { + const stripped = code.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:\\])\/\/.*$/gm, "$1"); + if (/^\s*(?:import|export)\b(?!\s*\()/m.test(stripped) || /\bimport\.meta\b/.test(stripped)) return false; + return /\brequire\s*\(|\bmodule\.exports\b|\bexports\.[A-Za-z_$]/.test(stripped); +} + +/** The suffix a CommonJS source's temporary copy gets in place of `tmpSuffix`. */ +export function commonJsTmpSuffix(tmpSuffix: string): string { + return tmpSuffix.replace(/\.mjs$/, ".cjs"); +} + +/** Where a source's temporary copy is written: beside it, `.cjs` for CommonJS. */ +export function tmpPathFor(filePath: string, tmpSuffix: string, commonJs: boolean): string { + return filePath + (commonJs ? commonJsTmpSuffix(tmpSuffix) : tmpSuffix); +} + /** Regex to find local relative import specifiers (ESM). */ const LOCAL_IMPORT_RE = /(?:import\s+(?:[\s\S]*?\s+from\s+)?|export\s+(?:[\s\S]*?\s+from\s+))(['"])(\.\.?\/[^'"]+)\1/g; @@ -259,6 +286,17 @@ export async function rewriteFileTree( const queue: string[] = [entryPath]; const visited = new Set(); const tmpFiles: string[] = []; + // Each file's module kind, read once: it names the file's own copy and every + // specifier that points at it. + const commonJs = new Map(); + const isCommonJsFile = async (path: string): Promise => { + let kind = commonJs.get(path); + if (kind === undefined) { + kind = isCommonJsSource(await readFile(path, "utf-8").catch(() => "")); + commonJs.set(path, kind); + } + return kind; + }; let esmShimUrl: string | null = null; if (distIndex && distUrl) { @@ -288,6 +326,8 @@ export async function rewriteFileTree( } else { code = await readFile(filePath, "utf-8"); } + // From the source as read (the entry's verified bytes), before any rewrite. + if (!commonJs.has(filePath)) commonJs.set(filePath, isCommonJsSource(code)); // Rewrite 'failproofai' or legacy 'claudeye' imports to the ESM shim (or direct CJS for require) if (esmShimUrl) { @@ -317,7 +357,9 @@ export async function rewriteFileTree( if (!visited.has(resolved) && !queue.includes(resolved)) { queue.push(resolved); } - let relPath = relative(dir, resolved + tmpSuffix).split("\\").join("/"); + let relPath = relative(dir, tmpPathFor(resolved, tmpSuffix, await isCommonJsFile(resolved))) + .split("\\") + .join("/"); if (!relPath.startsWith(".")) relPath = "./" + relPath; rewrites.set(specifier, relPath); } @@ -332,7 +374,7 @@ export async function rewriteFileTree( code = code.replace(new RegExp(`"${escaped}"`, "g"), `"${replacement}"`); } - const tmpPath = filePath + tmpSuffix; + const tmpPath = tmpPathFor(filePath, tmpSuffix, commonJs.get(filePath) === true); await writeFile(tmpPath, code, "utf-8"); tmpFiles.push(tmpPath); } From 4a4999a5724b5115f984ae209cb96977a3d7f002 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Fri, 20 Nov 2026 18:20:00 +0530 Subject: [PATCH 31/41] feat(daemon): log an error when hook data stops while the rest of the collector works A new hook-watch task compares hook data with everything else every five minutes and logs an ERROR, which the error roll-up carries to Cloud, when: - an agent's sessions show tool calls made in the last 10 minutes and none reached failproofai's hooks: its hooks are not installed or not firing, so those calls ran unchecked; - hook calls were answered and the hook activity source recorded nothing; - hook batches have waited 15 minutes while other events deliver; - Cloud refused hook batches. Tool calls are counted where every transcript event passes, the spool writer, and only when stamped within 15 minutes, so the backfill after setup never counts as activity. Hook calls are counted per agent by the socket server, health probes excepted. Each problem needs two checks running, repeats hourly while it lasts and is logged once at INFO when it clears. Not started when hook collection is off. FAILPROOFAI_HOOK_WATCH_INTERVAL_MS shortens the pause between checks, for tests. --- CHANGELOG.md | 1 + crates/failproofaid/src/hook_watch.rs | 779 ++++++++++++++++++++++++++ crates/failproofaid/src/main.rs | 23 + crates/failproofaid/src/server.rs | 16 +- crates/fpai-collect/src/health.rs | 46 +- crates/fpai-collect/src/spool.rs | 9 + 6 files changed, 867 insertions(+), 7 deletions(-) create mode 100644 crates/failproofaid/src/hook_watch.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ad4e857c..5165b3576 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Fixes +- The daemon logs an ERROR when hook data stops reaching Cloud while the rest of the collector keeps working: an agent whose sessions show tool calls in the last 10 minutes with none of them reaching failproofai's hooks (its hooks not installed or not firing, so those calls ran unchecked), hook calls answered with nothing recorded by the hook activity source, hook batches waiting 15 minutes while other events deliver, or hook batches Cloud refused. Only tool calls an agent is making now count, so the backfill after setup never raises it. The line reaches Cloud with the daemon's error roll-up, and clearing is logged once. Checked every 5 minutes, repeated hourly while it lasts, and not when hook collection is off (#1023) - A policy file written with `require()` loads and enforces under Node. Every policy's temporary copy was written as `.mjs`, where Node defines no `require`, `module` or `exports`, so a CommonJS policy (or an ES module policy importing a `module.exports` helper) failed to load and the calls it should have denied were allowed. A CommonJS file's copy is now `.cjs`. A new e2e test runs the bundled CLI under `node`; the rest of the suite runs under Bun, which hid this (#1023) - The daemon answers the previous plugin protocol, and clients re-ask an older daemon in its version, so a Hermes or OpenClaw gateway still running the plugin it loaded before an upgrade keeps getting real verdicts instead of denying every call; where the Cloud deployment targets policies at agents, which a request naming no agent would escape, it still fails closed (#1023) - `failproofai update` restarts running Hermes and OpenClaw gateways through their own drain-aware restart (after in-flight work finishes) so they load the updated plugin; only service-managed gateways are touched, and `--no-restart` opts out (#1023) diff --git a/crates/failproofaid/src/hook_watch.rs b/crates/failproofaid/src/hook_watch.rs new file mode 100644 index 000000000..691cba32b --- /dev/null +++ b/crates/failproofaid/src/hook_watch.rs @@ -0,0 +1,779 @@ +//! Says so, as an ERROR in `daemon.log`, when hook data stops reaching Cloud +//! while the rest of the collector keeps working. +//! +//! Hook data takes its own route. The worker answers each hook and writes an +//! activity row; the `hook-activity` source turns rows into events and spools +//! them as `hooks-*.jsonl` batches; the uploader sends those with every other +//! source's batches. Transcripts take a different route to the same uploader. +//! So the collector can look healthy, transcripts arriving and delivery +//! green, while not one policy check reaches Cloud: the activity store is +//! unwritable, the source reads the wrong directory, or Cloud refuses the hook +//! batches alone. Nothing on the machine said so. +//! +//! Every [`CHECK_EVERY`] this compares three things against the last check: +//! +//! - **Collected.** Hook calls the socket server answered ([`note_answered`]) +//! against events the `hook-activity` source produced. Calls answered in two +//! checks running, with no events from the source in either, is +//! [`Problem::NotCollected`]. Two, so one slow poll is not an alarm. +//! - **Delivered.** A `hooks-*` batch waiting in the spool for longer than +//! [`STALE_AFTER`] while the uploader has delivered something within it is +//! [`Problem::NotDelivered`]: delivery works, hook batches are not going. +//! - **Refused.** More `hooks-*` batches parked in `failed/` than at the last +//! check is [`Problem::Refused`]. +//! - **Hooked.** Per agent: tool calls its transcripts show it making now +//! (`live_tool_calls` in collector health, counted at the spool, so a +//! backfill re-reading last week does not count) against hook calls that +//! agent made. Tool calls across two checks running with no hook call from +//! it in either is [`Problem::NotHooked`]: the agent is working, its +//! sessions are being collected, and its hooks are not firing. That is how a +//! config whose schema changed under it, a plugin that failed to load or a +//! project with hooks turned off looks from here, and every one of those +//! tool calls ran unchecked. +//! +//! Each is logged at ERROR when it starts and again every [`REPEAT_EVERY`] +//! while it lasts, so logship's error roll-up carries it to Cloud, and at INFO +//! once when it clears. Health probes are not hook calls and are not counted. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +/// How often the counters are compared. +pub const CHECK_EVERY: Duration = Duration::from_secs(5 * 60); +/// How long a hook batch may wait in the spool while other batches deliver. +pub const STALE_AFTER: Duration = Duration::from_secs(15 * 60); +/// How often a problem that persists is logged again. +pub const REPEAT_EVERY: Duration = Duration::from_secs(60 * 60); +/// Fewer answered calls than this in a check are not evidence of anything. +const MIN_ANSWERED: u64 = 5; +/// Fewer live tool calls than this across two checks prove no hook is missing. +const MIN_TOOL_CALLS: u64 = 3; + +/// Hook calls the socket server answered with a verdict, since start. +static ANSWERED: AtomicU64 = AtomicU64::new(0); +/// The same, per agent (the request's `cli` / `integration`). +static ANSWERED_BY: Mutex> = Mutex::new(BTreeMap::new()); + +/// Count one answered hook call from `agent`. Not a health probe: the worker +/// writes no activity row for one, so counting it would report a gap that is +/// not there. +pub fn note_answered(agent: &str, stdin: &str) { + if stdin.contains("failproofai-health-probe") { + return; + } + ANSWERED.fetch_add(1, Ordering::Relaxed); + if let Ok(mut by) = ANSWERED_BY.lock() { + *by.entry(agent.to_string()).or_default() += 1; + } +} + +/// One agent's counters, both since start. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct AgentCounts { + /// Live tool calls its transcripts showed. + pub tool_calls: u64, + /// Hook calls it made that the daemon answered. + pub answered: u64, +} + +/// What one check reads. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Sample { + /// Unix seconds. + pub now: u64, + /// Hook calls answered since start. + pub answered: u64, + /// Events the `hook-activity` source produced since it started. + pub hook_events: u64, + /// The source's last poll error, if its last poll failed. + pub hook_error: Option, + /// Unix seconds of the last upload Cloud accepted; 0 for none. + pub delivered_at: u64, + /// `hooks-*` batches waiting in the spool, and the oldest one's age. + pub waiting: usize, + pub oldest_waiting_secs: u64, + /// `hooks-*` batches parked in `failed/`. + pub parked: usize, + /// Per traced agent. + pub agents: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum Kind { + NotCollected, + NotDelivered, + Refused, + NotHooked(String), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Problem { + NotCollected { + answered: u64, + minutes: u64, + error: Option, + }, + NotDelivered { + waiting: usize, + minutes: u64, + }, + Refused { + new: usize, + parked: usize, + }, + NotHooked { + agent: String, + tool_calls: u64, + minutes: u64, + }, +} + +impl Problem { + pub fn kind(&self) -> Kind { + match self { + Problem::NotCollected { .. } => Kind::NotCollected, + Problem::NotDelivered { .. } => Kind::NotDelivered, + Problem::Refused { .. } => Kind::Refused, + Problem::NotHooked { agent, .. } => Kind::NotHooked(agent.clone()), + } + } + + /// The `daemon.log` line. + pub fn line(&self) -> String { + match self { + Problem::NotCollected { + answered, + minutes, + error, + } => { + let mut line = format!( + "hook checks are not reaching Cloud: {answered} hook calls answered in the last \ + {minutes} minutes, none recorded by the hook activity source" + ); + if let Some(error) = error { + line.push_str(&format!(" (last error: {error})")); + } + line + } + Problem::NotDelivered { waiting, minutes } => format!( + "hook checks are not reaching Cloud: {waiting} hook batches have waited \ + {minutes} minutes while other events deliver" + ), + Problem::Refused { new, parked } => format!( + "hook checks are not reaching Cloud: Cloud refused {new} hook batches \ + ({parked} parked in failed/)" + ), + Problem::NotHooked { + agent, + tool_calls, + minutes, + } => format!( + "{agent}: {tool_calls} tool calls in the last {minutes} minutes and none reached \ + failproofai's hooks, so they ran unchecked: its hooks are not installed or not firing" + ), + } + } +} + +/// What a check decided. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Verdict { + /// Log at ERROR. + Raise(Problem), + /// Was raised, is over: log at INFO. + Cleared(Kind), +} + +/// The state between checks. +#[derive(Debug, Default)] +pub struct Watch { + prev: Option, + /// Checks running in which calls were answered and the source produced nothing. + quiet_checks: u32, + /// Answered calls across those checks. + quiet_answered: u64, + /// When each active problem was last logged (Unix seconds). + raised: Vec<(Kind, u64)>, + /// Each agent's (tool calls, answered) in the previous check. + last_agent_deltas: BTreeMap, +} + +impl Watch { + pub fn check(&mut self, s: Sample) -> Vec { + let Some(prev) = self.prev.replace(s.clone()) else { + return Vec::new(); // the first check is the baseline + }; + let mut found: Vec = Vec::new(); + + let answered = s.answered.saturating_sub(prev.answered); + let produced = s.hook_events.saturating_sub(prev.hook_events); + if produced > 0 || answered < MIN_ANSWERED { + self.quiet_checks = 0; + self.quiet_answered = 0; + } else { + self.quiet_checks += 1; + self.quiet_answered += answered; + } + if self.quiet_checks >= 2 { + found.push(Problem::NotCollected { + answered: self.quiet_answered, + minutes: u64::from(self.quiet_checks) * CHECK_EVERY.as_secs() / 60, + error: s.hook_error.clone(), + }); + } + + let others_deliver = + s.delivered_at > 0 && s.now.saturating_sub(s.delivered_at) < STALE_AFTER.as_secs(); + if s.waiting > 0 && s.oldest_waiting_secs >= STALE_AFTER.as_secs() && others_deliver { + found.push(Problem::NotDelivered { + waiting: s.waiting, + minutes: s.oldest_waiting_secs / 60, + }); + } + + let mut deltas = BTreeMap::new(); + for (agent, now) in &s.agents { + let before = prev.agents.get(agent).copied().unwrap_or_default(); + let tools = now.tool_calls.saturating_sub(before.tool_calls); + let answered = now.answered.saturating_sub(before.answered); + let (prev_tools, prev_answered) = + self.last_agent_deltas.get(agent).copied().unwrap_or((0, 0)); + // Two checks, so a tool call spooled just before its hook is + // counted (hooks fire before the call, transcripts after) cannot + // look like a missing hook. + if self.last_agent_deltas.contains_key(agent) + && tools > 0 + && tools + prev_tools >= MIN_TOOL_CALLS + && answered + prev_answered == 0 + { + found.push(Problem::NotHooked { + agent: agent.clone(), + tool_calls: tools + prev_tools, + minutes: 2 * CHECK_EVERY.as_secs() / 60, + }); + } + deltas.insert(agent.clone(), (tools, answered)); + } + self.last_agent_deltas = deltas; + + let refused = s.parked > prev.parked; + if refused { + found.push(Problem::Refused { + new: s.parked - prev.parked, + parked: s.parked, + }); + } + + let mut out = Vec::new(); + // Cleared: raised before, not found now. A refusal is an event, not a + // state, so it never "clears". + let now_kinds: Vec = found.iter().map(Problem::kind).collect(); + let agents_working: Vec<&String> = self + .last_agent_deltas + .iter() + .filter(|(_, (tools, answered))| *tools > 0 || *answered > 0) + .map(|(agent, _)| agent) + .collect(); + self.raised.retain(|(kind, _)| { + let still = now_kinds.contains(kind) + || *kind == Kind::Refused + // An unhooked agent that has gone quiet is not fixed: only a + // hook call from it, or it working again without one, decides. + || matches!(kind, Kind::NotHooked(agent) if !agents_working.contains(&agent)); + if !still { + out.push(Verdict::Cleared(kind.clone())); + } + still + }); + for problem in found { + let kind = problem.kind(); + match self.raised.iter_mut().find(|(k, _)| *k == kind) { + Some((_, at)) + if kind != Kind::Refused + && s.now.saturating_sub(*at) < REPEAT_EVERY.as_secs() => {} + Some((_, at)) => { + *at = s.now; + out.push(Verdict::Raise(problem)); + } + None => { + self.raised.push((kind, s.now)); + out.push(Verdict::Raise(problem)); + } + } + } + out + } +} + +/// `hooks-*` batch files in `dir`, and the oldest one's age in seconds. +fn hook_batches(dir: &Path, now: SystemTime) -> (usize, u64) { + let Ok(entries) = std::fs::read_dir(dir) else { + return (0, 0); + }; + let mut count = 0; + let mut oldest = 0; + for entry in entries.flatten() { + let name = entry.file_name(); + let name = name.to_string_lossy(); + if !(name.starts_with("hooks-") && name.contains(".jsonl")) { + continue; + } + count += 1; + let age = entry + .metadata() + .and_then(|m| m.modified()) + .ok() + .and_then(|at| now.duration_since(at).ok()) + .map_or(0, |d| d.as_secs()); + oldest = oldest.max(age); + } + (count, oldest) +} + +fn sample(health: &fpai_collect::Health, spool_dir: &Path, failed_dir: &Path) -> Sample { + let snapshot = health.snapshot(); + let hooks = snapshot.sources.get("hooks"); + let now = SystemTime::now(); + let (waiting, oldest_waiting_secs) = hook_batches(spool_dir, now); + // Only finished batches wait: a `.tmp` is still being written. + let (parked, _) = hook_batches(failed_dir, now); + let mut agents: BTreeMap = BTreeMap::new(); + for (source, h) in &snapshot.sources { + // `hermes: