Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Alibaba's 32 AI Coding Design Patterns: From Legacy Scanning to Agent Orchestration

Alibaba's 32 AI Coding Design Patterns: From Legacy Scanning to Agent Orchestration

Alibaba Cloud and Qoder share 32 battle-tested AI coding design patterns across six dimensions—human-AI collaboration, context integration, SDLC orchestration, knowledge memory, governance, and agent collaboration—with concrete prompts, acceptance criteria, and anti-patterns for each.

Overview

Alibaba Cloud Training Center and the Qoder team have distilled 32 enterprise-grade AI coding design patterns into a card-based reference. The patterns are organized into six dimensions that span the entire software development lifecycle (SDLC): Human-AI Collaboration Excellence, Context & Standards, Efficiency & Cost (SDLC Orchestration), Traceability & Auditability (Knowledge Memory), Quality & Security (Governance), and Organizational Capability Evolution (Agent Collaboration). Each pattern includes a trigger signal, a concrete prompt example, acceptance criteria, and a highlighted pitfall to avoid.

Dimension I: Human-AI Collaboration Excellence (基础协作)

01 Legacy Scanner Pattern

SDLC: Requirements / Current State Analysis

Systematically scan legacy codebases to produce a structured assessment report covering architecture, dependencies, code smells, and hotspots. This becomes the "medical record" for the legacy system, enabling evidence-based refactoring decisions.

How to start:

Signal: New hires ask "how does this project start?" more than three times.

Prompt:

Scan src/ directory: (1) Identify business modules and external dependencies (2) Flag circular dependencies, deep inheritance, duplicate code segments (3) Output markdown report with ASCII architecture diagram + complexity Top 10 + refactoring risk zones Top 10.

Acceptance: Within 30 minutes you can explain "what this code solves and where the main risks are."

Pitfall: Don't rush to rewrite after scanning. First circulate the report as onboarding documentation.

02 Spec Coding Pattern (Spec-Driven Development)

SDLC: Requirements / Design

Replace vague requests with structured specifications that become the single source of truth for both humans and AI. The spec evolves with requirement changes; code is merely the "last mile." Three maturity levels: Spec-first (spec discarded after implementation), Spec-anchored (spec retained and evolved), Spec-as-source (spec is the primary artifact, humans no longer edit code directly).

How to start:

Signal: Any feature you cannot explain in one sentence needs a spec.

Template (requirements → design → tasks):

# REQ-001 User Login Failure Lockout
## Requirement
As a user,
I want to be protected by the system on consecutive login failures,
So that the account is not brute-forced.
## Acceptance Criteria
- Given account A enters wrong password 5 times within 5 minutes
  When the 6th attempt occurs
  Then the API returns 423
  And repeated requests within 30 minutes also return 423

Prompt:

Based on this spec, generate implementation + unit tests + one boundary case; annotate each AC with the corresponding file and line.

Acceptance: Every number and boundary in the spec is something you explicitly stated, not invented by AI.

Pitfall: A spec is not a "detailed prompt"; it is written for human review, not for AI's preference.

03 Plan-Driven PRD Pattern

SDLC: Requirements Clarification

Don't let AI write a full PRD—it will hallucinate plausible defaults. Instead, use a Quest Spec mode where AI actively asks multiple-choice questions and you answer, turning fuzzy needs into a structured PRD. The questioning process forces clarity.

How to start:

Enable requirement_clarification phase; AI asks multiple-choice questions.

Rule: Check "AI must not assume default values" to prevent silent completions.

Acceptance: Every number and boundary in the final PRD came from your answers.

Pitfall: When AI supplies "reasonable" defaults, delete them and return to the underlying question.

04 Skill-Oriented Decomposition

SDLC: Implementation / Test

Decompose complex tasks into stable, reusable AI Skills (atomic capabilities) orchestrated by higher-level Agents. Skills live at .qoder/skills/<skill-name>/SKILL.md using YAML frontmatter + Markdown body.

Example Skill (migration-bdd-test):

---
name: migration-bdd-test
description: Generate BDD migration scripts for *.feature files. Invoke when user provides a feature file and requests step skeletons.
---

# Migration BDD Test

## When to Use
User provides `*.feature` (Gherkin syntax) and asks for corresponding step definition skeletons with dry-run.

