@ultimat3/cli 31.25.0 → 31.27.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 (123) hide show
  1. package/CLAUDE.md +44 -36
  2. package/README.md +5 -4
  3. package/package.json +29 -29
  4. package/src/app-mcp.ts +17 -3
  5. package/src/cmd-cache-spec.ts +5 -2
  6. package/src/cmd-db-recount.ts +7 -0
  7. package/src/cmd-db-spec.ts +2 -3
  8. package/src/cmd-db.ts +0 -2
  9. package/src/cmd-deploy-verify-sample.ts +93 -0
  10. package/src/cmd-deploy-verify.ts +2 -41
  11. package/src/cmd-dev-spec.ts +15 -1
  12. package/src/cmd-dev.ts +31 -4
  13. package/src/cmd-doctor.ts +4 -1
  14. package/src/cmd-exercise-spec.ts +7 -1
  15. package/src/cmd-exercise.ts +22 -10
  16. package/src/cmd-generate.ts +2 -0
  17. package/src/cmd-jobs-spec.ts +3 -6
  18. package/src/cmd-jobs.ts +1 -7
  19. package/src/cmd-logs-spec.ts +2 -1
  20. package/src/cmd-logs.ts +9 -28
  21. package/src/cmd-planned.ts +11 -45
  22. package/src/cmd-profile-frames.ts +99 -0
  23. package/src/cmd-profile-spec.ts +24 -0
  24. package/src/cmd-profile.ts +164 -0
  25. package/src/cmd-status-sample.ts +57 -0
  26. package/src/cmd-status-spec.ts +30 -0
  27. package/src/cmd-status.ts +108 -0
  28. package/src/cmd-token-spec.ts +5 -2
  29. package/src/cmd-token.ts +7 -3
  30. package/src/coverage-island.ts +121 -0
  31. package/src/coverage-lcov.ts +49 -5
  32. package/src/coverage-remap.ts +146 -0
  33. package/src/db-replay-engine-prepared.ts +66 -0
  34. package/src/db-replay-engine-template.ts +156 -0
  35. package/src/db-replay-engine.ts +4 -0
  36. package/src/db-replay-scratch-reap.ts +54 -0
  37. package/src/deploy-verify-flags.ts +9 -2
  38. package/src/deploy-verify-grade.ts +10 -3
  39. package/src/dev-boot.ts +14 -1
  40. package/src/dev-dashboard-guard.ts +57 -10
  41. package/src/dev-host.ts +46 -0
  42. package/src/dev-tls-cache.ts +103 -0
  43. package/src/dev-tls-der.ts +69 -0
  44. package/src/dev-tls.ts +120 -0
  45. package/src/dispatch.ts +6 -1
  46. package/src/doctor-browser.ts +60 -0
  47. package/src/error-codes-verify.ts +47 -0
  48. package/src/error-codes.ts +14 -23
  49. package/src/exercise-database.ts +40 -7
  50. package/src/exercise-push-device.ts +51 -0
  51. package/src/exercise-route-api.ts +74 -0
  52. package/src/exercise-routes.ts +14 -5
  53. package/src/exercise-services.ts +3 -1
  54. package/src/exercise-shard-flag.ts +47 -0
  55. package/src/fix-command.ts +2 -2
  56. package/src/generate-factories.ts +9 -11
  57. package/src/generate-feature-required.ts +9 -4
  58. package/src/generate-files.ts +20 -2
  59. package/src/generate-kinds.ts +5 -1
  60. package/src/guards.ts +21 -6
  61. package/src/island-bundle-options.ts +48 -0
  62. package/src/island-bundle.ts +18 -46
  63. package/src/island-link.ts +5 -0
  64. package/src/island-outputs.ts +5 -0
  65. package/src/mcp-errors-verify.ts +35 -0
  66. package/src/mcp-errors.ts +10 -19
  67. package/src/mcp-host-logs.ts +121 -0
  68. package/src/mcp-host.ts +12 -73
  69. package/src/messages-floor.ts +19 -0
  70. package/src/messages-status.ts +10 -0
  71. package/src/messages.ts +21 -0
  72. package/src/registry.ts +4 -0
  73. package/src/role-start-types.ts +7 -0
  74. package/src/role-start.ts +4 -0
  75. package/src/serve-boot.ts +7 -1
  76. package/src/serve-env-tls.ts +57 -0
  77. package/src/solid-loader.ts +27 -10
  78. package/src/templates/generate-export-rows.ts +136 -0
  79. package/src/templates/generate-import-rows.ts +186 -0
  80. package/src/templates/generate-rows-slice.ts +95 -0
  81. package/src/templates/github/ci.yml.ts +4 -0
  82. package/src/templates/scaffold-db-package.ts +3 -0
  83. package/src/templates/scaffold-docs.ts +8 -6
  84. package/src/templates/scaffold-repo.ts +2 -7
  85. package/src/templates/scaffold-site.ts +4 -1
  86. package/src/templates/scaffold-suites.ts +72 -0
  87. package/src/templates/scaffold-test-services.ts +35 -10
  88. package/src/templates/scaffold-verify-floor.ts +53 -31
  89. package/src/templates/shapes/api.ts +4 -0
  90. package/src/templates/slice-foundation.ts +3 -3
  91. package/src/unthrown-codes.ts +1 -1
  92. package/src/upgrade-gate.ts +6 -1
  93. package/src/upgrade-guards-baseline.ts +43 -0
  94. package/src/upgrade-guards.ts +37 -2
  95. package/src/upgrade-report.ts +3 -0
  96. package/src/verify-coverage-run.ts +42 -11
  97. package/src/verify-e2e.ts +115 -4
  98. package/src/verify-floor.ts +27 -0
  99. package/src/verify-guard-baseline.ts +109 -0
  100. package/src/verify-live.ts +72 -0
  101. package/src/verify-merge-skips.ts +51 -0
  102. package/src/verify-merge.ts +36 -2
  103. package/src/verify-run.ts +48 -7
  104. package/src/verify-services.ts +287 -0
  105. package/src/verify-skip-reason.ts +53 -0
  106. package/src/verify-strict.ts +108 -0
  107. package/src/verify-test-command.ts +129 -0
  108. package/src/verify-tests.ts +39 -126
  109. package/types/babel-modules.d.ts +2 -0
  110. package/wiki/Agents.md +2 -5
  111. package/wiki/CLI-Reference.md +142 -23
  112. package/wiki/Caching-And-Invalidation.md +1 -1
  113. package/wiki/Entities-And-Migrations.md +1 -1
  114. package/wiki/Interface-Rules.md +5 -0
  115. package/wiki/Jobs-And-Workflows.md +3 -3
  116. package/wiki/Known-Gaps.md +5 -1
  117. package/wiki/MCP-And-AI.md +103 -2
  118. package/wiki/Mail.md +52 -0
  119. package/wiki/PWA-And-Offline.md +1 -1
  120. package/wiki/Scraping.md +19 -4
  121. package/wiki/Troubleshooting.md +3 -3
  122. package/wiki/Tutorial-05-Deploy-Free.md +2 -2
  123. package/wiki/Upgrading.md +3 -0
@@ -0,0 +1,46 @@
1
+ // Which interface `x dev` binds: `--host`, else loopback. Validated at the boundary, because a
2
+ // typo handed to `Bun.serve` fails as an uncoded bind error and a hostname binds wherever DNS
3
+ // points today. A wider bind is something the caller types; loopback stays the default.
4
+
5
+ import { classifyAddress } from '@ultimat3/core';
6
+ import { BadFlagError } from './errors';
7
+ import { isLoopbackHostname } from './loopback-host';
8
+ import type { ParsedArgs } from './parse';
9
+ import { flagString } from './parse';
10
+ import { DEV_BINDING } from './web-binding';
11
+
12
+ const unbracketed = (raw: string): string =>
13
+ raw.startsWith('[') && raw.endsWith(']') ? raw.slice(1, -1) : raw;
14
+
15
+ /** `localhost` or an address LITERAL — `0.0.0.0` and `::` included — never a name to resolve. */
16
+ export function devHostFor(args: ParsedArgs): string {
17
+ const raw = flagString(args, 'host');
18
+ if (raw === undefined) return DEV_BINDING.hostname;
19
+ const host = unbracketed(raw.trim());
20
+ if (host.toLowerCase() === 'localhost') return 'localhost';
21
+ if (classifyAddress(host) !== undefined) return host;
22
+ throw new BadFlagError({
23
+ flag: 'host',
24
+ command: 'dev',
25
+ reason: `expects localhost or an IP address literal (IPv4, IPv6, 0.0.0.0, ::), got "${raw}"`,
26
+ fix: 'x dev --host 0.0.0.0',
27
+ });
28
+ }
29
+
30
+ /**
31
+ * The url a client on THIS machine dials. A wildcard bind answers on loopback too, and Bun reports
32
+ * it as `http://0.0.0.0:<port>` — an address a browser may refuse and `/_x` (a loopback Host
33
+ * only) always does — so it is reported as `localhost`. A specific address is reported as itself.
34
+ */
35
+ export function dialableUrl(url: string): string {
36
+ const parsed = URL.parse(url);
37
+ if (parsed === null || classifyAddress(parsed.hostname) !== 'unspecified') return url;
38
+ parsed.hostname = 'localhost';
39
+ return parsed.origin;
40
+ }
41
+
42
+ /** `/_x` on this server, or null when its bind leaves no loopback address to reach it on. */
43
+ export function dashboardUrl(url: string): string | null {
44
+ const parsed = URL.parse(url);
45
+ return parsed !== null && isLoopbackHostname(parsed.hostname) ? `${parsed.origin}/_x` : null;
46
+ }
@@ -0,0 +1,103 @@
1
+ // `x dev --tls`'s certificate on disk: `.x/tls/` (0700; gitignored, never committed), the key
2
+ // created 0600, and `meta.json` written last as the one thing that vouches for the pair. Reused
3
+ // while the names match, its end is not near and the cert and key belong together; else regenerated.
4
+
5
+ // why: WebCrypto parses no X.509, and the cached cert must be proven to match the cached key.
6
+ import { createPrivateKey, X509Certificate } from 'node:crypto';
7
+ // why: Bun.write takes no file mode — the key is CREATED 0600 in a 0700 directory, never chmod'ed after.
8
+ import { chmod, mkdir, rm, stat, writeFile } from 'node:fs/promises';
9
+ // why: Bun exposes no path-join primitive; Bun.file takes one already joined.
10
+ import { join } from 'node:path';
11
+ import type { CertificatePair } from './dev-tls';
12
+ import { DAY_MS, DEV_CERT_DAYS, selfSignedCertificate } from './dev-tls';
13
+
14
+ /** Inside this window of its end, a cached certificate is replaced rather than served. */
15
+ const RENEW_WITHIN_MS = 7 * DAY_MS;
16
+
17
+ export interface DevCertificate extends CertificatePair {
18
+ /** Where the certificate sits, for `curl --cacert` or a browser's trust store. */
19
+ readonly certPath: string;
20
+ }
21
+
22
+ interface CachedMeta {
23
+ readonly names: readonly string[];
24
+ readonly notAfter: number;
25
+ }
26
+
27
+ async function readMeta(path: string): Promise<CachedMeta | undefined> {
28
+ const file = Bun.file(path);
29
+ if (!(await file.exists())) return undefined;
30
+ const parsed: unknown = await file.json().catch(() => undefined);
31
+ if (typeof parsed !== 'object' || parsed === null) return undefined;
32
+ const { names, notAfter } = parsed as Record<string, unknown>;
33
+ if (!Array.isArray(names) || typeof notAfter !== 'number') return undefined;
34
+ return { names: names.filter((name): name is string => typeof name === 'string'), notAfter };
35
+ }
36
+
37
+ /**
38
+ * The cached key exists and no one but its owner can read it. A wider mode — a copy, an editor's
39
+ * save under umask 0002 — is not served: the pair is regenerated. Windows has no POSIX mode bits
40
+ * to read, so there the file's existence is the whole check.
41
+ */
42
+ async function keyIsPrivate(path: string): Promise<boolean> {
43
+ const found = await stat(path).catch(() => undefined);
44
+ if (found === undefined || !found.isFile()) return false;
45
+ return process.platform === 'win32' || (found.mode & 0o077) === 0;
46
+ }
47
+
48
+ /**
49
+ * The cached cert and key when they BELONG together — a key written by a regeneration that never
50
+ * reached its cert would otherwise be served beside the old cert, and every handshake fails.
51
+ */
52
+ async function cachedPair(certPath: string, keyPath: string): Promise<CertificatePair | undefined> {
53
+ const cert = await Bun.file(certPath)
54
+ .text()
55
+ .catch(() => undefined);
56
+ const key = await Bun.file(keyPath)
57
+ .text()
58
+ .catch(() => undefined);
59
+ if (cert === undefined || key === undefined) return undefined;
60
+ try {
61
+ return new X509Certificate(cert).checkPrivateKey(createPrivateKey(key))
62
+ ? { cert, key }
63
+ : undefined;
64
+ } catch {
65
+ return undefined; // unparseable is as stale as mismatched: regenerated, never served
66
+ }
67
+ }
68
+
69
+ /** The cached pair when it carries exactly `names` and is not near its end; else a new one, written. */
70
+ export async function devCertificate(input: {
71
+ readonly stateDir: string;
72
+ readonly names: readonly string[];
73
+ readonly now: Date;
74
+ }): Promise<DevCertificate> {
75
+ const dir = join(input.stateDir, 'tls');
76
+ const certPath = join(dir, 'cert.pem');
77
+ const keyPath = join(dir, 'key.pem');
78
+ const metaPath = join(dir, 'meta.json');
79
+ const names = [...new Set(input.names)].sort();
80
+ const meta = await readMeta(metaPath);
81
+ const fresh =
82
+ meta !== undefined &&
83
+ meta.names.join(',') === names.join(',') &&
84
+ meta.notAfter - input.now.getTime() > RENEW_WITHIN_MS;
85
+ if (fresh && (await keyIsPrivate(keyPath))) {
86
+ const cached = await cachedPair(certPath, keyPath);
87
+ if (cached !== undefined) return { ...cached, certPath };
88
+ }
89
+ const pair = await selfSignedCertificate({ names, now: input.now });
90
+ await mkdir(dir, { recursive: true, mode: 0o700 });
91
+ await chmod(dir, 0o700); // an existing `.x/tls` keeps whatever mode it was made with otherwise
92
+ // meta.json FIRST: it is what vouches for the pair, so a run killed (or failing) between the
93
+ // key and the cert leaves nothing vouching for the torn pair, and the next boot regenerates.
94
+ await rm(metaPath, { force: true });
95
+ // Removed, then created exclusively at 0600: a write over an existing 0644 file keeps 0644, and
96
+ // a chmod after the write leaves a window in which the key is readable by everyone.
97
+ await rm(keyPath, { force: true });
98
+ await writeFile(keyPath, pair.key, { mode: 0o600, flag: 'wx' });
99
+ await Bun.write(certPath, pair.cert);
100
+ const notAfter = input.now.getTime() + DEV_CERT_DAYS * DAY_MS;
101
+ await Bun.write(metaPath, JSON.stringify({ names, notAfter }));
102
+ return { ...pair, certPath };
103
+ }
@@ -0,0 +1,69 @@
1
+ // The DER this package writes, and no more: the handful of ASN.1 types a self-signed X.509 needs
2
+ // (`dev-tls.ts`). Hand-written because the alternative is a certificate dependency or shelling out
3
+ // to openssl, and neither earns its place for one local certificate (docs/idea/18-build-vs-wrap.md).
4
+
5
+ const lengthOf = (length: number): number[] => {
6
+ if (length < 0x80) return [length];
7
+ const bytes: number[] = [];
8
+ for (let rest = length; rest > 0; rest = Math.floor(rest / 256)) bytes.unshift(rest % 256);
9
+ return [0x80 | bytes.length, ...bytes];
10
+ };
11
+
12
+ /** One tag-length-value; the contents already encoded. */
13
+ export const tlv = (tag: number, ...contents: readonly Uint8Array[]): Uint8Array => {
14
+ const body = Buffer.concat(contents);
15
+ return Uint8Array.from([tag, ...lengthOf(body.length), ...body]);
16
+ };
17
+
18
+ export const sequence = (...items: readonly Uint8Array[]): Uint8Array => tlv(0x30, ...items);
19
+ export const set = (...items: readonly Uint8Array[]): Uint8Array => tlv(0x31, ...items);
20
+ export const octets = (bytes: Uint8Array): Uint8Array => tlv(0x04, bytes);
21
+ export const utf8 = (text: string): Uint8Array => tlv(0x0c, new TextEncoder().encode(text));
22
+ /** `[n] EXPLICIT`: a constructed context tag around the encoded value. */
23
+ export const explicit = (n: number, value: Uint8Array): Uint8Array => tlv(0xa0 | n, value);
24
+ export const bitString = (bytes: Uint8Array): Uint8Array => tlv(0x03, Uint8Array.of(0), bytes);
25
+ export const bool = (value: boolean): Uint8Array => Uint8Array.of(0x01, 0x01, value ? 0xff : 0);
26
+
27
+ /** An unsigned big-endian magnitude as INTEGER: no redundant zeros, a 0x00 before a high bit. */
28
+ export const integer = (magnitude: Uint8Array): Uint8Array => {
29
+ let start = 0;
30
+ while (start < magnitude.length - 1 && magnitude[start] === 0) start += 1;
31
+ const trimmed = magnitude.subarray(start);
32
+ const pad = (trimmed[0] ?? 0) & 0x80 ? Uint8Array.of(0) : new Uint8Array(0);
33
+ return tlv(0x02, pad, trimmed);
34
+ };
35
+
36
+ /** Dotted OID, base-128 per arc after the first two. */
37
+ export const oid = (dotted: string): Uint8Array => {
38
+ const arcs = dotted.split('.').map(Number);
39
+ const bytes: number[] = [(arcs[0] ?? 0) * 40 + (arcs[1] ?? 0)];
40
+ for (const arc of arcs.slice(2)) {
41
+ const group: number[] = [arc % 128];
42
+ for (let rest = Math.floor(arc / 128); rest > 0; rest = Math.floor(rest / 128)) {
43
+ group.unshift(0x80 | (rest % 128));
44
+ }
45
+ bytes.push(...group);
46
+ }
47
+ return tlv(0x06, Uint8Array.from(bytes));
48
+ };
49
+
50
+ /** UTCTime until 2049, GeneralizedTime after — RFC 5280 §4.1.2.5, always UTC, always seconds. */
51
+ export const time = (at: Date): Uint8Array => {
52
+ const iso = at.toISOString(); // UTC by definition: `YYYY-MM-DDTHH:MM:SS.sssZ`
53
+ const digits = `${iso.slice(0, 4)}${iso.slice(5, 7)}${iso.slice(8, 10)}${iso.slice(11, 13)}${iso.slice(14, 16)}${iso.slice(17, 19)}Z`;
54
+ const utc = at.getUTCFullYear() < 2050;
55
+ return tlv(utc ? 0x17 : 0x18, new TextEncoder().encode(utc ? digits.slice(2) : digits));
56
+ };
57
+
58
+ /** WebCrypto's ECDSA signature is `r || s`; X.509 carries `SEQUENCE { INTEGER r, INTEGER s }`. */
59
+ export const ecdsaSignature = (raw: Uint8Array): Uint8Array => {
60
+ const half = raw.length / 2;
61
+ return sequence(integer(raw.subarray(0, half)), integer(raw.subarray(half)));
62
+ };
63
+
64
+ /** PEM armour, 64 columns, the label as RFC 7468 spells it. */
65
+ export const pem = (label: string, der: Uint8Array): string => {
66
+ const base64 = Buffer.from(der).toString('base64');
67
+ const lines = base64.match(/.{1,64}/g) ?? [];
68
+ return `-----BEGIN ${label}-----\n${lines.join('\n')}\n-----END ${label}-----\n`;
69
+ };
package/src/dev-tls.ts ADDED
@@ -0,0 +1,120 @@
1
+ // `x dev --tls`'s certificate: a self-signed ECDSA P-256 X.509 built from WebCrypto alone, and
2
+ // the names a bind needs it to carry. Cached on disk by `dev-tls-cache.ts`.
3
+
4
+ import { classifyAddress } from '@ultimat3/core';
5
+ import {
6
+ bitString,
7
+ bool,
8
+ ecdsaSignature,
9
+ explicit,
10
+ integer,
11
+ octets,
12
+ oid,
13
+ pem,
14
+ sequence,
15
+ set,
16
+ time,
17
+ tlv,
18
+ utf8,
19
+ } from './dev-tls-der';
20
+
21
+ export const DAY_MS = 86_400_000;
22
+ /** Short on purpose: a local certificate is regenerated for free, and browsers cap leaf lifetimes. */
23
+ export const DEV_CERT_DAYS = 90;
24
+
25
+ const ECDSA_SHA256 = sequence(oid('1.2.840.10045.4.3.2'));
26
+ const SUBJECT = sequence(set(sequence(oid('2.5.4.3'), utf8('x dev local certificate'))));
27
+
28
+ export interface CertificatePair {
29
+ readonly cert: string;
30
+ readonly key: string;
31
+ }
32
+
33
+ /** Sixteen hex groups → bytes; `URL` first, so every spelling (`::ffff:1.2.3.4` too) is canonical. */
34
+ function v6Bytes(address: string): Uint8Array {
35
+ const canonical = (URL.parse(`http://[${address.split('%')[0]}]`)?.hostname ?? '[::]').slice(
36
+ 1,
37
+ -1,
38
+ );
39
+ const [head = '', tail] = canonical.split('::');
40
+ const left = head === '' ? [] : head.split(':');
41
+ const right = tail === undefined || tail === '' ? [] : tail.split(':');
42
+ const groups = [...left, ...Array<string>(8 - left.length - right.length).fill('0'), ...right];
43
+ const bytes = new Uint8Array(16);
44
+ groups.forEach((group, index) => {
45
+ const value = Number.parseInt(group, 16);
46
+ bytes[index * 2] = value >> 8;
47
+ bytes[index * 2 + 1] = value & 0xff;
48
+ });
49
+ return bytes;
50
+ }
51
+
52
+ /** `iPAddress [7]` for a literal, `dNSName [2]` for anything else — both IMPLICIT, primitive. */
53
+ function generalName(name: string): Uint8Array {
54
+ if (classifyAddress(name) === undefined) return tlv(0x82, new TextEncoder().encode(name));
55
+ const bytes = name.includes(':') ? v6Bytes(name) : Uint8Array.from(name.split('.').map(Number));
56
+ return tlv(0x87, bytes);
57
+ }
58
+
59
+ const extension = (id: string, critical: boolean, value: Uint8Array): Uint8Array =>
60
+ sequence(oid(id), ...(critical ? [bool(true)] : []), octets(value));
61
+
62
+ function serialNumber(): Uint8Array {
63
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
64
+ bytes[0] = ((bytes[0] ?? 0) & 0x7f) | 0x01; // positive and never a leading zero (RFC 5280 §4.1.2.2)
65
+ return bytes;
66
+ }
67
+
68
+ /** A fresh pair carrying `names` in its subjectAltName — the only field a client matches on. */
69
+ export async function selfSignedCertificate(input: {
70
+ readonly names: readonly string[];
71
+ readonly now: Date;
72
+ }): Promise<CertificatePair> {
73
+ const keys = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [
74
+ 'sign',
75
+ 'verify',
76
+ ]);
77
+ const spki = new Uint8Array(await crypto.subtle.exportKey('spki', keys.publicKey));
78
+ const tbs = sequence(
79
+ explicit(0, integer(Uint8Array.of(2))), // v3
80
+ integer(serialNumber()),
81
+ ECDSA_SHA256,
82
+ SUBJECT,
83
+ sequence(
84
+ time(new Date(input.now.getTime() - 3_600_000)),
85
+ time(new Date(input.now.getTime() + DEV_CERT_DAYS * DAY_MS)),
86
+ ),
87
+ SUBJECT,
88
+ spki,
89
+ explicit(
90
+ 3,
91
+ sequence(
92
+ extension('2.5.29.19', true, sequence()), // basicConstraints: not a CA
93
+ extension('2.5.29.37', false, sequence(oid('1.3.6.1.5.5.7.3.1'))), // serverAuth
94
+ extension('2.5.29.17', false, sequence(...input.names.map(generalName))),
95
+ ),
96
+ ),
97
+ );
98
+ const raw = new Uint8Array(
99
+ await crypto.subtle.sign(
100
+ { name: 'ECDSA', hash: 'SHA-256' },
101
+ keys.privateKey,
102
+ new Uint8Array(tbs),
103
+ ),
104
+ );
105
+ const der = sequence(tbs, ECDSA_SHA256, bitString(ecdsaSignature(raw)));
106
+ const pkcs8 = new Uint8Array(await crypto.subtle.exportKey('pkcs8', keys.privateKey));
107
+ return { cert: pem('CERTIFICATE', der), key: pem('PRIVATE KEY', pkcs8) };
108
+ }
109
+
110
+ /**
111
+ * The names a certificate for a bind on `hostname` carries: loopback in every spelling, plus the
112
+ * address itself when it is a specific one a client on another machine would dial.
113
+ */
114
+ export function certificateNames(hostname: string): readonly string[] {
115
+ const base = ['localhost', '127.0.0.1', '::1'];
116
+ // A wildcard is dialled as loopback; any other literal — `127.0.0.2` included — is the url printed.
117
+ const kind = classifyAddress(hostname);
118
+ const dialled = kind !== undefined && kind !== 'unspecified' && !base.includes(hostname);
119
+ return dialled ? [...base, hostname] : base;
120
+ }
package/src/dispatch.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  // why: a synchronous bin probe at the one place a result is rendered; Bun has no path helpers.
6
6
  import { existsSync } from 'node:fs';
