@ultimat3/cli 31.16.0 → 31.18.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 (77) hide show
  1. package/README.md +11 -2
  2. package/package.json +29 -29
  3. package/src/cache-graph.ts +67 -0
  4. package/src/cmd-cache-spec.ts +25 -0
  5. package/src/cmd-cache.ts +187 -0
  6. package/src/cmd-config-spec.ts +23 -0
  7. package/src/cmd-config.ts +61 -0
  8. package/src/cmd-doctor.ts +3 -3
  9. package/src/cmd-exercise.ts +34 -10
  10. package/src/cmd-explain-spec.ts +24 -0
  11. package/src/cmd-explain.ts +201 -0
  12. package/src/cmd-generate-spec.ts +3 -3
  13. package/src/cmd-generate.ts +2 -2
  14. package/src/cmd-logs-spec.ts +34 -0
  15. package/src/cmd-logs.ts +80 -0
  16. package/src/cmd-planned.ts +15 -29
  17. package/src/cmd-token-spec.ts +54 -0
  18. package/src/cmd-token.ts +173 -0
  19. package/src/cmd-verify-spec.ts +13 -3
  20. package/src/cmd-verify.ts +2 -0
  21. package/src/config-redact.ts +39 -0
  22. package/src/dev-boot-data-dir.ts +69 -0
  23. package/src/dev-boot.ts +26 -13
  24. package/src/doctor-chart-alerts.ts +50 -22
  25. package/src/error-codes-tooling.ts +6 -4
  26. package/src/error-codes.ts +2 -0
  27. package/src/errors.ts +8 -2
  28. package/src/exercise-entry-edit.ts +5 -1
  29. package/src/exercise-routes.ts +59 -0
  30. package/src/explain-capture.ts +38 -0
  31. package/src/generate-chart-alerts.ts +99 -45
  32. package/src/generate-exercise.ts +2 -2
  33. package/src/generate-factories.ts +133 -0
  34. package/src/generate-files.ts +15 -0
  35. package/src/generate-kinds.ts +15 -0
  36. package/src/mcp-db-target.ts +4 -3
  37. package/src/mcp-errors.ts +4 -0
  38. package/src/messages-gate.ts +2 -0
  39. package/src/messages-ops.ts +32 -0
  40. package/src/messages-upgrade.ts +1 -0
  41. package/src/messages.ts +4 -0
  42. package/src/otlp-export.ts +16 -2
  43. package/src/registry.ts +10 -0
  44. package/src/role-start.ts +11 -5
  45. package/src/runtime-services.ts +35 -19
  46. package/src/serve-boot-phases.ts +30 -0
  47. package/src/serve-boot-warnings.ts +62 -0
  48. package/src/serve-boot.ts +30 -11
  49. package/src/templates/chart-dashboard.ts +245 -0
  50. package/src/templates/generate-cron-job.ts +90 -0
  51. package/src/templates/generate-purge.ts +93 -0
  52. package/src/templates/generate-webhook-receiver.ts +274 -0
  53. package/src/templates/github/ci.yml.ts +101 -36
  54. package/src/templates/guard-repo-raw-sql-test.ts +174 -0
  55. package/src/templates/guard-repo-raw-sql.ts +115 -145
  56. package/src/templates/guard-unbounded-fanout.ts +170 -0
  57. package/src/templates/scaffold-claude-commands.ts +3 -2
  58. package/src/templates/scaffold-docs.ts +3 -2
  59. package/src/templates/scaffold-guards.ts +3 -0
  60. package/src/templates/scaffold-helm-alert-rules.ts +160 -0
  61. package/src/templates/scaffold-helm-alerts.ts +22 -87
  62. package/src/templates/scaffold-helm-templates.ts +2 -0
  63. package/src/templates/scaffold-helm.ts +20 -4
  64. package/src/upgrade-gate.ts +18 -6
  65. package/src/upgrade-report.ts +4 -0
  66. package/src/verify-plan.ts +127 -0
  67. package/wiki/Admin-Dashboard.md +6 -2
  68. package/wiki/CI-Parallel-Gate.md +38 -1
  69. package/wiki/CLI-Reference.md +95 -14
  70. package/wiki/Caching-And-Invalidation.md +10 -10
  71. package/wiki/Configuration.md +4 -2
  72. package/wiki/Known-Gaps.md +1 -1
  73. package/wiki/MCP-And-AI.md +1 -1
  74. package/wiki/Observability.md +6 -1
  75. package/wiki/Testing.md +64 -0
  76. package/wiki/Troubleshooting.md +3 -2
  77. package/wiki/Upgrading.md +10 -0
@@ -1,7 +1,7 @@
1
- // `x g chart-alerts`: the chart's two monitoring templates written into an app whose chart predates
2
- // them, plus the `values.yaml` blocks it lacks — appended, never rewritten, so a deliberate
3
- // `enabled: false` stays. `--print` is the same rule table as plain Prometheus rule groups, for a
4
- // rule loader outside Kubernetes. No `<name>`: an app has one chart, and `Chart.yaml` names it.
1
+ // `x g chart-alerts` / `x g chart-dashboard`: the chart's monitoring templates (or its Grafana
2
+ // dashboard) written into an app whose chart predates them, plus the `values.yaml` blocks it lacks
3
+ // — appended, never rewritten, so a deliberate `enabled: false` stays. `--print` is the same table
4
+ // for a loader outside Kubernetes. No `<name>`: an app has one chart, and `Chart.yaml` names it.
5
5
 