## Execution Steps
1. Parse feature file, extract all Scenarios
2. Generate step definition skeletons (no concrete actions)
3. Run dry-run, output list of unimplemented steps

## Output
- `tests/migration/<feature>.ts`
- `run-log.md` (including unimplemented steps list)

Acceptance: Same Skill run three times produces structurally stable output.

Pitfall: Skills are not "hard-coded script tools"; natural language description plus optional script snippets are more reusable than monolithic config templates.

05 Reflection Loop Pattern

SDLC: Cross-phase

After key decisions or complex changes, insert a reflection slot: AI + human jointly review intent, risks, and alternatives, producing a traceable decision record stored at docs/adr/NNNN-title.md with four sections: Intent / Solution / Risks / Alternatives.

Triggers: (1) Single PR > 300 lines; (2) Core module modified; (3) Rolled back twice within a week post-release.

Prompt:

Based on this commit diff, write a reflection report: what problem we intended to solve, what risks existed, what alternatives we abandoned.

Acceptance: Six months later you can still explain why that choice was made.

Pitfall: Reflection is not a blame session; focus on the system, not the person.

06 Refactoring Companion

SDLC: Evolution / Maintenance

Treat AI as a refactoring dialogue partner: identify smells → select technique → generate stepwise → human controls rhythm and final decision.

Prompt:

Locate functions in src/order/ with cyclomatic complexity > 15 and duplicate code > 50 lines; list top 5 and propose Extract Method / Move Method / Introduce Parameter Object refactorings; wait for my selection before generating diff.

Rhythm: Refactor one function at a time; run tests before continuing.

Pitfall: When AI proposes "elegant but over-engineered" solutions, fall back to the minimal change the business actually needs.

Dimension II: Context & Standards (能力集成)

07 MCP Integration Gateway

SDLC: Full Lifecycle

Unify external systems (Git, CI, DB, Monitoring) as AI-callable capability gateways via Model Context Protocol (MCP). Register MCP servers in .mcp.json at repo root.

Example Git MCP registration:

{
  "mcpServers": {
    "git": {
      "command": "uvx",
      "args": ["mcp-server-git", "--repository", "."]
    }
  }
}

Tools exposed by mcp-server-git include git_status, git_diff, git_log, git_show; full invocation format is mcp__<server>__<tool> (e.g., mcp__git__git_status).

Acceptance: AI can read current branch diff and offer review comments based on it.

Pitfall: Onboard one MCP at a time—Git first, then CI, then DB; monitoring last due to broad permissions.

08 Greenfield Scaffolding

SDLC: Initiation / Build

Encode "new project bootstrap tasks" as a Skill so AI generates a standards-compliant skeleton (CI, lint, directory structure, config docs) in minutes.

Example Skill (scaffold-nextjs):

---
name: scaffold-nextjs
description: Create a team-standard Next.js + TS project with lint, prettier, husky, CI. Trigger when user says "new project".
---

## Execution Steps
1. `pnpm create next-app@latest <name> --ts --eslint --app`
2. Install prettier, husky, lint-staged; enforce conventional commits
3. Add `.github/workflows/ci.yml` (pnpm cache + lint + test + build)
4. Write team rules into `.qoder/rules/` (e.g., no-any.md, require-test.md, no-console.md)

## Output
- A project ready for `git init && pnpm dev`

Trigger: In IDE chat, say "Create a new Next.js project per team standards."

Acceptance: New project can submit first PR within 5 minutes.

Pitfall: Don't over-rigidify the template; leave an org_rules extension point for team evolution.

09 Local RAG via MCP

SDLC: Full Lifecycle

Build a local "read internal docs" MCP server that exposes a search_docs(query) tool over ADR and style directories, so AI answers with "how we do it here" instead of generic web knowledge.

MCP registration (STDIO mode):

{
  "mcpServers": {
    "rag": {
      "command": "uvx",
      "args": ["local-rag-mcp", "--root", "docs/", "--include", "adr/**,style/**"]
    }
  }
}

Start with docs/adr and docs/style only; avoid full-repo indexing.

Acceptance: AI can answer "What is our project's error code convention?" citing a specific ADR file.

