Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
62 commits
Select commit Hold shift + click to select a range
487450d
[collect] Self Reports: MCP server, settings file and self_report events
chhhee10 Nov 25, 2026
bb0e716
[daemon] Self Reports: desired-state field, settings writer, sync and…
chhhee10 Nov 25, 2026
65caf1c
[hooks] Self Reports: allow and record the report tool, stdio MCP ser…
chhhee10 Nov 25, 2026
ddcdf77
[ts-sdk] Self Reports: self_report event, report tool helpers and fra…
chhhee10 Nov 25, 2026
20bdfbd
[ts-sdk] Self Reports: integration scenarios, README and changelog
chhhee10 Nov 25, 2026
fe6ac22
[self-reports] Register the failproofai MCP server in every hooked agent
chhhee10 Nov 25, 2026
c52b557
Merge branch 'feat/self-reports-hook' into feat/self-reports
chhhee10 Nov 25, 2026
5bfcf7d
Merge branch 'feat/self-reports-install' into feat/self-reports
chhhee10 Nov 25, 2026
6644970
Merge branch 'feat/self-reports-tssdk' into feat/self-reports
chhhee10 Nov 25, 2026
ce7f644
[self-reports] Integrate the parts: shared settings reader, in-proces…
chhhee10 Nov 25, 2026
995f199
feat(failproofai-sdk): Self Reports — self_report event, report tool …
chhhee10 Nov 25, 2026
46424ea
Merge branch 'feat/self-reports-pysdk' into feat/self-reports
chhhee10 Nov 25, 2026
b5984b1
[self-reports] Docs, changelog, and the Python SDK in the shared gold…
chhhee10 Nov 25, 2026
6f595a9
[self-reports] Live transport check, startup sync, status health, MCP…
chhhee10 Nov 26, 2026
3f4e8dd
[self-reports] Name the report arguments, accept aliased ones, quiete…
chhhee10 Nov 26, 2026
cc064fd
[self-reports] Fix the harness and SDK test-round bugs
chhhee10 Nov 26, 2026
fb102d1
[self-reports] Address review: daemon identity, HTTP gating, attribut…
chhhee10 Nov 26, 2026
f6efba8
[self-reports] Address second review round
chhhee10 Nov 27, 2026
bfbbbe3
[release] 1.0.18-beta.1 for the Self Reports beta
chhhee10 Nov 27, 2026
cf8fdf0
[self-reports] On by default; apply selfReport only from an accepted …
chhhee10 Nov 27, 2026
cfa875b
[self-reports] Project-scope installs leave user-wide MCP configs alo…
chhhee10 Nov 27, 2026
32ca69c
[self-reports] Apply machineLogs/logRequest only from an accepted des…
chhhee10 Nov 27, 2026
10e709d
[release] 1.0.18-beta.2
chhhee10 Nov 27, 2026
1046646
[self-reports] Name the local MCP server failproofai_local; enrolment…
chhhee10 Nov 27, 2026
93cc7f4
[self-reports] Fix the end-to-end run's findings; 1.0.18-beta.3
chhhee10 Nov 27, 2026
0ea26f6
[self-reports] Lean output, MCP events in the daemon log, sync fix pr…
chhhee10 Nov 27, 2026
60c5309
[self-reports] Test fake daemon ignores one-way selfReportLog frames …
chhhee10 Nov 27, 2026
e518765
[self-reports] Visible report tool in every harness, failure hint, re…
chhhee10 Nov 29, 2026
9b84b24
[self-reports] Record a Devin report once: skip the Claude path when …
chhhee10 Nov 29, 2026
b975b92
[self-reports] Lead instructions and description with how to call rep…
chhhee10 Nov 29, 2026
43073a2
[self-reports] Upgrade removes legacy Hermes/OpenClaw MCP entries bef…
chhhee10 Nov 29, 2026
5fb2899
[self-reports] Cut log previews on character boundaries, ASCII ellipsis
chhhee10 Nov 29, 2026
a7fc467
[self-reports] Failure hint only for clearly-blocking failures (auth,…
chhhee10 Nov 29, 2026
65d01ab
[self-reports] Quiet update/config output: routine gateway and Self R…
chhhee10 Nov 29, 2026
99d2d53
[self-reports] Docs: no Cloud Self Reports page; reports live on the …
chhhee10 Nov 29, 2026
749b7ba
[self-reports] One status command: drop --verbose; plain status shows…
chhhee10 Nov 29, 2026
79af748
[self-reports] File every report under a listed category
chhhee10 Nov 29, 2026
2091339
[self-reports] No gateway restart advice where Hermes or OpenClaw is …
chhhee10 Nov 29, 2026
faf8a30
[self-reports] Always-on instructions for Codex, Antigravity and Open…
chhhee10 Nov 29, 2026
6c1b719
Self Reports: task_failure also covers any other blocker no category …
chhhee10 Nov 30, 2026
c333634
Merge remote-tracking branch 'origin/main' into feat/self-reports
chhhee10 Nov 30, 2026
86adc25
Self Reports: grant the report tool's early allow only to our own reg…
chhhee10 Nov 30, 2026
4edfeb2
Hooks: exempt quoted grep/jq arguments only for the standard tool
chhhee10 Nov 30, 2026
bf73847
Self Reports: match a hook row only to a call from its own agent process
chhhee10 Nov 30, 2026
17ef5eb
Self Reports: register Hermes' report tool even while reporting is off
chhhee10 Nov 30, 2026
a32ff85
Self Reports: let Pi pick up the report tool after it started
chhhee10 Nov 30, 2026
66d3cff
Self Reports: scrub before cutting, and never log a raw category verb…
chhhee10 Nov 30, 2026
85d231d
Hooks: a bare grep/rg/jq is the real tool only where PATH finds it in…
chhhee10 Nov 30, 2026
1edd6d9
Merge remote-tracking branch 'origin/main' into feat/self-reports
chhhee10 Nov 30, 2026
f1aa4d8
Self Reports: strict ownership for the report exemption; skip HOME's …
chhhee10 Nov 30, 2026
4d760e3
Hooks: judge a bare grep by the agent's PATH, carried from the hook c…
chhhee10 Nov 30, 2026
e940852
Self Reports: match rows and sessions to the exact agent process
chhhee10 Nov 30, 2026
a2e6509
Self Reports: scrub the log preview from the detail as sent
chhhee10 Nov 30, 2026
490d2a4
Merge remote-tracking branch 'origin/main' into feat/self-reports
chhhee10 Nov 30, 2026
a31a6f5
Self Reports docs: Pi has MCP from 0.99; keep the extension's report …
chhhee10 Nov 30, 2026
bd93edd
Self Reports: keep the stdio log lines on macOS
chhhee10 Nov 30, 2026
f77881c
Self Reports: wait for the daemon to close before dropping a log conn…
chhhee10 Nov 30, 2026
d1f0bc9
Merge remote-tracking branch 'origin/main' into feat/self-reports
chhhee10 Nov 30, 2026
0db0f85
Self Reports: keep the process alive while a log event is in flight
chhhee10 Nov 30, 2026
6047d73
Self Reports: no exemption for an entry that can change what runs; sy…
chhhee10 Nov 30, 2026
d76ce83
Self Reports: dedup across builds while an upgrade is half done
chhhee10 Nov 30, 2026
f256a53
Self Reports: never keep part of a token at a detail cut
chhhee10 Nov 30, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 80 additions & 2 deletions CHANGELOG.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -1370,7 +1370,7 @@ sdk/python/ The telemetry SDK (Python, uv, pytest). PyPI dist
dependency we declare is a constraint they inherit.
`sdk/` is a directory because more languages go beside
`python/`, not inside it.
failproofai_sdk/_events.py The 15 public event methods, and the `_pending` map that
failproofai_sdk/_events.py The 16 public event methods, and the `_pending` map that
auto-computes duration_ms by pairing start/end events
failproofai_sdk/_schema.py One dataclass per event type; `to_dict()` IS the wire
format. Frozen byte-for-byte by tests/test_wire_format.py
Expand All @@ -1385,7 +1385,7 @@ sdk/python/ The telemetry SDK (Python, uv, pytest). PyPI dist
on either side. tests/test_spool_contract.py checks the
Rust and the TypeScript directly and never skips
sdk/typescript/ The telemetry SDK (TypeScript, npm, vitest). npm package
`@failproofai/sdk`. The same 15 events, wire format,
`@failproofai/sdk`. The same 16 events, wire format,
spool directory and Evaluator v2 protocol as
sdk/python — a fleet running both writes into one
pipe. Zero runtime dependencies for the same reason,
Expand Down
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*"]

[workspace.package]
version = "1.0.17"
version = "1.0.18-beta.4"
edition = "2024"
license-file = "LICENSE"
repository = "https://github.com/FailproofAI/failproofai"
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,11 @@ hand an agent more autonomy, not less:
- **One daemon, always in sync.** The same process ships every run to Cloud and keeps
your policies current, so a policy you approve reaches every machine without a
redeploy.
- **Agents that say when they're stuck.** [Self Reports](https://docs.befailproof.ai/self-reports)
gives every agent a `report` tool for looping, a broken credential, missing context or a
request it cannot do. No policy can block the call, and each report lands on its
session, so you see where agents get stuck without reading every transcript. It is on
by default; `failproofai self-report disable` (or the Cloud switch) turns it off.

---

Expand Down
158 changes: 158 additions & 0 deletions __tests__/fixtures/hermes-native-plugin-check.py
Original file line number Diff line number Diff line change
Expand Up @@ -1796,5 +1796,163 @@ def test_no_retry_below_the_oldest_supported_version(self) -> None:
self.assertIn("protocol version mismatch", str(result))
self.assertEqual(len(received), 1)

self_report_mod = sys.modules[f"{plugin.__name__}.self_report"]

SR_SERVER = {"instanceId": "inst-1", "port": 4319}
SR_SCHEMA = {"type": "object", "properties": {"category": {"type": "string"}, "detail": {"type": "string"}}}


def sr_rpc(calls: list, instance: str = "inst-1", tools: list | None = None):
def rpc(url, body, timeout):
calls.append((url, body))
if body["method"] == "initialize":
return {"result": {"serverInfo": {"name": "failproofai_local", "instanceId": instance}, "instructions": "Report when stuck."}}
if body["method"] == "tools/list":
return {"result": {"tools": tools if tools is not None else [{"name": "report", "description": "Report it.", "inputSchema": SR_SCHEMA}]}}
return {"result": {"content": [{"type": "text", "text": "Recorded."}]}}
return rpc


class ToolContext(FakeContext):
def __init__(self, data_dir: Path) -> None:
super().__init__(data_dir)
self.tools: list[dict] = []

def register_tool(self, **kwargs) -> None:
self.tools.append(kwargs)


class SelfReportToolTests(unittest.TestCase):
"""The report tool as a native Hermes tool (never behind tool search)."""

def setUp(self) -> None:
self.fake_toolsets = ModuleType("toolsets")
self.fake_toolsets._HERMES_CORE_TOOLS = ["terminal"]
self._saved = sys.modules.get("toolsets")
sys.modules["toolsets"] = self.fake_toolsets

def tearDown(self) -> None:
if self._saved is None:
sys.modules.pop("toolsets", None)
else:
sys.modules["toolsets"] = self._saved

def test_discover_trusts_only_this_users_daemon(self) -> None:
calls: list = []
tool = self_report_mod.discover_self_report_tool(lambda: SR_SERVER, sr_rpc(calls))
self.assertEqual(tool["description"], "Report it.")
self.assertEqual(tool["inputSchema"], SR_SCHEMA)
self.assertEqual(tool["instructions"], "Report when stuck.")
self.assertTrue(calls[0][0].startswith("http://127.0.0.1:4319/mcp?agent=hermes"))
# Another daemon answering the port, Self Reports off, or no daemon: no tool.
self.assertIsNone(self_report_mod.discover_self_report_tool(lambda: SR_SERVER, sr_rpc([], instance="other")))
self.assertIsNone(self_report_mod.discover_self_report_tool(lambda: SR_SERVER, sr_rpc([], tools=[])))
self.assertIsNone(self_report_mod.discover_self_report_tool(lambda: None, sr_rpc([])))

def test_registers_a_direct_tool_with_the_servers_text(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
ctx = ToolContext(Path(tmp))
state = self_report_mod.SelfReportTool(discover=lambda: {**SR_SERVER, "description": "Report it.", "inputSchema": SR_SCHEMA, "instructions": "Report when stuck."})
self.assertIs(self_report_mod.register_self_report_tool(ctx, state), state)
[reg] = ctx.tools
self.assertEqual(reg["name"], "mcp_failproofai_local_report")
self.assertEqual(reg["toolset"], "failproofai")
self.assertEqual(reg["schema"], {"name": "mcp_failproofai_local_report", "description": "Report it.", "parameters": SR_SCHEMA})
self.assertTrue(reg["check_fn"]())
# On Hermes' never-deferred list, so tool search keeps it direct.
self.assertIn("mcp_failproofai_local_report", self.fake_toolsets._HERMES_CORE_TOOLS)

def test_registers_a_hidden_tool_while_self_reports_is_off_or_the_daemon_is_gone(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
ctx = ToolContext(Path(tmp))
state = self_report_mod.SelfReportTool(discover=lambda: None)
self.assertIs(self_report_mod.register_self_report_tool(ctx, state), state)
[reg] = ctx.tools
self.assertEqual(reg["name"], "mcp_failproofai_local_report")
self.assertEqual(reg["schema"]["parameters"]["required"], ["category", "detail"])
self.assertFalse(reg["check_fn"]()) # hidden from the model while off
self.assertEqual(state.instructions(), "")
self.assertIn("mcp_failproofai_local_report", self.fake_toolsets._HERMES_CORE_TOOLS)

# F16: a gateway that started while Self Reports was off kept no tool, so
# enabling it later never reached that gateway until a restart.
def test_off_at_start_then_enabled_shows_the_tool_and_its_instructions_without_a_restart(self) -> None:
offered = {"on": False}
clock = {"t": 0.0}

def discover():
if not offered["on"]:
return None
return {**SR_SERVER, "description": "Report it.", "inputSchema": SR_SCHEMA, "instructions": "Report when stuck."}

with tempfile.TemporaryDirectory() as tmp:
ctx = ToolContext(Path(tmp))
state = self_report_mod.SelfReportTool(discover=discover, clock=lambda: clock["t"])
instance = plugin.FailproofAIPlugin(FakeContext(Path(tmp)))
instance.self_report = self_report_mod.register_self_report_tool(ctx, state)
[reg] = ctx.tools
self.assertFalse(reg["check_fn"]())
self.assertEqual(instance.pre_llm_call(), {"context": plugin._PROTOCOL_CONTEXT})
# Self Reports is turned on; within a minute the tool and its text follow.
offered["on"] = True
clock["t"] += 61.0
self.assertTrue(reg["check_fn"]())
self.assertTrue(instance.pre_llm_call()["context"].endswith("Report when stuck."))
# The registered schema took the daemon's text in place.
self.assertEqual(reg["schema"]["description"], "Report it.")
self.assertEqual(reg["schema"]["parameters"], SR_SCHEMA)
# And a call is handed to the daemon.
calls: list = []
state._call = lambda tool, args, cwd: self_report_mod.call_self_report_tool(tool, args, cwd, lambda: SR_SERVER, sr_rpc(calls))
self.assertEqual(reg["handler"]({"category": "looping", "detail": "again"}, cwd="/w"), "Recorded.")
self.assertEqual(calls[-1][1]["params"]["arguments"], {"category": "looping", "detail": "again"})
# Turned off again: hidden again.
offered["on"] = False
clock["t"] += 61.0
self.assertFalse(reg["check_fn"]())

def test_a_register_tool_that_raises_never_breaks_register(self) -> None:
class Raising(ToolContext):
def register_tool(self, **kwargs) -> None:
raise RuntimeError("name taken")
with tempfile.TemporaryDirectory() as tmp:
state = self_report_mod.SelfReportTool(discover=lambda: {**SR_SERVER, "description": "d", "inputSchema": SR_SCHEMA, "instructions": ""})
self.assertIsNone(self_report_mod.register_self_report_tool(Raising(Path(tmp)), state))

def test_a_call_goes_to_the_daemon_with_the_agent_cwd_and_normalised_arguments(self) -> None:
calls: list = []
tool = {**SR_SERVER, "description": "d", "inputSchema": SR_SCHEMA}
text = self_report_mod.call_self_report_tool(tool, {"type": "looping", "summary": "again"}, "/work/p", lambda: SR_SERVER, sr_rpc(calls))
self.assertEqual(text, "Recorded.")
url, body = calls[-1]
self.assertEqual(url, "http://127.0.0.1:4319/mcp?agent=hermes&cwd=%2Fwork%2Fp")
self.assertEqual(body["params"], {"name": "report", "arguments": {"category": "looping", "detail": "again"}})
# The daemon restarted on another instance: nothing is sent there.
calls.clear()
self_report_mod.call_self_report_tool(tool, {}, "/w", lambda: {"instanceId": "new", "port": 4319}, sr_rpc(calls))
self.assertEqual(calls, [])

def test_pre_llm_call_carries_the_instructions_only_with_the_tool(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
instance = plugin.FailproofAIPlugin(FakeContext(Path(tmp)))
self.assertEqual(instance.pre_llm_call(), {"context": plugin._PROTOCOL_CONTEXT})
instance.self_report = self_report_mod.SelfReportTool(discover=lambda: {**SR_SERVER, "description": "d", "inputSchema": SR_SCHEMA, "instructions": "Report when stuck."})
context = instance.pre_llm_call()["context"]
self.assertTrue(context.startswith(plugin._PROTOCOL_CONTEXT))
self.assertTrue(context.endswith("Report when stuck."))

def test_register_without_a_daemon_registers_hooks_and_a_hidden_tool(self) -> None:
with tempfile.TemporaryDirectory() as tmp, patch.dict(os.environ, {"FAILPROOFAI_DAEMON_SOCKET": str(Path(tmp) / "none.sock")}):
data_dir = Path(tmp) / "data"
ctx = ToolContext(data_dir)
plugin.register(ctx)
beat = json.loads((data_dir / "heartbeat.json").read_text())
[reg] = ctx.tools
self.assertFalse(reg["check_fn"]())
self.assertIs(beat["self_report_tool"], True)
self.assertIs(beat["self_report_on_at_start"], False)
self.assertIs(beat["register_ok"], True)


if __name__ == "__main__":
unittest.main()
43 changes: 43 additions & 0 deletions __tests__/helpers/self-report-registration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Test helper: a temp HOME in which every agent's `failproofai_local` entry is
* failproofai's own, as `self-report sync` writes it. The hook early-allows the
* report tool only while that is so (`selfReportRegistrationOwned`), so a test
* of the early allow needs a HOME like this one. Never the developer's real
* agent configs: HOME and every agent-home override point into `home`.
*/
import { resolve } from "node:path";
import { vi } from "vitest";
import { syncSelfReportMcp } from "../../src/hooks/self-report-install";

export const AGENT_HOME_ENV = [
"CLAUDE_CONFIG_DIR", "CODEX_HOME", "COPILOT_HOME", "PI_CODING_AGENT_DIR", "HERMES_HOME",
"OPENCLAW_STATE_DIR", "OPENCLAW_HOME", "OPENCLAW_CONFIG_PATH", "GOOSE_PATH_ROOT", "XDG_CONFIG_HOME",
];

/** Point HOME (and each agent's own home override) at `home`. Undo with `vi.unstubAllEnvs()`. */
export function isolateAgentHome(home: string): void {
vi.stubEnv("HOME", home);
vi.stubEnv("USERPROFILE", home);
for (const k of AGENT_HOME_ENV) vi.stubEnv(k, "");
}

/**
* The stdio command the registrations name: this checkout's own CLI entry
* point, which the report exemption requires (never run by these tests).
*/
export const REGISTERED_CLI = resolve(__dirname, "..", "..", "bin", "fail" + "proofai.mjs");

/** Write failproofai's own `failproofai_local` entry for every agent under the isolated HOME. */
export async function registerOwnSelfReportServer(): Promise<void> {
await syncSelfReportMcp({
quiet: true,
binaryPath: REGISTERED_CLI,
deps: {
daemonLive: async () => false,
hooksInstalled: () => true,
hookRecords: () => true,
settings: { enabled: true, port: 4319 },
httpAgents: [],
},
});
}
108 changes: 108 additions & 0 deletions __tests__/hooks/agent-path.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
// @vitest-environment node
/**
* F17 round 2: the guard's "is this bare `grep` the real grep" question is
* answered from the AGENT's PATH, which the hook CLI carries in the payload,
* never from the evaluating process's own PATH: in the daemon's warm worker
* that is the service's PATH, and a shadow `grep` early on the agent's PATH
* was judged by it and ran its argument.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

vi.mock("../../src/hooks/hooks-config", () => ({
readMergedHooksConfig: vi.fn(() => ({ enabledPolicies: [] })),
}));
vi.mock("../../src/hooks/custom-hooks-loader", () => ({
loadAllCustomHooks: vi.fn(async () => ({ hooks: [], conventionSources: [] })),
}));
vi.mock("../../src/hooks/hook-telemetry", () => ({
trackHookEvent: vi.fn(() => Promise.resolve()),
flushHookTelemetry: vi.fn(() => Promise.resolve()),
}));
vi.mock("../../lib/telemetry-id", () => ({ getInstanceId: vi.fn(() => "test-instance-id") }));
vi.mock("../../src/hooks/untraced-note", () => ({ noteUntracedAgent: vi.fn(() => false) }));
vi.mock("../../src/hooks/pack-manifest", () => ({
readInstalledPacks: vi.fn(() => ({ packs: [], errors: [] })),
hasInstalledPacks: vi.fn(() => false),
hasInstalledRegexPacks: vi.fn(() => false),
}));

import { AGENT_PATH_KEY, AGENT_PATH_MAX, agentPathOf, markAgentPath } from "../../src/hooks/agent-path";
import { evaluateHookEvent } from "../../src/hooks/handler";
import { _resetForTest } from "../../src/hooks/hook-activity-store";

const F = "fail" + "proofai";
const bash = (command: string, extra: Record<string, unknown> = {}) =>
JSON.stringify({ session_id: "s", cwd: "/tmp", tool_name: "Bash", tool_input: { command }, ...extra });

describe("markAgentPath (the hook CLI side)", () => {
it("carries this process's PATH on a payload that names a PATH-sensitive command", () => {
const out = JSON.parse(markAgentPath(bash("grep x f"), "/usr/bin:/bin"));
expect(out[AGENT_PATH_KEY]).toBe("/usr/bin:/bin");
expect(agentPathOf(out)).toBe("/usr/bin:/bin");
});

it("leaves any other payload untouched, and replaces or drops a value the payload already had", () => {
const ls = bash("ls");
expect(markAgentPath(ls, "/usr/bin")).toBe(ls);
const spoofed = bash("grep x f", { [AGENT_PATH_KEY]: "/usr/bin:/bin" });
expect(JSON.parse(markAgentPath(spoofed, "/evil:/usr/bin"))[AGENT_PATH_KEY]).toBe("/evil:/usr/bin");
expect(JSON.parse(markAgentPath(bash("ls", { [AGENT_PATH_KEY]: "/usr/bin" }), "/usr/bin"))).not.toHaveProperty(AGENT_PATH_KEY);
// No PATH, or one past the bound: none carried (so nothing is exempt).
expect(JSON.parse(markAgentPath(spoofed, ""))).not.toHaveProperty(AGENT_PATH_KEY);
expect(JSON.parse(markAgentPath(spoofed, "/x".repeat(AGENT_PATH_MAX)))).not.toHaveProperty(AGENT_PATH_KEY);
expect(markAgentPath("{not json grep", "/usr/bin")).toBe("{not json grep");
});
});

describe("the guard in evaluateHookEvent (what the daemon's worker runs)", () => {
let home: string;
let shadow: string;

beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "fpai-agent-path-"));
process.env.FAILPROOFAI_HOME = home;
process.env.FAILPROOFAI_STATE_DIR = join(home, "state");
_resetForTest(join(home, "hook-activity"));
shadow = join(home, "shadow-bin");
mkdirSync(shadow);
writeFileSync(join(shadow, "grep"), '#!/bin/sh\neval "$1"\n', { mode: 0o755 });
// The evaluating process (the worker) has a clean PATH throughout.
vi.stubEnv("PATH", "/usr/bin:/bin");
});

afterEach(() => {
vi.unstubAllEnvs();
delete process.env.FAILPROOFAI_HOME;
delete process.env.FAILPROOFAI_STATE_DIR;
_resetForTest();
rmSync(home, { recursive: true, force: true });
});

const cmd = `grep '(${F} config --pause)' f`;
const decide = async (payload: string) => (await evaluateHookEvent("PreToolUse", "claude", payload)).evaluation?.decision;

it("denies when the agent's PATH finds a shadow grep, though the worker's own PATH is clean", async () => {
expect(await decide(bash(cmd, { [AGENT_PATH_KEY]: `${shadow}:/usr/bin:/bin` }))).toBe("deny");
});

it("denies when no agent PATH came with the payload (an older client, a native plugin)", async () => {
expect(await decide(bash(cmd))).toBe("deny");
});

it.runIf(["/usr/bin/grep", "/bin/grep"].some((p) => existsSync(p)))(
"keeps the exemption when the agent's PATH finds the system grep",
async () => {
expect(await decide(bash(`grep -E '(${F}_local|kiln)' f`, { [AGENT_PATH_KEY]: "/usr/bin:/bin" }))).toBe("allow");
},
);

it("the one-shot hook path stamps the hook process's own PATH (markAgentPath on the real payload)", async () => {
vi.stubEnv("PATH", `${shadow}:/usr/bin:/bin`);
const stamped = markAgentPath(bash(cmd));
vi.stubEnv("PATH", "/usr/bin:/bin");
expect(await decide(stamped)).toBe("deny");
});
});
5 changes: 2 additions & 3 deletions __tests__/hooks/config-status.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -778,10 +778,9 @@ describe("config --status — Codex trust", () => {
const f = facts({ codex: { kind: "untrusted", path: "/h/.codex/hooks.json", untrusted: 10, total: 10 } });
const lines = renderStatusScreen(f, PLAIN);
expect(rowValue(lines, "codex")).toBe("○ Not enforcing: hooks not trusted");
expect(enforcement(lines).slice(-3)).toEqual([
expect(enforcement(lines).slice(-2)).toEqual([
"",
"▲ Codex won't run failproofai's hooks until they're trusted.",
" Re-run failproofai config and allow sudo, or open codex once and approve the hooks.",
"▲ Codex won't run failproofai's hooks until they're trusted. · failproofai config",
]);
});

Expand Down
Loading
Loading