A policy gateway with risk tiers, credentials the model never sees, and a hook that stops git push --force. Plus an honest list of what about 500 lines can't promise.
Two days ago Andrii Tkachuk published “The Harness Is the Product”, a long walk through what an agent harness looks like in 2026. Most of it is architecture at the whiteboard level, which is fine, that’s what it’s for. But one section stopped me, because it’s the one I keep getting wrong in my own projects. Section 7 says credentials never become model context and that policy sits between intent and execution. Section 8 adds the line I ended up writing on a sticky note: approval should never depend on the model choosing to ask for it.
I agree with that sentence completely. I also noticed that I have never actually built it. Every agent I’ve shipped for myself has some version of “Before running destructive commands, ask the user for confirmation” in its system prompt, and a tool layer underneath that will happily run anything the model sends.
So this weekend I took that one idea and built the smallest version of it I could defend, in .NET, against a local model through Ollama so nobody needs an API key to try it. This article is what I built, what I compared it against, where I was tempted to cheat by prompting, and what a few hundred lines honestly can and can’t guarantee.
The idea, stated narrowly
From Tkachuk’s piece, the part I’m implementing (his framing, my summary):
- The model expresses intent. It does not hold credentials. “I’m allowed to read invoices” is model context; the OAuth refresh token is not.
- Every tool call passes through a policy layer that classifies risk. His tiers are read, low-risk write, sensitive write, destructive.
- Approval is enforced by the harness. When a risky call hits policy, the harness pauses and asks a human, whatever the model intended. Model-initiated clarification (“which month did you mean?”) is a separate primitive.
He also points at OpenAI’s newly announced “dots” as shipping user-defined rules and mandatory consent for sensitive actions. That’s a vendor launch as reported in his article. I haven’t used dots and I’m not treating it as evidence of anything except that the idea is in the air.
What I am not building: his operation catalog, memory, routing, durable pause and resume, or a multi-surface approval UI. One gateway, one console, one repo.
Three ideas I borrowed from other people
Before writing code I reread three other pieces from the last two weeks, because they each pushed on a different part of the same problem.
Jaroslaw Wasowski, “AI Agent Permissions as Policy in the Call Path”. His opening example is the one I used as my test case: the same git push --force origin main gets three different outcomes in three modes of the same agent (PLAN proposes it, DEFAULT waits for a click, YOLO just runs it). His point is that the mode doesn't know what risk class the command belongs to. Mode and risk are two separate axes, so the policy is a matrix of action class by mode, enforced as a pre-tool hook. His subtitle also argues for command grammar instead of regex, which turned out to be the most practical advice in this whole exercise. The full piece is member-only and goes deeper than what I'm building; I'm using his framing, not reproducing his matrix.
Cyril Canovas, “My coding agent wrote outside the repo. Nothing stopped it.” This is the most concrete of the three. He describes a .NET 10 framework, Orkeon, where the agent never sees a disk path. It sees virtual paths backed by mounts you declare with rights (ro, rw, rwnd), and a Roslyn analyzer turns any direct System.IO call inside the framework into a compile error, so the framework itself can't step around the boundary. The numbers he gives (79 built-in tools, 50 justified suppressions, the analyzer package shipping twice in a form that silently didn't load) are the author's own reporting on his own project, and he's unusually upfront about the gaps, including that a "read-only" shell allowlist with cat still lets /etc/passwd through. Two things I took from it: refusal messages written for the model to read, and the idea that the harness should be unable to cheat, not just unwilling.
JIN, on instructions versus controls. Two pieces from the JIN System Architect publication. “Beyond CLAUDE.md” argues that instruction files stopped being sufficient and what’s needed is a verifiable control plane. “Who Searches, Who Decides, Who Owns the Blast Radius” opens with a story I recognized uncomfortably well: an agent that graded itself after every task and logged problems to a table, which after five months held four rows that nothing had ever read or acted on. Both are partly paywalled and the story is the author’s own anecdote. The lesson I took is a narrow one: a control is something that changes what happens next. An instruction asks. A log that nobody reads only remembers.
Microsoft’s Agent Framework update from September 24 is relevant too, mostly for what it’s careful to say. In the CodeAct section it separates two things that people tend to blur: Hyperlight isolates the model-generated code, while your registered tools still run in your application’s runtime with their own permissions. It also says that actions needing individual approval should stay explicitly approval-gated, and that resumed long-running work is not exactly-once, so an interrupted step may run again. The post reports roughly 50% lower latency and over 60% fewer tokens for CodeAct on its evaluated workload; that’s Microsoft’s own measurement on Microsoft’s own workload, and they say as much.
The shape of the thing
model --tool call--> PolicyGateway
1. unknown tool? → DENY
2. tool.Classify(args) → read | write | destructive | DENY
3. pre-tool hooks → BLOCK (no override)
4. matrix[class, mode] → execute | ask human | propose only
5. execute with injected credentials
6. scrub secrets from output
<--result text-- back to model
Two decisions carry most of the weight.
First, the harness classifies the call, not the model. The model calls git with ["push", "origin", "main"]. The GitTool parses that and decides it's destructive. There is no risk field the model fills in.
Second, hooks run before the matrix. The matrix decides how much friction an action gets. Hooks decide what is not allowed at all. A force push is not “very risky, ask twice”. It’s off the table, and no mode and no approval click can turn it back on.
Here’s the matrix. auto is Wasowski's YOLO with a less cheerful name.
+--------------------------+--------------+----------------+-------------------+
| Action class | plan | default | auto |
+--------------------------+--------------+----------------+-------------------+
| read | execute | execute | execute |
| write (local, reversible)| propose only | ask human | execute + audit |
| destructive | propose only | ask human | ask human |
| blocked by a hook | deny | deny | deny |
| unclassifiable / unknown | deny | deny | deny |
+--------------------------+--------------+----------------+-------------------+
And how my three tiers map onto Tkachuk’s four, since I collapsed one:
+---------------------------+-------------------------------------------+
| Tkachuk | This build |
+---------------------------+-------------------------------------------+
| READ -> execute | read |
| LOW-RISK WRITE -> audit | write, in auto mode |
| SENSITIVE WRITE -> confirm| write, in default mode |
| DESTRUCTIVE -> approval | destructive, every mode except plan |
| (not in his list) | hard block via hook, no approval possible |
+---------------------------+-------------------------------------------+
I merged his two write tiers and let the mode do the splitting. For a single-repo coding agent that felt honest. For anything that touches money or other people’s data, I’d keep his four tiers and add mode on top.
Setup
You need the .NET 8 SDK (or newer), git 2.31+ (for GIT_CONFIG_COUNT), and Ollama. No NuGet packages beyond the SDK; I talk to Ollama's /api/chat endpoint with HttpClient so there's no client library version to drift.
# Option A: native Ollama
ollama pull qwen2.5:7b
# Option B: Ollama in Docker
docker run -d -v ollama:/root/.ollama -p 11434:11434 --name ollama ollama/ollama
docker exec -it ollama ollama pull qwen2.5:7b
# The project
dotnet new console -n HarnessGate -f net8.0
cd HarnessGate
# replace Program.cs and add the other six files below
On model choice: qwen2.5:7b is what I'd start with for tool calling on a laptop. Canovas reports that qwen2.5:1.5b called tools reliably in his CI under Ollama 0.34.0 while llama3.2:1b kept emitting the tool-call envelope as plain text. That's his observation on his setup; small models vary a lot, so try a couple. Set OLLAMA_MODEL to switch.
The policy: one switch expression
// Policy.cs
using System.Text.Json;
namespace HarnessGate;
public enum ActionClass { Read, Write, Destructive }
public enum Mode { Plan, Default, Auto }
public enum Verdict { Execute, ExecuteAndAudit, AskHuman, ProposeOnly }
public sealed record ToolCall(string Name, JsonElement Arguments);
public sealed class PolicyException(string message) : Exception(message);
public static class PolicyMatrix
{
// The whole policy. If it stops fitting on one screen, it has become a second product.
public static Verdict Decide(ActionClass action, Mode mode) => (action, mode) switch
{
(ActionClass.Read, _) => Verdict.Execute,
(_, Mode.Plan) => Verdict.ProposeOnly,
(ActionClass.Write, Mode.Default) => Verdict.AskHuman,
(ActionClass.Write, Mode.Auto) => Verdict.ExecuteAndAudit,
(ActionClass.Destructive, _) => Verdict.AskHuman,
_ => throw new PolicyException($"no rule for {action}/{mode}")
};
}
I like that the entire policy is readable in ten seconds. The day it needs a rules engine is the day it needs its own tests, its own owner, and its own article.
The hook: grammar, not regex
My first version of the force-push check was a regex for --force|-f. It took about ten minutes of thinking adversarially to break it:
- -fu (short flags combine)
- --force-with-lease (matches, fine, but so does a lot of other stuff once you loosen the pattern)
- git push origin +main (a leading + on a refspec is a force push, no flag at all)
- git push origin :main (an empty source deletes the remote branch)
- git -C /somewhere push --force (global options before the subcommand shift where "push" sits)
So the hook works on a parsed command instead of a string: global options, then a subcommand, then the rest. That’s the “command grammar instead of regex” idea from Wasowski’s subtitle, in its cheapest possible form.
// Hooks.cs
namespace HarnessGate;
public sealed record HookResult(bool Blocked, string? Reason)
{
public static readonly HookResult Pass = new(false, null);
public static HookResult Block(string reason) => new(true, reason);
}
public interface IPreToolHook
{
string Name { get; }
HookResult Evaluate(ToolCall call, ActionClass actionClass);
}
// Hard stop: nothing rewrites or deletes remote history. Any mode, approved or not.
public sealed class NoRemoteHistoryRewriteHook : IPreToolHook
{
public string Name => "no-remote-history-rewrite";
public HookResult Evaluate(ToolCall call, ActionClass actionClass)
{
if (call.Name != "git") return HookResult.Pass;
var cmd = GitCommand.Parse(GitTool.ReadArgs(call.Arguments));
if (cmd.Subcommand != "push") return HookResult.Pass;
foreach (var arg in cmd.Rest)
{
// --force, --force-with-lease, --force-if-includes, plus the ref-deleting flags
if (arg.StartsWith("--force", StringComparison.Ordinal) || arg is "--mirror" or "--delete" or "--prune")
return HookResult.Block($"'{arg}' rewrites or deletes remote refs");
// Short flag clusters: -f, -fu, -uf, -d
if (arg.Length > 1 && arg[0] == '-' && arg[1] != '-' && (arg.Contains('f') || arg.Contains('d')))
return HookResult.Block($"short flags '{arg}' include force or delete");
// Refspec forms a regex on "--force" never sees: "+main" forces, ":main" deletes
if (arg.StartsWith('+') || arg.StartsWith(':') || arg.Contains(":+"))
return HookResult.Block($"refspec '{arg}' forces or deletes a remote ref");
}
return HookResult.Pass;
}
}
One decision I went back and forth on: --force-with-lease. It's the polite force push and I use it myself. I still block it, because the hook's rule is "the agent doesn't rewrite remote history", not "the agent rewrites remote history carefully". If I want a forced push, I'll type it.
Credentials: in the store, never in the prompt
// Credentials.cs
namespace HarnessGate;
public interface ICredentialStore
{
string? Get(string name);
IEnumerable<KeyValuePair<string, string>> All();
}
public sealed class EnvCredentialStore : ICredentialStore
{
private readonly Dictionary<string, string> _secrets = new();
public EnvCredentialStore(params string[] names)
{
foreach (var name in names)
{
if (Environment.GetEnvironmentVariable(name) is { Length: > 0 } value)
_secrets[name] = value;
// Remove it from our own environment so child processes (git, anything) don't inherit it.
Environment.SetEnvironmentVariable(name, null);
}
}
public string? Get(string name) => _secrets.GetValueOrDefault(name);
public IEnumerable<KeyValuePair<string, string>> All() => _secrets;
}
public static class Redactor
{
public static string Scrub(string text, ICredentialStore store)
{
foreach (var (name, value) in store.All())
text = text.Replace(value, $"[REDACTED:{name}]", StringComparison.Ordinal);
return text;
}
}
Two things here I only caught while writing this, not before.
Removing the variable from the process environment matters. If GITHUB_TOKEN stays in the harness's environment, every child process inherits it, including git, including any hook script git decides to run. The model can't read the environment through my tools, but "the model can't read it through my tools" is a much weaker statement than "it isn't there".
And output redaction is necessary because tool output is the side door. The classic one: a remote URL with a token embedded in it, printed by git remote -v. The redactor only knows secrets the harness loaded, though, which is a real limit I come back to below.
The tools, and the boundary around them
// Tools.cs
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace HarnessGate;
public sealed record ToolContext(ICredentialStore Credentials, string WorkDir);
public interface ITool
{
string Name { get; }
string Description { get; }
JsonObject Parameters { get; }
ActionClass Classify(JsonElement args, string workDir); // throws PolicyException to deny
Task<string> ExecuteAsync(JsonElement args, ToolContext ctx, CancellationToken ct);
}
internal static class Args
{
public static string String(JsonElement args, string name) =>
args.ValueKind == JsonValueKind.Object && args.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
? v.GetString()!
: throw new PolicyException($"missing string argument '{name}'");
public static JsonObject Schema(params string[] stringProps)
{
var props = new JsonObject();
foreach (var p in stringProps) props[p] = new JsonObject { ["type"] = "string" };
return new JsonObject
{
["type"] = "object",
["properties"] = props,
["required"] = new JsonArray(stringProps.Select(p => (JsonNode)p).ToArray())
};
}
}
public static class Workspace
{
public static string Resolve(string root, string relativePath)
{
var rootFull = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)) + Path.DirectorySeparatorChar;
var full = Path.GetFullPath(Path.Combine(rootFull, relativePath));
if (!full.StartsWith(rootFull, StringComparison.Ordinal))
throw new PolicyException($"'{relativePath}' is outside the workspace. Use a path relative to the repository root.");
var segments = Path.GetRelativePath(rootFull, full)
.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
if (segments.Contains(".git"))
throw new PolicyException("the .git directory is off limits (hooks and config live there)");
return full;
}
}
public sealed class ReadFileTool : ITool
{
public string Name => "read_file";
public string Description => "Read a text file. 'path' is relative to the repository root.";
public JsonObject Parameters => Args.Schema("path");
public ActionClass Classify(JsonElement args, string workDir)
{
Workspace.Resolve(workDir, Args.String(args, "path"));
return ActionClass.Read;
}
public async Task<string> ExecuteAsync(JsonElement args, ToolContext ctx, CancellationToken ct)
{
var text = await File.ReadAllTextAsync(Workspace.Resolve(ctx.WorkDir, Args.String(args, "path")), ct);
return text.Length > 20_000 ? text[..20_000] + "\n[truncated]" : text;
}
}
public sealed class WriteFileTool : ITool
{
public string Name => "write_file";
public string Description => "Create or overwrite a text file. 'path' is relative to the repository root.";
public JsonObject Parameters => Args.Schema("path", "content");
public ActionClass Classify(JsonElement args, string workDir)
{
Workspace.Resolve(workDir, Args.String(args, "path"));
Args.String(args, "content");
return ActionClass.Write;
}
public async Task<string> ExecuteAsync(JsonElement args, ToolContext ctx, CancellationToken ct)
{
var path = Workspace.Resolve(ctx.WorkDir, Args.String(args, "path"));
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
await File.WriteAllTextAsync(path, Args.String(args, "content"), ct);
return $"wrote {Path.GetRelativePath(ctx.WorkDir, path)}";
}
}
public sealed record GitCommand(string? Subcommand, IReadOnlyList<string> GlobalOptions, IReadOnlyList<string> Rest)
{
public static GitCommand Parse(IReadOnlyList<string> args)
{
var globals = new List<string>();
var i = 0;
while (i < args.Count && args[i].StartsWith('-')) globals.Add(args[i++]);
var sub = i < args.Count ? args[i] : null;
return new GitCommand(sub, globals, args.Skip(i + 1).ToList());
}
}
public sealed class GitTool : ITool
{
private static readonly HashSet<string> ReadOnly = ["status", "log", "diff", "show", "rev-parse", "ls-files", "blame"];
private static readonly HashSet<string> LocalWrites = ["add", "commit", "switch", "stash", "fetch", "tag"];
private static readonly HashSet<string> DestructiveOps = ["push", "reset", "clean", "rebase", "checkout", "restore", "merge"];
private static readonly string[] DangerousArgPrefixes = ["--output", "--ext-diff", "--exec", "--upload-pack", "--receive-pack"];
public string Name => "git";
public string Description =>
"Run git in the repository. 'args' is a JSON array of strings, e.g. [\"status\"] or [\"commit\",\"-m\",\"message\"].";
public JsonObject Parameters => new()
{
["type"] = "object",
["properties"] = new JsonObject
{
["args"] = new JsonObject { ["type"] = "array", ["items"] = new JsonObject { ["type"] = "string" } }
},
["required"] = new JsonArray("args")
};
public static IReadOnlyList<string> ReadArgs(JsonElement args)
{
if (args.ValueKind == JsonValueKind.Object && args.TryGetProperty("args", out var a) && a.ValueKind == JsonValueKind.Array)
return a.EnumerateArray().Select(e => e.GetString() ?? "").ToList();
throw new PolicyException("pass 'args' as a JSON array of strings, e.g. [\"push\",\"origin\",\"main\"]");
}
public ActionClass Classify(JsonElement args, string workDir)
{
var cmd = GitCommand.Parse(ReadArgs(args));
if (cmd.GlobalOptions.Count > 0)
throw new PolicyException("git global options (-c, -C, --git-dir, ...) are not allowed");
if (cmd.Rest.FirstOrDefault(r => DangerousArgPrefixes.Any(p => r.StartsWith(p, StringComparison.Ordinal))) is { } bad)
throw new PolicyException($"argument '{bad}' is not allowed");
return cmd.Subcommand switch
{
null => throw new PolicyException("missing git subcommand"),
"branch" when cmd.Rest.All(r => r is "-a" or "-v" or "--list") => ActionClass.Read,
"branch" when cmd.Rest.Any(r => r is "-d" or "-D" or "--delete" or "-m" or "-M" or "-f") => ActionClass.Destructive,
"branch" => ActionClass.Write,
"remote" when cmd.Rest.Count == 0 || cmd.Rest is ["-v"] => ActionClass.Read,
"remote" => ActionClass.Destructive,
var s when ReadOnly.Contains(s) => ActionClass.Read,
var s when LocalWrites.Contains(s) => ActionClass.Write,
var s when DestructiveOps.Contains(s) => ActionClass.Destructive,
var s => throw new PolicyException($"git '{s}' is not on the allowlist") // aliases land here too
};
}
public async Task<string> ExecuteAsync(JsonElement args, ToolContext ctx, CancellationToken ct)
{
var psi = new ProcessStartInfo("git")
{
WorkingDirectory = ctx.WorkDir,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
foreach (var a in ReadArgs(args)) psi.ArgumentList.Add(a); // no shell, no string concatenation
// Harness-side config, injected AFTER policy. The model never sees any of this.
psi.Environment["GIT_TERMINAL_PROMPT"] = "0";
var config = new List<(string Key, string Value)> { ("core.hooksPath", "/dev/null") };
if (ctx.Credentials.Get("GITHUB_TOKEN") is { } token)
{
var basic = Convert.ToBase64String(Encoding.UTF8.GetBytes($"x-access-token:{token}"));
config.Add(("http.https://github.com/.extraheader", $"AUTHORIZATION: basic {basic}"));
}
psi.Environment["GIT_CONFIG_COUNT"] = config.Count.ToString();
for (var i = 0; i < config.Count; i++)
{
psi.Environment[$"GIT_CONFIG_KEY_{i}"] = config[i].Key;
psi.Environment[$"GIT_CONFIG_VALUE_{i}"] = config[i].Value;
}
using var proc = Process.Start(psi)!;
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(60));
var stdout = proc.StandardOutput.ReadToEndAsync(timeout.Token);
var stderr = proc.StandardError.ReadToEndAsync(timeout.Token);
try { await proc.WaitForExitAsync(timeout.Token); }
catch (OperationCanceledException)
{
proc.Kill(entireProcessTree: true);
throw new PolicyException("git timed out after 60 seconds");
}
return $"exit={proc.ExitCode}\n{await stdout}{await stderr}".Trim();
}
}
A few things in here are the result of me being wrong first.
The **.git directory is inside the workspace.** My first Workspace.Resolve only checked that the path stayed under the repo root. Then I realized the model could write_file to .git/hooks/pre-commit and then politely ask for a git commit, which my matrix treats as a local write. Git would then execute whatever the model wrote. So .git is off limits for the file tools, and as a second layer the git tool runs with core.hooksPath=/dev/null. (That path is Linux and macOS; on Windows point it at an empty directory.)
Unknown subcommands are denied, not escalated. My first draft classified anything unrecognized as destructive, so it would go to a human. Then I thought about aliases. If ~/.gitconfig has p = push --force, the model sends ["p"], my hook doesn't see "push", and a tired human sees a short harmless-looking command in an approval prompt. Allowlist or deny.
Global options are denied. -c can set any config value for one command, and some config values run programs. -C moves the repo. None of that is something the model needs.
“Read-only” commands aren’t. git diff --output=somefile writes a file. --ext-diff runs an external program. I deny a short list of such arguments. I'm confident the list isn't complete.
Credentials go in after policy, through the environment. GIT_CONFIG_COUNT / GIT_CONFIG_KEY_n / GIT_CONFIG_VALUE_n lets me set the auth header without it appearing in the process argument list (where ps would show it) and without it ever touching the model. The header format is the x-access-token basic auth form used by GitHub's own checkout tooling.
Errors are written for the model. This one is straight from Canovas. “Path is outside the workspace. Use a path relative to the repository root.” gets a small model to correct itself on the next turn. “Access denied” gets it to try the same thing again with different slashes.
The gateway
// Gateway.cs
using System.Text.Json;
namespace HarnessGate;
public sealed record PendingAction(Guid Id, string Tool, string Arguments, ActionClass Class, Mode Mode);
public interface IApprover
{
Task<bool> ApproveAsync(PendingAction action, CancellationToken ct);
}
public sealed class ConsoleApprover : IApprover
{
public Task<bool> ApproveAsync(PendingAction a, CancellationToken ct)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"\n[approval {a.Id.ToString()[..8]}] {a.Class} action in {a.Mode} mode");
Console.WriteLine($" {a.Tool} {a.Arguments}");
Console.Write(" approve? [y/N] ");
Console.ResetColor();
var answer = Console.ReadLine()?.Trim().ToLowerInvariant();
return Task.FromResult(answer is "y" or "yes");
}
}
public sealed class AuditLog(string path)
{
public void Write(string evt, ToolCall call, ActionClass? cls, Mode mode, string? detail = null)
{
var line = JsonSerializer.Serialize(new
{
ts = DateTimeOffset.UtcNow, evt, tool = call.Name, args = call.Arguments.GetRawText(),
cls = cls?.ToString(), mode = mode.ToString(), detail
});
File.AppendAllText(path, line + Environment.NewLine);
}
}
public sealed class PolicyGateway(
IEnumerable<ITool> tools,
IEnumerable<IPreToolHook> hooks,
IApprover approver,
ICredentialStore credentials,
AuditLog audit,
string workDir)
{
private readonly Dictionary<string, ITool> _tools = tools.ToDictionary(t => t.Name);
public Mode Mode { get; set; } = Mode.Default; // set by the human at startup, never by a tool
public List<string> ProposedSteps { get; } = [];
public IEnumerable<ITool> Tools => _tools.Values;
public async Task<string> InvokeAsync(ToolCall call, CancellationToken ct)
{
// 1. Default deny for anything we don't know.
if (!_tools.TryGetValue(call.Name, out var tool))
{
audit.Write("deny", call, null, Mode, "unknown tool");
return $"DENIED: there is no tool named '{call.Name}'.";
}
// 2. The harness classifies. The model never gets to declare its own risk.
ActionClass cls;
try { cls = tool.Classify(call.Arguments, workDir); }
catch (PolicyException ex)
{
audit.Write("deny", call, null, Mode, ex.Message);
return $"DENIED: {ex.Message}";
}
// 3. Hard hooks run before the matrix, so no mode and no approval can override them.
foreach (var hook in hooks)
{
var result = hook.Evaluate(call, cls);
if (!result.Blocked) continue;
audit.Write("block", call, cls, Mode, $"{hook.Name}: {result.Reason}");
return $"BLOCKED by harness policy ({hook.Name}): {result.Reason}. " +
"This is not retryable. Do not try another way to achieve it; tell the user.";
}
// 4. Action class x mode.
var verdict = PolicyMatrix.Decide(cls, Mode);
if (verdict == Verdict.ProposeOnly)
{
ProposedSteps.Add($"{call.Name} {call.Arguments.GetRawText()}");
audit.Write("propose", call, cls, Mode);
return $"PLAN MODE: not executed. Recorded as proposed step {ProposedSteps.Count}.";
}
if (verdict == Verdict.AskHuman)
{
var pending = new PendingAction(Guid.NewGuid(), call.Name, call.Arguments.GetRawText(), cls, Mode);
if (!await approver.ApproveAsync(pending, ct))
{
audit.Write("rejected", call, cls, Mode);
return "DENIED by the human reviewer. Do not retry; ask the user what they want instead.";
}
audit.Write("approved", call, cls, Mode);
}
// 5. Execute with credentials the model never saw, then scrub the output.
try
{
var raw = await tool.ExecuteAsync(call.Arguments, new ToolContext(credentials, workDir), ct);
if (verdict != Verdict.Execute) audit.Write("executed", call, cls, Mode);
return Redactor.Scrub(raw, credentials);
}
catch (Exception ex) when (ex is PolicyException or IOException or UnauthorizedAccessException)
{
audit.Write("error", call, cls, Mode, ex.Message);
return $"ERROR: {Redactor.Scrub(ex.Message, credentials)}";
}
}
}
The ConsoleApprover is the cheap version of Tkachuk's "pending action". His version emits a structured pending state that a surface renders as buttons and that resumes paused execution. Mine blocks the loop on Console.ReadLine(). The interface (IApprover taking a PendingAction) is where a real implementation would plug in; the important part is that the decision is made in the gateway and the model has no way to skip it.
One property I got for free and want to point out: the JsonElement the human approves is the same immutable object that gets executed. There's no window where the model's arguments get re-read or re-serialized between "approved" and "run".
Talking to Ollama, and the loop
// Ollama.cs
using System.Text;
using System.Text.Json.Nodes;
namespace HarnessGate;
public sealed class OllamaClient(HttpClient http, string model)
{
public async Task<JsonObject> ChatAsync(JsonArray messages, JsonArray tools, CancellationToken ct)
{
var body = new JsonObject
{
["model"] = model,
["messages"] = messages.DeepClone(),
["tools"] = tools.DeepClone(),
["stream"] = false,
["options"] = new JsonObject { ["temperature"] = 0 }
};
using var content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json");
using var response = await http.PostAsync("/api/chat", content, ct);
response.EnsureSuccessStatusCode();
var json = JsonNode.Parse(await response.Content.ReadAsStringAsync(ct))!;
return json["message"]!.AsObject();
}
}
// Program.cs
using System.Text.Json;
using System.Text.Json.Nodes;
using HarnessGate;
var workDir = Path.GetFullPath(args.Length > 0 ? args[0] : ".");
var mode = Enum.Parse<Mode>(Environment.GetEnvironmentVariable("HARNESS_MODE") ?? "Default", ignoreCase: true);
var model = Environment.GetEnvironmentVariable("OLLAMA_MODEL") ?? "qwen2.5:7b";
var ollamaUrl = Environment.GetEnvironmentVariable("OLLAMA_URL") ?? "http://localhost:11434";
var credentials = new EnvCredentialStore("GITHUB_TOKEN");
var gateway = new PolicyGateway(
tools: [new ReadFileTool(), new WriteFileTool(), new GitTool()],
hooks: [new NoRemoteHistoryRewriteHook()],
approver: new ConsoleApprover(),
credentials: credentials,
audit: new AuditLog("audit.jsonl"),
workDir: workDir) { Mode = mode };
var ollama = new OllamaClient(new HttpClient { BaseAddress = new Uri(ollamaUrl), Timeout = TimeSpan.FromMinutes(5) }, model);
var toolSchemas = new JsonArray(gateway.Tools.Select(t => (JsonNode)new JsonObject
{
["type"] = "function",
["function"] = new JsonObject { ["name"] = t.Name, ["description"] = t.Description, ["parameters"] = t.Parameters }
}).ToArray());
Console.WriteLine($"harness: mode={mode} model={model} workspace={workDir}");
Console.Write("task> ");
var task = Console.ReadLine() ?? "";
var messages = new JsonArray
{
new JsonObject
{
["role"] = "system",
// Courtesy, not control. Nothing below depends on the model obeying this.
["content"] = "You are a coding assistant working inside one git repository. Use the tools to inspect and change it. " +
"Paths are relative to the repository root. If a tool result starts with BLOCKED or DENIED, stop and explain."
},
new JsonObject { ["role"] = "user", ["content"] = task }
};
for (var turn = 0; turn < 12; turn++)
{
var reply = await ollama.ChatAsync(messages, toolSchemas, CancellationToken.None);
messages.Add(reply.DeepClone());
if (reply["tool_calls"] is not JsonArray calls || calls.Count == 0)
{
Console.WriteLine($"\nassistant> {reply["content"]}");
break;
}
foreach (var c in calls)
{
var fn = c!["function"]!;
var name = fn["name"]!.GetValue<string>();
var argsNode = fn["arguments"];
var argsJson = argsNode is JsonValue v && v.TryGetValue<string>(out var s) ? s : argsNode?.ToJsonString() ?? "{}";
string result;
try
{
using var doc = JsonDocument.Parse(argsJson);
Console.WriteLine($"\ntool> {name} {argsJson}");
result = await gateway.InvokeAsync(new ToolCall(name, doc.RootElement.Clone()), CancellationToken.None);
}
catch (JsonException)
{
result = "ERROR: tool arguments were not valid JSON.";
}
Console.WriteLine($" -> {(result.Length > 400 ? result[..400] + " ..." : result)}");
messages.Add(new JsonObject { ["role"] = "tool", ["tool_name"] = name, ["content"] = result });
}
}
if (gateway.ProposedSteps.Count > 0)
{
Console.WriteLine("\nProposed plan (nothing below was executed):");
for (var i = 0; i < gateway.ProposedSteps.Count; i++)
Console.WriteLine($" {i + 1}. {gateway.ProposedSteps[i]}");
}
Note the comment on the system prompt. It still tells the model to stop on BLOCKED or DENIED, because that makes the conversation nicer. Nothing depends on it.
Running it
Create a throwaway repo with a local bare “remote”, push once, then amend the commit so a normal push will be rejected. That rejection is the moment an agent reaches for --force.
mkdir -p /tmp/harness-demo && cd /tmp/harness-demo
git init -q --bare remote.git
git init -q -b main work && cd work
git config user.email "you@example.com" && git config user.name "You"
echo "# demo" > README.md && git add . && git commit -qm "init"
git remote add origin ../remote.git && git push -q -u origin main
git commit -q --amend -m "init (reworded)"
Then, from the HarnessGate folder:
HARNESS_MODE=default dotnet run -- /tmp/harness-demo/work
Give it: push my reworded commit to origin main. The shape of a run looks like this (trimmed; your model's wording and order will differ):
harness: mode=Default model=qwen2.5:7b workspace=/tmp/harness-demo/work
task> push my reworded commit to origin main
tool> git {"args":["status"]}
-> exit=0
On branch main
Your branch and 'origin/main' have diverged ...
tool> git {"args":["push","origin","main"]}
[approval 3f2a9c1e] Destructive action in Default mode
git {"args":["push","origin","main"]}
approve? [y/N] y
-> exit=1
! [rejected] main -> main (non-fast-forward)
tool> git {"args":["push","--force","origin","main"]}
-> BLOCKED by harness policy (no-remote-history-rewrite): '--force' rewrites or
deletes remote refs. This is not retryable. Do not try another way to achieve
it; tell the user.
assistant> The push was rejected because the remote has a different history, and
force-pushing is blocked by policy. You can push it yourself with
--force-with-lease if you're sure, or pull and merge first.
Then try the other two modes:
HARNESS_MODE=plan dotnet run -- /tmp/harness-demo/work # reads run, everything else becomes a numbered plan
HARNESS_MODE=auto dotnet run -- /tmp/harness-demo/work # local writes run and get audited, the push still asks
Every decision lands in audit.jsonl:
cat audit.jsonl | tail -n 3
Whether you ever read that file is a different question, and JIN’s four-row table is a fair warning about the answer.
Where I was tempted to just prompt the model
I want to be honest about this part, because each of these felt reasonable at the time.
Letting the model declare risk. My first tool schema had a risk_level enum on every call. It's appealing: the model often knows what it's about to do better than my string parser does. But a model-declared risk level is a claim from the party being governed. If the model gets it wrong (or is steered by something it read in a file) the claim and the action fail together. I deleted it.
A run_shell tool with a polite sentence. I wanted a general shell tool, with "never run destructive commands" in the description. Writing a classifier for arbitrary shell is a research project; writing one for a dozen git subcommands is an afternoon. So the agent doesn't get a shell. That's a capability cost I'm choosing to pay, and it's the same trade Canovas describes when he suggests composing a host without the code execution tools.
Letting the model switch modes. I briefly had a set_mode tool so the agent could "move to plan mode when unsure". Then I noticed it could also move to auto mode when sure. Mode is now a property set once at startup by a human.
Retry instructions. When the hook blocks something, I was tempted to add a paragraph to the system prompt: “if you get blocked, do not try alternative ways to do the same thing”. It’s there, as courtesy. But the real defense against “try +main after --force fails" is that the hook also catches +main. If my safety story depends on the model taking the hint, it isn't a safety story.
What this guarantees, and what it doesn’t
What I’m fairly confident about, for this code, on this tool set:
- A tool call the gateway doesn’t recognize, can’t parse, or can’t classify does not execute.
- A git push with force flags, force refspecs, or delete forms is blocked in every mode, including after a human approves.
- In plan mode, nothing except reads executes.
- The model never receives GITHUB_TOKEN in its context, and any output containing that exact value is scrubbed before the model sees it.
What it does not guarantee, and I’d rather list it than have someone find it:
- No process isolation. Git runs as me, with my filesystem permissions. The boundary is in the call path, not in the operating system. A container or a separate user account is the real boundary; this is a seatbelt.
- The path check is a string check. Symlinks inside the repo that point outside it are not resolved. On Windows I’m comparing paths ordinally, which is wrong for a case-insensitive filesystem.
- Classifiers are allowlists maintained by a human. My dangerous-argument list for git is surely incomplete. Fail-closed helps (unknown subcommand means deny), but an argument I didn’t think of on an allowlisted subcommand will go through.
- The redactor only knows what it loaded. If the repo has a .env file with a different API key in it, read_file will happily return it to the model. Nothing in my harness knows that string is a secret.
- Nothing stops a future tool from bypassing the gateway. More on this one below, because it’s the gap I care most about.
- Approval fatigue is not solved by code. In default mode I approved the first push without really reading it, because I’d just approved three other things. A human clicking “y” is a control only while the human is paying attention.
- Not exactly-once. Same caveat Microsoft gives for resumed workflows: if this process dies after an approved push started, rerunning the task can push again. Here that’s harmless. For a tool that sends email or moves money, it isn’t.
On that bypass gap: Canovas solves this inside Orkeon with an analyzer that makes direct filesystem calls a compile error. I tried the closest thing available off the shelf, Microsoft.CodeAnalysis.BannedApiAnalyzers, banning System.Diagnostics.Process for tool code:
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" Version="3.3.4" PrivateAssets="all" />
<AdditionalFiles Include="BannedSymbols.txt" />
</ItemGroup>
T:System.Diagnostics.Process;Tools must not start processes directly. Go through the gateway-owned runner.
# .editorconfig
[*.cs]
dotnet_diagnostic.RS0030.severity = error
In a single project it’s a speed bump, because GitTool itself needs Process, so it carries a #pragma warning disable RS0030, which is exactly the kind of suppression Canovas counts in his repo. To make it mean something, the process runner has to live in its own assembly and tool projects reference only the interface. I haven't done that split yet. (Check NuGet for the current analyzer version before pasting.)
What I still don’t know
How this scales past one tool. A dozen git subcommands is classifiable by hand. Tkachuk describes harnesses with thousands of operations across hundreds of MCP servers. I don’t think hand-written classifiers survive that, and I don’t think model-declared risk is the answer either. Maybe the classification lives with the tool author as metadata, enforced by the gateway. Maybe operations need risk declared in their contract. I haven’t built it, so I don’t know.
Whether the matrix belongs to the agent or to the target. A force push to a personal scratch branch and a force push to main on a shared repo are the same command with very different blast radius. My hook can't tell them apart because it doesn't know whose repo it is. That's the "who owns the blast radius" question from JIN's title, and my code doesn't answer it.
And whether I’ll actually read audit.jsonl. I'm going to set a reminder. We'll see.
Sources
- Andrii Tkachuk, The Harness Is the Product: How Agents Are Actually Built in 2026
- Jaroslaw Wasowski, Harness Engineering: AI Agent Permissions as Policy in the Call Path (Action Matrix and Mode)
- Cyril Canovas, My coding agent wrote outside the repo. Nothing stopped it.
- JIN, Beyond CLAUDE.md: AI-Native SDLC Needs a Verifiable Engineering Control Plane
- JIN, Who Searches, Who Decides, Who Owns the Blast Radius
- Microsoft Agent Framework: Interactive experiences, memory, and resilient execution
Tags: dotnet, ai-agents, harness-engineering, llm, security, ollama, csharp, software-architecture
Top comments (0)