Pitfall: "Full indexing = full noise"; small high-quality scope beats large noisy scope.

10 Design-to-Code Prototyping

SDLC: Design / Prototype

Via Figma MCP, AI extracts layout and components from design files to produce frontend prototypes instantly.

Prompt:

Based on this Figma Frame, output React + Tailwind components using design tokens from the file; introduce no extra color values.

Acceptance: Screenshot matches design structure; color/spacing 100% aligned with design tokens.

Pitfall: If design file mixes real components with hand-drawn decorations, AI will fail—push design system maturity first.

11 CLI Ops Inspection

SDLC: Operations / Platform

Wrap Qoder CLI ( qodercli, not qoder) into scripts for repeatable network scanning, log analysis, and security checks.

Daily log analysis script:

qodercli chat 
  "Read /var/log/app-$(date +%Y%m%d).log, categorize by Auth / Resource / Exception Path,
   output markdown report to ./ops-report-$(date +%Y%m%d).md"

Cron entry: 0 7 * * * /usr/local/bin/qodercli-daily-report.sh Additional Skills: network-scan (ports/DNS/cert expiry) and security-check (dependency CVE scan + secret regex). All three run in parallel via same cron, independent and rollbackable.

Acceptance: Anomalies auto-categorized and linked to concrete files.

Pitfall: AI only does "read + attribute"; never let it mutate production directly. Read-only is the safety baseline.

Dimension III: SDLC Orchestration (SDLC 编排)

12 AI-DLC Three-Phase Orchestration

SDLC: End-to-End

Adopt the AWS Labs aidlc-workflows three-stage pipeline: Inception → Construction → Operations.

Inception: Quest Spec mode for PRD; enable requirement_clarification for reverse questioning.

Construction: Quest Experts mode (or multi-agent orchestration) for task decomposition and parallel scheduling.

Operations: qodercli for observability and ops inspections.

Acceptance: One diagram explains "where AI adds value in our three phases."

Pitfall: Every phase must retain a "human final sign-off" gate; no fully automated phase.

13 Quest Delegation Pattern

SDLC: Cross-phase Tasks

Model medium-to-large tasks as Quests: a lead Agent decomposes into sub-tasks, delegates to child Agents/Skills, aggregates results. You become the "task publisher."

Quest Input Structure:

quest: Migrate login module to OIDC
success_criteria: [Login success rate > 99.9%, legacy path fully retired, 100% test coverage]
constraints: [No existing session breakage, complete within 3 days]

Lead Agent presents decomposition for your review before execution—AI tends toward over-optimism.

Acceptance: Every sub-task yields an independently revertible PR.

Pitfall: Underspecified constraints invite AI to "helpfully" invent its own; list "what must not happen" more exhaustively than "what must happen."

14 Parallel Workstream

SDLC: Build / Test

Exploit AI parallelism: split work by "independently verifiable" boundaries, not by apparent relatedness. Concurrency limit (N=2–4) is set in the Quest board's "My Quests" view, bounded by team review capacity.

Wrong: Bundle "login + permissions + logging" into one stream.

Right: Three independent streams, each runs tests, each merges separately.

Acceptance: Each stream produces an independently revertible PR.

Pitfall: Don't let AI merge—humans merge, AI does local changes.

15 Test Generation Guardrail

SDLC: Test / Quality

Enforce "code generation must include test generation" as a hard gate. Use AI to accelerate test writing while treating tests themselves as quality guardrails.

GitHub Actions coverage gate:

- name: Coverage gate
  uses: org/repo/coverage-action@v1
  with:
    new-code-coverage: 80%
    lines-threshold: 50
    fail-under: true

Prompt:

Generate tests for this diff covering at least: happy path, error path, empty collection, permission denied.

Acceptance: CI fails until tests are added, then implementation follows.

Pitfall: AI loves writing "plausible but useless" assertions—require real assertions that can actually fail.

16 E2E Experiment Pattern

SDLC: Verification / Experiment

Combine Playwright + MCP to let AI spin up E2E environments and execute full user journeys, preventing regression cost from growing exponentially.

Start with the "golden path": Login → Create → Submit → Logout.

Prompt:

Based on this feature file, build Playwright test cases, auto-provision test environment and clean up.

Acceptance: Single command runs full E2E suite locally or in CI.

Pitfall: Do 5 core scenarios first, not 50 edge cases; expand later.

17 Cross-Language Migration

SDLC: Evolution / Refactoring

Migrate Java → Python (or any language pair) without a full rewrite: freeze the old code's external behavior contract (Spec), translate implementation with AI, then shadow 5% traffic at the gateway for comparison.

Comparison Rules:

String/JSON output: byte-for-byte identical.

Numeric output: floating-point tolerance (Java double vs Python float precision differs; hard 0.001% threshold will fail).

Timestamps/Random IDs: whitelist fields, ignore differences.

Acceptance: Per-module migration with automated comparison.

Pitfall: Never migrate the whole repo at once; migrate one module at a time, each compared.

18 Pilot-to-Scale Adoption

SDLC: Organizational Practice

Replicate AI coding from a single team to cross-team, cross-business-line standard capability via a reproducible roadmap.

Phase 1 (0–4 weeks, 6–8 weeks for zero-baseline teams): Pick a low-sensitivity, low-communication-overhead team for pilot.

Phase 2 (4–8 weeks): Produce a "Team SOP" so other teams can replicate by following the playbook.

Phase 3 (8+ weeks): Elevate to org-level templates, Skills, and rules.

Acceptance: Second team onboarding time reduced 30–60% vs first team (don't chase <50%, that's star-team territory).

Pitfall: Avoid top-down mandates; let one team demonstrate tangible wins first—more effective than ten kickoff meetings.

19 ChatOps Integration

SDLC: Collaboration / Operations

Connect AI with DingTalk / WeCom / Lark: PRs, builds, releases, alerts visible in chat with safe reverse operations.

Step 1: Read-only—push PR/build status to group.

Step 2: Annotate— @AI in group to summarize build failure causes.

Step 3: Reverse ops—only on-call SRE can trigger.

Acceptance: Group can answer "Which step is today's release stuck at?"

Pitfall: Never enable "anyone can trigger auto-rollback"; permissions must follow approval workflow.

Dimension IV: Knowledge Memory (知识记忆)

20 Layered Memory Pattern

SDLC: Collaboration / Operations

Store organizational/team/project/session knowledge in layered Memory scopes so AI reuses experience at the correct level. Map four conceptual layers to Qoder's two actual scopes:

Organization / Team / Project → Project scope (persisted in .qoder/repowiki/ or docs/).

Session → transient context, not persisted.

Personal preferences (naming, ESM, avoid any) → Personal scope (cross-project).

Qoder's official scopes: Personal Global Memory (coding habits, portable across projects) and Project-Specific Memory (repo-bound constraints, terminology, ADR summaries, contract templates). Personal memory managed in IDE "Knowledge Center / Memory" panel; project memory committed to repo.

Acceptance: Switch to a new repo—AI does not carry over previous project's business jargon/internal codenames.

Pitfall: Don't stuff personal preferences into project memory; project memory should be facts, not habits.

21 Repository Knowledge Atlas

SDLC: Operations / Maintenance

New hires' biggest fear isn't writing code—it's understanding what the codebase actually solves. Let AI scan the repo to generate module/sequence/entity diagrams, complemented by RepoWiki as structured knowledge.

Entry: In IDE chat, run /knowledge-plan to produce wiki_plan.yaml defining module hierarchy and focus areas. Declare diagrams explicitly:

diagrams: [module, sequence, entity]
/knowledge

then emits Mermaid/SVG alongside markdown; artifacts land in .qoder/repowiki/. Integrate into CI: commit wiki_plan.yaml, auto-regenerate on merge to main.

Acceptance: New member can explain main flows in week one using RepoWiki + three diagram types.

Pitfall: Don't create an encyclopedia; diagram only happy paths and exception routes—details left for code diving.

22 Postmortem & Knowledge

SDLC: Operations / Maintenance

After incidents, use AI to structure timeline, root cause, lessons learned into knowledge base and Memory.

Template: docs/postmortem/YYYY-MM-DD-<title>.md with fixed fields:

Incident Timeline / Trigger Chain / Root Cause / Immediate Mitigation / Long-term Fix / Recurrence Prevention / Owner

.

Prompt:

Based on this alert + logs + deployment records, produce a structured postmortem, tagging each action with Owner and due date.

Acceptance: Zero recurrence after 3 months.

Pitfall: Postmortem is not a blame session; focus on the system, not the person—otherwise nobody speaks truth.

23 Teaching & Learning Visualization

SDLC: Education / Training

Teaching's highest cost isn't slide creation—it's "explaining the unexplainable." Let AI turn abstract concepts into interactive web demos: algorithms step-through, architecture drill-down, animated flowcharts.

Toolchain: HTML + Mermaid + D3.js / Observable Plot + reveal.js—all AI-generated.

Prompt Example:

Generate an HTML page demonstrating quicksort partition steps with a "Next Step" button for frame-by-frame playback; initial array [3,1,4,2].

Persist common demos as .qoder/skills/viz-html/SKILL.md for reuse.

Acceptance: After your 30-minute session, newcomers remember at least 3 hands-on demos.

Pitfall: Visualization serves "why," not showmanship—don't let AI make flashy animations that obscure the principle.

Dimension V: Governance (治理规范)

24 Governance Guardrail

SDLC: Full Lifecycle

Use Qoder Rules to codify security, compliance, and style constraints as guardrails that keep AI output naturally within boundaries—not shackles, but a track.

Path: .qoder/rules/ (one rule per markdown file, committed for team sharing; personal rules in .gitignore). Rule level is set via IDE's Rule Type (four tiers):

Always Apply: Project hard constraints (coding style, doc format).

Model Decision: AI self-judges when to trigger ("write unit tests", "add comments").

