@carllee1983/dbcli 1.39.1 → 1.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -105,6 +105,7 @@ dbcli schema --use prod # Scan prod DB; saves to .dbcli/schemas/prod
105
105
 
106
106
  **Schema storage (v1.4+):** Schema is persisted as layered files under `.dbcli/schemas/`. With v2 multi-connection config each connection gets its own subdirectory (`.dbcli/schemas/<connection>/`). Run `dbcli schema --use <connection>` once per connection before querying it — otherwise `schema <table>` may return data from the wrong connection's cache.
107
107
 
108
+ > **PostgreSQL:** Introspection uses the exact `public` catalog identity throughout. Full catalog/schema/table joins prevent a reused constraint name from contaminating another table; enum lookup includes its namespace; composite primary-key order comes from the exact table OID and index ordinality; and row estimates are scoped to the exact `public` relation. Row-count SQL qualifies and quotes both `"public"` and the exact table identifier, escaping embedded quotes so mixed-case or punctuation-bearing names remain distinct and safe.
108
109
  > **Redis:** `schema <key>` is required (no full scan). The output exposes `type`, `ttl`, `size`, and a small `sample` (e.g. first 5 hash keys). `--reset` / `--refresh` are rejected — Redis caches no schema.
109
110
  > **Elasticsearch:** `schema [index]` flattens the `_mapping` properties (nested `a.b.c`) and emits each `.fields` multi-field as a separate column (e.g. `text` + `text.keyword`). Full scan iterates all non-system indices and stores per-connection caches alongside SQL engines.
110
111
  > **MongoDB:** schema is sampled via `$sample` (default 100, max 1000). `--sample-method natural` switches to `find().limit()`; `random` (default) falls back to natural order on driver error. Output columns surface nested dot-paths with `presence` (0..1) and `redacted: true` flags for blacklist-matched paths. The persisted cache records `sampleMethod` and `sampleSize`; `dbcli doctor` reports them via a `sampled: method=…, size=…` line.
@@ -192,9 +193,134 @@ dbcli explain --bulk @analytics/* # glob over saved queries
192
193
  | `nested-loop-large` | yellow | PG `Nested Loop` with planner rows > 10,000 |
193
194
 
194
195
  > Notes:
195
- > - `--analyze` executes the statement do not use against destructive SQL.
196
+ > - `--analyze` executes the statement, so dbcli accepts it only for SQL that is
197
+ > structurally proven to be a read-only, function-free `SELECT` (including
198
+ > SELECT-only CTEs). Explicit function and table-function calls are unproven
199
+ > because user-defined and built-in functions may have side effects. DML, DDL,
200
+ > data-modifying CTEs, session assignments, function-bearing SQL, and
201
+ > unrecognized SQL are rejected before the adapter is invoked; use plain
202
+ > `dbcli explain` for those statements.
196
203
  > - Auto-`LIMIT` is **not** applied to EXPLAIN statements (since v1.23 P1).
197
204
 
205
+ ### lint
206
+
207
+ Static, report-only SQL anti-pattern analysis for PostgreSQL, MySQL, and
208
+ MariaDB. `lint` never opens a database connection, never runs the SQL, and
209
+ never applies a rewrite. Schema-aware findings use only the layered schema
210
+ cache under `.dbcli/schemas/`.
211
+
212
+ ```text
213
+ dbcli lint [queries...]
214
+ dbcli lint --bulk <input>
215
+ dbcli --use <conn> lint [queries...]
216
+ ```
217
+
218
+ An input may be inline SQL, a saved query such as `@analytics/live-summary`, a
219
+ SQL file such as `@queries.sql`, or a saved-query/filesystem glob such as
220
+ `@analytics/*` or `@queries/**/*.sql`. `--bulk` accepts a comma-separated mix
221
+ of those `@file`, `@glob`, and `@saved-query` inputs; quote a filesystem glob
222
+ in a shell so the `@` reference reaches dbcli unchanged.
223
+
224
+ ```bash
225
+ dbcli lint "SELECT * FROM users WHERE email LIKE '%@example.com'" --format json
226
+ dbcli lint --bulk '@queries/**/*.sql' --format markdown
227
+ dbcli --use staging lint @analytics/live-summary --min-severity warn
228
+ ```
229
+
230
+ | Option | Default | Meaning |
231
+ |---|---|---|
232
+ | `--format <text\|json\|markdown>` | `text` | Render one report per resolved input. |
233
+ | `--min-severity <info\|warn\|error>` | `info` | Omit findings below the selected severity. |
234
+ | `--no-schema` | off | Skip schema-only checks without reading schema-cache paths; static `NOT IN` NULL checks still run. |
235
+ | `--bulk <input>` | none | Resolve a comma-separated list of `@file`, `@glob`, or `@saved-query` inputs. |
236
+ | `--recovery` | off | On command failure, emit and save a linked `RecoveryEnvelope`. |
237
+ | global `--use <conn>` | configured default | Select a v2 named connection and its isolated cache; place it before `lint`: `dbcli --use <conn> lint …`. |
238
+
239
+ **Rules:**
240
+
241
+ | Rule | Severity | What it reports |
242
+ |---|---|---|
243
+ | `select-star` | warn | A top-level `SELECT *`; when one table and its cached columns are unambiguous, the finding may include a column-list rewrite draft. |
244
+ | `unanchored-like` | warn | A `LIKE` / `ILIKE` pattern beginning with `%`, which a conventional B-tree index cannot anchor. |
245
+ | `missing-limit-offset` | info | Deep pagination with `OFFSET >= 1000`; prefer keyset pagination. |
246
+ | `non-sargable-where` | warn | A function or arithmetic expression applied to the column side of a predicate. |
247
+ | `or-to-union` | info | A top-level `OR` across different columns that can complicate index selection; any UNION alternative must preserve identity and multiplicity. |
248
+ | `subquery-to-join` | info | `IN (SELECT …)` where an equivalent `EXISTS`, or a JOIN with proven uniqueness/deduplication, may plan better. |
249
+ | `distinct-groupby-abuse` | warn | Redundant `DISTINCT` when simple projected columns exactly cover the `GROUP BY` columns. |
250
+ | `implicit-cast` | warn | A schema-verified column/literal type mismatch that can disable index use; safe, unambiguous numeric drafts may be included. |
251
+ | `not-in-nullable` | warn | A right-hand `NOT IN` value that can be NULL: explicit `NULL`, outer-join null extension, a nullable subquery projection, or a known nullable CASE/cast/aggregate expression. A nullable left-hand column is not this rule. |
252
+
253
+ `implicit-cast` and the schema-enriched portion of `not-in-nullable` read the
254
+ selected cache through the schema loader abstraction. Static `not-in-nullable`
255
+ checks still run without it. All schema caches live beneath `.dbcli/schemas/`. A v2
256
+ configuration always uses `.dbcli/schemas/<resolved-connection>/`, including
257
+ the configured default. The root `.dbcli/schemas/` directory is only the
258
+ v1/legacy unnamed cache. Global `dbcli --use <conn> lint …` selects another
259
+ named v2 slot. The command never refreshes the cache and never falls back to
260
+ schema embedded in config.
261
+
262
+ Skipped rules are returned with machine-readable `blocked:` reasons:
263
+
264
+ - Invalid SQL blocks all nine rules with `blocked: parse failed` and includes
265
+ `parseError`.
266
+ - `--no-schema` blocks `implicit-cast` and the schema-dependent portion of
267
+ `not-in-nullable` with `blocked: --no-schema`; static RHS hazards still run.
268
+ - A missing layered cache records
269
+ `blocked: schema cache unavailable (run dbcli schema)` for those unavailable
270
+ schema checks while retaining static RHS findings.
271
+
272
+ Every finding includes its rule, severity, source span, message, and
273
+ `schemaVerified` state. Some findings also carry a confidence-labelled rewrite
274
+ draft and a shell-safe verification command. It uses
275
+ `dbcli explain --analyze` only when the statement is structurally proven read-only;
276
+ function-bearing and session-assignment statements are unproven, so lint
277
+ falls back to plain `dbcli explain`. These are suggestions only: `lint` neither
278
+ executes the verification command nor changes the query.
279
+
280
+ When schema identifiers collide after case folding, schema-aware findings and
281
+ rewrites are withheld. The SQL parser does not preserve reliable quote
282
+ provenance, so an exact-looking mixed-case AST identifier cannot disambiguate
283
+ that collision. CTE, derived, schema-qualified, and database-qualified
284
+ relations also never borrow facts from the unqualified cache.
285
+
286
+ For `not-in-nullable`, remove or filter right-hand NULL values. In a subquery,
287
+ filter the projected value with `IS NOT NULL`; `NOT EXISTS` may be a better
288
+ semantic form when appropriate. dbcli does not automatically rewrite this case
289
+ unless correlation, type classification, qualified-column resolution, and the
290
+ rewrite target are all unambiguous. A direct or `AND`-conjoined `IS NOT NULL`
291
+ filter on the exact projected expression suppresses the finding; aggregates
292
+ apply the same proof in `HAVING`. Filters under `OR` or ambiguous expression
293
+ matches do not. The rule recursively checks projection, JOIN `ON`, `WHERE`, and
294
+ `HAVING` expressions, using each nested SELECT/CTE/derived statement's own
295
+ scope. Qualified outer-join null extension remains detectable without a cache,
296
+ but a join's synthetic NULL row is not applied inside that join's own `ON`;
297
+ declared nullability and completed earlier joins still apply there.
298
+
299
+ Trimmed JSON example:
300
+
301
+ ```json
302
+ [
303
+ {
304
+ "sql": "SELECT * FROM users",
305
+ "dialect": "postgresql",
306
+ "findings": [
307
+ {
308
+ "rule": "select-star",
309
+ "severity": "warn",
310
+ "message": "SELECT * fetches every column; list the columns you need.",
311
+ "span": { "start": 0, "end": 8 },
312
+ "schemaVerified": false
313
+ }
314
+ ],
315
+ "skippedRules": [],
316
+ "relatedCommands": [
317
+ "dbcli guide missing-index-for \"SELECT * FROM users\"",
318
+ "dbcli explain --analyze \"SELECT * FROM users\""
319
+ ]
320
+ }
321
+ ]
322
+ ```
323
+
198
324
  ### plan
199
325
 
200
326
  Static SQL risk analyzer. Classifies a statement into the same permission tiers
@@ -249,6 +375,7 @@ dbcli q @analytics/revenue --param days=30 --format html > report.html
249
375
  - `--dry-run` — print the bound SQL + values without executing
250
376
  - `--use <name>` — pick a v2 named connection
251
377
  - `--recovery` — emit a `RecoveryEnvelope` on failure (see `recover`)
378
+ - `--verify` — run the snippet's verification assertions after execution (only if the snippet defines them)
252
379
 
253
380
  **Permission:** query-only+
254
381
 
@@ -474,9 +601,10 @@ Insert data into a table.
474
601
  dbcli insert users --data '{"name":"Alice","email":"alice@example.com"}'
475
602
  dbcli insert users --data '{"name":"Alice"}' --dry-run
476
603
  dbcli insert users --data '{"name":"Alice"}' --force
604
+ dbcli insert users --data '{"name":"Alice"}' --plan --format json # risk analysis only; no DB connection
477
605
  ```
478
606
 
479
- **Options:** `--data <json>`, `--dry-run`, `--force`
607
+ **Options:** `--data <json>`, `--dry-run`, `--force`, `--plan` (analyze risk without connecting or executing), `--format <text|json>` (`--plan` output), `--recovery`
480
608
  **Permission:** read-write+
481
609
 
482
610
  ### update
@@ -486,11 +614,19 @@ Update existing data.
486
614
  ```bash
487
615
  dbcli update users --where "id=1" --set '{"name":"Bob"}'
488
616
  dbcli update users --where "id=1" --set '{"name":"Bob"}' --dry-run
617
+ dbcli update users --where "id=1" --set '{"name":"Bob"}' --plan --format json # risk analysis only; no DB connection
489
618
  ```
490
619
 
491
- **Options:** `--where <condition>` (required), `--set <json>` (required), `--dry-run`, `--force`
620
+ **Options:** `--where <condition>` (required), `--set <json>` (required), `--dry-run`, `--force`, `--plan` (analyze risk without connecting or executing), `--format <text|json>` (`--plan` output), `--recovery`
492
621
  **Permission:** read-write+
493
622
 
623
+ > **`--where` grammar (SQL `update` / `delete`)** — equality only: `col=val` or
624
+ > `col1=v1 AND col2=v2`. Comparison / pattern operators (`>`, `>=`, `<`, `!=`, `LIKE`, `IN`)
625
+ > raise a parse error, and `OR` is **silently folded into the value** (`a=1 OR b=2` parses as
626
+ > `a = "1 OR b=2"`, matching nothing intended). For ranges or compound predicates, select the
627
+ > target primary keys first, then issue one `update` / `delete --where "id=<pk>"` per key.
628
+ > (MongoDB `--where` accepts a full JSON filter and is exempt.)
629
+
494
630
  ### delete
495
631
 
496
632
  Delete data from a table.
@@ -499,9 +635,10 @@ Delete data from a table.
499
635
  dbcli delete users --where "id=1"
500
636
  dbcli delete users --where "id=1" --dry-run
501
637
  dbcli delete users --where "id=1" --force
638
+ dbcli delete users --where "id=1" --plan --format json # risk analysis only; no DB connection
502
639
  ```
503
640
 
504
- **Options:** `--where <condition>` (required), `--dry-run`, `--force`
641
+ **Options:** `--where <condition>` (required), `--dry-run`, `--force`, `--plan` (analyze risk without connecting or executing), `--format <text|json>` (`--plan` output), `--recovery`
505
642
  **Permission:** data-admin+
506
643
 
507
644
  ### export
@@ -521,7 +658,7 @@ dbcli export orders --format csv --output orders.csv # index name as query
521
658
  dbcli export orders --no-limit --format jsonl # scroll the whole index in batches
522
659
  ```
523
660
 
524
- **Options:** `--format <json|jsonl|csv|html>` (required), `--output <path>`, `--force`, `--recovery`, `--index <name>` (Elasticsearch), `--no-limit` (Elasticsearch full-index scroll)
661
+ **Options:** `--format <json|jsonl|csv|html>` (required), `--output <path>`, `--force`, `--recovery`, `--collection <name>` (MongoDB collection) / `--index <name>` (Elasticsearch index; alias for `--collection`), `--limit <number>` (overrides auto-limit), `--no-limit` (Elasticsearch full-index scroll)
525
662
  **Permission:** query-only+ — SQL, MongoDB, and **(v1.22)** Elasticsearch.
526
663
 
527
664
  The `html` format emits the same self-contained dashboard as `query --ui` (see [Interactive HTML dashboard](#interactive-html-dashboard)). Because `export` runs raw SQL (no snippet metadata), the HTML report is always rendered as a sortable / filterable table — no KPIs or charts. Use `dbcli q @<name> --format html` (or `--ui`) for the charted view.
@@ -572,6 +709,147 @@ dbcli diff --against before.json --format json
572
709
  **Options:** `--snapshot <path>`, `--against <path>`, `--format <json|table>`
573
710
  **Permission:** query-only+
574
711
 
712
+ #### `diff --against-orm`
713
+
714
+ Compare an ORM definition with the local SQL schema cache. This mode reads
715
+ `config.schema`; it does not open a database connection, refresh the cache, or
716
+ execute a proposal. An empty cache fails with
717
+ `Schema cache is empty. Run 'dbcli schema' first.` Snapshot mode remains a
718
+ separate `--snapshot` / `--against` workflow.
719
+
720
+ ```bash
721
+ # Prisma and normalized JSON accept exactly one file
722
+ dbcli diff --against-orm prisma/schema.prisma --format json
723
+ dbcli diff --against-orm schema.normalized.json --orm-format json --format table
724
+
725
+ # DDL accepts repeatable or comma-separated paths and real filesystem globs
726
+ dbcli diff --against-orm "migrations/*.sql" --format markdown
727
+ dbcli diff --against-orm migrations/base.sql,migrations/accounts.sql \
728
+ --against-orm migrations/orders.sql --orm-format ddl --format json
729
+
730
+ # Ignore patterns are comma-separated and match qualified table identity
731
+ dbcli diff --against-orm prisma/schema.prisma --ignore 'public.audit_*,public.Legacy'
732
+ ```
733
+
734
+ | Option | Behavior |
735
+ | :--- | :--- |
736
+ | `--against-orm <paths>` | Repeatable or comma-separated input. DDL inputs support real filesystem globs; matches are deduplicated and put in deterministic path order, then parsed as one shared ordered context so an index in a later file can attach to a table declared in an earlier file. Prisma and normalized JSON accept exactly one file, and globs are rejected for those formats. |
737
+ | `--orm-format prisma\|ddl\|json` | Override extension/content detection. Without it, dbcli detects Prisma, DDL, or normalized JSON from the path and content. |
738
+ | `--ignore <globs>` | Comma-separated, case-sensitive table globs. Patterns match the qualified display identity (for example `public.Users`). `_prisma_migrations` is always unmanaged. |
739
+ | `--format json\|table\|markdown` | Select machine JSON, human table, or Markdown output. Markdown is available only in ORM drift mode. |
740
+ | `--recovery` | On an I/O, configuration, empty-cache, invalid-format, or unsupported-engine failure, emit and save a structured recovery envelope. Invalid Prisma/DDL constructs normally become `unparsed` entries instead of throwing. |
741
+
742
+ The command supports PostgreSQL, MySQL, and MariaDB configurations. Only
743
+ error-level **scored drift** determines the report's drift exit code: one or more
744
+ scored errors exits `1`; warnings, infos, `unmanaged`, or `unparsed` entries alone
745
+ exit `0`. Command/configuration failures independently exit code `1`. The four
746
+ drift categories and tolerance rules are:
747
+
748
+ | Category | Severity and comparison rule |
749
+ | :--- | :--- |
750
+ | `missing_in_db` | `error` — a table, column, or index exists in the ORM definition but not in the cached DB schema. |
751
+ | `missing_in_orm` | `warn` — a table, column, or index exists in the cached DB schema but not in the ORM definition. |
752
+ | `mismatch` | `error` when the type family or nullability differs; `info` for same-family type spelling, default, or primary-key differences. |
753
+ | `unmanaged` | `info`, excluded from error/warn scoring — the table matched the built-in or user `--ignore` patterns. |
754
+
755
+ Type-family tolerance deliberately treats engine spellings such as `text` and
756
+ `varchar(191)` as the same family: the spelling difference is still visible as
757
+ `info`, while an integer/text family difference is an `error`. Indexes compare
758
+ by structural index signatures — ordered, case-folded column names plus
759
+ uniqueness — rather than by engine-specific index names. Duplicate signatures
760
+ are emitted once. Drift entries sort deterministically by table, object, category,
761
+ and detail using Unicode code-point order, never locale-dependent collation.
762
+
763
+ **Schema and table identity.** Storage preserves exact, case-sensitive schema
764
+ and table names from the database catalog. Exact, case-sensitive `(schema, table)`
765
+ tuples are the comparison key, so PostgreSQL `users` and `"Users"` can coexist.
766
+ DDL resolution rules: unquoted SQL identifiers fold to lowercase; quoted identifiers match exactly.
767
+ For example, unquoted `Users` resolves to `users`, and quoted
768
+ `"Users"` resolves only to `Users`. Quote state comes from the parsed identifier representation;
769
+ dbcli never infers it from display text, catalog spelling, or a
770
+ Prisma mapping. Qualified components resolve independently, and unqualified ORM
771
+ identities use the cached DB default schema when one is known. Qualified display
772
+ names and `--ignore` matching remain case-sensitive. Duplicate exact or
773
+ duplicate resolved table identities fail closed instead of overwriting one
774
+ another.
775
+
776
+ **Prisma subset.** The parser supports `model` blocks; scalar `String`, `Int`,
777
+ `BigInt`, `Float`, `Decimal`, `Boolean`, `DateTime`, `Json`, and `Bytes` fields;
778
+ `?`; relation-side `[]`; `@id`, `@unique`, `@default(...)`, `@map("...")`,
779
+ `@@map("...")`, `@@index([...])`, `@@unique([...])`; relations with
780
+ `fields` / `references`; and the validated native mappings `@db.Text`,
781
+ `@db.VarChar(n)`, `@db.Uuid`, `@db.Timestamptz([precision])`, `@db.Date`,
782
+ `@db.SmallInt`, and `@db.JsonB`. Views, composite types, enums used as scalar
783
+ columns, multi-schema datasource configuration, malformed declarations, unknown
784
+ attributes, and unsupported native mappings are never guessed.
785
+
786
+ Prisma and DDL constructs outside the supported subset are retained in
787
+ `unparsed` with a `blocked:` reason. These entries are separate from scored drift:
788
+ inspect and resolve them before treating an otherwise clean summary as complete.
789
+ Multi-file DDL is consumed as one deterministic shared ordered statement context,
790
+ so later `CREATE INDEX` statements can reference tables declared in earlier
791
+ files. PostgreSQL `PARTITION BY` and MySQL/MariaDB table engine, charset, and
792
+ other `CREATE TABLE` table options are unsupported: the construct produces a
793
+ `blocked:` `unparsed` entry and does not emit a managed ORM table.
794
+ The normalized JSON escape hatch is Zod-validated and uses an array of tables
795
+ with explicit exact `identity` objects; optional parsed identifiers must include
796
+ their `quoted` flags, and every normalized JSON `unparsed.reason` must start with
797
+ `blocked:`.
798
+
799
+ ```json
800
+ {
801
+ "ormSource": "prisma",
802
+ "entries": [
803
+ {
804
+ "category": "missing_in_db",
805
+ "severity": "error",
806
+ "table": "public.users",
807
+ "object": "email",
808
+ "detail": "column 'email' (text) is defined in prisma but absent in the database",
809
+ "proposedCommands": [
810
+ "# escalate: schema-qualified table 'public.users' is not losslessly representable by dbcli migrate — run: dbcli skill tasks plan migration-review"
811
+ ]
812
+ }
813
+ ],
814
+ "unparsed": [],
815
+ "summary": { "errors": 1, "warns": 0, "infos": 0, "unmanaged": 0 }
816
+ }
817
+ ```
818
+
819
+ Missing unqualified columns and indexes may receive shell-safe, dry-run-by-default
820
+ `dbcli migrate add-column` or `add-index` proposal strings. Simple arguments stay
821
+ unquoted; unsafe shell characters are POSIX single-quoted. Table creation,
822
+ removal, mismatch, and DB-only drift escalate to `migration-review`. A
823
+ schema-qualified target, or index columns that the current `migrate --columns`
824
+ CLI cannot represent losslessly, also escalates instead of emitting a corrupt
825
+ command. Any table, column, or type positional beginning with `-` also escalates
826
+ so Commander cannot reinterpret it as an option. A leading-dash option value is
827
+ rendered with option-safe attached syntax, for example `--default=-1` or
828
+ `--columns=--config,email`. Proposals are text only and never add `--execute`.
829
+
830
+ For a guided, cache-refreshing review, use the built-in `orm-drift-review` pack:
831
+
832
+ ```bash
833
+ dbcli skill tasks plan orm-drift-review \
834
+ --param orm_path=prisma/schema.prisma \
835
+ --format json
836
+ ```
837
+
838
+ The plan is `blacklist list` → `schema --format json` →
839
+ `diff --against-orm ... --format json`. Run any proposed `migrate` command in its
840
+ default dry-run mode, capture the emitted DDL, confirm its exact target, and pass
841
+ both values to the separate migration review:
842
+
843
+ ```sh
844
+ dbcli skill tasks plan migration-review \
845
+ --param "table=${exact_table}" \
846
+ --param "ddl=${captured_ddl}"
847
+ ```
848
+
849
+ Both parameters are required. Keep each expansion as one quoted shell argument;
850
+ never use `eval`, and consider `--execute` only after the plan and captured DDL
851
+ have been reviewed.
852
+
575
853
  ### snapshot
576
854
 
577
855
  Capture a **result fingerprint** of a query (not schema): `rowCount` plus per-column
@@ -892,6 +1170,7 @@ Boundaries:
892
1170
  | `--from <path>` | Read the envelope from this file instead of `.dbcli/last-recovery.json`. Accepts raw `RecoveryEnvelope` or `SavedRecoveryEnvelope`. | — |
893
1171
  | `--allow-write <tier>` | Open the risk gate. Values: `readonly-cmd` (local-side writes) \| `write-cmd` (database writes). | `none` |
894
1172
  | `--no-verify` | Skip the verify step appended after a successful `--apply`. | off (verify runs by default) |
1173
+ | `--write-verification-artifact` | After a successful `--apply`, persist a secret-free `VerificationArtifact` JSON under `.dbcli/verification/`. | off |
895
1174
  | `--format <format>` | `markdown` \| `json`. | `markdown` for inspect, `json` for `--apply` |
896
1175
 
897
1176
  #### Plan source resolution
@@ -1650,6 +1929,7 @@ dbcli skill --install codex # install to ~/.codex/skills/dbcli/
1650
1929
  **Options:**
1651
1930
  - `--install <platform>` — `claude` | `gemini` | `antigravity` | `copilot` | `cursor` | `codex` | `windsurf`. Writes `SKILL.md` plus `reference.md` next to it so the agent gets progressive disclosure.
1652
1931
  - `--output <path>` — write `SKILL.md` to a file instead of stdout. Does not install `reference.md`.
1932
+ - `--lang <en|zh-TW>` — source language for the emitted SKILL content (default `en`). It selects `assets/SKILL.md` vs `assets/SKILL.zh-TW.md`; the install/output filename stays `SKILL.md` regardless.
1653
1933
 
1654
1934
  **Notes:**
1655
1935
  - Both files come straight from `assets/SKILL.md` + `assets/reference.md` inside the dbcli package — no runtime rendering. Keep these in sync when shipping a release.
@@ -1662,6 +1942,21 @@ dbcli skill --install codex # install to ~/.codex/skills/dbcli/
1662
1942
 
1663
1943
  **Permission:** n/a.
1664
1944
 
1945
+ ### skill context
1946
+
1947
+ Emit an AI-friendly snapshot of the connected database's schema and saved-query snippets (blacklist-filtered) so an agent can be primed with the current context.
1948
+
1949
+ ```bash
1950
+ dbcli skill context # XML (default)
1951
+ dbcli skill context --format json
1952
+ dbcli skill context --format markdown
1953
+ ```
1954
+
1955
+ **Options:**
1956
+ - `--format <xml|json|markdown>` — output format (default: `xml`)
1957
+
1958
+ **Permission:** query-only+ — read-only; blacklisted objects are never emitted.
1959
+
1665
1960
  ### skill tasks (Agent Task Packs)
1666
1961
 
1667
1962
  ```bash
@@ -1685,8 +1980,12 @@ a read-only (`plan-only`) pack taking a required `table` parameter that walks
1685
1980
  in recent audit activity. Additional read-only packs ship for common agent
1686
1981
  workflows: `audit-permissions` (permission/blacklist audit), `safe-backfill`
1687
1982
  (plan a write with blacklist+schema+risk checks), `schema-drift-review` (cached
1688
- vs live schema diff), and `connection-health` (reachability/config/capacity
1689
- triage). Run `dbcli skill tasks list` for the full set.
1983
+ vs live schema diff), `orm-drift-review` (ORM definition vs cached DB schema),
1984
+ and `connection-health` (reachability/config/capacity
1985
+ triage). **MongoDB packs:** `mongo-safe-backfill` (dry-run–previewed backfill)
1986
+ and `mongo-schema-drift-review` (sampled dot-path drift, with a `sample_size` knob
1987
+ to damp sampling noise); filter them with `dbcli skill tasks list --engine mongodb`.
1988
+ Run `dbcli skill tasks list` for the full set.
1690
1989
 
1691
1990
  ```bash
1692
1991
  dbcli skill tasks plan analyze-table-perf --param table=betting_logs --format json
@@ -2201,7 +2500,7 @@ Rewrites emit a `REDIS_SIZE_REWRITE` warning; truncations emit `REDIS_SIZE_TRUNC
2201
2500
  Blacklist rules are enforced as **Redis-native key globs** (`*`, `?`, `[abc]`, `[a-z]`):
2202
2501
 
2203
2502
  ```bash
2204
- dbcli blacklist add 'secrets:*' # register a key-glob rule
2503
+ dbcli blacklist table add 'secrets:*' # register a key-glob rule
2205
2504
  dbcli query "GET secrets:api_key" # → BlacklistRejection (exit non-zero)
2206
2505
  dbcli query "MGET safe:k secrets:api" # → rejected (any matching key fails the whole command)
2207
2506
  dbcli query "KEYS secrets:*" # → rejected (pattern overlaps a rule)
@@ -22,6 +22,14 @@ steps:
22
22
  command: plan "{{query}}"
23
23
  reason: Analyze SQL risk without executing the query.
24
24
  risk: readonly
25
+ - type: command
26
+ command: lint "{{query}}" --format json
27
+ reason: Run local static analysis for SQL anti-patterns with no database round-trip.
28
+ risk: readonly
29
+ - type: command
30
+ command: explain "{{query}}" --format json
31
+ reason: Inspect the database query plan after resolving local lint findings.
32
+ risk: readonly
25
33
  - type: command
26
34
  command: q @diag/long-running --format json
27
35
  reason: Inspect active long-running queries through a saved diagnostic snippet.
@@ -0,0 +1,56 @@
1
+ ---
2
+ name: mongo-safe-backfill
3
+ description: Plan a safe MongoDB backfill/update with blacklist, sampled-schema and dry-run checks before any write.
4
+ tags: [data, write, safety]
5
+ engines: [mongodb]
6
+ params:
7
+ collection:
8
+ type: string
9
+ required: true
10
+ description: The collection the backfill writes to (exact name; confirm via `dbcli list`).
11
+ filter:
12
+ type: string
13
+ required: true
14
+ description: JSON filter selecting the documents to update (Mongo `--where`, e.g. '{"status":"pending"}').
15
+ set:
16
+ type: string
17
+ required: true
18
+ description: JSON update document (`--set`; auto-wrapped as $set when it has no $ operator).
19
+ safety:
20
+ mode: plan-only
21
+ requires:
22
+ - blacklist-list
23
+ - schema-check
24
+ steps:
25
+ - type: command
26
+ command: blacklist list
27
+ reason: Confirm the target collection and its fields are not protected before planning a write.
28
+ risk: readonly
29
+ - type: command
30
+ command: schema {{collection}} --format json
31
+ reason: Verify the exact sampled dot-path fields and types the backfill will touch.
32
+ risk: readonly
33
+ - type: command
34
+ command: update {{collection}} --where '{{filter}}' --set '{{set}}' --dry-run
35
+ reason: Preview the update as a shell-style plan; --dry-run connects but never writes.
36
+ risk: dry-run
37
+ ---
38
+ # Agent Notes
39
+
40
+ Use this task when a user wants to backfill or correct existing MongoDB documents. It only
41
+ PLANS — it never writes. MongoDB has no static SQL risk analyzer, so the preview is
42
+ `dbcli update ... --dry-run` (which prints a shell-style plan and writes nothing) rather
43
+ than `dbcli plan`.
44
+
45
+ Mongo specifics to respect:
46
+ - `--where` takes a **full JSON filter** (`'{"status":"pending"}'`), not `col=val`.
47
+ - `--set` is a **JSON document**; a plain object is auto-wrapped as `$set`, while explicit
48
+ operators (`$set` / `$inc` / `$push` / …) pass through untouched.
49
+ - Blacklisted fields accept dotted paths (`profile.email`) and trailing wildcards
50
+ (`profile.tokens.*`); confirm the write does not touch a protected path.
51
+
52
+ After reviewing the dry-run preview, scope the change with a read-only find on the same
53
+ filter first (`dbcli query '<filter>' --collection <collection> --format json`), then
54
+ re-run the update **without** `--dry-run` to execute (requires read-write or higher). Read
55
+ the documents back afterwards to confirm the write achieved its goal; explain any mismatch
56
+ via schema validators, defaults, or blacklist redaction.
@@ -0,0 +1,51 @@
1
+ ---
2
+ name: mongo-schema-drift-review
3
+ description: Detect drift between the cached sampled schema and the live collection for one MongoDB collection.
4
+ tags: [diagnostics, schema, readonly]
5
+ engines: [mongodb]
6
+ params:
7
+ collection:
8
+ type: string
9
+ required: true
10
+ description: The collection to compare against its cached schema (exact name; confirm via `dbcli list`).
11
+ sample_size:
12
+ type: number
13
+ default: 200
14
+ description: Documents to sample; raise it to reduce sampling-driven false positives in drift detection.
15
+ safety:
16
+ mode: plan-only
17
+ requires:
18
+ - blacklist-list
19
+ - schema-check
20
+ steps:
21
+ - type: command
22
+ command: blacklist list
23
+ reason: Confirm the collection is inspectable and not protected before reading its schema.
24
+ risk: readonly
25
+ - type: command
26
+ command: doctor
27
+ reason: Report the schema-cache age so a stale cache can be ruled out as the cause of drift.
28
+ risk: readonly
29
+ - type: command
30
+ command: schema {{collection}} --sample-size {{sample_size}} --format json
31
+ reason: Pull the current sampled shape to diff against the cached/committed definition.
32
+ risk: readonly
33
+ ---
34
+ # Agent Notes
35
+
36
+ Use this task when a query starts failing on a field that "should" exist, or a code path
37
+ may have begun (or stopped) writing a field. Unlike SQL, MongoDB has no DDL — the schema is
38
+ **sampled** via `$sample`, so "drift" means the set of dot-path fields, their types, or
39
+ their `presence` (0..1) changed relative to the cached snapshot under
40
+ `.dbcli/schemas/<connection>/`.
41
+
42
+ Read the diff with sampling in mind:
43
+ - A **high-presence** dot-path appearing or disappearing is real drift (a writer started or
44
+ stopped populating it).
45
+ - A **low-presence** field (presence < ~0.1) flickering between runs is usually sampling
46
+ variance, **not** drift — raise `sample_size` or re-run before trusting it. For very large
47
+ collections, `dbcli schema <collection> --sample-method natural` trades representativeness
48
+ for speed.
49
+
50
+ Do not run write operations or DDL. If `doctor` reports a stale schema cache, refresh it
51
+ (`dbcli schema <collection> --refresh`) before treating the difference as live drift.
@@ -0,0 +1,55 @@
1
+ ---
2
+ name: orm-drift-review
3
+ description: Compare an ORM schema definition (Prisma / DDL / normalized JSON) against the live schema cache and review drift before any corrective migration.
4
+ tags: [diagnostics, schema, orm, readonly]
5
+ engines: [postgres, mysql]
6
+ params:
7
+ orm_path:
8
+ type: string
9
+ required: true
10
+ description: Path to the ORM schema definition (e.g. prisma/schema.prisma, migrations/*.sql, or a normalized schema JSON).
11
+ safety:
12
+ mode: plan-only
13
+ requires:
14
+ - blacklist-list
15
+ - schema-check
16
+ steps:
17
+ - type: command
18
+ command: blacklist list
19
+ reason: Confirm sensitive-data boundaries before reading schema details.
20
+ risk: readonly
21
+ - type: command
22
+ command: schema --format json
23
+ reason: Refresh the local schema cache so the drift comparison runs against current DB state.
24
+ risk: readonly
25
+ - type: command
26
+ command: diff --against-orm "{{orm_path}}" --format json
27
+ reason: Compare the ORM definition against the cached DB schema; error-level entries are app-breaking drift.
28
+ risk: readonly
29
+ ---
30
+
31
+ # Agent Notes
32
+
33
+ Treat `missing_in_db` errors as release blockers: the application expects columns or
34
+ indexes the database does not have. `missing_in_orm` warnings usually mean a manual
35
+ hotfix was never backfilled into the ORM definition — backfill the definition rather
36
+ than dropping the column. Same-family type-spelling differences are reported as
37
+ `info` and are usually the ORM's default mapping, not real drift.
38
+
39
+ Proposals are `dbcli migrate` commands that run in default dry-run mode. Run a
40
+ proposed command only in that mode — do not add `--execute` — and capture the emitted
41
+ DDL. Identify the exact target table from the drift entry and DDL, then confirm it
42
+ against the refreshed schema output. Pass each value as one shell argument. Use the
43
+ current shell's safe quoting or argument-array mechanism; never use `eval`. For a
44
+ POSIX shell, bind the confirmed values to `exact_table` and `captured_ddl`, then keep
45
+ both expansions quoted:
46
+
47
+ ```sh
48
+ dbcli skill tasks plan migration-review \
49
+ --param "table=${exact_table}" \
50
+ --param "ddl=${captured_ddl}"
51
+ ```
52
+
53
+ Both `--param` values are required: the bare `migration-review` pack command is not a
54
+ review. Consider `--execute` only after the resulting migration-review plan and
55
+ captured DDL have been checked.