diff --git a/CHANGELOG.md b/CHANGELOG.md index 27f07145c..38222b13f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,38 @@ # Changelog -## 1.0.17-beta.0 — 2026-11-24 +## 1.0.17 — 2026-11-24 ### Fixes - Release workflows now open the version-bump pull request themselves, using the job's own token, when the repository lets GitHub Actions create pull requests. When it does not, the run prints the pre-filled link as a warning and the release still succeeds. A re-run reuses an open bump pull request instead of opening a second one (#1052) +- The daemon sends no daemon log while the org has troubleshooting off: when Cloud's policy poll says `machineLogs: false` it drops what was pending (an open log request included) and queues nothing until it is back on, and keeps nothing for context while it is. The off state is kept beside daemon.log, so a daemon restarted while it is off (cleanly or not) sends nothing before its first poll. Turning it back on sets a floor (kept there too): no later upload carries a line older than it, so an incident or a requested tail never delivers what was logged while it was off. A Cloud that sends no such key means on, as before (#1033) +- 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. A problem clears only on evidence it is fixed (a hook call from that agent, events from the hook source, the stuck batch gone), never because traffic fell, and its clearing is logged once. Checked every 5 minutes, repeated hourly while it lasts, and not when hook collection is off (#1033) +- 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`; which a file is gets decided the way Node decides an ambiguous `.js` file, by compiling it as CommonJS, and only for a file Node itself refused to load as an ES module for being CommonJS, one file at a time: a file Node loaded as an ES module, in a mixed graph included, is never reinterpreted, whatever its comments or strings say. On Node before 22.12, which cannot `require()` an ES module, a CommonJS policy's required `module.exports` helper is converted the same way, from the file Node's `ERR_REQUIRE_ESM` names. A new e2e test runs the bundled CLI under `node`; the rest of the suite runs under Bun, which hid this (#1033) +- 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 (#1033) +- `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 (#1033) +- 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 (#1033) +- 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 (#1033) +- `config --status` counts Cloud Jev-only deployments in its policies row; it showed "None installed" beside a deployment the line under it called enforcing (#1033) +- 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" (#1033) +- The "no pack is installed" warning is logged once per process instead of on every hook call, which buried the daemon log (#1033) +- 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 (#1033) +- 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 (#1033) +- 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 (#1033) +- The collector manager and cloud policy sync restart after a panic instead of stopping silently while the daemon keeps answering hooks (#1033) +- 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)" (#1033) +- 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 (#1033) +- 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/` (#1033) +- 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 (#1033) +- 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 (#1033) +- 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 (#1033) +- 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 (#1033) +- Setup's summary on a Cloud-managed machine says "Deploy from Cloud" instead of pointing at installing a pack (#1033) +- 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` (#1033) +- A desired-state response the daemon refuses (an unknown `schemaVersion`, or a payload that does not decode) no longer applies its `machineLogs` or `logRequest` first: it used to clear an org's troubleshooting-off and start a log upload on the way to being rejected; the last valid answer now stands (#1033) + +### Dependencies + +- `crewai` 1.15.42 → 1.15.44 in the Python SDK's dev/test lockfile (#1033) ## 1.0.16-beta.0 — 2026-11-24 diff --git a/CLAUDE.md b/CLAUDE.md index 87cd9a9fb..18a2e9a89 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: @@ -909,13 +914,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/Cargo.lock b/Cargo.lock index 428763e87..ffe0db5af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -298,7 +298,7 @@ dependencies = [ [[package]] name = "failproofaid" -version = "1.0.17-beta.0" +version = "1.0.17" dependencies = [ "fpai-collect", "fpai-ipc", @@ -361,7 +361,7 @@ dependencies = [ [[package]] name = "fpai-collect" -version = "1.0.17-beta.0" +version = "1.0.17" dependencies = [ "axum", "getrandom 0.4.3", @@ -382,7 +382,7 @@ dependencies = [ [[package]] name = "fpai-ipc" -version = "1.0.17-beta.0" +version = "1.0.17" dependencies = [ "libc", "proptest", diff --git a/Cargo.toml b/Cargo.toml index d0a89244c..fd6017f4a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "1.0.17-beta.0" +version = "1.0.17" edition = "2024" license-file = "LICENSE" repository = "https://github.com/FailproofAI/failproofai" 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..839bf046f --- /dev/null +++ b/__tests__/e2e/hooks/commonjs-policy-node.e2e.test.ts @@ -0,0 +1,172 @@ +// @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")); + +// Review F10: an ES module helper whose STRINGS mention require(), with its +// export on the same line as other statements, imported by an ES module +// policy. A text-based check called the helper CommonJS and the policy was +// skipped, so curl was allowed. +writeFileSync(join(policies, "esm-helper.mjs"), + `const command = "curl"; const example = "require()"; export default command;\n`); +writeFileSync(join(policies, "esm-literal.mjs"), [ + `import { customPolicies, deny, allow } from "failproofai";`, + `import command from "./esm-helper.mjs";`, + `customPolicies.add({ name: "esm-literal-no-curl", match: { events: ["PreToolUse"] },`, + ` fn: async (ctx) => String(ctx.toolInput?.command ?? "").includes(command) ? deny("esm literal says no curl") : allow() });`, +].join("\n")); +// And the reverse: CommonJS whose template literals contain import.meta and a +// line starting with `export`. +writeFileSync(join(policies, "cjs-literal.js"), [ + "const { customPolicies, deny, allow } = require(\"failproofai\");", + "const note = `import.meta is not used here`;", + "const doc = `", + "export default nothing", + "`;", + "customPolicies.add({ name: \"cjs-literal-no-curl\", match: { events: [\"PreToolUse\"] },", + " fn: async (ctx) => String(ctx.toolInput?.command ?? \"\").includes(\"curl\") ? deny(\"cjs literal says no curl \" + note.length + doc.length) : allow() });", +].join("\n")); + +// Review F10 (round 3): a valid ES module with no import/export at all, whose +// only CommonJS "hints" are a comment and a template string. Run as CommonJS it +// is sloppy-mode, `strict` is false and curl is allowed; it must stay an ES +// module, where it denies. +writeFileSync(join(policies, "esm-hints.mjs"), [ + "// Ported from an old version that did: const { deny } = require(\"failproofai\");", + "const note = `module.exports used to be how this was shared`;", + "const KEY = \"__failproofai_custom_hooks__\";", + "if (!Array.isArray(globalThis[KEY])) globalThis[KEY] = [];", + "const strict = (function () { return this === undefined; })();", + "globalThis[KEY].push({ name: \"esm-hints-no-curl\", match: { events: [\"PreToolUse\"] },", + " fn: async (ctx) => strict && String(ctx.toolInput?.command ?? \"\").includes(\"curl\")", + " ? { decision: \"deny\", reason: \"esm hints says no curl \" + note.length } : { decision: \"allow\" } });", +].join("\n")); + +// Review F10 (round 4): a MIXED graph. The entry imports a module.exports +// helper, so its load is retried with CommonJS copies; it also imports, for its +// side effect, an ES module whose only CommonJS hints are a comment and a +// template. That one must stay an ES module (strict), or curl is allowed. +writeFileSync(join(policies, "strict-flag.js"), [ + "// Was: module.exports.strict = ...; see require() notes in the README.", + "const note = `exports moved to the ES module below`;", + "globalThis.__fpaiStrictFlag = (function () { return this === undefined; })() && note.length > 0;", +].join("\n")); +writeFileSync(join(policies, "mixed-graph.mjs"), [ + `import { customPolicies, deny, allow } from "failproofai";`, + `import util from "./util.js";`, + `import "./strict-flag.js";`, + `customPolicies.add({ name: "mixed-graph-no-curl", match: { events: ["PreToolUse"] },`, + ` fn: async (ctx) => globalThis.__fpaiStrictFlag === true && util.isCurl(String(ctx.toolInput?.command ?? ""))`, + ` ? deny("mixed graph says no curl") : allow() });`, +].join("\n")); + +// Node before 22.12 cannot require() an ES module (ERR_REQUIRE_ESM), and 20.9 +// is the minimum supported. Where the running node has require(esm), this flag +// turns it off so that path is tested on whatever node CI has. +const noRequireEsm = + spawnSync("node", ["--no-experimental-require-module", "-e", ""], { encoding: "utf8" }).status === 0 + ? ["--no-experimental-require-module"] + : []; + +function hook(policyFile: string, command: string, nodeArgs: 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", [...nodeArgs, 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("a required module.exports helper loads where node cannot require() an ES module", () => { + const denied = hook("cjs.js", "curl example.com", noRequireEsm); + expect(denied.stdout, denied.stderr).toContain("cjs says no curl"); + expect(denied.stderr).not.toContain("require() of ES Module"); + const allowed = hook("cjs.js", "ls", noRequireEsm); + expect(allowed.status).toBe(0); + expect(allowed.stdout).not.toContain("deny"); + }); + + it("an ES module with only comment and template CommonJS hints keeps ES module semantics", () => { + const denied = hook("esm-hints.mjs", "curl example.com"); + expect(denied.stdout, denied.stderr).toContain("esm hints says no curl"); + }); + + it("an ES module helper that mentions require() in a string stays an ES module", () => { + const denied = hook("esm-literal.mjs", "curl example.com"); + expect(denied.stdout, denied.stderr).toContain("esm literal says no curl"); + }); + + it("CommonJS with import.meta and export inside template literals stays CommonJS", () => { + const denied = hook("cjs-literal.js", "curl example.com"); + expect(denied.stdout, denied.stderr).toContain("cjs literal says no curl"); + }); + + it("a mixed graph turns only the helper Node refused into CommonJS", () => { + const denied = hook("mixed-graph.mjs", "curl example.com"); + expect(denied.stdout, denied.stderr).toContain("mixed graph says no curl"); + }); + + 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__/fixtures/hermes-native-plugin-check.py b/__tests__/fixtures/hermes-native-plugin-check.py index 51e852b41..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) @@ -1631,7 +1637,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 +1707,94 @@ 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]], 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" + policies.mkdir() + if schema is not None: + (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)} + with patch.dict("os.environ", env): + 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_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_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="{" + ) + 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"}, + ]) + 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/config-status.test.ts b/__tests__/hooks/config-status.test.ts index 81046264b..ad03ef6dc 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, @@ -295,6 +296,25 @@ 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("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"); @@ -359,7 +379,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 +453,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 +482,19 @@ 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"); + // 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", () => { @@ -592,6 +634,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/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/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/custom-hooks-loader.test.ts b/__tests__/hooks/custom-hooks-loader.test.ts index 477c50185..23946dfd1 100644 --- a/__tests__/hooks/custom-hooks-loader.test.ts +++ b/__tests__/hooks/custom-hooks-loader.test.ts @@ -9,6 +9,8 @@ vi.mock("../../src/hooks/hook-logger", () => ({ vi.mock("../../src/hooks/custom-hooks-registry", () => ({ getCustomHooks: vi.fn(() => []), + // Read before every load, so a failed ES-module attempt can be rolled back. + getSemanticRegistrations: vi.fn(() => []), clearCustomHooks: vi.fn(), })); diff --git a/__tests__/hooks/daemon-client.test.ts b/__tests__/hooks/daemon-client.test.ts index 4077f4b29..c8abcb6ef 100644 --- a/__tests__/hooks/daemon-client.test.ts +++ b/__tests__/hooks/daemon-client.test.ts @@ -51,17 +51,28 @@ 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-")); 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"); + // 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())); } @@ -227,28 +238,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 +274,84 @@ 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 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("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"), "{"); + 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) => { + 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/daemon-service.test.ts b/__tests__/hooks/daemon-service.test.ts index 35d2155df..6dd7c5967 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( @@ -314,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 @@ -648,6 +649,91 @@ 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, "dist", "worker.mjs"); + mkdirSync(dirname(script), { recursive: true }); + 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, 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; + rmSync(unitDir, { recursive: true, force: true }); + } + }); + + 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("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. + 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")); + + 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", 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, allowed)).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; @@ -1253,6 +1339,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 }; @@ -1288,6 +1376,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/__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/__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/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/__tests__/hooks/gateway-restart.test.ts b/__tests__/hooks/gateway-restart.test.ts new file mode 100644 index 000000000..cc6bbaa0f --- /dev/null +++ b/__tests__/hooks/gateway-restart.test.ts @@ -0,0 +1,197 @@ +/** + * `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 { chmodSync, closeSync, mkdtempSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + openRestartLog, + openclawRestartLines, + restartHermesGateway, + restartOpenClawGateway, + restartOpenClawGateways, + openclawProfileEnv, + 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", + ]); + }); +}); + +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 { 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(); + }); + + 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; + } + }); +}); + +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/__tests__/hooks/handler.test.ts b/__tests__/hooks/handler.test.ts index d9934a588..ca426c8d3 100644 --- a/__tests__/hooks/handler.test.ts +++ b/__tests__/hooks/handler.test.ts @@ -195,6 +195,31 @@ 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).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 () => { + 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/hermes-update.test.ts b/__tests__/hooks/hermes-update.test.ts index f3d03167f..75c7cd94f 100644 --- a/__tests__/hooks/hermes-update.test.ts +++ b/__tests__/hooks/hermes-update.test.ts @@ -291,6 +291,27 @@ 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/); + // 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 () => { + 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/__tests__/hooks/loader-utils.test.ts b/__tests__/hooks/loader-utils.test.ts index b6f3b2da2..1c216c485 100644 --- a/__tests__/hooks/loader-utils.test.ts +++ b/__tests__/hooks/loader-utils.test.ts @@ -74,3 +74,46 @@ 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); + // A URL's "//" is not a comment start. + expect(isCommonJsSource(`const u = "http://x";\nmodule.exports = u;`)).toBe(true); + }); + + // Review F10: what text says is never syntax, and an export after a + // semicolon is still an export. + it("decides on syntax, not on text inside strings and templates", async () => { + const { isCommonJsSource } = await import("../../src/hooks/loader-utils"); + expect( + isCommonJsSource(`const command = "curl"; const example = "require()"; export default command;`), + ).toBe(false); + expect(isCommonJsSource("const a = 1; export { a };")).toBe(false); + expect(isCommonJsSource("const r = require('x');\nconst t = `import.meta`;\nmodule.exports = r;")).toBe(true); + expect(isCommonJsSource("const doc = `\nexport default nothing\n`;\nmodule.exports = { doc };")).toBe(true); + expect(isCommonJsSource("const s = 'import x from \"y\"';\nexports.s = s;")).toBe(true); + expect(isCommonJsSource("#!/usr/bin/env node\nconst a = require('a');")).toBe(true); + // Not valid either way: left an ES module, so its own error is reported. + expect(isCommonJsSource("const a = require('a'); )")).toBe(false); + }); +}); 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/openclaw-plugin.test.ts b/__tests__/hooks/openclaw-plugin.test.ts index 90a5ed025..ef04f99df 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(() => { @@ -222,7 +225,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 +249,74 @@ 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 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("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 { + 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); @@ -460,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/__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/policies-listing.test.ts b/__tests__/hooks/policies-listing.test.ts index e5dd1534e..ee5d6a42f 100644 --- a/__tests__/hooks/policies-listing.test.ts +++ b/__tests__/hooks/policies-listing.test.ts @@ -460,6 +460,31 @@ 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"); + }); + + 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/__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/__tests__/hooks/update-run.test.ts b/__tests__/hooks/update-run.test.ts new file mode 100644 index 000000000..744d6121d --- /dev/null +++ b/__tests__/hooks/update-run.test.ts @@ -0,0 +1,216 @@ +/** + * 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, + 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") { + 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(); + }); +}); + +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", + ]); + }); +}); + +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 8289ca364..e79a804d7 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); @@ -1143,13 +1149,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( @@ -1162,107 +1171,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. - let hermesOk = true; - let hermesMigrated = 0; - try { - const { runHermesUpdateMigration } = await import("../src/hooks/hermes-update"); - const svc = await import("../src/hooks/daemon-service"); - const hermesResult = await runHermesUpdateMigration({ - daemonSupportsPolicyEvaluation: () => svc.probeDaemonPolicyEvaluation(), - }); - 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; - } - - 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); @@ -2074,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( {}, { @@ -2097,6 +2044,35 @@ 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, setupGatewayLine, restartNewlyPlugged } = + await import("../src/hooks/update-run"); + const { screenKit, colorsEnabled } = await import("../src/hooks/tui"); + const kit = screenKit({ color: colorsEnabled(process.stdout) }); + if (!setupNeedsUpdateSteps(version)) { + // Already updated on this version: only a profile this run plugged in + // (one created since) has a gateway still running without the plugin. + const gateway = setupGatewayLine(await restartNewlyPlugged(pluggedBefore).catch(() => [])); + if (gateway) process.stdout.write(`${gateway.ok ? kit.ok(gateway.text) : kit.caution(gateway.text)}\n`); + } else { + const run = await runUpdateSteps({ layout: false, daemon: false, restart: true }); + // One line at most, in update's own words; a Hermes failure keeps its + // existing ✕ line so it is not lost. + const gateway = setupGatewayLine(run.restarts); + const out = [ + ...run.lines.filter((l) => l.startsWith("✕")), + ...(gateway ? [gateway.ok ? kit.ok(gateway.text) : kit.caution(gateway.text)] : []), + ]; + if (out.length > 0) process.stdout.write(`${out.join("\n")}\n`); + if (run.ok) markUpdated(version); + else updateExit = 1; + } + } await warnTokenOnArgv(); await track("cli_configure_invoked", { applied: result.applied, @@ -2115,7 +2091,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/crates/PROTOCOL.md b/crates/PROTOCOL.md index 6ac9fedbf..c07b936cc 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`) @@ -102,11 +104,28 @@ 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. + +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 +optional fields; raise `MIN_PROTOCOL_VERSION` only when an older request can no +longer be answered safely. ## Peer verification @@ -126,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/audit_lane.rs b/crates/failproofaid/src/audit_lane.rs index ce66835f4..0b37f68f1 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,12 @@ impl Lane { return; } self.announced = Some(state); - eprintln!("[failproofaid] {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}"), + } } } @@ -601,13 +606,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 +675,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 d9b1c7c94..becfb4d6e 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}"); } } @@ -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) @@ -870,41 +878,76 @@ impl CloudClient { .json::() .map_err(|err| PollFailure::payload(format!("invalid desired-state response: {err}"))) .and_then(|raw| { - // THE VERSION IS CHECKED BEFORE THE FIELDS, which is the whole - // point of having one. `SUPPORTED_SCHEMA_VERSIONS` accepts 1 as - // well, and its comment says that is "for files on DISK, never for - // a server" — but nothing enforced the second half, so this path - // took a v1 response. - // - // Decoding straight into `DesiredState` would also reject a v1 - // payload, since that type has no aliases for the old spelling — - // but on the WRONG grounds: serde reports "missing field - // `deployment`", which sends an operator hunting a malformed - // 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. - let version = raw.get("schemaVersion").and_then(serde_json::Value::as_u64); - match version { - Some(v) if v == u64::from(DESIRED_STATE_SCHEMA_VERSION) - || v == u64::from(SCOPED_DESIRED_STATE_SCHEMA_VERSION) => {} - Some(v) => { - return Err(PollFailure::payload(format!( - "server sent desired-state schemaVersion {v} but this daemon \ - speaks {DESIRED_STATE_SCHEMA_VERSION} or {SCOPED_DESIRED_STATE_SCHEMA_VERSION} — upgrade whichever half is behind" - ))); - } - None => { - return Err(PollFailure::payload( - "desired-state response has no schemaVersion field".to_string(), - )); - } + // Applied only once the whole response is known good: a response + // this daemon refuses (an unknown schemaVersion, a payload that + // does not decode) must not turn troubleshooting back on or start + // an upload, so the last valid answer keeps standing. + let (desired, consent) = decode_desired_state(raw)?; + // The org's troubleshooting switch: `machineLogs: false` means + // send no daemon log (logship.rs). Absent, from a Cloud with it + // on or one that predates the key, means send. + crate::logship::set_cloud_allows(consent.machine_logs != Some(false)); + // An operator asked for this machine's logs (logship.rs). + if let Some(id) = consent.log_request { + crate::logship::note_request(&id); } - serde_json::from_value::(raw).map_err(|err| { - PollFailure::payload(format!("invalid desired-state response: {err}")) - }) + Ok(desired) }) } + /// 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. /// @@ -1073,6 +1116,11 @@ 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). @@ -1080,91 +1128,94 @@ pub fn spawn_maintenance( // 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, || { + 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)) + { + tracing::warn!("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(); + tracing::info!( + "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) => tracing::info!( + "cloud enrolment removed; cloud-managed policies deactivated" + ), + Ok(false) => {} + Err(err) => { + tracing::warn!("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) { + tracing::info!( + "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 - }, - ); - } + }) }) } @@ -1209,11 +1260,12 @@ fn maintenance_tick( let reconciled = poll_once_guarded(store, &cloud, withdrawn); if !withdrawn() { repair(store, withdrawn); + cloud.ship_logs(); } reconciled } Err(err) => { - eprintln!("[failproofaid] cloud enrolment error: {err}"); + tracing::warn!("cloud enrolment error: {err}"); repair(store, &|| false); false } @@ -1221,12 +1273,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}" ), } } @@ -1237,7 +1289,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}"); } } @@ -1256,21 +1308,75 @@ 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}"), } } +/// The log-shipping fields of a desired-state response (logship.rs). +#[derive(Debug, Default, PartialEq, Eq)] +struct LogConsent { + machine_logs: Option, + log_request: Option, +} + +/// Validates a desired-state response and decodes it. The log-shipping fields +/// come back only with a response that was accepted, so a refused one has +/// nothing to apply. +fn decode_desired_state(raw: serde_json::Value) -> Result<(DesiredState, LogConsent), PollFailure> { + // THE VERSION IS CHECKED BEFORE THE FIELDS, which is the whole + // point of having one. `SUPPORTED_SCHEMA_VERSIONS` accepts 1 as + // well, and its comment says that is "for files on DISK, never for + // a server" — but nothing enforced the second half, so this path + // took a v1 response. + // + // Decoding straight into `DesiredState` would also reject a v1 + // payload, since that type has no aliases for the old spelling — + // but on the WRONG grounds: serde reports "missing field + // `deployment`", which sends an operator hunting a malformed + // 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. + let version = raw.get("schemaVersion").and_then(serde_json::Value::as_u64); + match version { + Some(v) + if v == u64::from(DESIRED_STATE_SCHEMA_VERSION) + || v == u64::from(SCOPED_DESIRED_STATE_SCHEMA_VERSION) => {} + Some(v) => { + return Err(PollFailure::payload(format!( + "server sent desired-state schemaVersion {v} but this daemon \ + speaks {DESIRED_STATE_SCHEMA_VERSION} or {SCOPED_DESIRED_STATE_SCHEMA_VERSION} — upgrade whichever half is behind" + ))); + } + None => { + return Err(PollFailure::payload( + "desired-state response has no schemaVersion field".to_string(), + )); + } + } + let consent = LogConsent { + machine_logs: raw.get("machineLogs").and_then(serde_json::Value::as_bool), + log_request: raw + .get("logRequest") + .and_then(|r| r.get("id")) + .and_then(serde_json::Value::as_str) + .map(str::to_owned), + }; + let desired = serde_json::from_value::(raw) + .map_err(|err| PollFailure::payload(format!("invalid desired-state response: {err}")))?; + Ok((desired, consent)) +} + /// One poll and its reconcile. `withdrawn` is asked right before anything is /// persisted — the reconcile's writes and the daemon's error state — so a /// disconnect that lands while the request is in flight is not undone by it. @@ -1292,7 +1398,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 } }; @@ -1325,9 +1431,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()); @@ -1337,14 +1445,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, @@ -1360,10 +1468,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() { @@ -1397,6 +1502,36 @@ 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| 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); + 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::*; @@ -1566,6 +1701,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(); @@ -1601,6 +1808,53 @@ mod tests { server.join().unwrap(); } + fn decode(body: &str) -> Result<(DesiredState, LogConsent), String> { + decode_desired_state(serde_json::from_str(body).unwrap()).map_err(|f| { + assert!(f.reportable, "a refused payload is the server's to see"); + f.message + }) + } + + /// A response the daemon refuses carries no consent to apply: the refusal + /// used to land AFTER `machineLogs` and `logRequest` were applied, so an + /// unknown schemaVersion with no `machineLogs` read as "on", removed + /// `uploads-off`, and started an upload. + #[test] + fn a_refused_desired_state_response_yields_no_troubleshooting_consent() { + let err = decode(r#"{"schemaVersion":999,"logRequest":{"id":"req-999"}}"#) + .expect_err("schema 999 must be refused"); + assert!(err.contains("schemaVersion 999"), "got: {err}"); + + let err = decode(r#"{"schemaVersion":2,"machineLogs":true,"logRequest":{"id":"req-bad"}}"#) + .expect_err("a payload missing `deployment` must be refused"); + assert!(err.contains("invalid desired-state response"), "got: {err}"); + + let err = decode(r#"{"machineLogs":true,"logRequest":{"id":"req-none"}}"#) + .expect_err("a response with no schemaVersion must be refused"); + assert!(err.contains("no schemaVersion"), "got: {err}"); + } + + /// The other half: an accepted response still carries both fields. + #[test] + fn an_accepted_desired_state_response_carries_troubleshooting_consent() { + let (desired, consent) = decode( + r#"{"schemaVersion":2,"deployment":7,"policies":[],"machineLogs":false,"logRequest":{"id":"req-ok"}}"#, + ) + .expect("a valid response is accepted"); + assert_eq!(desired.deployment, 7); + assert_eq!( + consent, + LogConsent { + machine_logs: Some(false), + log_request: Some("req-ok".to_string()), + } + ); + + let (_, consent) = decode(r#"{"schemaVersion":2,"deployment":7,"policies":[]}"#) + .expect("a valid response is accepted"); + assert_eq!(consent, LogConsent::default(), "absent keys stay absent"); + } + /// The machine's own answer has to reach the wire, and "cannot say" has to /// stay distinguishable from "deployment 0" once it gets there. #[test] @@ -1612,9 +1866,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, @@ -1639,6 +1906,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/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/hook_watch.rs b/crates/failproofaid/src/hook_watch.rs new file mode 100644 index 000000000..6b3910e7e --- /dev/null +++ b/crates/failproofaid/src/hook_watch.rs @@ -0,0 +1,859 @@ +//! 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 only on evidence that it is fixed, never because it was not + // found again: falling traffic stops a problem being detected without + // fixing it. A refusal is an event, not a state, so it never clears. + let now_kinds: Vec = found.iter().map(Problem::kind).collect(); + let stuck = s.waiting > 0 && s.oldest_waiting_secs >= STALE_AFTER.as_secs(); + let deltas = &self.last_agent_deltas; + self.raised.retain(|(kind, _)| { + let fixed = !now_kinds.contains(kind) + && match kind { + // The hook activity source produced events. + Kind::NotCollected => produced > 0, + // The stuck hook batch is gone. + Kind::NotDelivered => !stuck, + // A hook call from that agent was answered. + Kind::NotHooked(agent) => deltas.get(agent).is_some_and(|(_, a)| *a > 0), + Kind::Refused => false, + }; + if fixed { + out.push(Verdict::Cleared(kind.clone())); + } + !fixed + }); + 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: