@ultimat3/cli 31.15.0 → 31.17.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 (86) hide show
  1. package/README.md +7 -1
  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 +47 -37
  9. package/src/cmd-exercise.ts +42 -5
  10. package/src/cmd-explain-spec.ts +24 -0
  11. package/src/cmd-explain.ts +201 -0
  12. package/src/cmd-logs-spec.ts +34 -0
  13. package/src/cmd-logs.ts +80 -0
  14. package/src/cmd-planned.ts +15 -29
  15. package/src/cmd-token-spec.ts +54 -0
  16. package/src/cmd-token.ts +173 -0
  17. package/src/cmd-upgrade.ts +19 -2
  18. package/src/cmd-verify-spec.ts +13 -3
  19. package/src/cmd-verify.ts +2 -0
  20. package/src/config-redact.ts +39 -0
  21. package/src/coverage-floor.ts +2 -2
  22. package/src/dev-boot-data-dir.ts +69 -0
  23. package/src/dev-boot.ts +26 -13
  24. package/src/doctor-env-reserved.ts +111 -0
  25. package/src/doctor-floor.ts +62 -0
  26. package/src/doctor-pins.ts +101 -0
  27. package/src/doctor-probe.ts +21 -1
  28. package/src/doctor-row-security.ts +119 -4
  29. package/src/doctor-warnings.ts +55 -0
  30. package/src/error-codes-doctor.ts +24 -0
  31. package/src/error-codes-tooling.ts +6 -4
  32. package/src/error-codes.ts +7 -0
  33. package/src/errors.ts +8 -2
  34. package/src/exercise-entry-edit.ts +5 -1
  35. package/src/exercise-floor-report.ts +138 -0
  36. package/src/exercise-floor-verdict.ts +98 -0
  37. package/src/exercise-floor.ts +158 -0
  38. package/src/exercise-routes.ts +59 -0
  39. package/src/explain-capture.ts +38 -0
  40. package/src/generate-exercise.ts +2 -2
  41. package/src/generate-factories.ts +133 -0
  42. package/src/generate-files.ts +11 -0
  43. package/src/generate-kinds.ts +13 -0
  44. package/src/mcp-db-target.ts +4 -3
  45. package/src/mcp-errors.ts +14 -0
  46. package/src/messages-gate.ts +2 -0
  47. package/src/messages-ops.ts +32 -0
  48. package/src/messages-upgrade.ts +14 -0
  49. package/src/messages.ts +5 -0
  50. package/src/otlp-export.ts +16 -2
  51. package/src/registry.ts +10 -0
  52. package/src/role-start.ts +11 -5
  53. package/src/runtime-services.ts +35 -19
  54. package/src/serve-boot-phases.ts +30 -0
  55. package/src/serve-boot-warnings.ts +62 -0
  56. package/src/serve-boot.ts +30 -11
  57. package/src/templates/generate-cron-job.ts +90 -0
  58. package/src/templates/generate-purge.ts +93 -0
  59. package/src/templates/generate-webhook-receiver.ts +274 -0
  60. package/src/templates/github/ci.yml.ts +101 -36
  61. package/src/templates/guard-repo-raw-sql-test.ts +174 -0
  62. package/src/templates/guard-repo-raw-sql.ts +115 -145
  63. package/src/templates/guard-unbounded-fanout.ts +170 -0
  64. package/src/templates/scaffold-claude-commands.ts +3 -2
  65. package/src/templates/scaffold-docs.ts +3 -2
  66. package/src/templates/scaffold-guards.ts +3 -0
  67. package/src/templates/scaffold-verify-floor.ts +4 -0
  68. package/src/test-dotenv.ts +15 -2
  69. package/src/upgrade-coverage.ts +109 -0
  70. package/src/upgrade-document.ts +18 -0
  71. package/src/upgrade-exercise-floor.ts +53 -0
  72. package/src/upgrade-gate.ts +84 -29
  73. package/src/upgrade-guards.ts +159 -0
  74. package/src/upgrade-report.ts +33 -1
  75. package/src/verify-checks.ts +3 -1
  76. package/src/verify-floor.ts +13 -0
  77. package/src/verify-plan.ts +127 -0
  78. package/wiki/CI-Parallel-Gate.md +38 -1
  79. package/wiki/CLI-Reference.md +115 -14
  80. package/wiki/Caching-And-Invalidation.md +10 -10
  81. package/wiki/Configuration.md +20 -2
  82. package/wiki/Known-Gaps.md +1 -1
  83. package/wiki/MCP-And-AI.md +1 -1
  84. package/wiki/Testing.md +96 -2
  85. package/wiki/Troubleshooting.md +3 -2
  86. package/wiki/Upgrading.md +9 -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],
@@ -1,6 +1,7 @@
1
1
  // `x new`'s `x.verify.json`: the suite floor and the coverage bar every scaffolded app starts on.
2
2
  // Split from `scaffold-repo.ts` (the repo's root files), which had reached the 500-line ceiling.
3
3
 
4
+ import { STATEMENTS_MAX } from '@ultimat3/testing';
4
5
  import type { CoverageExclude } from '../coverage-floor';
5
6
  import { COVERAGE_BAR } from '../coverage-floor';
6
7
  import type { VerifyStepName } from '../verify-step';
@@ -91,6 +92,9 @@ export const verifyFloor = (example: boolean): string =>
91
92
  },
92
93
  // The rolling rail judges from the first migration: a new app has nothing to grandfather.
93
94
  rollingSince: '0',
95
+ // Nor does the exercise pass: every proof must ask, and one call sends the default ceiling
96
+ // at most. An app scaffolded before this key reads warnings instead (`exercise-floor.ts`).
97
+ exercise: { unprovenMax: 0, statementsMax: STATEMENTS_MAX },
94
98
  },
95
99
  null,
96
100
  2,
@@ -27,6 +27,18 @@ import { readFileSync } from 'node:fs'; // why: Bun ships no synchronous file re
27
27
  // why: Bun exposes no path-join primitive.
28
28
  import { join } from 'node:path';
29
29
 
30
+ /**
31
+ * Keys that LOCATE something on this host and never change what the app does: a browser binary
32
+ * (`browser-launcher.ts`'s `BROWSER_PATH_VARS`, restated so this file does not load the CDP driver
33
+ * graph; `test-dotenv.test.ts` pins the two lists together) and the temp directory. Scrubbing one
34
+ * because `.env.development` happens to name it only breaks the child — e2e stops finding Chrome.
35
+ */
36
+ export const HOST_LOCATOR_KEYS: readonly string[] = [
37
+ 'PUPPETEER_EXECUTABLE_PATH',
38
+ 'CHROME_PATH',
39
+ 'TMPDIR',
40
+ ];
41
+
30
42
  /** Bun's own grammar, matched against `env-example.ts`'s `ENV_KEY_RE` (kept separate: see header). */
31
43
  const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
32
44
 
@@ -72,14 +84,15 @@ export interface DevOnlyLeakInput {
72
84
 
73
85
  /**
74
86
  * The pure decision, no filesystem: every key `.env.development`/`.env.development.local` would
75
- * set, where `env`'s CURRENT value for that key is exactly what the file would have set. See this
76
- * file's header for why a legitimate test file declaring the same key does not exempt it.
87
+ * set, where `env`'s CURRENT value for that key is exactly what the file would have set — a
88
+ * `HOST_LOCATOR_KEYS` member excepted. See this file's header for why a legitimate test file declaring the same key does not exempt it.
77
89
  */
78
90
  export function devOnlyLeakedKeys(input: DevOnlyLeakInput): readonly string[] {
79
91
  const merged = new Map(parseDotenvValues(input.devText));
80
92
  for (const [key, value] of parseDotenvValues(input.devLocalText)) merged.set(key, value);
81
93
  const leaked: string[] = [];
82
94
  for (const [key, devValue] of merged) {
95
+ if (HOST_LOCATOR_KEYS.includes(key)) continue;
83
96
  // `Object.hasOwn` FIRST: `key` is data (a name out of a dotenv file), and `env['constructor']`
84
97
  // on a plain object answers `Object.prototype`'s member, not `undefined` — the rule
85
98
  // `scripts/proto-index.ts` ratchets, with its own sanctioned repair.
@@ -0,0 +1,109 @@
1
+ // A Bun-floor hop's coverage rebaseline: Bun 1.4.4 counted functions differently with no test or
2
+ // source changed, so a hop that moves the Bun floor measures the unit suite once (the installed
3
+ // CLI's `verify --only unit`) and, only when that lands under the stated floor, moves the floor to
4
+ // what it measured with a dated `why`. Written into the hop's diff and reported, never silently.
5
+
6
+ // why: Bun exposes no path-join primitive; `x.verify.json` sits at the app root.
7
+ import { join } from 'node:path';
8
+ import { t } from '@ultimat3/schema';
9
+ import type { CoverageFloor } from './coverage-floor';
10
+ import { COVERAGE_FIELD, floorFor, readCoverageFloor, shown } from './coverage-floor';
11
+ import { msg } from './messages';
12
+ import { documentIn } from './upgrade-document';
13
+ import type { InstalledCli } from './upgrade-guards';
14
+ import { parseJson } from './upgrade-registry';
15
+ import { VERIFY_FLOOR_FILE } from './verify-floor';
16
+
17
+ const NUMBERS = t.object({ lines: t.number, funcs: t.number });
18
+ const UNIT = t.object({
19
+ steps: t.array(
20
+ t.object({
21
+ name: t.string,
22
+ findings: t.optional(t.array(t.object({ code: t.string }))),
23
+ }),
24
+ ),
25
+ data: t.object({ coverage: t.object({ unit: NUMBERS }) }),
26
+ });
27
+
28
+ interface Numbers {
29
+ readonly lines: number;
30
+ readonly funcs: number;
31
+ }
32
+
33
+ /** What the `why` says about the hop that moved the floor. */
34
+ export interface CoverageRebaseline {
35
+ readonly release: string;
36
+ readonly bunFrom: string | null;
37
+ readonly bunTo: string;
38
+ /** `YYYY-MM-DD`, UTC: the day the measurement was taken. */
39
+ readonly today: string;
40
+ }
41
+
42
+ /** What the report carries: the floor before, the one written, and the measurement behind it. */
43
+ export interface HopCoverage {
44
+ readonly file: string;
45
+ readonly measured: Numbers;
46
+ readonly from: Numbers;
47
+ readonly to: Numbers;
48
+ readonly why: string;
49
+ }
50
+
51
+ /** The app's floor file, as an object, with the coverage floor in it — or undefined: nothing to move. */
52
+ export async function statedCoverage(
53
+ root: string,
54
+ ): Promise<
55
+ { readonly payload: Record<string, unknown>; readonly floor: CoverageFloor } | undefined
56
+ > {
57
+ const file = Bun.file(join(root, VERIFY_FLOOR_FILE));
58
+ if (!(await file.exists())) return undefined;
59
+ const payload = parseJson(await file.text());
60
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) return undefined;
61
+ const record = payload as Record<string, unknown>;
62
+ const floor = readCoverageFloor(record).coverage;
63
+ return floor === undefined ? undefined : { payload: record, floor };
64
+ }
65
+
66
+ /** Measures once; moves only the number that fell under its floor, and only to what was measured. */
67
+ export async function rebaselineCoverage(input: {
68
+ readonly cli: InstalledCli;
69
+ readonly root: string;
70
+ readonly stated: NonNullable<Awaited<ReturnType<typeof statedCoverage>>>;
71
+ readonly bun: CoverageRebaseline;
72
+ }): Promise<HopCoverage | null> {
73
+ const { cli, root, stated, bun } = input;
74
+ const parsed = UNIT.safeParse(
75
+ documentIn((await cli(['verify', '--only', 'unit', '--json'])).stdout),
76
+ );
77
+ if (parsed.issues !== undefined) return null;
78
+ const document = parsed.value as {
79
+ readonly steps: readonly { name: string; findings?: readonly { code: string }[] }[];
80
+ readonly data: { readonly coverage: { readonly unit: Numbers } };
81
+ };
82
+ const below = document.steps
83
+ .find((step) => step.name === 'unit')
84
+ ?.findings?.some((finding) => finding.code === 'X_COVERAGE_BELOW_FLOOR');
85
+ if (below !== true) return null;
86
+ const measured = document.data.coverage.unit;
87
+ const from = { lines: stated.floor.lines, funcs: stated.floor.funcs };
88
+ const to = {
89
+ lines: measured.lines < from.lines ? floorFor(measured.lines) : from.lines,
90
+ funcs: measured.funcs < from.funcs ? floorFor(measured.funcs) : from.funcs,
91
+ };
92
+ const said = msg('cli.upgrade.coverage.why', {
93
+ date: bun.today,
94
+ release: bun.release,
95
+ bunFrom: bun.bunFrom ?? msg('cli.upgrade.coverage.unpinned'),
96
+ bunTo: bun.bunTo,
97
+ lines: shown(measured.lines),
98
+ funcs: shown(measured.funcs),
99
+ fromLines: String(from.lines),
100
+ fromFuncs: String(from.funcs),
101
+ toLines: String(to.lines),
102
+ toFuncs: String(to.funcs),
103
+ });
104
+ const why = stated.floor.why === undefined ? said : `${said} ${stated.floor.why}`;
105
+ const raw = stated.payload[COVERAGE_FIELD] as Record<string, unknown>;
106
+ const next = { ...stated.payload, [COVERAGE_FIELD]: { ...raw, ...to, why } };
107
+ await Bun.write(join(root, VERIFY_FLOOR_FILE), `${JSON.stringify(next, null, 2)}\n`);
108
+ return { file: VERIFY_FLOOR_FILE, measured, from, to, why };
109
+ }
@@ -0,0 +1,18 @@
1
+ // The one JSON document on a child CLI's stdout, read as a foreign document: a hop's gate, the
2
+ // guards it installs and every caller that spawns an installed CLI share this one reading of it.
3
+
4
+ import { parseJson } from './upgrade-registry';
5
+
6
+ /**
7
+ * Whole first; then its last line that parses, because the CLI that keeps fd 1 to one document
8
+ * under `--json` is a recent one and a hop can install one that still logs a boot line ahead of it.
9
+ */
10
+ export function documentIn(stdout: string): unknown {
11
+ const whole = parseJson(stdout.trim());
12
+ if (whole !== undefined) return whole;
13
+ const lines = stdout.split('\n').filter((line) => line.trimStart().startsWith('{'));
14
+ return lines
15
+ .reverse()
16
+ .map(parseJson)
17
+ .find((parsed) => parsed !== undefined);
18
+ }
@@ -0,0 +1,53 @@
1
+ // A hop's exercise ratchet: after the hop's `x exercise` wrote `.x/exercise.json`, an app whose
2
+ // `x.verify.json` states no `exercise.unprovenMax` / `statementsMax` gets the figures that pass
3
+ // measured, so the floor starts where the app is and only falls. A key the app already wrote is
4
+ // never touched. Written into the hop's diff and reported, never silently.
5
+
6
+ // why: Bun exposes no path-join primitive; `x.verify.json` sits at the app root.
7
+ import { join } from 'node:path';
8
+ import type { ExerciseFloor } from './exercise-floor';
9
+ import { readExerciseFloor } from './exercise-floor';
10
+ import {
11
+ exerciseReportStamp,
12
+ measuredExerciseFloor,
13
+ withExerciseFloor,
14
+ } from './exercise-floor-report';
15
+ import { parseJson } from './upgrade-registry';
16
+ import { VERIFY_FLOOR_FILE } from './verify-floor';
17
+
18
+ /** What the report carries: the figures written, each one the hop's own pass measured. */
19
+ export interface HopExerciseFloor {
20
+ readonly file: string;
21
+ readonly written: ExerciseFloor;
22
+ }
23
+
24
+ /**
25
+ * Writes the measured figure for each exercise key the floor file lacks; null when none. `before`
26
+ * is the report's stamp ahead of the hop's `x exercise`: a report that pass did not rewrite (it
27
+ * died, or is a CLI with no report) holds another pass's figures and is never ratcheted.
28
+ */
29
+ export async function ratchetExerciseFloor(
30
+ root: string,
31
+ before: number | undefined,
32
+ ): Promise<HopExerciseFloor | null> {
33
+ const after = await exerciseReportStamp(root);
34
+ if (after === undefined || after === before) return null;
35
+ const file = Bun.file(join(root, VERIFY_FLOOR_FILE));
36
+ if (!(await file.exists())) return null;
37
+ const text = await file.text();
38
+ const payload = parseJson(text);
39
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) return null;
40
+ const stated = readExerciseFloor(payload as Record<string, unknown>);
41
+ // A malformed key is the `manifest` step's finding; writing beside it would hide it.
42
+ if (stated.problems.length > 0) return null;
43
+ const measured = await measuredExerciseFloor(root);
44
+ if (measured === undefined) return null;
45
+ const written: { unprovenMax?: number; statementsMax?: number } = {};
46
+ if (stated.floor?.unprovenMax === undefined) written.unprovenMax = measured.unprovenMax;
47
+ if (stated.floor?.statementsMax === undefined) written.statementsMax = measured.statementsMax;
48
+ if (Object.keys(written).length === 0) return null;
49
+ const next = withExerciseFloor(text, written);
50
+ if (next === text) return null;
51
+ await Bun.write(join(root, VERIFY_FLOOR_FILE), next);
52
+ return { file: VERIFY_FLOOR_FILE, written };
53
+ }