Specific Files: Scoped to patterns ( *.md, src/*.java).

Apply Manually: Invoked via @rule in Chat panel.

Starter Rule (Always Apply):

<!-- type: Always Apply -->
# No secret in code

Must not commit in source, tests, or comments:
- AWS / GCP / Azure access keys
- Private keys, API tokens, DB connection strings

Pre-commit must confirm absence of above.

Alternative: AGENTS.md at repo root; rule files override AGENTS.md.

Hard limit: All active rules combined ≤ 100k characters; natural language only, no images or links.

Acceptance: AI pauses before "dangerous operations" and asks for confirmation.

Pitfall: Don't dump 100 rules at once—start with three, run two weeks, then add.

25 Vibe Coding Pattern (Team Style Alignment)

SDLC: Implementation / Review

Terminology Note: Karpathy's 2025 "vibe coding" meant "let go, forget code exists"—opposite of this card's "style alignment, no AI flavor." Qoder reframes it as "Team Vibe Infusion": AI-generated code reads like it grew in this repo—style, architectural leanings, naming conventions. No AI smell, no alien smell. The repo reads like one author, yet isn't.

How to start:

Make implicit team style explicit—pull 5 old PRs, ask "why written this way?", document answers.

Convert to rules:

style:
  naming: camelCase-vars, PascalCase-types
  prefer: [composition, immutability, early-return]
  avoid: [boolean-trap-args, deep-nesting]

Acceptance: Newcomer cannot distinguish AI-written code from human-written.

Pitfall: Style shouldn't be a straitjacket; keep a house-style.md for team debate during reviews.

26 Code-Comment Alignment

SDLC: Implementation / Maintenance

Establish bidirectional verification between code and comments so comments never rot.

Comment Convention:

// SPEC: docs/spec/order.md#cancel-idempotent
// WHY:  we don't charge twice for canceled orders
// FROM:  issue #2341

CI Hook Check:

if (comment has "SPEC:" && spec id not in docs/spec/) fail;

Acceptance: Delete a line of code, PR comment auto-surfaces "the comment you removed references a spec—does that spec need updating?"

Pitfall: Don't let AI generate comments; comments are programmer-to-programmer dialogue, AI can only proofread.

27 Change Traceability

SDLC: Requirements / Implementation / Operations

Anchor everything to a Requirement ID , creating traceable links across PRs, code, tests, and ops records. This isn't documentation—it's the organization's safety net.

Naming Convention: All PR titles prefixed with REQ-1234:; commit messages retain prefix.

Git Hook:

if ! echo "$MSG" | grep -E "^REQ-[0-9]+:"; then exit 1; fi

Acceptance: Production issue → trace to requirement ID within 5 minutes.

Pitfall: Abandoning the numbering scheme mid-stream is the most common failure mode; enforce from day one, no exceptions for six months.

28 PR Co-Pilot Review

SDLC: Code Review

AI acts as "second pair of eyes" in PR reviews, surfacing risks while humans retain final decision authority.

AI Review Scope: (1) Potential bugs; (2) Standard violations; (3) Readability hints.

Human Review Scope: (1) Architectural decisions; (2) Business correctness; (3) Naming & intent.

Prompt:

Perform a silent review of this PR: list issues, severity, suggested changes, but do not modify code.

Acceptance: 80% of AI-raised issues auto-triaged within first 3 minutes.

Pitfall: AI never gets veto power; any "blocking" action requires human sign-off.

Dimension VI: Organizational Capability Evolution (组织能力演进)

29 AI IDE Extension & Platform

SDLC: Platform / Toolchain

Via MCP / CLI / extensions, unify multiple AI IDEs into an orchestratable platform capability supporting cross-IDE collaboration. Tools may change; organizational capability stays.

Step 1: Unify CLI entry—all IDEs trigger AI via qodercli.

Step 2: Package team-specific capabilities as reusable chat prompts / Skills (e.g.,

qodercli chat "Review PR #<id>, only list top 3 high-severity issues"

).

Step 3: Wire into each IDE's extension points; developer experience is "click once in IDE."

Acceptance: Switching IDEs doesn't require relearning AI workflows.

Pitfall: Don't patch each IDE separately; converge all capabilities into qodercli.

30 Role-Driven Agent Ensemble

SDLC: Platform / Toolchain

Create agent ensembles around roles (PM / Dev / QA / Architect) to simulate a virtual project team's collaboration and dialogue. One-person company isn't the goal; learning to think like a team is.

Minimal Role Definitions:

roles:
  pm: { goal: clarify value; not_do: [design, code] }
  dev: { goal: implement; not_do: [approve] }
  qa: { goal: verify; not_do: [ship] }
  arch: { goal: keep shape; not_do: [local-detail] }

Phase 1: Start with 1–2 roles, run a "virtual Daily."

Acceptance: Key decisions (architecture, naming, standards) traceable to specific roles.

Pitfall: Roles aren't to "replace people" but to "ensure someone owns every concern."

31 External Agent Collaboration

SDLC: Complex Tasks / Platform

When multiple agent types coexist in the enterprise, treat AI as an orchestrator with clear boundaries and contracts for multi-agent collaboration on complex tasks. The strongest future skill is orchestration.

Contract Trilogy:

Input: Structured schema, no free-form.

Output: Structured schema with verifiable version.

Side-effect Declaration: Which operations have side effects, documented in contract.

Acceptance: Swapping one agent leaves others unaffected.

Pitfall: Blurry boundaries cause agents to "call each other"; nail each agent's I/O with JSON Schema first.

32 AI Coding Observability

SDLC: Complex Tasks / Platform

Observe AI Coding as a production system: invocations, success rate, cost, feedback, anomalies. Without observability, there's no confidence to scale.

Four Core Metrics:

Success Rate: Post-merge rollback rate < 10%.

Latency: P50 / P90 from requirement to production.

Cost: Tokens and dollars per 1k invocations.

Feedback: Developer thumbs-up / complaints / fix suggestions.

Push metrics to existing Grafana / internal dashboards.

Acceptance: Weekly "AI Coding Health Report" posted to team channel.

Pitfall: Watching only invocation volume while ignoring quality is the easiest self-deception.

Closing Thoughts

These 32 cards don't write code for you. But they do something more valuable: they wipe away the tears, preserve your judgment, and help you keep rhythm amid AI's noise.

When AI becomes more like a colleague and less like a tool, what we must practice isn't coding faster—it's judging better, collaborating better, handing off better .

The 32 cards together aren't 32 answers. They are 32 postures of "every engineer has panicked, then steadied themselves."

Real growth isn't outrunning AI, it's running steadier than yesterday's you.

May you, after reading these 32 cards, look back at your own code next time not with anxiety, but with pride.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Report an issue with this article
design patternsMCPtestingAI CodingrefactoringSDLCAgent orchestrationQoder

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion