@ultimat3/cli 31.27.0 → 31.29.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 (134) hide show
  1. package/CLAUDE.md +4 -1
  2. package/README.md +14 -4
  3. package/package.json +29 -29
  4. package/src/app-manifest.ts +6 -1
  5. package/src/app-migrations-verdict.ts +84 -0
  6. package/src/cmd-doctor.ts +11 -3
  7. package/src/cmd-drill.ts +23 -9
  8. package/src/cmd-repro-spec.ts +13 -1
  9. package/src/cmd-repro.ts +37 -5
  10. package/src/cmd-upgrade-codemods.ts +71 -0
  11. package/src/cmd-upgrade-spec.ts +19 -5
  12. package/src/cmd-upgrade.ts +91 -34
  13. package/src/codemods/agents-dev-mcp.ts +50 -0
  14. package/src/codemods/authenticator-session-refusal.ts +214 -0
  15. package/src/codemods/biome-no-default-export.ts +58 -0
  16. package/src/codemods/bunfig-island-coverage.ts +33 -0
  17. package/src/codemods/chart-dashboard.ts +73 -0
  18. package/src/codemods/ci-e2e-browser-stock.ts +75 -0
  19. package/src/codemods/ci-e2e-browser.ts +63 -0
  20. package/src/codemods/codemod.ts +58 -0
  21. package/src/codemods/define-error-leaf.ts +73 -0
  22. package/src/codemods/docs-ci-parts.ts +65 -0
  23. package/src/codemods/docs-gate-prose.ts +53 -0
  24. package/src/codemods/docs-island-rows.ts +31 -0
  25. package/src/codemods/docs-shipped-guards.ts +100 -0
  26. package/src/codemods/docs-test-services.ts +62 -0
  27. package/src/codemods/engine-diff.ts +104 -0
  28. package/src/codemods/engine-edits.ts +111 -0
  29. package/src/codemods/engine-fs.ts +95 -0
  30. package/src/codemods/engine.ts +191 -0
  31. package/src/codemods/format-edited-hook-3122.ts +28 -0
  32. package/src/codemods/format-edited-hook.ts +152 -0
  33. package/src/codemods/helm-alerts-deploy.ts +85 -0
  34. package/src/codemods/helm-alerts-objective.ts +105 -0
  35. package/src/codemods/helm-alerts-stock.ts +108 -0
  36. package/src/codemods/index.ts +60 -0
  37. package/src/codemods/metrics-probe-healthz.ts +47 -0
  38. package/src/codemods/migrate-job-ordered.ts +81 -0
  39. package/src/codemods/migrate-job-stock.ts +41 -0
  40. package/src/codemods/pending.ts +36 -0
  41. package/src/codemods/repro-gitignore.ts +40 -0
  42. package/src/codemods/runtime-pin-lines.ts +109 -0
  43. package/src/codemods/runtime-pin.ts +116 -0
  44. package/src/codemods/solid-floor.ts +63 -0
  45. package/src/codemods/test-ports.ts +86 -0
  46. package/src/codemods/test-suites.ts +37 -0
  47. package/src/codemods/theme-toggle-mount-over.ts +70 -0
  48. package/src/codemods/vendored-guards.ts +186 -0
  49. package/src/codemods/verify-floor-skips.ts +88 -0
  50. package/src/codemods/verify-floor-steps.ts +90 -0
  51. package/src/doctor-advisory-floors.ts +113 -0
  52. package/src/doctor-guards.ts +39 -86
  53. package/src/doctor-superseded.ts +67 -0
  54. package/src/drill-schema-behind.ts +26 -0
  55. package/src/error-codes-doctor.ts +12 -4
  56. package/src/error-codes.ts +9 -0
  57. package/src/exercise-database.ts +7 -2
  58. package/src/framework-schema-apply.ts +7 -19
  59. package/src/framework-schema-stamp.ts +38 -3
  60. package/src/framework-schema-verify.ts +120 -0
  61. package/src/framework-schema-wait.ts +125 -0
  62. package/src/generate-files.ts +6 -5
  63. package/src/guards-built-in-codes.ts +36 -0
  64. package/src/guards-built-in-refusal.ts +25 -0
  65. package/src/guards-built-in.ts +134 -0
  66. package/src/guards-materialize.ts +42 -0
  67. package/src/guards-paths.ts +37 -0
  68. package/src/guards-shipped-names.ts +38 -0
  69. package/src/guards-vendored.ts +73 -0
  70. package/src/guards.ts +90 -34
  71. package/src/index.ts +10 -0
  72. package/src/lint-findings.ts +3 -3
  73. package/src/mcp-errors.ts +12 -1
  74. package/src/measure-scope.ts +23 -3
  75. package/src/messages-repro.ts +16 -2
  76. package/src/messages-upgrade.ts +15 -0
  77. package/src/messages.ts +1 -1
  78. package/src/repro-archive-collect.ts +161 -0
  79. package/src/repro-archive-write.ts +96 -0
  80. package/src/repro-archive.ts +161 -0
  81. package/src/repro-bundle.ts +8 -16
  82. package/src/repro-errors.ts +14 -2
  83. package/src/repro-framework.ts +53 -0
  84. package/src/repro-parse.ts +87 -0
  85. package/src/repro-redact.ts +218 -0
  86. package/src/repro-scrub.ts +257 -0
  87. package/src/role-pg-stats.ts +21 -0
  88. package/src/role-start.ts +4 -0
  89. package/src/runtime-queue.ts +27 -6
  90. package/src/serve-boot-probe.ts +97 -0
  91. package/src/serve-boot.ts +26 -1
  92. package/src/serve-retire.ts +16 -3
  93. package/src/superseded-match.ts +87 -0
  94. package/src/superseded.ts +84 -0
  95. package/src/templates/bun-image.ts +48 -0
  96. package/src/templates/chart-dashboard-panels.ts +178 -0
  97. package/src/templates/chart-dashboard.ts +9 -135
  98. package/src/templates/github/ci.yml.ts +1 -1
  99. package/src/templates/guard-released-forms.ts +112 -0
  100. package/src/templates/guard-runtime-pin-test.ts +54 -0
  101. package/src/templates/guard-runtime-pin.ts +189 -0
  102. package/src/templates/scaffold-claude-agents.ts +6 -6
  103. package/src/templates/scaffold-claude-commands.ts +1 -1
  104. package/src/templates/scaffold-claude-hook.ts +18 -8
  105. package/src/templates/scaffold-claude.ts +2 -2
  106. package/src/templates/scaffold-container.ts +2 -2
  107. package/src/templates/scaffold-docs.ts +26 -24
  108. package/src/templates/scaffold-guards.ts +73 -39
  109. package/src/templates/scaffold-helm-alert-deploy.ts +105 -0
  110. package/src/templates/scaffold-helm-alert-rules.ts +7 -1
  111. package/src/templates/scaffold-helm-alerts.ts +3 -0
  112. package/src/templates/scaffold-helm-migrate.ts +85 -0
  113. package/src/templates/scaffold-helm-templates.ts +2 -36
  114. package/src/templates/scaffold-helm.ts +1 -0
  115. package/src/templates/scaffold-repo.ts +2 -1
  116. package/src/unthrown-codes.ts +2 -0
  117. package/src/upgrade-bun-floor.ts +4 -0
  118. package/src/upgrade-clean-tree.ts +54 -0
  119. package/src/upgrade-gate-codemods-install.ts +40 -0
  120. package/src/upgrade-gate-codemods.ts +151 -0
  121. package/src/upgrade-gate.ts +38 -6
  122. package/src/upgrade-lock.ts +118 -0
  123. package/src/upgrade-plan.ts +2 -1
  124. package/src/upgrade-report-codemods.ts +54 -0
  125. package/src/upgrade-report.ts +52 -27
  126. package/src/upgrade-signals.ts +91 -0
  127. package/src/upgrade-unfinished.ts +61 -0
  128. package/wiki/CLI-Reference.md +70 -5
  129. package/wiki/Deployment.md +2 -1
  130. package/wiki/Interface-Rules.md +17 -8
  131. package/wiki/Known-Gaps.md +1 -1
  132. package/wiki/Observability.md +1 -0
  133. package/wiki/Project-Layout.md +4 -4
  134. package/wiki/Upgrading.md +6 -0
@@ -0,0 +1,218 @@
1
+ // Single responsibility: a repro subject as it may leave the app. Always: input masked by its
2
+ // `.sensitive()` schema and core's `captureValue`, rows minus sealed columns, undeclared entities
3
+ // dropped. By default, every value that is not a key becomes a stand-in the replay fills
4
+ // (`@ultimat3/testing`'s `repro-stand-in.ts`) and the actor's org a placeholder; `includeRows` opts out.
5
+
6
+ import type { FailureBundle, FailureRead } from '@ultimat3/core';
7
+ import { captureValue, REDACTED } from '@ultimat3/core';
8
+ import type { EntityDescription } from '@ultimat3/entity';
9
+ import { maskSensitive } from '@ultimat3/schema';
10
+ import type { ReproSubject } from './repro-bundle';
11
+
12
+ /** The actor a bundle carries; core's barrel names the bundle, not its parts. */
13
+ type FailureActor = NonNullable<FailureBundle['actor']>;
14
+
15
+ /** What the app declared, asked by name: the registries in production, a table in a test. */
16
+ export interface ReproLookups {
17
+ /** The input schema of the job, action or query `name`; `undefined` when none is registered. */
18
+ inputSchema(kind: 'job' | 'action' | 'query', name: string): unknown;
19
+ /** The entity `name`, its description and its sealed properties; `undefined` when undeclared. */
20
+ entity(
21
+ name: string,
22
+ ): { readonly description: EntityDescription; readonly sealed: readonly string[] } | undefined;
23
+ }
24
+
25
+ export interface RedactOptions {
26
+ /** `x repro --bundle --include-rows`: real non-key values. Secrets stay masked either way. */
27
+ readonly includeRows: boolean;
28
+ }
29
+
30
+ export interface RedactedSubject {
31
+ readonly subject: ReproSubject;
32
+ /** The declarations of the entities whose rows the reproducer seeds, by name. */
33
+ readonly entities: readonly EntityDescription[];
34
+ /** Entities whose read rows were dropped: not declared by this app. Sorted, unique. */
35
+ readonly dropped: readonly string[];
36
+ /** Every masked path in the subject: input paths bare, `<entity>:<path>`, `step:<name>:<path>`. */
37
+ readonly masked: readonly string[];
38
+ }
39
+
40
+ /** The actor's org, everywhere it appears: a uuid so a uuid column still takes it. */
41
+ export const ORG_STAND_IN = '00000000-0000-4000-8000-000000000001';
42
+
43
+ /** A key by its name: `id`, `postId`, `post_id`, `tagIds`. What seeding links rows by. */
44
+ const KEY_NAME = /^id$|Ids?$|_ids?$/;
45
+
46
+ const sorted = (paths: Iterable<string>): string[] => [...new Set(paths)].sort();
47
+
48
+ /**
49
+ * Every leaf not under a key name, replaced — `REDACTED` (which the replay fills from the schema)
50
+ * or, where `typed` asks for a shape the replay cannot rebuild, `0` for a number and the boolean as
51
+ * it was. Each replaced path is listed.
52
+ */
53
+ function standIn(value: unknown, at: string, masked: string[], typed: boolean, key = ''): unknown {
54
+ if (value === REDACTED || value === null || value === undefined) return value;
55
+ if (Array.isArray(value))
56
+ return value.map((entry) => standIn(entry, `${at}[]`, masked, typed, key));
57
+ if (typeof value === 'object') {
58
+ const out: Record<string, unknown> = {};
59
+ for (const [name, entry] of Object.entries(value)) {
60
+ const path = at === '' ? name : `${at}.${name}`;
61
+ Object.defineProperty(out, name, {
62
+ value: standIn(entry, path, masked, typed, name),
63
+ enumerable: true,
64
+ writable: true,
65
+ configurable: true,
66
+ });
67
+ }
68
+ return out;
69
+ }
70
+ if (KEY_NAME.test(key)) return value;
71
+ if (typed && typeof value === 'boolean') return value;
72
+ masked.push(at);
73
+ return typed && typeof value === 'number' ? 0 : REDACTED;
74
+ }
75
+
76
+ /** The input, masked by its schema's `.sensitive()` flags, core's capture rules, then stood in. */
77
+ function maskedInput(schema: unknown, input: unknown, options: RedactOptions) {
78
+ const flagged = schema === undefined ? input : maskSensitive(schema, input, REDACTED);
79
+ const { value, masked } = captureValue(flagged);
80
+ const paths = [...masked];
81
+ const kept = options.includeRows ? value : standIn(value, '', paths, false);
82
+ return { value: kept, masked: paths };
83
+ }
84
+
85
+ /** Every string leaf equal to the actor's org, replaced by `ORG_STAND_IN`. */
86
+ function withOrg(value: unknown, org: string): unknown {
87
+ if (value === org) return ORG_STAND_IN;
88
+ if (Array.isArray(value)) return value.map((entry) => withOrg(entry, org));
89
+ if (value === null || typeof value !== 'object') return value;
90
+ const out: Record<string, unknown> = {};
91
+ for (const [name, entry] of Object.entries(value)) {
92
+ Object.defineProperty(out, name, {
93
+ value: withOrg(entry, org),
94
+ enumerable: true,
95
+ writable: true,
96
+ configurable: true,
97
+ });
98
+ }
99
+ return out;
100
+ }
101
+
102
+ function redactJob(
103
+ subject: Extract<ReproSubject, { kind: 'job' }>,
104
+ lookups: ReproLookups,
105
+ options: RedactOptions,
106
+ ): RedactedSubject {
107
+ const { failure } = subject;
108
+ const input = maskedInput(lookups.inputSchema('job', failure.name), failure.input, options);
109
+ const stepMasks: string[] = [];
110
+ const steps = failure.steps.map((step) => {
111
+ const { value, masked } = captureValue(step.output);
112
+ const paths = [...masked];
113
+ const output = options.includeRows ? value : standIn(value, '', paths, true);
114
+ stepMasks.push(...sorted(paths).map((path) => `step:${step.name}:${path}`));
115
+ return { name: step.name, output };
116
+ });
117
+ const inputMasks = sorted([...failure.masked, ...input.masked]);
118
+ return {
119
+ subject: {
120
+ kind: 'job',
121
+ failure: { ...failure, input: input.value, masked: inputMasks, steps },
122
+ },
123
+ entities: [],
124
+ dropped: [],
125
+ masked: [...inputMasks, ...stepMasks],
126
+ };
127
+ }
128
+
129
+ /** The properties a row keeps under stand-ins: its primary key, its references, and key names. */
130
+ const keysOf = (description: EntityDescription): ReadonlySet<string> =>
131
+ new Set(
132
+ description.columns
133
+ .filter((column) => column.primaryKey || column.references !== null)
134
+ .map((column) => column.property),
135
+ );
136
+
137
+ function redactRead(
138
+ read: FailureRead,
139
+ declared: { readonly description: EntityDescription; readonly sealed: readonly string[] },
140
+ options: RedactOptions,
141
+ ): FailureRead {
142
+ const keys = keysOf(declared.description);
143
+ const row = Object.fromEntries(
144
+ Object.entries(read.row).filter(([property]) => !declared.sealed.includes(property)),
145
+ );
146
+ const { value, masked } = captureValue(row);
147
+ const paths = [...read.masked, ...masked];
148
+ const kept = value as Record<string, unknown>;
149
+ if (!options.includeRows) {
150
+ for (const [property, entry] of Object.entries(kept)) {
151
+ if (keys.has(property) || KEY_NAME.test(property) || entry === null || entry === REDACTED)
152
+ continue;
153
+ kept[property] = REDACTED;
154
+ paths.push(property);
155
+ }
156
+ }
157
+ return { entity: read.entity, row: kept, masked: sorted(paths) };
158
+ }
159
+
160
+ function redactRequest(
161
+ subject: Extract<ReproSubject, { kind: 'request' }>,
162
+ lookups: ReproLookups,
163
+ options: RedactOptions,
164
+ ): RedactedSubject {
165
+ const { bundle } = subject;
166
+ const input = maskedInput(
167
+ lookups.inputSchema(bundle.primitive, bundle.name),
168
+ bundle.input,
169
+ options,
170
+ );
171
+ const dropped = new Set<string>();
172
+ const kept = new Map<string, EntityDescription>();
173
+ const reads: FailureRead[] = [];
174
+ for (const read of bundle.reads) {
175
+ const declared = lookups.entity(read.entity);
176
+ if (declared === undefined) {
177
+ dropped.add(read.entity);
178
+ continue;
179
+ }
180
+ kept.set(read.entity, declared.description);
181
+ reads.push(redactRead(read, declared, options));
182
+ }
183
+ const inputMasks = sorted([...bundle.masked, ...input.masked]);
184
+ const org = options.includeRows ? null : (bundle.actor?.orgId ?? null);
185
+ const swap = <T>(value: T): T => (org === null ? value : (withOrg(value, org) as T));
186
+ const actor: FailureActor | null =
187
+ bundle.actor === null || org === null ? bundle.actor : { ...bundle.actor, orgId: ORG_STAND_IN };
188
+ return {
189
+ subject: {
190
+ kind: 'request',
191
+ bundle: {
192
+ ...bundle,
193
+ input: swap(input.value),
194
+ masked: inputMasks,
195
+ actor,
196
+ flags: captureValue(bundle.flags).value as Record<string, unknown>,
197
+ reads: swap(reads),
198
+ truncated: bundle.truncated || dropped.size > 0,
199
+ },
200
+ },
201
+ entities: [...kept.keys()].sort().map((name) => kept.get(name) as EntityDescription),
202
+ dropped: [...dropped].sort(),
203
+ masked: [
204
+ ...inputMasks,
205
+ ...sorted(reads.flatMap((read) => read.masked.map((path) => `${read.entity}:${path}`))),
206
+ ],
207
+ };
208
+ }
209
+
210
+ export function redactSubject(
211
+ subject: ReproSubject,
212
+ lookups: ReproLookups,
213
+ options: RedactOptions,
214
+ ): RedactedSubject {
215
+ return subject.kind === 'job'
216
+ ? redactJob(subject, lookups, options)
217
+ : redactRequest(subject, lookups, options);
218
+ }
@@ -0,0 +1,257 @@
1
+ // Single responsibility: what a repro bundle may say about the MACHINE and the people on it. The app
2
+ // root, home, secret-named / URL / dotenv env values (and a URL's credentials in every encoding),
3
+ // config hostnames, any URL's userinfo and query values, emails and IPs become tokens; a frame's
4
+ // absolute path is made relative. A value it was never told about is NOT found: say so to the user.
5
+
6
+ import { isRedactedKey } from '@ultimat3/core';
7
+
8
+ export interface ScrubEnv {
9
+ readonly name: string;
10
+ readonly value: string | undefined;
11
+ /** `process`: hidden only when secret-named or a URL. `dotenv`: an app file's, always hidden. */
12
+ readonly from: 'process' | 'dotenv';
13
+ }
14
+
15
+ export interface ScrubSources {
16
+ /** The app root, absolute. Becomes `.`. */
17
+ readonly root: string;
18
+ /** Every spelling of the home directory known here. Each becomes `~`. */
19
+ readonly homes: readonly string[];
20
+ readonly env: readonly ScrubEnv[];
21
+ /** Hostnames named by the config (and the machine's own); each becomes `[host]`. */
22
+ readonly hosts: readonly string[];
23
+ }
24
+
25
+ export interface ScrubReport {
26
+ /** Names (never values) of the env vars whose value was found and replaced, sorted. */
27
+ readonly env: readonly string[];
28
+ /** How many distinct hostnames were found and replaced. */
29
+ readonly hosts: number;
30
+ }
31
+
32
+ export interface Scrubber {
33
+ /** Every string leaf and key of a JSON-safe value, scrubbed. */
34
+ value(value: unknown): unknown;
35
+ /** A cause or a stack frame: scrubbed, then any absolute path left made relative. */
36
+ location(text: string): string;
37
+ report(): ScrubReport;
38
+ }
39
+
40
+ interface Needle {
41
+ readonly find: string;
42
+ readonly replace: string;
43
+ readonly env?: string;
44
+ readonly host?: true;
45
+ /** Matched as a whole token only: a URL's user `app` must not eat the `app` in `apps/`. */
46
+ readonly word?: true;
47
+ }
48
+
49
+ /** Shorter than this, a dotenv value is a flag (`true`, `3000`) that would match everywhere. */
50
+ const MIN_ENV_VALUE = 6;
51
+ /** A secret-NAMED var, or a URL's credential, hides from this length: a PIN is still a credential. */
52
+ const MIN_SECRET_VALUE = 3;
53
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '0.0.0.0', '::1', '[::1]']);
54
+
55
+ const parseUrl = (text: string): URL | undefined => {
56
+ if (!text.includes('://')) return undefined;
57
+ try {
58
+ return new URL(text.trim());
59
+ } catch {
60
+ return undefined;
61
+ }
62
+ };
63
+
64
+ /** The hostname inside an env value or config string that is a URL or a DSN, else `undefined`. */
65
+ export function hostOf(text: string): string | undefined {
66
+ const host = parseUrl(text)?.hostname.toLowerCase();
67
+ return host === undefined || host === '' || LOOPBACK.has(host) ? undefined : host;
68
+ }
69
+
70
+ const decoded = (text: string): string => {
71
+ try {
72
+ return decodeURIComponent(text);
73
+ } catch {
74
+ return text;
75
+ }
76
+ };
77
+
78
+ /** Every spelling a credential travels in: as written, URL-decoded, and base64 (a Basic header). */
79
+ function credentialSpellings(value: string): string[] {
80
+ const url = parseUrl(value);
81
+ if (url === undefined || (url.username === '' && url.password === '')) {
82
+ return base64Of([value]);
83
+ }
84
+ const user = decoded(url.username);
85
+ const pass = decoded(url.password);
86
+ return [
87
+ url.username,
88
+ url.password,
89
+ user,
90
+ pass,
91
+ ...base64Of([`${user}:${pass}`, `${url.username}:${url.password}`]),
92
+ ];
93
+ }
94
+
95
+ /**
96
+ * Base64 of each text's UTF-8 bytes — what a Basic header holds; `btoa` alone throws past Latin-1
97
+ * (`pässwörd€`) and took `x repro --bundle` down with it. A spelling that cannot be built is
98
+ * skipped, never the scrub.
99
+ */
100
+ function base64Of(texts: readonly string[]): string[] {
101
+ const out: string[] = [];
102
+ for (const text of texts) {
103
+ try {
104
+ out.push(btoa(String.fromCharCode(...new TextEncoder().encode(text))));
105
+ } catch {
106
+ // One spelling fewer: the raw and decoded values are still needles.
107
+ }
108
+ }
109
+ return out;
110
+ }
111
+
112
+ /** Both separators of a path, so a Windows root pasted either way is found. */
113
+ const spellings = (path: string): string[] =>
114
+ [...new Set([path, path.replaceAll('\\', '/'), path.replaceAll('/', '\\')])].filter(
115
+ (spelling) => spelling.length > 1,
116
+ );
117
+
118
+ function needlesOf(sources: ScrubSources): { paths: Needle[]; values: Needle[] } {
119
+ const paths = [
120
+ ...spellings(sources.root).map((find) => ({ find, replace: '.' })),
121
+ ...sources.homes.flatMap(spellings).map((find) => ({ find, replace: '~' })),
122
+ ];
123
+ const values: Needle[] = [];
124
+ const hosts = new Set(sources.hosts.map((host) => host.toLowerCase()));
125
+ for (const { name, value: raw, from } of sources.env) {
126
+ // Trimmed first: a dotenv `TOKEN="abc\n"` is held by the app, and reaches a log, as `abc`.
127
+ const value = raw?.trim();
128
+ if (value === undefined || value === '') continue;
129
+ const host = hostOf(value);
130
+ if (host !== undefined) hosts.add(host);
131
+ const secret = isRedactedKey(name);
132
+ const hidden = secret || host !== undefined || from === 'dotenv';
133
+ if (!hidden) continue;
134
+ const min = secret ? MIN_SECRET_VALUE : MIN_ENV_VALUE;
135
+ if (value.length >= min) values.push({ find: value, replace: `[env:${name}]`, env: name });
136
+ if (!secret && host === undefined) continue;
137
+ for (const find of credentialSpellings(value)) {
138
+ if (find.length >= MIN_SECRET_VALUE) {
139
+ values.push({ find, replace: `[env:${name}]`, env: name, word: true });
140
+ }
141
+ }
142
+ }
143
+ for (const host of hosts) {
144
+ if (host.length > 2 && !LOOPBACK.has(host))
145
+ values.push({ find: host, replace: '[host]', host: true });
146
+ }
147
+ // Longest first: a URL value is replaced whole before the host inside it is looked for.
148
+ const longest = (a: Needle, b: Needle): number => b.find.length - a.find.length;
149
+ return { paths: paths.sort(longest), values: values.sort(longest) };
150
+ }
151
+
152
+ const literal = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
153
+
154
+ /** A URL in prose: its scheme, then everything up to a space, a quote or a bracket. */
155
+ const URL_TEXT = /\b[a-z][a-z0-9+.-]*:\/\/[^\s'"`<>()]+/gi;
156
+ /** Any URL's userinfo and query VALUES: credentials and tokens ride in both. */
157
+ function withoutUrlSecrets(text: string): string {
158
+ return text.replace(URL_TEXT, (url) =>
159
+ url
160
+ .replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i, '$1[cred]@')
161
+ .replace(/\?[^#]*/, (query) => query.replace(/=[^&]*/g, '=[redacted]')),
162
+ );
163
+ }
164
+
165
+ const EMAIL = /(?<![\w.%+-])[\w.%+-]+@[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]{2,}(?![\w-])/gi;
166
+ const OCTET = '(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)';
167
+ const IPV4 = new RegExp(`(?<![\\w.])(?:${OCTET}\\.){3}${OCTET}(?![\\w.])`, 'g');
168
+ const H = '[0-9a-f]{1,4}';
169
+ /** Eight groups, or a `::` with a group on at least one side: never a clock time or `A::b` in a word. */
170
+ const IPV6 = new RegExp(
171
+ `(?<![\\w:.])(?:(?:${H}:){7}${H}|(?:${H}:){1,7}:(?:${H}(?::${H}){0,5})?|::${H}(?::${H}){0,6})(?![\\w:])`,
172
+ 'gi',
173
+ );
174
+
175
+ /** The first segment of a path that is the machine's, whatever its extension. */
176
+ const SYSTEM_ROOT =
177
+ /^\/(?:home|Users|root|tmp|private|var|opt|usr|etc|srv|mnt|nix|snap|proc|run)\//;
178
+ /** An absolute POSIX path not glued to a word, a URL's `//`, or a token this file wrote. */
179
+ const POSIX_PATH = /(?<![\w.~\]:/>@-])\/(?:[^\s/():'"`,]+\/)*[^\s/():'"`,]+/g;
180
+ const WINDOWS_PATH = /\b[A-Za-z]:\\(?:[^\s\\():'"`,]+\\)*[^\s\\():'"`,]+/g;
181
+
182
+ /** A path that is the machine's: a known system root, or a file (its last segment has an extension). */
183
+ function relativePath(path: string, separator: '/' | '\\'): string {
184
+ const segments = path.split(separator);
185
+ const modules = segments.lastIndexOf('node_modules');
186
+ if (modules >= 0) return segments.slice(modules).join('/');
187
+ const last = segments.at(-1) ?? '';
188
+ const isFile = /\.[A-Za-z0-9]+$/.test(last.replace(/(?::\d+)+$/, ''));
189
+ if (separator === '/' && !isFile && !SYSTEM_ROOT.test(`${path}/`)) return path;
190
+ return `<abs>/${last}`;
191
+ }
192
+
193
+ /**
194
+ * A host is a whole name, and only where a host stands: `checkbox` keeps its `box`, and a host
195
+ * after one `/` (a path segment, a package scope's tail) or after a bare `@` is not one. After a
196
+ * URL's `//` or this file's own `[cred]@` it is.
197
+ */
198
+ const hostPattern = (host: string): RegExp =>
199
+ new RegExp(`(?<![\\w.-])(?<!(?:^|[^/])/)(?<!(?:^|[^\\]])@)${literal(host)}(?![\\w-])`, 'gi');
200
+
201
+ export function scrubberFor(sources: ScrubSources): Scrubber {
202
+ const { paths, values } = needlesOf(sources);
203
+ const hitEnv = new Set<string>();
204
+ const hitHosts = new Set<string>();
205
+ const replaceAll = (out: string, needles: readonly Needle[]): string => {
206
+ let next = out;
207
+ for (const needle of needles) {
208
+ const pattern =
209
+ needle.host === true
210
+ ? hostPattern(needle.find)
211
+ : needle.word === true
212
+ ? new RegExp(`(?<![\\w%+-])${literal(needle.find)}(?![\\w%+-])`, 'g')
213
+ : new RegExp(literal(needle.find), 'g');
214
+ if (!pattern.test(next)) continue;
215
+ next = next.replace(pattern, needle.replace);
216
+ if (needle.env !== undefined) hitEnv.add(needle.env);
217
+ if (needle.host === true) hitHosts.add(needle.find);
218
+ }
219
+ return next;
220
+ };
221
+ const envNeedles = values.filter((needle) => needle.host !== true);
222
+ const hostNeedles = values.filter((needle) => needle.host === true);
223
+ const text = (input: string): string => {
224
+ let out = input;
225
+ for (const needle of paths) out = out.replaceAll(needle.find, needle.replace);
226
+ out = withoutUrlSecrets(replaceAll(out, envNeedles));
227
+ return replaceAll(out, hostNeedles)
228
+ .replace(EMAIL, '[email]')
229
+ .replace(IPV4, '[ip]')
230
+ .replace(IPV6, '[ip]');
231
+ };
232
+ const value = (input: unknown, depth = 0): unknown => {
233
+ if (typeof input === 'string') return text(input);
234
+ if (input === null || typeof input !== 'object') return input;
235
+ if (depth > 32) return '[depth-limit]';
236
+ if (Array.isArray(input)) return input.map((entry) => value(entry, depth + 1));
237
+ const out: Record<string, unknown> = {};
238
+ for (const [key, entry] of Object.entries(input)) {
239
+ // `defineProperty`: a key named `__proto__` in captured input must stay a key.
240
+ Object.defineProperty(out, text(key), {
241
+ value: value(entry, depth + 1),
242
+ enumerable: true,
243
+ writable: true,
244
+ configurable: true,
245
+ });
246
+ }
247
+ return out;
248
+ };
249
+ return {
250
+ value: (input) => value(input),
251
+ location: (input) =>
252
+ text(input.replaceAll('file://', ''))
253
+ .replace(POSIX_PATH, (path) => relativePath(path, '/'))
254
+ .replace(WINDOWS_PATH, (path) => relativePath(path, '\\')),
255
+ report: () => ({ env: [...hitEnv].sort(), hosts: hitHosts.size }),
256
+ };
257
+ }
@@ -0,0 +1,21 @@
1
+ // The scheduler's sampler of the Postgres server's own health (`@ultimat3/db`'s pg stats gauges):
2
+ // one role samples, because these are server facts every pod would read the same of. A real
3
+ // server only — the embedded database is one process's private copy and describes no fleet.
4
+
5
+ import type { PgExecutor, Role } from '@ultimat3/core';
6
+ import { startPostgresStatsGauges } from '@ultimat3/db';
7
+ import type { ServiceMode } from './runtime-bindings';
8
+
9
+ /** The stop, for the role's unwind list; `null` when nothing was started. */
10
+ export function startRolePgStats(
11
+ roles: readonly Role[],
12
+ mode: ServiceMode,
13
+ executor: PgExecutor,
14
+ /** `@ultimat3/db`'s sampler, its own interval; a test hands a recorder, so no timer runs. */
15
+ start: (executor: PgExecutor) => () => Promise<void> = startPostgresStatsGauges,
16
+ ): (() => Promise<void>) | null {
17
+ if (!roles.includes('scheduler') || mode !== 'external') return null;
18
+ // The stop itself, never wrapped: it awaits the round in flight, and a wrapper that dropped
19
+ // that promise let the role's unwind close the pool under a sampling query.
20
+ return start(executor);
21
+ }
package/src/role-start.ts CHANGED
@@ -38,6 +38,7 @@ import {
38
38
  startMetricsEndpoint,
39
39
  whenMetricsPortTaken,
40
40
  } from './metrics-endpoint';
41
+ import { startRolePgStats } from './role-pg-stats';
41
42
  import { rolesUnderRealtime } from './role-realtime';
42
43
  import { startReplicator } from './role-replicator';
43
44
  import { type DeviceMount, hostDeviceSockets } from './role-start-devices';
@@ -429,6 +430,9 @@ export async function startRoles(options: StartRolesOptions): Promise<RunningRol
429
430
  : null;
430
431
  scheduler?.start();
431
432
  if (scheduler !== null) started.push(() => scheduler.stop());
433
+ // The server's own health, sampled beside the scheduler on the primary's executor.
434
+ const pgStats = startRolePgStats(selected, options.runtime.services.db.mode, executor);
435
+ if (pgStats !== null) started.push(pgStats);
432
436
 
433
437
  // Last, and only after the transport it publishes to exists: a replicator started ahead of the
434
438
  // sync node would decode changes with nothing subscribed to receive them, and the slot it
@@ -33,7 +33,7 @@ import {
33
33
  resetJobsFacade,
34
34
  setJobsFacade,
35
35
  } from '@ultimat3/jobs';
36
- import { applyLockedSchema, ensureSchema, verifySchema } from './framework-schema-apply';
36
+ import { applyLockedSchema, ensureSchema } from './framework-schema-apply';
37
37
  import { appExtensions } from './migration-extensions';
38
38
  import type { DevServices } from './runtime-bindings';
39
39
  import type { RuntimeOverrides } from './runtime-overrides';
@@ -142,9 +142,29 @@ export function startDb(services: DevServices, env: ReplicaEnv): StartedDb {
142
142
  */
143
143
  export type SchemaMode = 'apply' | 'ensure' | 'verify';
144
144
 
145
- async function applySchema(client: DevDbClient, mode: SchemaMode): Promise<void> {
146
- if (mode === 'verify') await verifySchema(client);
147
- else if (mode === 'ensure') await ensureSchema(client);
145
+ /** The boot's own facts `'verify'` reads: how long to wait, and what this image ships. */
146
+ interface SchemaBoot {
147
+ readonly root: string;
148
+ /** The env the boot was HANDED — `ULTIMATE_SCHEMA_WAIT_MS` from it, never from `process.env`. */
149
+ readonly env: ReplicaEnv;
150
+ }
151
+
152
+ async function applySchema(client: DevDbClient, mode: SchemaMode, boot: SchemaBoot): Promise<void> {
153
+ // The deadline first: a malformed one is refused before any read, not after a wait.
154
+ if (mode === 'verify') {
155
+ // Behind `await import()`: `ROLE=migrate` and every CLI command reach this module and never
156
+ // verify, so the wait, the ledger verdict and the migrations reader stay off their graphs.
157
+ const [{ verifySchema }, { schemaWaitMsFromEnv }, { readMigrations }] = await Promise.all([
158
+ import('./framework-schema-verify'),
159
+ import('./framework-schema-wait'),
160
+ import('./migrations'),
161
+ ]);
162
+ const deadlineMs = schemaWaitMsFromEnv(boot.env);
163
+ // The image's own migrations — the files `ROLE=migrate` of this same image applies — so a role
164
+ // of release N over release N-1's ledger waits, instead of failing on its first new column.
165
+ const shipped = (await readMigrations(boot.root)).map((migration) => migration.id);
166
+ await verifySchema(client, { deadlineMs, shipped });
167
+ } else if (mode === 'ensure') await ensureSchema(client);
148
168
  else await applyLockedSchema(client);
149
169
  }
150
170
  /**
@@ -182,8 +202,9 @@ async function startJobs(
182
202
  replica: PostgresClient | undefined,
183
203
  overrides: RuntimeOverrides | undefined,
184
204
  schema: SchemaMode,
205
+ boot: SchemaBoot,
185
206
  ): Promise<RunningQueue> {
186
- await applySchema(client, schema);
207
+ await applySchema(client, schema, boot);
187
208
  // Bound to `client`, never the ambient `db()`: the queue and the idempotency reservations stay
188
209
  // on the boot's pool whatever transaction is open.
189
210
  const executor = dbExecutor(() => client);
@@ -313,7 +334,7 @@ export async function startQueue(
313
334
  // Pay the Postgres boot here, so the first request is not the slow one and a broken database
314
335
  // fails at boot rather than on some later query.
315
336
  await db.ping();
316
- return await startJobs(db, replica, overrides, schema);
337
+ return await startJobs(db, replica, overrides, schema, { root: services.root, env });
317
338
  } catch (error) {
318
339
  // `db.ping()` or `startJobs` is where a broken database is supposed to fail. Without this,
319
340
  // the caller exits holding the PGlite lock and the ambient accessors, and nothing is left to
@@ -0,0 +1,97 @@
1
+ // The web or sync role's own port while it boots: `/healthz` from the process's liveness, `/readyz`
2
+ // 503, every other path 503 — so the pod's startup and liveness probes, which knock on THIS port,
3
+ // see a live pod that is not ready while it waits for the migrate step, never a closed socket that
4
+ // restarts it at the startup probe's budget. `bootRoles` stops it just before the role binds.
5
+
6
+ import type { HealthPayload, Role } from '@ultimat3/core';
7
+ import { markListening, readyzPayload, stringField } from '@ultimat3/core';
8
+ import { rolePorts } from './metrics-endpoint';
9
+ import { livenessPayload } from './runtime-liveness';
10
+ import {
11
+ type ListenerTls,
12
+ ListenerTlsInvalidError,
13
+ TLS_CERT_ENV,
14
+ TLS_KEY_ENV,
15
+ } from './serve-env-tls';
16
+
17
+ export interface BootProbe {
18
+ /** Idempotent, and synchronous: the port is free for the role's listener when this returns. */
19
+ stop(): void;
20
+ }
21
+
22
+ export interface BootProbeInput {
23
+ readonly role: Role;
24
+ /** The app port; the sync role's listener is on `PORT + 1` (`rolePorts`). `0` opens none. */
25
+ readonly port: number;
26
+ readonly hostname: string;
27
+ readonly tls?: ListenerTls;
28
+ }
29
+
30
+ /** Seconds a client is told to come back after, while the pod boots. */
31
+ const RETRY_AFTER_S = '5';
32
+
33
+ function answer(payload: HealthPayload, role: Role): Response {
34
+ return Response.json(
35
+ { state: payload.body.state, ready: payload.body.ready, role },
36
+ { status: payload.status, headers: { 'cache-control': 'no-store' } },
37
+ );
38
+ }
39
+
40
+ /** OpenSSL's code alone: its message can quote the input, and the input can be a private key. */
41
+ const OPENSSL_CODE = /^ERR_OSSL_[A-Z0-9_]+$/;
42
+
43
+ /**
44
+ * The FIRST place `TLS_CERT` / `TLS_KEY` reach OpenSSL, before `defineHttpConfig` judges them, so
45
+ * a pair it refuses is `X_CONFIG_INVALID` here (both variables and the code, never the bytes)
46
+ * rather than a bare `ERR_OSSL_*` with no fix. Any other failure (a taken port) is the bind's own.
47
+ */
48
+ function servedWithTls<T>(serve: () => T): T {
49
+ try {
50
+ return serve();
51
+ } catch (error) {
52
+ const code = stringField(error, 'code');
53
+ if (code === undefined || !OPENSSL_CODE.test(code)) throw error;
54
+ throw new ListenerTlsInvalidError({
55
+ name: `${TLS_CERT_ENV} or ${TLS_KEY_ENV}`,
56
+ reason: `was refused by OpenSSL (${code}): the pair must be a PEM certificate and its own PEM private key`,
57
+ });
58
+ }
59
+ }
60
+
61
+ /**
62
+ * `undefined` for the roles whose probes knock on the metrics port — open before any boot work
63
+ * (`serve.ts`) — and for an ephemeral boot (a test), whose real port is not known yet.
64
+ */
65
+ export function openBootProbe(input: BootProbeInput): BootProbe | undefined {
66
+ const port = rolePorts(input.port, [input.role])[0]?.port;
67
+ if (port === undefined) return undefined;
68
+ const { role } = input;
69
+ const serve = () =>
70
+ Bun.serve({
71
+ port,
72
+ hostname: input.hostname,
73
+ ...(input.tls === undefined ? {} : { tls: { cert: input.tls.cert, key: input.tls.key } }),
74
+ fetch(request: Request): Response {
75
+ const path = new URL(request.url).pathname;
76
+ if (path === '/healthz') return answer(livenessPayload(), role);
77
+ if (path === '/readyz') return answer(readyzPayload(), role);
78
+ // Not served from a half-booted process: a request that reached a pod no probe called ready
79
+ // is told to come back, never answered by a schema it cannot read yet.
80
+ return Response.json(
81
+ { state: 'starting', ready: false, role },
82
+ { status: 503, headers: { 'cache-control': 'no-store', 'retry-after': RETRY_AFTER_S } },
83
+ );
84
+ },
85
+ });
86
+ const server = input.tls === undefined ? serve() : servedWithTls(serve);
87
+ const stopListening = markListening(server.url.origin);
88
+ let stopped = false;
89
+ return {
90
+ stop(): void {
91
+ if (stopped) return;
92
+ stopped = true;
93
+ server.stop(true);
94
+ stopListening();
95
+ },
96
+ };
97
+ }