@ultimat3/cli 31.24.0 → 31.26.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
@@ -109,6 +109,7 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
109
109
  | `templates/` | every emitted file; `scaffold-*.ts` for `x new`, one per generator otherwise. See history |
110
110
  | `generate-feature-required.ts` | `x g query`/`backfill` with no slice holding an `entity.ts` is `X_FEATURE_REQUIRED` |
111
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` |
112
113
  | `generate-format-written.ts` | the app's Biome over the TypeScript a run created, best effort; `lint` judges |
113
114
  | `templates/scaffold-mcp-{json,endpoint,admin}.ts` | `.mcp.json` (`bunx @ultimat3/cli mcp serve`, never `bunx x`) and the refusing MCP endpoints ‡ |
114
115
 
@@ -150,7 +151,7 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
150
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 |
151
152
  | `page-speculation.ts` | Speculation Rules for documents WITHOUT the router (`navigation.speculation`): an allow-list of pure-read pages ‡ |
152
153
  | `static-document.ts` | a served `static` page: `304` on `If-None-Match`; container keeps the document (never `x dev`) † |
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) † |
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 † |
154
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`) |
155
156
  | `serve-prebuilt.ts` / `serve-prebuilt-paths.ts` | the image's prebuilt store; a boot that built anything logs `X_IMAGE_NOT_PREBUILT` † |
156
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.24.0",
3
+ "version": "31.26.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.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",
56
+ "@ultimat3/action": "31.26.0",
57
+ "@ultimat3/admin": "31.26.0",
58
+ "@ultimat3/ai": "31.26.0",
59
+ "@ultimat3/auth": "31.26.0",
60
+ "@ultimat3/cache": "31.26.0",
61
+ "@ultimat3/core": "31.26.0",
62
+ "@ultimat3/db": "31.26.0",
63
+ "@ultimat3/entity": "31.26.0",
64
+ "@ultimat3/flags": "31.26.0",
65
+ "@ultimat3/http": "31.26.0",
66
+ "@ultimat3/i18n": "31.26.0",
67
+ "@ultimat3/jobs": "31.26.0",
68
+ "@ultimat3/mail": "31.26.0",
69
+ "@ultimat3/manifest": "31.26.0",
70
+ "@ultimat3/mcp": "31.26.0",
71
+ "@ultimat3/money": "31.26.0",
72
+ "@ultimat3/notify": "31.26.0",
73
+ "@ultimat3/policy": "31.26.0",
74
+ "@ultimat3/pwa": "31.26.0",
75
+ "@ultimat3/query": "31.26.0",
76
+ "@ultimat3/realtime": "31.26.0",
77
+ "@ultimat3/render": "31.26.0",
78
+ "@ultimat3/schema": "31.26.0",
79
+ "@ultimat3/scraping": "31.26.0",
80
+ "@ultimat3/seo": "31.26.0",
81
+ "@ultimat3/storage": "31.26.0",
82
+ "@ultimat3/testing": "31.26.0",
83
+ "@ultimat3/time": "31.26.0",
84
84
  "babel-preset-solid": "^1.9.16"
85
85
  }
86
86
  }
@@ -6,11 +6,14 @@
6
6
  import { finiteCount } from '@ultimat3/core';
7
7
  import type { CounterDescriptionLike, DbClient } from '@ultimat3/db';
8
8
  import {
9
+ baseClient,
9
10
  CROSS_TENANT_SETTING,
11
+ dbClientInstalled,
10
12
  recountBatchSql,
11
13
  recountDriftBatchSql,
12
14
  recountLockSql,
13
15
  recountWindowSql,
16
+ setDbClient,
14
17
  setLocal,
15
18
  withTransaction,
16
19
  } from '@ultimat3/db';
@@ -153,6 +156,9 @@ async function recount(ctx: CommandContext, root: string): Promise<CommandResult
153
156
  });
154
157
  }
155
158
  }
