@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
@@ -0,0 +1,170 @@
1
+ // The `unbounded-fanout` guard `x new` ships: a database call per element of a list runs through
2
+ // `mapBounded` with a stated width, never `Promise.all` over the whole list at once. Three adopters
3
+ // hand-rolled the pool this replaces; the list a table grows to is what makes the shape a defect.
4
+
5
+ import { guardCode } from './guard';
6
+ import type { GeneratedFile } from './naming';
7
+
8
+ /** Derived from the guard's name, never a literal: an `X_*` literal here is a FRAMEWORK code. */
9
+ const NAME = 'unbounded-fanout';
10
+ const CODE = guardCode(NAME);
11
+
12
+ const source =
13
+ (): string => `// unbounded-fanout: a database call per row runs a bounded number at a time, never all at once.
14
+ // \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
15
+ // step — nothing registers this file, so nothing can forget to. Delete it to drop the rule.
16
+ //
17
+ // Why: \`Promise.all(rows.map(async (row) => db…))\` opens one statement per row AT ONCE. Ten rows
18
+ // is fine; the ten thousand a table grows to is ten thousand statements queued on a pool of ten,
19
+ // every other request waiting behind them. \`mapBounded\` from \`@ultimat3/core\` is the same map with
20
+ // a stated width, results in input order, and the first failure stops the rest.
21
+ // Read: a \`Promise.all(\` or \`Promise.allSettled(\` over \`<list>.map(…)\`, async or not, whose
22
+ // callback names \`db\`, \`tx\` or a \`…repo\`/\`…Repo\`, anywhere under apps/ and packages/ but a test.
23
+ // Not read: an array literal, which is bounded where it is written. Admitted: a \`// why:\` on the
24
+ // line or the line above it.
25
+
26
+ import type { Finding, Guard } from '@ultimat3/cli';
27
+
28
+ /** The app owns the codes its own conventions raise — this one is named for the guard. */
29
+ const CODE = '${CODE}';
30
+
31
+ export interface SourceFile {
32
+ /** App-root-relative POSIX path, so the finding names the file an author opens. */
33
+ readonly path: string;
34
+ readonly source: string;
35
+ }
36
+
37
+ const ALL = /\\bPromise\\s*\\.\\s*all(?:Settled)?\\s*\\(/g;
38
+ /** \`async\` or not: \`rows.map((row) => db.posts.find(row.id))\` is the same statement per row. */
39
+ const MAPPED = /\\.\\s*map\\s*\\(/;
40
+ /** \`db\`, \`tx\`, and a repository by any name that ends in one: \`repo\`, \`usersRepo\`, \`PostRepo\`. */
41
+ const DATABASE = /\\b(?:db|tx|\\w*[Rr]epo)\\b\\s*[.(]/;
42
+ const WHY = /\\/\\/\\s*why:/;
43
+
44
+ /** Comments and string bodies blanked IN PLACE, so a line number still points at the source. */
45
+ const blank = (text: string): string =>
46
+ text
47
+ .replaceAll(/\\/\\*[\\s\\S]*?\\*\\//g, (match) => match.replaceAll(/[^\\n]/g, ' '))
48
+ .replaceAll(/(?<![:\\w])\\/\\/[^\\n]*/g, (match) => ' '.repeat(match.length))
49
+ .replaceAll(/'(?:[^'\\\\\\n]|\\\\.)*'|"(?:[^"\\\\\\n]|\\\\.)*"|\`(?:[^\`\\\\]|\\\\.)*\`/g, (match) =>
50
+ match.replaceAll(/[^\\n]/g, ' '),
51
+ );
52
+
53
+ /** The text between the \`(\` at \`open\` and the \`)\` that closes it. */
54
+ const argumentAt = (text: string, open: number): string => {
55
+ let depth = 0;
56
+ for (let index = open; index < text.length; index += 1) {
57
+ const char = text[index];
58
+ if (char === '(' || char === '[' || char === '{') depth += 1;
59
+ if (char === ')' || char === ']' || char === '}') depth -= 1;
60
+ if (depth === 0) return text.slice(open + 1, index);
61
+ }
62
+ return text.slice(open + 1);
63
+ };
64
+
65
+ /** Pure — the caller does the I/O — so the rule is testable without a filesystem. */
66
+ export function unboundedFanouts(files: readonly SourceFile[]): readonly Finding[] {
67
+ const findings: Finding[] = [];
68
+ for (const file of files) {
69
+ const lines = file.source.split('\\n');
70
+ const text = blank(file.source);
71
+ for (const match of text.matchAll(ALL)) {
72
+ const argument = argumentAt(text, match.index + match[0].length - 1);
73
+ const mapped = argument.search(MAPPED);
74
+ const list = argument.slice(0, Math.max(mapped, 0)).trim().replaceAll(/\\s+/g, ' ');
75
+ // An array literal is as long as the line that writes it; a list read from anywhere is not.
76
+ if (mapped < 1 || list.startsWith('[') || !DATABASE.test(argument)) continue;
77
+ const line = text.slice(0, match.index).split('\\n').length;
78
+ if (WHY.test(lines[line - 1] ?? '') || WHY.test(lines[line - 2] ?? '')) continue;
79
+ const at = \`\${file.path}:\${line}\`;
80
+ findings.push({
81
+ code: CODE,
82
+ cause: \`\${at} starts a database call for every element of \${list} at once — as many statements in flight as the list is long, queued on a pool a fraction of that size\`,
83
+ fix: \`mapBounded(\${list}, <the same async callback>, { width: 8 }) — from @ultimat3/core, in place of the Promise.all at \${at}, the width what the pool can take — or a // why: comment on that line naming the list's bound — then: x verify\`,
84
+ at,
85
+ });
86
+ }
87
+ }
88
+ return findings;
89
+ }
90
+
91
+ /** Every source file but a test: a fixture's fan-out is over the rows it planted. */
92
+ export const readsFile = (path: string): boolean => !/\\.test\\.tsx?$/.test(path);
93
+
94
+ export const guard: Guard = {
95
+ summary: 'a database call per row runs through mapBounded, never Promise.all over the list',
96
+ async check(_root, sources) {
97
+ // The run's ONE read of the source: every guard asking for this glob shares the walk.
98
+ const code = await sources.files('{apps,packages}/**/*.{ts,tsx}');
99
+ return unboundedFanouts(
100
+ code
101
+ .filter((file) => readsFile(file.path))
102
+ .map((file) => ({ path: file.path, source: file.text })),
103
+ );
104
+ },
105
+ };
106
+ `;
107
+
108
+ const test =
109
+ (): string => `// The rule, driven directly. Failure case first: a guard whose rule silently stopped matching is
110
+ // a green gate over the convention it was written to enforce.
111
+
112
+ import { expect, unitTest } from '@ultimat3/testing';
113
+ import { readsFile, unboundedFanouts } from './unbounded-fanout';
114
+
115
+ const file = (source: string) => [{ path: 'apps/web/app/posts/service.ts', source }];
116
+
117
+ unitTest('a database call per row, all at once, is refused at its line', () => {
118
+ const source =
119
+ 'const a = 1;\\nawait Promise.all(rows.map(async (row) => db.posts.update(row.id, row)));';
120
+ const findings = unboundedFanouts(file(source));
121
+ expect(findings).toHaveLength(1);
122
+ expect(findings[0]?.code).toBe('${CODE}');
123
+ expect(findings[0]?.at).toBe('apps/web/app/posts/service.ts:2');
124
+ expect(findings[0]?.fix).toStartWith('mapBounded(rows, <the same async callback>, { width: 8 })');
125
+ });
126
+
127
+ unitTest('allSettled, a tx, a repo and a chained list are the same rule', () => {
128
+ const settled = 'Promise.allSettled(ids.map(async (id) => tx.posts.delete(id)));';
129
+ expect(unboundedFanouts(file(settled))).toHaveLength(1);
130
+ const chained =
131
+ 'Promise.all(\\n rows\\n .filter((row) => row.ok)\\n .map(async (row) => repo.byId(row.id)),\\n);';
132
+ expect(unboundedFanouts(file(chained))[0]?.cause).toContain('rows .filter((row) => row.ok)');
133
+ });
134
+
135
+ unitTest('a callback without async, and a repository by any name, are the same rule', () => {
136
+ const plain = 'Promise.all(rows.map((r) => db.posts.find(r.id)));';
137
+ expect(unboundedFanouts(file(plain))).toHaveLength(1);
138
+ const named = 'Promise.all(ids.map((id) => usersRepo.byId(id)));';
139
+ expect(unboundedFanouts(file(named))).toHaveLength(1);
140
+ // Not a repository: \`report\` only starts like one.
141
+ expect(unboundedFanouts(file('Promise.all(ids.map((id) => report.sum(id)));'))).toEqual([]);
142
+ });
143
+
144
+ unitTest('an array literal, a map with no database call and a why: are not refused', () => {
145
+ const literal = 'Promise.all([a, b].map(async (one) => db.posts.byId(one)));';
146
+ expect(unboundedFanouts(file(literal))).toEqual([]);
147
+ expect(unboundedFanouts(file('Promise.all(urls.map(async (url) => hash(url)));'))).toEqual([]);
148
+ const why = '// why: at most three locales\\nPromise.all(locales.map(async (l) => db.t.byId(l)));';
149
+ expect(unboundedFanouts(file(why))).toEqual([]);
150
+ });
151
+
152
+ unitTest('a comment and a string naming the shape are not code', () => {
153
+ expect(unboundedFanouts(file('// Promise.all(rows.map(async (r) => db.x(r)))'))).toEqual([]);
154
+ expect(
155
+ unboundedFanouts(file("const s = 'Promise.all(rows.map(async (r) => db.x(r)))';")),
156
+ ).toEqual([]);
157
+ });
158
+
159
+ unitTest('every source file is read but a test', () => {
160
+ expect(readsFile('apps/web/app/posts/service.ts')).toBe(true);
161
+ expect(readsFile('packages/domain/src/rules.ts')).toBe(true);
162
+ expect(readsFile('apps/web/app/posts/service.test.ts')).toBe(false);
163
+ });
164
+ `;
165
+
166
+ /** `guards/unbounded-fanout.ts` and its test. No index, no registry — the directory registers it. */
167
+ export const unboundedFanoutGuardFiles = (): readonly GeneratedFile[] => [
168
+ { path: `guards/${NAME}.ts`, contents: source() },
169
+ { path: `guards/${NAME}.test.ts`, contents: test() },
170
+ ];
@@ -82,8 +82,9 @@ bun run verify --json # the same, machine-readable
82
82
  \`\`\`
83
83
 
84
84
  \`bun run verify\` is \`bunx x verify\`, the whole gate: its \`budgets\` step builds what it weighs when
85
- \`.x/build-stats.json\` is missing or older than the source. CI runs this same script —
86
- \`.github/workflows/ci.yml\` is \`bun run setup\` and then \`bun run verify\`, nothing else.
85
+ \`.x/build-stats.json\` is missing or older than the source. CI runs this same script, cut into
86
+ parts — \`.github/workflows/ci.yml\` asks \`bun run verify plan\` for them, runs \`bun run setup\` and
87
+ each part's \`bun run verify --only …\`, and \`bun run verify merge\` is the verdict.
87
88
 
88
89
  Red is instructions, not a verdict: **every finding carries an executable \`fix:\` — run it verbatim
89
90
  before improvising**, and \`bunx x errors explain <CODE>\` expands any code it names. Never narrow the gate
@@ -38,12 +38,13 @@ queries, jobs, MCP tools, published operations and tests it touches, each with p
38
38
 
39
39
  | Rule | Detail | Refused by |
40
40
  |---|---|---|
41
- | One gate | \`bun run verify\` — \`bunx x verify\`, which builds what its \`budgets\` step weighs. Green means shippable; never merge red. CI runs the same two commands as your terminal: \`bun run setup && bun run verify\` | the gate itself, and \`.github/workflows/ci.yml\` on every push and pull request; \`.github/workflows/image.yml\` publishes only a commit it passed |
41
+ | One gate | \`bun run verify\` — \`bunx x verify\`, which builds what its \`budgets\` step weighs. Green means shippable; never merge red. CI runs the same gate, cut into parts: \`bun run verify plan --json\` names them, each runner runs \`bun run setup && bun run verify --only <steps>\`, and \`bun run verify merge\` is the verdict | the gate itself, and \`.github/workflows/ci.yml\` on every push and pull request; \`.github/workflows/image.yml\` publishes only a commit it passed |
42
42
  | Coverage | the unit suite covers 95% of the lines and functions of this app's own source — every file under \`apps/\` and \`packages/\`, one no test loads counted at 0%. A floor, not the goal: a test added to raise it is proven by mutation — break the source, watch it go red, restore | \`X_COVERAGE_BELOW_FLOOR\` on the \`unit\` step; \`coverage\` in \`x.verify.json\` states the floor, and it only rises |
43
43
  | One way | generators, not hand-rolled files: \`bunx x g resource\`, \`bunx x g action\`, \`bunx x g route\` | review |
44
44
  | Surfaces | \`site/\` is 0kb JS and may not import \`app/\`; \`shared/\` is a leaf | \`X_BOUNDARY_SITE_TO_APP\` |
45
45
  | Data | routes call actions and queries; only \`repo.ts\` touches the database | \`X_BOUNDARY_ROUTE_TO_DB\` |
46
46
  | Repos | a \`repo.ts\` reads through the typed handle, never a \`sql\` literal the handle can express | \`guards/repo-raw-sql.ts\` |
47
+ | Fan-out | a database call per element of a list runs through \`mapBounded(rows, fn, { width })\` from \`@ultimat3/core\` — never \`Promise.all(rows.map(async …))\`, one statement per row at once; a \`// why:\` on the line admits a list bounded where it is built | \`guards/unbounded-fanout.ts\` |
47
48
  | Vendors | a server \`fetch(\` carries a \`signal\` in its own options — better, it is \`outbound()\` from \`@ultimat3/core/outbound\`: a deadline, the caller's signal, safe-only retry | \`guards/raw-fetch.ts\` |
48
49
  | Polling | an island re-reads a query on a timer with \`useQuery(ref, input, { poll: pollEvery(ms) })\` (\`@ultimat3/realtime\`), anything else with \`visibleInterval(run, ms)\` from \`@ultimat3/core/page\` — no call while the tab is hidden, none after a lost session — never a bare \`setInterval(\`; a \`// why:\` on the line admits a tick that is not a read | \`guards/raw-interval.ts\` |
49
50
  | Confirmation | a destructive act asks through \`ConfirmDialog\` from \`@ultimat3/ui\` — Cancel focused, a native post, stays open on a refusal — never \`confirm(\`; a \`// why:\` on the line admits a call that is not that question | \`guards/native-confirm.ts\` |
@@ -181,7 +182,7 @@ with \`X_DB_DRIFT\`, and that is the fix it names.
181
182
  | \`x.manifest.json\` | generated facts: routes, actions, jobs, policies |
182
183
  | \`.mcp.json\` | MCP client config: the dev tools, \`bunx @ultimat3/cli mcp serve --transport stdio\` |
183
184
  | \`apps/web/mcp.ts\` | the app's own \`POST /mcp\`: exposed actions, behind a bearer token |
184
- | \`.github/workflows/ci.yml\` | \`bun run setup\` then \`bun run verify\`, on push and pull request |
185
+ | \`.github/workflows/ci.yml\` | on push and pull request: \`bun run verify plan\` cuts the gate into parts, each runner runs \`bun run setup\` then its \`bun run verify --only …\`, and \`bun run verify merge\` folds them into the one verdict |
185
186
  | \`.github/workflows/image.yml\` | after a green \`ci\` on the default branch: \`docker/Dockerfile\` to \`ghcr.io\`, tagged \`sha-<7>\`, always on \`ubuntu-latest\` (bash and Docker). \`ci.yml\` runs on \`vars.CI_RUNNER\`, default \`ubuntu-latest\` |
186
187
  `;
187
188
 
@@ -24,6 +24,7 @@
24
24
  // is `bare-error`'s second half: an app code is declared once, with core's `defineError`. One is
25
25
  // about the TAB: an island polls with `visibleInterval()`, which a hidden tab and a lost session stop.
26
26
  // One is about the QUESTION: a destructive act asks through `ConfirmDialog`, never `confirm(`.
27
+ // One is about the POOL: a database call per row runs through `mapBounded`, never all at once.
27
28
 
28
29
  import { animatedLayoutPropertyGuardFiles } from './guard-animated-layout-property';
29
30
  import { bareErrorGuardFiles } from './guard-bare-error';
@@ -43,6 +44,7 @@ import { rawShadowGuardFiles } from './guard-raw-shadow';
43
44
  import { rawZIndexGuardFiles } from './guard-raw-z-index';
44
45
  import { repoRawSqlGuardFiles } from './guard-repo-raw-sql';
45
46
  import { semanticInteractiveGuardFiles } from './guard-semantic-interactive';
47
+ import { unboundedFanoutGuardFiles } from './guard-unbounded-fanout';
46
48
  import { undeclaredCustomPropertyGuardFiles } from './guard-undeclared-custom-property';
47
49
  import { undefinedStyleClassGuardFiles } from './guard-undefined-style-class';
48
50
  import { untranslatedStringGuardFiles } from './guard-untranslated-string';
@@ -74,6 +76,7 @@ const SHIPPED: readonly (readonly [string, () => readonly GeneratedFile[]])[] =
74
76
  ['raw-z-index', rawZIndexGuardFiles],
75
77
  ['repo-raw-sql', repoRawSqlGuardFiles],
76
78
  ['semantic-interactive', semanticInteractiveGuardFiles],
79
+ ['unbounded-fanout', unboundedFanoutGuardFiles],
77
80
  ['undeclared-custom-property', undeclaredCustomPropertyGuardFiles],
78
81
  ['undefined-style-class', undefinedStyleClassGuardFiles],
79
82
  ['untranslated-string', untranslatedStringGuardFiles],
@@ -0,0 +1,160 @@
1
+ // The rule table every Ultimate chart's alerts are written from, renderer-neutral. Only mechanism
2
+ // ships (axiom 8): a stalled queue, a dead letter, a lost lease, a dropped frame, error-budget burn,
3
+ // job failures, pool, loop and memory saturation, a dead target. A latency target is the app's.
4
+
5
+ /** How an expression names a series and groups its result, per renderer. */
6
+ export interface AlertScope {
7
+ /** `name{matchers}` — the scope's own matchers, then `extra`. */
8
+ readonly series: (name: string, extra?: string) => string;
9
+ /** The labels every rule groups by, so one release (or one job) fires one alert. */
10
+ readonly by: string;
11
+ /** The label naming a scrape target's role. */
12
+ readonly component: string;
13
+ /** The label naming one scrape target — a pod, or a plain `instance`. */
14
+ readonly target: string;
15
+ /** The rule's threshold, as the renderer spells it: a value lookup or the default. */
16
+ readonly threshold: (fallback: number) => string;
17
+ /** The error budget as a PromQL scalar: `(1 - <objective> / 100)`. */
18
+ readonly budget: string;
19
+ }
20
+
21
+ export interface ChartAlert {
22
+ readonly alert: string;
23
+ readonly expr: (scope: AlertScope) => string;
24
+ /** The default `alerts.rules.<alert>.threshold`, for a rule whose comparison is a number. */
25
+ readonly threshold?: number;
26
+ readonly for: string;
27
+ readonly severity: 'warning' | 'critical';
28
+ readonly summary: string;
29
+ /** The heading in `docs/ops/06-runbooks.md` the rule's `runbook_url` lands on. */
30
+ readonly anchor: string;
31
+ }
32
+
33
+ /** `alerts.objective`'s default: the share of requests, in percent, answered without a 5xx. */
34
+ export const DEFAULT_OBJECTIVE = 99.9;
35
+
36
+ /** The PromQL error budget for an objective in percent. */
37
+ export const budgetOf = (objective: string): string => `(1 - ${objective} / 100)`;
38
+
39
+ const rule = (alert: Omit<ChartAlert, 'anchor'>): ChartAlert => ({
40
+ ...alert,
41
+ anchor: alert.alert.toLowerCase(),
42
+ });
43
+
44
+ /** The share of requests answered 5xx over `window`, per release. */
45
+ const errorRatio = (s: AlertScope, window: string): string =>
46
+ `(sum by (${s.by}) (rate(${s.series('http_requests_total', 'status="5xx"')}[${window}])) / ` +
47
+ `sum by (${s.by}) (rate(${s.series('http_requests_total')}[${window}])))`;
48
+
49
+ /**
50
+ * Multi-window burn rate (the SRE workbook's): the long window says the budget is really going,
51
+ * the short one that it still is, so the alert resets minutes after the fault does.
52
+ */
53
+ const burn = (s: AlertScope, long: string, short: string, factor: number): string =>
54
+ `${errorRatio(s, long)} > ${s.threshold(factor)} * ${s.budget} and ` +
55
+ `${errorRatio(s, short)} > ${s.threshold(factor)} * ${s.budget}`;
56
+
57
+ export const CHART_ALERTS: readonly ChartAlert[] = [
58
+ rule({
59
+ alert: 'UltimateQueueStalled',
60
+ threshold: 300,
61
+ expr: (s) =>
62
+ `max by (${s.by}, queue) (${s.series('queue_oldest_ready_seconds')}) > ${s.threshold(300)}`,
63
+ for: '5m',
64
+ severity: 'warning',
65
+ summary: 'A queue has a due job nothing has claimed for longer than the threshold',
66
+ }),
67
+ rule({
68
+ alert: 'UltimateDeadLetters',
69
+ expr: (s) => `max by (${s.by}, queue) (${s.series('queue_dead_jobs')}) > 0`,
70
+ for: '5m',
71
+ severity: 'warning',
72
+ summary: 'A queue holds dead-lettered jobs',
73
+ }),
74
+ rule({
75
+ alert: 'UltimateLeaseLost',
76
+ expr: (s) => `sum by (${s.by}, queue) (rate(${s.series('job_leases_lost_total')}[5m])) > 0`,
77
+ for: '5m',
78
+ severity: 'warning',
79
+ summary: 'Job leases are lapsing while their jobs still run, so jobs run twice',
80
+ }),
81
+ rule({
82
+ alert: 'UltimateFramesDropped',
83
+ expr: (s) => `sum by (${s.by}) (rate(${s.series('channel_frames_dropped_total')}[5m])) > 0`,
84
+ for: '5m',
85
+ severity: 'warning',
86
+ summary: 'Sync nodes are dropping channel frames to socket backpressure',
87
+ }),
88
+ rule({
89
+ alert: 'UltimateServerErrors',
90
+ threshold: 0.05,
91
+ expr: (s) =>
92
+ `sum by (${s.by}) (rate(${s.series('http_requests_total', 'status="5xx"')}[5m])) / ` +
93
+ `sum by (${s.by}) (rate(${s.series('http_requests_total')}[5m])) > ${s.threshold(0.05)}`,
94
+ for: '10m',
95
+ severity: 'critical',
96
+ summary: 'The share of requests answered 5xx is above the threshold',
97
+ }),
98
+ rule({
99
+ alert: 'UltimateErrorBudgetFastBurn',
100
+ threshold: 14.4,
101
+ expr: (s) => burn(s, '1h', '5m', 14.4),
102
+ for: '2m',
103
+ severity: 'critical',
104
+ summary: 'The error budget is burning fast enough to spend 2% of a 30-day budget in an hour',
105
+ }),
106
+ rule({
107
+ alert: 'UltimateErrorBudgetSlowBurn',
108
+ threshold: 6,
109
+ expr: (s) => burn(s, '6h', '30m', 6),
110
+ for: '15m',
111
+ severity: 'warning',
112
+ summary: 'The error budget is burning fast enough to spend 5% of a 30-day budget in six hours',
113
+ }),
114
+ rule({
115
+ alert: 'UltimateJobFailures',
116
+ threshold: 0.1,
117
+ expr: (s) =>
118
+ `sum by (${s.by}, queue) (rate(${s.series('jobs_total', 'outcome=~"failed|dead"')}[15m])) / ` +
119
+ `sum by (${s.by}, queue) (rate(${s.series('jobs_total')}[15m])) > ${s.threshold(0.1)}`,
120
+ for: '15m',
121
+ severity: 'warning',
122
+ summary: "The share of a queue's job runs that fail is above the threshold",
123
+ }),
124
+ rule({
125
+ alert: 'UltimatePoolSaturated',
126
+ threshold: 0,
127
+ expr: (s) =>
128
+ `max by (${s.by}, ${s.target}) (${s.series('db_pool_waiting')}) > ${s.threshold(0)}`,
129
+ for: '5m',
130
+ severity: 'warning',
131
+ summary: 'Statements are queuing for a database connection: the pool is at its ceiling',
132
+ }),
133
+ rule({
134
+ alert: 'UltimateEventLoopLag',
135
+ threshold: 0.5,
136
+ expr: (s) =>
137
+ `histogram_quantile(0.99, sum by (${s.by}, ${s.target}, le) ` +
138
+ `(rate(${s.series('process_event_loop_lag_seconds_bucket')}[5m]))) > ${s.threshold(0.5)}`,
139
+ for: '10m',
140
+ severity: 'warning',
141
+ summary: 'A process runs its timers late: the event loop is blocked or the pod is starved',
142
+ }),
143
+ rule({
144
+ alert: 'UltimateMemoryNearLimit',
145
+ threshold: 0.9,
146
+ expr: (s) =>
147
+ `max by (${s.by}, ${s.target}) (${s.series('process_resident_memory_bytes')} / ` +
148
+ `${s.series('process_memory_limit_bytes')}) > ${s.threshold(0.9)}`,
149
+ for: '10m',
150
+ severity: 'warning',
151
+ summary: "A process holds more of its container's memory limit than the threshold",
152
+ }),
153
+ rule({
154
+ alert: 'UltimateTargetDown',
155
+ expr: (s) => `count by (${s.by}, ${s.component}) (${s.series('up')} == 0) > 0`,
156
+ for: '5m',
157
+ severity: 'critical',
158
+ summary: 'A role has a scrape target that is down',
159
+ }),
160
+ ];
@@ -1,87 +1,9 @@
1
1
  // The monitoring objects every Ultimate chart ships: the scrape object and the alert rules. The
2
- // rules are one table, rendered as the chart's PrometheusRule template and as plain rule groups for
3
- // a loader outside Kubernetes. Only mechanism ships — a stalled queue, a dead letter, a lost lease,
4
- // a dropped frame, a 5xx share, a dead target; a latency target is the app's (axiom 8).
2
+ // rules are one table (`scaffold-helm-alert-rules.ts`), rendered here as the chart's PrometheusRule
3
+ // template and as plain rule groups for a loader outside Kubernetes.
5
4
  import type { GeneratedFile, NameSet } from './naming';
6
-
7
- /** How an expression names a series and groups its result, per renderer. */
8
- export interface AlertScope {
9
- /** `name{matchers}` — the scope's own matchers, then `extra`. */
10
- readonly series: (name: string, extra?: string) => string;
11
- /** The labels every rule groups by, so one release (or one job) fires one alert. */
12
- readonly by: string;
13
- /** The label naming a scrape target's role. */
14
- readonly component: string;
15
- /** The rule's threshold, as the renderer spells it: a value lookup or the default. */
16
- readonly threshold: (fallback: number) => string;
17
- }
18
-
19
- export interface ChartAlert {
20
- readonly alert: string;
21
- readonly expr: (scope: AlertScope) => string;
22
- /** The default `alerts.rules.<alert>.threshold`, for a rule whose comparison is a number. */
23
- readonly threshold?: number;
24
- readonly for: string;
25
- readonly severity: 'warning' | 'critical';
26
- readonly summary: string;
27
- /** The heading in `docs/ops/06-runbooks.md` the rule's `runbook_url` lands on. */
28
- readonly anchor: string;
29
- }
30
-
31
- const rule = (alert: Omit<ChartAlert, 'anchor'>): ChartAlert => ({
32
- ...alert,
33
- anchor: alert.alert.toLowerCase(),
34
- });
35
-
36
- export const CHART_ALERTS: readonly ChartAlert[] = [
37
- rule({
38
- alert: 'UltimateQueueStalled',
39
- threshold: 300,
40
- expr: (s) =>
41
- `max by (${s.by}, queue) (${s.series('queue_oldest_ready_seconds')}) > ${s.threshold(300)}`,
42
- for: '5m',
43
- severity: 'warning',
44
- summary: 'A queue has a due job nothing has claimed for longer than the threshold',
45
- }),
46
- rule({
47
- alert: 'UltimateDeadLetters',
48
- expr: (s) => `max by (${s.by}, queue) (${s.series('queue_dead_jobs')}) > 0`,
49
- for: '5m',
50
- severity: 'warning',
51
- summary: 'A queue holds dead-lettered jobs',
52
- }),
53
- rule({
54
- alert: 'UltimateLeaseLost',
55
- expr: (s) => `sum by (${s.by}, queue) (rate(${s.series('job_leases_lost_total')}[5m])) > 0`,
56
- for: '5m',
57
- severity: 'warning',
58
- summary: 'Job leases are lapsing while their jobs still run, so jobs run twice',
59
- }),
60
- rule({
61
- alert: 'UltimateFramesDropped',
62
- expr: (s) => `sum by (${s.by}) (rate(${s.series('channel_frames_dropped_total')}[5m])) > 0`,
63
- for: '5m',
64
- severity: 'warning',
65
- summary: 'Sync nodes are dropping channel frames to socket backpressure',
66
- }),
67
- rule({
68
- alert: 'UltimateServerErrors',
69
- threshold: 0.05,
70
- expr: (s) =>
71
- `sum by (${s.by}) (rate(${s.series('http_requests_total', 'status="5xx"')}[5m])) / ` +
72
- `sum by (${s.by}) (rate(${s.series('http_requests_total')}[5m])) > ${s.threshold(0.05)}`,
73
- for: '10m',
74
- severity: 'critical',
75
- summary: 'The share of requests answered 5xx is above the threshold',
76
- }),
77
- rule({
78
- alert: 'UltimateTargetDown',
79
- expr: (s) => `count by (${s.by}, ${s.component}) (${s.series('up')} == 0) > 0`,
80
- for: '5m',
81
- severity: 'critical',
82
- summary: 'A role has a scrape target that is down',
83
- }),
84
- ];
5
+ import type { AlertScope, ChartAlert } from './scaffold-helm-alert-rules';
6
+ import { budgetOf, CHART_ALERTS, DEFAULT_OBJECTIVE } from './scaffold-helm-alert-rules';
85
7
 
86
8
  /** Where `runbook_url` points unless `alerts.runbookBase` says otherwise. */
87
9
  export const RUNBOOK_BASE =
@@ -99,22 +21,30 @@ export const K8S_SCOPE: AlertScope = {
99
21
  `${name}{${matchers('namespace="{{ $.Release.Namespace }}",app_kubernetes_io_instance="{{ $.Release.Name }}"', extra)}}`,
100
22
  by: 'namespace, app_kubernetes_io_instance',
101
23
  component: 'app_kubernetes_io_component',
24
+ // The operator's own target label: one pod, whichever role it runs.
25
+ target: 'pod',
102
26
  threshold: (fallback) => `{{ ternary $r.threshold ${fallback} (hasKey $r "threshold") }}`,
27
+ budget: budgetOf('{{ $objective }}'),
103
28
  };
104
29
 
105
- const plainScope = (own: string): AlertScope => ({
30
+ const plainScope = (own: string, objective: number): AlertScope => ({
106
31
  series: (name, extra) => {
107
32
  const inner = matchers(own, extra);
108
33
  return inner === '' ? name : `${name}{${inner}}`;
109
34
  },
110
35
  by: 'job',
111
36
  component: 'instance',
37
+ target: 'instance',
112
38
  threshold: (fallback) => String(fallback),
39
+ budget: budgetOf(String(objective)),
113
40
  });
114
41
 
115
- /** The rules as one plain Prometheus rule group, defaults in place, scoped by `own` matchers. */
116
- export function alertRuleGroups(own = ''): string {
117
- const scope = plainScope(own);
42
+ /**
43
+ * The rules as one plain Prometheus rule group, defaults in place, scoped by `own` matchers, the
44
+ * burn-rate rules against `objective` (percent).
45
+ */
46
+ export function alertRuleGroups(own = '', objective: number = DEFAULT_OBJECTIVE): string {
47
+ const scope = plainScope(own, objective);
118
48
  const rules = CHART_ALERTS.map(
119
49
  (a) => ` - alert: ${a.alert}
120
50
  expr: >-
@@ -164,9 +94,14 @@ const operatorGate = (
164
94
  const alertRulesTemplate = (chart: string): string => `{{/*
165
95
  The alert rules for this release's own series, written from @ultimat3/cli's rule table. Each rule
166
96
  reads alerts.rules.<alert> for threshold, for, severity and enabled; its runbook_url is
167
- alerts.runbookBase plus the rule's anchor. Rendered by capability, like servicemonitor.yaml.
97
+ alerts.runbookBase plus the rule's anchor; the burn-rate rules read alerts.objective (percent).
98
+ Rendered by capability, like servicemonitor.yaml.
168
99
  */}}
169
100
  ${operatorGate('alerts', 'PrometheusRule')}
101
+ {{- $objective := float64 (ternary $cfg.objective ${DEFAULT_OBJECTIVE} (hasKey $cfg "objective")) }}
102
+ {{- if not (and (gt $objective 0.0) (lt $objective 100.0)) }}
103
+ {{- fail (printf "alerts.objective is %v — set it to the percent of requests answered without a 5xx, above 0 and below 100, e.g. 99.9" $objective) }}
104
+ {{- end }}
170
105
  {{- $rules := $cfg.rules | default dict }}
171
106
  {{- $base := $cfg.runbookBase | default "${RUNBOOK_BASE}" }}
172
107
  apiVersion: monitoring.coreos.com/v1
@@ -2,6 +2,7 @@
2
2
  // role, the release-phase Job, an optional ingress and an optional per-role autoscaler.
3
3
  // Split from scaffold-helm.ts, which holds the chart's INPUTS (Chart.yaml, values.yaml).
4
4
 
5
+ import { helmDashboardFiles } from './chart-dashboard';
5
6
  import type { GeneratedFile, NameSet } from './naming';
6
7
  import { helmMonitoringFiles } from './scaffold-helm-alerts';
7
8
  import { helmFenceFiles } from './scaffold-helm-fences';
@@ -471,5 +472,6 @@ export function helmTemplateFiles(app: NameSet): readonly GeneratedFile[] {
471
472
  { path: 'docker/helm/templates/hpa.yaml', contents: hpa(app) },
472
473
  ...helmFenceFiles(app),
473
474
  ...helmMonitoringFiles(app),
475
+ ...helmDashboardFiles(app),
474
476
  ];
475
477
  }
@@ -43,12 +43,24 @@ export const ALERTS_VALUES = `# Each rule's runbook_url is runbookBase#<alert, l
43
43
  # threshold, for, severity, enabled — e.g. rules: { UltimateQueueStalled: { threshold: 600 } }.
44
44
  alerts:
45
45
  enabled: auto
46
+ objective: 99.9 # percent of requests answered without a 5xx; the burn-rate rules' budget
46
47
  runbookBase: ${RUNBOOK_BASE}
47
48
  labels: {} # what your operator's ruleSelector matches, if it uses one
48
49
  rules: {}
49
50
 
50
51
  `;
51
52
 
53
+ /** The dashboard's `values.yaml` block, beside the two monitoring ones. */
54
+ export const DASHBOARD_VALUES = `# The Grafana dashboard (dashboards/ultimate-app.json) as a ConfigMap, OFF by default: a Grafana
55
+ # sidecar provisions every ConfigMap carrying its label (kube-prometheus-stack's is the one below).
56
+ # Without a sidecar, import the JSON by hand; it picks namespace and release from process_info.
57
+ dashboard:
58
+ enabled: false
59
+ labels: { grafana_dashboard: "1" }
60
+ annotations: {} # e.g. the sidecar's grafana_folder: Ultimate
61
+
62
+ `;
63
+
52
64
  /**
53
65
  * `appVersion` is the default image tag (`image.tag: ""` below), so it must name a tag that can
54
66
  * exist. `x deploy --image <ref>` overrides both keys, which is the path that actually ships.
@@ -143,7 +155,7 @@ networkPolicy:
143
155
  # METRICS_PORT in the container; move one and the other follows.
144
156
  metricsPort: 9090
145
157
 
146
- ${SERVICE_MONITOR_VALUES}${ALERTS_VALUES}# The image's \`bun\` user, the same uid as the Dockerfile's USER: move one and the other follows.
158
+ ${SERVICE_MONITOR_VALUES}${ALERTS_VALUES}${DASHBOARD_VALUES}# The image's \`bun\` user, the same uid as the Dockerfile's USER: move one and the other follows.
147
159
  podSecurityContext:
148
160
  runAsNonRoot: true
149
161
  runAsUser: ${RUNTIME_UID}
@@ -196,8 +208,10 @@ roles:
196
208
  enabled: true
197
209
  replicas: 2
198
210
  port: 3000
211
+ # Requests are measured idle plus headroom, limits the ceiling: a web pod of the demo app idled
212
+ # at 73 Mi (plan 101 O6, 2026-11-11), so 128Mi; the limit is what an OOMKill reads.
199
213
  resources:
200
- requests: { cpu: 200m, memory: 256Mi }
214
+ requests: { cpu: 200m, memory: 128Mi }
201
215
  limits: { memory: 512Mi }
202
216
  autoscaling:
203
217
  enabled: false
@@ -234,8 +248,9 @@ roles:
234
248
  # exits at once, and a Terminating pod does not hold a rollout back. Added to this role's
235
249
  # terminationGracePeriodSeconds, which the kubelet counts the preStop against.
236
250
  retireSeconds: 3600
251
+ # 160Mi: ROLE=worker of the reference app idled at 138 MiB (Bun 1.4.4, 45 s, 2026-11-13).
237
252
  resources:
238
- requests: { cpu: 200m, memory: 256Mi }
253
+ requests: { cpu: 200m, memory: 160Mi }
239
254
  limits: { memory: 1Gi }
240
255
  autoscaling:
241
256
  enabled: false
@@ -258,7 +273,8 @@ roles:
258
273
  # when every role still built the app's islands first; at 256Mi the pod was OOMKilled on every
259
274
  # boot. Only web builds islands now, so the peak is lower but unmeasured, and the limit stays.
260
275
  resources:
261
- requests: { cpu: 50m, memory: 128Mi }
276
+ # 160Mi: ROLE=scheduler of the reference app idled at 137 MiB (Bun 1.4.4, 45 s, 2026-11-13).
277
+ requests: { cpu: 50m, memory: 160Mi }
262
278
  limits: { memory: 512Mi }
263
279
 
264
280
  replicator: