@ultimat3/cli 31.22.3 → 31.24.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.
package/CLAUDE.md CHANGED
@@ -52,7 +52,7 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
52
52
  | `coverage-{floor,lcov,source}.ts` / `verify-coverage-run.ts` | an app's `unit` coverage floor; `coverage-lcov.ts` is the ONE lcov reader † |
53
53
  | `verify-deadline.ts` / `verify-stalled.ts` / `verify-progress.ts` | a step past its deadline is `X_VERIFY_STEP_TIMEOUT`; its children are killed by tag † |
54
54
  | `load-findings.ts` | a module-load failure is reported once, by `manifest`; while red, each step that loads the app is wrapped in `blockedByLoad`: `skipped: load failed (see manifest)`. Under `--only` without `manifest` it carries the findings itself |
55
- | `verify-contract-diff.ts` | `contract-diff`: baseline is `x.manifest.json` at HEAD; in CI, at the merge base with `origin/$GITHUB_BASE_REF`, or that ref itself when a shallow checkout reaches no merge base; HEAD plus a fetch notice when the ref is not fetched; outside git, the file on disk with a notice |
55
+ | `verify-contract-diff.ts` | `contract-diff`: baseline `x.manifest.json` at HEAD; in CI at the merge base with `origin/$GITHUB_BASE_REF` (the ref when shallow; HEAD + notice when unfetched); outside git, the file on disk + notice |
56
56
  | `verify-factories.ts` | `unit` lints `<app>/packages/db/factories.ts` (`X_TEST_FACTORY_INVALID`) |
57
57
  | `verify-seeds.ts` / `verify-seeds-probe.ts` | `unit` runs the seeds in a child on ONE scratch database — `x exercise`'s (`withExerciseDatabase`): framework schema + migrations, installed as `db()`, so `register()` and entity rows agree; a refused row keeps the entity's code and fix, an uncoded throw is `X_SEED_FAILED` |
58
58
  | `boundary-findings.ts` / `app-boundaries.ts` / `boundary-cuts.ts` / `package-boundaries.ts` | surface + layer rules, `X_BOUNDARY_PACKAGE_TO_APP`; a `fix:` is the concrete cut † |
@@ -74,6 +74,7 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
74
74
  | `app-agents-md.ts` / `app-env.ts` / `app-openapi.ts` / `app-manifest.ts` | `manifest` and `contract-diff` ‡ |
75
75
  | `schema-drift.ts` / `drift.ts` / `drift-replica-identity.ts` / `db-destructive.ts` / `db-ungeneratable.ts` | `drift`: snapshot vs declarations, the source hash, the header markers ‡ |
76
76
  | `db-rolling.ts` / `doctor-rolling.ts` | `drift`'s rolling rail (`X_MIGRATION_ROLLING_UNSAFE`) † |
77
+ | `redundant-indexes.ts` / `doctor-redundant-indexes.ts` | covered indexes: `gen --drop-redundant` drops, `drift` excuses, `x doctor` lists |
77
78
  | `schema-dump-drift.ts` | also the dump-vs-newest-snapshot rail, no database (`X_DB_DRIFT`) ‡ |
78
79
  | `i18n-registration.ts` / `i18n-audit.ts` / `admin-catalog-keys.ts` | `i18n`; a mounted admin's keys are `AdminApp.catalogKeys()`, asked of every app catalog — never re-derived here (`X_CATALOG_MISSING_KEYS`) |
79
80
  | `error-unthrown.ts` / `unthrown-codes.ts` | host check: a registered code nothing throws is listed in `UNTHROWN_CODES` (a row's wording waives nothing); a listed code thrown again is `X_ERROR_CODE_UNTHROWN_STALE` |
@@ -141,7 +142,7 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
141
142
  | `runtime-render*.ts` / `runtime-{isr-outcome,assets,storage,hooks}.ts` / `route-islands.ts` / `api-routes.ts` | the HTTP surface both boots mount † |
142
143
  | `asset-route-meta.ts` | the ONE writer of an asset route's `tags: ['assets']` + `rateLimit: 'assets'`; the test walks `examples/dummy`'s built table and refuses an `assets.*` route on `default` |
143
144
  | `client-{errors,vitals}-*.ts` | `clientErrors` (and `.vitals`): the script on `app/` (vitals: listed) documents, its `POST` route, mounted by BOTH boots ‡ |
144
- | `retained-assets.ts` / `-layout.ts` / `-sweep.ts` / `-read.ts` / `-boot.ts` | `assets.retain`: the web boot publishes this build's hashed files before `/readyz` † |
145
+ | `retained-assets.ts` / `-layout.ts` / `-sweep.ts` / `-read.ts` / `-boot.ts` / `-warned.ts` | `assets.retain`: the web boot publishes this build's hashed files before `/readyz` † |
145
146
  | `runtime-overrides.ts` / `runtime-ports.ts` / `runtime-port-bindings.ts` | `runtime.ts`: a field per `ADAPTER_PORTS` row, installed by ONE loop or read where used; unbound row = build error. Plus `routes`. `docs/history/cli-adapter-ports.md` |
146
147
  | `plain-routes.ts` | the plain routes both boots mount and `x routes` lists: `runtime.routes`, then every declared `webhookReceiver()`'s, each once |
147
148
  | `app-openapi.ts` | `openapi.json` (complete when `defineApi({ openapi })` is declared) and each bearer mount's own document; staleness for all of them |
@@ -149,7 +150,7 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
149
150
  | `page-navigation.ts` | the client router for `navigation.client` surfaces — built, routed and named ONCE for `x dev`, the container and the static export; none opted in builds nothing |
150
151
  | `page-speculation.ts` | Speculation Rules for documents WITHOUT the router (`navigation.speculation`): an allow-list of pure-read pages ‡ |
151
152
  | `static-document.ts` | a served `static` page: `304` on `If-None-Match`; container keeps the document (never `x dev`) † |
152
- | `island-{bundle,groups,outputs,build-pool,group-cache,cache-inputs,store,sources,runtime}.ts` / `island-realtime*.ts` / `solid-loader.ts` | islands, named by their final bytes (#1075): one `Bun.build` per route group — islands on exactly the same routes split together, every other alone; groups read from `page.tsx` sources, the one input every caller has before rendering (`islands.sharedChunks` = one group). A group's output is reused from `.x/cache/islands/` while every file it read (Sass partials included), every directory listing it resolved in and the lockfile/tsconfig/`package.json` environment hash the same (`reuse: false` for a determinism test). `islands.vendorSolid` (`island-vendor.ts`, off: a regression on every tracked app) builds Solid once as `vendor-solid.<hash>.js` every island imports; `island-link-check.ts` refuses a merged bundle whose import names bind nothing (#1075's smoke) † |
153
+ | `island-{bundle,groups,outputs,build-pool,group-cache,cache-inputs,store,sources,runtime}.ts` / `island-realtime*.ts` / `solid-loader.ts` | islands, named by their final bytes (#1075): one `Bun.build` per route group — islands on exactly the same routes split together, every other alone; groups read from `page.tsx` sources, known before rendering (`islands.sharedChunks` = one group). A group's output is reused from `.x/cache/islands/` while every file it read (Sass partials too), directory listing it resolved in and lockfile/tsconfig/`package.json` hash unchanged (`reuse: false` for a determinism test). `islands.vendorSolid` (`island-vendor.ts`, off: regressed every tracked app) builds Solid once (`vendor-solid.<hash>.js`) for every island; `island-link-check.ts` refuses a merged bundle whose import names bind nothing (#1075's smoke) † |
153
154
  | `local-cli.ts` / `local-cli-handoff.ts` | a global `x` hands over to the app's own CLI (`local-cli.ts` decides whether; `x upgrade` alone stays when the app's is strictly older — `upgrade-handover.test.ts`) |
154
155
  | `serve-prebuilt.ts` / `serve-prebuilt-paths.ts` | the image's prebuilt store; a boot that built anything logs `X_IMAGE_NOT_PREBUILT` † |
155
156
  | `dev-*.ts` | `x dev` only: dashboard sources, traces, the N+1 ledger, watcher, reload, lock, port |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/cli",
3
- "version": "31.22.3",
3
+ "version": "31.24.0",
4
4
  "description": "The `x` binary: new, dev, build, verify, generate, db, mcp, doctor, deploy",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -53,34 +53,34 @@
53
53
  },
54
54
  "dependencies": {
55
55
  "@babel/core": "^8.0.9",
56
- "@ultimat3/action": "31.22.3",
57
- "@ultimat3/admin": "31.22.3",
58
- "@ultimat3/ai": "31.22.3",
59
- "@ultimat3/auth": "31.22.3",
60
- "@ultimat3/cache": "31.22.3",
61
- "@ultimat3/core": "31.22.3",
62
- "@ultimat3/db": "31.22.3",
63
- "@ultimat3/entity": "31.22.3",
64
- "@ultimat3/flags": "31.22.3",
65
- "@ultimat3/http": "31.22.3",
66
- "@ultimat3/i18n": "31.22.3",
67
- "@ultimat3/jobs": "31.22.3",
68
- "@ultimat3/mail": "31.22.3",
69
- "@ultimat3/manifest": "31.22.3",
70
- "@ultimat3/mcp": "31.22.3",
71
- "@ultimat3/money": "31.22.3",
72
- "@ultimat3/notify": "31.22.3",
73
- "@ultimat3/policy": "31.22.3",
74
- "@ultimat3/pwa": "31.22.3",
75
- "@ultimat3/query": "31.22.3",
76
- "@ultimat3/realtime": "31.22.3",
77
- "@ultimat3/render": "31.22.3",
78
- "@ultimat3/schema": "31.22.3",
79
- "@ultimat3/scraping": "31.22.3",
80
- "@ultimat3/seo": "31.22.3",
81
- "@ultimat3/storage": "31.22.3",
82
- "@ultimat3/testing": "31.22.3",
83
- "@ultimat3/time": "31.22.3",
56
+ "@ultimat3/action": "31.24.0",
57
+ "@ultimat3/admin": "31.24.0",
58
+ "@ultimat3/ai": "31.24.0",
59
+ "@ultimat3/auth": "31.24.0",
60
+ "@ultimat3/cache": "31.24.0",
61
+ "@ultimat3/core": "31.24.0",
62
+ "@ultimat3/db": "31.24.0",
63
+ "@ultimat3/entity": "31.24.0",
64
+ "@ultimat3/flags": "31.24.0",
65
+ "@ultimat3/http": "31.24.0",
66
+ "@ultimat3/i18n": "31.24.0",
67
+ "@ultimat3/jobs": "31.24.0",
68
+ "@ultimat3/mail": "31.24.0",
69
+ "@ultimat3/manifest": "31.24.0",
70
+ "@ultimat3/mcp": "31.24.0",
71
+ "@ultimat3/money": "31.24.0",
72
+ "@ultimat3/notify": "31.24.0",
73
+ "@ultimat3/policy": "31.24.0",
74
+ "@ultimat3/pwa": "31.24.0",
75
+ "@ultimat3/query": "31.24.0",
76
+ "@ultimat3/realtime": "31.24.0",
77
+ "@ultimat3/render": "31.24.0",
78
+ "@ultimat3/schema": "31.24.0",
79
+ "@ultimat3/scraping": "31.24.0",
80
+ "@ultimat3/seo": "31.24.0",
81
+ "@ultimat3/storage": "31.24.0",
82
+ "@ultimat3/testing": "31.24.0",
83
+ "@ultimat3/time": "31.24.0",
84
84
  "babel-preset-solid": "^1.9.16"
85
85
  }
86
86
  }
