Files
fermata/src/harness/mod.rs
T
g4borg 6bf602aa6a fix(fermata): a bad glob costs only itself; commands read what is there, behind a wrapper or a shell
- A glob in [files] or [policy] that does not compile costs only that pattern while open,
  with a note by name beside text output. A [files] list with none left leaves the built-in
  list. Under deny the refusal stays, and the channel filter stays strict.
- A file named `credentials` is on the default list, at any depth.
- A word with a separator counts only if the path is there, the shell may expand it, or a
  redirect names it: packages, branches and hosts' paths are not denied.
- timeout, nice, ionice, stdbuf, xargs and busybox are prefixes; `2>&1` stays in its segment.
- `bash|sh|zsh -c` and `eval` arguments are read as command lines.
- A `<<` with no closing line is no heredoc. A commented line's own comment is dropped.
  Text holding NUL fails to parse. The unknown-field message says so. Durations are bound
  to under 6 characters. More source extensions pass the gate.
- Removed: HarnessAdapter::post_tool_op (dead since 3C was dropped), tool_op back inline.
2026-11-07 02:00:45 +01:00

169 lines
5.9 KiB
Rust

//! Harness adapter layer. Normalizes harness-specific payloads into
//! `core` types and renders `Decision` back to harness wire format.
use crate::core::paths::Dialect;
use crate::core::secrets::Redactor;
use crate::core::Decision;
use std::path::PathBuf;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum AdapterError {
#[error("invalid request payload: {0}")]
Parse(String),
#[error("unsupported tool: {0}")]
UnsupportedTool(String),
#[error("io: {0}")]
Io(#[from] std::io::Error),
#[error("json: {0}")]
Json(#[from] serde_json::Error),
}
/// Normalized tool-call shape consumed by `core::Policy`.
/// Adapters translate harness-specific payloads into this; nothing in
/// `core` knows about adapters.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolCall {
/// Harness's tool name (e.g. "Read", "Write", "Edit", "Bash").
pub tool_name: String,
/// Op classification derived from `tool_name`.
pub op: ToolOp,
/// Original raw payload for the adapter to consult when rendering.
pub raw: serde_json::Value,
/// The session's current directory, if the harness sent one.
pub cwd: Option<PathBuf>,
/// Which shell's quoting a command is written in.
pub dialect: Dialect,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolOp {
Path { path: PathBuf, kind: PathKind },
Command { text: String },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathKind {
Read,
Write,
}
/// A PostToolUse hook payload -- tool already executed, output available for
/// inspection/redaction.
#[derive(Debug, Clone)]
pub struct PostToolUsePayload {
/// Harness's tool name (e.g. "Read", "Bash").
pub tool_name: String,
/// The tool input that was originally provided.
pub tool_input: serde_json::Value,
/// The tool's output as the harness sent it, in any shape. It may contain
/// secrets. `Null` when the harness sent none.
pub tool_response: serde_json::Value,
/// The session's current directory, if the harness sent one.
pub cwd: Option<PathBuf>,
}
impl PostToolUsePayload {
/// Whether there is any output to look at.
pub fn has_output(&self) -> bool {
!self.tool_response.is_null() && self.tool_response != ""
}
}
/// What redaction does to a tool's output.
#[derive(Debug, Clone, PartialEq)]
pub enum OutputEdit {
/// No secret in it: the original stands.
Unchanged,
/// The same shape with the secrets masked.
Replaced { output: serde_json::Value, redactions: usize },
/// A secret sits where the harness would reject a masked replacement and use
/// the original. `keys` names the secrets (key names, never values).
Unmaskable { keys: Vec<String> },
}
/// Hook event type discriminator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookEvent {
PreToolUse,
PostToolUse,
}
impl HookEvent {
/// Parse a hook event name from CLI or payload strings.
///
/// Accepts both kebab-case (`pre-tool-use`) and PascalCase (`PreToolUse`).
pub fn parse(s: &str) -> Option<Self> {
match s {
"pre-tool-use" | "PreToolUse" => Some(Self::PreToolUse),
"post-tool-use" | "PostToolUse" => Some(Self::PostToolUse),
_ => None,
}
}
}
/// Trait implemented by each harness adapter.
///
/// Adapters handle both PreToolUse (policy gate) and PostToolUse (output
/// redaction) hook events.
pub trait HarnessAdapter {
/// The CLI name (e.g. "claude", "codex", "gemini").
fn name(&self) -> &'static str;
// -- PreToolUse --------------------------------------------------------
/// Parse a PreToolUse hook payload into a normalized `ToolCall`.
fn parse_request(&self, input: &[u8]) -> Result<ToolCall, AdapterError>;
/// Render a policy `Decision` back to the harness's PreToolUse wire format.
fn render_decision(&self, call: &ToolCall, decision: &Decision) -> Result<Vec<u8>, AdapterError>;
/// The (text before, text after) of each change a call makes to a file's text.
/// `None` before: the whole file, which is what is on disk. Empty for any other call.
fn write_pairs(&self, call: &ToolCall) -> Vec<(Option<String>, String)>;
// -- PostToolUse -------------------------------------------------------
/// Parse a PostToolUse hook payload (tool name, input, response).
fn parse_post_tool_use(&self, input: &[u8]) -> Result<PostToolUsePayload, AdapterError>;
/// Mask every known secret in the payload's output, in the output's own shape.
fn redact_output(&self, payload: &PostToolUsePayload, redactor: &Redactor) -> OutputEdit;
/// The strings of `output` that are text, for the heuristic scanner.
fn output_text<'a>(&self, payload: &PostToolUsePayload, output: &'a serde_json::Value) -> Vec<&'a str>;
/// Whether this output shows file or command text, so that a note about what is not
/// masked belongs beside it. A session of many Writes must not pay for it each time.
fn shows_text(&self, payload: &PostToolUsePayload) -> bool;
/// Render a PostToolUse response: the replacement output if there is one, and
/// a note to show beside the result. Neither means the original stands.
fn render_post_tool_use(
&self,
payload: &PostToolUsePayload,
updated_output: Option<&serde_json::Value>,
context: Option<&str>,
) -> Result<Vec<u8>, AdapterError>;
/// Render a PostToolUse response that puts `refusal` in place of the whole
/// tool output, in whatever form this harness accepts as a replacement.
fn render_post_tool_use_withheld(
&self,
payload: &PostToolUsePayload,
refusal: &str,
) -> Result<Vec<u8>, AdapterError>;
}
#[cfg(feature = "harness-claude")]
pub mod claude;
/// Look up a registered adapter by CLI name.
pub fn lookup(name: &str) -> Option<Box<dyn HarnessAdapter>> {
match name {
#[cfg(feature = "harness-claude")]
"claude" => Some(Box::new(claude::ClaudeAdapter)),
_ => None,
}
}