backend-development

Backend development rules for an AI detective game built with Python and FastAPI. The rules describe its folder structure, imports, naming, architecture, and development practices.

In plain words
What is it for?
Use them when creating routes, application modules, tools, classes, functions, and startup scripts for the game backend.
Why use it?
They give contributors a shared structure for adding backend code without breaking project conventions or making the code harder to maintain.

Cursor rule for Cursor

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/cnwinds/ai-detective/backend-development
Clone the repo
git clone --depth 1 https://github.com/cnwinds/ai-detective

Made for: Cursor.

Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 6,157 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.06157
Opus 5 $0.00000 $0.03078
Sonnet 5 $0.00000 $0.01231
Haiku 4.5 $0.00000 $0.00616

Measured 2d ago against content hash d6ab9a9d4b07, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

backend-development scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

.cursor/rules/backend-development.mdc · 886 lines

How it starts

The opening of the file, as written. The whole thing — 886 lines — stays where its author put it; the contents beside it link to each section on GitHub.

后端开发规范

项目结构和架构原则

后端包结构规范

  • 后端包结构: 所有后端代码在backend包中,确保__init__.py存在
  • 相对导入: 后端模块间使用相对导入:from .module_name import ClassName
  • 启动脚本: 使用绝对导入:from backend.module_name import ClassName
  • 工具脚本: 所有工具脚本放置在tools/目录下
  • 启动方式: 必须在项目根目录运行 python start_game.py

开发原则

  • DRY原则: 避免重复代码,提取公共逻辑
  • 单一职责: 每个函数/类只完成一个明确的功能
  • 对象封装: 使用数据对象简化函数参数
  • 业务逻辑内聚: 相关逻辑封装在同一个类中

命名约定

  • Python: 蛇形命名法 (snake_case)
  • 文件命名: 小写字母加下划线,描述性命名
  • 类命名: 帕斯卡命名法 (PascalCase)
  • 常量命名: 全大写加下划线 (UPPER_SNAKE_CASE)

FastAPI应用架构

标准应用结构

# backend/app.py - 主应用入口
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from .routes import game, admin, history, websocket, common

app = FastAPI(title="AI侦探游戏", version="1.6.0")

# 中间件配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 路由注册
app.include_router(game.router, prefix="/api/game", tags=["游戏"])
app.include_router(admin.router, prefix="/api/admin", tags=["管理"])
app.include_router(history.router, prefix="/api/history", tags=["历史"])
app.include_router(websocket.router, prefix="/ws", tags=["WebSocket"])
app.include_router(common.router, prefix="/api", tags=["通用"])

# 静态文件服务
app.mount("/", StaticFiles(directory="frontend", html=True), name="static")

路由模块化

# backend/routes/game.py
from fastapi import APIRouter, HTTPException, Depends
from ..models import QuestionRequest, GameResponse
from ..game_engine import GameEngine

router = APIRouter()

@router.post("/start", response_model=GameResponse)
async def start_game(case_id: str):
    """开始新游戏会话"""
    try:
        game_engine = GameEngine(case_id)
        session_id = game_engine.create_session()
        
        return GameResponse(
            success=True,
            data={"session_id": session_id, "case": game_engine.get_case_info()}
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/question", response_model=GameResponse)
async def ask_question(request: QuestionRequest):
    """向角色提问"""
    try:
        # 获取游戏会话
        if request.session_id not in game_sessions:
            raise HTTPException(status_code=404, detail="游戏会话不存在")
        
        game_engine = game_sessions[request.session_id]
        
        # 异步处理AI响应
        response = await game_engine.process_question(
            request.character_name, 
            request.question
        )
        
        return GameResponse(success=True, data=response)
        
    except Exception as e:
        logger.error(f"处理问题时出错: {str(e)}")
        return GameResponse(success=False, error=str(e))

Read the full file on GitHub · 886 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 886 lines · 0 tokens per session scan A d6ab9a9d4b07

Subscribe to this mod's changes

backend-development is a cursor rule published in the GitHub repository cnwinds/ai-detective (6 stars, last pushed 1y ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 6,157 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.