@@ -1,12 +1,16 @@
1
1
  // `x db recount <entity>.<column>`: the counters `countedIn` declares, compared with the truth and
2
2
  // — with `--write` — set to it. A counter drifts only when its trigger was missing or disabled
3
- // (`X_LIFECYCLE_TRIGGER_MISSING`); this is the repair, and the dry run is the report.
3
+ // (`X_LIFECYCLE_TRIGGER_MISSING`); this is the repair, and the dry run is the report. The parent is
4
+ // walked in key-range windows, one transaction each, so a big table never holds one long lock.
4
5
 
6
+ import { finiteCount } from '@ultimat3/core';
7
+ import type { CounterDescriptionLike, DbClient } from '@ultimat3/db';
5
8
  import {
6
9
  CROSS_TENANT_SETTING,
7
- raw,
8
- recountDriftSql,
9
- recountSql,
10
+ recountBatchSql,
11
+ recountDriftBatchSql,
12
+ recountLockSql,
13
+ recountWindowSql,
10
14
  setLocal,
11
15
  withTransaction,
12
16
  } from '@ultimat3/db';
@@ -27,12 +31,75 @@ import { quoteArg } from './shell-quote';
27
31
  /** Rows of drift a report lists; the count is always whole. */
28
32
  const SHOWN = 50;
29
33
 
34
+ /**
35
+ * Parent rows per window. Each window is one transaction: its row locks are held only while its
36
+ * own statements run, so writers to the rest of the table never wait on the whole sweep.
37
+ */
38
+ export const RECOUNT_BATCH = 1_000;
39
+
30
40
  interface DriftRow {
31
41
  readonly key: string;
32
42
  readonly stored: number;
33
43
  readonly actual: number;
34
44
  }
35
45
 
