@ultimat3/cli 31.23.0 → 31.25.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.
Files changed (57) hide show
  1. package/CLAUDE.md +4 -2
  2. package/README.md +1 -0
  3. package/package.json +29 -29
  4. package/src/cmd-db-recount.ts +81 -24
  5. package/src/cmd-db-spec.ts +9 -1
  6. package/src/cmd-db.ts +1 -0
  7. package/src/cmd-doctor.ts +7 -1
  8. package/src/cmd-generate-spec.ts +3 -2
  9. package/src/cmd-generate.ts +4 -0
  10. package/src/db-diagnostics.ts +6 -0
  11. package/src/db-generate.ts +14 -3
  12. package/src/doctor-guards.ts +5 -3
  13. package/src/doctor-redundant-indexes.ts +76 -0
  14. package/src/fix-sequence.ts +0 -1
  15. package/src/framework-schema.ts +5 -4
  16. package/src/generate-files.ts +10 -0
  17. package/src/generate-invite.ts +195 -0
  18. package/src/generate-kinds.ts +4 -0
  19. package/src/messages.ts +3 -0
  20. package/src/metrics-endpoint.ts +5 -3
  21. package/src/redundant-indexes.ts +101 -0
  22. package/src/retained-assets-boot.ts +28 -15
  23. package/src/role-replicator.ts +26 -4
  24. package/src/role-start.ts +13 -0
  25. package/src/runtime-boot-warnings.ts +65 -0
  26. package/src/runtime-cache.ts +14 -8
  27. package/src/runtime-liveness.ts +23 -0
  28. package/src/schema-drift.ts +5 -2
  29. package/src/serve-boot-warnings.ts +9 -8
  30. package/src/serve.ts +4 -1
  31. package/src/templates/guard-error-declared.ts +48 -11
  32. package/src/templates/guard-repo-unbounded.ts +29 -13
  33. package/src/templates/invite-pages.ts +151 -0
  34. package/src/templates/invite-tests.ts +228 -0
  35. package/src/templates/invite.ts +293 -0
  36. package/src/templates/scaffold-container-compose.ts +3 -2
  37. package/src/templates/scaffold-guards.ts +26 -3
  38. package/src/templates/scaffold-helm-templates.ts +1 -1
  39. package/src/templates/scaffold-repo.ts +1 -0
  40. package/wiki/Auth.md +24 -0
  41. package/wiki/Building-Your-Own-Base.md +20 -0
  42. package/wiki/CLI-Reference.md +7 -1
  43. package/wiki/Entities-And-Migrations.md +6 -2
  44. package/wiki/FAQ.md +2 -2
  45. package/wiki/Home.md +1 -1
  46. package/wiki/Jobs-And-Workflows.md +8 -6
  47. package/wiki/Known-Gaps.md +1 -2
  48. package/wiki/Migrations-And-Backfills.md +1 -1
  49. package/wiki/Observability.md +2 -1
  50. package/wiki/Outbound-HTTP.md +40 -0
  51. package/wiki/Policies-And-Authz.md +52 -20
  52. package/wiki/Realtime.md +18 -1
  53. package/wiki/Scheduled-Tasks.md +1 -1
  54. package/wiki/Shapes.md +3 -2
  55. package/wiki/Testing.md +1 -0
  56. package/wiki/Tutorial-04-Jobs-And-Realtime.md +1 -1
  57. package/wiki/Upgrading.md +2 -0
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` |
@@ -108,6 +109,7 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
108
109
  | `templates/` | every emitted file; `scaffold-*.ts` for `x new`, one per generator otherwise. See history |
109
110
  | `generate-feature-required.ts` | `x g query`/`backfill` with no slice holding an `entity.ts` is `X_FEATURE_REQUIRED` |
110
111
  | `generate-sign-in*.ts` | `x g sign-in`: one flag, no name; OIDC swaps only `x new`'s bytes |
112
+ | `generate-invite*.ts`, `templates/invite*.ts` | `x g invite`: no name; three actions + two pages over `defineMemberInvite` |
111
113
  | `generate-format-written.ts` | the app's Biome over the TypeScript a run created, best effort; `lint` judges |
112
114
  | `templates/scaffold-mcp-{json,endpoint,admin}.ts` | `.mcp.json` (`bunx @ultimat3/cli mcp serve`, never `bunx x`) and the refusing MCP endpoints ‡ |
113
115
 
@@ -149,7 +151,7 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
149
151
  | `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
152
  | `page-speculation.ts` | Speculation Rules for documents WITHOUT the router (`navigation.speculation`): an allow-list of pure-read pages ‡ |
151
153
  | `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) † |
154
+ | `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, reused from `.x/cache/islands/` while every input is unchanged; `island-link-check.ts` refuses a merged bundle whose import names bind nothing † |
153
155
  | `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
156
  | `serve-prebuilt.ts` / `serve-prebuilt-paths.ts` | the image's prebuilt store; a boot that built anything logs `X_IMAGE_NOT_PREBUILT` † |
155
157
  | `dev-*.ts` | `x dev` only: dashboard sources, traces, the N+1 ledger, watcher, reload, lock, port |
package/README.md CHANGED
@@ -218,6 +218,7 @@ app does not hold (`X_SHIPPED_GUARD_MISSING`, beside the verdict, never in it).
218
218
  | `serve.ts` | **what a container starts** — `runRole(options)`, the same boot `x dev` runs minus the watcher, `/_x` and `dev: true`. `x new`'s `apps/web/server.ts` is three lines that call it. `ROLE`, `PORT` and `HOST` are read from `env`; `role`, `port` and `hostname` on `ServeOptions` override each. `ROLE=worker` also retires on SIGUSR2 (`serve-retire.ts`, 25.0.0): stop claiming, finish every held job, abort nothing, drain, exit 0 — what the chart's opt-in `roles.worker.retireSeconds` `preStop` sends; core's `isRetiring()` is true from the signal on, and a SIGTERM mid-retire drains on `drain.workerDeadlineMs` when declared (`lifecycleForRole`); a no-op on Windows ([Deployment](../../wiki/Deployment.md#retiring-a-worker-before-sigterm)) |
219
219
  | `prerender.ts` | `x build --target static`: which `site/` routes qualify, and where the bytes land |
220
220
  | `metrics-endpoint.ts` | the `METRICS_PATH` scrape listener every role opens, on `METRICS_PORT`; opening it starts the `process_*` series, labelled by `startMetricsEndpoint({ role })` |
221
+ | `runtime-liveness.ts` | `/healthz` on `METRICS_PORT`: core's liveness plus every running loop's heartbeat (`@ultimat3/jobs`' `staleLoops`) — 503 on a wedged worker, scheduler or replicator loop; the loop's name only in the `ultimate.liveness.loop-stale` log line |
221
222
  | `role-load.ts` / `document-graph.ts` / `serve-web.ts` | what each container role imports: `web`, `sync` and `replicator` every app module; `worker` and `scheduler` the API index plus every module that reaches no component or stylesheet |
222
223
  | `otlp-export.ts` | the exporters `OTEL_EXPORTER_OTLP_ENDPOINT` switches on, and their drain hooks |
223
224
  | `dev-*.ts` | what `x dev` boots: services, runtime, routes, hooks, roles, the `/_x` mount |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/cli",
3
- "version": "31.23.0",
3
+ "version": "31.25.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.23.0",
57
- "@ultimat3/admin": "31.23.0",
58
- "@ultimat3/ai": "31.23.0",
59
- "@ultimat3/auth": "31.23.0",
60
- "@ultimat3/cache": "31.23.0",
61
- "@ultimat3/core": "31.23.0",
62
- "@ultimat3/db": "31.23.0",
63
- "@ultimat3/entity": "31.23.0",
64
- "@ultimat3/flags": "31.23.0",
65
- "@ultimat3/http": "31.23.0",
66
- "@ultimat3/i18n": "31.23.0",
67
- "@ultimat3/jobs": "31.23.0",
68
- "@ultimat3/mail": "31.23.0",
69
- "@ultimat3/manifest": "31.23.0",
70
- "@ultimat3/mcp": "31.23.0",
71
- "@ultimat3/money": "31.23.0",
72
- "@ultimat3/notify": "31.23.0",
73
- "@ultimat3/policy": "31.23.0",
74
- "@ultimat3/pwa": "31.23.0",
75
- "@ultimat3/query": "31.23.0",
76
- "@ultimat3/realtime": "31.23.0",
77
- "@ultimat3/render": "31.23.0",
78
- "@ultimat3/schema": "31.23.0",
79
- "@ultimat3/scraping": "31.23.0",
80
- "@ultimat3/seo": "31.23.0",
81
- "@ultimat3/storage": "31.23.0",
82
- "@ultimat3/testing": "31.23.0",
83
- "@ultimat3/time": "31.23.0",
56
+ "@ultimat3/action": "31.25.0",
57
+ "@ultimat3/admin": "31.25.0",
58
+ "@ultimat3/ai": "31.25.0",
59
+ "@ultimat3/auth": "31.25.0",
60
+ "@ultimat3/cache": "31.25.0",
61
+ "@ultimat3/core": "31.25.0",
62
+ "@ultimat3/db": "31.25.0",
63
+ "@ultimat3/entity": "31.25.0",
64
+ "@ultimat3/flags": "31.25.0",
65
+ "@ultimat3/http": "31.25.0",
66
+ "@ultimat3/i18n": "31.25.0",
67
+ "@ultimat3/jobs": "31.25.0",
68
+ "@ultimat3/mail": "31.25.0",
69
+ "@ultimat3/manifest": "31.25.0",
70
+ "@ultimat3/mcp": "31.25.0",
71
+ "@ultimat3/money": "31.25.0",
72
+ "@ultimat3/notify": "31.25.0",
73
+ "@ultimat3/policy": "31.25.0",
74
+ "@ultimat3/pwa": "31.25.0",
75
+ "@ultimat3/query": "31.25.0",
76
+ "@ultimat3/realtime": "31.25.0",
77
+ "@ultimat3/render": "31.25.0",
78
+ "@ultimat3/schema": "31.25.0",
79
+ "@ultimat3/scraping": "31.25.0",
80
+ "@ultimat3/seo": "31.25.0",
81
+ "@ultimat3/storage": "31.25.0",
82
+ "@ultimat3/testing": "31.25.0",
83
+ "@ultimat3/time": "31.25.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,
@@ -11,8 +11,9 @@ export const generateSpec: CommandSpec = {
11
11
  // Projected from `GENERATORS`, never restated: the literal that used to live here had already
12
12
  // drifted — it omitted `backfill` — and a usage line that can disagree with the list it
13
13
  // describes is exactly the second source of truth axiom 2 forbids.
14
- // `sign-in` and the two chart generators take no `<name>`, so each is spelled in its own clause.
15
- usage: `x g ${GENERATORS.filter((kind) => kind !== 'sign-in' && !kind.startsWith('chart-')).join('|')} <name> [--feature f] · x g sign-in --password|--oidc <provider> · x g chart-alerts|chart-dashboard [--print]`,
14
+ // `sign-in`, `invite` and the two chart generators take no `<name>`, so each is spelled in its
15
+ // own clause.
16
+ usage: `x g ${GENERATORS.filter((kind) => kind !== 'sign-in' && kind !== 'invite' && !kind.startsWith('chart-')).join('|')} <name> [--feature f] · x g sign-in --password|--oidc <provider> · x g invite · x g chart-alerts|chart-dashboard [--print]`,
16
17
  // Declared from the SAME constant `readKind` validates against: without it `fix-command.ts`
17
18
  // has no set to judge the word after `x g`, and two shipped `@ultimat3/admin` fix lines said
18
19
  // `x g migration` — a generator that has never existed — straight through the `errors` gate.
@@ -20,6 +20,7 @@ import { assertSliceToRead } from './generate-feature-required';
20
20
  import { DEFAULT_APP, generate, sliceDir } from './generate-files';
21
21
  import { followUpEdits } from './generate-follow-ups';
22
22
  import { formatWritten } from './generate-format-written';
23
+ import { runInvite } from './generate-invite';
23
24
  import type { Generator } from './generate-kinds';
24
25
  import { readFeature, readKind, readName, readPermission, readSurface } from './generate-kinds';
25
26
  import { refusePluralTable } from './generate-plural';
@@ -79,6 +80,9 @@ export const generateCommand: CliCommand = {
79
80
  refuseChartAlertsFlags(kind, ctx.args);
80
81
  // One sign-in per app, named by a flag rather than a `<name>`, and edits no other kind makes.
81
82
  if (kind === 'sign-in') return await runSignIn(ctx, root);
83
+ // One invite per app, no `<name>`: the files are `templates/invite.ts`'s, the edits beside them
84
+ // the same follow-ups every generator makes.
85
+ if (kind === 'invite') return await runInvite(ctx, root);
82
86
  // One chart per app, named by its `Chart.yaml`: the same shape, for the same reason.
83
87
  if (isChartGenerator(kind)) return await runChartAlerts(ctx, root, kind);
84
88
  // A workspace, not a slice: no feature, no surface, no follow-up edit (`generate-workspace.ts`).
@@ -2,6 +2,7 @@
2
2
  // `dbDiagnostics()` and renders one table per answered section. Facts, never a verdict: exit 0
3
3
  // whatever they say, and the one failure is a connection that never opens (`X_DB_UNAVAILABLE`).
4
4
 
5
+ import { baseClient, dbClientInstalled, setDbClient } from '@ultimat3/db';
5
6
  import {
6
7
  type DbDiagnostics,
7
8
  type DiagnosticSection,
@@ -88,6 +89,10 @@ export async function runDiagnostics(ctx: CommandContext, root: string): Promise
88
89
  });
89
90
  }
90
91
  }
92
+ // `startDb` installs its client as the process's `db()`, and this command closes it: what was
93
+ // there before goes back, or every later `db()` in an embedding process reaches a dead pool.
94
+ // `undefined` when nothing was installed, which restores lazy construction rather than building it.
95
+ const previous = dbClientInstalled() ? baseClient() : undefined;
91
96
  const started = startDb(services, ctx.env);
92
97
  try {
93
98
  // Embedded, the probe IS the boot — a WASM compile and an initdb, 12.6 s cold under coverage —
@@ -107,6 +112,7 @@ export async function runDiagnostics(ctx: CommandContext, root: string): Promise
107
112
  data: diagnosticsJson(report),
108
113
  };
109
114
  } finally {
115
+ setDbClient(previous);
110
116
  await started.client.close();
111
117
  await started.replica?.close();
112
118
  }
@@ -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],
@@ -24,7 +24,7 @@ import {
24
24
  } from '@ultimat3/auth/schema';
25
25
  import { FAILURES_TABLE, SQL_FAILURES_TABLE, type TableStorage } from '@ultimat3/db';
26
26
  import { RATE_LIMIT_STORAGE, SQL_RATE_LIMIT_TABLE } from '@ultimat3/http';
27
- import { JOBS_TABLE_STORAGE, SQL_JOBS_TABLE } from '@ultimat3/jobs';
27
+ import { JOBS_STORAGE, SQL_JOBS_TABLE } from '@ultimat3/jobs';
28
28
  import { MCP_CONFIRMATIONS_TABLE, SQL_MCP_CONFIRMATIONS_TABLE } from '@ultimat3/mcp/schema';
29
29
  import {
30
30
  PUSH_DEVICES_TABLE,
@@ -82,9 +82,10 @@ export const FRAMEWORK_SCHEMA: readonly FrameworkSchema[] = Object.freeze([
82
82
  'x_job_counters',
83
83
  ]),
84
84
  ddl: Object.freeze([SQL_JOBS_TABLE]),
85
- // Fillfactor 80: the room a lease renewal's HOT update needs. Drift is what reports a hand
86
- // `alter table x_jobs reset (fillfactor)` — the apply never rewrites a table it made.
87
- storage: Object.freeze([JOBS_TABLE_STORAGE]),
85
+ // x_jobs at fillfactor 80, the room a lease renewal's HOT update needs, and the small hot
86
+ // tables' autovacuum triggers. Drift is what reports a hand `alter table … reset (…)` between
87
+ // two boots; the next apply converges it.
88
+ storage: JOBS_STORAGE,
88
89
  }),
89
90
  Object.freeze({
90
91
  pkg: '@ultimat3/action',
@@ -32,6 +32,7 @@ import { helmDashboardFiles } from './templates/chart-dashboard';
32
32
  import { cronJobFiles } from './templates/generate-cron-job';
33
33
  import { purgeFiles } from './templates/generate-purge';
34
34
  import { webhookReceiverFiles } from './templates/generate-webhook-receiver';
35
+ import { inviteFiles } from './templates/invite';
35
36
  import { helmMonitoringFiles } from './templates/scaffold-helm-alerts';
36
37
  import { oidcSignInFiles } from './templates/sign-in-oidc';
37
38
  import { passwordSignInFiles } from './templates/sign-in-password';
@@ -276,6 +277,15 @@ export function generate(options: GenerateOptions): readonly GeneratedFile[] {
276
277
  : oidcSignInFiles(signIn.provider, shape),
277
278
  );
278
279
  }
280
+ case 'invite':
281
+ // The invite's own files only; the grant, the exercise entries and the API listing are
282
+ // `generate-invite.ts`'s follow-ups, read off the app's disk.
283
+ return dedupe(
284
+ inviteFiles({
285
+ locales: options.locales ?? ['en'],
286
+ ...(options.catalogModule === undefined ? {} : { catalogModule: options.catalogModule }),
287
+ }),
288
+ );
279
289
  case 'app':
280
290
  case 'package': {
281
291
  // `run` reads the scope off the root manifest (`generate-workspace.ts`); a direct caller