Build a Guardrailed Agent Harness for Safe AI Delegation
Learn how to safely delegate routine system administration tasks to an LLM using a guardrailed CLI harness with fixed recipe parameters, protected entity checks, deterministic post-run state verification, and an audit log.

Tested on: Tested on a Linux server running Python with command-line system automation tools and file-based state verification.
Before you start
Giving an LLM unconstrained access to command-line administration tools is dangerous. Autonomous agents can misinterpret instructions, narrate actions they never actually executed, hang on background processes, or accidentally target critical infrastructure like main server power circuits. Without rigorous boundaries, delegating sysadmin tasks introduces unpredictability and operational risk.
In this tutorial, you will build a lightweight Python harness that enforces a safe delegation pattern. By constraining the LLM to fixed recipe templates, hardcoding protected entities, executing commands synchronously in the foreground, and running deterministic before-and-after checks against the real system state, you can reliably harness agent speed without sacrificing infrastructure safety.
What you need
- A Linux or Unix-compatible workstation or server environment
- Python 3.8 or newer (standard library only; no external dependencies required)
- A command-line terminal and text editor
- An optional external LLM CLI tool, or the included standard-library mock agent for testing
Step 1 · Understand the Guardrail Architecture
Delegating sysadmin tasks to an LLM requires a clear division of responsibility. Routine, repetitive tasks with easily verifiable outcomes belong to the subordinate agent. Complex diagnostics, bespoke logic, mains electrical work, and core infrastructure changes must remain strictly in human hands.
To make delegation safe, we enforce three core architectural principles. First, automation logic lives inside deterministic tools, never inside the LLM prompt. The model only fills in parameters. Second, the runner performs deterministic post-checks against real state because models have been observed to narrate successful actions without actually running commands. Third, a trust policy dictates that the first run of any recipe or device type must be inspected manually, and all automated actions are marked as pending review until verified.
DELEGATE TO AGENT (Routine & Verifiable): KEEP FOR OPERATOR (Risky & Complex):
- Register and configure known device types - Hardware and network fault diagnosis
- Create standard presence or lighting rules - Novel automation logic or custom scripts
- Append documentation notes to state logs - Electrical wiring and power infrastructure
- Parameter-constrained tool calls - Modifying protected servers or switchesStep 2 · Define System State and Protected Entities
For this teaching harness, we represent our system state using a self-contained state.json file. This models registered devices and automation rules without requiring real hardware or network calls.
Crucially, our system state defines protected entities, such as switch.server_power_plug. Critical infrastructure components must be hardcoded as untouchable so that no agent command can ever toggle or delete them. Additionally, we create a secrets.yaml.example file to illustrate that sensitive credentials must always be stored externally and referenced via placeholders, never passed in prompts.
{
"devices": {
"light.stairs_light": {
"type": "light",
"status": "online"
},
"sensor.stairs_top_presence": {
"type": "presence_sensor",
"status": "online"
},
"switch.server_power_plug": {
"type": "smart_plug",
"status": "online",
"protected": true
}
},
"rules": {
"rule_stairs_presence": {
"trigger": "sensor.stairs_top_presence",
"target": "light.stairs_light",
"enabled": true
}
}
}# Example secrets file for system administration tasks
# Keep actual secrets out of agent prompts and version control.
api_token: YOUR_SECRET_TOKEN
sysadmin_credential: YOUR_PASSWORD_OR_KEYStep 3 · Scaffold the CLI Harness and Recipe Allowlist
Now we build harness.py. Instead of giving the agent freeform shell access, we implement an allowlist containing exactly two constrained recipes: pair-device and create-rule.
Each recipe defines its accepted parameters and a prompt builder function. For example, pair-device accepts an entity ID and device type, while create-rule accepts a rule ID, trigger sensor, and target light. The runner handles CLI arguments using argparse and validates that only allowed recipes can be invoked.
PROTECTED_ENTITIES = {
"switch.server_power_plug",
"switch.workstation_power_plug",
}
def recipe_pair_device(params, current_state):
dev_id = params.get("id")
dev_type = params.get("type", "light")
validate_identifier(dev_id)
if dev_id in current_state.get("devices", {}):
raise ValueError(f"Device '{dev_id}' already exists in state.")
return (
f"TASK: Register a new device with ID '{dev_id}' of type '{dev_type}'.\n"
f"Set status to 'online'. Do not modify any other devices."
)
def recipe_create_rule(params, current_state):
rule_id = params.get("id")
sensor = params.get("sensor")
target_light = params.get("target_light")
for item in (rule_id, sensor, target_light):
validate_identifier(item)
devices = current_state.get("devices", {})
if sensor not in devices:
raise ValueError(f"Sensor '{sensor}' not found in state devices.")
if target_light not in devices:
raise ValueError(f"Target light '{target_light}' not found in state devices.")
return (
f"TASK: Create automation rule '{rule_id}' linking trigger sensor '{sensor}' "
f"to target '{target_light}'. Ensure 'enabled': true."
)Step 4 · Enforce Parameter Validation and State Backups
Before any agent command executes, the harness must validate parameters against our security rules and create an automatic backup of the state file.
The validate_identifier function checks that names contain only alphanumeric characters, underscores, and dots (no accents or whitespace). It also immediately raises an error if an argument matches any entity in PROTECTED_ENTITIES. Before running the task, create_backup duplicates state.json to state.json.bak so that if validation fails or a tool crashes, the system can restore the previous snapshot.
def validate_identifier(name):
if not re.match(r"^[a-zA-Z0-9_\.]+$", name):
raise ValueError(
f"Invalid identifier '{name}': only letters, numbers, underscores, "
f"and dots are allowed."
)
if name in PROTECTED_ENTITIES:
raise ValueError(
f"Security violation: '{name}' is a protected entity and cannot be modified."
)
def create_backup():
if os.path.exists(STATE_FILE):
shutil.copy2(STATE_FILE, BACKUP_FILE)
def restore_backup():
if os.path.exists(BACKUP_FILE):
shutil.copy2(BACKUP_FILE, STATE_FILE)Step 5 · Execute Agent Commands Synchronously in the Foreground
When delegating tasks to an LLM CLI tool, command execution must remain strictly controlled. In non-interactive batch or prompt mode, spawning background processes and waiting for completion notifications will hang the harness because headless sessions terminate immediately when tool calling stops.
Furthermore, avoid wrapping multi-line scripts in bash -c '...' or chaining commands with &&. Security permission filters cannot reliably parse complex shell strings and will auto-deny them. In harness.py, we execute agent commands in the foreground using subprocess.run with a short, explicit timeout (15 seconds) and pass recipe context cleanly via environment variables.
def run_agent_command(agent_cmd, prompt, recipe_name, params):
env = os.environ.copy()
env["HARNESS_RECIPE"] = recipe_name
env["HARNESS_PARAMS_JSON"] = json.dumps(params)
env["HARNESS_PROMPT"] = prompt
try:
proc = subprocess.run(
agent_cmd,
shell=True,
capture_output=True,
text=True,
timeout=15,
env=env
)
output = (proc.stdout + "\n" + proc.stderr).strip()
return proc.returncode, output
except subprocess.TimeoutExpired:
return -1, "Command timed out after 15 seconds."
except Exception as e:
return -1, f"Execution failed: {e}"Step 6 · Implement Deterministic Post-Execution Verification
Never trust the agent's prose response. LLMs have repeatedly been observed to report that a device was successfully configured or an automation created when no tool was ever executed. Comparing the actual system state before and after the run is the only way to verify success.
In harness.py, each recipe has a paired post-check function. For pair-device, the checker verifies that exactly one new device appeared in state.json, its name matches the parameter, no existing devices were modified or deleted, and protected entities remain intact. For create-rule, it verifies that exactly one rule was created, it is marked 'enabled': true, its triggers and targets match valid existing devices, and other rules are untouched.
def check_pair_device(before_state, after_state, params):
dev_id = params["id"]
before_devs = before_state.get("devices", {})
after_devs = after_state.get("devices", {})
added = set(after_devs.keys()) - set(before_devs.keys())
if added != {dev_id}:
return False, f"Expected exactly device '{dev_id}' added, found: {list(added)}"
for k, v in before_devs.items():
if k not in after_devs or after_devs[k] != v:
return False, f"Preexisting device '{k}' was altered or deleted."
for p in PROTECTED_ENTITIES:
if p in after_devs and after_devs[p] != before_devs.get(p):
return False, f"Protected device '{p}' was modified!"
return True, f"Device '{dev_id}' verified in state."Step 7 · Build the Audit Log and Test the Complete Harness
The final component of our pattern is the audit trail and trust policy. Every execution records the timestamp, recipe name, parameters, generated prompt, agent output, and post-check result to history.json.
Under our trust policy, any run that passes post-checks is recorded with status SUCCESS (Pending Review). The operator inspects the history log and marks it as fully verified. If post-checks fail, the run is logged as FAILED and the backup state is restored automatically. We can test both outcomes: running with the default harmless echo stub demonstrates the harness catching a hallucinated no-op, while running with mock_agent.py demonstrates a successful, verified state change.
# 1. Run with default echo stub: demonstrates catching hallucinated success
python3 harness.py run pair-device --id light.kitchen_ceiling --type light
# 2. Run with mock agent: demonstrates verified execution
python3 harness.py run pair-device --id light.kitchen_ceiling --type light --agent-cmd "python3 mock_agent.py"
# 3. Create a rule with mock agent
python3 harness.py run create-rule --id rule_kitchen_motion --sensor sensor.stairs_top_presence --target-light light.kitchen_ceiling --agent-cmd "python3 mock_agent.py"
# 4. View the audit trail
python3 harness.py historyTroubleshooting
The agent output reports that the task succeeded, but the post-check fails with 'Expected exactly device ... added, found: []'.
This indicates the deterministic post-check caught a hallucinated action where the agent replied in prose without modifying state.json. Verify that your agent command actually invokes the state-modifying tool rather than echoing text.
The runner times out after 15 seconds with 'Command timed out after 15 seconds.'
In headless CLI prompt mode, background processes do not send completion notifications to the runner. Ensure all commands run synchronously in the foreground with short timeouts.
The runner aborts immediately with 'Security violation: ... is a protected entity'.
The requested recipe parameter targeted a protected device (such as switch.server_power_plug). The guardrail deliberately blocks modifications to critical infrastructure. Specify an unprotected device instead.
Execution fails or is rejected when using complex multi-line shell commands or bash -c strings.
Security filters cannot inspect multi-line strings with pipes and logical operators, triggering automatic denials. Run single discrete commands or put complex logic inside a dedicated Python script.
A newly paired device is absent from the state check immediately after pairing.
The query ran before the system finished writing the new device entry. Introduce a brief sleep or retry in your tool check before failing the verification step.
What I learned
- Always verify real state rather than conversational output: Models can narrate an action convincingly without running the underlying tool. Comparing the actual state before and after execution with deterministic code is the only reliable verification.
- Foreground execution with timeouts prevents hung sessions: Launching background tasks in headless agent sessions leads to timeouts because batch CLI sessions terminate when tool calls conclude. Always run foreground commands with strict timeouts.
- Complex shell chains break permission inspections: Wrapping multi-line commands in bash -c with && or pipes prevents permission scanners from auditing the operation, leading to automatic denials. Use simple, single-purpose commands or dedicated Python scripts.
- Keep automation logic in the tool, not the model: Allowing an LLM to generate raw configuration files produces unpredictable syntax and logic bugs. Confine the LLM to supplying verified parameters to a rigid CLI tool.
- Maintain a strict human-in-the-loop trust policy: The first execution of any new recipe or device type must be manually inspected by the human operator, and all automated runs must be logged as pending review until audited.
Next steps
- Connect to production CLI tools: Replace the mock agent and JSON state file with your platform's real administration CLI tools (such as Zigbee or smart-home CLIs).
- Automated backup rollback: Enhance the harness to automatically restore state.json.bak if deterministic post-checks fail during execution.
- Expand the recipe library: Add new constrained recipes with strict parameter schemas for routine maintenance tasks, such as automated service health checks or log rotation.
Get the code
A lightweight, standard-library Python harness demonstrating guardrailed CLI recipes, deterministic post-checks, and audit logging for LLM agents.
Files in the repository (4)
README.md
# Guardrailed Agent Harness
> **Teaching Example Disclaimer:** This repository provides a simplified, self-contained Python demonstration of the guardrailed CLI delegation pattern. It uses a local `state.json` file rather than live production servers or home automation hardware. Adapt the recipes and tools to your specific environment.
## Overview
Giving an AI agent unrestricted command-line access to system administration tools introduces serious risks: hallucinations, hangs on background processes, and accidental disruption of critical power infrastructure.
This project demonstrates how to build a guardrailed execution harness that enforces:
1. **Fixed Recipe Templates:** The LLM only supplies parameters; the tool handles logic.
2. **Protected Entities:** Critical devices (e.g. server power plugs) are hardcoded as untouchable.
3. **Pre-Execution Backups:** State is snapshotted before any command runs.
4. **Synchronous Foreground Execution:** Commands run with strict timeouts, avoiding hung sessions.
5. **Deterministic Post-Checks:** Before-and-after state comparisons catch hallucinated successes.
6. **Audit Trail & Trust Policy:** Every run is recorded with a pending-review status for human auditing.
## Requirements
- Python 3.8 or newer (standard library only, no pip dependencies)
- Linux or Unix-compatible shell
## Repository Files
- `harness.py`: The CLI runner with recipe definitions, guardrails, post-checks, and audit logging.
- `mock_agent.py`: A simulated agent script that applies valid recipe changes to `state.json`.
- `state.json`: A sample system state representing registered devices and rules.
## Quickstart
### 1. Test Hallucination Detection (Default Echo Stub)
Run a recipe using the default harmless echo command. The agent outputs success text, but because `state.json` is not modified, the deterministic post-check immediately flags the failure:
```bash
python3 harness.py run pair-device --id light.kitchen_ceiling --type light
```
### 2. Test Verified Execution (Mock Agent)
Run the same recipe using `mock_agent.py`. The mock agent applies the requested change, and the post-check confirms the state mutation:
```bash
python3 harness.py run pair-device --id light.kitchen_ceiling --type light --agent-cmd "python3 mock_agent.py"
```
### 3. Create a Verified Automation Rule
Link an existing sensor to a light using the `create-rule` recipe:
```bash
python3 harness.py run create-rule --id rule_kitchen_presence --sensor sensor.stairs_top_presence --target-light light.stairs_light --agent-cmd "python3 mock_agent.py"
```
### 4. Test Protected Entity Guardrails
Attempting to modify a protected entity aborts immediately before any agent command is invoked:
```bash
python3 harness.py run pair-device --id switch.server_power_plug --type smart_plug
```
### 5. Inspect the Audit Log
View all past executions and their review status:
```bash
python3 harness.py history
```state.json
{
"devices": {
"light.stairs_light": {
"type": "light",
"status": "online"
},
"sensor.stairs_top_presence": {
"type": "presence_sensor",
"status": "online"
},
"switch.server_power_plug": {
"type": "smart_plug",
"status": "online",
"protected": true
}
},
"rules": {
"rule_stairs_presence": {
"trigger": "sensor.stairs_top_presence",
"target": "light.stairs_light",
"enabled": true
}
}
}mock_agent.py
#!/usr/bin/env python3
"""Simplified mock agent simulating tool execution for the harness.
Reads recipe parameters passed by harness.py via environment variables and
safely updates state.json to simulate an authorized tool action.
"""
import json
import os
import sys
STATE_FILE = "state.json"
def main():
recipe = os.environ.get("HARNESS_RECIPE")
params_raw = os.environ.get("HARNESS_PARAMS_JSON", "{}")
try:
params = json.loads(params_raw)
except json.JSONDecodeError:
print("Mock Agent Error: Invalid parameters JSON.", file=sys.stderr)
sys.exit(1)
if not os.path.exists(STATE_FILE):
print(f"Mock Agent Error: State file '{STATE_FILE}' not found.", file=sys.stderr)
sys.exit(1)
with open(STATE_FILE, "r", encoding="utf-8") as f:
state = json.load(f)
if recipe == "pair-device":
dev_id = params.get("id")
dev_type = params.get("type", "light")
state.setdefault("devices", {})[dev_id] = {
"type": dev_type,
"status": "online",
}
print(f"Mock Agent: Registered device '{dev_id}' of type '{dev_type}'.")
elif recipe == "create-rule":
rule_id = params.get("id")
sensor = params.get("sensor")
target = params.get("target_light")
state.setdefault("rules", {})[rule_id] = {
"trigger": sensor,
"target": target,
"enabled": True,
}
print(
f"Mock Agent: Created automation rule '{rule_id}' ({sensor} -> {target})."
)
else:
print(f"Mock Agent Error: Unknown recipe '{recipe}'.", file=sys.stderr)
sys.exit(1)
with open(STATE_FILE, "w", encoding="utf-8") as f:
json.dump(state, f, indent=2)
if __name__ == "__main__":
main()harness.py
#!/usr/bin/env python3
"""Simplified Guardrailed CLI Harness for LLM-Driven System Administration.
Demonstrates a safe delegation pattern:
1. Narrow recipes with strict parameter validation.
2. Protected entities that can never be modified.
3. Automatic pre-run state backups.
4. Synchronous foreground command execution with timeouts.
5. Deterministic post-checks comparing actual before/after state.
6. Audit logging with human-in-the-loop pending-review status.
"""
import argparse
from datetime import datetime, timezone
import json
import os
import re
import shutil
import subprocess
import sys
STATE_FILE = "state.json"
BACKUP_FILE = "state.json.bak"
HISTORY_FILE = "history.json"
PROTECTED_ENTITIES = {
"switch.server_power_plug",
"switch.workstation_power_plug",
}
def load_state(path=STATE_FILE):
if not os.path.exists(path):
return {"devices": {}, "rules": {}}
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def create_backup():
if os.path.exists(STATE_FILE):
shutil.copy2(STATE_FILE, BACKUP_FILE)
def restore_backup():
if os.path.exists(BACKUP_FILE):
shutil.copy2(BACKUP_FILE, STATE_FILE)
def validate_identifier(name):
if not re.match(r"^[a-zA-Z0-9_\.]+$", name):
raise ValueError(
f"Invalid name '{name}': only alphanumeric characters, underscores, and dots are allowed."
)
if name in PROTECTED_ENTITIES:
raise ValueError(
f"Security violation: '{name}' is a protected entity and cannot be modified."
)
def recipe_pair_device(params, current_state):
dev_id = params.get("id")
dev_type = params.get("type", "light")
if not dev_id:
raise ValueError("Missing required parameter: --id")
validate_identifier(dev_id)
if dev_id in current_state.get("devices", {}):
raise ValueError(f"Device '{dev_id}' already exists in state.")
return (
f"TASK: Register a new device with ID '{dev_id}' of type '{dev_type}'.\n"
f"Set initial status to 'online'. Do not modify any other devices."
)
def check_pair_device(before_state, after_state, params):
dev_id = params["id"]
before_devs = before_state.get("devices", {})
after_devs = after_state.get("devices", {})
added = set(after_devs.keys()) - set(before_devs.keys())
if added != {dev_id}:
return (
False,
f"Expected exactly device '{dev_id}' to be added, but found {list(added)}.",
)
for k, v in before_devs.items():
if k not in after_devs:
return False, f"Preexisting device '{k}' was deleted."
if after_devs[k] != v:
return False, f"Preexisting device '{k}' was unexpectedly modified."
for p in PROTECTED_ENTITIES:
if p in after_devs and after_devs[p] != before_devs.get(p):
return False, f"Protected device '{p}' was altered!"
return True, f"Device '{dev_id}' verified successfully in state."
def recipe_create_rule(params, current_state):
rule_id = params.get("id")
sensor = params.get("sensor")
target_light = params.get("target_light")
if not rule_id or not sensor or not target_light:
raise ValueError(
"Missing parameters: --id, --sensor, and --target-light are all required."
)
for item in (rule_id, sensor, target_light):
validate_identifier(item)
devices = current_state.get("devices", {})
if sensor not in devices:
raise ValueError(f"Sensor '{sensor}' does not exist in devices.")
if target_light not in devices:
raise ValueError(f"Target light '{target_light}' does not exist in devices.")
if rule_id in current_state.get("rules", {}):
raise ValueError(f"Rule '{rule_id}' already exists in state.")
return (
f"TASK: Create automation rule '{rule_id}' linking trigger sensor '{sensor}' "
f"to target '{target_light}'. Ensure rule is enabled with 'enabled': true."
)
def check_create_rule(before_state, after_state, params):
rule_id = params["id"]
sensor = params["sensor"]
target_light = params["target_light"]
before_rules = before_state.get("rules", {})
after_rules = after_state.get("rules", {})
added = set(after_rules.keys()) - set(before_rules.keys())
if added != {rule_id}:
return (
False,
f"Expected exactly rule '{rule_id}' to be added, but found {list(added)}.",
)
rule = after_rules[rule_id]
if rule.get("trigger") != sensor:
return False, f"Rule trigger is '{rule.get('trigger')}', expected '{sensor}'."
if rule.get("target") != target_light:
return False, f"Rule target is '{rule.get('target')}', expected '{target_light}'."
if not rule.get("enabled", False):
return False, "Rule was created but is not enabled."
for k, v in before_rules.items():
if k not in after_rules or after_rules[k] != v:
return False, f"Preexisting rule '{k}' was altered or deleted."
return True, f"Rule '{rule_id}' verified successfully in state."
RECIPES = {
"pair-device": {
"builder": recipe_pair_device,
"checker": check_pair_device,
},
"create-rule": {
"builder": recipe_create_rule,
"checker": check_create_rule,
},
}
def run_agent_command(agent_cmd, prompt, recipe_name, params):
env = os.environ.copy()
env["HARNESS_RECIPE"] = recipe_name
env["HARNESS_PARAMS_JSON"] = json.dumps(params)
env["HARNESS_PROMPT"] = prompt
try:
proc = subprocess.run(
agent_cmd,
shell=True,
capture_output=True,
text=True,
timeout=15,
env=env,
)
output = (proc.stdout + "\n" + proc.stderr).strip()
return proc.returncode, output
except subprocess.TimeoutExpired:
return -1, "Command timed out after 15 seconds."
except Exception as e:
return -1, f"Execution failed: {e}"
def log_history(entry):
history = []
if os.path.exists(HISTORY_FILE):
try:
with open(HISTORY_FILE, "r", encoding="utf-8") as f:
history = json.load(f)
except Exception:
history = []
history.append(entry)
with open(HISTORY_FILE, "w", encoding="utf-8") as f:
json.dump(history, f, indent=2)
def main():
parser = argparse.ArgumentParser(
description="Guardrailed CLI Harness for LLM-Driven System Administration"
)
subparsers = parser.add_subparsers(dest="command", required=True)
run_p = subparsers.add_parser("run", help="Run a guardrailed recipe")
run_p.add_argument("recipe", choices=list(RECIPES.keys()), help="Recipe name")
run_p.add_argument("--id", required=True, help="Identifier for device or rule")
run_p.add_argument("--type", default="light", help="Device type (pair-device)")
run_p.add_argument("--sensor", help="Trigger sensor entity ID (create-rule)")
run_p.add_argument("--target-light", help="Target light entity ID (create-rule)")
run_p.add_argument(
"--agent-cmd",
default='echo "Agent output: Task completed successfully."',
help="Agent command to execute (defaults to harmless echo stub)",
)
subparsers.add_parser("history", help="Show execution audit log")
args = parser.parse_args()
if args.command == "history":
if not os.path.exists(HISTORY_FILE):
print("No execution history found.")
return
with open(HISTORY_FILE, "r", encoding="utf-8") as f:
history = json.load(f)
print(f"{'TIMESTAMP':<25} {'RECIPE':<15} {'STATUS':<25} {'DETAILS'}")
print("-" * 80)
for entry in history:
ts = entry.get("timestamp", "")[:19]
rec = entry.get("recipe", "")
st = entry.get("status", "")
det = entry.get("check_message", "")
print(f"{ts:<25} {rec:<15} {st:<25} {det}")
return
if args.command == "run":
recipe_name = args.recipe
recipe_conf = RECIPES[recipe_name]
params = {
"id": args.id,
"type": args.type,
"sensor": args.sensor,
"target_light": args.target_light,
}
params = {k: v for k, v in params.items() if v is not None}
before_state = load_state()
try:
prompt = recipe_conf["builder"](params, before_state)
except Exception as e:
print(f"[PRE-CHECK ERROR] {e}")
sys.exit(1)
print(f"[*] Recipe: {recipe_name}")
print(f"[*] Prompt generated:\n {prompt}")
print(f"[*] Executing agent command: {args.agent_cmd}")
create_backup()
code, output = run_agent_command(args.agent_cmd, prompt, recipe_name, params)
print(f"[*] Agent exit code: {code}")
print(f"[*] Agent output:\n {output}")
after_state = load_state()
check_passed, check_msg = recipe_conf["checker"](before_state, after_state, params)
status = "SUCCESS (Pending Review)" if check_passed else "FAILED"
print(f"[*] Post-check result: {status}")
print(f" Message: {check_msg}")
log_entry = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"recipe": recipe_name,
"params": params,
"prompt": prompt,
"agent_cmd": args.agent_cmd,
"agent_output": output,
"check_passed": check_passed,
"check_message": check_msg,
"status": status,
"reviewed": False,
}
log_history(log_entry)
if not check_passed:
print("[!] Warning: Checks failed. Restoring previous state snapshot.")
restore_backup()
sys.exit(1)
else:
print("[+] Success: Operation verified and logged for manual review.")
if __name__ == "__main__":
main()