46
+ export interface RecountReport {
47
+ /** Windows walked, each its own transaction. */
48
+ readonly batches: number;
49
+ readonly drifted: number;
50
+ /** The first `SHOWN` drifted rows, in key order. */
51
+ readonly rows: readonly DriftRow[];
52
+ }
53
+
54
+ /**
55
+ * The sweep: windows of `batch` parent keys in key order. Each transaction locks its window's
56
+ * parent rows, then reads their drift and, with `write`, repairs it; cross-tenant, because a counter is every tenant's and under
57
+ * forced row security an unset tenant would match no row. A dry run writes nothing.
58
+ *
59
+ * Batched directly rather than through `@ultimat3/jobs`' `backfill()`: that factory DECLARES a job
60
+ * at module scope for a worker to run, and this is one operator command over a counter named at
61
+ * run time — no queue, no worker, no ledger row to leave behind.
62
+ */
63
+ export async function recountInBatches(
64
+ client: DbClient,
65
+ parent: string,
66
+ counter: CounterDescriptionLike,
67
+ options: { readonly write: boolean; readonly batch?: number },
68
+ ): Promise<RecountReport> {
69
+ const size = finiteCount('x db recount', 'batch', options.batch ?? RECOUNT_BATCH, 1);
70
+ const rows: DriftRow[] = [];
71
+ let drifted = 0;
72
+ let batches = 0;
73
+ let after: string | null = null;
74
+ for (;;) {
75
+ const from: string | null = after;
76
+ const last: string | null = await withTransaction(
77
+ async (tx): Promise<string | null> => {
78
+ await setLocal(tx, { [CROSS_TENANT_SETTING]: 'on' });
79
+ const [window] = await tx.query<{ last: string | null }>(
80
+ recountWindowSql(parent, counter, from, size),
81
+ );
82
+ const end: string | null = window?.last ?? null;
83
+ if (end === null) return null;
84
+ // Lock first, read after: the drift read and the repair then each see every writer that
85
+ // held one of these rows (`recountLockSql`).
86
+ await tx.query(recountLockSql(parent, counter, from, end));
87
+ const found = await tx.query<DriftRow>(recountDriftBatchSql(parent, counter, from, end));
88
+ if (options.write && found.length > 0) {
89
+ await tx.execute(recountBatchSql(parent, counter, from, end));
90
+ }
91
+ drifted += found.length;
92
+ rows.push(...found.slice(0, SHOWN - rows.length));
93
+ return end;
94
+ },
95
+ { client },
96
+ );
97
+ if (last === null) return { batches, drifted, rows };
98
+ batches += 1;
99
+ after = last;
100
+ }
101
+ }
102
+
36
103
  const refuse = (target: string, reason: string): never => {
37
104
  throw new BadFlagError({
38
105
  flag: 'name',
@@ -88,44 +155,34 @@ async function recount(ctx: CommandContext, root: string): Promise<CommandResult
88
155
  }
89
156
  const started = startDb(services, ctx.env);
90
157
  try {
91
- // One transaction, cross-tenant: a counter is every tenant's, and under forced row security an
92
- // unset tenant would match no row.
93
- const drift = await withTransaction(
94
- async (tx) => {
95
- await setLocal(tx, { [CROSS_TENANT_SETTING]: 'on' });
96
- const rows = await tx.query<DriftRow>(raw(recountDriftSql(parent.$table, counter)));
97
- if (write && rows.length > 0) await tx.execute(raw(recountSql(parent.$table, counter)));
98
- return rows;
99
- },
100
- { client: started.client },
101
- );
158
+ const report = await recountInBatches(started.client, parent.$table, counter, { write });
159
+ const drift = report.rows;
102
160
  return {
103
- ok: findings.length === 0 && (write || drift.length === 0),
161
+ ok: findings.length === 0 && (write || report.drifted === 0),
104
162
  command: 'db',
105
163
  summary: msg(write ? 'cli.db.recount.repaired' : 'cli.db.recount.drift', {
106
164
  target,
107
- count: drift.length,
165
+ count: report.drifted,
108
166
  }),
109
167
  findings: [
110
168
  ...findings,
111
- ...(write || drift.length === 0
169
+ ...(write || report.drifted === 0
112
170
  ? []
113
171
  : [
114
172
  {
115
173
  code: 'X_LIFECYCLE_TRIGGER_MISSING',
116
- cause: `${drift.length} row(s) of ${parent.$table} hold a ${counter.column} that is not the count of ${counter.table} rows pointing at them`,
174
+ cause: `${report.drifted} row(s) of ${parent.$table} hold a ${counter.column} that is not the count of ${counter.table} rows pointing at them`,
117
175
  fix: `x db recount ${quoteArg(target)} --write --json`,
118
176
  },
119
177
  ]),
120
178
  ],
121
- lines: drift
122
- .slice(0, SHOWN)
123
- .map((row) => ` ${row.key} stored ${row.stored} actual ${row.actual}`),
179
+ lines: drift.map((row) => ` ${row.key} stored ${row.stored} actual ${row.actual}`),
124
180
  data: {
125
181
  target,
126
182
  write,
127
- drifted: drift.length,
128
- rows: drift.slice(0, SHOWN).map((row) => ({ ...row })),
183
+ drifted: report.drifted,
184
+ batches: report.batches,
185
+ rows: drift.map((row) => ({ ...row })),
129
186
  },
130
187
  };
131
188
  } finally {
@@ -20,7 +20,7 @@ export const dbSpec: CommandSpec = {
20
20
  name: 'db',
21
21
  summary: 'gen, migrate, reset, seed, studio, branch, backfill, diagnostics, recount',
22
22
  usage:
23
- 'x db gen "add publish_at" | migrate | reset | seed [<name>] [--tier reference|dev] [--dry-run] | seed --generate [--rows n] [--seed n] [--dry-run] | studio | branch list | branch create <name> | branch delete <name> | backfill [<name>|--all] [--write] [--force] | backfill --pending | backfill --list [--name n] [--status s] [--limit n] | diagnostics [--limit n] | recount <entity>.<column> [--write]',
23
+ 'x db gen "add publish_at" [--drop-redundant] | migrate | reset | seed [<name>] [--tier reference|dev] [--dry-run] | seed --generate [--rows n] [--seed n] [--dry-run] | studio | branch list | branch create <name> | branch delete <name> | backfill [<name>|--all] [--write] [--force] | backfill --pending | backfill --list [--name n] [--status s] [--limit n] | diagnostics [--limit n] | recount <entity>.<column> [--write]',
24
24
  requiresApp: true,
25
25
  subcommands: DB_SUBCOMMANDS,
26
26
  // Declared from the constant `runBranchCommand` validates against, never a second literal: it
@@ -118,6 +118,14 @@ export const dbSpec: CommandSpec = {
118
118
  type: 'boolean',
119
119
  summary: 'let x db gen emit a drop whose down cannot restore the rows',
120
120
  },
121
+ // Opt-in, never a default: an index the framework added unasked that another index already
122
+ // leads with (`x doctor` lists them) is dropped concurrently, in a migration you review.
123
+ {
124
+ name: 'drop-redundant',
125
+ type: 'boolean',
126
+ summary: 'gen: drop each implicit index another index already leads with, concurrently',
127
+ subcommands: ['gen'],
128
+ },
121
129
  // Declared because `X_MIGRATION_ROLLING_UNSAFE`'s own fix line names it.
122
130
  {
123
131
  name: 'rolling-unsafe',
package/src/cmd-db.ts CHANGED
@@ -105,6 +105,7 @@ async function runGen(ctx: CommandContext, root: string, name: string): Promise<
105
105
  name,
106
106
  allowDestructive: flagBool(ctx.args, 'allow-destructive'),
107
107
  rollingUnsafe: flagBool(ctx.args, 'rolling-unsafe'),
108
+ dropRedundant: flagBool(ctx.args, 'drop-redundant'),
108
109
  });
109
110
  } catch (error) {
110
111
  return {
package/src/cmd-doctor.ts CHANGED
@@ -17,6 +17,7 @@ import { NO_POOLER_FACT, poolerFindings, withPoolerReport } from './doctor-poole
17
17
  import { doctorPort, portFindings } from './doctor-port';
18
18
  import type { DoctorProbe } from './doctor-probe';
19
19
  import { probeFor } from './doctor-probe';
20
+ import { redundantIndexesProbe, withRedundantIndexes } from './doctor-redundant-indexes';
20
21
  import { rollingSinceProbe, withRollingReminder } from './doctor-rolling';
21
22
  import { sealedKeyFindings } from './doctor-sealed';
22
23
  import { typescriptFindings } from './doctor-typescript';
@@ -168,10 +169,15 @@ export async function reportDoctor(probe: DoctorProbe): Promise<CommandResult> {
168
169
  covered,
169
170
  probe.root === undefined ? NOTHING_MISSING : chartAlertsProbe(probe.root),
170
171
  );
172
+ // The fourth: implicit indexes another already serves (`doctor-redundant-indexes.ts`).
173
+ const indexed = withRedundantIndexes(
174
+ charted,
175
+ probe.root === undefined ? undefined : await redundantIndexesProbe(probe.root),
176
+ );
171
177
  // A reminder, not a finding: the rolling rail is off until this is set (`doctor-rolling.ts`).
172
178
  const reminded = withPoolerReport(
173
179
  withRollingReminder(
174
- charted,
180
+ indexed,
175
181
  probe.root === undefined ? undefined : await rollingSinceProbe(probe.root),
176
182
  ),
177
183
  pooler,
@@ -13,13 +13,14 @@ import {
13
13
  ROLLING_UNSAFE_MARKER,
14
14
  snapshotJson,
15
15
  } from '@ultimat3/db';
16
- import { describeEntities } from '@ultimat3/entity';
16
+ import { registeredEntities } from '@ultimat3/entity';
17
17
  import { describeQueries } from '@ultimat3/query';
18
18
  import { loadApp } from './app-load';
19
19
  import { replicaIdentityTables } from './db-subscribes';
20
20
  import { reconcileSchemaHash, writeSchemaHash } from './drift';
21
21
  import { hashFileName, MIGRATIONS_DIR, readMigrations, snapshotFileName } from './migrations';
22
22
  import type { Finding } from './output';
23
+ import { settledDescriptions } from './redundant-indexes';
23
24
  import { appRowSecurity, type RowSecurityWanted } from './row-security-wanted';
24
25
 
25
26
  export interface GenerateMigrationOptions {
@@ -28,6 +29,12 @@ export interface GenerateMigrationOptions {
28
29
  readonly allowDestructive?: boolean | undefined;
29
30
  /** `x db gen "…" --rolling-unsafe`. A drop never retired, for an app that stops before it starts. */
30
31
  readonly rollingUnsafe?: boolean | undefined;
32
+ /**
33
+ * `x db gen "…" --drop-redundant`. Each implicit index another already leads with
34
+ * (`RegistryEntry.coveredIndexes`) is left out of the diff, so the follow-up drops it
35
+ * concurrently. Never a default; once dropped, a plain run does not rebuild it.
36
+ */
37
+ readonly dropRedundant?: boolean | undefined;
31
38
  /** `database.rowSecurity` and the tenant columns. The app's own unless a test injects one. */
32
39
  readonly rowSecurity?: RowSecurityWanted | undefined;
33
40
  }
@@ -89,7 +96,7 @@ export function migrationSql(migration: GeneratedMigration): string {
89
96
  * snapshot is what it diffs against (`declaredSchema`), so `x db gen` answers the same in CI, on a
90
97
  * laptop with no Postgres running, and against a database three migrations behind.
91
98
  *
92
- * An app that would not load generates nothing. `describeEntities()` is the registry a failed
99
+ * An app that would not load generates nothing. `registeredEntities()` is the registry a failed
93
100
  * import leaves short, and a diff against a short registry is a migration that drops the tables
94
101
  * whose module happened to throw — the one destructive edit no `--allow-destructive` was asked for.
95
102
  */
@@ -112,7 +119,11 @@ export async function generateAppMigration(
112
119
  throw migrationSnapshotMissing(id, join(MIGRATIONS_DIR, snapshotFileName(id)));
113
120
  }
114
121
 
115
- const entities = describeEntities();
122
+ const entities = settledDescriptions(
123
+ registeredEntities(),
124
+ migrations,
125
+ options.dropRedundant === true,
126
+ );
116
127
  // Read AFTER the findings check above, never before: a module that would not import leaves the
117
128
  // registry short, and every `subscribes:` name whose entity lives in that module would then look
118
129
  // like a typo. The refusal below is only sound over a whole registry.
@@ -9,7 +9,7 @@ import { ERROR_DOCS_URL } from '@ultimat3/core';
9
9
  import { GUARD_DIR, guardPaths } from './guards';
10
10
  import { msg } from './messages';
11
11
  import type { CommandResult, Finding, JsonValue } from './output';
12
- import { SHIPPED_GUARD_NAMES, shippedGuardSource } from './templates/scaffold-guards';
12
+ import { SHIPPED_GUARD_NAMES, shippedGuardSources } from './templates/scaffold-guards';
13
13
 
14
14
  export interface MissingGuard {
15
15
  readonly name: string;
@@ -72,8 +72,10 @@ export function differingShippedGuards(held: readonly HeldGuard[]): readonly Dif
72
72
  const differing: DifferingGuard[] = [];
73
73
  for (const { path, source } of held) {
74
74
  const name = path.slice(`${GUARD_DIR}/`.length).replace(/\.tsx?$/, '');
75
- const template = shippedGuardSource(name);
76
- if (template === undefined || sameText(source, template)) continue;
75
+ // An earlier form a shipped guard still accepts (`shippedGuardSources`) is current too.
76
+ const templates = shippedGuardSources(name);
77
+ if (templates.length === 0 || templates.some((template) => sameText(source, template)))
78
+ continue;
77
79
  differing.push({ name, refresh: `x g guard ${name} --force` });
78
80
  }
79
81
  return differing;
@@ -0,0 +1,76 @@
1
+ // `x doctor`'s redundant-index listing: each implicit index the entities describe that another
2
+ // index already leads with, still in the newest migration's snapshot — and the one command that
3
+ // drops them. A LISTING, never a finding: dropping is a reviewed migration the app opts into.
4
+
5
+ import type { SchemaDescription } from '@ultimat3/db';
6
+ import { declaredSchema } from '@ultimat3/db';
7
+ import type { RegistryEntry } from '@ultimat3/entity';
8
+ import { registeredEntities } from '@ultimat3/entity';
9
+ import { loadApp } from './app-load';
10
+ import { msg } from './messages';
11
+ import { readMigrations } from './migrations';
12
+ import type { CommandResult, JsonValue } from './output';
13
+ import { pendingRedundant, type RedundantIndex, redundantIndexes } from './redundant-indexes';
14
+
15
+ /** The command the listing hands out — the flag `cmd-db-spec.ts` declares. */
16
+ export const DROP_REDUNDANT_FIX = 'x db gen "drop redundant indexes" --drop-redundant';
17
+
18
+ export interface RedundantSource {
19
+ readonly entries: readonly RegistryEntry[];
20
+ readonly current: SchemaDescription;
21
+ }
22
+
23
+ /** The registry and the newest snapshot, or `undefined` when either is not there to read. */
24
+ export type ReadRedundantSource = (root: string) => Promise<RedundantSource | undefined>;
25
+
26
+ /** `appEntities`' rule (`schema-drift.ts`): a registry short one module is not "none covered". */
27
+ const appSource: ReadRedundantSource = async (root) => {
28
+ const app = await loadApp(root);
29
+ if (app.findings.length > 0) return undefined;
30
+ const current = declaredSchema(await readMigrations(root));
31
+ return current === undefined ? undefined : { entries: registeredEntities(), current };
32
+ };
33
+
34
+ /** The I/O half. `undefined` when the app would not load or has no snapshot to compare. */
35
+ export async function redundantIndexesProbe(
36
+ root: string,
37
+ read: ReadRedundantSource = appSource,
38
+ ): Promise<readonly RedundantIndex[] | undefined> {
39
+ const source = await read(root);
40
+ if (source === undefined) return undefined;
41
+ return pendingRedundant(redundantIndexes(source.entries), source.current);
42
+ }
43
+
44
+ /** The listing, on a result `x doctor` already decided: `ok` and the findings stay as they came. */
45
+ export function withRedundantIndexes(
46
+ result: CommandResult,
47
+ redundant: readonly RedundantIndex[] | undefined,
48
+ ): CommandResult {
49
+ if (redundant === undefined) return result;
50
+ const data = typeof result.data === 'object' && result.data !== null ? result.data : {};
51
+ const listed: JsonValue = redundant.map(({ table, name, columns, coveredBy }) => ({
52
+ table,
53
+ name,
54
+ columns: [...columns],
55
+ coveredBy,
56
+ }));
57
+ return {
58
+ ...result,
59
+ data: { ...(data as Record<string, JsonValue>), redundantIndexes: listed },
60
+ ...(redundant.length === 0
61
+ ? {}
62
+ : {
63
+ lines: [
64
+ ...(result.lines ?? []),
65
+ msg('cli.doctor.redundantIndexes', {
66
+ count: redundant.length,
67
+ fix: DROP_REDUNDANT_FIX,
68
+ }),
69
+ ...redundant.map(
70
+ ({ table, name, columns, coveredBy }) =>
71
+ ` ${table}.${name} (${columns.join(', ')}) — ${coveredBy}`,
72
+ ),
73
+ ],
74
+ }),
75
+ };
76
+ }
@@ -71,7 +71,6 @@ export const FIX_SEQUENCE_BASELINE: ReadonlyMap<string, number> = new Map([
71
71
  ['packages/db/src/lifecycle-errors.ts', 1],
72
72
  ['packages/db/src/primary-key.ts', 1],
73
73
  ['packages/docs-source/src/errors.ts', 4],
74
- ['packages/entity/src/counter.ts', 1],
75
74
  ['packages/entity/src/partition.ts', 1],
76
75
  ['packages/entity/src/retain.ts', 1],
77
76
  ['packages/jobs/src/subject-errors.ts', 1],
package/src/messages.ts CHANGED
@@ -104,6 +104,9 @@ const CATALOG = {
104
104
  // `x doctor`'s reminder: the rolling rail is off until this key is set (`doctor-rolling.ts`).
105
105
  'cli.doctor.rollingSince':
106
106
  'the rolling-deploy rail is off: set "rollingSince": "{newest}" in x.verify.json to judge every migration after your newest',
107
+ // `x doctor`'s listing: implicit indexes another one already serves (`doctor-redundant-indexes.ts`).
108
+ 'cli.doctor.redundantIndexes':
109
+ '{count} implicit index(es) another index already leads with, each paid for on every write; drop them in a migration you review: {fix}',
107
110
  // `x doctor`'s warnings: beside the verdict on `main`, red on `next` (`doctor-warnings.ts`).
108
111
  'cli.doctor.warnings': '{count} warning(s) — not in the verdict until the next major:',
109
112
  'cli.doctor.warning': ' {code}: {cause} — fix: {fix}',
@@ -0,0 +1,101 @@
1
+ // Single responsibility: which implicit indexes the app's entities describe that another index
2
+ // already serves (`RegistryEntry.coveredIndexes`), and the descriptions `x db gen` diffs with those
3
+ // left out — on `--drop-redundant`, and for good once a migration has dropped one.
4
+
5
+ import type { Migration, SchemaDescription } from '@ultimat3/db';
6
+ import { declaredSchema } from '@ultimat3/db';
7
+ import type { EntityDescription, RegistryEntry } from '@ultimat3/entity';
8
+
9
+ export interface RedundantIndex {
10
+ readonly table: string;
11
+ readonly name: string;
12
+ /** Physical columns, in index order. */
13
+ readonly columns: readonly string[];
14
+ /** The index, primary key or unique invariant that already leads with them. */
15
+ readonly coveredBy: string;
16
+ }
17
+
18
+ /** Every covered implicit index of the registry, in registry order. */
19
+ export const redundantIndexes = (entries: readonly RegistryEntry[]): readonly RedundantIndex[] =>
20
+ entries.flatMap((entry) =>
21
+ (entry.coveredIndexes ?? []).map((index) => ({
22
+ table: entry.tableName,
23
+ name: index.name,
24
+ columns: index.columns,
25
+ coveredBy: index.coveredBy,
26
+ })),
27
+ );
28
+
29
+ /** Each table the snapshot records, to the index names it holds. */
30
+ const recordedIndexes = (current: SchemaDescription): ReadonlyMap<string, ReadonlySet<string>> =>
31
+ new Map(
32
+ current.tables.map((table) => [table.name, new Set(table.indexes.map((index) => index.name))]),
33
+ );
34
+
35
+ /**
36
+ * The covered indexes still in the newest snapshot: what `--drop-redundant` would drop now. A
37
+ * table the snapshot does not hold yet is left out — its first migration has not been written.
38
+ */
39
+ export const pendingRedundant = (
40
+ redundant: readonly RedundantIndex[],
41
+ current: SchemaDescription,
42
+ ): readonly RedundantIndex[] => {
43
+ const recorded = recordedIndexes(current);
44
+ return redundant.filter((index) => recorded.get(index.table)?.has(index.name) === true);
45
+ };
46
+
47
+ /**
48
+ * Each table the newest snapshot holds, to the index names an EARLIER snapshot recorded on it and
49
+ * the newest no longer does: what a migration dropped. Absent from the newest alone is not that —
50
+ * a covered index newly declared on an existing table was never built.
51
+ */
52
+ const droppedIndexes = (
53
+ migrations: readonly Migration[],
54
+ current: SchemaDescription,
55
+ ): ReadonlyMap<string, ReadonlySet<string>> => {
56
+ const recorded = recordedIndexes(current);
57
+ const dropped = new Map<string, Set<string>>();
58
+ for (const migration of migrations) {
59
+ for (const table of migration.snapshot?.tables ?? []) {
60
+ const held = recorded.get(table.name);
61
+ if (held === undefined) continue;
62
+ for (const index of table.indexes) {
63
+ if (held.has(index.name)) continue;
64
+ dropped.set(table.name, (dropped.get(table.name) ?? new Set()).add(index.name));
65
+ }
66
+ }
67
+ }
68
+ return dropped;
69
+ };
70
+
71
+ /**
72
+ * The descriptions to diff. A covered index on a table the newest snapshot holds is left out when
73
+ * `drop` asks for it, or when a migration already dropped it — a plain `x db gen` rebuilding it
74
+ * would undo that review. A NEW table, or a covered index never built, keeps every index:
75
+ * dropping is never a default.
76
+ */
77
+ export const settledDescriptions = (
78
+ entries: readonly RegistryEntry[],
79
+ migrations: readonly Migration[],
80
+ drop: boolean,
81
+ ): readonly EntityDescription[] => {
82
+ const current = declaredSchema(migrations);
83
+ if (current === undefined) return entries.map((entry) => entry.describe());
84
+ const recorded = recordedIndexes(current);
85
+ const dropped = droppedIndexes(migrations, current);
86
+ return entries.map((entry) => {
87
+ const description = entry.describe();
88
+ const held = recorded.get(entry.tableName);
89
+ const gone = dropped.get(entry.tableName);
90
+ const left = new Set(
91
+ (entry.coveredIndexes ?? [])
92
+ .filter((index) => held !== undefined && (drop || gone?.has(index.name) === true))
93
+ .map((index) => index.name),
94
+ );
95
+ if (left.size === 0) return description;
96
+ return {
97
+ ...description,
98
+ indexes: description.indexes.filter((index) => !left.has(index.name)),
99
+ };
100
+ });
101
+ };