cd /news/ai-agents/your-ai-coding-agent-needs-a-securit… · home › topics › ai-agents › article
[ARTICLE · art-177852] src=pub.towardsai.net ↗ pub= topic=ai-agents verified=true sentiment=↑ positive

Your AI Coding Agent Needs a Security Harness

Sajid Hossain published a guide describing OpenCode Shield, a five-layer security harness for the OpenCode AI coding agent that relies on global Markdown rule files (AGENTS.md and MEMORY.md) plus OpenCode's built-in permissions list in ~/.config/opencode/opencode.jsonc to block secret reads and gate shell commands. Hossain writes that his first version bundled five background scanner servers, custom Node and Docker wrappers and plugins, which proved too heavy and burned memory before any feature work, so he cut it to the smallest architecture with one job per piece. The harness denies reads of *.env and *.env.* while allowing .env.example, sets shell commands to "ask" by default, and auto-allows npm test * and npm run *, with rules evaluated top to bottom so the last matching rule wins.

recommendation

Enforce agent limits with OpenCode's permissions list rather than prompt rules: deny reads of *.env and *.env.*, default shell to "ask", and allow only specific commands like npm test *, since the last matching rule wins.

more in playbook: Securing agents and AI tools
by read10 min views5 publishedNov 28, 2026

By Sajid Hossain

You ask your AI coding agent to build an app. Within minutes it creates folders, installs libraries, edits settings, and runs commands in your terminal.

Then you stop and wonder: if it accidentally opens my private API keys, runs a destructive terminal command, or ships a broken login screen, what actually stops it?

Typing “please write secure code” in your prompt does not stop it. The AI isn’t trying to cause damage — it just moves quickly with full access to your computer unless you put real safety rails around it.

I learned this the hard way while building OpenCode Shield, a security setup for OpenCode. My first version packed in everything I could find: five separate background scanner servers, custom Node and Docker wrappers, plugins, and long checklists. In daily work, it was simply too heavy. Tools checked the same things twice, wrappers needed upkeep, and running five servers at once burned through memory before I wrote a single feature.

So I stripped the whole setup down to the smallest architecture where every piece has one clear job. Instead of treating security as a panic check right before launch, this harness wraps five simple layers around OpenCode as you build — starting with a universal markdown files for every project, plus optional rules inside special repositories.

A security harness should never interrupt your flow on every prompt. While you are sketching layouts, trying ideas, and iterating quickly, only quiet background guardrails run — you won’t even notice them unless the AI tries to open real secrets or run a destructive command. Checkers and code scanners wait for natural s like adding logins, touching a database, or getting ready to push.

Every time you open a project in OpenCode, it looks inside your computer’s global OpenCode folder (~/.config/opencode/). Putting your universal rules there means you set them up once and get them everywhere—instead of copying files into every new app.

This layer starts with two plain Markdown files: AGENTS.md and MEMORY.md. Think of AGENTS.md as the standing rulebook: keep secrets private, for a review after changing logins or database code, and never mark something "safe" unless a real check actually ran (Pass, Fail, Not Tested, or Accepted Risk). MEMORY.md holds steady reminders, like preferring local scanners over guesswork and never testing outside websites you don't own.

One OpenCode quirk trips almost everyone up: OpenCode reads ~/.config/opencode/AGENTS.md automatically, but it ignores MEMORY.md unless you tell it to load that file. To keep MEMORY.md active across projects, list it inside the instructions array in ~/.config/opencode/opencode.jsonc.

Use written rules to steer habits — not to enforce hard boundaries. In a long chat, an AI can lose focus and skip a written rule. Hard locks come from OpenCode’s built-in permissions list inside opencode.jsonc.

If you are updating an older OpenCode config, check the names carefully. Current OpenCode uses permissions (plural) instead of permission, shell instead of bash, and subagent instead of task. Rules are read from top to bottom, and the last matching rule wins. That lets you set one broad safety rule and carve out tiny exceptions right below it.

Never wipe out your existing opencode.jsonc—just merge the instructions and permissions blocks into it:

~/.config/opencode/opencode.jsonc
{  "$schema": "https://opencode.ai/config.json",  "instructions": [    "~/.config/opencode/MEMORY.md"  ],  "permissions": [    { "action": "read", "resource": "*", "effect": "allow" },    { "action": "read", "resource": "*.env", "effect": "deny" },    { "action": "read", "resource": "*.env.*", "effect": "deny" },    { "action": "read", "resource": ".env.example", "effect": "allow" },    { "action": "shell", "resource": "*", "effect": "ask" },    { "action": "shell", "resource": "npm test *", "effect": "allow" },    { "action": "shell", "resource": "npm run *", "effect": "allow" },    { "action": "shell", "resource": "pytest *", "effect": "allow" },    { "action": "shell", "resource": "git status *", "effect": "allow" },    { "action": "shell", "resource": "git diff *", "effect": "allow" },    { "action": "shell", "resource": "git push *", "effect": "deny" }  ]}

Built-in locks block actions silently or ask you yes-or-no. Plugins go one step further: they look inside what the AI is about to do, stop risky requests right before they run, and explain why so the AI adjusts cleanly. From the OpenCode Shield repository, I kept just two small TypeScript plugins — env-protection and command-guard—both MIT-licensed and stored inside ~/.config/opencode/plugins/.

In OpenCode V2, point the plural plugins array in opencode.jsonc at the plugin folder paths (not individual .ts files, which OpenCode skips if referenced directly in config):

~/.config/opencode/opencode.jsonc (plugins)
~/.config/opencode/opencode.jsonc (plugins){  "plugins": [    "~/.config/opencode/plugins/env-protection",    "~/.config/opencode/plugins/command-guard"  ]}

Be honest about what plugins cannot catch: a plugin guarding the “read file” tool only watches the “read file” tool. If an agent runs cat .env in the terminal or opens a shortcut link pointing to .env, env-protection never sees it. Pattern-based command checks can also be tricked by unusual quoting or split commands. That is why plugins work as a helpful second lock backing up permissions, never as a wall by themselves.

Asking the same AI chat that just wrote a shortcut to grade its own security is like letting a builder sign off on their own electrical wiring. When the context is full of implementation details, the model naturally assumes its own fix worked.

“An AI that rushed a feature shouldn’t judge if its own fix is safe”

Earlier drafts of OpenCode Shield split guidance across multiple borrowed skills (reviewing-security and security-agent). To keep things light, I merged the core habits into one global skill at ~/.config/opencode/skills/security-baseline/SKILL.md. Whenever OpenCode works on logins, file uploads, user forms, or database calls, that skill gives it a simple three-step habit:

Instructions alone don’t give you an independent second pair of eyes. So I paired that single skill with three small, read-only helper agents in ~/.config/opencode/agents/—each with one narrow job:

Notice you do not run all three helpers during rapid prototyping. Skip security-planner on a simple weekend script or UI experiment—save it for apps with logins, payments, or user accounts. Let the main AI iterate freely while you build, and bring in security-auditor and security-verifier at natural s before shipping.

Notice two important rules here. First, each helper agent in OpenCode V2 defines its own permissions inside its file—it does not automatically copy the main agent's locks. By denying edit on all three checkers, none of them can quietly alter your code while reviewing it; the main agent fixes bugs, and security-verifier checks the result cleanly:

~/.config/opencode/agents/security-verifier.md
---description: Checks security fixes by inspecting diffs and re-running scanners without editing code.mode: subagentpermissions:  - action: edit    resource: "*"    effect: deny  - action: shell    resource: "*"    effect: ask  - action: shell    resource: "git diff *"    effect: allow  - action: shell    resource: "gitleaks *"    effect: allow  - action: shell    resource: "trivy *"    effect: allow---Inspect the diff for the reported security fix. Re-run the relevantscanner or check. with concrete evidence. Never mark a finding as Pass unless the check actually ran. after the final edit. List anything you did not test.

Second, be realistic about when these helpers run: OpenCode decides when to call a subagent, or you ask for one directly. Writing rules in AGENTS.md nudges the main agent to call security-planner or security-auditor at the right moment, and subagent rules in opencode.jsonc control which helpers it may launch—but no Markdown file can force the AI to call them every single time. That is why Layer 4 uses real scanners and automatic GitHub checks.

This layer is where I cut the most clutter. My first repo wired up five separate scanner integrations, complete with custom background servers and Docker wrappers — even for tools that already run cleanly in one terminal line. Keeping custom wrappers around simple command-line tools creates extra things that break without catching more bugs.

The lean rule is simple: one tool per lane, 100% free and open source for local scans, no mandatory paid accounts.

Semgrep reads your source code the way an experienced reviewer would — spotting common coding mistakes like SQL commands glued together from user input, weak password checks, or unsafe data handling. Its local Community Edition engine is LGPL-2.1 open source and works offline without a paid subscription (commercial team dashboards exist separately, and you do not need them).

Semgrep is the only security server (mcp) I keep wired into opencode.jsonc, because structured code warnings integrate cleanly inside OpenCode. One crucial ecosystem fix: do not install the old standalone semgrep/mcp GitHub repo, which was archived in October 2025. The maintained server now ships built right into Semgrep itself via semgrep mcp under mcp.servers:

~/.config/opencode/opencode.jsonc (mcp.servers)
{  "mcp": {    "servers": {      "semgrep": {        "type": "local",        "command": ["semgrep", "mcp"]      }    }  }}

Setup note: On Mac and Linux, install Semgrep with Homebrew or pipx and it works straight away. On Windows, run Semgrep inside WSL2 and point OpenCode at ["wsl", "semgrep", "mcp"].

Gitleaks (MIT license) has one job: finding API keys, tokens, and passwords left behind in your files or hidden in past Git commits. Deleting a key later doesn’t erase it from Git history — anyone who clones the repo can still read old saves. Running Gitleaks directly from the terminal (gitleaks git . for repos or gitleaks dir . for plain folders) replaces both custom wrappers and older deprecated commands like gitleaks protect. Prebuilt binaries drop straight into your PATH on Windows, Mac, and Linux.

Most modern apps rely on dozens of borrowed open-source packages listed in package-lock.json, requirements.txt, or go.mod, plus setup files like Dockerfile. Trivy (Apache-2.0 license) checks all of them with one command: trivy fs --scanners vuln,misconfig,secret .. No extra server needed—just one clear report showing risky libraries or exposed cloud settings before you deploy.

File scanners cannot see what happens once your server starts running — things like missing browser security headers or unsafe cookies. When you build a web app or API, OWASP ZAP (Apache-2.0) fills that gap as a strictly optional tool. Only point it at local or staging apps you own or have permission to test, and know the difference between its two modes: zap-baseline.py gently observes a running site, while zap-full-scan.py fires active attacks. For scripts, CLI tools, or static libraries, skip ZAP completely.

Remember that AI subagents only run when the model chooses to call them (or when you ask). So your final safety net should never depend on AI memory. In OpenCode Shield, .github/workflows/security.yml runs Gitleaks and Semgrep automatically every time code is pushed or a pull request opens—catching leaks before they hit main.

Put those four global layers together and you have Iteration 1: your universal baseline. Every new project you open immediately inherits your rules, locks, plugins, checklist, three checkers, and scanners — without copying setup files everywhere.

Iteration 2 adds extra rules inside one specific project when that domain carries unusual risks. Take an algorithmic trading research repo as a clear example. Code can pass every Semgrep check and look completely clean, yet still lose real money if a test simulation accidentally reads tomorrow’s data or sends an order to a live brokerage account.

For trading research projects, I place a project-only skill inside .opencode/skills/openagent-trade-research/SKILL.md (alongside local notes in the project's AGENTS.md). Inspired by the workflow in spbRusty/openagent_trade_architecture, it requires logging experiments, checking numbers carefully, and strictly separating practice simulations from live money. Because openagent_trade_architecture has no visible license file on GitHub, I wrote our project skill cleanly from scratch under MIT instead of copying someone else's text.

Keeping those domain rules local solves two problems at once: unrelated web apps never waste tokens reading trading rules, and the trading project still inherits every global lock and scanner without repeating a single line.

Saving a config file proves only that the file exists — not that it blocks anything when an AI agent starts moving fast. Run these five quick checks once after setting things up:

No collection of prompts, plugins, checkers, or scanners makes an app unbreakable. Knowing exactly where this harness stops is what makes it trustworthy:

A good security harness isn’t the one with the most pop-ups, servers, or checklists. It stays invisible while you build in flow, steps in smoothly before risky changes ship, and stays light enough that you actually leave it turned on every day.

Your AI Coding Agent Needs a Security Harness was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.

── more in #ai-agents 4 stories · sorted by recency
── more on @sajid hossain 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/your-ai-coding-agent…] indexed:0 read:10min 2026-11-28 · —