{"id":20750,"plugin_id":"plugins_6aa698dc64588191b48664000f8522de","kind":"skill","collection_source":null,"comparison_source":null,"observed_at":"2026-09-30T23:16:27.595Z","digest":"957fbe3a96df996e426dc2a6bb8f5f9f74047a885f236b7ccb8ae3d3b555c2ce","against":null,"payload":{"name":"sql-performance-advisor","description":"Use when investigating SQL Server or PostgreSQL performance and guiding a case from scoped diagnosis to measured, business-correct verification.","included_files":[],"skill_md_contents":"---\nname: sql-performance-advisor\ndescription: Use when investigating SQL Server or PostgreSQL performance and guiding a case from scoped diagnosis to measured, business-correct verification.\n---\n\n# SQL Performance Advisor\n\nFor explicit tuning acceptance limits, supply `budgets` with `caseId` and\n`maxCandidateMedianMs` and/or `maxRegressionMs`. Report every unbudgeted case.\nTreat exceeded limits as a rejected candidate and context drift as inconclusive;\ndo not label observed median budgets as production SLO or percentile guarantees.\n\nFor ERP invariants, add lab cases with `assertion: \"zero_violations\"` using reviewed\ncontrol-query templates. Each must return one `violations` integer count. Treat\nnonzero or malformed evidence as rejection even when both query results match.\nState exactly which business rule and database principal were tested; never claim\nuniversal ERP or cross-role correctness from these checks.\n\nUse `run_tuning_lab` to combine before/after live context fingerprints with the\nadministratively qualified lab rewrite replay. Require all replay scope, registry,\ntemplate and edge-case coverage prerequisites. Reject result differences and treat\ncontext drift as inconclusive. Median client duration is not server CPU or a proven\nproduction improvement. Report the returned missing evidence before proposing a fix.\n\nFor SQL Server TempDB investigation use `collect_tempdb_health` with explicit\n`engine: \"sqlserver\", database: \"tempdb\"`. Explain that TempDB is shared across\napplication databases. Review file settings, data/log counters and observed page\nwaits without inferring disk headroom, allocation contention or workload ownership.\nPreserve unavailable/truncated sections. Never automatically shrink or resize files.\n\nFor PostgreSQL replication or WAL-retention investigations, use\n`collect_replication_health` with explicit `engine: \"postgres\"` and `database`.\nReport cluster-wide physical slots/archive statistics separately from database-local\nlogical slots. Preserve unavailable sections and decimal-string LSN distances;\nnever equate them with disk usage or replica delay. Findings request investigation,\nnot permission to drop slots or remove WAL. Subscriber health remains unverified.\n\nFor ERP/CRM vendor context, first follow `../erp-crm-advisor/SKILL.md` and select\nthe exact product profile. Do not infer that a vendor-managed SQL endpoint permits\nindex changes or that faster SQL preserves application business semantics.\n\nResolve the plugin root two directories above this SKILL.md and use its absolute\n`runtime/runTool.js` path. Check Node.js and installed dependencies first; use\n`npm ci` in that plugin root when dependencies are missing. Do not request an LLM\nAPI key: Codex supplies the reasoning. Database credentials come from the user's\nprocess environment or an explicitly selected private environment file.\n\nFor real database requests, require live evidence with\n`CODEXDB_REQUIRE_LIVE_CONNECTION=true`. Never present mock samples, heuristic\nscores, generated runbooks, or estimated improvements as measured facts. Report\nconnection failures and missing evidence explicitly. Start with read-only analysis;\ndo not execute generated writes without the user's authorization.\n\nUse JSON via stdin (`runTool.js advisor_workflow -`) for structured inputs.\nKeep persistent state outside the plugin cache using `CODEXDB_STATE_DIR`.\n\n## Standard workflow\n\nUse `collect_blocking_frame` for a real PostgreSQL frame with explicit `engine`,\n`systemId`, `database`, and optional `connectionProfile`. Pass the returned `frame`\ninto `blocking_timeline` along with earlier frames from the same scope. The tool\ncaptures session starts and pg_blocking_pids, not SQL text or usernames. Hidden\nidentities and excessive session counts fail closed. PID zero remains an unresolved\nprepared-transaction blocker. This is on-demand collection; do not start frequent\npolling or imply unattended monitoring. SQL Server/MySQL/MariaDB frame collection\nis not supported by this command yet.\n\nFor sampled blocking history, use `blocking_timeline` with `engine`, `systemId`,\n`database`, and 1..120 `frames` in ascending capture order. Each frame repeats the\nscope and contains canonical UTC `capturedAt`, `evidenceRef`, and `sessions`.\nA session has string `sessionId`, canonical UTC `startedAt`, and `blockedBy` as\nan array of session IDs in the same frame (including unresolved IDs if the blocker\nwas not captured). Start time distinguishes reused IDs. Explain edges, observed\nroot blockers, unresolved blockers, and cycles. Never infer uninterrupted blocking\nduration from samples or call a cycle a proven deadlock; obtain the native deadlock\nartifact separately. Do not execute KILL or cancel sessions from these findings.\n\nUse `operational_window_compare` for supplied cumulative counters. Require top-level\n`engine`, `systemId`, `database` and `before`/`after` windows repeating that scope.\nEach window has canonical UTC `start`/`end`, `metrics`, and `queries`. A metric is\n`{metric,unit,start:{value,counterEpoch},end:{value,counterEpoch}}`; values must be\nnonnegative safe integers. Queries are `{queryId,metrics}`. Supported metrics:\nexecution_count/logical_reads/physical_reads/rows/errors in count; elapsed_time/\ncpu_time/lock_wait_time in ms; bytes_read/bytes_written in bytes. Windows must have\nequal positive duration, must not overlap, and counters must share an epoch.\nResets, decreasing counters, or missing queries mean insufficient evidence.\nOptional `slo` entries contain metric, unit, aggregation (`delta` or `rate`),\noperator (`lte` or `gte`), threshold, and optional queryId. Rate units use `/s`.\nReport supplied-counter differences, never inferred percentiles, causal impact,\nbackground monitoring, or CPU derived from elapsed time.\n\nUse `consulting_project` to maintain a local consulting case. Require explicit\n`tenantId` and `projectId`. Actions are `create`, `get`, `update`, and `export`.\nCreate/update `data` supports `goals`, `systems`, `findings`, `decisions`, and\n`evidence`, each a list of `{id,text,evidenceRefs?}`. Goals and systems are required;\nevidence references must resolve to IDs in the evidence list. Updates require the\nlast `expectedRevision`. Export with `format: json` or `markdown`; the result\ncontains the report and its hash. Keep customer secrets out of all project text.\nAcceptance is recorded as supplied, not authenticated: accepted/rejected requires\nreviewer, recordedAt, note, and evidenceRefs. Content updates invalidate acceptance\nunless a new explicit statement accompanies them. Project namespaces are not\ntenant authorization; use OS/process isolation for different customers.\n\nFor operating evidence, run `collect_dba_maintenance` with explicit SQL Server or\nPostgreSQL `engine`, `database`, and optional `connectionProfile`. Report section\nstatus and scope. PostgreSQL tuple counts are estimates, not bloat measurements;\nSQL Server modification counters do not define a universal maintenance threshold.\nSQL Server backup history is not recovery-chain or restore proof. PostgreSQL\nrequires external backup-tool evidence. Do not infer RPO/RTO compliance or perform\nmaintenance writes from these results.\n\nIf legacy audit import prevents any operation, use `audit_state_recovery` with\n`action: inspect` first. It reads the configured state only and returns a source\nfingerprint. `start_new_epoch` requires the exact `expectedFingerprint`,\n`acknowledgeHistoricalGaps: true`, and a bounded `reason`. Explain the historical\ngaps and obtain the user's authorization to resume with a separate epoch before\ndoing so. Original files and exact source bytes are preserved locally. The\narchived bytes may contain historical sensitive content; protect the state folder.\nThis is not repair of the old chain. Never reinterpret\n`current_epoch_verified_legacy_unverified` as globally verified audit history.\n\nFor a consolidated first review, run `database_engineer_brief` with explicit\n`engine`, `database`, optional `connectionProfile`, and optionally a SELECT `sql`.\nExplain the report in terms of observed facts, unresolved questions, and the next\nsafe measurement. Cite the relevant section and its capture time for each finding.\nThe report requires live discovery; downstream collector failures remain visible\nwithout being replaced by mock data. It reuses one discovery snapshot for native\nindex reviews, limits each list to 20 with explicit totals, and returns no health\nscore or write approval. Retrieve the named detail tool when a section is truncated.\nSQL Server/PostgreSQL have catalog/security sections; native index review and the\noptional plan section currently target SQLite/MySQL/MariaDB. Unsupported sections\nare not clean bills of health. Never claim uniqueness against competitors or\nproduction readiness from this report alone.\n\nUse `duplicate_index_review` with a SQLite/MySQL/MariaDB discovery `result` as\n`snapshot` to find groups with identical observed full-column index keys. Key\norder, sort direction, and SQLite collation are compared. Unique, partial,\nexpression, prefix, and incompletely described indexes are excluded. Treat each\ngroup as a review candidate only. Check foreign-key dependencies, application\nhints, visibility/storage options, and representative usage before proposing any\nretirement. Never turn these findings directly into DROP INDEX; the tool provides\nneither executable DDL nor fabricated storage/write-cost savings.\n\nUse `compare_native_plans` with `before` and `after` results from\n`native_query_plan` and optional `maxAgeMinutes` (default 60, maximum 10080).\nThe command requires identical engine, database, profile label, and exact SQL\nhash, and reports positional native-plan differences plus evidence age gaps.\nDo not call `plan_changed` a regression or improvement: obtain workload timing\nand business-correctness evidence separately. The SQL fingerprint is not a secret\nredaction mechanism; do not put sensitive literals into queries or exported plans.\nProfiles and supplied timestamps are not independent server-identity attestations.\n\nFor SQLite/MySQL/MariaDB foreign-key indexing, pass the discovery `result` as\n`snapshot` to `foreign_key_index_review`. It compares child-key columns with\nleading full-column index positions, preserving order and schema/table identity.\nPartial, expression, prefix, or incompletely described indexes are skipped and\nreported. `leading_columns_observed` is metadata evidence, not proof of actual\noptimizer use. `no_matching_index_observed` is a review candidate, not permission\nto create an index. Preserve coverage gaps; do not claim missing indexes are\nproven absent or automatically generate index DDL.\n\nFor SQLite, MySQL, or MariaDB query plans, run `native_query_plan` with `engine`,\n`database`, `sql`, and optional `connectionProfile`. It uses the native adapter's\nEXPLAIN without ANALYZE. Treat plan rows and index choices as optimizer evidence,\nnot measured latency or proof that an index will improve performance. SQLite\nsupports guarded SELECT plans. MySQL/MariaDB currently accept only a single\nbase-table SELECT with `*` or named columns and optional LIMIT, bounded to 1000;\njoins, predicates, expressions, views, and stored functions are intentionally\nunsupported. Report this limitation rather than rewriting a query and presenting\nits plan as equivalent. Never retry rejected queries through a less restricted\nexecutor. This command does not enable query execution or writes.\n\nFor deployment review, use `schema_contract_check` with `before` and `after`\nobservation envelopes returned by `discover_database` (including `scope`,\n`capturedAt`, and `result`). Supply a `contract` containing `requiredObjects`,\n`protectedObjects`, `expectedChanges`, and `maxAgeMinutes` (1..1440). Object\nidentities contain `kind`, `schema`, and `name`; expected changes contain\n`identity` and `type` from the schema comparison. At least one contract rule is\nrequired. Protect ERP keys and business-critical columns explicitly, not by name\nheuristics. Expected changes never override protection. Missing objects mean\nnot observed, not proven deleted. Pass a previous `reviewFingerprint` as\n`reviewedFingerprint` to detect changes to the exact evidence or contract.\nThis hash is not approval. Preserve `insufficient_evidence` for incomplete\ncatalogs and stale timestamps. Even `observed_contract_matches` is only a result\nagainst supplied observations, never authorization to deploy or modify data.\n\nUse `compare_live_schemas` for two live connection scopes, supplied as `before`\nand `after`, each with `engine`, `database`, and optional `connectionProfile`.\nUse `compare_database_snapshots` for previously collected discovery results.\nBoth require the same engine and report changed observations and one-sided\nobjects, not executable migration instructions. Incomplete discovery cannot prove\nobject deletion. Changes to statistics are not necessarily schema changes. Never\nturn this output directly into DROP/ALTER statements or claim an atomic snapshot.\n\nFor schema inventory, run `discover_database` with explicit `engine` and `database`.\nSupported inspection engines: `sqlserver`, `postgres`, `sqlite`, `mysql`, `mariadb`.\nUse `database_capabilities` to inspect adapter support and\n`database_security_findings` for scoped security evidence. All three require a\nlive connection, validate the selected database, and never authorize changes.\nRespect per-kind coverage and limitations; `complete: false` is not a full audit.\nSQLite supports metadata inspection only through these commands. MySQL/MariaDB\nsecurity auditing is explicitly unsupported. Do not route those engines through\nlegacy SQL Server/PostgreSQL tuning, replay, migration, or administrative tools.\n\nFor SQLite, set `CODEXDB_SQLITE_DATABASE` to an existing absolute database file\npath and pass that same path as `database`; the file opens read-only. For MySQL\nor MariaDB, use `CODEXDB_MYSQL_*` or `CODEXDB_MARIADB_*` profile fields `SERVER`,\n`PORT`, `DATABASE`, `USER`, and `PASSWORD`. Verified TLS is mandatory; no automatic\ninsecure fallback. Credentials must remain in the private environment.\n\nBefore live diagnosis, run `admin_preflight` with explicit `engine` and `database`,\nand optional `connectionProfile`, `schema`, `table`. This always requires a live\nconnection and checks query-statistics, lock and index collectors independently.\nReport `blocked` or `limited` and each missing capability. `available_no_rows`\ndoes not mean healthy. This tool never restarts a service or grants write access.\n\nLive index changes are limited to the explicit `lab` environment. Follow\n`../../FIRST_RUN.md` for `create_index` / `rollback_migration`: request a dry-run\ndraft, review exact SQL and scope, then pass its signature and unchanged issue/expiry\ntimes into apply. An external signing key and explicit actor/database/schema/table\nare required. The actor is self-declared, not authenticated approval. Other migration\ntools are draft-only; never treat local qualification as production authorization.\n\nLive query statistics contain measured means, not latency percentiles. `p95Ms`\nand `regressionScore` are null when unavailable. PostgreSQL execution time is not\nCPU time; its `cpuMs` is null. Preserve `metricEvidence` and never substitute an\naverage, a multiplier or a fabricated baseline for these missing measurements.\n\nFor backup/restore assessment, call `backup_restore_readiness_guard` with numeric\n`lastBackupAgeHours`, `lastRestoreTestDays`, `restoreDurationHours` (all >= 0),\nexplicit positive `rpoHours`, `rtoHours`, `maxRestoreTestAgeDays`, and boolean\n`restoreTestSucceeded`. Missing evidence never qualifies as ready. These are\nsupplied assertions, not an independently witnessed restore or execution approval.\n\nUse `advisor_workflow` as the main entry, with `action: start`, an `objective`, and\n`systemId`, `environment`, `product`, `productVersion`. For database-only cases,\nuse the actual database product/version, not an invented ERP profile. Resume with\n`action: resume`, the same scope and `caseId`; follow its `nextStep` through\n`advisory_case`. Missing evidence means collect or ask for it, not assume success.\n\nRead the persistent-case section of `../erp-crm-advisor/SKILL.md` for case inputs.\nIt also applies to database-only cases; vendor-specific catalog selection does not.\nThe approved business contract must name required company/currency/unit/metric\ngroups. Both technical measurements and these controls must pass verification and\nlater follow-up before confirmation. Never synthesize approval references.\n\nFor application/integration/database traces, use `causal_evidence_review` with\nscoped events and hypotheses listing supporting and refuting event IDs. Review\nalternative explanations. Correlation does not establish root cause.\n\nWhen causes remain ambiguous, use `next_evidence_test` to compare proposed tests.\nSupply the full scope including deployment, hypothesis IDs, available evidence\nreferences, and tests with matching scope, `id`, `readOnly`, `estimatedMinutes`,\n`requiresEvidence`, and `outcomes` (`id`, `compatibleHypotheses`). Codex proposes\nthese compatibility assumptions explicitly; never describe them as measured facts.\nThe tool prefers tests that narrow hypotheses even in their worst modeled outcome,\nthen lower estimated time. Missing prerequisites, mutations and excessive cost\nexclude a test. Review the selected test's actual SQL/permissions before execution.\nIf an unexpected outcome occurs, stop and revise the model rather than forcing\nthe result into a predefined conclusion. No candidate is a valid result.\n\nFind relevant history through `advisory_case` with `action: find_confirmed`, exact\nscope, `workloadId` and `customizationHash`. Explain why a prior case applies and\nwhat must be remeasured. No matches is a valid result, not grounds to broaden scope.\n\n## Evidence-driven operating loop\n\nFor automatically collected context, use `live_context_fingerprint` with engine,\ndatabase, connectionProfile and the five-field system scope. Use its returned\nvalidityContext when proposing a case. `live_recommendation_check` collects a fresh\ncontext and checks caseId; never replace failed collection with caller hashes.\nThese are visible metadata, row estimates and instantaneous load, not content\nchecksums or continuous monitoring. Schedule checks only on explicit user request.\n\n`collect_process_evidence` fetches spans from an administrator-configured HTTPS\nexporter and collects database context. Configure endpoints as documented in\nFIRST_RUN.md. `process_trace_correlation` accepts supplied spans without network\naccess. Each span needs full five-field scope, id, traceId, spanId, parentSpanId\n(null for roots), processId, layer (app/api/db/wait/plan), startedAt, durationMs,\nevidenceRef. Joins require exact trace and parent-span identities; ambiguous links\nremain unresolved. Separate query/lock snapshots are not automatically proven trace\njoins. Exporter evidence is not independently attested causality.\n\nUse `live_workload_replay` only in an explicitly registered isolated lab database.\nPass full scope, cases (id, baselineTemplate, candidateTemplate, parameters,\noffsetMs), concurrency 1..5, repetitions 3..10 and optional ordered comparison.\nSQL is taken only from reviewed environment configuration, never from case input.\nProvide anonymized scalar parameters through stdin, not command-line arguments.\nThe runtime does not anonymize customer data. Alternating paired runs preserve\nparameter cases; actual arrival offsets reveal queueing. No raw results or parameter\nvalues are exported. Results compare driver values, including multiplicity and nulls;\nfreeze test data and preserve exact decimal precision in reviewed SQL projections.\n\n`live_rewrite_verification` additionally requires coverage mapping nulls, duplicates,\nrounding, timezone and permissions to case IDs. These references are declared test\ncoverage, not proof that every edge case or every principal was exercised. A match\nmeans matched recorded cases, never universal SQL equivalence or production approval.\n\n`business_outcome_measurement` takes before/after process runs and businessControls.\nEach run has full five-field scope, exportId, processId, cohortHash, datasetHash,\nsloMs, window {startAt,endAt}, events. Each event repeats scope/processId/cohortHash,\nand has eventId, caseId, status (success/error), startedAt, durationMs, blockedMs,\nevidenceRef. Both runs require identical case IDs, process, cohort, dataset and SLO,\nfresh non-overlapping equal-duration windows, distinct export/event IDs. Controls\nuse the existing business reconciliation schema plus matching processId, cohortHash\nand window, with snapshotHash equal to datasetHash and capturedAt after window end.\nReport measured success, errors, SLO breaches, blocking and duration deltas together\nwith correctness. Do not call supplied exports live telemetry or turn them into ROI.\n\nEnterprise approval and external hash witnesses are opt-in configured integrations.\nUse `enterprise_approval_check` and `enterprise_audit_witness` per FIRST_RUN.md.\nNeither is an IdP login implementation or immutable audit storage certificate.\n\nUse `diagnostic_session` with full scope (`systemId`, `environment`, `product`,\n`productVersion`, `deployment`). Start with `action: start`, `objective` and 2-20\nhypotheses. Read with `sessionId`; every mutation requires `expectedRevision`.\n`plan_test` takes the test model described above. Execute only a separately reviewed\nread-only test, then `record_result` with the pending plan's `inputHash` as `planHash`,\nselected `testId`, actual `observedOutcomeId`, fresh `observedAt`, unique\n`evidenceRefs` and exact `resultScope`. References are supplied evidence, not attestation.\nUnexpected results require `revise_model` with a reason and replacement hypotheses.\n`record_trace_review` accepts `causalEvidence`; counterevidence must remain visible.\nOne remaining hypothesis is ready for verification, not proof of causality.\n\n`record_verification` accepts `measurements` and `businessControls: {before, after}`.\nThe standalone `outcome_evidence_gate` checks these same inputs: repeated technical\nimprovement AND unchanged supplied business controls, with matching snapshot hashes\nand full five-field scope on every benchmark run and business export. Session\nmeasurements must follow the diagnostic result. A verified session must still pass\nthe approved expected-control contract and follow-up in `advisory_case` before closure.\n\nPrioritize actual process impact with `business_impact_priority`, full scope and\n`processes`: each has `id`, `name`, `evidenceRef`, fresh `observedAt`, `criticality`\n(`critical`, `high`, `normal`), integer `affectedTransactions`, `blockedTransactions`,\nand nullable `p95Ms`, `sloMs`, `deadlineAt`. Explain the returned ordering; missing\nmetrics remain unassessed. Do not invent lost revenue or measured AI confidence.\n\nWhen proposing a case, supply `validityContext` with deployment and SHA-256 hashes\n`schemaHash`, `dataProfileHash`, `loadProfileHash`, `configurationHash`, plus optional\n`validityHours` (default 24, maximum 720). Pass current context to `find_confirmed`\nor `recommendation_validity` (`action: check`, case ID and scope). Changed, missing,\nexpired or explicitly invalidated context requires revalidation. `action: invalidate`\nrequires revision and reason. This compares supplied hashes, not a background monitor.\n\nFor authenticated-issuer lab approval, follow FIRST_RUN.md. `admin_approval_check`\nvalidates trusted Ed25519 receipts; verification alone never executes or consumes\nthem. Actual apply consumes the issuer/nonce once before connecting. This proves\nan issuer assertion, not an independent IdP login, and never enables production apply.\n\nKeep legacy simulators, scorecards and generated ROI narratives out of the default\nevidence path. Use them only for explicitly requested scenario exploration and\nlabel their assumptions. The older `sql_performance_advisor` tool remains available\nfor compatibility, not as a substitute for the verified case workflow.\n"},"changes":[],"summary":"First saved snapshot. No earlier version is available for comparison.","summary_kind":"deterministic","summary_metadata":{}}