6
6
  import { stringField, UltimateError } from '@ultimat3/core';
7
7
  import { generateSpec } from './cmd-generate-spec';
@@ -12,30 +12,41 @@ import { generate } from './generate-files';
12
12
  import type { Generator } from './generate-kinds';
13
13
  import { containedPath, planWrites, writeFiles } from './generate-write';
14
14
  import { msg } from './messages';
15
- import type { CommandResult } from './output';
15
+ import type { CommandResult, JsonValue } from './output';
16
16
  import type { ParsedArgs } from './parse';
17
17
  import { flagBool } from './parse';
18
18
  import type { GeneratedFile } from './templates';
19
- import { ALERTS_VALUES, SERVICE_MONITOR_VALUES } from './templates/scaffold-helm';
20
- import { alertRuleGroups, CHART_ALERTS } from './templates/scaffold-helm-alerts';
19
+ import { dashboardJson } from './templates/chart-dashboard';
20
+ import { ALERTS_VALUES, DASHBOARD_VALUES, SERVICE_MONITOR_VALUES } from './templates/scaffold-helm';
21
+ import { CHART_ALERTS } from './templates/scaffold-helm-alert-rules';
22
+ import { alertRuleGroups } from './templates/scaffold-helm-alerts';
21
23
 
22
24
  export const CHART_FILE = 'docker/helm/Chart.yaml';
23
25
  export const VALUES_FILE = 'docker/helm/values.yaml';
24
26
 
27
+ /** The two generators that write into the app's one chart, and only into it. */
28
+ export type ChartGenerator = 'chart-alerts' | 'chart-dashboard';
29
+
25
30
  /** A chart is not there to write into. Its fix is the half that needs none. */
