[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M72ZZP5MJ7QX7JTP1K649FCF":3,"skill-same:01M72ZZP5MJ7QX7JTP1K649FCF":69},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":45,"commitSha":46,"skillDirectory":47,"forksCount":48,"repositoryHtmlUrl":49,"repositoryHomepageUrl":50,"ownerHtmlUrl":51,"ownerBlogUrl":52,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M72ZZP5MJ7QX7JTP1K649FCF","ai-code-maintainability",null,"Write production-safe code that survives maintenance — avoid the 15 patterns AI agents commonly generate that work on day 1 but break 3 months later; enforce error handling, logging, type safety, no magic values, and testable structure before writing any code.","Horonomos-laps\u002FYana-AI","Horonomos-laps","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F355299122?v=4","01M76B3QPXE88ET2SQPDPVATZT"," Horonomos-laps","01M72ZQRJPCYPSSWT4D00VJR2A",13,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fai-code-maintainability\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: ai-code-maintainability\ndescription: Write production-safe code that survives maintenance — avoid the 15 patterns AI agents commonly generate that work on day 1 but break 3 months later; enforce error handling, logging, type safety, no magic values, and testable structure before writing any code.\ntriggers:\n  - \"ai code maintenance\"\n  - \"code maintainability\"\n  - \"production ready code\"\n  - \"ai generated code problems\"\n  - \"code quality gate\"\n  - \"avoid technical debt\"\n  - \"code review checklist\"\n  - \"prevent maintenance bugs\"\n  - \"ai code anti-patterns\"\n  - \"sustainable code\"\n  - \"code that lasts\"\n  - \"avoid magic numbers\"\n  - \"proper error handling\"\ndo_not_use_for:\n  - Quick prototypes explicitly marked as throwaway\n  - Test fixtures and mock data\nsee_also:\n  - verification\n  - golden-principles\n  - agent-code-constraints\n---\n\n# AI Code Maintainability — Write Code That Survives\n\n**The core problem:** AI agents optimize for \"works on first run.\" Maintenance bugs appear 3–6 months later when context is gone, requirements shift, or edge cases hit prod.\n\n---\n\n## The 15 Patterns That Kill Maintainability\n\n### 1. Silent Error Swallowing (most dangerous)\n\n```python\n# ❌ AI generates this — crashes silently in prod\ntry:\n    result = call_external_api(data)\nexcept:\n    pass\n\n# ✅ Always log + re-raise or return error state\nimport logging\nlogger = logging.getLogger(__name__)\n\ntry:\n    result = call_external_api(data)\nexcept ExternalAPIError as e:\n    logger.error(\"API call failed: %s | data=%s\", e, data, exc_info=True)\n    raise  # or: return Result.error(str(e))\nexcept Exception as e:\n    logger.critical(\"Unexpected error in call_external_api: %s\", e, exc_info=True)\n    raise\n```\n\n### 2. Bare `except` \u002F Pokémon Exception Handling\n\n```python\n# ❌ Catches KeyboardInterrupt, SystemExit, MemoryError — everything\ntry:\n    do_work()\nexcept Exception:  # still too broad\n    return None    # swallowed silently\n\n# ✅ Catch specific exceptions, handle each explicitly\ntry:\n    do_work()\nexcept ValueError as e:\n    logger.warning(\"Invalid input: %s\", e)\n    return default_value\nexcept NetworkError as e:\n    logger.error(\"Network failure: %s\", e)\n    raise RetryableError(f\"Network unavailable: {e}\") from e\n```\n\n### 3. Magic Numbers and Strings\n\n```python\n# ❌ What is 300? What is \"active\"?\nif user.age > 300:\n    status = \"active\"\ntime.sleep(300)\n\n# ✅ Named constants with explanations\nMAX_VALID_AGE_YEARS = 150  # ISO 8601 human lifespan upper bound\nACTIVE_STATUS = \"active\"\nCACHE_REFRESH_INTERVAL_SECONDS = 300  # 5-minute cache TTL per SLA\n\nif user.age > MAX_VALID_AGE_YEARS:\n    status = ACTIVE_STATUS\ntime.sleep(CACHE_REFRESH_INTERVAL_SECONDS)\n```\n\n### 4. print() Instead of Structured Logging\n\n```python\n# ❌ No timestamp, no level, no context, can't filter in prod\nprint(f\"Processing user {user_id}\")\nprint(\"ERROR: something failed\")\n\n# ✅ Structured logging — searchable in Datadog\u002FCloudWatch\u002FGrafana\nimport logging\nlogger = logging.getLogger(__name__)\n\nlogger.info(\"Processing user\", extra={\"user_id\": user_id, \"action\": \"process\"})\nlogger.error(\"Processing failed\", extra={\"user_id\": user_id}, exc_info=True)\n```\n\n### 5. Missing Type Hints (Python \u002F TypeScript)\n\n```python\n# ❌ Future maintainer has no idea what this accepts\u002Freturns\ndef process_data(data, config, mode=None):\n    ...\n\n# ✅ Self-documenting — IDE and mypy catch errors immediately\nfrom typing import Optional\nfrom dataclasses import dataclass\n\ndef process_data(\n    data: list[dict[str, str]],\n    config: ProcessConfig,\n    mode: Optional[ProcessMode] = None,\n) -> ProcessResult:\n    ...\n```\n\n```typescript\n\u002F\u002F ❌ any disables the type system\nfunction processUser(data: any): any {\n  return data.profile.name;\n}\n\n\u002F\u002F ✅ Full types — TypeScript catches data.profile?.name at compile time\ninterface User { id: string; profile: { name: string; email: string } }\ninterface ProcessResult { displayName: string; emailHash: string }\n\nfunction processUser(data: User): ProcessResult {\n  return { displayName: data.profile.name, emailHash: hash(data.profile.email) };\n}\n```\n\n### 6. Mutable Default Arguments (Python silent bug)\n\n```python\n# ❌ Classic Python bug — list shared across ALL calls\ndef add_item(item, items=[]):  # same [] object forever\n    items.append(item)\n    return items\n\nadd_item(\"a\")  # [\"a\"]\nadd_item(\"b\")  # [\"a\", \"b\"]  ← not [\"b\"]!\n\n# ✅ None sentinel pattern\ndef add_item(item: str, items: list[str] | None = None) -> list[str]:\n    if items is None:\n        items = []\n    items.append(item)\n    return items\n```\n\n### 7. Hardcoded Paths and Environment Values\n\n```python\n# ❌ Breaks in Docker, in CI, on another dev's machine\nDATA_PATH = \"\u002Fhome\u002Fuser\u002Fprojects\u002Fmyapp\u002Fdata\"\nAPI_URL = \"http:\u002F\u002Flocalhost:8000\"\n\n# ✅ Environment-driven — works everywhere\nimport os\nfrom pathlib import Path\n\nDATA_PATH = Path(os.environ.get(\"DATA_PATH\", \".\u002Fdata\")).resolve()\nAPI_URL = os.environ.get(\"API_URL\", \"http:\u002F\u002Flocalhost:8000\")\n\nif not os.environ.get(\"API_URL\"):\n    raise EnvironmentError(\"API_URL must be set. Example: export API_URL=https:\u002F\u002Fapi.prod.com\")\n```\n\n### 8. No Retry \u002F Timeout on External Calls\n\n```python\n# ❌ Hangs forever if service is slow; crashes on first transient error\nresponse = requests.get(f\"{API_URL}\u002Fusers\u002F{user_id}\")\ndata = response.json()\n\n# ✅ Timeout + retry with exponential backoff\nimport requests\nfrom tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type\n\n@retry(\n    retry=retry_if_exception_type((requests.Timeout, requests.ConnectionError)),\n    wait=wait_exponential(multiplier=1, min=1, max=30),\n    stop=stop_after_attempt(3),\n)\ndef fetch_user(user_id: str) -> dict:\n    response = requests.get(\n        f\"{API_URL}\u002Fusers\u002F{user_id}\",\n        timeout=(3.05, 27),   # (connect_timeout, read_timeout)\n    )\n    response.raise_for_status()\n    return response.json()\n```\n\n### 9. Unvalidated External Input\n\n```python\n# ❌ Crashes or does wrong thing on unexpected input\ndef create_user(data: dict) -> User:\n    return User(\n        name=data[\"name\"],\n        email=data[\"email\"],\n        age=data[\"age\"],\n    )\n\n# ✅ Validate at system boundary — fail fast with clear message\nfrom pydantic import BaseModel, EmailStr, Field\n\nclass CreateUserRequest(BaseModel):\n    name: str = Field(min_length=1, max_length=100)\n    email: EmailStr\n    age: int = Field(ge=0, le=150)\n\ndef create_user(raw_data: dict) -> User:\n    req = CreateUserRequest.model_validate(raw_data)  # raises ValidationError with details\n    return User(name=req.name, email=req.email, age=req.age)\n```\n\n### 10. Uncaught Promise Rejections (TypeScript\u002FJS)\n\n```typescript\n\u002F\u002F ❌ Unhandled rejection crashes Node.js silently in some versions\nasync function loadData() {\n  const data = await fetchFromAPI();  \u002F\u002F what if this throws?\n  return data;\n}\n\u002F\u002F Caller: loadData()  ← no await, no .catch()\n\n\u002F\u002F ✅ Always handle async errors\nasync function loadData(): Promise\u003CResult\u003CData, AppError>> {\n  try {\n    const data = await fetchFromAPI();\n    return { ok: true, data };\n  } catch (error) {\n    logger.error(\"Failed to load data\", { error });\n    return { ok: false, error: new AppError(\"DATA_LOAD_FAILED\", String(error)) };\n  }\n}\n\n\u002F\u002F Caller always handles:\nconst result = await loadData();\nif (!result.ok) return handleError(result.error);\n```\n\n### 11. Resource Leaks (File\u002FDB\u002FConnection)\n\n```python\n# ❌ File not closed if exception thrown\nf = open(\"data.csv\")\ndata = f.read()\nprocess(data)\nf.close()  # never reached if process() throws\n\n# ✅ Context manager guarantees cleanup\nwith open(\"data.csv\", \"r\", encoding=\"utf-8\") as f:\n    data = f.read()\n\n# ✅ Async version\nasync with aiofiles.open(\"data.csv\") as f:\n    data = await f.read()\n```\n\n### 12. N+1 Query Problem (AI loves loops over DB)\n\n```python\n# ❌ N queries for N users — kills prod at scale\nusers = db.query(User).all()\nfor user in users:\n    orders = db.query(Order).filter(Order.user_id == user.id).all()  # N queries\n    send_summary(user, orders)\n\n# ✅ Eager load with JOIN — 1 query total\nfrom sqlalchemy.orm import joinedload\n\nusers = db.query(User).options(joinedload(User.orders)).all()\nfor user in users:\n    send_summary(user, user.orders)  # already loaded\n```\n\n### 13. Sleeping Instead of Polling with Backoff\n\n```python\n# ❌ Fixed sleep — either too fast (hammers API) or too slow\nwhile True:\n    status = check_job_status(job_id)\n    if status == \"done\":\n        break\n    time.sleep(5)\n\n# ✅ Exponential backoff with max cap\nimport time\n\ndef wait_for_job(job_id: str, max_wait: int = 300) -> JobResult:\n    delay = 1\n    elapsed = 0\n    while elapsed \u003C max_wait:\n        status = check_job_status(job_id)\n        if status.is_terminal():\n            return status\n        logger.debug(\"Job %s status=%s, retrying in %ds\", job_id, status, delay)\n        time.sleep(delay)\n        elapsed += delay\n        delay = min(delay * 2, 30)   # cap at 30s\n    raise TimeoutError(f\"Job {job_id} did not complete within {max_wait}s\")\n```\n\n### 14. Implicit Dependencies Between Modules\n\n```python\n# ❌ Module A depends on global state set by module B — breaks on import order change\n# in config.py\nDATABASE_URL = None\n\n# in main.py\nfrom config import *\nDATABASE_URL = os.environ[\"DATABASE_URL\"]  # set globally\n\n# in users.py — only works if main.py ran first\nfrom config import DATABASE_URL\ndb = connect(DATABASE_URL)  # None if imported before main.py init\n\n# ✅ Explicit dependency injection\nclass UserRepository:\n    def __init__(self, db_url: str):\n        self.db = connect(db_url)\n\n# main.py wires everything\ndb_url = os.environ[\"DATABASE_URL\"]\nuser_repo = UserRepository(db_url=db_url)\n```\n\n### 15. No Idempotency on Write Operations\n\n```python\n# ❌ Double-click \u002F retry creates duplicate records\ndef create_order(user_id: str, items: list) -> Order:\n    order = Order(user_id=user_id, items=items)\n    db.add(order)\n    db.commit()\n    return order\n\n# ✅ Idempotency key prevents duplicates\ndef create_order(user_id: str, items: list, idempotency_key: str) -> Order:\n    existing = db.query(Order).filter(\n        Order.idempotency_key == idempotency_key\n    ).first()\n    if existing:\n        return existing   # same result, no duplicate\n\n    order = Order(user_id=user_id, items=items, idempotency_key=idempotency_key)\n    db.add(order)\n    db.commit()\n    return order\n```\n\n---\n\n## Pre-Write Checklist (run mentally before every function)\n\n```\n□ What happens when the external call fails? (error path written?)\n□ What happens with empty input \u002F null \u002F zero?\n□ Will this work in 6 months without the original context? (self-documenting?)\n□ Are all \"magic\" values named constants?\n□ Does every exception get logged with context?\n□ Are all required env vars validated at startup, not at use time?\n□ If this function is called twice, does it produce the same result?\n□ Can this be tested without the real DB\u002FAPI\u002Ffilesystem?\n```\n\n---\n\n## Self-Review Protocol (before handing off code)\n\n```python\n# Run this mental filter on every file written:\n\nMAINTAINABILITY_CHECKLIST = {\n    \"error_handling\": \"Every try block has a specific except with logging\",\n    \"type_safety\":    \"All function params and returns are typed\",\n    \"constants\":      \"No unexplained numeric or string literals\",\n    \"logging\":        \"Structured logger used, not print()\",\n    \"env_config\":     \"All config comes from env vars with startup validation\",\n    \"timeouts\":       \"All external calls have explicit timeout values\",\n    \"idempotency\":    \"Write operations are safe to retry\",\n    \"resource_mgmt\":  \"All file\u002Fdb\u002Fconnection handles use context managers\",\n    \"no_globals\":     \"No mutable global state; deps injected explicitly\",\n    \"testability\":    \"Can I unit-test this without real external systems?\",\n}\n```\n\n---\n\n## Anti-Fake-Pass Checks\n\n- [ ] Code runs ≠ code is production-safe — always apply checklist\n- [ ] Catching `Exception` is still too broad for most cases — catch specific types\n- [ ] `logger.error(\"failed\")` with no context is nearly useless — log IDs, inputs, stack\n- [ ] Type hints on just the happy path but `Optional` not handled = hidden None crashes\n- [ ] Passing tests doesn't mean idempotency — tests usually don't test double-submit\n- [ ] \"Works in dev\" with env vars from `.env` file ≠ works in prod with missing vars\n","# AI Code Maintainability — Write Code That Survives\n\n**The core problem:** AI agents optimize for \"works on first run.\" Maintenance bugs appear 3–6 months later when context is gone, requirements shift, or edge cases hit prod.\n\n---\n\n## The 15 Patterns That Kill Maintainability\n\n### 1. Silent Error Swallowing (most dangerous)\n\n```python\n# ❌ AI generates this — crashes silently in prod\ntry:\n    result = call_external_api(data)\nexcept:\n    pass\n\n# ✅ Always log + re-raise or return error state\nimport logging\nlogger = logging.getLogger(__name__)\n\ntry:\n    result = call_external_api(data)\nexcept ExternalAPIError as e:\n    logger.error(\"API call failed: %s | data=%s\", e, data, exc_info=True)\n    raise  # or: return Result.error(str(e))\nexcept Exception as e:\n    logger.critical(\"Unexpected error in call_external_api: %s\", e, exc_info=True)\n    raise\n```\n\n### 2. Bare `except` \u002F Pokémon Exception Handling\n\n```python\n# ❌ Catches KeyboardInterrupt, SystemExit, MemoryError — everything\ntry:\n    do_work()\nexcept Exception:  # still too broad\n    return None    # swallowed silently\n\n# ✅ Catch specific exceptions, handle each explicitly\ntry:\n    do_work()\nexcept ValueError as e:\n    logger.warning(\"Invalid input: %s\", e)\n    return default_value\nexcept NetworkError as e:\n    logger.error(\"Network failure: %s\", e)\n    raise RetryableError(f\"Network unavailable: {e}\") from e\n```\n\n### 3. Magic Numbers and Strings\n\n```python\n# ❌ What is 300? What is \"active\"?\nif user.age > 300:\n    status = \"active\"\ntime.sleep(300)\n\n# ✅ Named constants with explanations\nMAX_VALID_AGE_YEARS = 150  # ISO 8601 human lifespan upper bound\nACTIVE_STATUS = \"active\"\nCACHE_REFRESH_INTERVAL_SECONDS = 300  # 5-minute cache TTL per SLA\n\nif user.age > MAX_VALID_AGE_YEARS:\n    status = ACTIVE_STATUS\ntime.sleep(CACHE_REFRESH_INTERVAL_SECONDS)\n```\n\n### 4. print() Instead of Structured Logging\n\n```python\n# ❌ No timestamp, no level, no context, can't filter in prod\nprint(f\"Processing user {user_id}\")\nprint(\"ERROR: something failed\")\n\n# ✅ Structured logging — searchable in Datadog\u002FCloudWatch\u002FGrafana\nimport logging\nlogger = logging.getLogger(__name__)\n\nlogger.info(\"Processing user\", extra={\"user_id\": user_id, \"action\": \"process\"})\nlogger.error(\"Processing failed\", extra={\"user_id\": user_id}, exc_info=True)\n```\n\n### 5. Missing Type Hints (Python \u002F TypeScript)\n\n```python\n# ❌ Future maintainer has no idea what this accepts\u002Freturns\ndef process_data(data, config, mode=None):\n    ...\n\n# ✅ Self-documenting — IDE and mypy catch errors immediately\nfrom typing import Optional\nfrom dataclasses import dataclass\n\ndef process_data(\n    data: list[dict[str, str]],\n    config: ProcessConfig,\n    mode: Optional[ProcessMode] = None,\n) -> ProcessResult:\n    ...\n```\n\n```typescript\n\u002F\u002F ❌ any disables the type system\nfunction processUser(data: any): any {\n  return data.profile.name;\n}\n\n\u002F\u002F ✅ Full types — TypeScript catches data.profile?.name at compile time\ninterface User { id: string; profile: { name: string; email: string } }\ninterface ProcessResult { displayName: string; emailHash: string }\n\nfunction processUser(data: User): ProcessResult {\n  return { displayName: data.profile.name, emailHash: hash(data.profile.email) };\n}\n```\n\n### 6. Mutable Default Arguments (Python silent bug)\n\n```python\n# ❌ Classic Python bug — list shared across ALL calls\ndef add_item(item, items=[]):  # same [] object forever\n    items.append(item)\n    return items\n\nadd_item(\"a\")  # [\"a\"]\nadd_item(\"b\")  # [\"a\", \"b\"]  ← not [\"b\"]!\n\n# ✅ None sentinel pattern\ndef add_item(item: str, items: list[str] | None = None) -> list[str]:\n    if items is None:\n        items = []\n    items.append(item)\n    return items\n```\n\n### 7. Hardcoded Paths and Environment Values\n\n```python\n# ❌ Breaks in Docker, in CI, on another dev's machine\nDATA_PATH = \"\u002Fhome\u002Fuser\u002Fprojects\u002Fmyapp\u002Fdata\"\nAPI_URL = \"http:\u002F\u002Flocalhost:8000\"\n\n# ✅ Environment-driven — works everywhere\nimport os\nfrom pathlib import Path\n\nDATA_PATH = Path(os.environ.get(\"DATA_PATH\", \".\u002Fdata\")).resolve()\nAPI_URL = os.environ.get(\"API_URL\", \"http:\u002F\u002Flocalhost:8000\")\n\nif not os.environ.get(\"API_URL\"):\n    raise EnvironmentError(\"API_URL must be set. Example: export API_URL=https:\u002F\u002Fapi.prod.com\")\n```\n\n### 8. No Retry \u002F Timeout on External Calls\n\n```python\n# ❌ Hangs forever if service is slow; crashes on first transient error\nresponse = requests.get(f\"{API_URL}\u002Fusers\u002F{user_id}\")\ndata = response.json()\n\n# ✅ Timeout + retry with exponential backoff\nimport requests\nfrom tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type\n\n@retry(\n    retry=retry_if_exception_type((requests.Timeout, requests.ConnectionError)),\n    wait=wait_exponential(multiplier=1, min=1, max=30),\n    stop=stop_after_attempt(3),\n)\ndef fetch_user(user_id: str) -> dict:\n    response = requests.get(\n        f\"{API_URL}\u002Fusers\u002F{user_id}\",\n        timeout=(3.05, 27),   # (connect_timeout, read_timeout)\n    )\n    response.raise_for_status()\n    return response.json()\n```\n\n### 9. Unvalidated External Input\n\n```python\n# ❌ Crashes or does wrong thing on unexpected input\ndef create_user(data: dict) -> User:\n    return User(\n        name=data[\"name\"],\n        email=data[\"email\"],\n        age=data[\"age\"],\n    )\n\n# ✅ Validate at system boundary — fail fast with clear message\nfrom pydantic import BaseModel, EmailStr, Field\n\nclass CreateUserRequest(BaseModel):\n    name: str = Field(min_length=1, max_length=100)\n    email: EmailStr\n    age: int = Field(ge=0, le=150)\n\ndef create_user(raw_data: dict) -> User:\n    req = CreateUserRequest.model_validate(raw_data)  # raises ValidationError with details\n    return User(name=req.name, email=req.email, age=req.age)\n```\n\n### 10. Uncaught Promise Rejections (TypeScript\u002FJS)\n\n```typescript\n\u002F\u002F ❌ Unhandled rejection crashes Node.js silently in some versions\nasync function loadData() {\n  const data = await fetchFromAPI();  \u002F\u002F what if this throws?\n  return data;\n}\n\u002F\u002F Caller: loadData()  ← no await, no .catch()\n\n\u002F\u002F ✅ Always handle async errors\nasync function loadData(): Promise\u003CResult\u003CData, AppError>> {\n  try {\n    const data = await fetchFromAPI();\n    return { ok: true, data };\n  } catch (error) {\n    logger.error(\"Failed to load data\", { error });\n    return { ok: false, error: new AppError(\"DATA_LOAD_FAILED\", String(error)) };\n  }\n}\n\n\u002F\u002F Caller always handles:\nconst result = await loadData();\nif (!result.ok) return handleError(result.error);\n```\n\n### 11. Resource Leaks (File\u002FDB\u002FConnection)\n\n```python\n# ❌ File not closed if exception thrown\nf = open(\"data.csv\")\ndata = f.read()\nprocess(data)\nf.close()  # never reached if process() throws\n\n# ✅ Context manager guarantees cleanup\nwith open(\"data.csv\", \"r\", encoding=\"utf-8\") as f:\n    data = f.read()\n\n# ✅ Async version\nasync with aiofiles.open(\"data.csv\") as f:\n    data = await f.read()\n```\n\n### 12. N+1 Query Problem (AI loves loops over DB)\n\n```python\n# ❌ N queries for N users — kills prod at scale\nusers = db.query(User).all()\nfor user in users:\n    orders = db.query(Order).filter(Order.user_id == user.id).all()  # N queries\n    send_summary(user, orders)\n\n# ✅ Eager load with JOIN — 1 query total\nfrom sqlalchemy.orm import joinedload\n\nusers = db.query(User).options(joinedload(User.orders)).all()\nfor user in users:\n    send_summary(user, user.orders)  # already loaded\n```\n\n### 13. Sleeping Instead of Polling with Backoff\n\n```python\n# ❌ Fixed sleep — either too fast (hammers API) or too slow\nwhile True:\n    status = check_job_status(job_id)\n    if status == \"done\":\n        break\n    time.sleep(5)\n\n# ✅ Exponential backoff with max cap\nimport time\n\ndef wait_for_job(job_id: str, max_wait: int = 300) -> JobResult:\n    delay = 1\n    elapsed = 0\n    while elapsed \u003C max_wait:\n        status = check_job_status(job_id)\n        if status.is_terminal():\n            return status\n        logger.debug(\"Job %s status=%s, retrying in %ds\", job_id, status, delay)\n        time.sleep(delay)\n        elapsed += delay\n        delay = min(delay * 2, 30)   # cap at 30s\n    raise TimeoutError(f\"Job {job_id} did not complete within {max_wait}s\")\n```\n\n### 14. Implicit Dependencies Between Modules\n\n```python\n# ❌ Module A depends on global state set by module B — breaks on import order change\n# in config.py\nDATABASE_URL = None\n\n# in main.py\nfrom config import *\nDATABASE_URL = os.environ[\"DATABASE_URL\"]  # set globally\n\n# in users.py — only works if main.py ran first\nfrom config import DATABASE_URL\ndb = connect(DATABASE_URL)  # None if imported before main.py init\n\n# ✅ Explicit dependency injection\nclass UserRepository:\n    def __init__(self, db_url: str):\n        self.db = connect(db_url)\n\n# main.py wires everything\ndb_url = os.environ[\"DATABASE_URL\"]\nuser_repo = UserRepository(db_url=db_url)\n```\n\n### 15. No Idempotency on Write Operations\n\n```python\n# ❌ Double-click \u002F retry creates duplicate records\ndef create_order(user_id: str, items: list) -> Order:\n    order = Order(user_id=user_id, items=items)\n    db.add(order)\n    db.commit()\n    return order\n\n# ✅ Idempotency key prevents duplicates\ndef create_order(user_id: str, items: list, idempotency_key: str) -> Order:\n    existing = db.query(Order).filter(\n        Order.idempotency_key == idempotency_key\n    ).first()\n    if existing:\n        return existing   # same result, no duplicate\n\n    order = Order(user_id=user_id, items=items, idempotency_key=idempotency_key)\n    db.add(order)\n    db.commit()\n    return order\n```\n\n---\n\n## Pre-Write Checklist (run mentally before every function)\n\n```\n□ What happens when the external call fails? (error path written?)\n□ What happens with empty input \u002F null \u002F zero?\n□ Will this work in 6 months without the original context? (self-documenting?)\n□ Are all \"magic\" values named constants?\n□ Does every exception get logged with context?\n□ Are all required env vars validated at startup, not at use time?\n□ If this function is called twice, does it produce the same result?\n□ Can this be tested without the real DB\u002FAPI\u002Ffilesystem?\n```\n\n---\n\n## Self-Review Protocol (before handing off code)\n\n```python\n# Run this mental filter on every file written:\n\nMAINTAINABILITY_CHECKLIST = {\n    \"error_handling\": \"Every try block has a specific except with logging\",\n    \"type_safety\":    \"All function params and returns are typed\",\n    \"constants\":      \"No unexplained numeric or string literals\",\n    \"logging\":        \"Structured logger used, not print()\",\n    \"env_config\":     \"All config comes from env vars with startup validation\",\n    \"timeouts\":       \"All external calls have explicit timeout values\",\n    \"idempotency\":    \"Write operations are safe to retry\",\n    \"resource_mgmt\":  \"All file\u002Fdb\u002Fconnection handles use context managers\",\n    \"no_globals\":     \"No mutable global state; deps injected explicitly\",\n    \"testability\":    \"Can I unit-test this without real external systems?\",\n}\n```\n\n---\n\n## Anti-Fake-Pass Checks\n\n- [ ] Code runs ≠ code is production-safe — always apply checklist\n- [ ] Catching `Exception` is still too broad for most cases — catch specific types\n- [ ] `logger.error(\"failed\")` with no context is nearly useless — log IDs, inputs, stack\n- [ ] Type hints on just the happy path but `Optional` not handled = hidden None crashes\n- [ ] Passing tests doesn't mean idempotency — tests usually don't test double-submit\n- [ ] \"Works in dev\" with env vars from `.env` file ≠ works in prod with missing vars\n",{"name":5,"see_also":24,"triggers":28,"description":7,"do_not_use_for":42},[25,26,27],"verification","golden-principles","agent-code-constraints",[29,30,31,32,33,34,35,36,37,38,39,40,41],"ai code maintenance","code maintainability","production ready code","ai generated code problems","code quality gate","avoid technical debt","code review checklist","prevent maintenance bugs","ai code anti-patterns","sustainable code","code that lasts","avoid magic numbers","proper error handling",[43,44],"Quick prototypes explicitly marked as throwaway","Test fixtures and mock data","main","481dcd7dd2e288b9d627a2bd017db70e64e6c6fa",".claude\u002Fskills\u002Fai-code-maintainability",2,"https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI","https:\u002F\u002Fyana.vutam.link\u002F","https:\u002F\u002Fgithub.com\u002FHoronomos-laps","https:\u002F\u002Fyana.vutam.link","An open-source governed runtime & execution environment for multi-agent AI systems.","2026-11-14 13:24:09",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add Horonomos-laps\u002FYana-AI --skill ai-code-maintainability",{"tool":61,"command":62},"bunx","bunx skills add Horonomos-laps\u002FYana-AI --skill ai-code-maintainability",{"tool":64,"command":65},"pnpm","pnpm dlx skills add Horonomos-laps\u002FYana-AI --skill ai-code-maintainability","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fai-code-maintainability\u002FSKILL.md",true,[],[70,78,85,93,101,109],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":74,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M735GKET5YVYKAY62W2P5YXB","openai--sentry--sentry","Use when the user asks to inspect Sentry issues or events, summarize recent production errors, or pull basic Sentry health data via the Sentry API; perform read-only queries with the bundled script and require `SENTRY_AUTH_TOKEN`.","MIT","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fopenai--sentry--sentry\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M73DCAP83T17HY7SMGK7MGFE","ito-basket-compare","Compare Itô prediction-market baskets against a user's knowledge base, portfolio notes, financial context, watchlist, or research thesis. Use for read-only basket comparison and gap analysis without investment advice or live trading.","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fito-basket-compare\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":89,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M734CYEMZFDR3KH6SW0JP8TD","implementing-network-traffic-baselining","Build network traffic baselines from NetFlow\u002FIPFIX data using Python pandas for statistical analysis, z-score anomaly detection, and hourly\u002Fdaily traffic pattern profiling","https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-network-traffic-baselining\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-network-traffic-baselining\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":97,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":19},"01M73ASZ6NJRJM44Z2P84NGQ3Q","detecting-evasion-techniques-in-endpoint-logs","Detects defense evasion techniques used by adversaries in endpoint logs including log tampering, timestomping, process injection, and security tool disabling. Use when investigating suspicious endpoint behavior, building detection rules for evasion tactics, or conducting threat hunting for stealthy adversary activity. Activates for requests involving evasion detection, defense evasion analysis, log tampering detection, or MITRE ATT&CK TA0005.","https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fdetecting-evasion-techniques-in-endpoint-logs\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fdetecting-evasion-techniques-in-endpoint-logs\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":105,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":19},"01M734AFNXD06Z78QRK0VKGT7Q","implementing-microsegmentation-with-guardicore","Implementing microsegmentation using Akamai Guardicore Segmentation to map application dependencies, create granular network policies, visualize east-west traffic flows, and enforce least-privilege communication between workloads across data centers and cloud.","https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-microsegmentation-with-guardicore\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-microsegmentation-with-guardicore\u002FSKILL.md",[],[],{"skillNo":110,"name":111,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":19},"01M736TK27QMCXK0DVCH25SJN5","ramdisk-tmpfs-patterns","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Framdisk-tmpfs-patterns\u002FSKILL.md",[],[]]