[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7D901STJHC53W9578GTRFDF":3,"skill-same:01M7D901STJHC53W9578GTRFDF":80},{"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":58,"commitSha":59,"skillDirectory":60,"forksCount":14,"repositoryHtmlUrl":61,"repositoryHomepageUrl":6,"ownerHtmlUrl":62,"ownerBlogUrl":63,"ownerDescription":64,"updatedAt":65,"install":66,"resources":79},"01M7D901STJHC53W9578GTRFDF","N+1 Query Detector",null,"Detect and eliminate N+1 query problems in database-backed applications through query counting, execution plan analysis, and ORM configuration auditing","GrupoANDevelopment-m\u002Falberto-ai","GrupoANDevelopment-m","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F257455179?v=4","01M7D69X2N2KEVN0SJF6WGM6SH","Antônio  Ndombe","01M7D69X3P5JTT8H8S904N3888",0,"MIT","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fn-plus-one-query-detector\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: N+1 Query Detector\ndescription: Detect and eliminate N+1 query problems in database-backed applications through query counting, execution plan analysis, and ORM configuration auditing\nversion: 1.0.0\nauthor: Pramod\nlicense: MIT\ntags: [n-plus-one, database-performance, query-optimization, orm, eager-loading, sql-profiling, database-testing]\ntestingTypes: [performance, database]\nframeworks: []\nlanguages: [typescript, javascript, python, java]\ndomains: [api]\nagents: [claude-code, cursor, github-copilot, windsurf, codex, aider, continue, cline, zed, bolt, gemini-cli, amp]\n---\n\n# N+1 Query Detector Skill\n\nYou are an expert QA automation engineer specializing in database performance testing and N+1 query detection. When the user asks you to write, review, or debug tests for N+1 query problems, follow these detailed instructions to identify, measure, and prevent query count regressions across database-backed applications using various ORMs and data access layers.\n\n## Core Principles\n\n1. **Measure, do not guess** -- Always instrument query counting at the database driver level. Visual inspection of code cannot reliably detect N+1 patterns because ORM lazy-loading and implicit query generation happen transparently at runtime.\n2. **Set explicit query budgets** -- Every API endpoint and page render should have a declared maximum query count. Treat query budget overruns as test failures, not warnings.\n3. **Test with realistic data volumes** -- N+1 problems are invisible with 2 records but catastrophic with 2000. Always seed test data with enough rows to expose linear query scaling.\n4. **Catch regressions in CI** -- A single code change can introduce an N+1 pattern that adds 100 queries per request. Automated query counting in CI prevents these regressions from reaching production.\n5. **Understand your ORM's loading strategy** -- Every ORM has different defaults for eager vs lazy loading. Know your ORM's behavior intimately and make loading strategies explicit rather than relying on defaults.\n6. **Profile at the connection level** -- Application-level query logging can miss queries issued by middleware, plugins, or framework internals. Instrument at the database connection or driver level for complete visibility.\n7. **Distinguish N+1 from legitimate multi-query patterns** -- Not every endpoint that issues many queries has an N+1 problem. Some operations legitimately require multiple queries. The key indicator is query count scaling linearly with data size.\n\n## Project Structure\n\nOrganize N+1 detection projects with this structure:\n\n```\ntests\u002F\n  performance\u002F\n    n-plus-one\u002F\n      api-endpoints.spec.ts\n      graphql-resolvers.spec.ts\n      page-renders.spec.ts\n    query-budgets\u002F\n      budget-definitions.ts\n      budget-enforcement.spec.ts\n  helpers\u002F\n    query-counter.ts\n    query-logger.ts\n    data-seeder.ts\n  fixtures\u002F\n    database.fixture.ts\n    query-monitor.fixture.ts\n  reports\u002F\n    query-count-reporter.ts\nconfig\u002F\n  query-budgets.json\n  thresholds.ts\n```\n\n## Query Counting Middleware\n\nThe foundation of N+1 detection is accurate query counting. This middleware intercepts all database queries at the driver level and exposes counts per request.\n\n### Generic Query Counter for Node.js\n\n```typescript\nimport { EventEmitter } from 'events';\n\ninterface QueryLog {\n  sql: string;\n  params: unknown[];\n  duration: number;\n  timestamp: number;\n  stack?: string;\n}\n\nclass QueryCounter extends EventEmitter {\n  private queries: QueryLog[] = [];\n  private isCapturing = false;\n\n  start(): void {\n    this.queries = [];\n    this.isCapturing = true;\n  }\n\n  stop(): QueryLog[] {\n    this.isCapturing = false;\n    return [...this.queries];\n  }\n\n  record(sql: string, params: unknown[], duration: number): void {\n    if (!this.isCapturing) return;\n\n    const entry: QueryLog = {\n      sql,\n      params,\n      duration,\n      timestamp: Date.now(),\n      stack: new Error().stack,\n    };\n\n    this.queries.push(entry);\n    this.emit('query', entry);\n  }\n\n  get count(): number {\n    return this.queries.length;\n  }\n\n  get totalDuration(): number {\n    return this.queries.reduce((sum, q) => sum + q.duration, 0);\n  }\n\n  getGroupedByPattern(): Map\u003Cstring, number> {\n    const groups = new Map\u003Cstring, number>();\n\n    for (const query of this.queries) {\n      \u002F\u002F Normalize the SQL by replacing literal values with placeholders\n      const normalized = query.sql\n        .replace(\u002F= '\\w+'\u002Fg, \"= '?'\")\n        .replace(\u002F= \\d+\u002Fg, '= ?')\n        .replace(\u002FIN \\([^)]+\\)\u002Fg, 'IN (?)')\n        .replace(\u002FLIMIT \\d+\u002Fg, 'LIMIT ?')\n        .replace(\u002FOFFSET \\d+\u002Fg, 'OFFSET ?');\n\n      groups.set(normalized, (groups.get(normalized) || 0) + 1);\n    }\n\n    return groups;\n  }\n\n  detectNPlusOne(threshold: number = 5): string[] {\n    const groups = this.getGroupedByPattern();\n    const violations: string[] = [];\n\n    for (const [pattern, count] of groups) {\n      if (count >= threshold) {\n        violations.push(\n          `N+1 detected: \"${pattern}\" executed ${count} times`\n        );\n      }\n    }\n\n    return violations;\n  }\n\n  reset(): void {\n    this.queries = [];\n    this.isCapturing = false;\n  }\n}\n\nexport const queryCounter = new QueryCounter();\n```\n\n### Prisma Integration\n\n```typescript\nimport { PrismaClient } from '@prisma\u002Fclient';\nimport { queryCounter } from '.\u002Fquery-counter';\n\nfunction createInstrumentedPrisma(): PrismaClient {\n  const prisma = new PrismaClient({\n    log: [\n      { level: 'query', emit: 'event' },\n    ],\n  });\n\n  prisma.$on('query' as never, (e: { query: string; params: string; duration: number }) => {\n    queryCounter.record(e.query, JSON.parse(e.params), e.duration);\n  });\n\n  return prisma;\n}\n\nexport const prisma = createInstrumentedPrisma();\n```\n\n### Express Middleware for Per-Request Counting\n\n```typescript\nimport { Request, Response, NextFunction } from 'express';\nimport { queryCounter } from '.\u002Fquery-counter';\n\ninterface QueryMetrics {\n  queryCount: number;\n  totalDuration: number;\n  nPlusOneViolations: string[];\n}\n\nexport function queryCountingMiddleware(\n  maxQueries: number = 20\n) {\n  return (req: Request, res: Response, next: NextFunction) => {\n    queryCounter.start();\n\n    const originalJson = res.json.bind(res);\n    res.json = function (body: unknown) {\n      const logs = queryCounter.stop();\n      const violations = queryCounter.detectNPlusOne();\n\n      const metrics: QueryMetrics = {\n        queryCount: logs.length,\n        totalDuration: logs.reduce((sum, q) => sum + q.duration, 0),\n        nPlusOneViolations: violations,\n      };\n\n      \u002F\u002F Attach metrics to response headers in development\n      if (process.env.NODE_ENV !== 'production') {\n        res.setHeader('X-Query-Count', metrics.queryCount.toString());\n        res.setHeader('X-Query-Duration', `${metrics.totalDuration}ms`);\n\n        if (metrics.queryCount > maxQueries) {\n          console.warn(\n            `[N+1 WARNING] ${req.method} ${req.path}: ${metrics.queryCount} queries (limit: ${maxQueries})`\n          );\n          for (const v of violations) {\n            console.warn(`  ${v}`);\n          }\n        }\n      }\n\n      return originalJson(body);\n    };\n\n    next();\n  };\n}\n```\n\n## Detecting N+1 Patterns in ORMs\n\n### Prisma N+1 Detection\n\nPrisma defaults to lazy-loading relations, which is the primary source of N+1 queries. The fix is explicit `include` or `select` clauses.\n\n```typescript\nimport { test, expect, beforeAll, afterAll } from 'vitest';\nimport { prisma } from '..\u002Fhelpers\u002Fprisma-instrumented';\nimport { queryCounter } from '..\u002Fhelpers\u002Fquery-counter';\n\nbeforeAll(async () => {\n  \u002F\u002F Seed test data with enough volume to expose N+1\n  const users = Array.from({ length: 50 }, (_, i) => ({\n    name: `User ${i}`,\n    email: `user${i}@test.com`,\n  }));\n\n  await prisma.user.createMany({ data: users });\n\n  const createdUsers = await prisma.user.findMany();\n  for (const user of createdUsers) {\n    await prisma.post.createMany({\n      data: Array.from({ length: 5 }, (_, i) => ({\n        title: `Post ${i} by ${user.name}`,\n        content: `Content ${i}`,\n        authorId: user.id,\n      })),\n    });\n  }\n});\n\nafterAll(async () => {\n  await prisma.post.deleteMany();\n  await prisma.user.deleteMany();\n});\n\ntest('GET \u002Fapi\u002Fusers should not cause N+1 queries', async () => {\n  queryCounter.start();\n\n  \u002F\u002F Simulate the endpoint handler\n  const users = await prisma.user.findMany({\n    include: {\n      posts: {\n        select: { id: true, title: true },\n      },\n    },\n  });\n\n  const logs = queryCounter.stop();\n  const violations = queryCounter.detectNPlusOne();\n\n  \u002F\u002F With proper eager loading, this should be 2 queries max:\n  \u002F\u002F 1. SELECT users\n  \u002F\u002F 2. SELECT posts WHERE authorId IN (...)\n  expect(logs.length).toBeLessThanOrEqual(3);\n  expect(violations).toHaveLength(0);\n\n  \u002F\u002F Verify the data is complete (not lazy-loaded)\n  for (const user of users) {\n    expect(user.posts).toBeDefined();\n    expect(Array.isArray(user.posts)).toBe(true);\n  }\n});\n\ntest('ANTI-PATTERN: lazy loading causes N+1', async () => {\n  queryCounter.start();\n\n  \u002F\u002F This is the N+1 anti-pattern -- DO NOT DO THIS in production\n  const users = await prisma.user.findMany(); \u002F\u002F Query 1\n  for (const user of users) {\n    \u002F\u002F Each iteration issues a new query -- Query 2..N+1\n    const posts = await prisma.post.findMany({\n      where: { authorId: user.id },\n    });\n    \u002F\u002F Process posts...\n  }\n\n  const logs = queryCounter.stop();\n  const violations = queryCounter.detectNPlusOne();\n\n  \u002F\u002F This will issue 1 + N queries (51 queries for 50 users)\n  expect(logs.length).toBeGreaterThan(50);\n  expect(violations.length).toBeGreaterThan(0);\n});\n```\n\n### SQLAlchemy N+1 Detection (Python)\n\n```python\nimport pytest\nfrom sqlalchemy import event, text\nfrom sqlalchemy.orm import Session\nfrom app.models import User, Post\nfrom app.database import engine, SessionLocal\n\n\nclass QueryCounter:\n    def __init__(self):\n        self.queries = []\n        self._listening = False\n\n    def start(self, engine):\n        self.queries = []\n        self._listening = True\n        event.listen(engine, \"before_cursor_execute\", self._record)\n\n    def stop(self, engine):\n        self._listening = False\n        event.remove(engine, \"before_cursor_execute\", self._record)\n        return self.queries\n\n    def _record(self, conn, cursor, statement, parameters, context, executemany):\n        if self._listening:\n            self.queries.append({\n                \"sql\": statement,\n                \"params\": parameters,\n            })\n\n    @property\n    def count(self):\n        return len(self.queries)\n\n    def detect_n_plus_one(self, threshold=5):\n        from collections import Counter\n        import re\n\n        normalized = []\n        for q in self.queries:\n            sql = re.sub(r\"= '[^']*'\", \"= '?'\", q[\"sql\"])\n            sql = re.sub(r\"= \\d+\", \"= ?\", sql)\n            normalized.append(sql)\n\n        counts = Counter(normalized)\n        return {sql: count for sql, count in counts.items() if count >= threshold}\n\n\n@pytest.fixture\ndef query_counter():\n    counter = QueryCounter()\n    counter.start(engine)\n    yield counter\n    counter.stop(engine)\n\n\ndef test_get_users_with_posts_no_n_plus_one(query_counter, db_session: Session):\n    \"\"\"Verify eager loading prevents N+1 queries.\"\"\"\n    from sqlalchemy.orm import joinedload\n\n    # Correct: eager load with joinedload\n    users = (\n        db_session.query(User)\n        .options(joinedload(User.posts))\n        .all()\n    )\n\n    assert query_counter.count \u003C= 2  # 1 JOIN query or 2 separate queries\n    violations = query_counter.detect_n_plus_one()\n    assert len(violations) == 0\n\n    # Verify data is loaded\n    for user in users:\n        assert hasattr(user, \"posts\")\n\n\ndef test_lazy_loading_causes_n_plus_one(query_counter, db_session: Session):\n    \"\"\"Demonstrate the N+1 anti-pattern with lazy loading.\"\"\"\n    # Anti-pattern: no eager loading specified\n    users = db_session.query(User).all()  # Query 1\n\n    for user in users:\n        _ = user.posts  # Each access triggers a query\n\n    violations = query_counter.detect_n_plus_one()\n    assert len(violations) > 0, \"Expected N+1 pattern not detected\"\n```\n\n### Hibernate N+1 Detection (Java)\n\n```java\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport net.ttddyy.dsproxy.QueryCountHolder;\nimport static org.assertj.core.api.Assertions.assertThat;\n\n@SpringBootTest\nclass NPlusOneDetectionTest {\n\n    @Autowired\n    private UserRepository userRepository;\n\n    @Test\n    void getUsersWithPosts_shouldNotCauseNPlusOne() {\n        QueryCountHolder.clear();\n\n        \u002F\u002F Uses @EntityGraph or JOIN FETCH\n        var users = userRepository.findAllWithPosts();\n\n        var queryCount = QueryCountHolder.getGrandTotal();\n\n        \u002F\u002F Should be at most 1-2 queries with proper fetch strategy\n        assertThat(queryCount.getSelect()).isLessThanOrEqualTo(2);\n\n        \u002F\u002F Verify posts are loaded\n        for (var user : users) {\n            assertThat(user.getPosts()).isNotNull();\n            assertThat(\n                org.hibernate.Hibernate.isInitialized(user.getPosts())\n            ).isTrue();\n        }\n    }\n}\n```\n\n## Automated Threshold Testing\n\n### Query Budget Definitions\n\n```typescript\n\u002F\u002F config\u002Fquery-budgets.ts\n\nexport interface QueryBudget {\n  endpoint: string;\n  method: string;\n  maxQueries: number;\n  maxDurationMs: number;\n  description: string;\n}\n\nexport const QUERY_BUDGETS: QueryBudget[] = [\n  {\n    endpoint: '\u002Fapi\u002Fusers',\n    method: 'GET',\n    maxQueries: 3,\n    maxDurationMs: 100,\n    description: 'List users with counts',\n  },\n  {\n    endpoint: '\u002Fapi\u002Fusers\u002F:id',\n    method: 'GET',\n    maxQueries: 4,\n    maxDurationMs: 50,\n    description: 'Single user with relations',\n  },\n  {\n    endpoint: '\u002Fapi\u002Fposts',\n    method: 'GET',\n    maxQueries: 5,\n    maxDurationMs: 150,\n    description: 'List posts with author and tags',\n  },\n  {\n    endpoint: '\u002Fapi\u002Fdashboard',\n    method: 'GET',\n    maxQueries: 8,\n    maxDurationMs: 200,\n    description: 'Dashboard with aggregations',\n  },\n  {\n    endpoint: '\u002Fapi\u002Ffeed',\n    method: 'GET',\n    maxQueries: 6,\n    maxDurationMs: 200,\n    description: 'Activity feed with nested data',\n  },\n];\n```\n\n### Budget Enforcement Tests\n\n```typescript\nimport { test, expect, describe, beforeEach, afterEach } from 'vitest';\nimport { queryCounter } from '..\u002Fhelpers\u002Fquery-counter';\nimport { QUERY_BUDGETS } from '..\u002F..\u002Fconfig\u002Fquery-budgets';\nimport request from 'supertest';\nimport { app } from '..\u002F..\u002Fsrc\u002Fapp';\n\ndescribe('Query Budget Enforcement', () => {\n  for (const budget of QUERY_BUDGETS) {\n    test(`${budget.method} ${budget.endpoint} should stay within query budget (max: ${budget.maxQueries})`, async () => {\n      queryCounter.start();\n\n      const resolvedEndpoint = budget.endpoint.replace(\n        \u002F:id\u002Fg,\n        '1'\n      );\n\n      const response = await request(app)\n        [budget.method.toLowerCase() as 'get' | 'post'](resolvedEndpoint)\n        .set('Accept', 'application\u002Fjson');\n\n      const logs = queryCounter.stop();\n\n      expect(response.status).toBeLessThan(500);\n\n      \u002F\u002F Enforce query count budget\n      expect(\n        logs.length,\n        `${budget.method} ${budget.endpoint}: ${logs.length} queries exceeds budget of ${budget.maxQueries}. ` +\n        `Queries:\\n${logs.map((q) => `  - ${q.sql.substring(0, 120)}`).join('\\n')}`\n      ).toBeLessThanOrEqual(budget.maxQueries);\n\n      \u002F\u002F Enforce duration budget\n      const totalDuration = logs.reduce((sum, q) => sum + q.duration, 0);\n      expect(\n        totalDuration,\n        `${budget.method} ${budget.endpoint}: ${totalDuration}ms exceeds duration budget of ${budget.maxDurationMs}ms`\n      ).toBeLessThanOrEqual(budget.maxDurationMs);\n\n      \u002F\u002F Check for N+1 patterns\n      const violations = queryCounter.detectNPlusOne(3);\n      expect(\n        violations,\n        `N+1 detected in ${budget.method} ${budget.endpoint}:\\n${violations.join('\\n')}`\n      ).toHaveLength(0);\n    });\n  }\n});\n```\n\n## DataLoader Pattern for GraphQL\n\nGraphQL APIs are especially vulnerable to N+1 problems because each resolver fetches data independently. The DataLoader pattern batches and deduplicates these fetches.\n\n```typescript\nimport DataLoader from 'dataloader';\nimport { prisma } from '.\u002Fprisma';\n\n\u002F\u002F DataLoader batches individual post lookups into a single query\nexport function createPostLoader() {\n  return new DataLoader\u003Cstring, Post[]>(async (userIds) => {\n    \u002F\u002F Single query: SELECT * FROM posts WHERE authorId IN (...)\n    const posts = await prisma.post.findMany({\n      where: {\n        authorId: { in: [...userIds] },\n      },\n    });\n\n    \u002F\u002F Map posts back to their respective user IDs\n    const postsByUserId = new Map\u003Cstring, Post[]>();\n    for (const post of posts) {\n      const existing = postsByUserId.get(post.authorId) || [];\n      existing.push(post);\n      postsByUserId.set(post.authorId, existing);\n    }\n\n    return userIds.map((id) => postsByUserId.get(id) || []);\n  });\n}\n\n\u002F\u002F Test that DataLoader properly batches\nimport { test, expect } from 'vitest';\n\ntest('DataLoader should batch user post lookups', async () => {\n  queryCounter.start();\n\n  const postLoader = createPostLoader();\n\n  \u002F\u002F These 50 calls should be batched into 1 query\n  const userIds = Array.from({ length: 50 }, (_, i) => `user-${i}`);\n  const results = await Promise.all(\n    userIds.map((id) => postLoader.load(id))\n  );\n\n  const logs = queryCounter.stop();\n\n  \u002F\u002F DataLoader should batch all 50 lookups into 1 query\n  expect(logs.length).toBe(1);\n  expect(logs[0].sql).toContain('IN');\n  expect(results).toHaveLength(50);\n});\n\ntest('DataLoader should deduplicate identical requests', async () => {\n  queryCounter.start();\n\n  const postLoader = createPostLoader();\n\n  \u002F\u002F Same user ID requested 10 times\n  const sameId = 'user-1';\n  const results = await Promise.all(\n    Array.from({ length: 10 }, () => postLoader.load(sameId))\n  );\n\n  const logs = queryCounter.stop();\n\n  \u002F\u002F Should still be 1 query despite 10 requests\n  expect(logs.length).toBe(1);\n  \u002F\u002F All results should be the same reference\n  const firstResult = results[0];\n  results.forEach((r) => expect(r).toBe(firstResult));\n});\n```\n\n## Request-Level Query Budgets\n\n### Middleware That Fails Requests Exceeding Budget\n\n```typescript\nimport { Request, Response, NextFunction } from 'express';\nimport { queryCounter } from '.\u002Fquery-counter';\n\ninterface BudgetConfig {\n  [route: string]: {\n    maxQueries: number;\n    action: 'warn' | 'block' | 'log';\n  };\n}\n\nconst budgetConfig: BudgetConfig = {\n  'GET \u002Fapi\u002Fusers': { maxQueries: 3, action: 'block' },\n  'GET \u002Fapi\u002Fposts': { maxQueries: 5, action: 'block' },\n  'GET \u002Fapi\u002Fdashboard': { maxQueries: 10, action: 'warn' },\n  '*': { maxQueries: 20, action: 'log' },\n};\n\nexport function queryBudgetMiddleware() {\n  return (req: Request, res: Response, next: NextFunction) => {\n    queryCounter.start();\n\n    const originalEnd = res.end.bind(res);\n    res.end = function (...args: Parameters\u003CResponse['end']>) {\n      const logs = queryCounter.stop();\n      const routeKey = `${req.method} ${req.route?.path || req.path}`;\n      const config =\n        budgetConfig[routeKey] || budgetConfig['*'];\n\n      if (logs.length > config.maxQueries) {\n        const message = `Query budget exceeded: ${routeKey} used ${logs.length}\u002F${config.maxQueries} queries`;\n\n        switch (config.action) {\n          case 'block':\n            if (!res.headersSent) {\n              res.status(503).json({\n                error: 'Service temporarily unavailable',\n                reason: process.env.NODE_ENV === 'development' ? message : undefined,\n              });\n              return res;\n            }\n            break;\n          case 'warn':\n            console.warn(`[QUERY BUDGET WARNING] ${message}`);\n            break;\n          case 'log':\n            console.log(`[QUERY BUDGET] ${message}`);\n            break;\n        }\n      }\n\n      return originalEnd(...args);\n    } as Response['end'];\n\n    next();\n  };\n}\n```\n\n## CI Integration for Query Count Regression\n\n### GitHub Actions Workflow Integration\n\n```typescript\n\u002F\u002F tests\u002Fperformance\u002Fquery-regression.spec.ts\nimport { test, expect, describe } from 'vitest';\nimport { queryCounter } from '..\u002Fhelpers\u002Fquery-counter';\nimport { readFileSync, writeFileSync, existsSync } from 'fs';\nimport { join } from 'path';\n\nconst BASELINE_PATH = join(__dirname, '..\u002F..\u002F.query-baseline.json');\n\ninterface QueryBaseline {\n  [endpoint: string]: {\n    queryCount: number;\n    measuredAt: string;\n  };\n}\n\nfunction loadBaseline(): QueryBaseline {\n  if (existsSync(BASELINE_PATH)) {\n    return JSON.parse(readFileSync(BASELINE_PATH, 'utf-8'));\n  }\n  return {};\n}\n\nfunction saveBaseline(baseline: QueryBaseline): void {\n  writeFileSync(BASELINE_PATH, JSON.stringify(baseline, null, 2));\n}\n\ndescribe('Query Count Regression Detection', () => {\n  const endpoints = [\n    { method: 'GET', path: '\u002Fapi\u002Fusers', handler: getUsersHandler },\n    { method: 'GET', path: '\u002Fapi\u002Fposts', handler: getPostsHandler },\n    { method: 'GET', path: '\u002Fapi\u002Fdashboard', handler: getDashboardHandler },\n  ];\n\n  for (const endpoint of endpoints) {\n    test(`${endpoint.method} ${endpoint.path} should not regress in query count`, async () => {\n      const baseline = loadBaseline();\n      const key = `${endpoint.method} ${endpoint.path}`;\n\n      queryCounter.start();\n      await endpoint.handler();\n      const logs = queryCounter.stop();\n\n      const currentCount = logs.length;\n\n      if (baseline[key]) {\n        const previousCount = baseline[key].queryCount;\n        const regressionThreshold = Math.ceil(previousCount * 1.1); \u002F\u002F 10% tolerance\n\n        expect(\n          currentCount,\n          `Query regression detected for ${key}: was ${previousCount}, now ${currentCount}`\n        ).toBeLessThanOrEqual(regressionThreshold);\n      }\n\n      \u002F\u002F Update baseline if running in update mode\n      if (process.env.UPDATE_QUERY_BASELINE === 'true') {\n        baseline[key] = {\n          queryCount: currentCount,\n          measuredAt: new Date().toISOString(),\n        };\n        saveBaseline(baseline);\n      }\n    });\n  }\n});\n```\n\n### Eager vs Lazy Loading Audit\n\n```typescript\nimport { test, expect, describe } from 'vitest';\nimport { PrismaClient } from '@prisma\u002Fclient';\n\ndescribe('ORM Loading Strategy Audit', () => {\n  test('all list endpoints should use explicit includes', async () => {\n    \u002F\u002F Parse the route handlers and check for include clauses\n    const routeFiles = [\n      'src\u002Froutes\u002Fusers.ts',\n      'src\u002Froutes\u002Fposts.ts',\n      'src\u002Froutes\u002Fcomments.ts',\n    ];\n\n    for (const file of routeFiles) {\n      const content = require('fs').readFileSync(file, 'utf-8');\n\n      \u002F\u002F Check for findMany without include (potential N+1)\n      const findManyWithoutInclude = \u002F\\.findMany\\(\\s*\\)\u002Fg;\n      const matches = content.match(findManyWithoutInclude);\n\n      if (matches) {\n        console.warn(\n          `${file}: Found ${matches.length} findMany() calls without includes`\n        );\n      }\n\n      expect(\n        matches,\n        `${file} has findMany() without explicit include — potential N+1`\n      ).toBeNull();\n    }\n  });\n\n  test('related data access should use include, not separate queries', async () => {\n    \u002F\u002F Verify that getting a user with posts uses a single include\n    queryCounter.start();\n\n    const user = await prisma.user.findUnique({\n      where: { id: 'test-user-1' },\n      include: {\n        posts: true,\n        comments: true,\n        profile: true,\n      },\n    });\n\n    const logs = queryCounter.stop();\n\n    \u002F\u002F findUnique with include should generate at most 4 queries\n    \u002F\u002F (1 per relation + 1 for the main entity, or fewer with JOINs)\n    expect(logs.length).toBeLessThanOrEqual(4);\n  });\n});\n```\n\n## Configuration\n\n### Query Counter Configuration\n\n```typescript\n\u002F\u002F config\u002Fthresholds.ts\n\nexport const QUERY_THRESHOLDS = {\n  \u002F\u002F Maximum queries per request before triggering N+1 detection\n  nPlusOneDetectionThreshold: 5,\n\n  \u002F\u002F Maximum total queries per request\n  maxQueriesPerRequest: 20,\n\n  \u002F\u002F Maximum total query duration per request (ms)\n  maxQueryDurationMs: 500,\n\n  \u002F\u002F Percentage increase allowed before flagging as regression\n  regressionTolerancePercent: 10,\n\n  \u002F\u002F Minimum data volume for meaningful N+1 testing\n  minimumTestDataRows: 50,\n\n  \u002F\u002F Enable detailed query logging in CI\n  verboseLogging: process.env.CI === 'true',\n\n  \u002F\u002F File path for query count baselines\n  baselinePath: '.query-baseline.json',\n};\n```\n\n## Best Practices\n\n1. **Always use `include` or `select` with list queries** -- When fetching a list of records that will need related data, declare the relations upfront in the query. Never iterate over results and issue individual relation lookups.\n\n2. **Seed tests with at least 50 parent records** -- N+1 problems are proportional to data size. With 2 records, 3 queries vs 2 queries is invisible. With 50 records, 51 queries vs 2 queries is obvious.\n\n3. **Make query budgets part of the API contract** -- Document the expected query count for each endpoint. When a PR changes an endpoint, reviewers should verify that the query budget is still reasonable.\n\n4. **Use DataLoader for GraphQL resolvers** -- Every resolver that accesses related data must use a DataLoader instance. Create a new DataLoader per request to avoid cross-request caching issues.\n\n5. **Profile production queries periodically** -- N+1 problems can hide behind caches in development. Use production query profiling tools (pg_stat_statements, slow query logs) to identify patterns that only emerge at production data volumes.\n\n6. **Prefer batch operations over loops** -- Replace `for` loops that issue individual `INSERT`, `UPDATE`, or `DELETE` statements with batch operations (`createMany`, `updateMany`, bulk operations).\n\n7. **Test with pagination** -- N+1 detection must work correctly with paginated queries. Ensure that eager loading applies to the paginated subset, not to all records.\n\n8. **Instrument integration tests, not just unit tests** -- Unit tests with mocked databases cannot detect N+1 patterns. Use integration tests with a real database (or in-memory database like SQLite) for query counting.\n\n9. **Log the full query with parameters** -- When a query budget violation is detected, log the complete SQL with bound parameters. This makes it immediately clear which query is being repeated.\n\n10. **Use connection pooling metrics** -- Monitor connection pool checkout counts per request. An N+1 pattern will show high pool checkout rates even if individual queries are fast.\n\n11. **Fail CI on query count regressions** -- Make query budget tests non-optional in CI. A query count regression that is merged today becomes a production performance incident tomorrow.\n\n12. **Audit ORM lazy-loading configuration** -- Review your ORM's default loading strategy. In Prisma, relations are not loaded by default. In Hibernate, `@OneToMany` defaults to `FetchType.LAZY`. Know the defaults and override them explicitly.\n\n## Anti-Patterns to Avoid\n\n1. **Iterating and querying in a loop** -- The classic N+1 anti-pattern: `users.forEach(async (user) => { const posts = await getPosts(user.id); })`. Always use `include`, `JOIN`, or `IN` clauses instead.\n\n2. **Relying on ORM lazy loading in production** -- Lazy loading is convenient in development but catastrophic in production. Disable lazy loading or configure your ORM to warn when it triggers implicit queries.\n\n3. **Caching to hide N+1 problems** -- Adding a Redis cache on top of an N+1 endpoint masks the problem but does not fix it. Cache misses will still trigger the full N+1 pattern, and cold starts become extremely slow.\n\n4. **Testing with empty or minimal data** -- Testing with 1-2 records will never reveal N+1 issues. The query count will look reasonable even with the most pathological access patterns. Always test with realistic data volumes.\n\n5. **Using `SELECT *` when only IDs are needed** -- Fetching full records when you only need identifiers wastes bandwidth and memory. Use `select` clauses to fetch only the columns you need, and use `IN` queries for batch lookups.\n\n6. **Ignoring GraphQL query depth** -- Deeply nested GraphQL queries can create cascading N+1 problems at each resolver level. Implement query depth limiting and require DataLoader at every level.\n\n7. **Manual SQL string construction in loops** -- Building `WHERE id = ?` queries in a loop instead of `WHERE id IN (?, ?, ?)` is an N+1 pattern that ORMs would normally prevent. If writing raw SQL, always use batch operations.\n\n## Debugging Tips\n\n1. **Enable query logging at the driver level** -- Set `log: ['query']` in Prisma, `echo=True` in SQLAlchemy, or `hibernate.show_sql=true` in Hibernate. Count the queries manually for a single request to establish a baseline.\n\n2. **Use `EXPLAIN ANALYZE` on repeated queries** -- If you see the same query pattern repeated many times, run `EXPLAIN ANALYZE` to understand its execution plan. A query that does a full table scan 50 times per request is doubly problematic.\n\n3. **Check for missing indexes on foreign keys** -- N+1 queries often hit foreign key columns. Ensure that all foreign key columns have indexes. Without indexes, each individual query in the N+1 pattern does a sequential scan.\n\n4. **Watch for N+1 in serialization** -- Some frameworks trigger lazy loading during JSON serialization when accessing relation properties. The N+1 happens not in the controller but in the serializer.\n\n5. **Profile with a database proxy** -- Tools like pgBouncer, datasource-proxy (Java), or prisma-query-log can intercept all queries without modifying application code. This gives complete visibility into query patterns.\n\n6. **Count queries per request in development** -- Add a simple middleware that logs the total query count for every request during development. Make this visible in the terminal output so developers notice regressions immediately.\n\n7. **Examine the SQL pattern, not just the count** -- A high query count is not always N+1. Look for the signature pattern: one query followed by N identical queries with different parameter values. This distinguishes N+1 from legitimate multi-query operations.\n\n8. **Test GraphQL resolvers in isolation** -- When debugging GraphQL N+1 issues, test each resolver independently with the DataLoader context to verify that batching is working. A misconfigured DataLoader that creates a new instance per resolve call will not batch.\n\n9. **Check for N+1 in database triggers** -- If your database has triggers that run additional queries on INSERT or UPDATE, these can create N+1-like behavior that is invisible at the application level. Review trigger definitions when query counts exceed expectations.\n\n10. **Use flamegraph-style query visualization** -- Tools that show queries on a timeline (like Prisma Studio or Django Debug Toolbar) make it visually obvious when 50 identical queries fire in sequence. The waterfall pattern of N+1 is unmistakable in a timeline view.\n","# N+1 Query Detector Skill\n\nYou are an expert QA automation engineer specializing in database performance testing and N+1 query detection. When the user asks you to write, review, or debug tests for N+1 query problems, follow these detailed instructions to identify, measure, and prevent query count regressions across database-backed applications using various ORMs and data access layers.\n\n## Core Principles\n\n1. **Measure, do not guess** -- Always instrument query counting at the database driver level. Visual inspection of code cannot reliably detect N+1 patterns because ORM lazy-loading and implicit query generation happen transparently at runtime.\n2. **Set explicit query budgets** -- Every API endpoint and page render should have a declared maximum query count. Treat query budget overruns as test failures, not warnings.\n3. **Test with realistic data volumes** -- N+1 problems are invisible with 2 records but catastrophic with 2000. Always seed test data with enough rows to expose linear query scaling.\n4. **Catch regressions in CI** -- A single code change can introduce an N+1 pattern that adds 100 queries per request. Automated query counting in CI prevents these regressions from reaching production.\n5. **Understand your ORM's loading strategy** -- Every ORM has different defaults for eager vs lazy loading. Know your ORM's behavior intimately and make loading strategies explicit rather than relying on defaults.\n6. **Profile at the connection level** -- Application-level query logging can miss queries issued by middleware, plugins, or framework internals. Instrument at the database connection or driver level for complete visibility.\n7. **Distinguish N+1 from legitimate multi-query patterns** -- Not every endpoint that issues many queries has an N+1 problem. Some operations legitimately require multiple queries. The key indicator is query count scaling linearly with data size.\n\n## Project Structure\n\nOrganize N+1 detection projects with this structure:\n\n```\ntests\u002F\n  performance\u002F\n    n-plus-one\u002F\n      api-endpoints.spec.ts\n      graphql-resolvers.spec.ts\n      page-renders.spec.ts\n    query-budgets\u002F\n      budget-definitions.ts\n      budget-enforcement.spec.ts\n  helpers\u002F\n    query-counter.ts\n    query-logger.ts\n    data-seeder.ts\n  fixtures\u002F\n    database.fixture.ts\n    query-monitor.fixture.ts\n  reports\u002F\n    query-count-reporter.ts\nconfig\u002F\n  query-budgets.json\n  thresholds.ts\n```\n\n## Query Counting Middleware\n\nThe foundation of N+1 detection is accurate query counting. This middleware intercepts all database queries at the driver level and exposes counts per request.\n\n### Generic Query Counter for Node.js\n\n```typescript\nimport { EventEmitter } from 'events';\n\ninterface QueryLog {\n  sql: string;\n  params: unknown[];\n  duration: number;\n  timestamp: number;\n  stack?: string;\n}\n\nclass QueryCounter extends EventEmitter {\n  private queries: QueryLog[] = [];\n  private isCapturing = false;\n\n  start(): void {\n    this.queries = [];\n    this.isCapturing = true;\n  }\n\n  stop(): QueryLog[] {\n    this.isCapturing = false;\n    return [...this.queries];\n  }\n\n  record(sql: string, params: unknown[], duration: number): void {\n    if (!this.isCapturing) return;\n\n    const entry: QueryLog = {\n      sql,\n      params,\n      duration,\n      timestamp: Date.now(),\n      stack: new Error().stack,\n    };\n\n    this.queries.push(entry);\n    this.emit('query', entry);\n  }\n\n  get count(): number {\n    return this.queries.length;\n  }\n\n  get totalDuration(): number {\n    return this.queries.reduce((sum, q) => sum + q.duration, 0);\n  }\n\n  getGroupedByPattern(): Map\u003Cstring, number> {\n    const groups = new Map\u003Cstring, number>();\n\n    for (const query of this.queries) {\n      \u002F\u002F Normalize the SQL by replacing literal values with placeholders\n      const normalized = query.sql\n        .replace(\u002F= '\\w+'\u002Fg, \"= '?'\")\n        .replace(\u002F= \\d+\u002Fg, '= ?')\n        .replace(\u002FIN \\([^)]+\\)\u002Fg, 'IN (?)')\n        .replace(\u002FLIMIT \\d+\u002Fg, 'LIMIT ?')\n        .replace(\u002FOFFSET \\d+\u002Fg, 'OFFSET ?');\n\n      groups.set(normalized, (groups.get(normalized) || 0) + 1);\n    }\n\n    return groups;\n  }\n\n  detectNPlusOne(threshold: number = 5): string[] {\n    const groups = this.getGroupedByPattern();\n    const violations: string[] = [];\n\n    for (const [pattern, count] of groups) {\n      if (count >= threshold) {\n        violations.push(\n          `N+1 detected: \"${pattern}\" executed ${count} times`\n        );\n      }\n    }\n\n    return violations;\n  }\n\n  reset(): void {\n    this.queries = [];\n    this.isCapturing = false;\n  }\n}\n\nexport const queryCounter = new QueryCounter();\n```\n\n### Prisma Integration\n\n```typescript\nimport { PrismaClient } from '@prisma\u002Fclient';\nimport { queryCounter } from '.\u002Fquery-counter';\n\nfunction createInstrumentedPrisma(): PrismaClient {\n  const prisma = new PrismaClient({\n    log: [\n      { level: 'query', emit: 'event' },\n    ],\n  });\n\n  prisma.$on('query' as never, (e: { query: string; params: string; duration: number }) => {\n    queryCounter.record(e.query, JSON.parse(e.params), e.duration);\n  });\n\n  return prisma;\n}\n\nexport const prisma = createInstrumentedPrisma();\n```\n\n### Express Middleware for Per-Request Counting\n\n```typescript\nimport { Request, Response, NextFunction } from 'express';\nimport { queryCounter } from '.\u002Fquery-counter';\n\ninterface QueryMetrics {\n  queryCount: number;\n  totalDuration: number;\n  nPlusOneViolations: string[];\n}\n\nexport function queryCountingMiddleware(\n  maxQueries: number = 20\n) {\n  return (req: Request, res: Response, next: NextFunction) => {\n    queryCounter.start();\n\n    const originalJson = res.json.bind(res);\n    res.json = function (body: unknown) {\n      const logs = queryCounter.stop();\n      const violations = queryCounter.detectNPlusOne();\n\n      const metrics: QueryMetrics = {\n        queryCount: logs.length,\n        totalDuration: logs.reduce((sum, q) => sum + q.duration, 0),\n        nPlusOneViolations: violations,\n      };\n\n      \u002F\u002F Attach metrics to response headers in development\n      if (process.env.NODE_ENV !== 'production') {\n        res.setHeader('X-Query-Count', metrics.queryCount.toString());\n        res.setHeader('X-Query-Duration', `${metrics.totalDuration}ms`);\n\n        if (metrics.queryCount > maxQueries) {\n          console.warn(\n            `[N+1 WARNING] ${req.method} ${req.path}: ${metrics.queryCount} queries (limit: ${maxQueries})`\n          );\n          for (const v of violations) {\n            console.warn(`  ${v}`);\n          }\n        }\n      }\n\n      return originalJson(body);\n    };\n\n    next();\n  };\n}\n```\n\n## Detecting N+1 Patterns in ORMs\n\n### Prisma N+1 Detection\n\nPrisma defaults to lazy-loading relations, which is the primary source of N+1 queries. The fix is explicit `include` or `select` clauses.\n\n```typescript\nimport { test, expect, beforeAll, afterAll } from 'vitest';\nimport { prisma } from '..\u002Fhelpers\u002Fprisma-instrumented';\nimport { queryCounter } from '..\u002Fhelpers\u002Fquery-counter';\n\nbeforeAll(async () => {\n  \u002F\u002F Seed test data with enough volume to expose N+1\n  const users = Array.from({ length: 50 }, (_, i) => ({\n    name: `User ${i}`,\n    email: `user${i}@test.com`,\n  }));\n\n  await prisma.user.createMany({ data: users });\n\n  const createdUsers = await prisma.user.findMany();\n  for (const user of createdUsers) {\n    await prisma.post.createMany({\n      data: Array.from({ length: 5 }, (_, i) => ({\n        title: `Post ${i} by ${user.name}`,\n        content: `Content ${i}`,\n        authorId: user.id,\n      })),\n    });\n  }\n});\n\nafterAll(async () => {\n  await prisma.post.deleteMany();\n  await prisma.user.deleteMany();\n});\n\ntest('GET \u002Fapi\u002Fusers should not cause N+1 queries', async () => {\n  queryCounter.start();\n\n  \u002F\u002F Simulate the endpoint handler\n  const users = await prisma.user.findMany({\n    include: {\n      posts: {\n        select: { id: true, title: true },\n      },\n    },\n  });\n\n  const logs = queryCounter.stop();\n  const violations = queryCounter.detectNPlusOne();\n\n  \u002F\u002F With proper eager loading, this should be 2 queries max:\n  \u002F\u002F 1. SELECT users\n  \u002F\u002F 2. SELECT posts WHERE authorId IN (...)\n  expect(logs.length).toBeLessThanOrEqual(3);\n  expect(violations).toHaveLength(0);\n\n  \u002F\u002F Verify the data is complete (not lazy-loaded)\n  for (const user of users) {\n    expect(user.posts).toBeDefined();\n    expect(Array.isArray(user.posts)).toBe(true);\n  }\n});\n\ntest('ANTI-PATTERN: lazy loading causes N+1', async () => {\n  queryCounter.start();\n\n  \u002F\u002F This is the N+1 anti-pattern -- DO NOT DO THIS in production\n  const users = await prisma.user.findMany(); \u002F\u002F Query 1\n  for (const user of users) {\n    \u002F\u002F Each iteration issues a new query -- Query 2..N+1\n    const posts = await prisma.post.findMany({\n      where: { authorId: user.id },\n    });\n    \u002F\u002F Process posts...\n  }\n\n  const logs = queryCounter.stop();\n  const violations = queryCounter.detectNPlusOne();\n\n  \u002F\u002F This will issue 1 + N queries (51 queries for 50 users)\n  expect(logs.length).toBeGreaterThan(50);\n  expect(violations.length).toBeGreaterThan(0);\n});\n```\n\n### SQLAlchemy N+1 Detection (Python)\n\n```python\nimport pytest\nfrom sqlalchemy import event, text\nfrom sqlalchemy.orm import Session\nfrom app.models import User, Post\nfrom app.database import engine, SessionLocal\n\n\nclass QueryCounter:\n    def __init__(self):\n        self.queries = []\n        self._listening = False\n\n    def start(self, engine):\n        self.queries = []\n        self._listening = True\n        event.listen(engine, \"before_cursor_execute\", self._record)\n\n    def stop(self, engine):\n        self._listening = False\n        event.remove(engine, \"before_cursor_execute\", self._record)\n        return self.queries\n\n    def _record(self, conn, cursor, statement, parameters, context, executemany):\n        if self._listening:\n            self.queries.append({\n                \"sql\": statement,\n                \"params\": parameters,\n            })\n\n    @property\n    def count(self):\n        return len(self.queries)\n\n    def detect_n_plus_one(self, threshold=5):\n        from collections import Counter\n        import re\n\n        normalized = []\n        for q in self.queries:\n            sql = re.sub(r\"= '[^']*'\", \"= '?'\", q[\"sql\"])\n            sql = re.sub(r\"= \\d+\", \"= ?\", sql)\n            normalized.append(sql)\n\n        counts = Counter(normalized)\n        return {sql: count for sql, count in counts.items() if count >= threshold}\n\n\n@pytest.fixture\ndef query_counter():\n    counter = QueryCounter()\n    counter.start(engine)\n    yield counter\n    counter.stop(engine)\n\n\ndef test_get_users_with_posts_no_n_plus_one(query_counter, db_session: Session):\n    \"\"\"Verify eager loading prevents N+1 queries.\"\"\"\n    from sqlalchemy.orm import joinedload\n\n    # Correct: eager load with joinedload\n    users = (\n        db_session.query(User)\n        .options(joinedload(User.posts))\n        .all()\n    )\n\n    assert query_counter.count \u003C= 2  # 1 JOIN query or 2 separate queries\n    violations = query_counter.detect_n_plus_one()\n    assert len(violations) == 0\n\n    # Verify data is loaded\n    for user in users:\n        assert hasattr(user, \"posts\")\n\n\ndef test_lazy_loading_causes_n_plus_one(query_counter, db_session: Session):\n    \"\"\"Demonstrate the N+1 anti-pattern with lazy loading.\"\"\"\n    # Anti-pattern: no eager loading specified\n    users = db_session.query(User).all()  # Query 1\n\n    for user in users:\n        _ = user.posts  # Each access triggers a query\n\n    violations = query_counter.detect_n_plus_one()\n    assert len(violations) > 0, \"Expected N+1 pattern not detected\"\n```\n\n### Hibernate N+1 Detection (Java)\n\n```java\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport net.ttddyy.dsproxy.QueryCountHolder;\nimport static org.assertj.core.api.Assertions.assertThat;\n\n@SpringBootTest\nclass NPlusOneDetectionTest {\n\n    @Autowired\n    private UserRepository userRepository;\n\n    @Test\n    void getUsersWithPosts_shouldNotCauseNPlusOne() {\n        QueryCountHolder.clear();\n\n        \u002F\u002F Uses @EntityGraph or JOIN FETCH\n        var users = userRepository.findAllWithPosts();\n\n        var queryCount = QueryCountHolder.getGrandTotal();\n\n        \u002F\u002F Should be at most 1-2 queries with proper fetch strategy\n        assertThat(queryCount.getSelect()).isLessThanOrEqualTo(2);\n\n        \u002F\u002F Verify posts are loaded\n        for (var user : users) {\n            assertThat(user.getPosts()).isNotNull();\n            assertThat(\n                org.hibernate.Hibernate.isInitialized(user.getPosts())\n            ).isTrue();\n        }\n    }\n}\n```\n\n## Automated Threshold Testing\n\n### Query Budget Definitions\n\n```typescript\n\u002F\u002F config\u002Fquery-budgets.ts\n\nexport interface QueryBudget {\n  endpoint: string;\n  method: string;\n  maxQueries: number;\n  maxDurationMs: number;\n  description: string;\n}\n\nexport const QUERY_BUDGETS: QueryBudget[] = [\n  {\n    endpoint: '\u002Fapi\u002Fusers',\n    method: 'GET',\n    maxQueries: 3,\n    maxDurationMs: 100,\n    description: 'List users with counts',\n  },\n  {\n    endpoint: '\u002Fapi\u002Fusers\u002F:id',\n    method: 'GET',\n    maxQueries: 4,\n    maxDurationMs: 50,\n    description: 'Single user with relations',\n  },\n  {\n    endpoint: '\u002Fapi\u002Fposts',\n    method: 'GET',\n    maxQueries: 5,\n    maxDurationMs: 150,\n    description: 'List posts with author and tags',\n  },\n  {\n    endpoint: '\u002Fapi\u002Fdashboard',\n    method: 'GET',\n    maxQueries: 8,\n    maxDurationMs: 200,\n    description: 'Dashboard with aggregations',\n  },\n  {\n    endpoint: '\u002Fapi\u002Ffeed',\n    method: 'GET',\n    maxQueries: 6,\n    maxDurationMs: 200,\n    description: 'Activity feed with nested data',\n  },\n];\n```\n\n### Budget Enforcement Tests\n\n```typescript\nimport { test, expect, describe, beforeEach, afterEach } from 'vitest';\nimport { queryCounter } from '..\u002Fhelpers\u002Fquery-counter';\nimport { QUERY_BUDGETS } from '..\u002F..\u002Fconfig\u002Fquery-budgets';\nimport request from 'supertest';\nimport { app } from '..\u002F..\u002Fsrc\u002Fapp';\n\ndescribe('Query Budget Enforcement', () => {\n  for (const budget of QUERY_BUDGETS) {\n    test(`${budget.method} ${budget.endpoint} should stay within query budget (max: ${budget.maxQueries})`, async () => {\n      queryCounter.start();\n\n      const resolvedEndpoint = budget.endpoint.replace(\n        \u002F:id\u002Fg,\n        '1'\n      );\n\n      const response = await request(app)\n        [budget.method.toLowerCase() as 'get' | 'post'](resolvedEndpoint)\n        .set('Accept', 'application\u002Fjson');\n\n      const logs = queryCounter.stop();\n\n      expect(response.status).toBeLessThan(500);\n\n      \u002F\u002F Enforce query count budget\n      expect(\n        logs.length,\n        `${budget.method} ${budget.endpoint}: ${logs.length} queries exceeds budget of ${budget.maxQueries}. ` +\n        `Queries:\\n${logs.map((q) => `  - ${q.sql.substring(0, 120)}`).join('\\n')}`\n      ).toBeLessThanOrEqual(budget.maxQueries);\n\n      \u002F\u002F Enforce duration budget\n      const totalDuration = logs.reduce((sum, q) => sum + q.duration, 0);\n      expect(\n        totalDuration,\n        `${budget.method} ${budget.endpoint}: ${totalDuration}ms exceeds duration budget of ${budget.maxDurationMs}ms`\n      ).toBeLessThanOrEqual(budget.maxDurationMs);\n\n      \u002F\u002F Check for N+1 patterns\n      const violations = queryCounter.detectNPlusOne(3);\n      expect(\n        violations,\n        `N+1 detected in ${budget.method} ${budget.endpoint}:\\n${violations.join('\\n')}`\n      ).toHaveLength(0);\n    });\n  }\n});\n```\n\n## DataLoader Pattern for GraphQL\n\nGraphQL APIs are especially vulnerable to N+1 problems because each resolver fetches data independently. The DataLoader pattern batches and deduplicates these fetches.\n\n```typescript\nimport DataLoader from 'dataloader';\nimport { prisma } from '.\u002Fprisma';\n\n\u002F\u002F DataLoader batches individual post lookups into a single query\nexport function createPostLoader() {\n  return new DataLoader\u003Cstring, Post[]>(async (userIds) => {\n    \u002F\u002F Single query: SELECT * FROM posts WHERE authorId IN (...)\n    const posts = await prisma.post.findMany({\n      where: {\n        authorId: { in: [...userIds] },\n      },\n    });\n\n    \u002F\u002F Map posts back to their respective user IDs\n    const postsByUserId = new Map\u003Cstring, Post[]>();\n    for (const post of posts) {\n      const existing = postsByUserId.get(post.authorId) || [];\n      existing.push(post);\n      postsByUserId.set(post.authorId, existing);\n    }\n\n    return userIds.map((id) => postsByUserId.get(id) || []);\n  });\n}\n\n\u002F\u002F Test that DataLoader properly batches\nimport { test, expect } from 'vitest';\n\ntest('DataLoader should batch user post lookups', async () => {\n  queryCounter.start();\n\n  const postLoader = createPostLoader();\n\n  \u002F\u002F These 50 calls should be batched into 1 query\n  const userIds = Array.from({ length: 50 }, (_, i) => `user-${i}`);\n  const results = await Promise.all(\n    userIds.map((id) => postLoader.load(id))\n  );\n\n  const logs = queryCounter.stop();\n\n  \u002F\u002F DataLoader should batch all 50 lookups into 1 query\n  expect(logs.length).toBe(1);\n  expect(logs[0].sql).toContain('IN');\n  expect(results).toHaveLength(50);\n});\n\ntest('DataLoader should deduplicate identical requests', async () => {\n  queryCounter.start();\n\n  const postLoader = createPostLoader();\n\n  \u002F\u002F Same user ID requested 10 times\n  const sameId = 'user-1';\n  const results = await Promise.all(\n    Array.from({ length: 10 }, () => postLoader.load(sameId))\n  );\n\n  const logs = queryCounter.stop();\n\n  \u002F\u002F Should still be 1 query despite 10 requests\n  expect(logs.length).toBe(1);\n  \u002F\u002F All results should be the same reference\n  const firstResult = results[0];\n  results.forEach((r) => expect(r).toBe(firstResult));\n});\n```\n\n## Request-Level Query Budgets\n\n### Middleware That Fails Requests Exceeding Budget\n\n```typescript\nimport { Request, Response, NextFunction } from 'express';\nimport { queryCounter } from '.\u002Fquery-counter';\n\ninterface BudgetConfig {\n  [route: string]: {\n    maxQueries: number;\n    action: 'warn' | 'block' | 'log';\n  };\n}\n\nconst budgetConfig: BudgetConfig = {\n  'GET \u002Fapi\u002Fusers': { maxQueries: 3, action: 'block' },\n  'GET \u002Fapi\u002Fposts': { maxQueries: 5, action: 'block' },\n  'GET \u002Fapi\u002Fdashboard': { maxQueries: 10, action: 'warn' },\n  '*': { maxQueries: 20, action: 'log' },\n};\n\nexport function queryBudgetMiddleware() {\n  return (req: Request, res: Response, next: NextFunction) => {\n    queryCounter.start();\n\n    const originalEnd = res.end.bind(res);\n    res.end = function (...args: Parameters\u003CResponse['end']>) {\n      const logs = queryCounter.stop();\n      const routeKey = `${req.method} ${req.route?.path || req.path}`;\n      const config =\n        budgetConfig[routeKey] || budgetConfig['*'];\n\n      if (logs.length > config.maxQueries) {\n        const message = `Query budget exceeded: ${routeKey} used ${logs.length}\u002F${config.maxQueries} queries`;\n\n        switch (config.action) {\n          case 'block':\n            if (!res.headersSent) {\n              res.status(503).json({\n                error: 'Service temporarily unavailable',\n                reason: process.env.NODE_ENV === 'development' ? message : undefined,\n              });\n              return res;\n            }\n            break;\n          case 'warn':\n            console.warn(`[QUERY BUDGET WARNING] ${message}`);\n            break;\n          case 'log':\n            console.log(`[QUERY BUDGET] ${message}`);\n            break;\n        }\n      }\n\n      return originalEnd(...args);\n    } as Response['end'];\n\n    next();\n  };\n}\n```\n\n## CI Integration for Query Count Regression\n\n### GitHub Actions Workflow Integration\n\n```typescript\n\u002F\u002F tests\u002Fperformance\u002Fquery-regression.spec.ts\nimport { test, expect, describe } from 'vitest';\nimport { queryCounter } from '..\u002Fhelpers\u002Fquery-counter';\nimport { readFileSync, writeFileSync, existsSync } from 'fs';\nimport { join } from 'path';\n\nconst BASELINE_PATH = join(__dirname, '..\u002F..\u002F.query-baseline.json');\n\ninterface QueryBaseline {\n  [endpoint: string]: {\n    queryCount: number;\n    measuredAt: string;\n  };\n}\n\nfunction loadBaseline(): QueryBaseline {\n  if (existsSync(BASELINE_PATH)) {\n    return JSON.parse(readFileSync(BASELINE_PATH, 'utf-8'));\n  }\n  return {};\n}\n\nfunction saveBaseline(baseline: QueryBaseline): void {\n  writeFileSync(BASELINE_PATH, JSON.stringify(baseline, null, 2));\n}\n\ndescribe('Query Count Regression Detection', () => {\n  const endpoints = [\n    { method: 'GET', path: '\u002Fapi\u002Fusers', handler: getUsersHandler },\n    { method: 'GET', path: '\u002Fapi\u002Fposts', handler: getPostsHandler },\n    { method: 'GET', path: '\u002Fapi\u002Fdashboard', handler: getDashboardHandler },\n  ];\n\n  for (const endpoint of endpoints) {\n    test(`${endpoint.method} ${endpoint.path} should not regress in query count`, async () => {\n      const baseline = loadBaseline();\n      const key = `${endpoint.method} ${endpoint.path}`;\n\n      queryCounter.start();\n      await endpoint.handler();\n      const logs = queryCounter.stop();\n\n      const currentCount = logs.length;\n\n      if (baseline[key]) {\n        const previousCount = baseline[key].queryCount;\n        const regressionThreshold = Math.ceil(previousCount * 1.1); \u002F\u002F 10% tolerance\n\n        expect(\n          currentCount,\n          `Query regression detected for ${key}: was ${previousCount}, now ${currentCount}`\n        ).toBeLessThanOrEqual(regressionThreshold);\n      }\n\n      \u002F\u002F Update baseline if running in update mode\n      if (process.env.UPDATE_QUERY_BASELINE === 'true') {\n        baseline[key] = {\n          queryCount: currentCount,\n          measuredAt: new Date().toISOString(),\n        };\n        saveBaseline(baseline);\n      }\n    });\n  }\n});\n```\n\n### Eager vs Lazy Loading Audit\n\n```typescript\nimport { test, expect, describe } from 'vitest';\nimport { PrismaClient } from '@prisma\u002Fclient';\n\ndescribe('ORM Loading Strategy Audit', () => {\n  test('all list endpoints should use explicit includes', async () => {\n    \u002F\u002F Parse the route handlers and check for include clauses\n    const routeFiles = [\n      'src\u002Froutes\u002Fusers.ts',\n      'src\u002Froutes\u002Fposts.ts',\n      'src\u002Froutes\u002Fcomments.ts',\n    ];\n\n    for (const file of routeFiles) {\n      const content = require('fs').readFileSync(file, 'utf-8');\n\n      \u002F\u002F Check for findMany without include (potential N+1)\n      const findManyWithoutInclude = \u002F\\.findMany\\(\\s*\\)\u002Fg;\n      const matches = content.match(findManyWithoutInclude);\n\n      if (matches) {\n        console.warn(\n          `${file}: Found ${matches.length} findMany() calls without includes`\n        );\n      }\n\n      expect(\n        matches,\n        `${file} has findMany() without explicit include — potential N+1`\n      ).toBeNull();\n    }\n  });\n\n  test('related data access should use include, not separate queries', async () => {\n    \u002F\u002F Verify that getting a user with posts uses a single include\n    queryCounter.start();\n\n    const user = await prisma.user.findUnique({\n      where: { id: 'test-user-1' },\n      include: {\n        posts: true,\n        comments: true,\n        profile: true,\n      },\n    });\n\n    const logs = queryCounter.stop();\n\n    \u002F\u002F findUnique with include should generate at most 4 queries\n    \u002F\u002F (1 per relation + 1 for the main entity, or fewer with JOINs)\n    expect(logs.length).toBeLessThanOrEqual(4);\n  });\n});\n```\n\n## Configuration\n\n### Query Counter Configuration\n\n```typescript\n\u002F\u002F config\u002Fthresholds.ts\n\nexport const QUERY_THRESHOLDS = {\n  \u002F\u002F Maximum queries per request before triggering N+1 detection\n  nPlusOneDetectionThreshold: 5,\n\n  \u002F\u002F Maximum total queries per request\n  maxQueriesPerRequest: 20,\n\n  \u002F\u002F Maximum total query duration per request (ms)\n  maxQueryDurationMs: 500,\n\n  \u002F\u002F Percentage increase allowed before flagging as regression\n  regressionTolerancePercent: 10,\n\n  \u002F\u002F Minimum data volume for meaningful N+1 testing\n  minimumTestDataRows: 50,\n\n  \u002F\u002F Enable detailed query logging in CI\n  verboseLogging: process.env.CI === 'true',\n\n  \u002F\u002F File path for query count baselines\n  baselinePath: '.query-baseline.json',\n};\n```\n\n## Best Practices\n\n1. **Always use `include` or `select` with list queries** -- When fetching a list of records that will need related data, declare the relations upfront in the query. Never iterate over results and issue individual relation lookups.\n\n2. **Seed tests with at least 50 parent records** -- N+1 problems are proportional to data size. With 2 records, 3 queries vs 2 queries is invisible. With 50 records, 51 queries vs 2 queries is obvious.\n\n3. **Make query budgets part of the API contract** -- Document the expected query count for each endpoint. When a PR changes an endpoint, reviewers should verify that the query budget is still reasonable.\n\n4. **Use DataLoader for GraphQL resolvers** -- Every resolver that accesses related data must use a DataLoader instance. Create a new DataLoader per request to avoid cross-request caching issues.\n\n5. **Profile production queries periodically** -- N+1 problems can hide behind caches in development. Use production query profiling tools (pg_stat_statements, slow query logs) to identify patterns that only emerge at production data volumes.\n\n6. **Prefer batch operations over loops** -- Replace `for` loops that issue individual `INSERT`, `UPDATE`, or `DELETE` statements with batch operations (`createMany`, `updateMany`, bulk operations).\n\n7. **Test with pagination** -- N+1 detection must work correctly with paginated queries. Ensure that eager loading applies to the paginated subset, not to all records.\n\n8. **Instrument integration tests, not just unit tests** -- Unit tests with mocked databases cannot detect N+1 patterns. Use integration tests with a real database (or in-memory database like SQLite) for query counting.\n\n9. **Log the full query with parameters** -- When a query budget violation is detected, log the complete SQL with bound parameters. This makes it immediately clear which query is being repeated.\n\n10. **Use connection pooling metrics** -- Monitor connection pool checkout counts per request. An N+1 pattern will show high pool checkout rates even if individual queries are fast.\n\n11. **Fail CI on query count regressions** -- Make query budget tests non-optional in CI. A query count regression that is merged today becomes a production performance incident tomorrow.\n\n12. **Audit ORM lazy-loading configuration** -- Review your ORM's default loading strategy. In Prisma, relations are not loaded by default. In Hibernate, `@OneToMany` defaults to `FetchType.LAZY`. Know the defaults and override them explicitly.\n\n## Anti-Patterns to Avoid\n\n1. **Iterating and querying in a loop** -- The classic N+1 anti-pattern: `users.forEach(async (user) => { const posts = await getPosts(user.id); })`. Always use `include`, `JOIN`, or `IN` clauses instead.\n\n2. **Relying on ORM lazy loading in production** -- Lazy loading is convenient in development but catastrophic in production. Disable lazy loading or configure your ORM to warn when it triggers implicit queries.\n\n3. **Caching to hide N+1 problems** -- Adding a Redis cache on top of an N+1 endpoint masks the problem but does not fix it. Cache misses will still trigger the full N+1 pattern, and cold starts become extremely slow.\n\n4. **Testing with empty or minimal data** -- Testing with 1-2 records will never reveal N+1 issues. The query count will look reasonable even with the most pathological access patterns. Always test with realistic data volumes.\n\n5. **Using `SELECT *` when only IDs are needed** -- Fetching full records when you only need identifiers wastes bandwidth and memory. Use `select` clauses to fetch only the columns you need, and use `IN` queries for batch lookups.\n\n6. **Ignoring GraphQL query depth** -- Deeply nested GraphQL queries can create cascading N+1 problems at each resolver level. Implement query depth limiting and require DataLoader at every level.\n\n7. **Manual SQL string construction in loops** -- Building `WHERE id = ?` queries in a loop instead of `WHERE id IN (?, ?, ?)` is an N+1 pattern that ORMs would normally prevent. If writing raw SQL, always use batch operations.\n\n## Debugging Tips\n\n1. **Enable query logging at the driver level** -- Set `log: ['query']` in Prisma, `echo=True` in SQLAlchemy, or `hibernate.show_sql=true` in Hibernate. Count the queries manually for a single request to establish a baseline.\n\n2. **Use `EXPLAIN ANALYZE` on repeated queries** -- If you see the same query pattern repeated many times, run `EXPLAIN ANALYZE` to understand its execution plan. A query that does a full table scan 50 times per request is doubly problematic.\n\n3. **Check for missing indexes on foreign keys** -- N+1 queries often hit foreign key columns. Ensure that all foreign key columns have indexes. Without indexes, each individual query in the N+1 pattern does a sequential scan.\n\n4. **Watch for N+1 in serialization** -- Some frameworks trigger lazy loading during JSON serialization when accessing relation properties. The N+1 happens not in the controller but in the serializer.\n\n5. **Profile with a database proxy** -- Tools like pgBouncer, datasource-proxy (Java), or prisma-query-log can intercept all queries without modifying application code. This gives complete visibility into query patterns.\n\n6. **Count queries per request in development** -- Add a simple middleware that logs the total query count for every request during development. Make this visible in the terminal output so developers notice regressions immediately.\n\n7. **Examine the SQL pattern, not just the count** -- A high query count is not always N+1. Look for the signature pattern: one query followed by N identical queries with different parameter values. This distinguishes N+1 from legitimate multi-query operations.\n\n8. **Test GraphQL resolvers in isolation** -- When debugging GraphQL N+1 issues, test each resolver independently with the DataLoader context to verify that batching is working. A misconfigured DataLoader that creates a new instance per resolve call will not batch.\n\n9. **Check for N+1 in database triggers** -- If your database has triggers that run additional queries on INSERT or UPDATE, these can create N+1-like behavior that is invisible at the application level. Review trigger definitions when query counts exceed expectations.\n\n10. **Use flamegraph-style query visualization** -- Tools that show queries on a timeline (like Prisma Studio or Django Debug Toolbar) make it visually obvious when 50 identical queries fire in sequence. The waterfall pattern of N+1 is unmistakable in a timeline view.\n",{"name":5,"tags":24,"agents":32,"author":45,"domains":46,"license":15,"version":48,"languages":49,"frameworks":54,"description":7,"testingTypes":55},[25,26,27,28,29,30,31],"n-plus-one","database-performance","query-optimization","orm","eager-loading","sql-profiling","database-testing",[33,34,35,36,37,38,39,40,41,42,43,44],"claude-code","cursor","github-copilot","windsurf","codex","aider","continue","cline","zed","bolt","gemini-cli","amp","Pramod",[47],"api","1.0.0",[50,51,52,53],"typescript","javascript","python","java",[],[56,57],"performance","database","main","eac438ea9216a7cb8a570cab803eb01eeafc6793","skills\u002Fqa\u002Fn-plus-one-query-detector","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m","https:\u002F\u002Fid-preview--d5bef06d-6c9e-4563-a3d4-a855b9d61610.lovable.app\u002F","Eu sou Antonio B. B. Ndombe \r\nEu sou um Pesquisador e desenvolvedor de sistema autonomia cognitivos, fundador de sistemas ODCs ( organismos digital conscientes)","2026-11-04 06:53:39",{"source":8,"skillName":5,"commands":67,"prompt":77,"zipAvailable":78},[68,71,74],{"tool":69,"command":70},"npx","npx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"N+1 Query Detector\"",{"tool":72,"command":73},"bunx","bunx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"N+1 Query Detector\"",{"tool":75,"command":76},"pnpm","pnpm dlx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"N+1 Query Detector\"","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fn-plus-one-query-detector\u002FSKILL.md",true,[],[81,89,96,103,110,117],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7DASC6FSCJP49JZBSK0NY1Z","nemoclaw-user-reference","Describes the NemoClaw integration layer and blueprint architecture and how they orchestrate compatible agent sandboxes. Use when looking up architecture, agent integration, plugin structure, or blueprint design. Trigger keywords - nemoclaw architecture, nemoclaw agent architecture, nemoclaw plugin blueprint structure, nemoclaw vs openshell, which cli, nemoclaw cli, openshell cli, sandbox commands, nemoclaw cli commands, nemoclaw command reference, nemoclaw network policy, sandbox egress control operator approval, nemoclaw troubleshooting, nemoclaw debug sandbox issues.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-reference\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":19},"01M7DAS5S79VK33XFGVAM2TFWF","nemoclaw-user-overview","Explains how OpenClaw, OpenShell, and NemoClaw form the ecosystem, NemoClaw's position in the stack, what NemoClaw adds beyond the community sandbox, and when to prefer NemoClaw versus integrating OpenShell and OpenClaw directly. Use when users ask about the relationship between OpenClaw, OpenShell, and NemoClaw, or when to use NemoClaw versus OpenShell. Trigger keywords - nemoclaw ecosystem, openclaw openshell, nemoclaw vs openshell, sandboxed openclaw, how nemoclaw works, nemoclaw sandbox lifecycle blueprint, nemoclaw overview, openclaw always-on assistants, nvidia openshell, nvidia nemotron, nemoclaw release notes, nemoclaw changelog.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-overview\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":19},"01M7DAS0PQEMET5MNGZ1ABSZVS","nemoclaw-user-monitor-sandbox","Inspects sandbox health, traces agent behavior, and diagnoses problems. Use when monitoring a running sandbox, debugging agent issues, or checking sandbox logs. Trigger keywords - monitor nemoclaw sandbox, debug nemoclaw agent issues.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-monitor-sandbox\u002FSKILL.md",[],[],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":19},"01M7DARQYGF7E9A69VH6S3CGN9","nemoclaw-user-manage-sandboxes","Explains operational tasks after the quickstart: listing sandboxes, status and health checks, logs, diagnostics, port forwards, multiple sandboxes, credential reset, rebuilds, network presets, upgrades, and uninstall. Trigger keywords - manage nemoclaw sandboxes, nemoclaw status, nemoclaw list, nemoclaw dashboard port, nemoclaw rebuild, nemoclaw upgrade sandboxes, nemoclaw uninstall, sandbox mutability, sandbox runtime configuration, sandbox rebuild, nemoclaw backup, nemoclaw restore, workspace backup, openshell sandbox download upload, nemoclaw messaging channels, nemoclaw telegram, nemoclaw discord, nemoclaw slack, nemoclaw wechat, nemoclaw whatsapp, openshell channel messaging, nemoclaw workspace files, soul.md, user.md, identity.md, agents.md, sandbox persistence.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-manage-sandboxes\u002FSKILL.md",[],[],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":19},"01M7DARH8BRTG51TRCAB7YWDJ4","nemoclaw-user-manage-policy","Adds, removes, or modifies allowed endpoints in the sandbox policy. Use when customizing network policy, changing egress rules, or configuring sandbox endpoint access. Trigger keywords - customize nemoclaw network policy, sandbox egress policy configuration, nemoclaw integration policy examples, post-install policy setup, openshell approval workflow, policy preset, nemoclaw approve network requests, sandbox egress approval tui.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-manage-policy\u002FSKILL.md",[],[],{"skillNo":118,"name":119,"nameZh":6,"description":120,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":121,"categories":122,"keywords":123,"publishedAt":19},"01M7DARAT62M2VR37590VCZ5NS","nemoclaw-user-get-started","Installs NemoClaw, launches a sandbox, and runs the first agent prompt. Use when onboarding, installing, or launching a NemoClaw sandbox for the first time. Trigger keywords - nemoclaw quickstart, install nemoclaw openclaw sandbox, nemohermes quickstart, hermes agent nemoclaw, run hermes openshell sandbox, nemoclaw prerequisites, nemoclaw supported platforms, nemoclaw hardware software, nemoclaw windows wsl2 setup, nemoclaw install windows docker desktop.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-get-started\u002FSKILL.md",[],[]]