---
title: "AI-generated code ships hidden vulnerabilities"
slug: "ai-generated-code-ships-hidden-vulnerabilities"
publishedAt: "2026-04-09T19:51:12.845Z"
dateModified: "2026-04-09T19:51:12.845Z"
canonical: "https://www.notesof.dev/ai-generated-code-ships-hidden-vulnerabilities"
author: "Hieu (Chris) Pham"
tags: ["Agentic AI", "AI", "Context Engineering", "LLMs"]
excerpt: "An AI wrote 200 lines of auth code in 45 seconds, and the audit found a known CVE. Here is a six-phase workflow that catches it."
---

# AI-generated code ships hidden vulnerabilities

> Part 5 of 6 in the "Context Engineering in 2026" series

**TL;DR:** AI-generated code is usually functional and often insecure, because nobody defined the security requirements or checked the output. The fix is a six-phase workflow (brainstorm, plan, implement, validate, secure, ship) where each phase gets only the context it needs. **Security constraints and an approved dependency list written into your seed file** prevent most vulnerable patterns before they are generated.

A developer opens their AI IDE (integrated development environment) and types "*build a user authentication system with JWT tokens.*" The AI writes 200 lines of code in 45 seconds. The developer scans it, thinks "looks right," commits, pushes, and moves on.

> **JWT** — JSON Web Token, a signed token that proves a user is logged in.

Three weeks later, a security audit finds that the JWT implementation uses a deprecated library with a known CVE. The password hashing uses bcrypt with a cost factor of 4 (it should be at least 12). And the refresh token sits in localStorage, a textbook XSS attack vector.

> **CVE** — Common Vulnerabilities and Exposures, the public catalog of known security flaws in software.

> **XSS** — Cross-site scripting, an attack where injected script runs in the victim's browser and can read anything in localStorage.

Nobody brainstormed the security requirements, validated the output against known vulnerabilities, or checked the dependencies.

## The six-phase workflow

Anthropic's engineering team published a detailed guide on effective context engineering for AI agents. The guide argues that **agents perform best when they work through structured phases.** Give each phase only the context it needs.

This maps to a development lifecycle most experienced engineers recognize, and that AI-assisted workflows tend to skip:

```text
Brainstorm → Plan → Implement → Validate → Secure → Ship
```

### Phase 1: brainstorm before you code

The most useful thing you can do for AI-assisted development is to **stop jumping straight into code.** Brainstorm first.

Superpowers (134K stars) builds this in. Its brainstorming skill activates automatically when you start something new. It asks clarifying questions, explores alternatives you have not considered, identifies edge cases, and presents a design document in digestible chunks for you to validate.

This phase produces a document (brainstorm.md or design.md) that defines what the code should do, what it should not do, and why.

**The brainstorming conversation is disposable, and the document it produces is the asset.** A brainstorming chat might run to 20,000-50,000 tokens. The resulting design document is maybe 3,000-5,000. Start the implementation session from the document instead of the chat history, and you spend 60-70% fewer tokens and get more consistent results.

A good brainstorm document captures the problem statement, the accepted approach, the rejected alternatives (so the AI stops re-suggesting them), the constraints, and the edge cases that will definitely happen in production.

Teams using [AgentKit (formerly ClaudeKit)](https://agentkit.best/?ref=35VIG2ZI) can use the Brainstormer agent for this phase, then the Planner agent to turn its output into an implementation plan.

![Problem, Options and Constraints cards merging into a Decision document that leads to a code window](https://a.storyblok.com/f/288495199849781/1672x941/9e67696b2a/brainstorm-before-coding.webp)

### Phase 2: plan in small tasks

With a validated design document, the planning phase breaks the work into tasks small enough to execute reliably. In Superpowers, each task is 2-5 minutes of work, with exact file paths, complete code expectations, and verification steps.

Why small? Anthropic's guide stresses that **context rot increases with context size**. The more tokens in the window, the more the model's attention is stretched. A task that needs 50 files at once produces worse output than a task focused on 3.

> **Context rot** — the drop in output quality as a model's context window fills up.

The plan becomes a checklist. Each item states what to do, which files to touch, how to verify it worked, and only the context the implementing agent needs. This is the "just-in-time context" pattern Anthropic describes: your plan is the index, and the agent loads only what each step requires.

![A page layout split into three task cards, each listing a task, its files and a check](https://a.storyblok.com/f/288495199849781/1672x941/e7fb23bfbd/plan-into-small-tasks.webp)

### Phase 3: implement against the plan

Implementation is phase 3 of 6, not phase 1. With a brainstorm document and a plan, the AI executes against a validated spec with focused context.

**Subagent isolation.** For multi-step work, a worker agent executes each task with only the context it needs, so the main session stays clean. Superpowers does this automatically, and AgentKit's team orchestration runs multiple independent Claude Code sessions in parallel.

**Artifact-driven context.** Keep decisions, approach, and test notes as artifacts. When someone asks "why was the payment module built this way?" six months from now, the answer is in the plan folder.

### Phase 4: validate with tests and reviews

Superpowers enforces true red/green TDD: write the failing test first, then write the minimal code to make it pass. It prevents the "looks right, so it probably works" habit.

> **TDD** — test-driven development, a practice where a failing test is written before the code that makes it pass.

Validation goes beyond unit tests. A spec compliance check confirms the code matches the plan, then a quality review confirms it does so well. Context validation checks that the functions and patterns named in the seed file (CLAUDE.md) still exist, because context rot is silent and your AI follows stale instructions faithfully. Coverage mapping confirms every quality assurance (QA) scenario from Part 3 has a corresponding test.

### Phase 5: secure what the AI generated

Most AI workflows skip this phase. The AI makes dependency choices and writes configuration from training data that may include outdated patterns and deprecated libraries.

Veracode tested code from more than 100 language models and found that [AI-generated code introduced risky security flaws in 45% of tests](https://www.veracode.com/resources/analyst-reports/2025-genai-code-security-report/), and that larger, newer models did not improve the result. A Stanford user study found that [participants with an AI assistant wrote significantly less secure code and were more likely to believe it was secure](https://arxiv.org/abs/2211.03622). That overconfidence is the bigger risk, because code the author trusts gets less review.

![Dependencies, Patterns and Secrets passing through a scanner arch, with flagged items dropped into a warning bin and clean code moving on](https://a.storyblok.com/f/288495199849781/1672x941/473af6210a/security-scan-checkpoint.webp)

### Scan dependencies before you commit

Scan every AI-generated `package.json` or `requirements.txt` before it is committed, not after CI (continuous integration).

```bash
npm audit
pip-audit
```

Your seed file can also hold security constraints that make the AI less likely to generate vulnerable code in the first place:

```markdown
### Security Constraints
- NEVER store tokens/secrets in localStorage (use httpOnly cookies)
- NEVER use bcrypt with cost factor below 12
- Always use parameterized queries
- JWT tokens must expire within 15 minutes
```

### Check the supply chain

AI models are trained on public code, including code that uses compromised packages, typosquatted packages (names that imitate popular ones), and packages since taken over by malicious actors. When the AI suggests `npm install cool-utils`, it has no way to know whether `cool-utils` is a maintained package or a malicious look-alike.

Check the lockfile diff, the maintenance status, and the license of every new dependency. Some models suggest GPL (GNU General Public License) packages for proprietary projects.

The OWASP (Open Worldwide Application Security Project) Top 10 now ranks this risk third, as [A03:2025 Software Supply Chain Failures](https://top10.owasp.org/2025). The OWASP list for large language model (LLM) applications also ranks supply chain third, as [LLM03:2025 Supply Chain](https://www.promptfoo.dev/blog/owasp-top-10-llms-tldr/).

Snyk, Socket.dev, and Dependabot can automate these checks. The context engineering step is to **add your approved dependency list to your seed file**, so the AI suggests from it first and flags anything new.

```markdown
### Approved Dependencies
- HTTP client: axios. Validation: zod. ORM: drizzle-orm.
- If you need a dependency not on this list, ASK first with justification
```

### Review code patterns

AI-generated code also carries pattern-level flaws: injection (SQL, XSS, command), missing access checks and overly permissive CORS (cross-origin resource sharing), error messages that leak infrastructure, and hardcoded secrets.

AgentKit's Code Reviewer agent includes security scanning in its review, and its Git Manager scans for security issues during the commit workflow. Superpowers' two-stage review also catches security problems at the spec compliance level. If the spec says "use parameterized queries" and the code concatenates strings, the review flags it.

### Example: a JWT mistake, before and after

Ask an assistant for a quick login endpoint and you can get this.

```javascript
app.use(cors({ origin: true, credentials: true }));

const token = jwt.sign({ sub: req.body.userId }, 'secret123');

const payload = jwt.verify(req.headers.authorization, 'secret123', {
  algorithms: ['HS256', 'none'],
});
```

The secret is hardcoded, tokens never expire, and the `none` algorithm lets an attacker forge a token. The `origin: true` option lets any site make credentialed requests. Run [Semgrep](https://docs.semgrep.dev/getting-started/cli) with its JavaScript and JWT rule packs:

```bash
semgrep --config p/javascript --config p/jwt --metrics=off server.js
```

On Semgrep 1.179.0 this reported three blocking findings, and nothing on the CORS line.

```text
jwt-hardcode.hardcoded-jwt-secret
jwt-none-alg.jwt-none-alg
jwt-hardcode.hardcoded-jwt-secret
```

A scanner catches only the patterns it has rules for, so the CORS mistake still needs a human reviewer or a seed-file rule. Here is the fixed version, which reported 0 findings:

```javascript
const SECRET = process.env.JWT_SECRET;
if (!SECRET) throw new Error('JWT_SECRET is required');

app.use(cors({ origin: ['https://app.example.com'], credentials: true }));

const token = jwt.sign({ sub: userId }, SECRET, { algorithm: 'HS256', expiresIn: '15m' });
const payload = jwt.verify(auth, SECRET, { algorithms: ['HS256'] });
```

The dependency check works the same way. With `jsonwebtoken@8.5.1` installed, `npm audit` reported one high severity vulnerability with three advisories, including [signature validation bypass due to an insecure default algorithm](https://github.com/advisories/GHSA-qwph-4952-7xr6). After `npm install jsonwebtoken@latest` (9.0.3 today), it reported none.

### Phase 6: ship and monitor in production

AI-assisted code can have runtime behaviors that static analysis and tests miss, such as race conditions under load and edge cases that only appear with real user data. Put observability rules in the seed file: structured logging on every endpoint, alerts on error rates, and CVE monitoring through Dependabot or Snyk.

### The complete flow

Each phase uses only the context it needs and produces an artifact that feeds the next: design.md from brainstorm, plan.md from planning, tested code from implementation, a coverage and spec check from validation, a scan and audit from security, and a release with full traceability from shipping.

A green `npm audit` means only that no installed package has a known advisory. For a throwaway script that touches no user data, `npm audit` alone is enough. For code that handles your users' data or money, the full pipeline is ordinary engineering, and the AI makes each phase faster.

![A six-step pipeline of Brainstorm, Plan, Implement, Validate, Secure and Ship, with the Secure step highlighted](https://a.storyblok.com/f/288495199849781/1672x941/70ed39f727/secure-ai-coding-pipeline.webp)

---

*One more post to go. It covers how to prove the workflow works with real metrics, which is the job of harness engineering.*

*Next up: [**Part 6 — Harness engineering proves your AI works**](/posts/harness-engineering-proves-your-ai-works) — the production-grade practices that close the loop.*

---

*This is Part 5 of the "Context Engineering in 2026" series. [Part 1](/posts/why-your-ai-forgets-your-project) | [Part 2](/posts/give-your-ai-a-context-file) | [Part 3](/posts/context-engineering-is-a-team-sport) | [Part 4](/posts/pick-the-right-ai-workflow-framework)*