159
+ // `startDb` installs its client as the process's `db()`, and this command closes it: what was
160
+ // there before goes back (`undefined`: lazy construction), as `db-diagnostics.ts` does.
161
+ const previous = dbClientInstalled() ? baseClient() : undefined;
156
162
  const started = startDb(services, ctx.env);
157
163
  try {
158
164
  const report = await recountInBatches(started.client, parent.$table, counter, { write });
@@ -186,6 +192,7 @@ async function recount(ctx: CommandContext, root: string): Promise<CommandResult
186
192
  },
187
193
  };
188
194
  } finally {
195
+ setDbClient(previous);
189
196
  await started.client.close();
190
197
  await started.replica?.close();
191
198
  }
@@ -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
  }
package/src/dispatch.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  // why: a synchronous bin probe at the one place a result is rendered; Bun has no path helpers.
6
6
  import { existsSync } from 'node:fs';
7
7
  import { dirname, isAbsolute, join, resolve } from 'node:path';
8
- import { setLogStream } from '@ultimat3/core';
8
+ import { currentLogStream, setLogStream } from '@ultimat3/core';
9
9
  import { requireAppRoot, requireBunVersion } from './app-root';
10
10
  import { createHelpCommand } from './cmd-help';
11
11
  import { plannedCommandError, plannedCommandFor } from './cmd-planned';
@@ -166,6 +166,9 @@ export async function dispatch(options: DispatchOptions): Promise<number> {
166
166
  ...(options.invocation === undefined ? {} : { invocation: options.invocation }),
167
167
  };
168
168
 
169
+ // Put back in the `finally`: the stream is process-wide, so a dispatch that left `stderr` behind
170
+ // moved every later line of an embedding process — the next test file's, on a shared worker.
171
+ const callerStream = currentLogStream();
169
172
  try {
170
173
  // `--json` means fd 1 carries ONE document, and every command that boots an app logs through
171
174
  // core's module-scope `logger`, whose default writer is stdout: `x db migrate --json` printed
@@ -197,5 +200,7 @@ export async function dispatch(options: DispatchOptions): Promise<number> {
197
200
  const result = errorResult(args.command, error);
198
201
  sinkFor(result, options)(render(result, args.json, false, reader));
199
202
  return 1;
203
+ } finally {
204
+ setLogStream(callerStream);
200
205
  }
201
206
  }
@@ -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',
@@ -123,6 +123,10 @@ export const FACTORY_GENERATORS: readonly FactoryGenerator[] = [
123
123
  none: 'one signed delivery to an endpoint the app stores, with its ledger; deferred (plan 101 U6) until x g plants the endpoint table and the ledger it needs',
124
124
  },
125
125
  { factory: 'webhookReceiver', generator: 'webhook-receiver' },
126
+ {
127
+ factory: 'inboundMail',
128
+ none: 'a receiver over a provider the app has an account with — which provider, its secret and where a message goes are choices x g cannot read off the disk; the wiki Mail page has the one call to paste',
129
+ },
126
130
  ];
127
131
 
128
132
  /** `x g llm` or `x g agent-job`: the factory a word names, when it is one no generator writes. */
@@ -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
@@ -0,0 +1,195 @@
1
+ // `x g invite`: the member invite's files written through the one writer (`writeFiles` — a second
2
+ // run conflicts and writes nothing), then the edits outside them: `member:invite` granted to
3
+ // `admin`, the three actions listed in the API index, and each one's exercise entry turned off
4
+ // with its reason, so the app's next `x verify` is green. No name and no flag: one invite per app.
5
+
6
+ import { indexBindingFindings } from './api-registration';
7
+ import { generateSpec } from './cmd-generate-spec';
8
+ import type { CommandContext } from './command';
9
+ import { invocationOf } from './command';
10
+ import { BadFlagError } from './errors';
11
+ import { localiseCatalogs, namedOrAppLocales } from './generate-catalog-locales';
12
+ import { appDisk, plannedDisk } from './generate-disk';
13
+ import { writtenExercises } from './generate-exercise';
14
+ import { generate } from './generate-files';
15
+ import { followUpEdits } from './generate-follow-ups';
16
+ import { formatWritten } from './generate-format-written';
17
+ import { appManifestIfAny, existingArtifacts } from './generate-sign-in-manifest';
18
+ import { planWrites, writeFiles } from './generate-write';
19
+ import { resolveDbModule } from './handle-registration';
20
+ import { resolveCatalogModule } from './i18n-audit';
21
+ import { msg } from './messages';
22
+ import type { CommandResult } from './output';
23
+ import { flagBool, flagList, type ParsedArgs } from './parse';
24
+ import { resolveLocales } from './templates';
25
+ import { withDependency } from './workspace-dep-edit';
26
+
27
+ const KIND = 'invite';
28
+
29
+ /** The `x g` flags this generator reads; any other one would change nothing, so is refused. */
30
+ const READS = new Set(['force', 'dry-run', 'locales', 'json']);
31
+
32
+ /** No `<name>` and no flag it ignores: a second spelling of one command is refused, not dropped. */
33
+ export function refuseInviteArgs(args: ParsedArgs): void {
34
+ const named = args.positionals[1];
35
+ if (named !== undefined) {
36
+ throw new BadFlagError({
37
+ flag: 'name',
38
+ command: 'g invite',
39
+ reason: `an app has one member invite, so "${named}" names nothing`,
40
+ fix: 'x g invite',
41
+ });
42
+ }
43
+ for (const flag of generateSpec.flags ?? []) {
44
+ if (READS.has(flag.name)) continue;
45
+ const value = args.flags.get(flag.name);
46
+ if (value === undefined || value === flag.default) continue;
47
+ throw new BadFlagError({
48
+ flag: flag.name,
49
+ command: 'g invite',
50
+ reason: `the invite generator does not read --${flag.name}, so it would change nothing`,
51
+ fix: 'x g invite',
52
+ });
53
+ }
54
+ }
55
+
56
+ const ROOT_MANIFEST = 'package.json';
57
+ const MAIL_PACKAGE = '@ultimat3/mail';
58
+
59
+ /**
60
+ * The root manifest with `@ultimat3/mail` declared at the range the app already holds
61
+ * `@ultimat3/auth` at — the invite mails. `x new` declares it from this release on; the edit is for an
62
+ * app scaffolded before that. `undefined` when it is
63
+ * declared already, or the manifest is not one this can read; `package-shape` then names the line.
64
+ */
65
+ async function mailDependency(root: string): Promise<string | undefined> {
66
+ const text = await appDisk(root).read(ROOT_MANIFEST);
67
+ if (text === undefined) return undefined;
68
+ let parsed: unknown;
69
+ try {
70
+ parsed = JSON.parse(text);
71
+ } catch {
72
+ return undefined;
73
+ }
74
+ const deps =
75
+ typeof parsed === 'object' && parsed !== null && 'dependencies' in parsed
76
+ ? (parsed as { readonly dependencies?: unknown }).dependencies
77
+ : undefined;
78
+ const range =
79
+ typeof deps === 'object' && deps !== null
80
+ ? (deps as Readonly<Record<string, unknown>>)['@ultimat3/auth']
81
+ : undefined;
82
+ return typeof range === 'string' ? withDependency(text, MAIL_PACKAGE, range) : undefined;
83
+ }
84
+
85
+ export async function runInvite(ctx: CommandContext, root: string): Promise<CommandResult> {
86
+ refuseInviteArgs(ctx.args);
87
+ const catalogModule = await resolveCatalogModule(root);
88
+ const dbModule = await resolveDbModule(root);
89
+ const locales = resolveLocales(await namedOrAppLocales(root, flagList(ctx.args, 'locales')));
90
+ const files = await localiseCatalogs(
91
+ root,
92
+ generate({
93
+ kind: KIND,
94
+ name: KIND,
95
+ locales,
96
+ ...(catalogModule === undefined ? {} : { catalogModule }),
97
+ }),
98
+ );
99
+ const invocation = [invocationOf(ctx, 'g'), KIND].join(' ');
100
+ const force = flagBool(ctx.args, 'force');
101
+ // An app already binding `inviteMember` in its API index is refused before anything lands.
102
+ const bindings = await indexBindingFindings(
103
+ root,
104
+ files.map((file) => file.path),
105
+ `${invocation} # after renaming what apps/web/api/index.ts already binds under that name`,
106
+ );
107
+
108
+ if (flagBool(ctx.args, 'dry-run')) {
109
+ const plan = await planWrites(root, files, force, invocation, KIND);
110
+ const planned = new Map(
111
+ files.flatMap((file) =>
112
+ plan.written.includes(file.path) && typeof file.contents === 'string'
113
+ ? [[file.path, file.contents] as const]
114
+ : [],
115
+ ),
116
+ );
117
+ const refused = [...plan.conflicts, ...bindings];
118
+ const follow =
119
+ refused.length > 0
120
+ ? { edited: [], findings: [] }
121
+ : await followUpEdits(
122
+ root,
123
+ plan.written,
124
+ dbModule,
125
+ plannedDisk(root, planned),
126
+ writtenExercises(files, plan.written),
127
+ );
128
+ const manifest = refused.length > 0 ? undefined : await mailDependency(root);
129
+ const touched =
130
+ refused.length > 0
131
+ ? []
132
+ : [
133
+ ...new Set([
134
+ ...plan.written,
135
+ ...follow.edited,
136
+ ...(manifest === undefined ? [] : [ROOT_MANIFEST]),
137
+ ]),
138
+ ];
139
+ const findings = [...refused, ...follow.findings];
140
+ return {
141
+ ok: findings.length === 0,
142
+ command: 'g',
143
+ summary: msg('cli.generate.planned', { count: touched.length, kind: KIND, name: KIND }),
144
+ data: {
145
+ files: touched,
146
+ ...(touched.length === 0 ? {} : { refreshes: [...(await existingArtifacts(root))] }),
147
+ dryRun: true,
148
+ },
149
+ lines: touched.map((path) => msg('cli.file.added', { path })),
150
+ findings,
151
+ };
152
+ }
153
+
154
+ const report =
155
+ bindings.length > 0
156
+ ? { written: [], conflicts: bindings }
157
+ : await writeFiles(root, files, force, invocation, KIND);
158
+ if (report.conflicts.length > 0) {
159
+ return {
160
+ ok: false,
161
+ command: 'g',
162
+ summary: msg('cli.generate.wrote', { count: 0, kind: KIND, name: KIND }),
163
+ data: { files: [] },
164
+ findings: report.conflicts,
165
+ };
166
+ }
167
+ const manifest = await mailDependency(root);
168
+ if (manifest !== undefined) await appDisk(root).write(ROOT_MANIFEST, manifest);
169
+ const follow = await followUpEdits(
170
+ root,
171
+ report.written,
172
+ dbModule,
173
+ appDisk(root),
174
+ writtenExercises(files, report.written),
175
+ );
176
+ await formatWritten(root, report.written, ctx.runner);
177
+ const refreshed = await appManifestIfAny(root);
178
+ const written = [
179
+ ...new Set([
180
+ ...report.written,
181
+ ...(manifest === undefined ? [] : [ROOT_MANIFEST]),
182
+ ...follow.edited,
183
+ ...refreshed.written,
184
+ ]),
185
+ ];
186
+ const findings = [...follow.findings, ...refreshed.findings];
187
+ return {
188
+ ok: findings.length === 0,
189
+ command: 'g',
190
+ summary: msg('cli.generate.wrote', { count: written.length, kind: KIND, name: KIND }),
191
+ data: { files: written },
192
+ lines: written.map((path) => msg('cli.file.added', { path })),
193
+ findings,
194
+ };
195
+ }
@@ -34,6 +34,8 @@ export const GENERATORS = [
34
34
  'admin:page',
35
35
  'guard',
36
36
  'sign-in',
37
+ // The member invite over `defineMemberInvite`: one per app, no `<name>` (`generate-invite.ts`).
38
+ 'invite',
37
39
  'chart-alerts',
38
40
  'chart-dashboard',
39
41
  'app',
@@ -300,6 +302,8 @@ const EXAMPLE_NAME: Readonly<Record<Generator, string>> = {
300
302
  guard: 'migration-safety',
301
303
  // Sign-in takes no name: its "example" is the flag that picks a shape, so the line still runs.
302
304
  'sign-in': '--password',
305
+ // No name and no flag: the example is the bare command, and `--json` keeps the line runnable.
306
+ invite: '--json',
303
307
  // No name either: an app has one chart. `--print` runs with or without one.
304
308
  'chart-alerts': '--print',
305
309
  'chart-dashboard': '--print',
@@ -8,7 +8,6 @@ import {
8
8
  BUILD_ID_HEADER,
9
9
  finiteCount,
10
10
  type HealthPayload,
11
- healthzPayload,
12
11
  logger,
13
12
  METRICS_CONTENT_TYPE,
14
13
  METRICS_PATH,
@@ -20,6 +19,7 @@ import {
20
19
  UltimateError,
21
20
  } from '@ultimat3/core';
22
21
  import { neighbouringPort, PORT_RANGE, syncPortFor } from './flag-number';
22
+ import { livenessPayload } from './runtime-liveness';
23
23
  import { quoteArg } from './shell-quote';
24
24
 
25
25
  /**
@@ -211,7 +211,8 @@ export interface MetricsEndpoint {
211
211
 
212
212
  /**
213
213
  * `/healthz` and `/readyz` for the roles whose only socket this is — `worker`, `scheduler`,
214
- * `replicator` — so the replicator's readiness check (`role-replicator.ts`) is read by a probe.
214
+ * `replicator` — so the replicator's readiness check (`role-replicator.ts`) is read by a probe, and
215
+ * `/healthz` is their LIVENESS: 503 once any running loop's heartbeat is past its bound.
215
216
  * The verdict only, never the report: this port is unauthenticated, and check names are topology.
216
217
  */
217
218
  function healthResponse(payload: HealthPayload, role: string, buildId: string | null): Response {
@@ -262,7 +263,8 @@ export function startMetricsEndpoint(options: MetricsEndpointOptions = {}): Metr
262
263
  fetch(request: Request): Response {
263
264
  const url = new URL(request.url);
264
265
  const role = options.role ?? 'unknown';
265
- if (url.pathname === '/healthz') return healthResponse(healthzPayload(), role, buildId);
266
+ // Liveness reads the loops' heartbeats (`runtime-liveness.ts`): the probe a wedge fails.
267
+ if (url.pathname === '/healthz') return healthResponse(livenessPayload(), role, buildId);
266
268
  if (url.pathname === '/readyz') {
267
269
  return healthResponse(
268
270
  readyzPayload({ deep: url.searchParams.get('deep') === '1' }),
@@ -10,6 +10,7 @@ import {
10
10
  renderThrowable,
11
11
  } from '@ultimat3/core';
12
12
  import { describeEntities } from '@ultimat3/entity';
13
+ import { loopHeartbeat } from '@ultimat3/jobs';
13
14
  import { ReplicatorSlotHeldError } from '@ultimat3/realtime';
14
15
  import type { Replicator, ReplicatorOptions, Transport } from '@ultimat3/realtime/server';
15
16
  import {
@@ -107,6 +108,13 @@ const noEntitiesRefusal = (dev: boolean): BadFlagError | ConfigInvalidError =>
107
108
  meta: { role: 'replicator' },
108
109
  });
109
110
 
111
+ /**
112
+ * The replicator's tick for its heartbeat: the feed's status interval (10 s), the longest a live
113
+ * walsender stays silent. Event-driven — a quiet feed is healthy — so only a change held open past
114
+ * the bound (`livenessBoundMs`) is a wedge: a publish that never returns.
115
+ */
116
+ const REPLICATOR_TICK_MS = 10_000;
117
+
110
118
  /** The name `/readyz` reports the replicator under. */
111
119
  export const REPLICATOR_READINESS_CHECK = 'replicator';
112
120
 
@@ -174,10 +182,15 @@ export async function startReplicator(options: StartReplicatorOptions): Promise<
174
182
  const selection = selectChangeFeed(options.env, { entities });
175
183
  const slot = selection.slot ?? '';
176
184
  const key = replicatorLockKey(slot);
185
+ const heartbeat = loopHeartbeat('realtime.replicator', {
186
+ tickMs: REPLICATOR_TICK_MS,
187
+ periodic: false,
188
+ });
177
189
  const replicator = (options.create ?? changeFeedReplicator)({
178
190
  feed: selection.feed,
179
191
  transport: options.transport,
180
192
  lock: selection.lock,
193
+ heartbeat,
181
194
  });
182
195
  // `start()` answers `false` for the one condition that is not this process's fault: another
183
196
  // process holds the lock. A dev boot has nothing to fail over to, so it is terminal there, with
@@ -186,10 +199,18 @@ export async function startReplicator(options: StartReplicatorOptions): Promise<
186
199
  // terminated the old holder, so every rollout stalled (`replicator.ts`'s header: the loser stays
187
200
  // up, unready).
188
201
  let cancelStandby = (): void => undefined;
189
- if (!(await replicator.start())) {
190
- if (options.dev) throw new ReplicatorSlotHeldError({ key });
191
- logger.warn('replicator.standby', { key, detail: 'another process holds the slot' });
192
- cancelStandby = standBy(replicator, key);
202
+ // Started BEFORE the feed: a change the feed delivers while it starts opens a pass, and a start
203
+ // after it would clear that pass. Judged by `/healthz` on the scrape port (`runtime-liveness.ts`).
204
+ heartbeat.start();
205
+ try {
206
+ if (!(await replicator.start())) {
207
+ if (options.dev) throw new ReplicatorSlotHeldError({ key });
208
+ logger.warn('replicator.standby', { key, detail: 'another process holds the slot' });
209
+ cancelStandby = standBy(replicator, key);
210
+ }
211
+ } catch (error) {
212
+ heartbeat.stop();
213
+ throw error;
193
214
  }
194
215
  const unregister = watchReplicatorReadiness(replicator);
195
216
  return {
@@ -201,6 +222,7 @@ export async function startReplicator(options: StartReplicatorOptions): Promise<
201
222
  // ask for a slot after the role that wanted it has gone.
202
223
  cancelStandby();
203
224
  unregister();
225
+ heartbeat.stop();
204
226
  await replicator.stop();
205
227
  },
206
228
  };
@@ -0,0 +1,23 @@
1
+ // Single responsibility: the LIVENESS answer of the roles whose only socket is the scrape port —
2
+ // `worker`, `scheduler`, `replicator`. Core's `/healthz` (503 once stopped) plus every running
3
+ // loop's heartbeat (`@ultimat3/jobs`' `staleLoops`): a loop past its bound is a wedged process
4
+ // the kubelet must restart, even while its event loop still answers every scrape.
5
+
6
+ import { type HealthPayload, healthzPayload, logger } from '@ultimat3/core';
7
+ import { staleLoops } from '@ultimat3/jobs';
8
+
9
+ /**
10
+ * `/healthz` on `METRICS_PORT`. The answer carries no loop name — that port is unauthenticated and
11
+ * names are topology — so the log line is where an operator reads which loop, why and how long.
12
+ * `/readyz` never reads loops: a wedge is a restart, never a traffic decision.
13
+ */
14
+ export function livenessPayload(): HealthPayload {
15
+ const health = healthzPayload();
16
+ if (!health.ok) return health;
17
+ const stale = staleLoops();
18
+ if (stale.length === 0) return health;
19
+ logger.error('ultimate.liveness.loop-stale', {
20
+ loops: stale.map((loop) => `${loop.name} ${loop.reason} ${loop.ageMs}ms > ${loop.boundMs}ms`),
21
+ });
22
+ return { ok: false, status: 503, body: health.body };
23
+ }