7
7
  import { dirname, isAbsolute, join, resolve } from 'node:path';
8
- import { setLogStream } from '@ultimat3/core';
8
+ import { currentLogStream, setLogStream } from '@ultimat3/core';
9
9
  import { requireAppRoot, requireBunVersion } from './app-root';
10
10
  import { createHelpCommand } from './cmd-help';
11
11
  import { plannedCommandError, plannedCommandFor } from './cmd-planned';
@@ -166,6 +166,9 @@ export async function dispatch(options: DispatchOptions): Promise<number> {
166
166
  ...(options.invocation === undefined ? {} : { invocation: options.invocation }),
167
167
  };
168
168
 
169
+ // Put back in the `finally`: the stream is process-wide, so a dispatch that left `stderr` behind
170
+ // moved every later line of an embedding process — the next test file's, on a shared worker.
171
+ const callerStream = currentLogStream();
169
172
  try {
170
173
  // `--json` means fd 1 carries ONE document, and every command that boots an app logs through
171
174
  // core's module-scope `logger`, whose default writer is stdout: `x db migrate --json` printed
@@ -197,5 +200,7 @@ export async function dispatch(options: DispatchOptions): Promise<number> {
197
200
  const result = errorResult(args.command, error);
198
201
  sinkFor(result, options)(render(result, args.json, false, reader));
199
202
  return 1;
203
+ } finally {
204
+ setLogStream(callerStream);
200
205
  }
201
206
  }
@@ -0,0 +1,60 @@
1
+ // `x doctor`'s browser report: which Chrome the e2e driver would launch on this machine, or that
2
+ // there is none and the command that installs one. A WARNING only where `x.verify.json` requires
3
+ // `e2e` — the case `x verify` reds (`judgeE2eBrowser`) — so an app that upgrades keeps its verdict.
4
+
5
+ import { findChrome } from '@ultimat3/scraping/cdp';
6
+ import { msg } from './messages';
7
+ import type { CommandResult, Finding, JsonValue } from './output';
8
+ import { browserInstallCommand, e2eBrowserMissingFinding } from './verify-e2e';
9
+ import { floorRequires, readVerifyFloor } from './verify-floor';
10
+
11
+ type Env = Readonly<Record<string, string | undefined>>;
12
+
13
+ export interface BrowserFact {
14
+ /** The binary `findChrome` answered, or `undefined` when this machine has none it can start. */
15
+ readonly path: string | undefined;
16
+ /** Whether `x.verify.json` names `e2e`, which turns an absent browser into a red gate. */
17
+ readonly required: boolean;
18
+ /** The finding an absent browser is, pre-rendered for this platform and environment. */
19
+ readonly missing: Finding;
20
+ /** The install command for this platform, for the report line. */
21
+ readonly install: string;
22
+ }
23
+
24
+ /** The I/O half. `undefined` outside an app: there is no floor and no e2e suite to report on. */
25
+ export async function browserProbe(
26
+ root: string | undefined,
27
+ env: Env = Bun.env,
28
+ platform: string = process.platform,
29
+ ): Promise<BrowserFact | undefined> {
30
+ if (root === undefined) return undefined;
31
+ return {
32
+ path: await findChrome(env, platform),
33
+ required: floorRequires(await readVerifyFloor(root), 'e2e'),
34
+ missing: e2eBrowserMissingFinding(env, platform),
35
+ install: browserInstallCommand(platform),
36
+ };
37
+ }
38
+
39
+ /** The warning `x doctor` lists beside its verdict: only a REQUIRED step with no browser. */
40
+ export const browserWarnings = (fact: BrowserFact | undefined): readonly Finding[] =>
41
+ fact !== undefined && fact.path === undefined && fact.required ? [fact.missing] : [];
42
+
43
+ /** `data.browser` and one line, on a result `x doctor` already decided: `ok` and findings stay. */
44
+ export function withBrowserReport(
45
+ result: CommandResult,
46
+ fact: BrowserFact | undefined,
47
+ ): CommandResult {
48
+ if (fact === undefined) return result;
49
+ const data = typeof result.data === 'object' && result.data !== null ? result.data : {};
50
+ const browser: JsonValue = { path: fact.path ?? null, e2eRequired: fact.required };
51
+ const line =
52
+ fact.path === undefined
53
+ ? msg('cli.doctor.browserMissing', { install: fact.install })
54
+ : msg('cli.doctor.browserFound', { path: fact.path });
55
+ return {
56
+ ...result,
57
+ data: { ...(data as Record<string, JsonValue>), browser },
58
+ lines: [...(result.lines ?? []), line],
59
+ };
60
+ }
@@ -0,0 +1,47 @@
1
+ // The X_* codes of the gate's own floor and run — `x.verify.json`'s ratchets (`steps`, `strict`,
2
+ // `skipCeiling`, `coverage`, `guardBaseline`), a step's deadline, the shard/merge split and the
3
+ // services a suite needs — split out of `error-codes.ts` at its 500-line ceiling, as
4
+ // `error-codes-package.ts` was. That file folds these into the CLI's union and registers them.
5
+
6
+ /** Codes the gate's floor, its run and its split declare and own. */
7
+ export const CLI_VERIFY_ERROR_CODES = [
8
+ // The ratchet's own code. A skipped step is not a failure — unless `x.verify.json` says this
9
+ // repo already ran it, in which case the suite was deleted and the gate would otherwise print
10
+ // one more green line for it.
11
+ 'X_VERIFY_SUITE_VANISHED',
12
+ 'X_VERIFY_SHARD_INVALID',
13
+ 'X_VERIFY_MERGE_INCOMPLETE',
14
+ 'X_VERIFY_MERGE_INPUT',
15
+ 'X_VERIFY_STEP_TIMEOUT',
16
+ 'X_COVERAGE_BELOW_FLOOR',
17
+ 'X_COVERAGE_FLOOR_UNSTATED',
18
+ 'X_COVERAGE_FLOOR_STALE',
19
+ 'X_VERIFY_SKIPS_OVER_CEILING',
20
+ 'X_TEST_SERVICES_UNAVAILABLE',
21
+ 'X_VERIFY_E2E_BROWSER_MISSING',
22
+ 'X_VERIFY_STRICT_UNRUN',
23
+ 'X_GUARD_OVER_BASELINE',
24
+ 'X_GUARD_BASELINE_STALE',
25
+ ] as const;
26
+
27
+ export type CliVerifyErrorCode = (typeof CLI_VERIFY_ERROR_CODES)[number];
28
+
29
+ /** Their titles, typed over the list above so a code without one is a build error. */
30
+ export const CLI_VERIFY_ERROR_TITLES: Readonly<Record<CliVerifyErrorCode, string>> = {
31
+ X_VERIFY_SUITE_VANISHED: 'a step the committed floor requires had nothing left to check',
32
+ X_VERIFY_SHARD_INVALID: 'x verify --shard was given a spec or a step list it cannot split',
33
+ X_VERIFY_MERGE_INCOMPLETE: 'x verify merge was handed parts that do not add up to the whole gate',
34
+ X_VERIFY_MERGE_INPUT: 'a part handed to x verify merge is not an x verify --json document',
35
+ X_VERIFY_STEP_TIMEOUT: 'a gate step ran past its deadline and was stopped',
36
+ X_COVERAGE_BELOW_FLOOR: 'the unit suite covers less of the app than x.verify.json states',
37
+ X_COVERAGE_FLOOR_UNSTATED:
38
+ 'x.verify.json states no coverage floor, or one under 95 with no reason',
39
+ X_COVERAGE_FLOOR_STALE: 'the app now covers more than the floor in x.verify.json states',
40
+ X_VERIFY_SKIPS_OVER_CEILING: 'a step skipped more tests than its skipCeiling allows',
41
+ X_TEST_SERVICES_UNAVAILABLE:
42
+ "the live step's test database is not reachable and could not be started",
43
+ X_VERIFY_E2E_BROWSER_MISSING: 'a floored e2e step found no browser to drive',
44
+ X_VERIFY_STRICT_UNRUN: 'x.verify.json is strict and a step ran no check with no written why',
45
+ X_GUARD_OVER_BASELINE: 'a guard reports more findings than its x.verify.json baseline allows',
46
+ X_GUARD_BASELINE_STALE: 'a guard baseline is above what the tree reports',
47
+ };
@@ -13,6 +13,8 @@ import type { CliShotErrorCode } from './error-codes-shot';
13
13
  import { CLI_SHOT_ERROR_CODES, CLI_SHOT_ERROR_TITLES } from './error-codes-shot';
14
14
  import type { CliToolingErrorCode } from './error-codes-tooling';
15
15
  import { CLI_TOOLING_ERROR_CODES, CLI_TOOLING_ERROR_TITLES } from './error-codes-tooling';
16
+ import type { CliVerifyErrorCode } from './error-codes-verify';
17
+ import { CLI_VERIFY_ERROR_CODES, CLI_VERIFY_ERROR_TITLES } from './error-codes-verify';
16
18
 
17
19
  /** Codes this package declares and owns. */
18
20
  export const CLI_OWNED_ERROR_CODES = [
@@ -51,10 +53,6 @@ export const CLI_OWNED_ERROR_CODES = [
51
53
  'X_TYPECHECK_FAILED',
52
54
  'X_LINT_FAILED',
53
55
  'X_TEST_FAILED',
54
- // The ratchet's own code. A skipped step is not a failure — unless `x.verify.json` says this
55
- // repo already ran it, in which case the suite was deleted and the gate would otherwise print
56
- // one more green line for it.
57
- 'X_VERIFY_SUITE_VANISHED',
58
56
  // The framework's own tables, refused by name rather than by the driver's rejection: a raw
59
57
  // `permission denied for schema public` says which statement failed and neither which framework
60
58
  // table it was creating nor which package wants it.
@@ -164,17 +162,10 @@ export const CLI_OWNED_ERROR_CODES = [
164
162
  'X_ROUTE_ASYNC_PAGE',
165
163
  'X_BUDGET_PARAMS_UNDECLARED',
166
164
  'X_TEST_BUDGET_INVALID',
167
- 'X_VERIFY_SHARD_INVALID',
168
- 'X_VERIFY_MERGE_INCOMPLETE',
169
- 'X_VERIFY_MERGE_INPUT',
170
165
  'X_SITEMAP_EXTRA_INVALID',
171
166
  'X_DEV_RESTART_REQUIRED',
172
167
  'X_DEV_ROOT_GONE',
173
168
  'X_SEAL_RESEAL_PENDING',
174
- 'X_VERIFY_STEP_TIMEOUT',
175
- 'X_COVERAGE_BELOW_FLOOR',
176
- 'X_COVERAGE_FLOOR_UNSTATED',
177
- 'X_COVERAGE_FLOOR_STALE',
178
169
  'X_DB_HANDLE_UNREGISTERED',
179
170
  'X_ROLE_LOAD_INCOMPLETE',
180
171
  'X_ADMIN_RESOURCE_UNWIRED',
@@ -227,7 +218,6 @@ export const CLI_OWNED_ERROR_CODES = [
227
218
  'X_SEO_CARD_ROUTE_UNKNOWN',
228
219
  'X_SEO_CARD_BROWSER_MISSING',
229
220
  'X_IMAGE_SOURCE_UNREADABLE',
230
- 'X_VERIFY_SKIPS_OVER_CEILING',
231
221
  'X_ASSET_VARIANT_UNDECLARED',
232
222
  'X_NEW_SHAPE_GENERATE_FAILED',
233
223
  'X_ISLAND_DISPOSER_MISSING',
@@ -243,6 +233,10 @@ export const CLI_OWNED_ERROR_CODES = [
243
233
  'X_NATIVE_FORM_UNANSWERED',
244
234
  'X_ASSET_RETAIN_UNDECLARED',
245
235
  'X_DEV_DATA_UNOPENABLE',
236
+ 'X_DEV_LOG_ABSENT',
237
+ 'X_DEV_PEER_REFUSED',
238
+ 'X_PROFILE_ROUTE_FAILED',
239
+ 'X_ROWS_SLICE_ENTITY',
246
240
  ] as const;
247
241
 
248
242
  /**
@@ -283,6 +277,7 @@ export const CLI_ERROR_CODES = [
283
277
  ...CLI_PACKAGE_ERROR_CODES,
284
278
  ...CLI_SHOT_ERROR_CODES,
285
279
  ...CLI_TOOLING_ERROR_CODES,
280
+ ...CLI_VERIFY_ERROR_CODES,
286
281
  ...CLI_BORROWED_ERROR_CODES,
287
282
  ] as const;
288
283
 
@@ -294,7 +289,8 @@ export type CliOwnedErrorCode =
294
289
  | CliDoctorErrorCode
295
290
  | CliPackageErrorCode
296
291
  | CliShotErrorCode
297
- | CliToolingErrorCode;
292
+ | CliToolingErrorCode
293
+ | CliVerifyErrorCode;
298
294
  export type CliErrorCode = (typeof CLI_ERROR_CODES)[number];
299
295
 
300
296
  /**
@@ -331,7 +327,6 @@ export const CLI_ERROR_TITLES: Readonly<Record<CliListedErrorCode, string>> = {
331
327
  X_TYPECHECK_FAILED: 'tsc failed',
332
328
  X_LINT_FAILED: 'Biome failed',
333
329
  X_TEST_FAILED: 'a test type failed',
334
- X_VERIFY_SUITE_VANISHED: 'a step the committed floor requires had nothing left to check',
335
330
  X_MANIFEST_STALE: 'openapi.json is stale',
336
331
  X_MANIFEST_MISSING: 'the app ships no x.manifest.json',
337
332
  X_BUDGET_UNMEASURED: 'a route declares a budget the build never measured',
@@ -380,19 +375,11 @@ export const CLI_ERROR_TITLES: Readonly<Record<CliListedErrorCode, string>> = {
380
375
  X_BUDGET_PARAMS_UNDECLARED:
381
376
  'a dynamic route with a budget declares no prerender() paths to weigh it by',
382
377
  X_TEST_BUDGET_INVALID: 'a test memory budget or worker cap env var does not parse',
383
- X_VERIFY_SHARD_INVALID: 'x verify --shard was given a spec or a step list it cannot split',
384
- X_VERIFY_MERGE_INCOMPLETE: 'x verify merge was handed parts that do not add up to the whole gate',
385
- X_VERIFY_MERGE_INPUT: 'a part handed to x verify merge is not an x verify --json document',
386
378
  X_SITEMAP_EXTRA_INVALID: 'a seo.sitemap.extra path names no public page',
387
379
  X_DEV_RESTART_REQUIRED:
388
380
  'a save reached a module that defines a primitive; only a new process serves it',
389
381
  X_DEV_ROOT_GONE: 'the app root x dev serves was deleted or moved',
390
382
  X_SEAL_RESEAL_PENDING: 'sealed columns still hold values under a retired master key',
391
- X_VERIFY_STEP_TIMEOUT: 'a gate step ran past its deadline and was stopped',
392
- X_COVERAGE_BELOW_FLOOR: 'the unit suite covers less of the app than x.verify.json states',
393
- X_COVERAGE_FLOOR_UNSTATED:
394
- 'x.verify.json states no coverage floor, or one under 95 with no reason',
395
- X_COVERAGE_FLOOR_STALE: 'the app now covers more than the floor in x.verify.json states',
396
383
  X_DB_HANDLE_UNREGISTERED: "an entity x g wrote is not in the app's typed database handle",
397
384
  X_ROLE_LOAD_INCOMPLETE: 'a worker or scheduler did not register a job or task the manifest names',
398
385
  X_ADMIN_RESOURCE_UNWIRED: "an admin override x g wrote is not in the app's defineAdmin() call",
@@ -453,7 +440,6 @@ export const CLI_ERROR_TITLES: Readonly<Record<CliListedErrorCode, string>> = {
453
440
  X_SEO_CARD_BROWSER_MISSING:
454
441
  'a static build with social cards found no browser to photograph them',
455
442
  X_IMAGE_SOURCE_UNREADABLE: 'a responsiveImage src is not a file the static export holds',
456
- X_VERIFY_SKIPS_OVER_CEILING: 'a step skipped more tests than its skipCeiling allows',
457
443
  X_ASSET_VARIANT_UNDECLARED: 'an /assets image variant responsiveImage() never mints',
458
444
  X_NEW_SHAPE_GENERATE_FAILED: 'a shape generator failed in the new app',
459
445
  X_ISLAND_DISPOSER_MISSING: "an island's mount returns no disposer",
@@ -472,6 +458,10 @@ export const CLI_ERROR_TITLES: Readonly<Record<CliListedErrorCode, string>> = {
472
458
  X_NATIVE_FORM_UNANSWERED: 'a page form posts to an action that declares no native answer',
473
459
  X_ASSET_RETAIN_UNDECLARED: "A served build keeps no earlier build's assets",
474
460
  X_DEV_DATA_UNOPENABLE: 'x dev set aside an embedded data directory that would not open',
461
+ X_DEV_LOG_ABSENT: 'the dev log does not exist yet',
462
+ X_DEV_PEER_REFUSED: 'a /_x request came from a non-loopback peer',
463
+ X_PROFILE_ROUTE_FAILED: 'the profiled route answered an error',
464
+ X_ROWS_SLICE_ENTITY: "the slice's entity is not the scaffolded table",
475
465
  };
476
466
 
477
467
  // One unconditional call, so a second package claiming one of the CLI's codes throws
@@ -485,6 +475,7 @@ registerErrorCodes(
485
475
  ...CLI_PACKAGE_ERROR_TITLES,
486
476
  ...CLI_SHOT_ERROR_TITLES,
487
477
  ...CLI_TOOLING_ERROR_TITLES,
478
+ ...CLI_VERIFY_ERROR_TITLES,
488
479
  }).map(([code, title]) => [code, { title }]),
489
480
  ),
490
481
  );