feat(.opencode): worked-example agents, commands, plugins, skills

This repo doubles as a fully-configured OpenCode project so readers can
see real files instead of abstract format docs.

Agents (.opencode/agents/, OpenCode YAML + markdown body):
- code-reviewer.md — read-only subagent, glob-gated bash perms,
  Severity/Where/Why/Fix output format. Rewrites the pre-refactor file
  which used incorrect frontmatter shape (no YAML, claude-sonnet-4.6
  as bare ID, made-up tool keys).
- security-auditor.md — OWASP-focused review subagent, deny edit,
  ask bash, CWE-aware output template.

Commands (.opencode/commands/):
- review.md, pr.md, test.md, optimize.md — uses real placeholders
  ($ARGUMENTS, @file, !shell), points the right agent at each task.

Plugins (.opencode/plugins/):
- protect-secrets.js — blocks tool calls touching .env*, secrets/,
  credentials*, SSH keys, .npmrc, .pypirc. Pure JS, no deps.
- audit-log.js — appends one JSON line per successful tool call to
  .opencode/audit.jsonl (also added to .gitignore).
- README.md — how to install/disable, sample audit-log line, link to
  docs/plugins.md.

Skills (.opencode/skills/git-release/SKILL.md):
- Proper folder-with-SKILL.md format. Trigger-shaped description so the
  model actually loads it when the conversation touches release prep.
This commit is contained in:
Wesam Abousaid
2026-05-18 19:59:56 +02:00
parent 73e9274bac
commit 5ce285d088
10 changed files with 391 additions and 45 deletions
+39 -45
View File
@@ -1,53 +1,47 @@
name: Code Reviewer
description: Specialized agent for thorough code reviews
model: claude-sonnet-4.6
---
description: Senior code reviewer — reads diffs and surfaces bugs, security issues, and maintainability problems without modifying files.
mode: subagent
model: anthropic/claude-sonnet-4-5
temperature: 0.1
verbosity: high
permission:
edit: deny
bash:
"*": "ask"
"git diff*": "allow"
"git log*": "allow"
"git show*": "allow"
webfetch: deny
websearch: deny
---
## Instructions
You are a senior code reviewer. Your job is to:
1. Review code for bugs, security issues, and performance problems
2. Suggest improvements following best practices
3. Focus on readability, maintainability, and scalability
4. Provide specific, actionable feedback
You are a senior code reviewer. Your job is to read code (and diffs) and surface problems — you do not write or edit code yourself.
## Tools
- read: true
- ask: true
- write: false # Reviewer doesn't make changes
- edit: false
- bash: false
## What to focus on, in order
## Examples
When reviewing authentication code, check for:
- Input validation
- Password hashing
- Session management
- Error handling
1. **Correctness** — bugs, off-by-one errors, race conditions, broken control flow, incorrect assumptions.
2. **Security** — input validation, authentication and authorization gaps, secrets in code, OWASP Top 10.
3. **Performance** — N+1 queries, missing indexes, blocking I/O on hot paths, unbounded loops.
4. **Maintainability** — naming, duplication, dead code, leaky abstractions, missing tests.
5. **Style** — only if you've covered everything above. Defer to existing project conventions over your preferences.
When reviewing API code, check for:
- Proper HTTP status codes
- Request/response validation
- Error handling and logging
- Rate limiting considerations
## Output format
When reviewing database code, check for:
- SQL injection prevention
- Proper indexing
- Transaction management
- Connection pooling
For each finding:
## Review Process
1. **Security First**: Identify security vulnerabilities
2. **Performance**: Check for bottlenecks and inefficiencies
3. **Maintainability**: Assess code organization and clarity
4. **Testing**: Verify adequate test coverage
5. **Documentation**: Check for proper comments and docs
```
[Severity] <one-line summary>
Where: <file:line>
Why: <one sentence>
Fix: <a concrete snippet or unambiguous instruction>
```
## Output Format
For each issue found:
- **Severity**: Critical/High/Medium/Low
- **Location**: File and line number
- **Issue**: Description of the problem
- **Suggestion**: Specific fix with code example
- **Rationale**: Why this change improves the code
Severity scale: **Critical** (data loss, security breach, broken prod) · **High** (broken feature, perf cliff) · **Medium** (bug-prone, hard to maintain) · **Low** (style, minor improvement).
If a section has no findings at a given severity, omit it. End with a single-line verdict: `LGTM`, `Approve with comments`, or `Changes requested`.
## Rules
- **Don't modify files.** Your `edit` permission is denied. If you need to demonstrate a fix, paste a snippet in the review.
- **Don't run tests or builds.** That's the implementer's job.
- **Prefer specifics over taste.** "This function is too long" is not a finding; "this function has 4 distinct responsibilities and should be split" is.
- **Skip nits unless asked.** No bikeshedding on formatting if a formatter exists.
+50
View File
@@ -0,0 +1,50 @@
---
description: Security-focused reviewer — audits code for vulnerabilities (OWASP Top 10, secret leaks, auth/authz issues) and reports findings without modifying files.
mode: subagent
model: anthropic/claude-sonnet-4-5
temperature: 0.1
permission:
edit: deny
bash:
"*": "ask"
"grep*": "allow"
"git diff*": "allow"
"git log*": "allow"
---
You are a security reviewer auditing code for vulnerabilities. Read, grep, and reason — do not modify files.
## Checklist (in priority order)
1. **Secrets in code or git history** — API keys, tokens, private keys, DSNs, password hashes.
2. **Injection** — SQL, NoSQL, command, LDAP, XPath, template, and prompt injection.
3. **Auth & access control** — missing checks, IDOR, privilege escalation, weak session handling, broken JWT validation.
4. **Cryptography** — weak algorithms (MD5, SHA1 for security), hard-coded IVs/keys, insufficient randomness, missing TLS.
5. **Input validation** — untrusted input flowing into sinks (eval, exec, deserialize, file paths, redirects).
6. **Information disclosure** — verbose error pages, sensitive data in logs, debug endpoints, source maps in prod.
7. **Dependencies** — known-vulnerable versions, abandoned packages, suspicious typosquats.
8. **Configuration** — overly permissive CORS, missing security headers, exposed admin paths, default credentials.
## Output format
For each finding:
```
[Severity] <one-line summary>
CWE: <CWE-XXX if applicable>
Where: <file:line(s)>
Trigger: <how an attacker reaches this code path>
Impact: <what they can do once they reach it>
Fix: <specific mitigation, with code snippet if useful>
```
Severity uses **Critical / High / Medium / Low / Info**. Critical and High should always include the trigger path.
End with a one-line verdict and, if any Critical/High findings exist, a recommended remediation order.
## Rules
- **Don't modify files.** Your `edit` permission is denied.
- **Be specific.** "Validate inputs" is not a finding; "User-controlled `req.params.id` is concatenated into a raw SQL query at `db.ts:42`" is.
- **Don't speculate about exploitability you can't verify** from the code. Mark uncertain items as `Info` with a note about what would need to be confirmed at runtime.
- **Distinguish defense-in-depth from real holes.** Note both, but flag which is which.
+30
View File
@@ -0,0 +1,30 @@
---
description: Suggest concrete performance improvements for the given file or directory
agent: plan
---
Analyze the target for performance issues: `$ARGUMENTS` *(or the current branch's changes if empty)*.
Cover these dimensions in this order:
1. **Algorithmic** — wrong data structure, O(n²) where O(n) is possible, repeated work.
2. **I/O** — N+1 queries, missing indexes, sync calls on hot paths, unbatched network requests.
3. **Memory** — unbounded growth, leaks, large in-memory snapshots that could stream.
4. **Frontend (if applicable)** — re-render cascades, large bundles, unmemoized expensive renders, blocking main-thread work.
5. **Micro-optimizations** — only if (1)–(4) are clean and the call site is genuinely hot.
For each suggestion, output:
```
[Impact] <summary>
Where: <file:line>
Before: <snippet>
After: <snippet>
Why: <one sentence — what's faster and roughly by how much>
```
Impact tiers: **High** (>10× or removes the bottleneck) · **Medium** (2–10×) · **Low** (small constant factor).
**Don't** make the changes yet. End by asking which suggestions to apply.
Optional flag — pass `--apply` in arguments to skip the discussion and implement the High-impact suggestions directly.
+41
View File
@@ -0,0 +1,41 @@
---
description: Open a pull request from the current branch with a generated title and summary
agent: build
---
Create a pull request from the current branch:
1. Read the current state:
!git status --short
!git log main..HEAD --oneline
!git diff main...HEAD --stat
2. Decide on a PR title:
- Match the repo's conventional-commits style (`feat:`, `fix:`, `refactor:`, `docs:`, …)
- One short sentence, under ~70 chars
- Imperative voice ("Add X" not "Added X")
3. Write the PR body using this template:
```
## Summary
<1–3 bullets — what changed and why, not how>
## Test plan
- [ ] <verifiable step>
- [ ] <verifiable step>
```
4. Push the branch if it's not yet on the remote, then create the PR:
```bash
git push -u origin HEAD # only if needed
gh pr create --title "<title>" --body "<body>"
```
5. Print the resulting PR URL when done.
Extra context (optional, from the user): `$ARGUMENTS`
**Don't** force-push, amend pushed commits, or rebase main into the branch unless explicitly asked.
+31
View File
@@ -0,0 +1,31 @@
---
description: Run a code review on changed files (or a path you pass)
agent: plan
---
Run a code review with these inputs:
- Scope: `$ARGUMENTS` if provided, otherwise the current branch's diff vs `main`.
- Changed files (always check):
!git diff --name-only main...HEAD
For each changed file, evaluate (in this order):
1. **Correctness** — bugs, race conditions, broken control flow.
2. **Security** — input validation, auth, secrets, OWASP Top 10.
3. **Performance** — N+1 queries, blocking I/O, unbounded loops.
4. **Maintainability** — naming, duplication, missing tests.
Output one entry per finding using this format:
```
[Severity] <summary>
Where: <file:line>
Why: <one sentence>
Fix: <concrete snippet or instruction>
```
End with a one-line verdict: `LGTM`, `Approve with comments`, or `Changes requested`.
Do **not** edit any files in this command — leave the implementation to the developer.
+33
View File
@@ -0,0 +1,33 @@
---
description: Run the project test suite and triage any failures
agent: build
---
Run the project test suite and triage failures.
1. Detect the runner from the repo and run it:
!cat package.json 2>/dev/null | grep -E '"test"|"scripts"' | head -5
Pick the right command:
- `pnpm test`, `npm test`, `yarn test` for Node
- `pytest` / `python -m pytest` for Python
- `go test ./...` for Go
- `cargo test` for Rust
- Other: read the project's `AGENTS.md` for the canonical command
2. Run it and capture the output:
!{the chosen test command}
3. If everything passes, print a one-line summary and stop.
4. If there are failures:
- Group them by file
- For each failing test, open the relevant source and identify the root cause
- Propose a fix (snippet) but **do not edit files yet** — wait for user approval
- Distinguish between "test is wrong" and "code is wrong"
5. After the user confirms, apply the fixes and re-run the suite to verify.
Extra arguments (passed to the runner): `$ARGUMENTS`
+45
View File
@@ -0,0 +1,45 @@
# `.opencode/plugins/`
Working examples of OpenCode plugins. Drop-in to any project — pure JS, no npm dependencies.
| Plugin | What it does |
|---|---|
| [`protect-secrets.js`](protect-secrets.js) | Blocks any tool call (read/write/bash) touching `.env*`, `secrets/`, `credentials*`, SSH keys, `.npmrc`, `.pypirc`. |
| [`audit-log.js`](audit-log.js) | Appends a one-line JSON record of every successful tool call to `.opencode/audit.jsonl`. |
## How they load
OpenCode auto-loads every `.js` / `.ts` file in `.opencode/plugins/` at session start. No registration step.
```bash
opencode # loads both plugins automatically
opencode --pure # skip all plugins for one run
```
## Audit how this plugin folder fires
```bash
tail -f .opencode/audit.jsonl # watch tool calls live
```
Sample line:
```json
{"ts":"2026-05-18T19:30:12.451Z","tool":"edit","ok":true,"input_keys":["file_path","old_string","new_string"]}
```
## Disabling temporarily
Three options:
1. Move the plugin file out of `.opencode/plugins/`.
2. Comment out the `export default` line.
3. Gate the body of the plugin on an env var:
```js
if (process.env.OPENCODE_DISABLE_AUDIT_LOG) return {};
```
## Writing your own
See [`docs/plugins.md`](../../docs/plugins.md) for the full API, event list, and more patterns (auto-format on save, idle notifications, etc.).
+38
View File
@@ -0,0 +1,38 @@
// .opencode/plugins/audit-log.js
//
// Append a JSONL record of every successful tool call to .opencode/audit.jsonl.
// Useful as an after-the-fact paper trail of what the agent did this session.
//
// Toggle off by deleting this file or by gating with an env var:
// if (process.env.OPENCODE_DISABLE_AUDIT_LOG) return {};
import { appendFile, mkdir } from "node:fs/promises";
import { dirname, join } from "node:path";
export const AuditLog = async ({ directory }) => {
const logPath = join(directory, ".opencode", "audit.jsonl");
// Make sure .opencode/ exists in case this plugin runs in a fresh project
await mkdir(dirname(logPath), { recursive: true });
return {
event: async ({ event }) => {
if (event?.type !== "tool.execute.after") return;
const record = {
ts: new Date().toISOString(),
tool: event.tool,
ok: !event.error,
// Capture small inputs only — full inputs can be huge (file content, diffs)
input_keys: event.input ? Object.keys(event.input) : [],
// Truncate long error messages
error: event.error
? String(event.error).slice(0, 240)
: undefined,
};
await appendFile(logPath, JSON.stringify(record) + "\n");
},
};
};
export default AuditLog;
+37
View File
@@ -0,0 +1,37 @@
// .opencode/plugins/protect-secrets.js
//
// Block any tool call that would read, write, or shell-touch a sensitive path
// (`.env*`, `secrets/`, `credentials*`, common SSH key files). Belt-and-braces
// on top of `external_directory: deny` and gitignore — never your only line
// of defense, but a useful one.
const SENSITIVE = /(^|\/)(\.env(\..*)?|secrets|credentials|id_rsa|id_ed25519|\.npmrc|\.pypirc)(\b|\/)/i;
function pathFromInput(toolName, input) {
if (!input || typeof input !== "object") return "";
return (
input.path ??
input.file_path ??
input.filePath ??
input.target ??
input.command ?? // for bash tool, scan the command line itself
""
);
}
export const ProtectSecrets = async () => {
return {
event: async ({ event }) => {
if (event?.type !== "tool.execute.before") return;
const candidate = pathFromInput(event.tool, event.input);
if (candidate && SENSITIVE.test(String(candidate))) {
throw new Error(
`[protect-secrets] blocked ${event.tool} on sensitive path: ${candidate}`
);
}
},
};
};
export default ProtectSecrets;
+47
View File
@@ -0,0 +1,47 @@
---
name: git-release
description: Draft release notes from merged PRs, propose a semver bump, and emit a copy-pasteable `gh release create` command. Use when preparing a tagged GitHub release.
license: MIT
compatibility: opencode
metadata:
audience: maintainers
workflow: github
---
## What I do
1. Read recent merged PRs since the last tag and group them:
- **Features** (`feat:` commits)
- **Fixes** (`fix:`)
- **Other** (`refactor:`, `perf:`, `docs:`, `chore:`, …)
2. Propose a **semver bump** based on the diff:
- Major if any breaking changes (look for `BREAKING CHANGE:` footers or `!:` markers)
- Minor if any features
- Patch otherwise
3. Emit a clean **release-notes draft** in Keep-a-Changelog format.
4. Print a ready-to-run command:
```bash
gh release create v<version> --title "<title>" --notes-file release-notes.md
```
## When to use me
When the user is preparing a tagged release. Triggers include:
- "draft release notes"
- "prepare a release"
- "what's in v1.X.Y?"
Ask the user to confirm the proposed version bump before running anything destructive (tag creation, release publish).
## What I need from the repo
- `gh` CLI must be authenticated.
- The repo should have at least one prior tag — if not, propose `v0.1.0`.
- Conventional-commit messages are ideal but not required; without them, I'll group by PR labels or fall back to plain summaries.
## What I won't do
- Push tags or publish releases without explicit confirmation.
- Edit the working tree.
- Generate fictional changelog entries — if a PR is unclear, I quote the original PR title verbatim and flag it for review.