26
31
  export class ChartMissingError extends UltimateError {
27
- constructor(reason: string) {
32
+ constructor(reason: string, kind: ChartGenerator = 'chart-alerts') {
28
33
  super({
29
34
  code: 'X_CHART_MISSING',
30
- cause: `${CHART_FILE} ${reason}, so there is no chart for the monitoring templates to join`,
31
- fix: 'x g chart-alerts --print --json',
35
+ cause: `${CHART_FILE} ${reason}, so there is no chart for the ${kind === 'chart-alerts' ? 'monitoring templates' : 'dashboard'} to join`,
36
+ fix:
37
+ kind === 'chart-alerts'
38
+ ? 'x g chart-alerts --print --json'
39
+ : 'x g chart-dashboard --print --json',
32
40
  });
33
41
  }
34
42
  }
35
43
 
36
- /** `--print` is this generator's, and on any other one it would be a flag accepted and ignored. */
44
+ export const isChartGenerator = (kind: Generator): kind is ChartGenerator =>
45
+ kind === 'chart-alerts' || kind === 'chart-dashboard';
46
+
47
+ /** `--print` is the chart generators', and on any other one it would be a flag accepted and ignored. */
37
48
  export function refuseChartAlertsFlags(kind: Generator, args: ParsedArgs): void {
38
- if (kind === 'chart-alerts' || !args.flags.has('print')) return;
49
+ if (isChartGenerator(kind) || !args.flags.has('print')) return;
39
50
  throw new BadFlagError({
40
51
  flag: 'print',
41
52
  command: `g ${kind}`,
@@ -47,14 +58,21 @@ export function refuseChartAlertsFlags(kind: Generator, args: ParsedArgs): void
47
58
  /** The flags this generator reads; any other set to something but its default is refused. */
48
59
  const READS = new Set(['print', 'force', 'dry-run']);
49
60
 
50
- function refuseUnreadFlags(args: ParsedArgs): void {
61
+ /** Each generator's own bare run: a literal per kind, so a fix line splices no value. */
62
+ const BARE_RUN: ReadonlyMap<ChartGenerator, string> = new Map([
63
+ ['chart-alerts', 'x g chart-alerts'],
64
+ ['chart-dashboard', 'x g chart-dashboard'],
65
+ ]);
66
+
67
+ function refuseUnreadFlags(args: ParsedArgs, kind: ChartGenerator): void {
68
+ const fix = BARE_RUN.get(kind) ?? 'x g chart-alerts';
51
69
  const named = args.positionals[1];
52
70
  if (named !== undefined) {
53
71
  throw new BadFlagError({
54
72
  flag: 'name',
55
- command: 'g chart-alerts',
73
+ command: `g ${kind}`,
56
74
  reason: `takes no <name> and got "${named}": an app has one chart, and Chart.yaml names it`,
57
- fix: 'x g chart-alerts',
75
+ fix,
58
76
  });
59
77
  }
60
78
  for (const flag of generateSpec.flags ?? []) {
@@ -63,63 +81,99 @@ function refuseUnreadFlags(args: ParsedArgs): void {
63
81
  if (value === undefined || value === flag.default) continue;
64
82
  throw new BadFlagError({
65
83
  flag: flag.name,
66
- command: 'g chart-alerts',
67
- reason: `the chart-alerts generator does not read --${flag.name}, so it would change nothing`,
68
- fix: 'x g chart-alerts',
84
+ command: `g ${kind}`,
85
+ reason: `the ${kind} generator does not read --${flag.name}, so it would change nothing`,
86
+ fix,
69
87
  });
70
88
  }
71
89
  }
72
90
 
73
91
  /** The chart's `name`, which its helpers (`<name>.fullname`, `<name>.labels`) are named after. */
74
- export async function chartName(root: string): Promise<string> {
92
+ export async function chartName(
93
+ root: string,
94
+ kind: ChartGenerator = 'chart-alerts',
95
+ ): Promise<string> {
75
96
  const file = Bun.file(containedPath(root, CHART_FILE));
76
- if (!(await file.exists())) throw new ChartMissingError('does not exist');
97
+ if (!(await file.exists())) throw new ChartMissingError('does not exist', kind);
77
98
  let parsed: unknown;
78
99
  try {
79
100
  parsed = Bun.YAML.parse(await file.text());
80
101
  } catch {
81
- throw new ChartMissingError('does not parse as YAML');
102
+ throw new ChartMissingError('does not parse as YAML', kind);
82
103
  }
83
104
  const name = stringField(parsed, 'name');
84
105
  if (name === undefined || !/^[a-z0-9][a-z0-9-]*$/.test(name)) {
85
- throw new ChartMissingError('declares no chart name of lowercase letters, digits and hyphens');
106
+ throw new ChartMissingError(
107
+ 'declares no chart name of lowercase letters, digits and hyphens',
108
+ kind,
109
+ );
86
110
  }
87
111
  return name;
88
112
  }
89
113
 
114
+ /** Each generator's `values.yaml` blocks, by the top-level key each declares. */
115
+ const VALUE_BLOCKS: ReadonlyMap<ChartGenerator, readonly (readonly [string, string])[]> = new Map([
116
+ [
117
+ 'chart-alerts',
118
+ [
119
+ ['serviceMonitor', SERVICE_MONITOR_VALUES],
120
+ ['alerts', ALERTS_VALUES],
121
+ ],
122
+ ],
123
+ ['chart-dashboard', [['dashboard', DASHBOARD_VALUES]]],
124
+ ]);
125
+
90
126
  /**
91
127
  * The blocks `values.yaml` lacks, by top-level key. A key already there is the app's — whatever it
92
- * says — and the templates read a missing one as `auto`, so a values file this never touches works.
128
+ * says — and the templates read a missing one as their default, so a values file this never
129
+ * touches works.
93
130
  */
94
- export function missingValueBlocks(values: string): string {
131
+ export function missingValueBlocks(values: string, kind: ChartGenerator = 'chart-alerts'): string {
95
132
  const has = (key: string) => new RegExp(`^${key}\\s*:`, 'm').test(values);
96
- return [
97
- ...(has('serviceMonitor') ? [] : [SERVICE_MONITOR_VALUES]),
98
- ...(has('alerts') ? [] : [ALERTS_VALUES]),
99
- ].join('');
133
+ return (VALUE_BLOCKS.get(kind) ?? [])
134
+ .filter(([key]) => !has(key))
135
+ .map(([, block]) => block)
136
+ .join('');
100
137
  }
101
138
 
102
- /** `values` with `blocks` appended after one blank line. */
103
- const appended = (values: string, blocks: string): string =>
104
- `${values.trimEnd()}\n\n${blocks.trimEnd()}\n`;
105
-
106
- export async function runChartAlerts(ctx: CommandContext, root: string): Promise<CommandResult> {
107
- refuseUnreadFlags(ctx.args);
108
- if (flagBool(ctx.args, 'print')) {
109
- const rules = alertRuleGroups();
139
+ /** `--print`: what a loader outside Kubernetes takes — rule groups, or the dashboard's JSON. */
140
+ function printed(kind: ChartGenerator): CommandResult {
141
+ if (kind === 'chart-dashboard') {
142
+ const json = dashboardJson();
110
143
  return {
111
144
  ok: true,
112
145
  command: 'g',
113
- summary: msg('cli.generate.chartAlertsPrinted', { count: CHART_ALERTS.length }),
114
- data: { rules },
115
- lines: rules.trimEnd().split('\n'),
146
+ summary: msg('cli.generate.chartDashboardPrinted'),
147
+ data: { dashboard: JSON.parse(json) as JsonValue },
148
+ lines: json.trimEnd().split('\n'),
116
149
  };
117
150
  }
118
- const name = await chartName(root);
151
+ const rules = alertRuleGroups();
152
+ return {
153
+ ok: true,
154
+ command: 'g',
155
+ summary: msg('cli.generate.chartAlertsPrinted', { count: CHART_ALERTS.length }),
156
+ data: { rules },
157
+ lines: rules.trimEnd().split('\n'),
158
+ };
159
+ }
160
+
161
+ /** `values` with `blocks` appended after one blank line. */
162
+ const appended = (values: string, blocks: string): string =>
163
+ `${values.trimEnd()}\n\n${blocks.trimEnd()}\n`;
164
+
165
+ export async function runChartAlerts(
166
+ ctx: CommandContext,
167
+ root: string,
168
+ kind: ChartGenerator = 'chart-alerts',
169
+ ): Promise<CommandResult> {
170
+ refuseUnreadFlags(ctx.args, kind);
171
+ if (flagBool(ctx.args, 'print')) return printed(kind);
172
+ const name = await chartName(root, kind);
119
173
  const force = flagBool(ctx.args, 'force');
120
174
  // Without --force a template already there is kept, never a conflict: it is the app's, and this
121
- // run's job is the files the chart lacks. --force rewrites both from the current table.
122
- const files = generate({ kind: 'chart-alerts', name }).map(
175
+ // run's job is the files the chart lacks. --force rewrites them from the current table.
176
+ const files = generate({ kind, name }).map(
123
177
  (file): GeneratedFile =>
124
178
  force || typeof file.contents !== 'string'
125
179
  ? file
@@ -128,9 +182,9 @@ export async function runChartAlerts(ctx: CommandContext, root: string): Promise
128
182
  const valuesPath = containedPath(root, VALUES_FILE);
129
183
  const valuesFile = Bun.file(valuesPath);
130
184
  const values = (await valuesFile.exists()) ? await valuesFile.text() : undefined;
131
- const blocks = values === undefined ? '' : missingValueBlocks(values);
185
+ const blocks = values === undefined ? '' : missingValueBlocks(values, kind);
132
186
  const edited = blocks === '' ? [] : [VALUES_FILE];
133
- const invocation = `${invocationOf(ctx, 'g')} chart-alerts`;
187
+ const invocation = `${invocationOf(ctx, 'g')} ${kind}`;
134
188
  const dryRun = flagBool(ctx.args, 'dry-run');
135
189
  const report = dryRun
136
190
  ? await planWrites(root, files, force, invocation)
@@ -142,7 +196,7 @@ export async function runChartAlerts(ctx: CommandContext, root: string): Promise
142
196
  // Zero files is a run like any other: a chart that holds both templates and both values blocks.
143
197
  const summary = msg(dryRun ? 'cli.generate.planned' : 'cli.generate.wrote', {
144
198
  count: touched.length,
145
- kind: 'chart-alerts',
199
+ kind,
146
200
  name,
147
201
  });
148
202
  return {
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { UltimateError } from '@ultimat3/core';
6
6
  import type { ExerciseEntry } from './exercise-entry-edit';
7
- import { editExerciseFile } from './exercise-entry-edit';
7
+ import { editExerciseFile, entryKey } from './exercise-entry-edit';
8
8
  import { EXERCISE_FILE } from './exercise-registration';
9
9
  import type { GenerateDisk } from './generate-disk';
10
10
  import type { Finding } from './output';
@@ -23,7 +23,7 @@ export const writtenExercises = (
23
23
 
24
24
  /** One line of an entry: what the fix asks to paste, whitespace folded. */
25
25
  const oneLine = (entry: ExerciseEntry): string =>
26
- `${entry.name}: ${entry.value.replace(/\s*\n\s*/g, ' ').replace(/, }/g, ' }')}`;
26
+ `${entryKey(entry.name)}: ${entry.value.replace(/\s*\n\s*/g, ' ').replace(/, }/g, ' }')}`;
27
27
 
28
28
  /** Inserts `entries` into the app's exercise file; answers the path when it changed, or a refusal. */
29
29
  export async function declareGeneratedExercises(
@@ -0,0 +1,133 @@
1
+ // Which `x g` generator scaffolds each primitive factory, or why none does. One row per
2
+ // `PRIMITIVE_FACTORIES` entry, held to it by `generate-factories.test.ts`: a factory that ships
3
+ // with neither a generator nor a reason is refused there, never noticed later.
4
+
5
+ import type { Generator } from './generate-kinds';
6
+
7
+ /** A factory `x g <generator>` scaffolds: the one call, its tests, in the feature's slice. */
8
+ interface Generated {
9
+ readonly factory: string;
10
+ readonly generator: Generator;
11
+ }
12
+
13
+ /** A factory no generator writes, and the sentence that says why — the decision, on the record. */
14
+ interface NotGenerated {
15
+ readonly factory: string;
16
+ readonly none: string;
17
+ }
18
+
19
+ export type FactoryGenerator = Generated | NotGenerated;
20
+
21
+ /** The model rule three AI factories share: the app registers every model, the framework none. */
22
+ const MODEL =
23
+ 'calls a model the app registers itself (registerModel, @ultimat3/ai) — the framework registers none, so a generated declaration would name an id that is X_AI_MODEL_UNKNOWN at its first call';
24
+
25
+ /** Sorted by factory name, as `PRIMITIVE_FACTORIES` is by package then name. */
26
+ export const FACTORY_GENERATORS: readonly FactoryGenerator[] = [
27
+ { factory: 'agent', none: MODEL },
28
+ {
29
+ factory: 'agentJob',
30
+ none: 'wraps an action the app already declares, and which one is a choice x g cannot read off the disk; deferred (plan 101 U6) until x g takes the action to wrap',
31
+ },
32
+ { factory: 'backfill', generator: 'backfill' },
33
+ {
34
+ factory: 'consumer',
35
+ none: 'subscribes to an event topic the app publishes — the topic and its payload are the app’s own vocabulary, and a generated consumer would subscribe to nothing',
36
+ },
37
+ { factory: 'cronJob', generator: 'cron-job' },
38
+ {
39
+ factory: 'deviceSocket',
40
+ none: 'a websocket mount speaking the app’s own device protocol; the protocol is the whole of the declaration, and only the app knows it',
41
+ },
42
+ {
43
+ factory: 'exportRows',
44
+ none: 'reads one table through the app’s typed handle into a storage disk; deferred (plan 101 U6) until x g can refuse a slice whose table is not the scaffolded one under its own code',
45
+ },
46
+ { factory: 'hive', none: MODEL },
47
+ {
48
+ factory: 'importRows',
49
+ none: 'writes an uploaded file into one table through the app’s typed handle; deferred (plan 101 U6) on the same refusal exportRows waits for',
50
+ },
51
+ {
52
+ factory: 'ledger',
53
+ none: 'the attempt table a webhook() delivery writes, declared once beside that webhook — it has no meaning without one, so it ships with it',
54
+ },
55
+ { factory: 'llm', none: MODEL },
56
+ {
57
+ factory: 'mcpConfirmations',
58
+ none: 'the MCP server’s own confirmation actions: an app lists the value @ultimat3/mcp returns in defineApi, and has no body of its own to write',
59
+ },
60
+ {
61
+ factory: 'notifier',
62
+ none: 'fans a notification out over the channels the app configures — mail, push, in-app — and which channels exist is the app’s configuration, not a template',
63
+ },
64
+ {
65
+ factory: 'partitions',
66
+ none: 'keeps a partitioned table’s partitions ahead of time, and only a table the schema declares partitioned has any; x db gen writes that declaration',
67
+ },
68
+ {
69
+ factory: 'pdf',
70
+ none: 'renders a page the app serves into a document; the page and its route are the declaration, and x g route writes the route',
71
+ },
72
+ { factory: 'purge', generator: 'purge' },
73
+ {
74
+ factory: 'pushRegister',
75
+ none: 'a framework action over the device registrations @ultimat3/notify stores; an app lists it in defineApi and writes no body',
76
+ },
77
+ {
78
+ factory: 'pushSubscribe',
79
+ none: 'a framework action over the Web Push subscriptions @ultimat3/pwa stores; an app lists it in defineApi and writes no body',
80
+ },
81
+ {
82
+ factory: 'pushUnregister',
83
+ none: 'the other half of pushRegister: a framework action an app lists in defineApi, with no body of its own',
84
+ },
85
+ {
86
+ factory: 'pushUnsubscribe',
87
+ none: 'the other half of pushSubscribe: a framework action an app lists in defineApi, with no body of its own',
88
+ },
89
+ {
90
+ factory: 'refreshView',
91
+ none: 'refreshes a materialized view the schema declares; with no view there is nothing to refresh, and the view is a migration, not a template',
92
+ },
93
+ {
94
+ factory: 'reindex',
95
+ none: 'rebuilds an index the schema declares, concurrently; which index bloats is a measurement on a live database, never a scaffold',
96
+ },
97
+ {
98
+ factory: 'rollup',
99
+ none: 'counts a source table into a destination entity by bucket; deferred (plan 101 U6) until x g plants the destination entity and its migration beside it',
100
+ },
101
+ {
102
+ factory: 'scrape',
103
+ none: 'fetches pages the app names and extracts what the app wants from them; the target and the extraction are the whole declaration',
104
+ },
105
+ {
106
+ factory: 'subjectErase',
107
+ none: 'erases one data subject across every table that holds one, which the app declares per entity — the coverage x verify holds is that declaration',
108
+ },
109
+ {
110
+ factory: 'subjectExport',
111
+ none: 'exports one data subject across the same declared tables subjectErase reads; one declaration per app, written beside the entities',
112
+ },
113
+ {
114
+ factory: 'transition',
115
+ none: 'declares the edges of an entity’s own status column — which states exist is the app’s business convention; x g mutator writes the mutator shape it returns',
116
+ },
117
+ {
118
+ factory: 'uploadFlow',
119
+ none: 'a request and a confirm action over the app’s storage bucket and the row an upload attaches to — both the app’s, and neither on the disk x g reads',
120
+ },
121
+ {
122
+ factory: 'webhook',
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
+ },
125
+ { factory: 'webhookReceiver', generator: 'webhook-receiver' },
126
+ ];
127
+
128
+ /** `x g llm` or `x g agent-job`: the factory a word names, when it is one no generator writes. */
129
+ export function factoryWithoutGenerator(raw: string): NotGenerated | undefined {
130
+ const camel = raw.replaceAll(/-([a-z])/g, (_match, letter: string) => letter.toUpperCase());
131
+ const row = FACTORY_GENERATORS.find((entry) => entry.factory === camel);
132
+ return row !== undefined && 'none' in row ? row : undefined;
133
+ }
@@ -28,6 +28,10 @@ import {
28
28
  taskFiles,
29
29
  } from './templates';
30
30
  import { adminCatalogFiles } from './templates/admin-catalog';
31
+ import { helmDashboardFiles } from './templates/chart-dashboard';
32
+ import { cronJobFiles } from './templates/generate-cron-job';
33
+ import { purgeFiles } from './templates/generate-purge';
34
+ import { webhookReceiverFiles } from './templates/generate-webhook-receiver';
31
35
  import { helmMonitoringFiles } from './templates/scaffold-helm-alerts';
32
36
  import { oidcSignInFiles } from './templates/sign-in-oidc';
33
37
  import { passwordSignInFiles } from './templates/sign-in-password';
@@ -195,6 +199,14 @@ export function generate(options: GenerateOptions): readonly GeneratedFile[] {
195
199
  ...(options.sliceRepo === undefined ? {} : { sliceRepo: options.sliceRepo }),
196
200
  }),
197
201
  );
202
+ // A primitive factory's one call, in the feature's slice. None reads the slice: each declares
203
+ // no table of its own, so it compiles in a feature that has no entity yet.
204
+ case 'cron-job':
205
+ return dedupe(cronJobFiles(options.name, target));
206
+ case 'purge':
207
+ return dedupe(purgeFiles(options.name, target));
208
+ case 'webhook-receiver':
209
+ return dedupe(webhookReceiverFiles(options.name, target));
198
210
  case 'entity':
199
211
  // With the labels the admin reads for it: the entity is an admin screen once it is in the
200
212
  // handle, whether or not a resource was generated around it.
@@ -277,6 +289,9 @@ export function generate(options: GenerateOptions): readonly GeneratedFile[] {
277
289
  // `name` is the chart's own (`Chart.yaml`), which its helpers are named after. The values
278
290
  // blocks are an edit to a file the app owns, so `generate-chart-alerts.ts` makes it.
279
291
  return helmMonitoringFiles(names(options.name));
292
+ case 'chart-dashboard':
293
+ // The same chart, the same name: the dashboard JSON and the ConfigMap that ships it.
294
+ return helmDashboardFiles(names(options.name));
280
295
  case 'route':
281
296
  // `--locales` reaches the route generator too: its catalog entry is the route's title and
282
297
  // description, and a locale asked for on the command line is a locale that gets a file.
@@ -9,6 +9,7 @@ import {
9
9
  MissingSubcommandError,
10
10
  UnknownCommandError,
11
11
  } from './errors';
12
+ import { factoryWithoutGenerator } from './generate-factories';
12
13
  import { quoteArg } from './shell-quote';
13
14
  import type { Surface } from './templates';
14
15
  import { camel, kebab } from './templates/naming';
@@ -18,6 +19,11 @@ export const GENERATORS = [
18
19
  'action',
19
20
  'mutator',
20
21
  'backfill',
22
+ // Three primitive factories, each its one call in the feature's `jobs/`. Which factories have a
23
+ // generator, and why the rest have none, is `FACTORY_GENERATORS` (`generate-factories.ts`).
24
+ 'cron-job',
25
+ 'purge',
26
+ 'webhook-receiver',
21
27
  'job',
22
28
  'route',
23
29
  'policy',
@@ -29,6 +35,7 @@ export const GENERATORS = [
29
35
  'guard',
30
36
  'sign-in',
31
37
  'chart-alerts',
38
+ 'chart-dashboard',
32
39
  'app',
33
40
  'package',
34
41
  ] as const;
@@ -102,12 +109,16 @@ export function readKind(raw: string | undefined): Generator {
102
109
  // deliberately never asked about an absent word, since the empty string is within `job`'s
103
110
  // cutoff and would "suggest" a generator nobody typed.
104
111
  if (raw === undefined) throw new MissingSubcommandError({ command: 'g', known: GENERATORS });
112
+ const decided = factoryWithoutGenerator(raw);
105
113
  const near = nearestName(raw, kinds);
106
114
  const suggestion = GENERATORS.find((kind) => kind === near);
107
115
  throw new UnknownCommandError({
108
116
  path: `g ${raw}`.trim(),
109
117
  known: GENERATORS,
110
118
  suggestion: suggestion === undefined ? 'help g' : `g ${suggestion} ${EXAMPLE_NAME[suggestion]}`,
119
+ ...(decided === undefined
120
+ ? {}
121
+ : { why: `${decided.factory}() has no generator: ${decided.none}` }),
111
122
  });
112
123
  }
113
124
 
@@ -275,6 +286,9 @@ const EXAMPLE_NAME: Readonly<Record<Generator, string>> = {
275
286
  action: 'publish-post',
276
287
  mutator: 'rename-post',
277
288
  backfill: 'backfill-slugs',
289
+ 'cron-job': 'nightly-report',
290
+ purge: 'purge-retained',
291
+ 'webhook-receiver': 'billing-events',
278
292
  job: 'send-digest',
279
293
  route: 'posts',
280
294
  policy: 'post',
@@ -288,6 +302,7 @@ const EXAMPLE_NAME: Readonly<Record<Generator, string>> = {
288
302
  'sign-in': '--password',
289
303
  // No name either: an app has one chart. `--print` runs with or without one.
290
304
  'chart-alerts': '--print',
305
+ 'chart-dashboard': '--print',
291
306
  // A workspace: `apps/admin`, `packages/domain`.
292
307
  app: 'admin',
293
308
  package: 'domain',
@@ -27,7 +27,7 @@ import { safeUrlLabel } from './safe-url-label';
27
27
  */
28
28
  export function databaseTarget(services: DevServices, env: Env): DatabaseTarget {
29
29
  const url = services.db.url;
30
- const production = isProduction(env);
30
+ const production = readsAsProduction(env);
31
31
  return services.db.mode === 'embedded'
32
32
  ? { label: url, branch: pgliteBranch(url, services.stateDir), production }
33
33
  : {
@@ -46,9 +46,10 @@ export function databaseTarget(services: DevServices, env: Env): DatabaseTarget
46
46
  * `undefined` is answered **true**, and that is the whole point of using it here. It means exactly
47
47
  * one thing: `ULTIMATE_ENV` is set to something that is not an environment. Reading a typo as "not
48
48
  * production" would let the single misconfiguration this guard exists to survive defeat it — so an
49
- * environment that cannot be read is treated as the most dangerous one it could be.
49
+ * environment that cannot be read is treated as the most dangerous one it could be. `x explain` and
50
+ * `x token` ask the same question through this one reader (`cmd-explain.ts`, `cmd-token.ts`).
50
51
  */
51
- const isProduction = (env: Env): boolean => {
52
+ export const readsAsProduction = (env: Env): boolean => {
52
53
  const environment = tryResolveEnvironment({ env });
53
54
  return environment === undefined || environment === 'production';
54
55
  };
package/src/mcp-errors.ts CHANGED
@@ -394,6 +394,10 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
394
394
  'x doctor --json # its X_VERIFY_STEP_UNFLOORED fix names the steps: run that x verify --only, then add each step that passed, not skipped, to "steps" in x.verify.json',
395
395
  X_DB_ROW_SECURITY_OFF:
396
396
  'database: { rowSecurity: true } # in defineConfig, app.config.ts; then: x db gen "row security" --json && x db migrate --json && x doctor --json',
397
+ X_DEV_DATA_UNOPENABLE:
398
+ 'x db migrate --json # the fresh database has no tables yet; then x db seed --json if the app declares a seed. The moved directory (meta.aside) is kept: delete it once its rows are not needed',
399
+ X_EXPLAIN_PRODUCTION_DATABASE:
400
+ 'env -u DATABASE_URL x queries list --json # then the same prefix on x explain <query> --json: it plans on the embedded dev database; for a copy of production data, point DATABASE_URL at a staging restore with ULTIMATE_ENV=staging',
397
401
  };
398
402
 
399
403
  const isCliCode = (code: string): code is CliErrorCode =>
@@ -73,6 +73,8 @@ export const GATE_MESSAGES = {
73
73
  'cli.verify.notAGateRun': 'NOT A GATE RUN — {summary}',
74
74
  'cli.verify.pass': 'all {count} steps passed in {ms}ms',
75
75
  'cli.verify.fail': '{failed} of {count} steps failed',
76
+ 'cli.verify.plan':
77
+ 'the gate in {parts} part(s) over {steps} steps — the CI matrix is data.matrix',
76
78
  // The budgets step built before it weighed (`verify-budgets-build.ts`): which stats state made it.
77
79
  'cli.verify.budgets.built':
78
80
  'built first: build stats were {state} — x build --target static --out {out} ({ms}ms)',
@@ -0,0 +1,32 @@
1
+ // The `x token`, `x config`, `x logs`, `x cache` and `x explain` rows of the CLI catalog
2
+ // (`messages.ts` composes them): what each operator command found or did. Data only.
3
+
4
+ export const OPS_MESSAGES = {
5
+ 'cli.token.created': 'issued {prefix} with {count} scope(s) — the token is printed once, below',
6
+ 'cli.token.plaintext': ' {token}',
7
+ 'cli.token.once': ' shown once: only its hash is stored, and no command prints it again',
8
+ 'cli.token.listed': '{count} token(s) owned by {owner}',
9
+ 'cli.token.row': ' {prefix} {scopes} {state}',
10
+ 'cli.token.revoked': 'revoked {at}',
11
+ 'cli.token.noExpiry': 'no expiry',
12
+ 'cli.token.expires': 'expires {at}',
13
+ 'cli.token.revokedOne': 'revoked {id} — the next request that presents it is refused',
14
+ 'cli.token.notLive': 'no live token has the id {id} — nothing to revoke',
15
+ 'cli.config.show': '{name}: {count} config section(s), defaults merged, from {path}',
16
+ 'cli.config.section': '{section}, defaults merged, from {path}',
17
+ 'cli.logs.tail': '{count} line(s) from the end of {path}',
18
+ 'cli.cache.graph': '{tags} tag(s); {stale} read and never invalidated by an action',
19
+ 'cli.cache.graphRow': ' {tag}: written by {writers} · read by {readers}',
20
+ 'cli.cache.busted': 'busted {tags} tag(s) here and on every replica listening on {bus}',
21
+ 'cli.cache.bustedLocal':
22
+ 'busted {tags} tag(s) in this process only: the bus is in-process, so no running server heard it — set NATS_URL or REDIS_URL, or bust from /_x',
23
+ 'cli.cache.tierRow': ' {tier}: {keys} key(s) dropped',
24
+ 'cli.explain.served': '{query}: {planned} statement(s) planned, each served by a declared index',
25
+ 'cli.explain.red': '{query}: {count} read(s) no declared index serves',
26
+ 'cli.explain.unplannable':
27
+ '{query}: the dev database could not plan it — x db migrate first if its tables are missing',
28
+ 'cli.explain.none':
29
+ '{query}: sent no statement — its rows come from memory or a provider that reads no table',
30
+ 'cli.explain.exempt': ' may scan: {reason}',
31
+ 'cli.explain.refused': ' not planned: {reason}',
32
+ } as const;
@@ -31,6 +31,7 @@ export const UPGRADE_MESSAGES = {
31
31
  'cli.upgrade.done': '{from} -> {to}: the gate is green',
32
32
  'cli.upgrade.dryRun': '{from} -> {to}: nothing written, no gate run',
33
33
  'cli.upgrade.guard': 'guard, yours to take or leave: {fix}',
34
+ 'cli.upgrade.doctorWarning': 'doctor warning: {code}, red on the next major — fix: {fix}',
34
35
  'cli.upgrade.guardInstalled':
35
36
  'guard installed: guards/{name}.ts, from this release (delete the file to drop the rule)',
36
37
  'cli.upgrade.guardWithheld':
package/src/messages.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  import { CLIENT_MESSAGES } from './messages-client';
7
7
  import { DB_MESSAGES } from './messages-db';
8
8
  import { GATE_MESSAGES } from './messages-gate';
9
+ import { OPS_MESSAGES } from './messages-ops';
9
10
  import { REPRO_MESSAGES } from './messages-repro';
10
11
  import { SHOT_MESSAGES } from './messages-shot';
11
12
  import { UPGRADE_MESSAGES } from './messages-upgrade';
@@ -101,6 +102,7 @@ const CATALOG = {
101
102
  'cli.doctor.coverageExclude':
102
103
  '{count} path(s) x.verify.json excludes from the coverage floor — each with the reason it gives:',
103
104
  'cli.doctor.chartAlerts': '{count} monitoring template(s) missing from the chart:',
105
+ 'cli.doctor.chartDashboard': '{count} dashboard file(s) missing from the chart:',
104
106
  // `x doctor`'s reminder: the rolling rail is off until this key is set (`doctor-rolling.ts`).
105
107
  'cli.doctor.rollingSince':
106
108
  'the rolling-deploy rail is off: set "rollingSince": "{newest}" in x.verify.json to judge every migration after your newest',
@@ -145,6 +147,7 @@ const CATALOG = {
145
147
  // believed the files were on disk.
146
148
  'cli.generate.planned': 'would write {count} file(s) for {kind} {name} — nothing written',
147
149
  'cli.generate.chartAlertsPrinted': '{count} alert rule(s), as Prometheus rule groups',
150
+ 'cli.generate.chartDashboardPrinted': 'the Grafana dashboard, as JSON to import',
148
151
  'cli.i18n.added': 'added {locale} — {keys} key(s) seeded from {from}',
149
152
  'cli.i18n.dynamic': '{count} dynamic t() call(s) the extractor cannot verify:',
150
153
  'cli.i18n.gaps': '{missing} missing key(s) across {locales} locale(s)',
@@ -282,6 +285,7 @@ const CATALOG = {
282
285
  ...SHOT_MESSAGES,
283
286
  ...UPGRADE_MESSAGES,
284
287
  ...GATE_MESSAGES,
288
+ ...OPS_MESSAGES,
285
289
  } as const;
286
290
 
287
291
  export type MessageKey = keyof typeof CATALOG;
@@ -8,6 +8,7 @@
8
8
 
9
9
  import type { OtlpSignal, ShutdownReason } from '@ultimat3/core';
10
10
  import {
11
+ finiteCount,
11
12
  isProduction,
12
13
  logger,
13
14
  onShutdown,
@@ -65,7 +66,15 @@ export const METRIC_EXPORT_INTERVAL_MS = 60_000;
65
66
  * and its timer stops, rather than being dropped and leaked. Metrics are the same shape since
66
67
  * 31.0.0: a `metric.export` subscription, released by its unsubscribe.
67
68
  */
68
- export function startOtlpExport(env: Env = process.env): () => void {
69
+ export interface OtlpExportOptions {
70
+ /** `database.slowStatementMs` from `app.config.ts`: replaces the 500 ms default, `0` is off. */
71
+ readonly slowStatementMs?: number | undefined;
72
+ }
73
+
74
+ export function startOtlpExport(
75
+ env: Env = process.env,
76
+ options: OtlpExportOptions = {},
77
+ ): () => void {
69
78
  const releases: (() => void)[] = [];
70
79
  const flushes: (() => Promise<void>)[] = [];
71
80
 
@@ -78,7 +87,12 @@ export function startOtlpExport(env: Env = process.env): () => void {
78
87
  // test suite's deliberately slow statements are not an operator's incident. Released with the
79
88
  // rest, so a second boot in this process never logs each statement twice.
80
89
  const production = isProduction({ env });
81
- releases.push(slowStatementLog({ thresholdMs: production ? SLOW_STATEMENT_THRESHOLD_MS : 0 }));
90
+ const threshold = finiteCount(
91
+ 'startOtlpExport',
92
+ 'slowStatementMs',
93
+ options.slowStatementMs ?? SLOW_STATEMENT_THRESHOLD_MS,
94
+ );
95
+ releases.push(slowStatementLog({ thresholdMs: production ? threshold : 0 }));
82
96
  // Every environment: the statements, renders and cache lookups each request caused, which
83
97
  // `http.request.slow` carries (its own threshold, `http.slowRequestMs`, decides whether it is
84
98
  // written). Without it the line holds the gate and handler split and no statement count.