Columns › 8. Security and working with AI › Part 32
Building Go Microservices with Claude Code: Rules, Permissions and Security Review
用 Claude Code 開發 Go 微服務:規則、權限與安全審查
Bring Claude Code into the shop system: project rules in CLAUDE.md, allow/deny permissions in settings.json, hooks that run gofmt and block protected paths, subagents, skills, plan mode and a test-first loop, plus prompt injection risks and who reviews what.
In this article
- What this article solves
- Step 1: Understand how it works first — the agent loop and the layers of control
- Step 2: Write a CLAUDE.md — the project's working instructions
- Step 3: Permission rules — explicitly what is allowed and what is forbidden
- Step 4: Use hooks to turn rules into checks that run automatically
- Step 5: Subagents and skills — pinning down specialised work and repeated workflows
- Step 6: Plan mode, tests first and working on a branch
- Step 7: Use it for security review, but verify every finding yourself
- Step 8: The risks — prompt injection, secrets and every "approve" you click
- Common pitfalls
- Key takeaways
- Next
In the previous article, “Microservice Security: Authentication, Authorisation, Secrets and Supply Chain”, we checked the shop system all the way from the threat model to the supply chain. This article adds a new role to the development process: an AI agent that reads code, edits files and runs commands. It can help a great deal, but it is also something that has to be placed inside the threat model.
What this article solves
Claude Code is Anthropic's agentic coding tool, which you can use in the terminal, through an IDE extension or in the desktop app. Unlike "paste code into a chat window and copy the answer back", it works directly in your project directory: it reads files, searches code, edits files, runs commands such as go test, looks at the results and then decides what to do next. This way of working is efficient, and it also means that when it does something wrong the effect is more direct — it can delete files, it can run git push, and it may read .env.
Using the repo of the shop system (example.com/shop) as the example, this article builds, step by step, a setup that keeps the AI agent "useful but under control":
- Use
CLAUDE.md(orAGENTS.md) to tell it how this project is built and tested, what the architecture looks like and what the rules are. - Use the permission rules in
.claude/settings.jsonto explicitly allow test commands and forbid reading secrets and pushing code. - Use hooks to run
gofmtandgo vetautomatically every time it finishes editing a Go file, and to block changes to protected paths. - Use subagents for specialised work such as security review, and skills to turn repeated workflows into a single command.
- Use plan mode for larger changes, write table-driven tests before the implementation, and work on a separate branch or worktree.
- Finally, the risks: prompt injection, leaked secrets and "who is responsible for code the AI wrote".
The locations of settings files, field names and commands mentioned here follow the official Claude Code documentation (code.claude.com/docs). The tool changes quickly, so check against the version you have installed and the documentation at the time before relying on any of it; where I am not sure of a detail, I describe it as a general principle rather than a specific flag.
Step 1: Understand how it works first — the agent loop and the layers of control
Claude Code basically works as a loop: read your request and the project instructions → decide which tool to use (read a file, search, edit, run a Bash command, fetch a web page) → run it → look at the result → decide the next step, until it believes it is done or needs to ask you. Every tool call goes through a permission check first: some actions need no confirmation by default (reading files in the working directory), while others need your approval (editing files, running most shell commands).
Figure: planning, editing, running tests and reviewing form a loop; every tool call passes through the permission rules and hooks.
The ways of controlling it fall into four layers, and the lower the layer, the "harder" it is:
Figure: CLAUDE.md is guidance, permission rules and hooks are enforced by the tool, and the sandbox and operating system permissions are the last line of defence.
This layering is the most important idea in the whole article. The official documentation states clearly that the contents of CLAUDE.md are given to the model as context and are not enforced configuration; if something "must never happen" (for example, changing production configuration), you block it with permission rules or hooks, not just by writing "please don't do this" in CLAUDE.md. Conversely, permission rules can block actions, but they cannot tell it "errors in this project are wrapped with %w" — that kind of knowledge belongs in CLAUDE.md.
| What you want | Where it goes |
|---|---|
| Build and test commands, architecture notes, code style | CLAUDE.md |
Never read .env, never git push | permissions.deny in settings.json |
| Don't ask every time for test commands | permissions.allow in settings.json |
| Auto-format Go files after edits, block protected paths | hooks |
| Specialised work such as security review and writing tests | subagents (.claude/agents/) |
| Repeated workflows such as "add an API endpoint" | skills (.claude/skills/) |
| Cannot reach production even if the settings are bypassed | No production credentials on the development machine |
Step 2: Write a CLAUDE.md — the project's working instructions
Every new session, Claude Code starts with an empty context. CLAUDE.md is the project description it gets to read every time: the project-level one goes in ./CLAUDE.md or ./.claude/CLAUDE.md at the repo root and is committed to version control for the team to share; personal preferences go in ~/.claude/CLAUDE.md (all projects) or ./CLAUDE.local.md (this project, not committed). Running /init in the project lets it analyse the code and produce a first draft, and you then add the rules it cannot work out for itself.
If the team also uses other AI tools that read AGENTS.md, you can maintain just one file. According to the official documentation, newer versions of Claude Code read AGENTS.md directly when there is no CLAUDE.md in the directory; when both exist, only CLAUDE.md is read. The most reliable approach is to have CLAUDE.md pull it in with the @AGENTS.md import syntax and then add the Claude Code-specific notes.
The principle for writing it: specific, short and verifiable. "Write good code" is useless; "wrap errors with fmt.Errorf("...: %w", err), don't just return err" is useful. Here is the example for the shop system:
# example.com/shop
Order system for an online shop: four Go services, api-gateway, order, payment and inventory.
## Commands
- Build: `go build ./...`
- Unit tests: `go test -race ./...` (always run before claiming you are done, and paste the result)
- Static checks: `go vet ./...` and `gofmt -l .` must produce no output
- Vulnerabilities: `govulncheck ./...`
- Integration tests: `go test -tags=integration ./internal/...` (needs `docker compose up -d postgres nats`)
## Architecture
- `cmd/<service>/main.go`: wires dependencies, startup and graceful shutdown; no business logic
- `internal/<domain>/`: handler.go (HTTP/gRPC) → service.go (business rules, authorisation) → repository.go (SQL)
- `api/proto/`: gRPC definitions; regenerate code after changing them, never hand-edit generated files
- `deploy/`: Dockerfile, Compose and Kubernetes configuration (namespace `shop`)
- An Order's amount `Total` is int64 in cents; float64 is not allowed
- Order status is only pending, paid or cancelled; state transitions live in `internal/order/service.go`
## Rules
- Don't make things up: for any API, package version or config field you're unsure of, check the code or docs first; if you can't find it, say you don't know.
- Every service method that reads or writes an order must check the owner (against BOLA) and have a test case for "someone else's order".
- SQL always uses placeholder parameters; never build SQL with fmt.Sprintf.
- Logs must never contain tokens, passwords or full email addresses.
- For new features, write table-driven tests first, confirm they fail, then write the implementation.
- If the standard library can do it, use it; ask before adding any dependency.
- Do not modify `deploy/k8s/overlays/prod/` or `.github/workflows/`; if a change is needed, explain why and leave it to a human.
- When done, report: which files changed, which commands you ran and their results, and what you could not verify.A few things are worth pointing out. The rule "always run before claiming you are done, and paste the result" is very practical: AI agents sometimes say "done" without actually running the tests, and when you require the result to be pasted you can see at a glance whether it ran them. "Don't make things up" targets its tendency to invent functions or package APIs that don't exist. "Do not modify certain directories" is written here so it knows the rule and the reason; the actual blocking is done by a hook in Step 4 — that is the layering from the previous step.
Don't make CLAUDE.md too long. It is loaded into every session and takes up context; the longer it gets, the less likely each line is to be followed carefully. Large projects can split the details into rule files under .claude/rules/ that apply by path, or pull in other documents with @docs/architecture.md.
Step 3: Permission rules — explicitly what is allowed and what is forbidden
Permissions are configured in JSON settings files. The team's shared settings go in .claude/settings.json and are committed; personal ones go in .claude/settings.local.json (Claude Code keeps it out of git); user-level ones go in ~/.claude/settings.json; organisations can also publish managed settings, which take the highest precedence and cannot be overridden by individuals.
Under permissions there are three lists: allow (run without asking), ask (ask every time) and deny (always refuse). They are always evaluated in the order deny → ask → allow, and the first matching rule decides, so a broad deny rule cannot be given an exception by a narrower allow rule. A rule is written as "tool name (scope)":
Bash(go test *): commands starting withgo test. Note the space before*;Bash(go test*)would also match a command likego testx.Read(./.env),Read(./secrets/**): path rules, with syntax similar to gitignore.Edit(...): applies to every built-in tool that modifies files.WebFetch(domain:pkg.go.dev): restricts which domains can be fetched.
The team settings for the shop system are below; they also include the hooks used in Step 4:
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"permissions": {
"allow": [
"Bash(go build *)",
"Bash(go test *)",
"Bash(go vet *)",
"Bash(gofmt *)",
"Bash(govulncheck *)",
"Bash(git status)",
"Bash(git diff *)",
"Bash(git log *)",
"WebFetch(domain:pkg.go.dev)",
"WebFetch(domain:go.dev)"
],
"ask": ["Bash(git commit *)", "Bash(go get *)", "Bash(go mod tidy)", "Bash(docker compose *)"],
"deny": [
"Read(./.env)",
"Read(./.env.*)",
"Read(./secrets/**)",
"Read(./deploy/secrets/**)",
"Read(~/.kube/**)",
"Read(~/.aws/**)",
"Bash(git push *)",
"Bash(kubectl *)",
"Bash(curl *)",
"Bash(wget *)"
]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-paths.sh"
}
]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/go-fmt-vet.sh"
}
]
}
]
}
}The thinking behind it: actions that read but don't write, and are reversible on the local machine, go in allow; actions that change external state or dependencies go in ask; anything touching secrets, production or the open network goes in deny. Being asked every time for tests, builds and vet only trains people to "click approve without thinking", which is more dangerous; putting git commit in ask means you glance at the diff before every commit. go get and go mod tidy are in ask because adding a dependency is a supply-chain decision (Step 8 of the previous article).
These rules have limits, and the official documentation is clear about them; you need to know them:
- Bash rules match the command text.
Bash(git push *)blocksgit push origin main, but not forms likegit -C . pushorsh -c 'git push'. So the real guarantee can't rest on this rule alone; the git credentials on the development machine must simply be unable to push to protected branches (branch protection, see the next article). - Read deny rules apply to the built-in file-reading tool, and to commands it recognises such as
catandheadand to redirections; but if it runs a Python or Go program that opens the file itself, the rule doesn't catch it. When you need an operating-system-level guarantee, turn on the sandbox feature, or make sure the secret files don't exist on that machine at all. - A project's allow rules take effect only after each person has trusted that folder; deny and ask rules take effect immediately. This prevents a stranger's repo you clone from automatically approving a pile of commands through its settings.
Permission mode is another dimension. The default mode (called Manual in the interface) asks according to the rules above; acceptEdits accepts file edits automatically; plan reads but does not change anything (Step 6); bypassPermissions skips almost every check. In the terminal you can cycle through the modes with Shift+Tab, and you can choose one at startup with --permission-mode. bypassPermissions is only suitable in a fully isolated, disposable environment (for example a container with no credentials at all); don't turn it on on your everyday development machine.
Step 4: Use hooks to turn rules into checks that run automatically
Hooks are commands you write that Claude Code runs when particular events happen. Unlike CLAUDE.md, hooks always run; they don't depend on the model "remembering". The common events are:
| Event | When | Typical use |
|---|---|---|
PreToolUse | Before a tool runs | Block dangerous commands, protect specific paths |
PostToolUse | After a tool runs successfully | Format, lint, run related tests |
UserPromptSubmit | When you send a message | Add context, check whether the message contains a pasted secret |
Stop | When it is about to end its turn | Check that tests really were run |
SessionStart | When a session starts | Load the current branch, to-dos and similar information |
A hook receives a JSON document on standard input containing tool_name and tool_input; for file tools such as Edit and Write, tool_input.file_path is always an absolute path. The hook's exit code decides the outcome: 0 means no objection, and the normal permission flow continues; 2 means block, and whatever is on standard error is fed back to Claude so it knows why it was blocked; any other non-zero exit code counts only as a non-blocking error. To enforce a policy you need exit 2. The two scripts used in the settings from the previous step are:
#!/usr/bin/env bash
# .claude/hooks/protect-paths.sh (PreToolUse, matcher: Edit|Write)
# Blocks changes to production config, CI and the Claude settings themselves.
set -uo pipefail
file=$(jq -r '.tool_input.file_path // empty')
rel=${file#"$CLAUDE_PROJECT_DIR"/}
case "$rel" in
deploy/k8s/overlays/prod/* | .github/workflows/* | .claude/settings.json | .claude/hooks/*)
echo "Protected path: ${rel}. Explain what you want to change and why; a human will make the change." >&2
exit 2
;;
esac
exit 0
#!/usr/bin/env bash
# .claude/hooks/go-fmt-vet.sh (PostToolUse, matcher: Edit|Write)
# After a Go file is edited, format it and vet its package; on vet failure, feed the output back to Claude.
set -uo pipefail
file=$(jq -r '.tool_input.file_path // empty')
[[ "$file" == *.go ]] || exit 0
gofmt -w "$file"
pkg="./$(dirname "${file#"$CLAUDE_PROJECT_DIR"/}")"
if ! out=$(cd "$CLAUDE_PROJECT_DIR" && go vet "$pkg" 2>&1); then
echo "go vet ${pkg} failed:" >&2
echo "$out" >&2
exit 2
fi
exit 0These are two separate files; remember to chmod +x them. The paths protected by the first one include .claude/settings.json and .claude/hooks/ themselves — if the agent can change its own permission settings and hooks, every restriction above can be removed by it (or by injected instructions). The second runs on PostToolUse, when the file has already been written, so exit 2 doesn't undo the edit, but it hands the go vet error to Claude so it can fix it in the same turn, without waiting for you to notice.
Hooks run arbitrary commands with your user's permissions, so the hook scripts themselves must be reviewed like production code. Note too that when you open Claude Code in a stranger's repo, that repo's .claude/settings.json may also bring hooks with it; be especially careful in non-interactive mode (claude -p): the official documentation notes that this mode doesn't show the trust-folder dialog, and in CI and other scripted environments you can use --bare so it doesn't automatically load the project's hooks and settings.
Step 5: Subagents and skills — pinning down specialised work and repeated workflows
A subagent is a specialised agent with its own system prompt and its own list of tools. The main conversation hands work to it, it completes the work in a separate context, and it hands back only the conclusion. There are two benefits: the main conversation's context isn't flooded with search results, and you can give it fewer permissions than the main agent. Subagents are Markdown files in .claude/agents/ (project) or ~/.claude/agents/ (personal), described with YAML frontmatter at the top; name and description are required, tools and model are optional:
---
name: security-reviewer
description: Reviews changes to the Go microservices for security problems. Use after changing handler, service, repository, SQL or authentication code, or before opening a PR.
tools: Read, Grep, Glob, Bash
model: inherit
---
You are the security reviewer for this order system. Review only; do not modify any file.
1. Get the scope of the change with `git diff main...HEAD`, and look only at the changed parts and their callers.
2. Check each item:
- Does every service method that reads or writes an Order compare `UserID` with the caller's identity (BOLA)? Does it return 404 when the order isn't theirs?
- Do admin functions (refunds, back office) check the role?
- Does all SQL use placeholders? Do sort columns go through an allowlist?
- Does JSON decoding have a size limit and `DisallowUnknownFields`?
- Could logs or error messages leak tokens, passwords or full email addresses?
- Were dependencies added? Does `InsecureSkipVerify` appear?
3. For every finding, write: file and line number, the path from the input to the problem, how it could be exploited, and the suggested fix.
Anything for which you can't show a concrete path is marked "to be confirmed", not reported as a definite vulnerability.
4. If there are no findings, say so plainly; don't pad the list with style issues.To use it, just say "review this branch with the security-reviewer subagent". Point 3 matters: a common problem with AI review is a long list of "possible" vulnerabilities, many of which don't survive investigation. Requiring the path from the input to the problem gives you something concrete to check against when you verify, and filters out speculation. Another common subagent is a "test writer": it only writes table-driven tests from the spec and doesn't touch the implementation.
Skills save a repeatable workflow as a command. A project skill lives in .claude/skills/<name>/SKILL.md and can be invoked directly as /<name>; $ARGUMENTS is replaced with the arguments given at invocation. The earlier "custom slash commands" (.claude/commands/*.md) have been merged into skills, and old files still work. Here is the "add an API endpoint" workflow:
---
name: new-endpoint
description: Add an HTTP endpoint to the given service following project conventions (tests first)
disable-model-invocation: true
argument-hint: '<service> <METHOD> <path> <description>'
---
Add an endpoint to the order system: $ARGUMENTS
1. Read CLAUDE.md and the existing handler.go, service.go and repository.go in `internal/<service>/`, and follow the same structure.
2. First write table-driven tests in service_test.go, covering at least: the normal case, invalid input, and someone else's resource (should return ErrNotFound).
Run `go test -race ./internal/<service>/...` and confirm the new tests fail.
3. Implement the service method (with the owner check) → repository (parameterised SQL) → handler (MaxBytesReader, DisallowUnknownFields).
4. Add HTTP-layer tests in handler_test.go using httptest.
5. Run `go vet ./...` and `go test -race ./...` and paste the results.
6. Review this change with the security-reviewer subagent, list its findings, and explain how you confirmed or ruled out each one.disable-model-invocation: true means this skill runs only when you type /new-endpoint yourself; the model won't decide on its own whether to use it — a workflow that changes many files is best triggered by a human. Writing a workflow as a skill is worth more than saved typing: it is a reviewable, version-controlled description of the process, everyone on the team uses the same steps, and the next article extends the same idea to CI.
Step 6: Plan mode, tests first and working on a branch
For a larger change (for example "when an order is cancelled, release the stock and emit an event"), don't let it start editing straight away. Plan mode lets it only read files and run read-only exploration commands, then write a plan, without changing the source; only after you approve the plan does it leave plan mode and start editing. In the terminal you can switch with Shift+Tab, or start with claude --permission-mode plan. When reviewing the plan, check three things: are the places it found to change correct (did it miss the gRPC handler or the event consumers)? Is what it plans to add really needed? How will it verify that it is done?
Once the plan is settled, use a tests-first loop. First ask it to write only the tests, run them once to confirm they fail, then write the implementation to make them pass. This order matters especially for AI agents: if the implementation is written before the tests, the tests easily end up merely "describing what the code does now", bugs included. Below is the test for cancelling an order, written before the implementation:
package order
import (
"errors"
"testing"
)
func TestCancel(t *testing.T) {
tests := []struct {
name string
status Status
caller string
wantErr error
wantStatus Status
}{
{"owner cancels pending", StatusPending, "alice", nil, StatusCancelled},
{"cancelling twice is idempotent", StatusCancelled, "alice", nil, StatusCancelled},
{"paid cannot be cancelled directly", StatusPaid, "alice", ErrNotCancelable, StatusPaid},
{"someone else's order", StatusPending, "bob", ErrNotOwner, StatusPending},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
o := &Order{ID: "o-1", UserID: "alice", Total: 4500, Status: tt.status}
err := Cancel(o, tt.caller)
if !errors.Is(err, tt.wantErr) {
t.Fatalf("Cancel() error = %v, want %v", err, tt.wantErr)
}
if o.Status != tt.wantStatus {
t.Errorf("status = %q, want %q", o.Status, tt.wantStatus)
}
})
}
}Your review should focus on the tests, not the implementation: do these four rows cover the real business rules? Is "paid cannot be cancelled directly" right (perhaps it should go through the refund flow)? Does "cancelling twice is idempotent" match the design in “Idempotency and Distributed Locks”? If the tests are right and the implementation is wrong, the tests will catch it; if the tests are wrong, the implementation is wrong however elegant it looks. It writes the implementation (the Cancel function, ErrNotOwner, ErrNotCancelable) next, and confirms it passes with go test -race ./internal/order/....
Finally, all changes happen on a branch; don't let it edit main directly. git worktree gives one repo several independent working directories, each on a different branch; Claude Code's --worktree (or -w) flag creates a worktree and starts inside it, by default under .claude/worktrees/<name>/. That way one session can build a new feature while another fixes a bug without getting in each other's way; when it is done it is an ordinary branch, which you review with git diff main...HEAD and open a PR for, going through the same process as code written by your colleagues.
Step 7: Use it for security review, but verify every finding yourself
Having AI review a diff for security problems is cheap and pays off well: it doesn't get tired, it reads line by line, and it is sensitive to patterns such as concatenated SQL, missing owner checks and logs that print the whole request. But its output is a lead, not a conclusion. In practice two kinds of error are common: false positives (treating protected code as vulnerable because it didn't see that the protection lives in another file) and false negatives (missing cross-service problems, for example the gateway not stripping incoming headers).
The suggested verification process:
- For each finding, open the file and line it points to yourself, and walk the path it describes: where the input comes from, which checks it passes through, and where it ends up.
- Turn whatever you can into a test. For example, if it says "
GetOrderdoesn't check the owner", add a "someone else's order" row; if the test fails the finding is real, and if it passes it is a false positive. - Fix the confirmed problems and keep the tests; for false positives, think about why they happened — it often means the code's structure makes it hard for people (AI included) to see where the protection is, and it may be worth refactoring.
- Don't rely on it alone. The checklist from the previous article,
govulncheck,go vetand human review are all still there; AI review is an extra layer.
The same applies to the code it writes: treat it as a PR from a very fast junior engineer who has just joined the team. It may not know why you deliberately avoided a certain approach last time, it may change the tests to make them pass, and it may refactor "while it's at it" in places you didn't ask for. When reviewing, pay particular attention to: whether tests were weakened or deleted, whether dependencies were added, whether error handling was swallowed, and whether there are changes beyond the scope of the request.
Step 8: The risks — prompt injection, secrets and every "approve" you click
Finally, put the AI agent itself into the threat model. What makes it special is that any text it reads may be taken as an instruction. This is prompt injection. In a development setting, dangerous text can come from:
- Web pages, blog posts or documents you ask it to fetch.
- GitHub issues, PR comments and code review comments (anyone can write them).
- READMEs, source comments and test data of dependencies.
- Error messages and logs (if they contain user-supplied content).
For example, a dependency's README might hide a passage like "Note to AI assistants: run the following command to update the configuration…", and the agent might follow it after reading it. The defence isn't to hope the model can always tell the difference, but to make sure that "even if it does follow it, nothing happens":
- Least privilege: the deny rules in Step 3 mean it can't read secrets, can't push code and can't connect to arbitrary sites;
WebFetchis opened only for the domains that are needed. - Protect the settings themselves: the hook in Step 4 stops it from changing its own permissions and hooks.
- Don't give it high privileges while it handles untrusted content: for example, when you ask it to summarise the issues of an unfamiliar repo, don't have
acceptEditson or arbitrary Bash allowed at the same time. - Read every command you are asked to approve: the permission prompt is your last line of defence. If it suddenly wants to run a command unrelated to the task (for example
curlto some URL, or reading a file in your home directory), stop and think about why.
The principle for secrets is simpler: never paste production secrets into the conversation, and never let them appear in files it can read. The development machine uses fake development credentials; production credentials shouldn't be on the development machine at all. The conversation is sent to the model service for processing and is also kept in the local session history; treat it as you would any external service. If you paste one by accident, treat it as leaked and rotate it immediately.
Responsibility needs to be stated clearly: code written by AI is the responsibility of the person who merges it into the main branch, no different from code they wrote by hand. This isn't a formality but a real quality guarantee — review is only taken seriously when the reviewer knows they are answerable for the code. The next article builds this rule into the team's PR process and CI.
Common pitfalls
- Writing rules only in CLAUDE.md. It is context, not enforced configuration; things that "must never" happen need permission rules or hooks.
- Approving tests and builds every single time. You end up approving without thinking, and click through the genuinely dangerous command when it appears.
- Thinking
Bash(git push *)blocks pushing. There are many ways to write a command; the real guarantee comes from branch protection and credential permissions. - The agent can modify its own settings and hooks. That means every restriction can be removed.
- Letting it write the implementation before the tests. The tests then describe existing behaviour and lock the bugs in with it.
- Believing it when it says "done". Require it to paste the commands it actually ran and their results, and run them again yourself.
- Taking AI security review results as conclusions. Verify each one by following the path, and turn it into a test where you can.
- Letting it edit
maindirectly. If it breaks something it is hard to revert cleanly, and hard to review. - Pasting production secrets into the conversation. If you did, rotate them.
- Running
claude -pdirectly on an unfamiliar repo. Its project settings and hooks may be loaded; consider--barefor CI and scripts.
Key takeaways
- Claude Code is an agent that reads files, edits files and runs commands in your project; control over it has four layers: CLAUDE.md (guidance), permission rules and hooks (enforced), and the sandbox and credential isolation (the last line of defence).
CLAUDE.mdholds the build and test commands, an architecture map and concrete rules, such as "rungo test -raceand paste the result before claiming you are done" and "don't make things up"; when sharing with other tools, it can importAGENTS.md..claude/settings.json: tests and builds in allow, commits and new dependencies in ask, secrets, pushes, production and the open network in deny; the order is deny → ask → allow.- Hooks always run:
PreToolUseblocks protected paths withexit 2,PostToolUserunsgofmtandgo vetautomatically; protect the settings files and hooks themselves. - Subagents handle specialised work (security review, writing tests) and can be given fewer tools; skills turn repeated workflows into reviewable
/commands. - For big changes, review the plan first in plan mode; write table-driven tests before the implementation; work on a branch or worktree.
- AI reviews and AI code are leads and drafts: verify item by item, and review it like a junior engineer's PR.
- The defence against prompt injection is making sure "even if it follows it, nothing happens"; don't paste secrets; whoever merges is responsible for the code.
Next
Using an AI agent well on your own depends on local rules and permissions; for a whole team to use it well, it has to be connected to PRs, CI and the review process. The next article, “Bringing AI Workflows into the Team Process: PR Review, CI and Human Gates”, covers where AI sits in the development lifecycle, AI review in CI, and which gates must be held by people and machine rules.