AI Agent Shell Reliability Evaluation and Safe Execution Scheduling
A practical guide to evaluating AI agents through benchmark regression tests and blind comparisons of real tasks, assessing Shell command reliability, measuring steerability, and applying safety constraints to execution scheduling. It covers review criteria, bounded retries, human approval, audit logging, and a Python validation excerpt for sandboxed command execution.
Large language models are evolving from question-answering tools into agents that can call tools and carry out multistep tasks autonomously. Static benchmarks alone cannot capture how these agents perform on long-running engineering tasks. Developers also need practical evaluation methods and execution constraints.
This article covers baseline capability assessment, Shell command reliability, task redirection, and safety-constrained execution scheduling.
1. Evaluate Baseline Agent Capabilities
Standard benchmarks are inexpensive and reproducible, making them useful for regression testing after each model release. However, benchmark scores do not show whether a model will get stuck in a real workflow or drift away from the task objective.
Blind evaluations of real conversations help fill that gap. Collect anonymized task conversations, have two model versions handle the same tasks, and ask reviewers to judge which version performed better using a consistent rubric.
These methods serve different purposes:
- Standard benchmarks detect regressions.
- Blind comparisons support model selection.
Use the net improvement rate to summarize blind comparison results:
Net improvement rate =(New-version wins − New-version losses) / Total valid comparisons × 100%
Ties count toward the total number of valid comparisons but not toward wins or losses.
Calculate this metric separately for each dimension, such as Bash Reliability and Steerability. Do not combine dimensions into a single overall score: improvements in one area could conceal regressions in another.
Sampling and Review Protocol
- Prepare at least 500 valid conversations per dimension. The proposed sampling guideline targets a 95% confidence interval with a margin of approximately four percentage points when outcomes are close to evenly split. Use the calculated interval for the actual net improvement metric when making decisions.
- Stratify tasks into work, programming, and chat categories. Fix their proportions before testing—for example, 40% work, 40% programming, and 20% chat. Do not adjust them after seeing the results.
- Bootstrap the judgments 1,000 times. Use the 2.5th and 97.5th percentiles as the bounds of the 95% confidence interval.
- Have a second reviewer recheck a random 10% of judgments. If reviewer agreement is below 80%, withhold the conclusion, align the review criteria, and repeat the review.
- Adopt the new version only if the confidence interval’s lower bound is above zero. This is the criterion for concluding that the new version performs better.
The order matters: check reviewer agreement first, then examine the confidence interval’s lower bound.
After each evaluation round, record:
- Test date and time
- Model versions
- Sample counts for each task category
- Win, tie, and loss counts
- Net improvement rate
- Confidence interval
- Agreement rate on the reviewed subset
- Final decision and rationale
Label the decision “Adopt” or “Do not adopt yet,” and explain why.
2. Evaluate Shell Command Reliability
Bash Reliability measures the accuracy and safety of generated commands, along with the agent’s ability to handle execution errors.
| Dimension | Observable signal | Common failure mode | Mitigation |
|---|---|---|---|
| Syntax and context | Whether the command runs on the target system | Ignoring the working directory or using an incorrect path | List the directory and verify that paths exist before execution |
| Safety | Whether execution stays within the authorized scope | Wildcard deletion at the filesystem root or execution without confirmation | Command allowlists, path restrictions, previews, and confirmation |
| Error interpretation | Whether the agent correctly understands stderr |
Treating a permission error as a syntax error and retrying | Route handling by error type |
| Retry control | Number of retries and their outcomes | Repeated failure of the same command | Cap retries and escalate to a human when the limit is reached |
Example: Cleaning Up Old Logs
For a request to remove logs older than seven days, an agent might generate:
find /var/log -type f -mtime +7 -exec rm {} \;
This command has three problems:
- Its scope is too broad: it targets all of
/var/log. - Deletion is irreversible, with no confirmation step.
- It does not preview the files that will be affected.
A more controlled workflow separates the operation into steps, with an explicit stopping point at each stage.
Step 1: Preview Without Making Changes
find /var/log/myapp -type f -mtime +7 -print
Inspect the matched files before proceeding.
Step 2: Count and Verify
find /var/log/myapp -type f -mtime +7 | wc -l
Proceed only if the result matches expectations. A human runs this step directly in the terminal, not through the agent’s executor.
Step 3: Create a Backup
find /var/log/myapp -type f -mtime +7 -print0 | tar --null -czf /backup/myapp-old-logs-YYYY-MM-DD.tar.gz -T -
Step 4: Verify the Backup
tar -tzf /backup/myapp-old-logs-YYYY-MM-DD.tar.gz | wc -l
The number of archive entries must equal the count from Step 2.
Step 5: Delete Only After Human Confirmation
find /var/log/myapp -type f -mtime +7 -delete
Do not execute the deletion until a human has confirmed it.
Step 6: Restore If Needed
tar -xzf /backup/myapp-old-logs-YYYY-MM-DD.tar.gz -C /
tar removes the leading slash from stored absolute paths. Extracting the archive under / restores the files to their original locations.
Keep file selection and deletion confined to /var/log/myapp. Deletion against / or root-level wildcard targets is prohibited.
Check the Time Boundary
-mtime +7 matches files whose modification age, measured in complete 24-hour periods, is greater than seven: files in the eighth day and beyond. Files exactly seven days old are not matched. Verify this boundary during the preview step.
Route Errors by Type
Do not apply the same retry policy to every recoverable error.
permission_denied: Report the error and request human authorization. Do not automatically escalate privileges with commands such assudoorchmod 777.path_invalid: List the parent directory to confirm the actual path, then retry at most once.syntax_error: Correct the command syntax before retrying.- Other unrecoverable errors: Stop immediately and record the complete
stderroutput in the audit log.
All retry paths must have an upper limit. Once that limit is reached, hand the task over to a human.
3. Measure and Implement Steerability
Steerability is an agent’s ability to respond to external instructions or internal state feedback and promptly change direction when a task deviates from expectations.
For example, if a user says, “Stop the current search and analyze the local data instead,” the agent should stop its current task sequence, discard intermediate results tied to the old objective, and switch to the new task.
Three metrics capture this behavior:
- Redirection response steps: How many additional steps the agent takes after receiving the instruction before it changes its actions.
- Residual operations after redirection: How many operations associated with the old objective still occur after the switch.
- Task completion rate after redirection: The proportion of redirected tasks that are ultimately completed.
Lower values are better for the first two metrics; higher values are better for the third.
Decouple Input from Execution
Use a message queue to separate user input from the execution flow. Users can enqueue high-priority redirection messages at any time, and the executor polls the queue before each reasoning step.
Reset the Execution Context
When a redirection signal arrives, reset the execution context. Retain the overall goal and critical constraints while discarding redundant intermediate steps.
For long-running tasks, a vector database can store long-term memory, such as summaries of task objectives and confirmed decisions. If the context window is truncated, the agent can retrieve the original objective instead of losing track of its direction.
4. Implement Safety-Constrained Execution Scheduling
The following Python excerpt demonstrates command validation and the beginning of a safety-constrained execution routine.
Runtime Requirements
- Python 3.9 or later.
sandbox_executor.run(argv, timeout)accepts an argument list and must invoke subprocesses internally withshell=False. It returns an object withreturncode,stdout, andstderrattributes and raisesTimeoutErroron timeout.agentimplementsanalyze_error(stderr)andgenerate_fix_command(analysis). The analysis result haskindandis_recoverablefields. Thekindvalue ispermission_denied,path_invalid,syntax_error, or another error category.contextprovidesworkdir,allowed_roots, anaudit_loglist, arequire_confirmationboolean, and aconfirm(text)method.sandbox_executorruns in a container without write access to the host. Authorized directories are mounted read-only unless the task genuinely requires write access.
Example configuration:
context = ExecContext(workdir="/var/log/myapp",allowed_roots=["/var/log/myapp"],require_confirmation=True,)
Validation and Retry-Limit Excerpt
The supplied implementation ends at the reminder to confirm every command. The excerpt below preserves that boundary; it does not include the subsequent confirmation, execution, or error-handling implementation.
import osimport shlexMAX_RETRY_DEPTH = 2TIMEOUT_SECONDS = 30ALLOWED_COMMANDS = {"ls", "cat", "grep", "find", "tail", "df", "du"}FORBIDDEN_ARGS = {"-delete", "-exec", "-execdir", "-ok", "-okdir"}def path_within(path, allowed_roots):"""Both path and allowed_roots must be realpath results."""for root in allowed_roots:real_root = os.path.realpath(root)if os.path.commonpath([path, real_root]) == real_root:return Truereturn Falsedef path_operands(argv):"""Extract potential path arguments; use only value for --opt=value."""for arg in argv[1:]:if arg.startswith("-"):if "=" in arg:yield arg.split("=", 1)[1]continueyield argdef validate_command(argv, context):"""Return (passed, reason). Parse argv with shlex.split, not a shell."""if not argv:return False, "Empty command"if argv[0] not in ALLOWED_COMMANDS:return False, f"Command is not allowlisted: {argv[0]}"for arg in argv[1:]:if arg in FORBIDDEN_ARGS:return False, f"Forbidden argument: {arg}"workdir = os.path.realpath(context.workdir)if not path_within(workdir, context.allowed_roots):return False, f"Working directory is outside authorized roots: {workdir}"for operand in path_operands(argv):# os.path.join returns an absolute operand unchanged.# realpath resolves .. components and symbolic links.target = os.path.realpath(os.path.join(workdir, operand))if not path_within(target, context.allowed_roots):return False, f"Path is outside authorized roots: {operand} -> {target}"return True, "Passed"def preview_text(argv):return " ".join(shlex.quote(arg) for arg in argv)def execute_shell_command(agent, command, context, depth=0, path_retry_used=False):if depth > MAX_RETRY_DEPTH:context.audit_log.append({"command": command, "depth": depth, "result": "retry_limit"})return {"status": "failed", "message": "Retry limit exceeded; escalate to a human"}try:argv = shlex.split(command)except ValueError as exc:context.audit_log.append({"command": command, "depth": depth, "check": f"Cannot parse: {exc}"})return {"status": "rejected", "message": f"Cannot parse command: {exc}"}passed, reason = validate_command(argv, context)context.audit_log.append({"command": command, "depth": depth, "check": reason})if not passed:return {"status": "rejected", "message": reason}# Confirm every command, including the first command.
